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
31 # define SIG_ERR ((Sighandler_t) -1)
36 /* Missing protos on LynxOS */
41 # include <sys/wait.h>
46 # include <sys/select.h>
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 # define FD_CLOEXEC 1 /* NeXT needs this */
56 /* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
66 /* Can't use PerlIO to write as it allocates memory */
67 PerlLIO_write(PerlIO_fileno(Perl_error_log),
68 PL_no_mem, strlen(PL_no_mem));
70 NORETURN_FUNCTION_END;
73 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
74 # define ALWAYS_NEED_THX
77 /* paranoid version of system's malloc() */
80 Perl_safesysmalloc(MEM_SIZE size)
82 #ifdef ALWAYS_NEED_THX
88 PerlIO_printf(Perl_error_log,
89 "Allocation too large: %lx\n", size) FLUSH;
92 #endif /* HAS_64K_LIMIT */
93 #ifdef PERL_TRACK_MEMPOOL
98 Perl_croak_nocontext("panic: malloc");
100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
101 PERL_ALLOC_CHECK(ptr);
102 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
104 #ifdef PERL_TRACK_MEMPOOL
105 struct perl_memory_debug_header *const header
106 = (struct perl_memory_debug_header *)ptr;
110 PoisonNew(((char *)ptr), size, char);
113 #ifdef PERL_TRACK_MEMPOOL
114 header->interpreter = aTHX;
115 /* Link us into the list. */
116 header->prev = &PL_memory_debug_header;
117 header->next = PL_memory_debug_header.next;
118 PL_memory_debug_header.next = header;
119 header->next->prev = header;
123 ptr = (Malloc_t)((char*)ptr+sTHX);
128 #ifndef ALWAYS_NEED_THX
134 return write_no_mem();
140 /* paranoid version of system's realloc() */
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
145 #ifdef ALWAYS_NEED_THX
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150 Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
155 PerlIO_printf(Perl_error_log,
156 "Reallocation too large: %lx\n", size) FLUSH;
159 #endif /* HAS_64K_LIMIT */
166 return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
174 if (header->interpreter != aTHX) {
175 Perl_croak_nocontext("panic: realloc from wrong pool");
177 assert(header->next->prev == header);
178 assert(header->prev->next == header);
180 if (header->size > size) {
181 const MEM_SIZE freed_up = header->size - size;
182 char *start_of_freed = ((char *)where) + size;
183 PoisonFree(start_of_freed, freed_up, char);
191 Perl_croak_nocontext("panic: realloc");
193 ptr = (Malloc_t)PerlMem_realloc(where,size);
194 PERL_ALLOC_CHECK(ptr);
196 /* MUST do this fixup first, before doing ANYTHING else, as anything else
197 might allocate memory/free/move memory, and until we do the fixup, it
198 may well be chasing (and writing to) free memory. */
199 #ifdef PERL_TRACK_MEMPOOL
201 struct perl_memory_debug_header *const header
202 = (struct perl_memory_debug_header *)ptr;
205 if (header->size < size) {
206 const MEM_SIZE fresh = size - header->size;
207 char *start_of_fresh = ((char *)ptr) + size;
208 PoisonNew(start_of_fresh, fresh, char);
212 header->next->prev = header;
213 header->prev->next = header;
215 ptr = (Malloc_t)((char*)ptr+sTHX);
219 /* In particular, must do that fixup above before logging anything via
220 *printf(), as it can reallocate memory, which can cause SEGVs. */
222 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
230 #ifndef ALWAYS_NEED_THX
236 return write_no_mem();
242 /* safe version of system's free() */
245 Perl_safesysfree(Malloc_t where)
247 #ifdef ALWAYS_NEED_THX
252 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
254 #ifdef PERL_TRACK_MEMPOOL
255 where = (Malloc_t)((char*)where-sTHX);
257 struct perl_memory_debug_header *const header
258 = (struct perl_memory_debug_header *)where;
260 if (header->interpreter != aTHX) {
261 Perl_croak_nocontext("panic: free from wrong pool");
264 Perl_croak_nocontext("panic: duplicate free");
266 if (!(header->next) || header->next->prev != header
267 || header->prev->next != header) {
268 Perl_croak_nocontext("panic: bad free");
270 /* Unlink us from the chain. */
271 header->next->prev = header->prev;
272 header->prev->next = header->next;
274 PoisonNew(where, header->size, char);
276 /* Trigger the duplicate free warning. */
284 /* safe version of system's calloc() */
287 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
289 #ifdef ALWAYS_NEED_THX
293 MEM_SIZE total_size = 0;
295 /* Even though calloc() for zero bytes is strange, be robust. */
296 if (size && (count <= MEM_SIZE_MAX / size))
297 total_size = size * count;
299 Perl_croak_nocontext("%s", PL_memory_wrap);
300 #ifdef PERL_TRACK_MEMPOOL
301 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
304 Perl_croak_nocontext("%s", PL_memory_wrap);
307 if (total_size > 0xffff) {
308 PerlIO_printf(Perl_error_log,
309 "Allocation too large: %lx\n", total_size) FLUSH;
312 #endif /* HAS_64K_LIMIT */
314 if ((long)size < 0 || (long)count < 0)
315 Perl_croak_nocontext("panic: calloc");
317 #ifdef PERL_TRACK_MEMPOOL
318 /* Have to use malloc() because we've added some space for our tracking
320 /* malloc(0) is non-portable. */
321 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
323 /* Use calloc() because it might save a memset() if the memory is fresh
324 and clean from the OS. */
326 ptr = (Malloc_t)PerlMem_calloc(count, size);
327 else /* calloc(0) is non-portable. */
328 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
330 PERL_ALLOC_CHECK(ptr);
331 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));
333 #ifdef PERL_TRACK_MEMPOOL
335 struct perl_memory_debug_header *const header
336 = (struct perl_memory_debug_header *)ptr;
338 memset((void*)ptr, 0, total_size);
339 header->interpreter = aTHX;
340 /* Link us into the list. */
341 header->prev = &PL_memory_debug_header;
342 header->next = PL_memory_debug_header.next;
343 PL_memory_debug_header.next = header;
344 header->next->prev = header;
346 header->size = total_size;
348 ptr = (Malloc_t)((char*)ptr+sTHX);
354 #ifndef ALWAYS_NEED_THX
359 return write_no_mem();
363 /* These must be defined when not using Perl's malloc for binary
368 Malloc_t Perl_malloc (MEM_SIZE nbytes)
371 return (Malloc_t)PerlMem_malloc(nbytes);
374 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
377 return (Malloc_t)PerlMem_calloc(elements, size);
380 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
383 return (Malloc_t)PerlMem_realloc(where, nbytes);
386 Free_t Perl_mfree (Malloc_t where)
394 /* copy a string up to some (non-backslashed) delimiter, if any */
397 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
401 PERL_ARGS_ASSERT_DELIMCPY;
403 for (tolen = 0; from < fromend; from++, tolen++) {
405 if (from[1] != delim) {
412 else if (*from == delim)
423 /* return ptr to little string in big string, NULL if not found */
424 /* This routine was donated by Corey Satten. */
427 Perl_instr(register const char *big, register const char *little)
431 PERL_ARGS_ASSERT_INSTR;
439 register const char *s, *x;
442 for (x=big,s=little; *s; /**/ ) {
453 return (char*)(big-1);
458 /* same as instr but allow embedded nulls */
461 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
463 PERL_ARGS_ASSERT_NINSTR;
467 const char first = *little;
469 bigend -= lend - little++;
471 while (big <= bigend) {
472 if (*big++ == first) {
473 for (x=big,s=little; s < lend; x++,s++) {
477 return (char*)(big-1);
484 /* reverse of the above--find last substring */
487 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
489 register const char *bigbeg;
490 register const I32 first = *little;
491 register const char * const littleend = lend;
493 PERL_ARGS_ASSERT_RNINSTR;
495 if (little >= littleend)
496 return (char*)bigend;
498 big = bigend - (littleend - little++);
499 while (big >= bigbeg) {
500 register const char *s, *x;
503 for (x=big+2,s=little; s < littleend; /**/ ) {
512 return (char*)(big+1);
517 /* As a space optimization, we do not compile tables for strings of length
518 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
519 special-cased in fbm_instr().
521 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
524 =head1 Miscellaneous Functions
526 =for apidoc fbm_compile
528 Analyses the string in order to make fast searches on it using fbm_instr()
529 -- the Boyer-Moore algorithm.
535 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
538 register const U8 *s;
544 PERL_ARGS_ASSERT_FBM_COMPILE;
546 if (flags & FBMcf_TAIL) {
547 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
548 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
549 if (mg && mg->mg_len >= 0)
552 s = (U8*)SvPV_force_mutable(sv, len);
553 if (len == 0) /* TAIL might be on a zero-length string. */
555 SvUPGRADE(sv, SVt_PVGV);
560 const unsigned char *sb;
561 const U8 mlen = (len>255) ? 255 : (U8)len;
564 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
566 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
567 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
568 memset((void*)table, mlen, 256);
570 sb = s - mlen + 1; /* first char (maybe) */
572 if (table[*s] == mlen)
577 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
579 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
581 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
582 for (i = 0; i < len; i++) {
583 if (PL_freq[s[i]] < frequency) {
585 frequency = PL_freq[s[i]];
588 BmFLAGS(sv) = (U8)flags;
589 BmRARE(sv) = s[rarest];
590 BmPREVIOUS(sv) = rarest;
591 BmUSEFUL(sv) = 100; /* Initial value */
592 if (flags & FBMcf_TAIL)
594 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
595 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
598 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
599 /* If SvTAIL is actually due to \Z or \z, this gives false positives
603 =for apidoc fbm_instr
605 Returns the location of the SV in the string delimited by C<str> and
606 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
607 does not have to be fbm_compiled, but the search will not be as fast
614 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
616 register unsigned char *s;
618 register const unsigned char *little
619 = (const unsigned char *)SvPV_const(littlestr,l);
620 register STRLEN littlelen = l;
621 register const I32 multiline = flags & FBMrf_MULTILINE;
623 PERL_ARGS_ASSERT_FBM_INSTR;
625 if ((STRLEN)(bigend - big) < littlelen) {
626 if ( SvTAIL(littlestr)
627 && ((STRLEN)(bigend - big) == littlelen - 1)
629 || (*big == *little &&
630 memEQ((char *)big, (char *)little, littlelen - 1))))
635 if (littlelen <= 2) { /* Special-cased */
637 if (littlelen == 1) {
638 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
639 /* Know that bigend != big. */
640 if (bigend[-1] == '\n')
641 return (char *)(bigend - 1);
642 return (char *) bigend;
650 if (SvTAIL(littlestr))
651 return (char *) bigend;
655 return (char*)big; /* Cannot be SvTAIL! */
658 if (SvTAIL(littlestr) && !multiline) {
659 if (bigend[-1] == '\n' && bigend[-2] == *little)
660 return (char*)bigend - 2;
661 if (bigend[-1] == *little)
662 return (char*)bigend - 1;
666 /* This should be better than FBM if c1 == c2, and almost
667 as good otherwise: maybe better since we do less indirection.
668 And we save a lot of memory by caching no table. */
669 const unsigned char c1 = little[0];
670 const unsigned char c2 = little[1];
675 while (s <= bigend) {
685 goto check_1char_anchor;
696 goto check_1char_anchor;
699 while (s <= bigend) {
704 goto check_1char_anchor;
713 check_1char_anchor: /* One char and anchor! */
714 if (SvTAIL(littlestr) && (*bigend == *little))
715 return (char *)bigend; /* bigend is already decremented. */
718 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
719 s = bigend - littlelen;
720 if (s >= big && bigend[-1] == '\n' && *s == *little
721 /* Automatically of length > 2 */
722 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
724 return (char*)s; /* how sweet it is */
727 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
729 return (char*)s + 1; /* how sweet it is */
733 if (!SvVALID(littlestr)) {
734 char * const b = ninstr((char*)big,(char*)bigend,
735 (char*)little, (char*)little + littlelen);
737 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
738 /* Chop \n from littlestr: */
739 s = bigend - littlelen + 1;
741 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
751 if (littlelen > (STRLEN)(bigend - big))
755 register const unsigned char * const table
756 = little + littlelen + PERL_FBM_TABLE_OFFSET;
757 register const unsigned char *oldlittle;
759 --littlelen; /* Last char found by table lookup */
762 little += littlelen; /* last char */
768 if ((tmp = table[*s])) {
769 if ((s += tmp) < bigend)
773 else { /* less expensive than calling strncmp() */
774 register unsigned char * const olds = s;
779 if (*--s == *--little)
781 s = olds + 1; /* here we pay the price for failure */
783 if (s < bigend) /* fake up continue to outer loop */
792 && (BmFLAGS(littlestr) & FBMcf_TAIL)
793 && memEQ((char *)(bigend - littlelen),
794 (char *)(oldlittle - littlelen), littlelen) )
795 return (char*)bigend - littlelen;
800 /* start_shift, end_shift are positive quantities which give offsets
801 of ends of some substring of bigstr.
802 If "last" we want the last occurrence.
803 old_posp is the way of communication between consequent calls if
804 the next call needs to find the .
805 The initial *old_posp should be -1.
807 Note that we take into account SvTAIL, so one can get extra
808 optimizations if _ALL flag is set.
811 /* If SvTAIL is actually due to \Z or \z, this gives false positives
812 if PL_multiline. In fact if !PL_multiline the authoritative answer
813 is not supported yet. */
816 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
819 register const unsigned char *big;
821 register I32 previous;
823 register const unsigned char *little;
824 register I32 stop_pos;
825 register const unsigned char *littleend;
828 PERL_ARGS_ASSERT_SCREAMINSTR;
830 assert(SvTYPE(littlestr) == SVt_PVGV);
831 assert(SvVALID(littlestr));
834 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
835 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
837 if ( BmRARE(littlestr) == '\n'
838 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
839 little = (const unsigned char *)(SvPVX_const(littlestr));
840 littleend = little + SvCUR(littlestr);
847 little = (const unsigned char *)(SvPVX_const(littlestr));
848 littleend = little + SvCUR(littlestr);
850 /* The value of pos we can start at: */
851 previous = BmPREVIOUS(littlestr);
852 big = (const unsigned char *)(SvPVX_const(bigstr));
853 /* The value of pos we can stop at: */
854 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
855 if (previous + start_shift > stop_pos) {
857 stop_pos does not include SvTAIL in the count, so this check is incorrect
858 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
861 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
866 while (pos < previous + start_shift) {
867 if (!(pos += PL_screamnext[pos]))
872 register const unsigned char *s, *x;
873 if (pos >= stop_pos) break;
874 if (big[pos] != first)
876 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
882 if (s == littleend) {
884 if (!last) return (char *)(big+pos);
887 } while ( pos += PL_screamnext[pos] );
889 return (char *)(big+(*old_posp));
891 if (!SvTAIL(littlestr) || (end_shift > 0))
893 /* Ignore the trailing "\n". This code is not microoptimized */
894 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
895 stop_pos = littleend - little; /* Actual littlestr len */
900 && ((stop_pos == 1) ||
901 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
909 Returns true if the leading len bytes of the strings s1 and s2 are the same
910 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
911 match themselves and their opposite case counterparts. Non-cased and non-ASCII
912 range bytes match only themselves.
919 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
921 register const U8 *a = (const U8 *)s1;
922 register const U8 *b = (const U8 *)s2;
924 PERL_ARGS_ASSERT_FOLDEQ;
927 if (*a != *b && *a != PL_fold[*b])
935 =for apidoc foldEQ_locale
937 Returns true if the leading len bytes of the strings s1 and s2 are the same
938 case-insensitively in the current locale; false otherwise.
944 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
947 register const U8 *a = (const U8 *)s1;
948 register const U8 *b = (const U8 *)s2;
950 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
953 if (*a != *b && *a != PL_fold_locale[*b])
960 /* copy a string to a safe spot */
963 =head1 Memory Management
967 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
968 string which is a duplicate of C<pv>. The size of the string is
969 determined by C<strlen()>. The memory allocated for the new string can
970 be freed with the C<Safefree()> function.
976 Perl_savepv(pTHX_ const char *pv)
983 const STRLEN pvlen = strlen(pv)+1;
984 Newx(newaddr, pvlen, char);
985 return (char*)memcpy(newaddr, pv, pvlen);
989 /* same thing but with a known length */
994 Perl's version of what C<strndup()> would be if it existed. Returns a
995 pointer to a newly allocated string which is a duplicate of the first
996 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
997 the new string can be freed with the C<Safefree()> function.
1003 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1005 register char *newaddr;
1006 PERL_UNUSED_CONTEXT;
1008 Newx(newaddr,len+1,char);
1009 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1011 /* might not be null terminated */
1012 newaddr[len] = '\0';
1013 return (char *) CopyD(pv,newaddr,len,char);
1016 return (char *) ZeroD(newaddr,len+1,char);
1021 =for apidoc savesharedpv
1023 A version of C<savepv()> which allocates the duplicate string in memory
1024 which is shared between threads.
1029 Perl_savesharedpv(pTHX_ const char *pv)
1031 register char *newaddr;
1036 pvlen = strlen(pv)+1;
1037 newaddr = (char*)PerlMemShared_malloc(pvlen);
1039 return write_no_mem();
1041 return (char*)memcpy(newaddr, pv, pvlen);
1045 =for apidoc savesharedpvn
1047 A version of C<savepvn()> which allocates the duplicate string in memory
1048 which is shared between threads. (With the specific difference that a NULL
1049 pointer is not acceptable)
1054 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1056 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1058 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1061 return write_no_mem();
1063 newaddr[len] = '\0';
1064 return (char*)memcpy(newaddr, pv, len);
1068 =for apidoc savesvpv
1070 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1071 the passed in SV using C<SvPV()>
1077 Perl_savesvpv(pTHX_ SV *sv)
1080 const char * const pv = SvPV_const(sv, len);
1081 register char *newaddr;
1083 PERL_ARGS_ASSERT_SAVESVPV;
1086 Newx(newaddr,len,char);
1087 return (char *) CopyD(pv,newaddr,len,char);
1091 /* the SV for Perl_form() and mess() is not kept in an arena */
1101 return newSVpvs_flags("", SVs_TEMP);
1106 /* Create as PVMG now, to avoid any upgrading later */
1108 Newxz(any, 1, XPVMG);
1109 SvFLAGS(sv) = SVt_PVMG;
1110 SvANY(sv) = (void*)any;
1112 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1117 #if defined(PERL_IMPLICIT_CONTEXT)
1119 Perl_form_nocontext(const char* pat, ...)
1124 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1125 va_start(args, pat);
1126 retval = vform(pat, &args);
1130 #endif /* PERL_IMPLICIT_CONTEXT */
1133 =head1 Miscellaneous Functions
1136 Takes a sprintf-style format pattern and conventional
1137 (non-SV) arguments and returns the formatted string.
1139 (char *) Perl_form(pTHX_ const char* pat, ...)
1141 can be used any place a string (char *) is required:
1143 char * s = Perl_form("%d.%d",major,minor);
1145 Uses a single private buffer so if you want to format several strings you
1146 must explicitly copy the earlier strings away (and free the copies when you
1153 Perl_form(pTHX_ const char* pat, ...)
1157 PERL_ARGS_ASSERT_FORM;
1158 va_start(args, pat);
1159 retval = vform(pat, &args);
1165 Perl_vform(pTHX_ const char *pat, va_list *args)
1167 SV * const sv = mess_alloc();
1168 PERL_ARGS_ASSERT_VFORM;
1169 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1174 =for apidoc Am|SV *|mess|const char *pat|...
1176 Take a sprintf-style format pattern and argument list. These are used to
1177 generate a string message. If the message does not end with a newline,
1178 then it will be extended with some indication of the current location
1179 in the code, as described for L</mess_sv>.
1181 Normally, the resulting message is returned in a new mortal SV.
1182 During global destruction a single SV may be shared between uses of
1188 #if defined(PERL_IMPLICIT_CONTEXT)
1190 Perl_mess_nocontext(const char *pat, ...)
1195 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1196 va_start(args, pat);
1197 retval = vmess(pat, &args);
1201 #endif /* PERL_IMPLICIT_CONTEXT */
1204 Perl_mess(pTHX_ const char *pat, ...)
1208 PERL_ARGS_ASSERT_MESS;
1209 va_start(args, pat);
1210 retval = vmess(pat, &args);
1216 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1219 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1221 PERL_ARGS_ASSERT_CLOSEST_COP;
1223 if (!o || o == PL_op)
1226 if (o->op_flags & OPf_KIDS) {
1228 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1231 /* If the OP_NEXTSTATE has been optimised away we can still use it
1232 * the get the file and line number. */
1234 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1235 cop = (const COP *)kid;
1237 /* Keep searching, and return when we've found something. */
1239 new_cop = closest_cop(cop, kid);
1245 /* Nothing found. */
1251 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1253 Expands a message, intended for the user, to include an indication of
1254 the current location in the code, if the message does not already appear
1257 C<basemsg> is the initial message or object. If it is a reference, it
1258 will be used as-is and will be the result of this function. Otherwise it
1259 is used as a string, and if it already ends with a newline, it is taken
1260 to be complete, and the result of this function will be the same string.
1261 If the message does not end with a newline, then a segment such as C<at
1262 foo.pl line 37> will be appended, and possibly other clauses indicating
1263 the current state of execution. The resulting message will end with a
1266 Normally, the resulting message is returned in a new mortal SV.
1267 During global destruction a single SV may be shared between uses of this
1268 function. If C<consume> is true, then the function is permitted (but not
1269 required) to modify and return C<basemsg> instead of allocating a new SV.
1275 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1280 PERL_ARGS_ASSERT_MESS_SV;
1282 if (SvROK(basemsg)) {
1288 sv_setsv(sv, basemsg);
1293 if (SvPOK(basemsg) && consume) {
1298 sv_copypv(sv, basemsg);
1301 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1303 * Try and find the file and line for PL_op. This will usually be
1304 * PL_curcop, but it might be a cop that has been optimised away. We
1305 * can try to find such a cop by searching through the optree starting
1306 * from the sibling of PL_curcop.
1309 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1314 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1315 OutCopFILE(cop), (IV)CopLINE(cop));
1316 /* Seems that GvIO() can be untrustworthy during global destruction. */
1317 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1318 && IoLINES(GvIOp(PL_last_in_gv)))
1320 const bool line_mode = (RsSIMPLE(PL_rs) &&
1321 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1322 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1323 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1324 line_mode ? "line" : "chunk",
1325 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1328 sv_catpvs(sv, " during global destruction");
1329 sv_catpvs(sv, ".\n");
1335 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1337 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1338 argument list. These are used to generate a string message. If the
1339 message does not end with a newline, then it will be extended with
1340 some indication of the current location in the code, as described for
1343 Normally, the resulting message is returned in a new mortal SV.
1344 During global destruction a single SV may be shared between uses of
1351 Perl_vmess(pTHX_ const char *pat, va_list *args)
1354 SV * const sv = mess_alloc();
1356 PERL_ARGS_ASSERT_VMESS;
1358 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1359 return mess_sv(sv, 1);
1363 Perl_write_to_stderr(pTHX_ SV* msv)
1369 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1371 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1372 && (io = GvIO(PL_stderrgv))
1373 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1380 SAVESPTR(PL_stderrgv);
1383 PUSHSTACKi(PERLSI_MAGIC);
1387 PUSHs(SvTIED_obj(MUTABLE_SV(io), mg));
1390 call_method("PRINT", G_SCALAR);
1398 /* SFIO can really mess with your errno */
1401 PerlIO * const serr = Perl_error_log;
1403 const char* message = SvPVx_const(msv, msglen);
1405 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1406 (void)PerlIO_flush(serr);
1414 =head1 Warning and Dieing
1417 /* Common code used in dieing and warning */
1420 S_with_queued_errors(pTHX_ SV *ex)
1422 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1423 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1424 sv_catsv(PL_errors, ex);
1425 ex = sv_mortalcopy(PL_errors);
1426 SvCUR_set(PL_errors, 0);
1432 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1438 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1439 /* sv_2cv might call Perl_croak() or Perl_warner() */
1440 SV * const oldhook = *hook;
1448 cv = sv_2cv(oldhook, &stash, &gv, 0);
1450 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1460 exarg = newSVsv(ex);
1461 SvREADONLY_on(exarg);
1464 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1468 call_sv(MUTABLE_SV(cv), G_DISCARD);
1477 =for apidoc Am|OP *|die_sv|SV *baseex
1479 Behaves the same as L</croak_sv>, except for the return type.
1480 It should be used only where the C<OP *> return type is required.
1481 The function never actually returns.
1487 Perl_die_sv(pTHX_ SV *baseex)
1489 PERL_ARGS_ASSERT_DIE_SV;
1496 =for apidoc Am|OP *|die|const char *pat|...
1498 Behaves the same as L</croak>, except for the return type.
1499 It should be used only where the C<OP *> return type is required.
1500 The function never actually returns.
1505 #if defined(PERL_IMPLICIT_CONTEXT)
1507 Perl_die_nocontext(const char* pat, ...)
1511 va_start(args, pat);
1517 #endif /* PERL_IMPLICIT_CONTEXT */
1520 Perl_die(pTHX_ const char* pat, ...)
1523 va_start(args, pat);
1531 =for apidoc Am|void|croak_sv|SV *baseex
1533 This is an XS interface to Perl's C<die> function.
1535 C<baseex> is the error message or object. If it is a reference, it
1536 will be used as-is. Otherwise it is used as a string, and if it does
1537 not end with a newline then it will be extended with some indication of
1538 the current location in the code, as described for L</mess_sv>.
1540 The error message or object will be used as an exception, by default
1541 returning control to the nearest enclosing C<eval>, but subject to
1542 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1543 function never returns normally.
1545 To die with a simple string message, the L</croak> function may be
1552 Perl_croak_sv(pTHX_ SV *baseex)
1554 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1555 PERL_ARGS_ASSERT_CROAK_SV;
1556 invoke_exception_hook(ex, FALSE);
1561 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1563 This is an XS interface to Perl's C<die> function.
1565 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1566 argument list. These are used to generate a string message. If the
1567 message does not end with a newline, then it will be extended with
1568 some indication of the current location in the code, as described for
1571 The error message will be used as an exception, by default
1572 returning control to the nearest enclosing C<eval>, but subject to
1573 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1574 function never returns normally.
1576 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1577 (C<$@>) will be used as an error message or object instead of building an
1578 error message from arguments. If you want to throw a non-string object,
1579 or build an error message in an SV yourself, it is preferable to use
1580 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1586 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1588 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1589 invoke_exception_hook(ex, FALSE);
1594 =for apidoc Am|void|croak|const char *pat|...
1596 This is an XS interface to Perl's C<die> function.
1598 Take a sprintf-style format pattern and argument list. These are used to
1599 generate a string message. If the message does not end with a newline,
1600 then it will be extended with some indication of the current location
1601 in the code, as described for L</mess_sv>.
1603 The error message will be used as an exception, by default
1604 returning control to the nearest enclosing C<eval>, but subject to
1605 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1606 function never returns normally.
1608 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1609 (C<$@>) will be used as an error message or object instead of building an
1610 error message from arguments. If you want to throw a non-string object,
1611 or build an error message in an SV yourself, it is preferable to use
1612 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1617 #if defined(PERL_IMPLICIT_CONTEXT)
1619 Perl_croak_nocontext(const char *pat, ...)
1623 va_start(args, pat);
1628 #endif /* PERL_IMPLICIT_CONTEXT */
1631 Perl_croak(pTHX_ const char *pat, ...)
1634 va_start(args, pat);
1641 =for apidoc Am|void|croak_no_modify
1643 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1644 terser object code than using C<Perl_croak>. Less code used on exception code
1645 paths reduces CPU cache pressure.
1651 Perl_croak_no_modify(pTHX)
1653 Perl_croak(aTHX_ "%s", PL_no_modify);
1657 =for apidoc Am|void|warn_sv|SV *baseex
1659 This is an XS interface to Perl's C<warn> 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 by default be written to standard error,
1667 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1669 To warn with a simple string message, the L</warn> function may be
1676 Perl_warn_sv(pTHX_ SV *baseex)
1678 SV *ex = mess_sv(baseex, 0);
1679 PERL_ARGS_ASSERT_WARN_SV;
1680 if (!invoke_exception_hook(ex, TRUE))
1681 write_to_stderr(ex);
1685 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1687 This is an XS interface to Perl's C<warn> function.
1689 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1690 argument list. These are used to generate a string message. If the
1691 message does not end with a newline, then it will be extended with
1692 some indication of the current location in the code, as described for
1695 The error message or object will by default be written to standard error,
1696 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1698 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1704 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1706 SV *ex = vmess(pat, args);
1707 PERL_ARGS_ASSERT_VWARN;
1708 if (!invoke_exception_hook(ex, TRUE))
1709 write_to_stderr(ex);
1713 =for apidoc Am|void|warn|const char *pat|...
1715 This is an XS interface to Perl's C<warn> function.
1717 Take a sprintf-style format pattern and argument list. These are used to
1718 generate a string message. If the message does not end with a newline,
1719 then it will be extended with some indication of the current location
1720 in the code, as described for L</mess_sv>.
1722 The error message or object will by default be written to standard error,
1723 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1725 Unlike with L</croak>, C<pat> is not permitted to be null.
1730 #if defined(PERL_IMPLICIT_CONTEXT)
1732 Perl_warn_nocontext(const char *pat, ...)
1736 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1737 va_start(args, pat);
1741 #endif /* PERL_IMPLICIT_CONTEXT */
1744 Perl_warn(pTHX_ const char *pat, ...)
1747 PERL_ARGS_ASSERT_WARN;
1748 va_start(args, pat);
1753 #if defined(PERL_IMPLICIT_CONTEXT)
1755 Perl_warner_nocontext(U32 err, const char *pat, ...)
1759 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1760 va_start(args, pat);
1761 vwarner(err, pat, &args);
1764 #endif /* PERL_IMPLICIT_CONTEXT */
1767 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1769 PERL_ARGS_ASSERT_CK_WARNER_D;
1771 if (Perl_ckwarn_d(aTHX_ err)) {
1773 va_start(args, pat);
1774 vwarner(err, pat, &args);
1780 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1782 PERL_ARGS_ASSERT_CK_WARNER;
1784 if (Perl_ckwarn(aTHX_ err)) {
1786 va_start(args, pat);
1787 vwarner(err, pat, &args);
1793 Perl_warner(pTHX_ U32 err, const char* pat,...)
1796 PERL_ARGS_ASSERT_WARNER;
1797 va_start(args, pat);
1798 vwarner(err, pat, &args);
1803 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1806 PERL_ARGS_ASSERT_VWARNER;
1807 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1808 SV * const msv = vmess(pat, args);
1810 invoke_exception_hook(msv, FALSE);
1814 Perl_vwarn(aTHX_ pat, args);
1818 /* implements the ckWARN? macros */
1821 Perl_ckwarn(pTHX_ U32 w)
1824 /* If lexical warnings have not been set, use $^W. */
1826 return PL_dowarn & G_WARN_ON;
1828 return ckwarn_common(w);
1831 /* implements the ckWARN?_d macro */
1834 Perl_ckwarn_d(pTHX_ U32 w)
1837 /* If lexical warnings have not been set then default classes warn. */
1841 return ckwarn_common(w);
1845 S_ckwarn_common(pTHX_ U32 w)
1847 if (PL_curcop->cop_warnings == pWARN_ALL)
1850 if (PL_curcop->cop_warnings == pWARN_NONE)
1853 /* Check the assumption that at least the first slot is non-zero. */
1854 assert(unpackWARN1(w));
1856 /* Check the assumption that it is valid to stop as soon as a zero slot is
1858 if (!unpackWARN2(w)) {
1859 assert(!unpackWARN3(w));
1860 assert(!unpackWARN4(w));
1861 } else if (!unpackWARN3(w)) {
1862 assert(!unpackWARN4(w));
1865 /* Right, dealt with all the special cases, which are implemented as non-
1866 pointers, so there is a pointer to a real warnings mask. */
1868 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1870 } while (w >>= WARNshift);
1875 /* Set buffer=NULL to get a new one. */
1877 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1879 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1880 PERL_UNUSED_CONTEXT;
1881 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1884 (specialWARN(buffer) ?
1885 PerlMemShared_malloc(len_wanted) :
1886 PerlMemShared_realloc(buffer, len_wanted));
1888 Copy(bits, (buffer + 1), size, char);
1892 /* since we've already done strlen() for both nam and val
1893 * we can use that info to make things faster than
1894 * sprintf(s, "%s=%s", nam, val)
1896 #define my_setenv_format(s, nam, nlen, val, vlen) \
1897 Copy(nam, s, nlen, char); \
1899 Copy(val, s+(nlen+1), vlen, char); \
1900 *(s+(nlen+1+vlen)) = '\0'
1902 #ifdef USE_ENVIRON_ARRAY
1903 /* VMS' my_setenv() is in vms.c */
1904 #if !defined(WIN32) && !defined(NETWARE)
1906 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1910 /* only parent thread can modify process environment */
1911 if (PL_curinterp == aTHX)
1914 #ifndef PERL_USE_SAFE_PUTENV
1915 if (!PL_use_safe_putenv) {
1916 /* most putenv()s leak, so we manipulate environ directly */
1918 register const I32 len = strlen(nam);
1921 /* where does it go? */
1922 for (i = 0; environ[i]; i++) {
1923 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1927 if (environ == PL_origenviron) { /* need we copy environment? */
1933 while (environ[max])
1935 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1936 for (j=0; j<max; j++) { /* copy environment */
1937 const int len = strlen(environ[j]);
1938 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1939 Copy(environ[j], tmpenv[j], len+1, char);
1942 environ = tmpenv; /* tell exec where it is now */
1945 safesysfree(environ[i]);
1946 while (environ[i]) {
1947 environ[i] = environ[i+1];
1952 if (!environ[i]) { /* does not exist yet */
1953 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1954 environ[i+1] = NULL; /* make sure it's null terminated */
1957 safesysfree(environ[i]);
1961 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1962 /* all that work just for this */
1963 my_setenv_format(environ[i], nam, nlen, val, vlen);
1966 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1967 # if defined(HAS_UNSETENV)
1969 (void)unsetenv(nam);
1971 (void)setenv(nam, val, 1);
1973 # else /* ! HAS_UNSETENV */
1974 (void)setenv(nam, val, 1);
1975 # endif /* HAS_UNSETENV */
1977 # if defined(HAS_UNSETENV)
1979 (void)unsetenv(nam);
1981 const int nlen = strlen(nam);
1982 const int vlen = strlen(val);
1983 char * const new_env =
1984 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1985 my_setenv_format(new_env, nam, nlen, val, vlen);
1986 (void)putenv(new_env);
1988 # else /* ! HAS_UNSETENV */
1990 const int nlen = strlen(nam);
1996 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1997 /* all that work just for this */
1998 my_setenv_format(new_env, nam, nlen, val, vlen);
1999 (void)putenv(new_env);
2000 # endif /* HAS_UNSETENV */
2001 # endif /* __CYGWIN__ */
2002 #ifndef PERL_USE_SAFE_PUTENV
2008 #else /* WIN32 || NETWARE */
2011 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2014 register char *envstr;
2015 const int nlen = strlen(nam);
2022 Newx(envstr, nlen+vlen+2, char);
2023 my_setenv_format(envstr, nam, nlen, val, vlen);
2024 (void)PerlEnv_putenv(envstr);
2028 #endif /* WIN32 || NETWARE */
2030 #endif /* !VMS && !EPOC*/
2032 #ifdef UNLINK_ALL_VERSIONS
2034 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2038 PERL_ARGS_ASSERT_UNLNK;
2040 while (PerlLIO_unlink(f) >= 0)
2042 return retries ? 0 : -1;
2046 /* this is a drop-in replacement for bcopy() */
2047 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2049 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2051 char * const retval = to;
2053 PERL_ARGS_ASSERT_MY_BCOPY;
2055 if (from - to >= 0) {
2063 *(--to) = *(--from);
2069 /* this is a drop-in replacement for memset() */
2072 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2074 char * const retval = loc;
2076 PERL_ARGS_ASSERT_MY_MEMSET;
2084 /* this is a drop-in replacement for bzero() */
2085 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2087 Perl_my_bzero(register char *loc, register I32 len)
2089 char * const retval = loc;
2091 PERL_ARGS_ASSERT_MY_BZERO;
2099 /* this is a drop-in replacement for memcmp() */
2100 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2102 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2104 register const U8 *a = (const U8 *)s1;
2105 register const U8 *b = (const U8 *)s2;
2108 PERL_ARGS_ASSERT_MY_MEMCMP;
2111 if ((tmp = *a++ - *b++))
2116 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2119 /* This vsprintf replacement should generally never get used, since
2120 vsprintf was available in both System V and BSD 2.11. (There may
2121 be some cross-compilation or embedded set-ups where it is needed,
2124 If you encounter a problem in this function, it's probably a symptom
2125 that Configure failed to detect your system's vprintf() function.
2126 See the section on "item vsprintf" in the INSTALL file.
2128 This version may compile on systems with BSD-ish <stdio.h>,
2129 but probably won't on others.
2132 #ifdef USE_CHAR_VSPRINTF
2137 vsprintf(char *dest, const char *pat, void *args)
2141 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2142 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2143 FILE_cnt(&fakebuf) = 32767;
2145 /* These probably won't compile -- If you really need
2146 this, you'll have to figure out some other method. */
2147 fakebuf._ptr = dest;
2148 fakebuf._cnt = 32767;
2153 fakebuf._flag = _IOWRT|_IOSTRG;
2154 _doprnt(pat, args, &fakebuf); /* what a kludge */
2155 #if defined(STDIO_PTR_LVALUE)
2156 *(FILE_ptr(&fakebuf)++) = '\0';
2158 /* PerlIO has probably #defined away fputc, but we want it here. */
2160 # undef fputc /* XXX Should really restore it later */
2162 (void)fputc('\0', &fakebuf);
2164 #ifdef USE_CHAR_VSPRINTF
2167 return 0; /* perl doesn't use return value */
2171 #endif /* HAS_VPRINTF */
2174 #if BYTEORDER != 0x4321
2176 Perl_my_swap(pTHX_ short s)
2178 #if (BYTEORDER & 1) == 0
2181 result = ((s & 255) << 8) + ((s >> 8) & 255);
2189 Perl_my_htonl(pTHX_ long l)
2193 char c[sizeof(long)];
2196 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2197 #if BYTEORDER == 0x12345678
2200 u.c[0] = (l >> 24) & 255;
2201 u.c[1] = (l >> 16) & 255;
2202 u.c[2] = (l >> 8) & 255;
2206 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2207 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2212 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2213 u.c[o & 0xf] = (l >> s) & 255;
2221 Perl_my_ntohl(pTHX_ long l)
2225 char c[sizeof(long)];
2228 #if BYTEORDER == 0x1234
2229 u.c[0] = (l >> 24) & 255;
2230 u.c[1] = (l >> 16) & 255;
2231 u.c[2] = (l >> 8) & 255;
2235 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2236 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2243 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2244 l |= (u.c[o & 0xf] & 255) << s;
2251 #endif /* BYTEORDER != 0x4321 */
2255 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2256 * If these functions are defined,
2257 * the BYTEORDER is neither 0x1234 nor 0x4321.
2258 * However, this is not assumed.
2262 #define HTOLE(name,type) \
2264 name (register type n) \
2268 char c[sizeof(type)]; \
2271 register U32 s = 0; \
2272 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2273 u.c[i] = (n >> s) & 0xFF; \
2278 #define LETOH(name,type) \
2280 name (register type n) \
2284 char c[sizeof(type)]; \
2287 register U32 s = 0; \
2290 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2291 n |= ((type)(u.c[i] & 0xFF)) << s; \
2297 * Big-endian byte order functions.
2300 #define HTOBE(name,type) \
2302 name (register type n) \
2306 char c[sizeof(type)]; \
2309 register U32 s = 8*(sizeof(u.c)-1); \
2310 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2311 u.c[i] = (n >> s) & 0xFF; \
2316 #define BETOH(name,type) \
2318 name (register type n) \
2322 char c[sizeof(type)]; \
2325 register U32 s = 8*(sizeof(u.c)-1); \
2328 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2329 n |= ((type)(u.c[i] & 0xFF)) << s; \
2335 * If we just can't do it...
2338 #define NOT_AVAIL(name,type) \
2340 name (register type n) \
2342 Perl_croak_nocontext(#name "() not available"); \
2343 return n; /* not reached */ \
2347 #if defined(HAS_HTOVS) && !defined(htovs)
2350 #if defined(HAS_HTOVL) && !defined(htovl)
2353 #if defined(HAS_VTOHS) && !defined(vtohs)
2356 #if defined(HAS_VTOHL) && !defined(vtohl)
2360 #ifdef PERL_NEED_MY_HTOLE16
2362 HTOLE(Perl_my_htole16,U16)
2364 NOT_AVAIL(Perl_my_htole16,U16)
2367 #ifdef PERL_NEED_MY_LETOH16
2369 LETOH(Perl_my_letoh16,U16)
2371 NOT_AVAIL(Perl_my_letoh16,U16)
2374 #ifdef PERL_NEED_MY_HTOBE16
2376 HTOBE(Perl_my_htobe16,U16)
2378 NOT_AVAIL(Perl_my_htobe16,U16)
2381 #ifdef PERL_NEED_MY_BETOH16
2383 BETOH(Perl_my_betoh16,U16)
2385 NOT_AVAIL(Perl_my_betoh16,U16)
2389 #ifdef PERL_NEED_MY_HTOLE32
2391 HTOLE(Perl_my_htole32,U32)
2393 NOT_AVAIL(Perl_my_htole32,U32)
2396 #ifdef PERL_NEED_MY_LETOH32
2398 LETOH(Perl_my_letoh32,U32)
2400 NOT_AVAIL(Perl_my_letoh32,U32)
2403 #ifdef PERL_NEED_MY_HTOBE32
2405 HTOBE(Perl_my_htobe32,U32)
2407 NOT_AVAIL(Perl_my_htobe32,U32)
2410 #ifdef PERL_NEED_MY_BETOH32
2412 BETOH(Perl_my_betoh32,U32)
2414 NOT_AVAIL(Perl_my_betoh32,U32)
2418 #ifdef PERL_NEED_MY_HTOLE64
2420 HTOLE(Perl_my_htole64,U64)
2422 NOT_AVAIL(Perl_my_htole64,U64)
2425 #ifdef PERL_NEED_MY_LETOH64
2427 LETOH(Perl_my_letoh64,U64)
2429 NOT_AVAIL(Perl_my_letoh64,U64)
2432 #ifdef PERL_NEED_MY_HTOBE64
2434 HTOBE(Perl_my_htobe64,U64)
2436 NOT_AVAIL(Perl_my_htobe64,U64)
2439 #ifdef PERL_NEED_MY_BETOH64
2441 BETOH(Perl_my_betoh64,U64)
2443 NOT_AVAIL(Perl_my_betoh64,U64)
2447 #ifdef PERL_NEED_MY_HTOLES
2448 HTOLE(Perl_my_htoles,short)
2450 #ifdef PERL_NEED_MY_LETOHS
2451 LETOH(Perl_my_letohs,short)
2453 #ifdef PERL_NEED_MY_HTOBES
2454 HTOBE(Perl_my_htobes,short)
2456 #ifdef PERL_NEED_MY_BETOHS
2457 BETOH(Perl_my_betohs,short)
2460 #ifdef PERL_NEED_MY_HTOLEI
2461 HTOLE(Perl_my_htolei,int)
2463 #ifdef PERL_NEED_MY_LETOHI
2464 LETOH(Perl_my_letohi,int)
2466 #ifdef PERL_NEED_MY_HTOBEI
2467 HTOBE(Perl_my_htobei,int)
2469 #ifdef PERL_NEED_MY_BETOHI
2470 BETOH(Perl_my_betohi,int)
2473 #ifdef PERL_NEED_MY_HTOLEL
2474 HTOLE(Perl_my_htolel,long)
2476 #ifdef PERL_NEED_MY_LETOHL
2477 LETOH(Perl_my_letohl,long)
2479 #ifdef PERL_NEED_MY_HTOBEL
2480 HTOBE(Perl_my_htobel,long)
2482 #ifdef PERL_NEED_MY_BETOHL
2483 BETOH(Perl_my_betohl,long)
2487 Perl_my_swabn(void *ptr, int n)
2489 register char *s = (char *)ptr;
2490 register char *e = s + (n-1);
2493 PERL_ARGS_ASSERT_MY_SWABN;
2495 for (n /= 2; n > 0; s++, e--, n--) {
2503 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2505 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2508 register I32 This, that;
2514 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2516 PERL_FLUSHALL_FOR_CHILD;
2517 This = (*mode == 'w');
2521 taint_proper("Insecure %s%s", "EXEC");
2523 if (PerlProc_pipe(p) < 0)
2525 /* Try for another pipe pair for error return */
2526 if (PerlProc_pipe(pp) >= 0)
2528 while ((pid = PerlProc_fork()) < 0) {
2529 if (errno != EAGAIN) {
2530 PerlLIO_close(p[This]);
2531 PerlLIO_close(p[that]);
2533 PerlLIO_close(pp[0]);
2534 PerlLIO_close(pp[1]);
2538 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2547 /* Close parent's end of error status pipe (if any) */
2549 PerlLIO_close(pp[0]);
2550 #if defined(HAS_FCNTL) && defined(F_SETFD)
2551 /* Close error pipe automatically if exec works */
2552 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2555 /* Now dup our end of _the_ pipe to right position */
2556 if (p[THIS] != (*mode == 'r')) {
2557 PerlLIO_dup2(p[THIS], *mode == 'r');
2558 PerlLIO_close(p[THIS]);
2559 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2560 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2563 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2564 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2565 /* No automatic close - do it by hand */
2572 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2578 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2584 do_execfree(); /* free any memory malloced by child on fork */
2586 PerlLIO_close(pp[1]);
2587 /* Keep the lower of the two fd numbers */
2588 if (p[that] < p[This]) {
2589 PerlLIO_dup2(p[This], p[that]);
2590 PerlLIO_close(p[This]);
2594 PerlLIO_close(p[that]); /* close child's end of pipe */
2596 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2597 SvUPGRADE(sv,SVt_IV);
2599 PL_forkprocess = pid;
2600 /* If we managed to get status pipe check for exec fail */
2601 if (did_pipes && pid > 0) {
2606 while (n < sizeof(int)) {
2607 n1 = PerlLIO_read(pp[0],
2608 (void*)(((char*)&errkid)+n),
2614 PerlLIO_close(pp[0]);
2616 if (n) { /* Error */
2618 PerlLIO_close(p[This]);
2619 if (n != sizeof(int))
2620 Perl_croak(aTHX_ "panic: kid popen errno read");
2622 pid2 = wait4pid(pid, &status, 0);
2623 } while (pid2 == -1 && errno == EINTR);
2624 errno = errkid; /* Propagate errno from kid */
2629 PerlLIO_close(pp[0]);
2630 return PerlIO_fdopen(p[This], mode);
2632 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2633 return my_syspopen4(aTHX_ NULL, mode, n, args);
2635 Perl_croak(aTHX_ "List form of piped open not implemented");
2636 return (PerlIO *) NULL;
2641 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2642 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2644 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2648 register I32 This, that;
2651 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2655 PERL_ARGS_ASSERT_MY_POPEN;
2657 PERL_FLUSHALL_FOR_CHILD;
2660 return my_syspopen(aTHX_ cmd,mode);
2663 This = (*mode == 'w');
2665 if (doexec && PL_tainting) {
2667 taint_proper("Insecure %s%s", "EXEC");
2669 if (PerlProc_pipe(p) < 0)
2671 if (doexec && PerlProc_pipe(pp) >= 0)
2673 while ((pid = PerlProc_fork()) < 0) {
2674 if (errno != EAGAIN) {
2675 PerlLIO_close(p[This]);
2676 PerlLIO_close(p[that]);
2678 PerlLIO_close(pp[0]);
2679 PerlLIO_close(pp[1]);
2682 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2685 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2696 PerlLIO_close(pp[0]);
2697 #if defined(HAS_FCNTL) && defined(F_SETFD)
2698 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2701 if (p[THIS] != (*mode == 'r')) {
2702 PerlLIO_dup2(p[THIS], *mode == 'r');
2703 PerlLIO_close(p[THIS]);
2704 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2705 PerlLIO_close(p[THAT]);
2708 PerlLIO_close(p[THAT]);
2711 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2718 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2723 /* may or may not use the shell */
2724 do_exec3(cmd, pp[1], did_pipes);
2727 #endif /* defined OS2 */
2729 #ifdef PERLIO_USING_CRLF
2730 /* Since we circumvent IO layers when we manipulate low-level
2731 filedescriptors directly, need to manually switch to the
2732 default, binary, low-level mode; see PerlIOBuf_open(). */
2733 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2736 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2737 SvREADONLY_off(GvSV(tmpgv));
2738 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2739 SvREADONLY_on(GvSV(tmpgv));
2741 #ifdef THREADS_HAVE_PIDS
2742 PL_ppid = (IV)getppid();
2745 #ifdef PERL_USES_PL_PIDSTATUS
2746 hv_clear(PL_pidstatus); /* we have no children */
2752 do_execfree(); /* free any memory malloced by child on vfork */
2754 PerlLIO_close(pp[1]);
2755 if (p[that] < p[This]) {
2756 PerlLIO_dup2(p[This], p[that]);
2757 PerlLIO_close(p[This]);
2761 PerlLIO_close(p[that]);
2763 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2764 SvUPGRADE(sv,SVt_IV);
2766 PL_forkprocess = pid;
2767 if (did_pipes && pid > 0) {
2772 while (n < sizeof(int)) {
2773 n1 = PerlLIO_read(pp[0],
2774 (void*)(((char*)&errkid)+n),
2780 PerlLIO_close(pp[0]);
2782 if (n) { /* Error */
2784 PerlLIO_close(p[This]);
2785 if (n != sizeof(int))
2786 Perl_croak(aTHX_ "panic: kid popen errno read");
2788 pid2 = wait4pid(pid, &status, 0);
2789 } while (pid2 == -1 && errno == EINTR);
2790 errno = errkid; /* Propagate errno from kid */
2795 PerlLIO_close(pp[0]);
2796 return PerlIO_fdopen(p[This], mode);
2799 #if defined(atarist) || defined(EPOC)
2802 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2804 PERL_ARGS_ASSERT_MY_POPEN;
2805 PERL_FLUSHALL_FOR_CHILD;
2806 /* Call system's popen() to get a FILE *, then import it.
2807 used 0 for 2nd parameter to PerlIO_importFILE;
2810 return PerlIO_importFILE(popen(cmd, mode), 0);
2814 FILE *djgpp_popen();
2816 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2818 PERL_FLUSHALL_FOR_CHILD;
2819 /* Call system's popen() to get a FILE *, then import it.
2820 used 0 for 2nd parameter to PerlIO_importFILE;
2823 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2826 #if defined(__LIBCATAMOUNT__)
2828 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2836 #endif /* !DOSISH */
2838 /* this is called in parent before the fork() */
2840 Perl_atfork_lock(void)
2843 #if defined(USE_ITHREADS)
2844 /* locks must be held in locking order (if any) */
2846 MUTEX_LOCK(&PL_malloc_mutex);
2852 /* this is called in both parent and child after the fork() */
2854 Perl_atfork_unlock(void)
2857 #if defined(USE_ITHREADS)
2858 /* locks must be released in same order as in atfork_lock() */
2860 MUTEX_UNLOCK(&PL_malloc_mutex);
2869 #if defined(HAS_FORK)
2871 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2876 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2877 * handlers elsewhere in the code */
2882 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2883 Perl_croak_nocontext("fork() not available");
2885 #endif /* HAS_FORK */
2890 Perl_dump_fds(pTHX_ const char *const s)
2895 PERL_ARGS_ASSERT_DUMP_FDS;
2897 PerlIO_printf(Perl_debug_log,"%s", s);
2898 for (fd = 0; fd < 32; fd++) {
2899 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2900 PerlIO_printf(Perl_debug_log," %d",fd);
2902 PerlIO_printf(Perl_debug_log,"\n");
2905 #endif /* DUMP_FDS */
2909 dup2(int oldfd, int newfd)
2911 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2914 PerlLIO_close(newfd);
2915 return fcntl(oldfd, F_DUPFD, newfd);
2917 #define DUP2_MAX_FDS 256
2918 int fdtmp[DUP2_MAX_FDS];
2924 PerlLIO_close(newfd);
2925 /* good enough for low fd's... */
2926 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2927 if (fdx >= DUP2_MAX_FDS) {
2935 PerlLIO_close(fdtmp[--fdx]);
2942 #ifdef HAS_SIGACTION
2945 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2948 struct sigaction act, oact;
2951 /* only "parent" interpreter can diddle signals */
2952 if (PL_curinterp != aTHX)
2953 return (Sighandler_t) SIG_ERR;
2956 act.sa_handler = (void(*)(int))handler;
2957 sigemptyset(&act.sa_mask);
2960 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2961 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2963 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2964 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2965 act.sa_flags |= SA_NOCLDWAIT;
2967 if (sigaction(signo, &act, &oact) == -1)
2968 return (Sighandler_t) SIG_ERR;
2970 return (Sighandler_t) oact.sa_handler;
2974 Perl_rsignal_state(pTHX_ int signo)
2976 struct sigaction oact;
2977 PERL_UNUSED_CONTEXT;
2979 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2980 return (Sighandler_t) SIG_ERR;
2982 return (Sighandler_t) oact.sa_handler;
2986 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2989 struct sigaction act;
2991 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2994 /* only "parent" interpreter can diddle signals */
2995 if (PL_curinterp != aTHX)
2999 act.sa_handler = (void(*)(int))handler;
3000 sigemptyset(&act.sa_mask);
3003 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3004 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3006 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3007 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3008 act.sa_flags |= SA_NOCLDWAIT;
3010 return sigaction(signo, &act, save);
3014 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3018 /* only "parent" interpreter can diddle signals */
3019 if (PL_curinterp != aTHX)
3023 return sigaction(signo, save, (struct sigaction *)NULL);
3026 #else /* !HAS_SIGACTION */
3029 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3031 #if defined(USE_ITHREADS) && !defined(WIN32)
3032 /* only "parent" interpreter can diddle signals */
3033 if (PL_curinterp != aTHX)
3034 return (Sighandler_t) SIG_ERR;
3037 return PerlProc_signal(signo, handler);
3048 Perl_rsignal_state(pTHX_ int signo)
3051 Sighandler_t oldsig;
3053 #if defined(USE_ITHREADS) && !defined(WIN32)
3054 /* only "parent" interpreter can diddle signals */
3055 if (PL_curinterp != aTHX)
3056 return (Sighandler_t) SIG_ERR;
3060 oldsig = PerlProc_signal(signo, sig_trap);
3061 PerlProc_signal(signo, oldsig);
3063 PerlProc_kill(PerlProc_getpid(), signo);
3068 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3070 #if defined(USE_ITHREADS) && !defined(WIN32)
3071 /* only "parent" interpreter can diddle signals */
3072 if (PL_curinterp != aTHX)
3075 *save = PerlProc_signal(signo, handler);
3076 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3080 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3082 #if defined(USE_ITHREADS) && !defined(WIN32)
3083 /* only "parent" interpreter can diddle signals */
3084 if (PL_curinterp != aTHX)
3087 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3090 #endif /* !HAS_SIGACTION */
3091 #endif /* !PERL_MICRO */
3093 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3094 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3096 Perl_my_pclose(pTHX_ PerlIO *ptr)
3099 Sigsave_t hstat, istat, qstat;
3107 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
3108 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3110 *svp = &PL_sv_undef;
3112 if (pid == -1) { /* Opened by popen. */
3113 return my_syspclose(ptr);
3116 close_failed = (PerlIO_close(ptr) == EOF);
3119 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3122 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3123 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3124 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3127 pid2 = wait4pid(pid, &status, 0);
3128 } while (pid2 == -1 && errno == EINTR);
3130 rsignal_restore(SIGHUP, &hstat);
3131 rsignal_restore(SIGINT, &istat);
3132 rsignal_restore(SIGQUIT, &qstat);
3138 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
3141 #if defined(__LIBCATAMOUNT__)
3143 Perl_my_pclose(pTHX_ PerlIO *ptr)
3148 #endif /* !DOSISH */
3150 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3152 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3156 PERL_ARGS_ASSERT_WAIT4PID;
3159 #ifdef PERL_USES_PL_PIDSTATUS
3162 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3163 pid, rather than a string form. */
3164 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3165 if (svp && *svp != &PL_sv_undef) {
3166 *statusp = SvIVX(*svp);
3167 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3175 hv_iterinit(PL_pidstatus);
3176 if ((entry = hv_iternext(PL_pidstatus))) {
3177 SV * const sv = hv_iterval(PL_pidstatus,entry);
3179 const char * const spid = hv_iterkey(entry,&len);
3181 assert (len == sizeof(Pid_t));
3182 memcpy((char *)&pid, spid, len);
3183 *statusp = SvIVX(sv);
3184 /* The hash iterator is currently on this entry, so simply
3185 calling hv_delete would trigger the lazy delete, which on
3186 aggregate does more work, beacuse next call to hv_iterinit()
3187 would spot the flag, and have to call the delete routine,
3188 while in the meantime any new entries can't re-use that
3190 hv_iterinit(PL_pidstatus);
3191 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3198 # ifdef HAS_WAITPID_RUNTIME
3199 if (!HAS_WAITPID_RUNTIME)
3202 result = PerlProc_waitpid(pid,statusp,flags);
3205 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3206 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3209 #ifdef PERL_USES_PL_PIDSTATUS
3210 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3215 Perl_croak(aTHX_ "Can't do waitpid with flags");
3217 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3218 pidgone(result,*statusp);
3224 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3227 if (result < 0 && errno == EINTR) {
3229 errno = EINTR; /* reset in case a signal handler changed $! */
3233 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3235 #ifdef PERL_USES_PL_PIDSTATUS
3237 S_pidgone(pTHX_ Pid_t pid, int status)
3241 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3242 SvUPGRADE(sv,SVt_IV);
3243 SvIV_set(sv, status);
3248 #if defined(atarist) || defined(OS2) || defined(EPOC)
3251 int /* Cannot prototype with I32
3253 my_syspclose(PerlIO *ptr)
3256 Perl_my_pclose(pTHX_ PerlIO *ptr)
3259 /* Needs work for PerlIO ! */
3260 FILE * const f = PerlIO_findFILE(ptr);
3261 const I32 result = pclose(f);
3262 PerlIO_releaseFILE(ptr,f);
3270 Perl_my_pclose(pTHX_ PerlIO *ptr)
3272 /* Needs work for PerlIO ! */
3273 FILE * const f = PerlIO_findFILE(ptr);
3274 I32 result = djgpp_pclose(f);
3275 result = (result << 8) & 0xff00;
3276 PerlIO_releaseFILE(ptr,f);
3281 #define PERL_REPEATCPY_LINEAR 4
3283 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3285 PERL_ARGS_ASSERT_REPEATCPY;
3288 memset(to, *from, count);
3290 register char *p = to;
3291 I32 items, linear, half;
3293 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3294 for (items = 0; items < linear; ++items) {
3295 register const char *q = from;
3297 for (todo = len; todo > 0; todo--)
3302 while (items <= half) {
3303 I32 size = items * len;
3304 memcpy(p, to, size);
3310 memcpy(p, to, (count - items) * len);
3316 Perl_same_dirent(pTHX_ const char *a, const char *b)
3318 char *fa = strrchr(a,'/');
3319 char *fb = strrchr(b,'/');
3322 SV * const tmpsv = sv_newmortal();
3324 PERL_ARGS_ASSERT_SAME_DIRENT;
3337 sv_setpvs(tmpsv, ".");
3339 sv_setpvn(tmpsv, a, fa - a);
3340 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3343 sv_setpvs(tmpsv, ".");
3345 sv_setpvn(tmpsv, b, fb - b);
3346 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3348 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3349 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3351 #endif /* !HAS_RENAME */
3354 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3355 const char *const *const search_ext, I32 flags)
3358 const char *xfound = NULL;
3359 char *xfailed = NULL;
3360 char tmpbuf[MAXPATHLEN];
3365 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3366 # define SEARCH_EXTS ".bat", ".cmd", NULL
3367 # define MAX_EXT_LEN 4
3370 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3371 # define MAX_EXT_LEN 4
3374 # define SEARCH_EXTS ".pl", ".com", NULL
3375 # define MAX_EXT_LEN 4
3377 /* additional extensions to try in each dir if scriptname not found */
3379 static const char *const exts[] = { SEARCH_EXTS };
3380 const char *const *const ext = search_ext ? search_ext : exts;
3381 int extidx = 0, i = 0;
3382 const char *curext = NULL;
3384 PERL_UNUSED_ARG(search_ext);
3385 # define MAX_EXT_LEN 0
3388 PERL_ARGS_ASSERT_FIND_SCRIPT;
3391 * If dosearch is true and if scriptname does not contain path
3392 * delimiters, search the PATH for scriptname.
3394 * If SEARCH_EXTS is also defined, will look for each
3395 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3396 * while searching the PATH.
3398 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3399 * proceeds as follows:
3400 * If DOSISH or VMSISH:
3401 * + look for ./scriptname{,.foo,.bar}
3402 * + search the PATH for scriptname{,.foo,.bar}
3405 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3406 * this will not look in '.' if it's not in the PATH)
3411 # ifdef ALWAYS_DEFTYPES
3412 len = strlen(scriptname);
3413 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3414 int idx = 0, deftypes = 1;
3417 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3420 int idx = 0, deftypes = 1;
3423 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3425 /* The first time through, just add SEARCH_EXTS to whatever we
3426 * already have, so we can check for default file types. */
3428 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3434 if ((strlen(tmpbuf) + strlen(scriptname)
3435 + MAX_EXT_LEN) >= sizeof tmpbuf)
3436 continue; /* don't search dir with too-long name */
3437 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3441 if (strEQ(scriptname, "-"))
3443 if (dosearch) { /* Look in '.' first. */
3444 const char *cur = scriptname;
3446 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3448 if (strEQ(ext[i++],curext)) {
3449 extidx = -1; /* already has an ext */
3454 DEBUG_p(PerlIO_printf(Perl_debug_log,
3455 "Looking for %s\n",cur));
3456 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3457 && !S_ISDIR(PL_statbuf.st_mode)) {
3465 if (cur == scriptname) {
3466 len = strlen(scriptname);
3467 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3469 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3472 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3473 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3478 if (dosearch && !strchr(scriptname, '/')
3480 && !strchr(scriptname, '\\')
3482 && (s = PerlEnv_getenv("PATH")))
3486 bufend = s + strlen(s);
3487 while (s < bufend) {
3488 #if defined(atarist) || defined(DOSISH)
3493 && *s != ';'; len++, s++) {
3494 if (len < sizeof tmpbuf)
3497 if (len < sizeof tmpbuf)
3499 #else /* ! (atarist || DOSISH) */
3500 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3503 #endif /* ! (atarist || DOSISH) */
3506 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3507 continue; /* don't search dir with too-long name */
3509 # if defined(atarist) || defined(DOSISH)
3510 && tmpbuf[len - 1] != '/'
3511 && tmpbuf[len - 1] != '\\'
3514 tmpbuf[len++] = '/';
3515 if (len == 2 && tmpbuf[0] == '.')
3517 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3521 len = strlen(tmpbuf);
3522 if (extidx > 0) /* reset after previous loop */
3526 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3527 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3528 if (S_ISDIR(PL_statbuf.st_mode)) {
3532 } while ( retval < 0 /* not there */
3533 && extidx>=0 && ext[extidx] /* try an extension? */
3534 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3539 if (S_ISREG(PL_statbuf.st_mode)
3540 && cando(S_IRUSR,TRUE,&PL_statbuf)
3541 #if !defined(DOSISH)
3542 && cando(S_IXUSR,TRUE,&PL_statbuf)
3546 xfound = tmpbuf; /* bingo! */
3550 xfailed = savepv(tmpbuf);
3553 if (!xfound && !seen_dot && !xfailed &&
3554 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3555 || S_ISDIR(PL_statbuf.st_mode)))
3557 seen_dot = 1; /* Disable message. */
3559 if (flags & 1) { /* do or die? */
3560 Perl_croak(aTHX_ "Can't %s %s%s%s",
3561 (xfailed ? "execute" : "find"),
3562 (xfailed ? xfailed : scriptname),
3563 (xfailed ? "" : " on PATH"),
3564 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3569 scriptname = xfound;
3571 return (scriptname ? savepv(scriptname) : NULL);
3574 #ifndef PERL_GET_CONTEXT_DEFINED
3577 Perl_get_context(void)
3580 #if defined(USE_ITHREADS)
3581 # ifdef OLD_PTHREADS_API
3583 if (pthread_getspecific(PL_thr_key, &t))
3584 Perl_croak_nocontext("panic: pthread_getspecific");
3587 # ifdef I_MACH_CTHREADS
3588 return (void*)cthread_data(cthread_self());
3590 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3599 Perl_set_context(void *t)
3602 PERL_ARGS_ASSERT_SET_CONTEXT;
3603 #if defined(USE_ITHREADS)
3604 # ifdef I_MACH_CTHREADS
3605 cthread_set_data(cthread_self(), t);
3607 if (pthread_setspecific(PL_thr_key, t))
3608 Perl_croak_nocontext("panic: pthread_setspecific");
3615 #endif /* !PERL_GET_CONTEXT_DEFINED */
3617 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3626 Perl_get_op_names(pTHX)
3628 PERL_UNUSED_CONTEXT;
3629 return (char **)PL_op_name;
3633 Perl_get_op_descs(pTHX)
3635 PERL_UNUSED_CONTEXT;
3636 return (char **)PL_op_desc;
3640 Perl_get_no_modify(pTHX)
3642 PERL_UNUSED_CONTEXT;
3643 return PL_no_modify;
3647 Perl_get_opargs(pTHX)
3649 PERL_UNUSED_CONTEXT;
3650 return (U32 *)PL_opargs;
3654 Perl_get_ppaddr(pTHX)
3657 PERL_UNUSED_CONTEXT;
3658 return (PPADDR_t*)PL_ppaddr;
3661 #ifndef HAS_GETENV_LEN
3663 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3665 char * const env_trans = PerlEnv_getenv(env_elem);
3666 PERL_UNUSED_CONTEXT;
3667 PERL_ARGS_ASSERT_GETENV_LEN;
3669 *len = strlen(env_trans);
3676 Perl_get_vtbl(pTHX_ int vtbl_id)
3678 const MGVTBL* result;
3679 PERL_UNUSED_CONTEXT;
3683 result = &PL_vtbl_sv;
3686 result = &PL_vtbl_env;
3688 case want_vtbl_envelem:
3689 result = &PL_vtbl_envelem;
3692 result = &PL_vtbl_sig;
3694 case want_vtbl_sigelem:
3695 result = &PL_vtbl_sigelem;
3697 case want_vtbl_pack:
3698 result = &PL_vtbl_pack;
3700 case want_vtbl_packelem:
3701 result = &PL_vtbl_packelem;
3703 case want_vtbl_dbline:
3704 result = &PL_vtbl_dbline;
3707 result = &PL_vtbl_isa;
3709 case want_vtbl_isaelem:
3710 result = &PL_vtbl_isaelem;
3712 case want_vtbl_arylen:
3713 result = &PL_vtbl_arylen;
3715 case want_vtbl_mglob:
3716 result = &PL_vtbl_mglob;
3718 case want_vtbl_nkeys:
3719 result = &PL_vtbl_nkeys;
3721 case want_vtbl_taint:
3722 result = &PL_vtbl_taint;
3724 case want_vtbl_substr:
3725 result = &PL_vtbl_substr;
3728 result = &PL_vtbl_vec;
3731 result = &PL_vtbl_pos;
3734 result = &PL_vtbl_bm;
3737 result = &PL_vtbl_fm;
3739 case want_vtbl_uvar:
3740 result = &PL_vtbl_uvar;
3742 case want_vtbl_defelem:
3743 result = &PL_vtbl_defelem;
3745 case want_vtbl_regexp:
3746 result = &PL_vtbl_regexp;
3748 case want_vtbl_regdata:
3749 result = &PL_vtbl_regdata;
3751 case want_vtbl_regdatum:
3752 result = &PL_vtbl_regdatum;
3754 #ifdef USE_LOCALE_COLLATE
3755 case want_vtbl_collxfrm:
3756 result = &PL_vtbl_collxfrm;
3759 case want_vtbl_amagic:
3760 result = &PL_vtbl_amagic;
3762 case want_vtbl_amagicelem:
3763 result = &PL_vtbl_amagicelem;
3765 case want_vtbl_backref:
3766 result = &PL_vtbl_backref;
3768 case want_vtbl_utf8:
3769 result = &PL_vtbl_utf8;
3775 return (MGVTBL*)result;
3779 Perl_my_fflush_all(pTHX)
3781 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3782 return PerlIO_flush(NULL);
3784 # if defined(HAS__FWALK)
3785 extern int fflush(FILE *);
3786 /* undocumented, unprototyped, but very useful BSDism */
3787 extern void _fwalk(int (*)(FILE *));
3791 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3793 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3794 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3796 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3797 open_max = sysconf(_SC_OPEN_MAX);
3800 open_max = FOPEN_MAX;
3803 open_max = OPEN_MAX;
3814 for (i = 0; i < open_max; i++)
3815 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3816 STDIO_STREAM_ARRAY[i]._file < open_max &&
3817 STDIO_STREAM_ARRAY[i]._flag)
3818 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3822 SETERRNO(EBADF,RMS_IFI);
3829 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3831 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3833 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3834 if (ckWARN(WARN_IO)) {
3835 const char * const direction =
3836 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3838 Perl_warner(aTHX_ packWARN(WARN_IO),
3839 "Filehandle %s opened only for %sput",
3842 Perl_warner(aTHX_ packWARN(WARN_IO),
3843 "Filehandle opened only for %sput", direction);
3850 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3852 warn_type = WARN_CLOSED;
3856 warn_type = WARN_UNOPENED;
3859 if (ckWARN(warn_type)) {
3860 const char * const pars =
3861 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3862 const char * const func =
3864 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3865 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3866 op < 0 ? "" : /* handle phoney cases */
3868 const char * const type =
3870 (OP_IS_SOCKET(op) ||
3871 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3872 "socket" : "filehandle");
3873 if (name && *name) {
3874 Perl_warner(aTHX_ packWARN(warn_type),
3875 "%s%s on %s %s %s", func, pars, vile, type, name);
3876 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3878 aTHX_ packWARN(warn_type),
3879 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3884 Perl_warner(aTHX_ packWARN(warn_type),
3885 "%s%s on %s %s", func, pars, vile, type);
3886 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3888 aTHX_ packWARN(warn_type),
3889 "\t(Are you trying to call %s%s on dirhandle?)\n",
3897 /* XXX Add documentation after final interface and behavior is decided */
3898 /* May want to show context for error, so would pass Perl_bslash_c(pTHX_ const char* current, const char* start, const bool output_warning)
3899 U8 source = *current;
3901 May want to add eg, WARN_REGEX
3905 Perl_grok_bslash_c(pTHX_ const char source, const bool output_warning)
3910 if (! isASCII(source)) {
3911 Perl_croak(aTHX_ "Character following \"\\c\" must be ASCII");
3914 result = toCTRL(source);
3915 if (! isCNTRL(result)) {
3916 if (source == '{') {
3917 Perl_croak(aTHX_ "It is proposed that \"\\c{\" no longer be valid. It has historically evaluated to\n \";\". If you disagree with this proposal, send email to perl5-porters@perl.org\nOtherwise, or in the meantime, you can work around this failure by changing\n\"\\c{\" to \";\"");
3919 else if (output_warning) {
3922 if (! isALNUM(result)) {
3923 clearer[i++] = '\\';
3925 clearer[i++] = result;
3926 clearer[i++] = '\0';
3928 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
3929 "\"\\c%c\" more clearly written simply as \"%s\"",
3939 Perl_grok_bslash_o(pTHX_ const char *s,
3942 const char** error_msg,
3943 const bool output_warning)
3946 /* Documentation to be supplied when interface nailed down finally
3947 * This returns FALSE if there is an error which the caller need not recover
3948 * from; , otherwise TRUE. In either case the caller should look at *len
3950 * s points to a string that begins with 'o', and the previous character
3952 * uv points to a UV that will hold the output value, valid only if the
3953 * return from the function is TRUE
3954 * len on success will point to the next character in the string past the
3955 * end of this construct.
3956 * on failure, it will point to the failure
3957 * error_msg is a pointer that will be set to an internal buffer giving an
3958 * error message upon failure (the return is FALSE). Untouched if
3960 * output_warning says whether to output any warning messages, or suppress
3965 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3966 | PERL_SCAN_DISALLOW_PREFIX
3967 /* XXX Until the message is improved in grok_oct, handle errors
3969 | PERL_SCAN_SILENT_ILLDIGIT;
3971 PERL_ARGS_ASSERT_GROK_BSLASH_O;
3978 *len = 1; /* Move past the o */
3979 *error_msg = "Missing braces on \\o{}";
3985 *len = 2; /* Move past the o{ */
3986 *error_msg = "Missing right brace on \\o{";
3990 /* Return past the '}' no matter what is inside the braces */
3991 *len = e - s + 2; /* 2 = 1 for the o + 1 for the '}' */
3993 s++; /* Point to first digit */
3995 numbers_len = e - s;
3996 if (numbers_len == 0) {
3997 *error_msg = "Number with no digits";
4001 *uv = NATIVE_TO_UNI(grok_oct(s, &numbers_len, &flags, NULL));
4002 /* Note that if has non-octal, will ignore everything starting with that up
4005 if (output_warning && numbers_len != (STRLEN) (e - s)) {
4006 Perl_ck_warner(aTHX_ packWARN(WARN_DIGIT),
4007 /* diag_listed_as: Non-octal character '%c'. Resolved as "%s" */
4008 "Non-octal character '%c'. Resolved as \"\\o{%.*s}\"",
4017 /* To workaround core dumps from the uninitialised tm_zone we get the
4018 * system to give us a reasonable struct to copy. This fix means that
4019 * strftime uses the tm_zone and tm_gmtoff values returned by
4020 * localtime(time()). That should give the desired result most of the
4021 * time. But probably not always!
4023 * This does not address tzname aspects of NETaa14816.
4028 # ifndef STRUCT_TM_HASZONE
4029 # define STRUCT_TM_HASZONE
4033 #ifdef STRUCT_TM_HASZONE /* Backward compat */
4034 # ifndef HAS_TM_TM_ZONE
4035 # define HAS_TM_TM_ZONE
4040 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
4042 #ifdef HAS_TM_TM_ZONE
4044 const struct tm* my_tm;
4045 PERL_ARGS_ASSERT_INIT_TM;
4047 my_tm = localtime(&now);
4049 Copy(my_tm, ptm, 1, struct tm);
4051 PERL_ARGS_ASSERT_INIT_TM;
4052 PERL_UNUSED_ARG(ptm);
4057 * mini_mktime - normalise struct tm values without the localtime()
4058 * semantics (and overhead) of mktime().
4061 Perl_mini_mktime(pTHX_ struct tm *ptm)
4065 int month, mday, year, jday;
4066 int odd_cent, odd_year;
4067 PERL_UNUSED_CONTEXT;
4069 PERL_ARGS_ASSERT_MINI_MKTIME;
4071 #define DAYS_PER_YEAR 365
4072 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
4073 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
4074 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
4075 #define SECS_PER_HOUR (60*60)
4076 #define SECS_PER_DAY (24*SECS_PER_HOUR)
4077 /* parentheses deliberately absent on these two, otherwise they don't work */
4078 #define MONTH_TO_DAYS 153/5
4079 #define DAYS_TO_MONTH 5/153
4080 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4081 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4082 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4083 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4086 * Year/day algorithm notes:
4088 * With a suitable offset for numeric value of the month, one can find
4089 * an offset into the year by considering months to have 30.6 (153/5) days,
4090 * using integer arithmetic (i.e., with truncation). To avoid too much
4091 * messing about with leap days, we consider January and February to be
4092 * the 13th and 14th month of the previous year. After that transformation,
4093 * we need the month index we use to be high by 1 from 'normal human' usage,
4094 * so the month index values we use run from 4 through 15.
4096 * Given that, and the rules for the Gregorian calendar (leap years are those
4097 * divisible by 4 unless also divisible by 100, when they must be divisible
4098 * by 400 instead), we can simply calculate the number of days since some
4099 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4100 * the days we derive from our month index, and adding in the day of the
4101 * month. The value used here is not adjusted for the actual origin which
4102 * it normally would use (1 January A.D. 1), since we're not exposing it.
4103 * We're only building the value so we can turn around and get the
4104 * normalised values for the year, month, day-of-month, and day-of-year.
4106 * For going backward, we need to bias the value we're using so that we find
4107 * the right year value. (Basically, we don't want the contribution of
4108 * March 1st to the number to apply while deriving the year). Having done
4109 * that, we 'count up' the contribution to the year number by accounting for
4110 * full quadracenturies (400-year periods) with their extra leap days, plus
4111 * the contribution from full centuries (to avoid counting in the lost leap
4112 * days), plus the contribution from full quad-years (to count in the normal
4113 * leap days), plus the leftover contribution from any non-leap years.
4114 * At this point, if we were working with an actual leap day, we'll have 0
4115 * days left over. This is also true for March 1st, however. So, we have
4116 * to special-case that result, and (earlier) keep track of the 'odd'
4117 * century and year contributions. If we got 4 extra centuries in a qcent,
4118 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4119 * Otherwise, we add back in the earlier bias we removed (the 123 from
4120 * figuring in March 1st), find the month index (integer division by 30.6),
4121 * and the remainder is the day-of-month. We then have to convert back to
4122 * 'real' months (including fixing January and February from being 14/15 in
4123 * the previous year to being in the proper year). After that, to get
4124 * tm_yday, we work with the normalised year and get a new yearday value for
4125 * January 1st, which we subtract from the yearday value we had earlier,
4126 * representing the date we've re-built. This is done from January 1
4127 * because tm_yday is 0-origin.
4129 * Since POSIX time routines are only guaranteed to work for times since the
4130 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4131 * applies Gregorian calendar rules even to dates before the 16th century
4132 * doesn't bother me. Besides, you'd need cultural context for a given
4133 * date to know whether it was Julian or Gregorian calendar, and that's
4134 * outside the scope for this routine. Since we convert back based on the
4135 * same rules we used to build the yearday, you'll only get strange results
4136 * for input which needed normalising, or for the 'odd' century years which
4137 * were leap years in the Julian calander but not in the Gregorian one.
4138 * I can live with that.
4140 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4141 * that's still outside the scope for POSIX time manipulation, so I don't
4145 year = 1900 + ptm->tm_year;
4146 month = ptm->tm_mon;
4147 mday = ptm->tm_mday;
4148 /* allow given yday with no month & mday to dominate the result */
4149 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4152 jday = 1 + ptm->tm_yday;
4161 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4162 yearday += month*MONTH_TO_DAYS + mday + jday;
4164 * Note that we don't know when leap-seconds were or will be,
4165 * so we have to trust the user if we get something which looks
4166 * like a sensible leap-second. Wild values for seconds will
4167 * be rationalised, however.
4169 if ((unsigned) ptm->tm_sec <= 60) {
4176 secs += 60 * ptm->tm_min;
4177 secs += SECS_PER_HOUR * ptm->tm_hour;
4179 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4180 /* got negative remainder, but need positive time */
4181 /* back off an extra day to compensate */
4182 yearday += (secs/SECS_PER_DAY)-1;
4183 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4186 yearday += (secs/SECS_PER_DAY);
4187 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4190 else if (secs >= SECS_PER_DAY) {
4191 yearday += (secs/SECS_PER_DAY);
4192 secs %= SECS_PER_DAY;
4194 ptm->tm_hour = secs/SECS_PER_HOUR;
4195 secs %= SECS_PER_HOUR;
4196 ptm->tm_min = secs/60;
4198 ptm->tm_sec += secs;
4199 /* done with time of day effects */
4201 * The algorithm for yearday has (so far) left it high by 428.
4202 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4203 * bias it by 123 while trying to figure out what year it
4204 * really represents. Even with this tweak, the reverse
4205 * translation fails for years before A.D. 0001.
4206 * It would still fail for Feb 29, but we catch that one below.
4208 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4209 yearday -= YEAR_ADJUST;
4210 year = (yearday / DAYS_PER_QCENT) * 400;
4211 yearday %= DAYS_PER_QCENT;
4212 odd_cent = yearday / DAYS_PER_CENT;
4213 year += odd_cent * 100;
4214 yearday %= DAYS_PER_CENT;
4215 year += (yearday / DAYS_PER_QYEAR) * 4;
4216 yearday %= DAYS_PER_QYEAR;
4217 odd_year = yearday / DAYS_PER_YEAR;
4219 yearday %= DAYS_PER_YEAR;
4220 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4225 yearday += YEAR_ADJUST; /* recover March 1st crock */
4226 month = yearday*DAYS_TO_MONTH;
4227 yearday -= month*MONTH_TO_DAYS;
4228 /* recover other leap-year adjustment */
4237 ptm->tm_year = year - 1900;
4239 ptm->tm_mday = yearday;
4240 ptm->tm_mon = month;
4244 ptm->tm_mon = month - 1;
4246 /* re-build yearday based on Jan 1 to get tm_yday */
4248 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4249 yearday += 14*MONTH_TO_DAYS + 1;
4250 ptm->tm_yday = jday - yearday;
4251 /* fix tm_wday if not overridden by caller */
4252 if ((unsigned)ptm->tm_wday > 6)
4253 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4257 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)
4265 PERL_ARGS_ASSERT_MY_STRFTIME;
4267 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4270 mytm.tm_hour = hour;
4271 mytm.tm_mday = mday;
4273 mytm.tm_year = year;
4274 mytm.tm_wday = wday;
4275 mytm.tm_yday = yday;
4276 mytm.tm_isdst = isdst;
4278 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4279 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4284 #ifdef HAS_TM_TM_GMTOFF
4285 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4287 #ifdef HAS_TM_TM_ZONE
4288 mytm.tm_zone = mytm2.tm_zone;
4293 Newx(buf, buflen, char);
4294 len = strftime(buf, buflen, fmt, &mytm);
4296 ** The following is needed to handle to the situation where
4297 ** tmpbuf overflows. Basically we want to allocate a buffer
4298 ** and try repeatedly. The reason why it is so complicated
4299 ** is that getting a return value of 0 from strftime can indicate
4300 ** one of the following:
4301 ** 1. buffer overflowed,
4302 ** 2. illegal conversion specifier, or
4303 ** 3. the format string specifies nothing to be returned(not
4304 ** an error). This could be because format is an empty string
4305 ** or it specifies %p that yields an empty string in some locale.
4306 ** If there is a better way to make it portable, go ahead by
4309 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4312 /* Possibly buf overflowed - try again with a bigger buf */
4313 const int fmtlen = strlen(fmt);
4314 int bufsize = fmtlen + buflen;
4316 Renew(buf, bufsize, char);
4318 buflen = strftime(buf, bufsize, fmt, &mytm);
4319 if (buflen > 0 && buflen < bufsize)
4321 /* heuristic to prevent out-of-memory errors */
4322 if (bufsize > 100*fmtlen) {
4328 Renew(buf, bufsize, char);
4333 Perl_croak(aTHX_ "panic: no strftime");
4339 #define SV_CWD_RETURN_UNDEF \
4340 sv_setsv(sv, &PL_sv_undef); \
4343 #define SV_CWD_ISDOT(dp) \
4344 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4345 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4348 =head1 Miscellaneous Functions
4350 =for apidoc getcwd_sv
4352 Fill the sv with current working directory
4357 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4358 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4359 * getcwd(3) if available
4360 * Comments from the orignal:
4361 * This is a faster version of getcwd. It's also more dangerous
4362 * because you might chdir out of a directory that you can't chdir
4366 Perl_getcwd_sv(pTHX_ register SV *sv)
4370 #ifndef INCOMPLETE_TAINTS
4374 PERL_ARGS_ASSERT_GETCWD_SV;
4378 char buf[MAXPATHLEN];
4380 /* Some getcwd()s automatically allocate a buffer of the given
4381 * size from the heap if they are given a NULL buffer pointer.
4382 * The problem is that this behaviour is not portable. */
4383 if (getcwd(buf, sizeof(buf) - 1)) {
4388 sv_setsv(sv, &PL_sv_undef);
4396 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4400 SvUPGRADE(sv, SVt_PV);
4402 if (PerlLIO_lstat(".", &statbuf) < 0) {
4403 SV_CWD_RETURN_UNDEF;
4406 orig_cdev = statbuf.st_dev;
4407 orig_cino = statbuf.st_ino;
4417 if (PerlDir_chdir("..") < 0) {
4418 SV_CWD_RETURN_UNDEF;
4420 if (PerlLIO_stat(".", &statbuf) < 0) {
4421 SV_CWD_RETURN_UNDEF;
4424 cdev = statbuf.st_dev;
4425 cino = statbuf.st_ino;
4427 if (odev == cdev && oino == cino) {
4430 if (!(dir = PerlDir_open("."))) {
4431 SV_CWD_RETURN_UNDEF;
4434 while ((dp = PerlDir_read(dir)) != NULL) {
4436 namelen = dp->d_namlen;
4438 namelen = strlen(dp->d_name);
4441 if (SV_CWD_ISDOT(dp)) {
4445 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4446 SV_CWD_RETURN_UNDEF;
4449 tdev = statbuf.st_dev;
4450 tino = statbuf.st_ino;
4451 if (tino == oino && tdev == odev) {
4457 SV_CWD_RETURN_UNDEF;
4460 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4461 SV_CWD_RETURN_UNDEF;
4464 SvGROW(sv, pathlen + namelen + 1);
4468 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4471 /* prepend current directory to the front */
4473 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4474 pathlen += (namelen + 1);
4476 #ifdef VOID_CLOSEDIR
4479 if (PerlDir_close(dir) < 0) {
4480 SV_CWD_RETURN_UNDEF;
4486 SvCUR_set(sv, pathlen);
4490 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4491 SV_CWD_RETURN_UNDEF;
4494 if (PerlLIO_stat(".", &statbuf) < 0) {
4495 SV_CWD_RETURN_UNDEF;
4498 cdev = statbuf.st_dev;
4499 cino = statbuf.st_ino;
4501 if (cdev != orig_cdev || cino != orig_cino) {
4502 Perl_croak(aTHX_ "Unstable directory path, "
4503 "current directory changed unexpectedly");
4514 #define VERSION_MAX 0x7FFFFFFF
4517 =for apidoc prescan_version
4522 Perl_prescan_version(pTHX_ const char *s, bool strict,
4523 const char **errstr,
4524 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4525 bool qv = (sqv ? *sqv : FALSE);
4527 int saw_decimal = 0;
4531 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4533 if (qv && isDIGIT(*d))
4534 goto dotted_decimal_version;
4536 if (*d == 'v') { /* explicit v-string */
4541 else { /* degenerate v-string */
4542 /* requires v1.2.3 */
4543 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4546 dotted_decimal_version:
4547 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4548 /* no leading zeros allowed */
4549 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4552 while (isDIGIT(*d)) /* integer part */
4558 d++; /* decimal point */
4563 /* require v1.2.3 */
4564 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4567 goto version_prescan_finish;
4574 while (isDIGIT(*d)) { /* just keep reading */
4576 while (isDIGIT(*d)) {
4578 /* maximum 3 digits between decimal */
4579 if (strict && j > 3) {
4580 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4585 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4588 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4593 else if (*d == '.') {
4595 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4600 else if (!isDIGIT(*d)) {
4606 if (strict && i < 2) {
4607 /* requires v1.2.3 */
4608 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4611 } /* end if dotted-decimal */
4613 { /* decimal versions */
4614 /* special strict case for leading '.' or '0' */
4617 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4619 if (*d == '0' && isDIGIT(d[1])) {
4620 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4624 /* consume all of the integer part */
4628 /* look for a fractional part */
4630 /* we found it, so consume it */
4634 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4637 BADVERSION(s,errstr,"Invalid version format (version required)");
4639 /* found just an integer */
4640 goto version_prescan_finish;
4642 else if ( d == s ) {
4643 /* didn't find either integer or period */
4644 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4646 else if (*d == '_') {
4647 /* underscore can't come after integer part */
4649 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4651 else if (isDIGIT(d[1])) {
4652 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4655 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4659 /* anything else after integer part is just invalid data */
4660 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4663 /* scan the fractional part after the decimal point*/
4665 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4666 /* strict or lax-but-not-the-end */
4667 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4670 while (isDIGIT(*d)) {
4672 if (*d == '.' && isDIGIT(d[-1])) {
4674 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4677 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4679 d = (char *)s; /* start all over again */
4681 goto dotted_decimal_version;
4685 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4688 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4690 if ( ! isDIGIT(d[1]) ) {
4691 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4699 version_prescan_finish:
4703 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4704 /* trailing non-numeric data */
4705 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4713 *ssaw_decimal = saw_decimal;
4720 =for apidoc scan_version
4722 Returns a pointer to the next character after the parsed
4723 version string, as well as upgrading the passed in SV to
4726 Function must be called with an already existing SV like
4729 s = scan_version(s, SV *sv, bool qv);
4731 Performs some preprocessing to the string to ensure that
4732 it has the correct characteristics of a version. Flags the
4733 object if it contains an underscore (which denotes this
4734 is an alpha version). The boolean qv denotes that the version
4735 should be interpreted as if it had multiple decimals, even if
4742 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4747 const char *errstr = NULL;
4748 int saw_decimal = 0;
4752 AV * const av = newAV();
4753 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4755 PERL_ARGS_ASSERT_SCAN_VERSION;
4757 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4759 #ifndef NODEFAULT_SHAREKEYS
4760 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4763 while (isSPACE(*s)) /* leading whitespace is OK */
4766 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4768 /* "undef" is a special case and not an error */
4769 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4770 Perl_croak(aTHX_ "%s", errstr);
4780 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4782 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4783 if ( !qv && width < 3 )
4784 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4786 while (isDIGIT(*pos))
4788 if (!isALPHA(*pos)) {
4794 /* this is atoi() that delimits on underscores */
4795 const char *end = pos;
4799 /* the following if() will only be true after the decimal
4800 * point of a version originally created with a bare
4801 * floating point number, i.e. not quoted in any way
4803 if ( !qv && s > start && saw_decimal == 1 ) {
4807 rev += (*s - '0') * mult;
4809 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4810 || (PERL_ABS(rev) > VERSION_MAX )) {
4811 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4812 "Integer overflow in version %d",VERSION_MAX);
4823 while (--end >= s) {
4825 rev += (*end - '0') * mult;
4827 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4828 || (PERL_ABS(rev) > VERSION_MAX )) {
4829 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4830 "Integer overflow in version");
4839 /* Append revision */
4840 av_push(av, newSViv(rev));
4845 else if ( *pos == '.' )
4847 else if ( *pos == '_' && isDIGIT(pos[1]) )
4849 else if ( *pos == ',' && isDIGIT(pos[1]) )
4851 else if ( isDIGIT(*pos) )
4858 while ( isDIGIT(*pos) )
4863 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4871 if ( qv ) { /* quoted versions always get at least three terms*/
4872 I32 len = av_len(av);
4873 /* This for loop appears to trigger a compiler bug on OS X, as it
4874 loops infinitely. Yes, len is negative. No, it makes no sense.
4875 Compiler in question is:
4876 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4877 for ( len = 2 - len; len > 0; len-- )
4878 av_push(MUTABLE_AV(sv), newSViv(0));
4882 av_push(av, newSViv(0));
4885 /* need to save off the current version string for later */
4887 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4888 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4889 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4891 else if ( s > start ) {
4892 SV * orig = newSVpvn(start,s-start);
4893 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4894 /* need to insert a v to be consistent */
4895 sv_insert(orig, 0, 0, "v", 1);
4897 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4900 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4901 av_push(av, newSViv(0));
4904 /* And finally, store the AV in the hash */
4905 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4907 /* fix RT#19517 - special case 'undef' as string */
4908 if ( *s == 'u' && strEQ(s,"undef") ) {
4916 =for apidoc new_version
4918 Returns a new version object based on the passed in SV:
4920 SV *sv = new_version(SV *ver);
4922 Does not alter the passed in ver SV. See "upg_version" if you
4923 want to upgrade the SV.
4929 Perl_new_version(pTHX_ SV *ver)
4932 SV * const rv = newSV(0);
4933 PERL_ARGS_ASSERT_NEW_VERSION;
4934 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4937 AV * const av = newAV();
4939 /* This will get reblessed later if a derived class*/
4940 SV * const hv = newSVrv(rv, "version");
4941 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4942 #ifndef NODEFAULT_SHAREKEYS
4943 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4949 /* Begin copying all of the elements */
4950 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4951 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4953 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4954 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4956 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4958 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4959 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4962 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4964 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4965 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4968 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4969 /* This will get reblessed later if a derived class*/
4970 for ( key = 0; key <= av_len(sav); key++ )
4972 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4973 av_push(av, newSViv(rev));
4976 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4981 const MAGIC* const mg = SvVSTRING_mg(ver);
4982 if ( mg ) { /* already a v-string */
4983 const STRLEN len = mg->mg_len;
4984 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4985 sv_setpvn(rv,version,len);
4986 /* this is for consistency with the pure Perl class */
4987 if ( isDIGIT(*version) )
4988 sv_insert(rv, 0, 0, "v", 1);
4993 sv_setsv(rv,ver); /* make a duplicate */
4998 return upg_version(rv, FALSE);
5002 =for apidoc upg_version
5004 In-place upgrade of the supplied SV to a version object.
5006 SV *sv = upg_version(SV *sv, bool qv);
5008 Returns a pointer to the upgraded SV. Set the boolean qv if you want
5009 to force this SV to be interpreted as an "extended" version.
5015 Perl_upg_version(pTHX_ SV *ver, bool qv)
5017 const char *version, *s;
5022 PERL_ARGS_ASSERT_UPG_VERSION;
5024 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
5026 /* may get too much accuracy */
5028 #ifdef USE_LOCALE_NUMERIC
5029 char *loc = setlocale(LC_NUMERIC, "C");
5031 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
5032 #ifdef USE_LOCALE_NUMERIC
5033 setlocale(LC_NUMERIC, loc);
5035 while (tbuf[len-1] == '0' && len > 0) len--;
5036 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
5037 version = savepvn(tbuf, len);
5040 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
5041 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
5045 else /* must be a string or something like a string */
5048 version = savepv(SvPV(ver,len));
5050 # if PERL_VERSION > 5
5051 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
5052 if ( len >= 3 && !instr(version,".") && !instr(version,"_")
5053 && !(*version == 'u' && strEQ(version, "undef"))
5054 && (*version < '0' || *version > '9') ) {
5055 /* may be a v-string */
5056 SV * const nsv = sv_newmortal();
5059 int saw_decimal = 0;
5060 sv_setpvf(nsv,"v%vd",ver);
5061 pos = nver = savepv(SvPV_nolen(nsv));
5063 /* scan the resulting formatted string */
5064 pos++; /* skip the leading 'v' */
5065 while ( *pos == '.' || isDIGIT(*pos) ) {
5071 /* is definitely a v-string */
5072 if ( saw_decimal >= 2 ) {
5081 s = scan_version(version, ver, qv);
5083 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5084 "Version string '%s' contains invalid data; "
5085 "ignoring: '%s'", version, s);
5093 Validates that the SV contains a valid version object.
5095 bool vverify(SV *vobj);
5097 Note that it only confirms the bare minimum structure (so as not to get
5098 confused by derived classes which may contain additional hash entries):
5102 =item * The SV contains a [reference to a] hash
5104 =item * The hash contains a "version" key
5106 =item * The "version" key has [a reference to] an AV as its value
5114 Perl_vverify(pTHX_ SV *vs)
5118 PERL_ARGS_ASSERT_VVERIFY;
5123 /* see if the appropriate elements exist */
5124 if ( SvTYPE(vs) == SVt_PVHV
5125 && hv_exists(MUTABLE_HV(vs), "version", 7)
5126 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5127 && SvTYPE(sv) == SVt_PVAV )
5136 Accepts a version object and returns the normalized floating
5137 point representation. Call like:
5141 NOTE: you can pass either the object directly or the SV
5142 contained within the RV.
5148 Perl_vnumify(pTHX_ SV *vs)
5156 PERL_ARGS_ASSERT_VNUMIFY;
5162 Perl_croak(aTHX_ "Invalid version object");
5164 /* see if various flags exist */
5165 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5167 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5168 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5173 /* attempt to retrieve the version array */
5174 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5175 return newSVpvs("0");
5181 return newSVpvs("0");
5184 digit = SvIV(*av_fetch(av, 0, 0));
5185 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5186 for ( i = 1 ; i < len ; i++ )
5188 digit = SvIV(*av_fetch(av, i, 0));
5190 const int denom = (width == 2 ? 10 : 100);
5191 const div_t term = div((int)PERL_ABS(digit),denom);
5192 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5195 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5201 digit = SvIV(*av_fetch(av, len, 0));
5202 if ( alpha && width == 3 ) /* alpha version */
5204 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5208 sv_catpvs(sv, "000");
5216 Accepts a version object and returns the normalized string
5217 representation. Call like:
5221 NOTE: you can pass either the object directly or the SV
5222 contained within the RV.
5228 Perl_vnormal(pTHX_ SV *vs)
5235 PERL_ARGS_ASSERT_VNORMAL;
5241 Perl_croak(aTHX_ "Invalid version object");
5243 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5245 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5250 return newSVpvs("");
5252 digit = SvIV(*av_fetch(av, 0, 0));
5253 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5254 for ( i = 1 ; i < len ; i++ ) {
5255 digit = SvIV(*av_fetch(av, i, 0));
5256 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5261 /* handle last digit specially */
5262 digit = SvIV(*av_fetch(av, len, 0));
5264 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5266 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5269 if ( len <= 2 ) { /* short version, must be at least three */
5270 for ( len = 2 - len; len != 0; len-- )
5277 =for apidoc vstringify
5279 In order to maintain maximum compatibility with earlier versions
5280 of Perl, this function will return either the floating point
5281 notation or the multiple dotted notation, depending on whether
5282 the original version contained 1 or more dots, respectively
5288 Perl_vstringify(pTHX_ SV *vs)
5290 PERL_ARGS_ASSERT_VSTRINGIFY;
5296 Perl_croak(aTHX_ "Invalid version object");
5298 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5300 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5304 return &PL_sv_undef;
5307 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5317 Version object aware cmp. Both operands must already have been
5318 converted into version objects.
5324 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5327 bool lalpha = FALSE;
5328 bool ralpha = FALSE;
5333 PERL_ARGS_ASSERT_VCMP;
5340 if ( !vverify(lhv) )
5341 Perl_croak(aTHX_ "Invalid version object");
5343 if ( !vverify(rhv) )
5344 Perl_croak(aTHX_ "Invalid version object");
5346 /* get the left hand term */
5347 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5348 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5351 /* and the right hand term */
5352 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5353 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5361 while ( i <= m && retval == 0 )
5363 left = SvIV(*av_fetch(lav,i,0));
5364 right = SvIV(*av_fetch(rav,i,0));
5372 /* tiebreaker for alpha with identical terms */
5373 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5375 if ( lalpha && !ralpha )
5379 else if ( ralpha && !lalpha)
5385 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5389 while ( i <= r && retval == 0 )
5391 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5392 retval = -1; /* not a match after all */
5398 while ( i <= l && retval == 0 )
5400 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5401 retval = +1; /* not a match after all */
5409 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5410 # define EMULATE_SOCKETPAIR_UDP
5413 #ifdef EMULATE_SOCKETPAIR_UDP
5415 S_socketpair_udp (int fd[2]) {
5417 /* Fake a datagram socketpair using UDP to localhost. */
5418 int sockets[2] = {-1, -1};
5419 struct sockaddr_in addresses[2];
5421 Sock_size_t size = sizeof(struct sockaddr_in);
5422 unsigned short port;
5425 memset(&addresses, 0, sizeof(addresses));
5428 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5429 if (sockets[i] == -1)
5430 goto tidy_up_and_fail;
5432 addresses[i].sin_family = AF_INET;
5433 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5434 addresses[i].sin_port = 0; /* kernel choses port. */
5435 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5436 sizeof(struct sockaddr_in)) == -1)
5437 goto tidy_up_and_fail;
5440 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5441 for each connect the other socket to it. */
5444 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5446 goto tidy_up_and_fail;
5447 if (size != sizeof(struct sockaddr_in))
5448 goto abort_tidy_up_and_fail;
5449 /* !1 is 0, !0 is 1 */
5450 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5451 sizeof(struct sockaddr_in)) == -1)
5452 goto tidy_up_and_fail;
5455 /* Now we have 2 sockets connected to each other. I don't trust some other
5456 process not to have already sent a packet to us (by random) so send
5457 a packet from each to the other. */
5460 /* I'm going to send my own port number. As a short.
5461 (Who knows if someone somewhere has sin_port as a bitfield and needs
5462 this routine. (I'm assuming crays have socketpair)) */
5463 port = addresses[i].sin_port;
5464 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5465 if (got != sizeof(port)) {
5467 goto tidy_up_and_fail;
5468 goto abort_tidy_up_and_fail;
5472 /* Packets sent. I don't trust them to have arrived though.
5473 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5474 connect to localhost will use a second kernel thread. In 2.6 the
5475 first thread running the connect() returns before the second completes,
5476 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5477 returns 0. Poor programs have tripped up. One poor program's authors'
5478 had a 50-1 reverse stock split. Not sure how connected these were.)
5479 So I don't trust someone not to have an unpredictable UDP stack.
5483 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5484 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5488 FD_SET((unsigned int)sockets[0], &rset);
5489 FD_SET((unsigned int)sockets[1], &rset);
5491 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5492 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5493 || !FD_ISSET(sockets[1], &rset)) {
5494 /* I hope this is portable and appropriate. */
5496 goto tidy_up_and_fail;
5497 goto abort_tidy_up_and_fail;
5501 /* And the paranoia department even now doesn't trust it to have arrive
5502 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5504 struct sockaddr_in readfrom;
5505 unsigned short buffer[2];
5510 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5511 sizeof(buffer), MSG_DONTWAIT,
5512 (struct sockaddr *) &readfrom, &size);
5514 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5516 (struct sockaddr *) &readfrom, &size);
5520 goto tidy_up_and_fail;
5521 if (got != sizeof(port)
5522 || size != sizeof(struct sockaddr_in)
5523 /* Check other socket sent us its port. */
5524 || buffer[0] != (unsigned short) addresses[!i].sin_port
5525 /* Check kernel says we got the datagram from that socket */
5526 || readfrom.sin_family != addresses[!i].sin_family
5527 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5528 || readfrom.sin_port != addresses[!i].sin_port)
5529 goto abort_tidy_up_and_fail;
5532 /* My caller (my_socketpair) has validated that this is non-NULL */
5535 /* I hereby declare this connection open. May God bless all who cross
5539 abort_tidy_up_and_fail:
5540 errno = ECONNABORTED;
5544 if (sockets[0] != -1)
5545 PerlLIO_close(sockets[0]);
5546 if (sockets[1] != -1)
5547 PerlLIO_close(sockets[1]);
5552 #endif /* EMULATE_SOCKETPAIR_UDP */
5554 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5556 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5557 /* Stevens says that family must be AF_LOCAL, protocol 0.
5558 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5563 struct sockaddr_in listen_addr;
5564 struct sockaddr_in connect_addr;
5569 || family != AF_UNIX
5572 errno = EAFNOSUPPORT;
5580 #ifdef EMULATE_SOCKETPAIR_UDP
5581 if (type == SOCK_DGRAM)
5582 return S_socketpair_udp(fd);
5585 listener = PerlSock_socket(AF_INET, type, 0);
5588 memset(&listen_addr, 0, sizeof(listen_addr));
5589 listen_addr.sin_family = AF_INET;
5590 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5591 listen_addr.sin_port = 0; /* kernel choses port. */
5592 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5593 sizeof(listen_addr)) == -1)
5594 goto tidy_up_and_fail;
5595 if (PerlSock_listen(listener, 1) == -1)
5596 goto tidy_up_and_fail;
5598 connector = PerlSock_socket(AF_INET, type, 0);
5599 if (connector == -1)
5600 goto tidy_up_and_fail;
5601 /* We want to find out the port number to connect to. */
5602 size = sizeof(connect_addr);
5603 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5605 goto tidy_up_and_fail;
5606 if (size != sizeof(connect_addr))
5607 goto abort_tidy_up_and_fail;
5608 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5609 sizeof(connect_addr)) == -1)
5610 goto tidy_up_and_fail;
5612 size = sizeof(listen_addr);
5613 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5616 goto tidy_up_and_fail;
5617 if (size != sizeof(listen_addr))
5618 goto abort_tidy_up_and_fail;
5619 PerlLIO_close(listener);
5620 /* Now check we are talking to ourself by matching port and host on the
5622 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5624 goto tidy_up_and_fail;
5625 if (size != sizeof(connect_addr)
5626 || listen_addr.sin_family != connect_addr.sin_family
5627 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5628 || listen_addr.sin_port != connect_addr.sin_port) {
5629 goto abort_tidy_up_and_fail;
5635 abort_tidy_up_and_fail:
5637 errno = ECONNABORTED; /* This would be the standard thing to do. */
5639 # ifdef ECONNREFUSED
5640 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5642 errno = ETIMEDOUT; /* Desperation time. */
5649 PerlLIO_close(listener);
5650 if (connector != -1)
5651 PerlLIO_close(connector);
5653 PerlLIO_close(acceptor);
5659 /* In any case have a stub so that there's code corresponding
5660 * to the my_socketpair in global.sym. */
5662 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5663 #ifdef HAS_SOCKETPAIR
5664 return socketpair(family, type, protocol, fd);
5673 =for apidoc sv_nosharing
5675 Dummy routine which "shares" an SV when there is no sharing module present.
5676 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5677 Exists to avoid test for a NULL function pointer and because it could
5678 potentially warn under some level of strict-ness.
5684 Perl_sv_nosharing(pTHX_ SV *sv)
5686 PERL_UNUSED_CONTEXT;
5687 PERL_UNUSED_ARG(sv);
5692 =for apidoc sv_destroyable
5694 Dummy routine which reports that object can be destroyed when there is no
5695 sharing module present. It ignores its single SV argument, and returns
5696 'true'. Exists to avoid test for a NULL function pointer and because it
5697 could potentially warn under some level of strict-ness.
5703 Perl_sv_destroyable(pTHX_ SV *sv)
5705 PERL_UNUSED_CONTEXT;
5706 PERL_UNUSED_ARG(sv);
5711 Perl_parse_unicode_opts(pTHX_ const char **popt)
5713 const char *p = *popt;
5716 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5720 opt = (U32) atoi(p);
5723 if (*p && *p != '\n' && *p != '\r')
5724 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5729 case PERL_UNICODE_STDIN:
5730 opt |= PERL_UNICODE_STDIN_FLAG; break;
5731 case PERL_UNICODE_STDOUT:
5732 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5733 case PERL_UNICODE_STDERR:
5734 opt |= PERL_UNICODE_STDERR_FLAG; break;
5735 case PERL_UNICODE_STD:
5736 opt |= PERL_UNICODE_STD_FLAG; break;
5737 case PERL_UNICODE_IN:
5738 opt |= PERL_UNICODE_IN_FLAG; break;
5739 case PERL_UNICODE_OUT:
5740 opt |= PERL_UNICODE_OUT_FLAG; break;
5741 case PERL_UNICODE_INOUT:
5742 opt |= PERL_UNICODE_INOUT_FLAG; break;
5743 case PERL_UNICODE_LOCALE:
5744 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5745 case PERL_UNICODE_ARGV:
5746 opt |= PERL_UNICODE_ARGV_FLAG; break;
5747 case PERL_UNICODE_UTF8CACHEASSERT:
5748 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5750 if (*p != '\n' && *p != '\r')
5752 "Unknown Unicode option letter '%c'", *p);
5758 opt = PERL_UNICODE_DEFAULT_FLAGS;
5760 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5761 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5762 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5774 * This is really just a quick hack which grabs various garbage
5775 * values. It really should be a real hash algorithm which
5776 * spreads the effect of every input bit onto every output bit,
5777 * if someone who knows about such things would bother to write it.
5778 * Might be a good idea to add that function to CORE as well.
5779 * No numbers below come from careful analysis or anything here,
5780 * except they are primes and SEED_C1 > 1E6 to get a full-width
5781 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5782 * probably be bigger too.
5785 # define SEED_C1 1000003
5786 #define SEED_C4 73819
5788 # define SEED_C1 25747
5789 #define SEED_C4 20639
5793 #define SEED_C5 26107
5795 #ifndef PERL_NO_DEV_RANDOM
5800 # include <starlet.h>
5801 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5802 * in 100-ns units, typically incremented ever 10 ms. */
5803 unsigned int when[2];
5805 # ifdef HAS_GETTIMEOFDAY
5806 struct timeval when;
5812 /* This test is an escape hatch, this symbol isn't set by Configure. */
5813 #ifndef PERL_NO_DEV_RANDOM
5814 #ifndef PERL_RANDOM_DEVICE
5815 /* /dev/random isn't used by default because reads from it will block
5816 * if there isn't enough entropy available. You can compile with
5817 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5818 * is enough real entropy to fill the seed. */
5819 # define PERL_RANDOM_DEVICE "/dev/urandom"
5821 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5823 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5832 _ckvmssts(sys$gettim(when));
5833 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5835 # ifdef HAS_GETTIMEOFDAY
5836 PerlProc_gettimeofday(&when,NULL);
5837 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5840 u = (U32)SEED_C1 * when;
5843 u += SEED_C3 * (U32)PerlProc_getpid();
5844 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5845 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5846 u += SEED_C5 * (U32)PTR2UV(&when);
5852 Perl_get_hash_seed(pTHX)
5855 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5861 if (s && isDIGIT(*s))
5862 myseed = (UV)Atoul(s);
5864 #ifdef USE_HASH_SEED_EXPLICIT
5868 /* Compute a random seed */
5869 (void)seedDrand01((Rand_seed_t)seed());
5870 myseed = (UV)(Drand01() * (NV)UV_MAX);
5871 #if RANDBITS < (UVSIZE * 8)
5872 /* Since there are not enough randbits to to reach all
5873 * the bits of a UV, the low bits might need extra
5874 * help. Sum in another random number that will
5875 * fill in the low bits. */
5877 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5878 #endif /* RANDBITS < (UVSIZE * 8) */
5879 if (myseed == 0) { /* Superparanoia. */
5880 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5882 Perl_croak(aTHX_ "Your random numbers are not that random");
5885 PL_rehash_seed_set = TRUE;
5892 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5894 const char * const stashpv = CopSTASHPV(c);
5895 const char * const name = HvNAME_get(hv);
5896 PERL_UNUSED_CONTEXT;
5897 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5899 if (stashpv == name)
5901 if (stashpv && name)
5902 if (strEQ(stashpv, name))
5909 #ifdef PERL_GLOBAL_STRUCT
5911 #define PERL_GLOBAL_STRUCT_INIT
5912 #include "opcode.h" /* the ppaddr and check */
5915 Perl_init_global_struct(pTHX)
5917 struct perl_vars *plvarsp = NULL;
5918 # ifdef PERL_GLOBAL_STRUCT
5919 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5920 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5921 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5922 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5923 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5927 plvarsp = PL_VarsPtr;
5928 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5934 # define PERLVAR(var,type) /**/
5935 # define PERLVARA(var,n,type) /**/
5936 # define PERLVARI(var,type,init) plvarsp->var = init;
5937 # define PERLVARIC(var,type,init) plvarsp->var = init;
5938 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5939 # include "perlvars.h"
5945 # ifdef PERL_GLOBAL_STRUCT
5948 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5949 if (!plvarsp->Gppaddr)
5953 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5954 if (!plvarsp->Gcheck)
5956 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5957 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5959 # ifdef PERL_SET_VARS
5960 PERL_SET_VARS(plvarsp);
5962 # undef PERL_GLOBAL_STRUCT_INIT
5967 #endif /* PERL_GLOBAL_STRUCT */
5969 #ifdef PERL_GLOBAL_STRUCT
5972 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5974 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5975 # ifdef PERL_GLOBAL_STRUCT
5976 # ifdef PERL_UNSET_VARS
5977 PERL_UNSET_VARS(plvarsp);
5979 free(plvarsp->Gppaddr);
5980 free(plvarsp->Gcheck);
5981 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5987 #endif /* PERL_GLOBAL_STRUCT */
5991 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5992 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5993 * given, and you supply your own implementation.
5995 * The default implementation reads a single env var, PERL_MEM_LOG,
5996 * expecting one or more of the following:
5998 * \d+ - fd fd to write to : must be 1st (atoi)
5999 * 'm' - memlog was PERL_MEM_LOG=1
6000 * 's' - svlog was PERL_SV_LOG=1
6001 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
6003 * This makes the logger controllable enough that it can reasonably be
6004 * added to the system perl.
6007 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
6008 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
6010 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
6012 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
6013 * writes to. In the default logger, this is settable at runtime.
6015 #ifndef PERL_MEM_LOG_FD
6016 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
6019 #ifndef PERL_MEM_LOG_NOIMPL
6021 # ifdef DEBUG_LEAKING_SCALARS
6022 # define SV_LOG_SERIAL_FMT " [%lu]"
6023 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
6025 # define SV_LOG_SERIAL_FMT
6026 # define _SV_LOG_SERIAL_ARG(sv)
6030 S_mem_log_common(enum mem_log_type mlt, const UV n,
6031 const UV typesize, const char *type_name, const SV *sv,
6032 Malloc_t oldalloc, Malloc_t newalloc,
6033 const char *filename, const int linenumber,
6034 const char *funcname)
6038 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
6040 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
6043 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
6045 /* We can't use SVs or PerlIO for obvious reasons,
6046 * so we'll use stdio and low-level IO instead. */
6047 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
6049 # ifdef HAS_GETTIMEOFDAY
6050 # define MEM_LOG_TIME_FMT "%10d.%06d: "
6051 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
6053 gettimeofday(&tv, 0);
6055 # define MEM_LOG_TIME_FMT "%10d: "
6056 # define MEM_LOG_TIME_ARG (int)when
6060 /* If there are other OS specific ways of hires time than
6061 * gettimeofday() (see ext/Time-HiRes), the easiest way is
6062 * probably that they would be used to fill in the struct
6066 int fd = atoi(pmlenv);
6068 fd = PERL_MEM_LOG_FD;
6070 if (strchr(pmlenv, 't')) {
6071 len = my_snprintf(buf, sizeof(buf),
6072 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6073 PerlLIO_write(fd, buf, len);
6077 len = my_snprintf(buf, sizeof(buf),
6078 "alloc: %s:%d:%s: %"IVdf" %"UVuf
6079 " %s = %"IVdf": %"UVxf"\n",
6080 filename, linenumber, funcname, n, typesize,
6081 type_name, n * typesize, PTR2UV(newalloc));
6084 len = my_snprintf(buf, sizeof(buf),
6085 "realloc: %s:%d:%s: %"IVdf" %"UVuf
6086 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6087 filename, linenumber, funcname, n, typesize,
6088 type_name, n * typesize, PTR2UV(oldalloc),
6092 len = my_snprintf(buf, sizeof(buf),
6093 "free: %s:%d:%s: %"UVxf"\n",
6094 filename, linenumber, funcname,
6099 len = my_snprintf(buf, sizeof(buf),
6100 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6101 mlt == MLT_NEW_SV ? "new" : "del",
6102 filename, linenumber, funcname,
6103 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6108 PerlLIO_write(fd, buf, len);
6112 #endif /* !PERL_MEM_LOG_NOIMPL */
6114 #ifndef PERL_MEM_LOG_NOIMPL
6116 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6117 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6119 /* this is suboptimal, but bug compatible. User is providing their
6120 own implemenation, but is getting these functions anyway, and they
6121 do nothing. But _NOIMPL users should be able to cope or fix */
6123 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6124 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
6128 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6130 const char *filename, const int linenumber,
6131 const char *funcname)
6133 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6134 NULL, NULL, newalloc,
6135 filename, linenumber, funcname);
6140 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6141 Malloc_t oldalloc, Malloc_t newalloc,
6142 const char *filename, const int linenumber,
6143 const char *funcname)
6145 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6146 NULL, oldalloc, newalloc,
6147 filename, linenumber, funcname);
6152 Perl_mem_log_free(Malloc_t oldalloc,
6153 const char *filename, const int linenumber,
6154 const char *funcname)
6156 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6157 filename, linenumber, funcname);
6162 Perl_mem_log_new_sv(const SV *sv,
6163 const char *filename, const int linenumber,
6164 const char *funcname)
6166 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6167 filename, linenumber, funcname);
6171 Perl_mem_log_del_sv(const SV *sv,
6172 const char *filename, const int linenumber,
6173 const char *funcname)
6175 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6176 filename, linenumber, funcname);
6179 #endif /* PERL_MEM_LOG */
6182 =for apidoc my_sprintf
6184 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6185 the length of the string written to the buffer. Only rare pre-ANSI systems
6186 need the wrapper function - usually this is a direct call to C<sprintf>.
6190 #ifndef SPRINTF_RETURNS_STRLEN
6192 Perl_my_sprintf(char *buffer, const char* pat, ...)
6195 PERL_ARGS_ASSERT_MY_SPRINTF;
6196 va_start(args, pat);
6197 vsprintf(buffer, pat, args);
6199 return strlen(buffer);
6204 =for apidoc my_snprintf
6206 The C library C<snprintf> functionality, if available and
6207 standards-compliant (uses C<vsnprintf>, actually). However, if the
6208 C<vsnprintf> is not available, will unfortunately use the unsafe
6209 C<vsprintf> which can overrun the buffer (there is an overrun check,
6210 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6211 getting C<vsnprintf>.
6216 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6221 PERL_ARGS_ASSERT_MY_SNPRINTF;
6222 va_start(ap, format);
6223 #ifdef HAS_VSNPRINTF
6224 retval = vsnprintf(buffer, len, format, ap);
6226 retval = vsprintf(buffer, format, ap);
6229 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
6230 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
6231 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6236 =for apidoc my_vsnprintf
6238 The C library C<vsnprintf> if available and standards-compliant.
6239 However, if if the C<vsnprintf> is not available, will unfortunately
6240 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6241 overrun check, but that may be too late). Consider using
6242 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6247 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6254 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6256 Perl_va_copy(ap, apc);
6257 # ifdef HAS_VSNPRINTF
6258 retval = vsnprintf(buffer, len, format, apc);
6260 retval = vsprintf(buffer, format, apc);
6263 # ifdef HAS_VSNPRINTF
6264 retval = vsnprintf(buffer, len, format, ap);
6266 retval = vsprintf(buffer, format, ap);
6268 #endif /* #ifdef NEED_VA_COPY */
6269 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
6270 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
6271 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6276 Perl_my_clearenv(pTHX)
6279 #if ! defined(PERL_MICRO)
6280 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6282 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6283 # if defined(USE_ENVIRON_ARRAY)
6284 # if defined(USE_ITHREADS)
6285 /* only the parent thread can clobber the process environment */
6286 if (PL_curinterp == aTHX)
6287 # endif /* USE_ITHREADS */
6289 # if ! defined(PERL_USE_SAFE_PUTENV)
6290 if ( !PL_use_safe_putenv) {
6292 if (environ == PL_origenviron)
6293 environ = (char**)safesysmalloc(sizeof(char*));
6295 for (i = 0; environ[i]; i++)
6296 (void)safesysfree(environ[i]);
6299 # else /* PERL_USE_SAFE_PUTENV */
6300 # if defined(HAS_CLEARENV)
6302 # elif defined(HAS_UNSETENV)
6303 int bsiz = 80; /* Most envvar names will be shorter than this. */
6304 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6305 char *buf = (char*)safesysmalloc(bufsiz);
6306 while (*environ != NULL) {
6307 char *e = strchr(*environ, '=');
6308 int l = e ? e - *environ : (int)strlen(*environ);
6310 (void)safesysfree(buf);
6311 bsiz = l + 1; /* + 1 for the \0. */
6312 buf = (char*)safesysmalloc(bufsiz);
6314 memcpy(buf, *environ, l);
6316 (void)unsetenv(buf);
6318 (void)safesysfree(buf);
6319 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6320 /* Just null environ and accept the leakage. */
6322 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6323 # endif /* ! PERL_USE_SAFE_PUTENV */
6325 # endif /* USE_ENVIRON_ARRAY */
6326 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6327 #endif /* PERL_MICRO */
6330 #ifdef PERL_IMPLICIT_CONTEXT
6332 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6333 the global PL_my_cxt_index is incremented, and that value is assigned to
6334 that module's static my_cxt_index (who's address is passed as an arg).
6335 Then, for each interpreter this function is called for, it makes sure a
6336 void* slot is available to hang the static data off, by allocating or
6337 extending the interpreter's PL_my_cxt_list array */
6339 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6341 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6345 PERL_ARGS_ASSERT_MY_CXT_INIT;
6347 /* this module hasn't been allocated an index yet */
6348 #if defined(USE_ITHREADS)
6349 MUTEX_LOCK(&PL_my_ctx_mutex);
6351 *index = PL_my_cxt_index++;
6352 #if defined(USE_ITHREADS)
6353 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6357 /* make sure the array is big enough */
6358 if (PL_my_cxt_size <= *index) {
6359 if (PL_my_cxt_size) {
6360 while (PL_my_cxt_size <= *index)
6361 PL_my_cxt_size *= 2;
6362 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6365 PL_my_cxt_size = 16;
6366 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6369 /* newSV() allocates one more than needed */
6370 p = (void*)SvPVX(newSV(size-1));
6371 PL_my_cxt_list[*index] = p;
6372 Zero(p, size, char);
6376 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6379 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6384 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6386 for (index = 0; index < PL_my_cxt_index; index++) {
6387 const char *key = PL_my_cxt_keys[index];
6388 /* try direct pointer compare first - there are chances to success,
6389 * and it's much faster.
6391 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6398 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6404 PERL_ARGS_ASSERT_MY_CXT_INIT;
6406 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6408 /* this module hasn't been allocated an index yet */
6409 #if defined(USE_ITHREADS)
6410 MUTEX_LOCK(&PL_my_ctx_mutex);
6412 index = PL_my_cxt_index++;
6413 #if defined(USE_ITHREADS)
6414 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6418 /* make sure the array is big enough */
6419 if (PL_my_cxt_size <= index) {
6420 int old_size = PL_my_cxt_size;
6422 if (PL_my_cxt_size) {
6423 while (PL_my_cxt_size <= index)
6424 PL_my_cxt_size *= 2;
6425 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6426 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6429 PL_my_cxt_size = 16;
6430 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6431 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6433 for (i = old_size; i < PL_my_cxt_size; i++) {
6434 PL_my_cxt_keys[i] = 0;
6435 PL_my_cxt_list[i] = 0;
6438 PL_my_cxt_keys[index] = my_cxt_key;
6439 /* newSV() allocates one more than needed */
6440 p = (void*)SvPVX(newSV(size-1));
6441 PL_my_cxt_list[index] = p;
6442 Zero(p, size, char);
6445 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6446 #endif /* PERL_IMPLICIT_CONTEXT */
6450 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6452 Size_t used, length, copy;
6455 length = strlen(src);
6456 if (size > 0 && used < size - 1) {
6457 copy = (length >= size - used) ? size - used - 1 : length;
6458 memcpy(dst + used, src, copy);
6459 dst[used + copy] = '\0';
6461 return used + length;
6467 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6469 Size_t length, copy;
6471 length = strlen(src);
6473 copy = (length >= size) ? size - 1 : length;
6474 memcpy(dst, src, copy);
6481 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6482 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6483 long _ftol( double ); /* Defined by VC6 C libs. */
6484 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6488 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6491 SV * const dbsv = GvSVn(PL_DBsub);
6492 const bool save_taint = PL_tainted;
6494 /* We do not care about using sv to call CV;
6495 * it's for informational purposes only.
6498 PERL_ARGS_ASSERT_GET_DB_SUB;
6502 if (!PERLDB_SUB_NN) {
6503 GV * const gv = CvGV(cv);
6505 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6506 || strEQ(GvNAME(gv), "END")
6507 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6508 !( (SvTYPE(*svp) == SVt_PVGV)
6509 && (GvCV((const GV *)*svp) == cv) )))) {
6510 /* Use GV from the stack as a fallback. */
6511 /* GV is potentially non-unique, or contain different CV. */
6512 SV * const tmp = newRV(MUTABLE_SV(cv));
6513 sv_setsv(dbsv, tmp);
6517 gv_efullname3(dbsv, gv, NULL);
6521 const int type = SvTYPE(dbsv);
6522 if (type < SVt_PVIV && type != SVt_IV)
6523 sv_upgrade(dbsv, SVt_PVIV);
6524 (void)SvIOK_on(dbsv);
6525 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6527 TAINT_IF(save_taint);
6531 Perl_my_dirfd(pTHX_ DIR * dir) {
6533 /* Most dirfd implementations have problems when passed NULL. */
6538 #elif defined(HAS_DIR_DD_FD)
6541 Perl_die(aTHX_ PL_no_func, "dirfd");
6548 Perl_get_re_arg(pTHX_ SV *sv) {
6554 sv = MUTABLE_SV(SvRV(sv));
6555 if (SvTYPE(sv) == SVt_REGEXP)
6556 return (REGEXP*) sv;
6564 * c-indentation-style: bsd
6566 * indent-tabs-mode: t
6569 * ex: set ts=8 sts=4 sw=4 noet: