3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 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
16 /* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
23 #define PERL_IN_UTIL_C
29 # define SIG_ERR ((Sighandler_t) -1)
34 /* Missing protos on LynxOS */
39 # include <sys/wait.h>
44 # include <sys/select.h>
50 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51 # define FD_CLOEXEC 1 /* NeXT needs this */
54 /* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
64 /* Can't use PerlIO to write as it allocates memory */
65 PerlLIO_write(PerlIO_fileno(Perl_error_log),
66 PL_no_mem, strlen(PL_no_mem));
68 NORETURN_FUNCTION_END;
71 /* paranoid version of system's malloc() */
74 Perl_safesysmalloc(MEM_SIZE size)
80 PerlIO_printf(Perl_error_log,
81 "Allocation too large: %lx\n", size) FLUSH;
84 #endif /* HAS_64K_LIMIT */
85 #ifdef PERL_TRACK_MEMPOOL
90 Perl_croak_nocontext("panic: malloc");
92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
93 PERL_ALLOC_CHECK(ptr);
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
96 #ifdef PERL_TRACK_MEMPOOL
97 struct perl_memory_debug_header *const header
98 = (struct perl_memory_debug_header *)ptr;
102 PoisonNew(((char *)ptr), size, char);
105 #ifdef PERL_TRACK_MEMPOOL
106 header->interpreter = aTHX;
107 /* Link us into the list. */
108 header->prev = &PL_memory_debug_header;
109 header->next = PL_memory_debug_header.next;
110 PL_memory_debug_header.next = header;
111 header->next->prev = header;
115 ptr = (Malloc_t)((char*)ptr+sTHX);
122 return write_no_mem();
127 /* paranoid version of system's realloc() */
130 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
134 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
135 Malloc_t PerlMem_realloc();
136 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
140 PerlIO_printf(Perl_error_log,
141 "Reallocation too large: %lx\n", size) FLUSH;
144 #endif /* HAS_64K_LIMIT */
151 return safesysmalloc(size);
152 #ifdef PERL_TRACK_MEMPOOL
153 where = (Malloc_t)((char*)where-sTHX);
156 struct perl_memory_debug_header *const header
157 = (struct perl_memory_debug_header *)where;
159 if (header->interpreter != aTHX) {
160 Perl_croak_nocontext("panic: realloc from wrong pool");
162 assert(header->next->prev == header);
163 assert(header->prev->next == header);
165 if (header->size > size) {
166 const MEM_SIZE freed_up = header->size - size;
167 char *start_of_freed = ((char *)where) + size;
168 PoisonFree(start_of_freed, freed_up, char);
176 Perl_croak_nocontext("panic: realloc");
178 ptr = (Malloc_t)PerlMem_realloc(where,size);
179 PERL_ALLOC_CHECK(ptr);
181 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
182 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
185 #ifdef PERL_TRACK_MEMPOOL
186 struct perl_memory_debug_header *const header
187 = (struct perl_memory_debug_header *)ptr;
190 if (header->size < size) {
191 const MEM_SIZE fresh = size - header->size;
192 char *start_of_fresh = ((char *)ptr) + size;
193 PoisonNew(start_of_fresh, fresh, char);
197 header->next->prev = header;
198 header->prev->next = header;
200 ptr = (Malloc_t)((char*)ptr+sTHX);
207 return write_no_mem();
212 /* safe version of system's free() */
215 Perl_safesysfree(Malloc_t where)
217 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
222 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
224 #ifdef PERL_TRACK_MEMPOOL
225 where = (Malloc_t)((char*)where-sTHX);
227 struct perl_memory_debug_header *const header
228 = (struct perl_memory_debug_header *)where;
230 if (header->interpreter != aTHX) {
231 Perl_croak_nocontext("panic: free from wrong pool");
234 Perl_croak_nocontext("panic: duplicate free");
236 if (!(header->next) || header->next->prev != header
237 || header->prev->next != header) {
238 Perl_croak_nocontext("panic: bad free");
240 /* Unlink us from the chain. */
241 header->next->prev = header->prev;
242 header->prev->next = header->next;
244 PoisonNew(where, header->size, char);
246 /* Trigger the duplicate free warning. */
254 /* safe version of system's calloc() */
257 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
261 MEM_SIZE total_size = 0;
263 /* Even though calloc() for zero bytes is strange, be robust. */
264 if (size && (count <= MEM_SIZE_MAX / size))
265 total_size = size * count;
267 Perl_croak_nocontext(PL_memory_wrap);
268 #ifdef PERL_TRACK_MEMPOOL
269 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
272 Perl_croak_nocontext(PL_memory_wrap);
275 if (total_size > 0xffff) {
276 PerlIO_printf(Perl_error_log,
277 "Allocation too large: %lx\n", total_size) FLUSH;
280 #endif /* HAS_64K_LIMIT */
282 if ((long)size < 0 || (long)count < 0)
283 Perl_croak_nocontext("panic: calloc");
285 #ifdef PERL_TRACK_MEMPOOL
286 /* Have to use malloc() because we've added some space for our tracking
288 /* malloc(0) is non-portable. */
289 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
291 /* Use calloc() because it might save a memset() if the memory is fresh
292 and clean from the OS. */
294 ptr = (Malloc_t)PerlMem_calloc(count, size);
295 else /* calloc(0) is non-portable. */
296 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
298 PERL_ALLOC_CHECK(ptr);
299 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));
301 #ifdef PERL_TRACK_MEMPOOL
303 struct perl_memory_debug_header *const header
304 = (struct perl_memory_debug_header *)ptr;
306 memset((void*)ptr, 0, total_size);
307 header->interpreter = aTHX;
308 /* Link us into the list. */
309 header->prev = &PL_memory_debug_header;
310 header->next = PL_memory_debug_header.next;
311 PL_memory_debug_header.next = header;
312 header->next->prev = header;
314 header->size = total_size;
316 ptr = (Malloc_t)((char*)ptr+sTHX);
323 return write_no_mem();
326 /* These must be defined when not using Perl's malloc for binary
331 Malloc_t Perl_malloc (MEM_SIZE nbytes)
334 return (Malloc_t)PerlMem_malloc(nbytes);
337 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
340 return (Malloc_t)PerlMem_calloc(elements, size);
343 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
346 return (Malloc_t)PerlMem_realloc(where, nbytes);
349 Free_t Perl_mfree (Malloc_t where)
357 /* copy a string up to some (non-backslashed) delimiter, if any */
360 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
365 PERL_ARGS_ASSERT_DELIMCPY;
367 for (tolen = 0; from < fromend; from++, tolen++) {
369 if (from[1] != delim) {
376 else if (*from == delim)
387 /* return ptr to little string in big string, NULL if not found */
388 /* This routine was donated by Corey Satten. */
391 Perl_instr(pTHX_ register const char *big, register const char *little)
396 PERL_ARGS_ASSERT_INSTR;
404 register const char *s, *x;
407 for (x=big,s=little; *s; /**/ ) {
418 return (char*)(big-1);
423 /* same as instr but allow embedded nulls */
426 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
428 PERL_ARGS_ASSERT_NINSTR;
433 const char first = *little++;
435 bigend -= lend - little;
437 while (big <= bigend) {
438 if (*big++ == first) {
439 for (x=big,s=little; s < lend; x++,s++) {
443 return (char*)(big-1);
450 /* reverse of the above--find last substring */
453 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
455 register const char *bigbeg;
456 register const I32 first = *little;
457 register const char * const littleend = lend;
460 PERL_ARGS_ASSERT_RNINSTR;
462 if (little >= littleend)
463 return (char*)bigend;
465 big = bigend - (littleend - little++);
466 while (big >= bigbeg) {
467 register const char *s, *x;
470 for (x=big+2,s=little; s < littleend; /**/ ) {
479 return (char*)(big+1);
484 /* As a space optimization, we do not compile tables for strings of length
485 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
486 special-cased in fbm_instr().
488 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
491 =head1 Miscellaneous Functions
493 =for apidoc fbm_compile
495 Analyses the string in order to make fast searches on it using fbm_instr()
496 -- the Boyer-Moore algorithm.
502 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
505 register const U8 *s;
511 PERL_ARGS_ASSERT_FBM_COMPILE;
513 if (flags & FBMcf_TAIL) {
514 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
515 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
516 if (mg && mg->mg_len >= 0)
519 s = (U8*)SvPV_force_mutable(sv, len);
520 if (len == 0) /* TAIL might be on a zero-length string. */
522 SvUPGRADE(sv, SVt_PVGV);
527 const unsigned char *sb;
528 const U8 mlen = (len>255) ? 255 : (U8)len;
531 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
533 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
534 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
535 memset((void*)table, mlen, 256);
537 sb = s - mlen + 1; /* first char (maybe) */
539 if (table[*s] == mlen)
544 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
546 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
548 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
549 for (i = 0; i < len; i++) {
550 if (PL_freq[s[i]] < frequency) {
552 frequency = PL_freq[s[i]];
555 BmFLAGS(sv) = (U8)flags;
556 BmRARE(sv) = s[rarest];
557 BmPREVIOUS(sv) = rarest;
558 BmUSEFUL(sv) = 100; /* Initial value */
559 if (flags & FBMcf_TAIL)
561 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
562 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
565 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
566 /* If SvTAIL is actually due to \Z or \z, this gives false positives
570 =for apidoc fbm_instr
572 Returns the location of the SV in the string delimited by C<str> and
573 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
574 does not have to be fbm_compiled, but the search will not be as fast
581 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
583 register unsigned char *s;
585 register const unsigned char *little
586 = (const unsigned char *)SvPV_const(littlestr,l);
587 register STRLEN littlelen = l;
588 register const I32 multiline = flags & FBMrf_MULTILINE;
590 PERL_ARGS_ASSERT_FBM_INSTR;
592 if ((STRLEN)(bigend - big) < littlelen) {
593 if ( SvTAIL(littlestr)
594 && ((STRLEN)(bigend - big) == littlelen - 1)
596 || (*big == *little &&
597 memEQ((char *)big, (char *)little, littlelen - 1))))
602 if (littlelen <= 2) { /* Special-cased */
604 if (littlelen == 1) {
605 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
606 /* Know that bigend != big. */
607 if (bigend[-1] == '\n')
608 return (char *)(bigend - 1);
609 return (char *) bigend;
617 if (SvTAIL(littlestr))
618 return (char *) bigend;
622 return (char*)big; /* Cannot be SvTAIL! */
625 if (SvTAIL(littlestr) && !multiline) {
626 if (bigend[-1] == '\n' && bigend[-2] == *little)
627 return (char*)bigend - 2;
628 if (bigend[-1] == *little)
629 return (char*)bigend - 1;
633 /* This should be better than FBM if c1 == c2, and almost
634 as good otherwise: maybe better since we do less indirection.
635 And we save a lot of memory by caching no table. */
636 const unsigned char c1 = little[0];
637 const unsigned char c2 = little[1];
642 while (s <= bigend) {
652 goto check_1char_anchor;
663 goto check_1char_anchor;
666 while (s <= bigend) {
671 goto check_1char_anchor;
680 check_1char_anchor: /* One char and anchor! */
681 if (SvTAIL(littlestr) && (*bigend == *little))
682 return (char *)bigend; /* bigend is already decremented. */
685 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
686 s = bigend - littlelen;
687 if (s >= big && bigend[-1] == '\n' && *s == *little
688 /* Automatically of length > 2 */
689 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
691 return (char*)s; /* how sweet it is */
694 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
696 return (char*)s + 1; /* how sweet it is */
700 if (!SvVALID(littlestr)) {
701 char * const b = ninstr((char*)big,(char*)bigend,
702 (char*)little, (char*)little + littlelen);
704 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
705 /* Chop \n from littlestr: */
706 s = bigend - littlelen + 1;
708 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
718 if (littlelen > (STRLEN)(bigend - big))
722 register const unsigned char * const table
723 = little + littlelen + PERL_FBM_TABLE_OFFSET;
724 register const unsigned char *oldlittle;
726 --littlelen; /* Last char found by table lookup */
729 little += littlelen; /* last char */
735 if ((tmp = table[*s])) {
736 if ((s += tmp) < bigend)
740 else { /* less expensive than calling strncmp() */
741 register unsigned char * const olds = s;
746 if (*--s == *--little)
748 s = olds + 1; /* here we pay the price for failure */
750 if (s < bigend) /* fake up continue to outer loop */
759 && (BmFLAGS(littlestr) & FBMcf_TAIL)
760 && memEQ((char *)(bigend - littlelen),
761 (char *)(oldlittle - littlelen), littlelen) )
762 return (char*)bigend - littlelen;
767 /* start_shift, end_shift are positive quantities which give offsets
768 of ends of some substring of bigstr.
769 If "last" we want the last occurrence.
770 old_posp is the way of communication between consequent calls if
771 the next call needs to find the .
772 The initial *old_posp should be -1.
774 Note that we take into account SvTAIL, so one can get extra
775 optimizations if _ALL flag is set.
778 /* If SvTAIL is actually due to \Z or \z, this gives false positives
779 if PL_multiline. In fact if !PL_multiline the authoritative answer
780 is not supported yet. */
783 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
786 register const unsigned char *big;
788 register I32 previous;
790 register const unsigned char *little;
791 register I32 stop_pos;
792 register const unsigned char *littleend;
795 PERL_ARGS_ASSERT_SCREAMINSTR;
797 assert(SvTYPE(littlestr) == SVt_PVGV);
798 assert(SvVALID(littlestr));
801 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
802 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
804 if ( BmRARE(littlestr) == '\n'
805 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
806 little = (const unsigned char *)(SvPVX_const(littlestr));
807 littleend = little + SvCUR(littlestr);
814 little = (const unsigned char *)(SvPVX_const(littlestr));
815 littleend = little + SvCUR(littlestr);
817 /* The value of pos we can start at: */
818 previous = BmPREVIOUS(littlestr);
819 big = (const unsigned char *)(SvPVX_const(bigstr));
820 /* The value of pos we can stop at: */
821 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
822 if (previous + start_shift > stop_pos) {
824 stop_pos does not include SvTAIL in the count, so this check is incorrect
825 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
828 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
833 while (pos < previous + start_shift) {
834 if (!(pos += PL_screamnext[pos]))
839 register const unsigned char *s, *x;
840 if (pos >= stop_pos) break;
841 if (big[pos] != first)
843 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
849 if (s == littleend) {
851 if (!last) return (char *)(big+pos);
854 } while ( pos += PL_screamnext[pos] );
856 return (char *)(big+(*old_posp));
858 if (!SvTAIL(littlestr) || (end_shift > 0))
860 /* Ignore the trailing "\n". This code is not microoptimized */
861 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
862 stop_pos = littleend - little; /* Actual littlestr len */
867 && ((stop_pos == 1) ||
868 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
874 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
876 register const U8 *a = (const U8 *)s1;
877 register const U8 *b = (const U8 *)s2;
880 PERL_ARGS_ASSERT_IBCMP;
883 if (*a != *b && *a != PL_fold[*b])
891 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
894 register const U8 *a = (const U8 *)s1;
895 register const U8 *b = (const U8 *)s2;
898 PERL_ARGS_ASSERT_IBCMP_LOCALE;
901 if (*a != *b && *a != PL_fold_locale[*b])
908 /* copy a string to a safe spot */
911 =head1 Memory Management
915 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
916 string which is a duplicate of C<pv>. The size of the string is
917 determined by C<strlen()>. The memory allocated for the new string can
918 be freed with the C<Safefree()> function.
924 Perl_savepv(pTHX_ const char *pv)
931 const STRLEN pvlen = strlen(pv)+1;
932 Newx(newaddr, pvlen, char);
933 return (char*)memcpy(newaddr, pv, pvlen);
937 /* same thing but with a known length */
942 Perl's version of what C<strndup()> would be if it existed. Returns a
943 pointer to a newly allocated string which is a duplicate of the first
944 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
945 the new string can be freed with the C<Safefree()> function.
951 Perl_savepvn(pTHX_ const char *pv, register I32 len)
953 register char *newaddr;
956 Newx(newaddr,len+1,char);
957 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
959 /* might not be null terminated */
961 return (char *) CopyD(pv,newaddr,len,char);
964 return (char *) ZeroD(newaddr,len+1,char);
969 =for apidoc savesharedpv
971 A version of C<savepv()> which allocates the duplicate string in memory
972 which is shared between threads.
977 Perl_savesharedpv(pTHX_ const char *pv)
979 register char *newaddr;
984 pvlen = strlen(pv)+1;
985 newaddr = (char*)PerlMemShared_malloc(pvlen);
987 return write_no_mem();
989 return (char*)memcpy(newaddr, pv, pvlen);
993 =for apidoc savesharedpvn
995 A version of C<savepvn()> which allocates the duplicate string in memory
996 which is shared between threads. (With the specific difference that a NULL
997 pointer is not acceptable)
1002 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1004 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1006 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1009 return write_no_mem();
1011 newaddr[len] = '\0';
1012 return (char*)memcpy(newaddr, pv, len);
1016 =for apidoc savesvpv
1018 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1019 the passed in SV using C<SvPV()>
1025 Perl_savesvpv(pTHX_ SV *sv)
1028 const char * const pv = SvPV_const(sv, len);
1029 register char *newaddr;
1031 PERL_ARGS_ASSERT_SAVESVPV;
1034 Newx(newaddr,len,char);
1035 return (char *) CopyD(pv,newaddr,len,char);
1039 /* the SV for Perl_form() and mess() is not kept in an arena */
1049 return newSVpvs_flags("", SVs_TEMP);
1054 /* Create as PVMG now, to avoid any upgrading later */
1056 Newxz(any, 1, XPVMG);
1057 SvFLAGS(sv) = SVt_PVMG;
1058 SvANY(sv) = (void*)any;
1060 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1065 #if defined(PERL_IMPLICIT_CONTEXT)
1067 Perl_form_nocontext(const char* pat, ...)
1072 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1073 va_start(args, pat);
1074 retval = vform(pat, &args);
1078 #endif /* PERL_IMPLICIT_CONTEXT */
1081 =head1 Miscellaneous Functions
1084 Takes a sprintf-style format pattern and conventional
1085 (non-SV) arguments and returns the formatted string.
1087 (char *) Perl_form(pTHX_ const char* pat, ...)
1089 can be used any place a string (char *) is required:
1091 char * s = Perl_form("%d.%d",major,minor);
1093 Uses a single private buffer so if you want to format several strings you
1094 must explicitly copy the earlier strings away (and free the copies when you
1101 Perl_form(pTHX_ const char* pat, ...)
1105 PERL_ARGS_ASSERT_FORM;
1106 va_start(args, pat);
1107 retval = vform(pat, &args);
1113 Perl_vform(pTHX_ const char *pat, va_list *args)
1115 SV * const sv = mess_alloc();
1116 PERL_ARGS_ASSERT_VFORM;
1117 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1121 #if defined(PERL_IMPLICIT_CONTEXT)
1123 Perl_mess_nocontext(const char *pat, ...)
1128 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1129 va_start(args, pat);
1130 retval = vmess(pat, &args);
1134 #endif /* PERL_IMPLICIT_CONTEXT */
1137 Perl_mess(pTHX_ const char *pat, ...)
1141 PERL_ARGS_ASSERT_MESS;
1142 va_start(args, pat);
1143 retval = vmess(pat, &args);
1149 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1152 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1154 PERL_ARGS_ASSERT_CLOSEST_COP;
1156 if (!o || o == PL_op)
1159 if (o->op_flags & OPf_KIDS) {
1161 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1164 /* If the OP_NEXTSTATE has been optimised away we can still use it
1165 * the get the file and line number. */
1167 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1168 cop = (const COP *)kid;
1170 /* Keep searching, and return when we've found something. */
1172 new_cop = closest_cop(cop, kid);
1178 /* Nothing found. */
1184 Perl_vmess(pTHX_ const char *pat, va_list *args)
1187 SV * const sv = mess_alloc();
1189 PERL_ARGS_ASSERT_VMESS;
1191 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1192 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1194 * Try and find the file and line for PL_op. This will usually be
1195 * PL_curcop, but it might be a cop that has been optimised away. We
1196 * can try to find such a cop by searching through the optree starting
1197 * from the sibling of PL_curcop.
1200 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1205 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1206 OutCopFILE(cop), (IV)CopLINE(cop));
1207 /* Seems that GvIO() can be untrustworthy during global destruction. */
1208 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1209 && IoLINES(GvIOp(PL_last_in_gv)))
1211 const bool line_mode = (RsSIMPLE(PL_rs) &&
1212 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1213 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1214 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1215 line_mode ? "line" : "chunk",
1216 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1219 sv_catpvs(sv, " during global destruction");
1220 sv_catpvs(sv, ".\n");
1226 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1232 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1234 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1235 && (io = GvIO(PL_stderrgv))
1236 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1243 SAVESPTR(PL_stderrgv);
1246 PUSHSTACKi(PERLSI_MAGIC);
1250 PUSHs(SvTIED_obj((SV*)io, mg));
1251 mPUSHp(message, msglen);
1253 call_method("PRINT", G_SCALAR);
1261 /* SFIO can really mess with your errno */
1262 const int e = errno;
1264 PerlIO * const serr = Perl_error_log;
1266 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1267 (void)PerlIO_flush(serr);
1274 /* Common code used by vcroak, vdie, vwarn and vwarner */
1277 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1283 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1284 /* sv_2cv might call Perl_croak() or Perl_warner() */
1285 SV * const oldhook = *hook;
1292 cv = sv_2cv(oldhook, &stash, &gv, 0);
1294 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1304 if (warn || message) {
1305 msg = newSVpvn_flags(message, msglen, utf8);
1313 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1317 call_sv((SV*)cv, G_DISCARD);
1326 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1330 const char *message;
1333 SV * const msv = vmess(pat, args);
1334 if (PL_errors && SvCUR(PL_errors)) {
1335 sv_catsv(PL_errors, msv);
1336 message = SvPV_const(PL_errors, *msglen);
1337 SvCUR_set(PL_errors, 0);
1340 message = SvPV_const(msv,*msglen);
1341 *utf8 = SvUTF8(msv);
1348 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1354 Perl_vdie(pTHX_ const char* pat, va_list *args)
1357 const char *message;
1358 const int was_in_eval = PL_in_eval;
1362 message = vdie_croak_common(pat, args, &msglen, &utf8);
1364 PL_restartop = die_where(message, msglen);
1365 SvFLAGS(ERRSV) |= utf8;
1366 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1368 return PL_restartop;
1371 #if defined(PERL_IMPLICIT_CONTEXT)
1373 Perl_die_nocontext(const char* pat, ...)
1378 PERL_ARGS_ASSERT_DIE_NOCONTEXT;
1379 va_start(args, pat);
1380 o = vdie(pat, &args);
1384 #endif /* PERL_IMPLICIT_CONTEXT */
1387 Perl_die(pTHX_ const char* pat, ...)
1391 va_start(args, pat);
1392 o = vdie(pat, &args);
1398 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1401 const char *message;
1405 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1408 PL_restartop = die_where(message, msglen);
1409 SvFLAGS(ERRSV) |= utf8;
1413 message = SvPVx_const(ERRSV, msglen);
1415 write_to_stderr(message, msglen);
1419 #if defined(PERL_IMPLICIT_CONTEXT)
1421 Perl_croak_nocontext(const char *pat, ...)
1425 PERL_ARGS_ASSERT_CROAK_NOCONTEXT;
1426 va_start(args, pat);
1431 #endif /* PERL_IMPLICIT_CONTEXT */
1434 =head1 Warning and Dieing
1438 This is the XSUB-writer's interface to Perl's C<die> function.
1439 Normally call this function the same way you call the C C<printf>
1440 function. Calling C<croak> returns control directly to Perl,
1441 sidestepping the normal C order of execution. See C<warn>.
1443 If you want to throw an exception object, assign the object to
1444 C<$@> and then pass C<NULL> to croak():
1446 errsv = get_sv("@", TRUE);
1447 sv_setsv(errsv, exception_object);
1454 Perl_croak(pTHX_ const char *pat, ...)
1457 va_start(args, pat);
1464 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1468 SV * const msv = vmess(pat, args);
1469 const I32 utf8 = SvUTF8(msv);
1470 const char * const message = SvPV_const(msv, msglen);
1472 PERL_ARGS_ASSERT_VWARN;
1475 if (vdie_common(message, msglen, utf8, TRUE))
1479 write_to_stderr(message, msglen);
1482 #if defined(PERL_IMPLICIT_CONTEXT)
1484 Perl_warn_nocontext(const char *pat, ...)
1488 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1489 va_start(args, pat);
1493 #endif /* PERL_IMPLICIT_CONTEXT */
1498 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1499 function the same way you call the C C<printf> function. See C<croak>.
1505 Perl_warn(pTHX_ const char *pat, ...)
1508 PERL_ARGS_ASSERT_WARN;
1509 va_start(args, pat);
1514 #if defined(PERL_IMPLICIT_CONTEXT)
1516 Perl_warner_nocontext(U32 err, const char *pat, ...)
1520 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1521 va_start(args, pat);
1522 vwarner(err, pat, &args);
1525 #endif /* PERL_IMPLICIT_CONTEXT */
1528 Perl_warner(pTHX_ U32 err, const char* pat,...)
1531 PERL_ARGS_ASSERT_WARNER;
1532 va_start(args, pat);
1533 vwarner(err, pat, &args);
1538 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1541 PERL_ARGS_ASSERT_VWARNER;
1542 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1543 SV * const msv = vmess(pat, args);
1545 const char * const message = SvPV_const(msv, msglen);
1546 const I32 utf8 = SvUTF8(msv);
1550 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1553 PL_restartop = die_where(message, msglen);
1554 SvFLAGS(ERRSV) |= utf8;
1557 write_to_stderr(message, msglen);
1561 Perl_vwarn(aTHX_ pat, args);
1565 /* implements the ckWARN? macros */
1568 Perl_ckwarn(pTHX_ U32 w)
1574 && PL_curcop->cop_warnings != pWARN_NONE
1576 PL_curcop->cop_warnings == pWARN_ALL
1577 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1578 || (unpackWARN2(w) &&
1579 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1580 || (unpackWARN3(w) &&
1581 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1582 || (unpackWARN4(w) &&
1583 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1588 isLEXWARN_off && PL_dowarn & G_WARN_ON
1593 /* implements the ckWARN?_d macro */
1596 Perl_ckwarn_d(pTHX_ U32 w)
1601 || PL_curcop->cop_warnings == pWARN_ALL
1603 PL_curcop->cop_warnings != pWARN_NONE
1605 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1606 || (unpackWARN2(w) &&
1607 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1608 || (unpackWARN3(w) &&
1609 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1610 || (unpackWARN4(w) &&
1611 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1617 /* Set buffer=NULL to get a new one. */
1619 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1621 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1622 PERL_UNUSED_CONTEXT;
1623 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1626 (specialWARN(buffer) ?
1627 PerlMemShared_malloc(len_wanted) :
1628 PerlMemShared_realloc(buffer, len_wanted));
1630 Copy(bits, (buffer + 1), size, char);
1634 /* since we've already done strlen() for both nam and val
1635 * we can use that info to make things faster than
1636 * sprintf(s, "%s=%s", nam, val)
1638 #define my_setenv_format(s, nam, nlen, val, vlen) \
1639 Copy(nam, s, nlen, char); \
1641 Copy(val, s+(nlen+1), vlen, char); \
1642 *(s+(nlen+1+vlen)) = '\0'
1644 #ifdef USE_ENVIRON_ARRAY
1645 /* VMS' my_setenv() is in vms.c */
1646 #if !defined(WIN32) && !defined(NETWARE)
1648 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1652 /* only parent thread can modify process environment */
1653 if (PL_curinterp == aTHX)
1656 #ifndef PERL_USE_SAFE_PUTENV
1657 if (!PL_use_safe_putenv) {
1658 /* most putenv()s leak, so we manipulate environ directly */
1659 register I32 i=setenv_getix(nam); /* where does it go? */
1662 if (environ == PL_origenviron) { /* need we copy environment? */
1668 while (environ[max])
1670 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1671 for (j=0; j<max; j++) { /* copy environment */
1672 const int len = strlen(environ[j]);
1673 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1674 Copy(environ[j], tmpenv[j], len+1, char);
1677 environ = tmpenv; /* tell exec where it is now */
1680 safesysfree(environ[i]);
1681 while (environ[i]) {
1682 environ[i] = environ[i+1];
1687 if (!environ[i]) { /* does not exist yet */
1688 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1689 environ[i+1] = NULL; /* make sure it's null terminated */
1692 safesysfree(environ[i]);
1696 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1697 /* all that work just for this */
1698 my_setenv_format(environ[i], nam, nlen, val, vlen);
1701 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1702 # if defined(HAS_UNSETENV)
1704 (void)unsetenv(nam);
1706 (void)setenv(nam, val, 1);
1708 # else /* ! HAS_UNSETENV */
1709 (void)setenv(nam, val, 1);
1710 # endif /* HAS_UNSETENV */
1712 # if defined(HAS_UNSETENV)
1714 (void)unsetenv(nam);
1716 const int nlen = strlen(nam);
1717 const int vlen = strlen(val);
1718 char * const new_env =
1719 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1720 my_setenv_format(new_env, nam, nlen, val, vlen);
1721 (void)putenv(new_env);
1723 # else /* ! HAS_UNSETENV */
1725 const int nlen = strlen(nam);
1731 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1732 /* all that work just for this */
1733 my_setenv_format(new_env, nam, nlen, val, vlen);
1734 (void)putenv(new_env);
1735 # endif /* HAS_UNSETENV */
1736 # endif /* __CYGWIN__ */
1737 #ifndef PERL_USE_SAFE_PUTENV
1743 #else /* WIN32 || NETWARE */
1746 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1749 register char *envstr;
1750 const int nlen = strlen(nam);
1757 Newx(envstr, nlen+vlen+2, char);
1758 my_setenv_format(envstr, nam, nlen, val, vlen);
1759 (void)PerlEnv_putenv(envstr);
1763 #endif /* WIN32 || NETWARE */
1767 Perl_setenv_getix(pTHX_ const char *nam)
1770 register const I32 len = strlen(nam);
1772 PERL_ARGS_ASSERT_SETENV_GETIX;
1773 PERL_UNUSED_CONTEXT;
1775 for (i = 0; environ[i]; i++) {
1778 strnicmp(environ[i],nam,len) == 0
1780 strnEQ(environ[i],nam,len)
1782 && environ[i][len] == '=')
1783 break; /* strnEQ must come first to avoid */
1784 } /* potential SEGV's */
1787 #endif /* !PERL_MICRO */
1789 #endif /* !VMS && !EPOC*/
1791 #ifdef UNLINK_ALL_VERSIONS
1793 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1797 PERL_ARGS_ASSERT_UNLNK;
1799 while (PerlLIO_unlink(f) >= 0)
1801 return retries ? 0 : -1;
1805 /* this is a drop-in replacement for bcopy() */
1806 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1808 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1810 char * const retval = to;
1812 PERL_ARGS_ASSERT_MY_BCOPY;
1814 if (from - to >= 0) {
1822 *(--to) = *(--from);
1828 /* this is a drop-in replacement for memset() */
1831 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1833 char * const retval = loc;
1835 PERL_ARGS_ASSERT_MY_MEMSET;
1843 /* this is a drop-in replacement for bzero() */
1844 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1846 Perl_my_bzero(register char *loc, register I32 len)
1848 char * const retval = loc;
1850 PERL_ARGS_ASSERT_MY_BZERO;
1858 /* this is a drop-in replacement for memcmp() */
1859 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1861 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1863 register const U8 *a = (const U8 *)s1;
1864 register const U8 *b = (const U8 *)s2;
1867 PERL_ARGS_ASSERT_MY_MEMCMP;
1870 if ((tmp = *a++ - *b++))
1875 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1878 /* This vsprintf replacement should generally never get used, since
1879 vsprintf was available in both System V and BSD 2.11. (There may
1880 be some cross-compilation or embedded set-ups where it is needed,
1883 If you encounter a problem in this function, it's probably a symptom
1884 that Configure failed to detect your system's vprintf() function.
1885 See the section on "item vsprintf" in the INSTALL file.
1887 This version may compile on systems with BSD-ish <stdio.h>,
1888 but probably won't on others.
1891 #ifdef USE_CHAR_VSPRINTF
1896 vsprintf(char *dest, const char *pat, void *args)
1900 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
1901 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
1902 FILE_cnt(&fakebuf) = 32767;
1904 /* These probably won't compile -- If you really need
1905 this, you'll have to figure out some other method. */
1906 fakebuf._ptr = dest;
1907 fakebuf._cnt = 32767;
1912 fakebuf._flag = _IOWRT|_IOSTRG;
1913 _doprnt(pat, args, &fakebuf); /* what a kludge */
1914 #if defined(STDIO_PTR_LVALUE)
1915 *(FILE_ptr(&fakebuf)++) = '\0';
1917 /* PerlIO has probably #defined away fputc, but we want it here. */
1919 # undef fputc /* XXX Should really restore it later */
1921 (void)fputc('\0', &fakebuf);
1923 #ifdef USE_CHAR_VSPRINTF
1926 return 0; /* perl doesn't use return value */
1930 #endif /* HAS_VPRINTF */
1933 #if BYTEORDER != 0x4321
1935 Perl_my_swap(pTHX_ short s)
1937 #if (BYTEORDER & 1) == 0
1940 result = ((s & 255) << 8) + ((s >> 8) & 255);
1948 Perl_my_htonl(pTHX_ long l)
1952 char c[sizeof(long)];
1955 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
1956 #if BYTEORDER == 0x12345678
1959 u.c[0] = (l >> 24) & 255;
1960 u.c[1] = (l >> 16) & 255;
1961 u.c[2] = (l >> 8) & 255;
1965 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1966 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1971 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1972 u.c[o & 0xf] = (l >> s) & 255;
1980 Perl_my_ntohl(pTHX_ long l)
1984 char c[sizeof(long)];
1987 #if BYTEORDER == 0x1234
1988 u.c[0] = (l >> 24) & 255;
1989 u.c[1] = (l >> 16) & 255;
1990 u.c[2] = (l >> 8) & 255;
1994 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1995 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2002 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2003 l |= (u.c[o & 0xf] & 255) << s;
2010 #endif /* BYTEORDER != 0x4321 */
2014 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2015 * If these functions are defined,
2016 * the BYTEORDER is neither 0x1234 nor 0x4321.
2017 * However, this is not assumed.
2021 #define HTOLE(name,type) \
2023 name (register type n) \
2027 char c[sizeof(type)]; \
2030 register U32 s = 0; \
2031 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2032 u.c[i] = (n >> s) & 0xFF; \
2037 #define LETOH(name,type) \
2039 name (register type n) \
2043 char c[sizeof(type)]; \
2046 register U32 s = 0; \
2049 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2050 n |= ((type)(u.c[i] & 0xFF)) << s; \
2056 * Big-endian byte order functions.
2059 #define HTOBE(name,type) \
2061 name (register type n) \
2065 char c[sizeof(type)]; \
2068 register U32 s = 8*(sizeof(u.c)-1); \
2069 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2070 u.c[i] = (n >> s) & 0xFF; \
2075 #define BETOH(name,type) \
2077 name (register type n) \
2081 char c[sizeof(type)]; \
2084 register U32 s = 8*(sizeof(u.c)-1); \
2087 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2088 n |= ((type)(u.c[i] & 0xFF)) << s; \
2094 * If we just can't do it...
2097 #define NOT_AVAIL(name,type) \
2099 name (register type n) \
2101 Perl_croak_nocontext(#name "() not available"); \
2102 return n; /* not reached */ \
2106 #if defined(HAS_HTOVS) && !defined(htovs)
2109 #if defined(HAS_HTOVL) && !defined(htovl)
2112 #if defined(HAS_VTOHS) && !defined(vtohs)
2115 #if defined(HAS_VTOHL) && !defined(vtohl)
2119 #ifdef PERL_NEED_MY_HTOLE16
2121 HTOLE(Perl_my_htole16,U16)
2123 NOT_AVAIL(Perl_my_htole16,U16)
2126 #ifdef PERL_NEED_MY_LETOH16
2128 LETOH(Perl_my_letoh16,U16)
2130 NOT_AVAIL(Perl_my_letoh16,U16)
2133 #ifdef PERL_NEED_MY_HTOBE16
2135 HTOBE(Perl_my_htobe16,U16)
2137 NOT_AVAIL(Perl_my_htobe16,U16)
2140 #ifdef PERL_NEED_MY_BETOH16
2142 BETOH(Perl_my_betoh16,U16)
2144 NOT_AVAIL(Perl_my_betoh16,U16)
2148 #ifdef PERL_NEED_MY_HTOLE32
2150 HTOLE(Perl_my_htole32,U32)
2152 NOT_AVAIL(Perl_my_htole32,U32)
2155 #ifdef PERL_NEED_MY_LETOH32
2157 LETOH(Perl_my_letoh32,U32)
2159 NOT_AVAIL(Perl_my_letoh32,U32)
2162 #ifdef PERL_NEED_MY_HTOBE32
2164 HTOBE(Perl_my_htobe32,U32)
2166 NOT_AVAIL(Perl_my_htobe32,U32)
2169 #ifdef PERL_NEED_MY_BETOH32
2171 BETOH(Perl_my_betoh32,U32)
2173 NOT_AVAIL(Perl_my_betoh32,U32)
2177 #ifdef PERL_NEED_MY_HTOLE64
2179 HTOLE(Perl_my_htole64,U64)
2181 NOT_AVAIL(Perl_my_htole64,U64)
2184 #ifdef PERL_NEED_MY_LETOH64
2186 LETOH(Perl_my_letoh64,U64)
2188 NOT_AVAIL(Perl_my_letoh64,U64)
2191 #ifdef PERL_NEED_MY_HTOBE64
2193 HTOBE(Perl_my_htobe64,U64)
2195 NOT_AVAIL(Perl_my_htobe64,U64)
2198 #ifdef PERL_NEED_MY_BETOH64
2200 BETOH(Perl_my_betoh64,U64)
2202 NOT_AVAIL(Perl_my_betoh64,U64)
2206 #ifdef PERL_NEED_MY_HTOLES
2207 HTOLE(Perl_my_htoles,short)
2209 #ifdef PERL_NEED_MY_LETOHS
2210 LETOH(Perl_my_letohs,short)
2212 #ifdef PERL_NEED_MY_HTOBES
2213 HTOBE(Perl_my_htobes,short)
2215 #ifdef PERL_NEED_MY_BETOHS
2216 BETOH(Perl_my_betohs,short)
2219 #ifdef PERL_NEED_MY_HTOLEI
2220 HTOLE(Perl_my_htolei,int)
2222 #ifdef PERL_NEED_MY_LETOHI
2223 LETOH(Perl_my_letohi,int)
2225 #ifdef PERL_NEED_MY_HTOBEI
2226 HTOBE(Perl_my_htobei,int)
2228 #ifdef PERL_NEED_MY_BETOHI
2229 BETOH(Perl_my_betohi,int)
2232 #ifdef PERL_NEED_MY_HTOLEL
2233 HTOLE(Perl_my_htolel,long)
2235 #ifdef PERL_NEED_MY_LETOHL
2236 LETOH(Perl_my_letohl,long)
2238 #ifdef PERL_NEED_MY_HTOBEL
2239 HTOBE(Perl_my_htobel,long)
2241 #ifdef PERL_NEED_MY_BETOHL
2242 BETOH(Perl_my_betohl,long)
2246 Perl_my_swabn(void *ptr, int n)
2248 register char *s = (char *)ptr;
2249 register char *e = s + (n-1);
2252 PERL_ARGS_ASSERT_MY_SWABN;
2254 for (n /= 2; n > 0; s++, e--, n--) {
2262 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2264 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2267 register I32 This, that;
2273 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2275 PERL_FLUSHALL_FOR_CHILD;
2276 This = (*mode == 'w');
2280 taint_proper("Insecure %s%s", "EXEC");
2282 if (PerlProc_pipe(p) < 0)
2284 /* Try for another pipe pair for error return */
2285 if (PerlProc_pipe(pp) >= 0)
2287 while ((pid = PerlProc_fork()) < 0) {
2288 if (errno != EAGAIN) {
2289 PerlLIO_close(p[This]);
2290 PerlLIO_close(p[that]);
2292 PerlLIO_close(pp[0]);
2293 PerlLIO_close(pp[1]);
2305 /* Close parent's end of error status pipe (if any) */
2307 PerlLIO_close(pp[0]);
2308 #if defined(HAS_FCNTL) && defined(F_SETFD)
2309 /* Close error pipe automatically if exec works */
2310 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2313 /* Now dup our end of _the_ pipe to right position */
2314 if (p[THIS] != (*mode == 'r')) {
2315 PerlLIO_dup2(p[THIS], *mode == 'r');
2316 PerlLIO_close(p[THIS]);
2317 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2318 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2321 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2322 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2323 /* No automatic close - do it by hand */
2330 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2336 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2342 do_execfree(); /* free any memory malloced by child on fork */
2344 PerlLIO_close(pp[1]);
2345 /* Keep the lower of the two fd numbers */
2346 if (p[that] < p[This]) {
2347 PerlLIO_dup2(p[This], p[that]);
2348 PerlLIO_close(p[This]);
2352 PerlLIO_close(p[that]); /* close child's end of pipe */
2355 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2357 SvUPGRADE(sv,SVt_IV);
2359 PL_forkprocess = pid;
2360 /* If we managed to get status pipe check for exec fail */
2361 if (did_pipes && pid > 0) {
2366 while (n < sizeof(int)) {
2367 n1 = PerlLIO_read(pp[0],
2368 (void*)(((char*)&errkid)+n),
2374 PerlLIO_close(pp[0]);
2376 if (n) { /* Error */
2378 PerlLIO_close(p[This]);
2379 if (n != sizeof(int))
2380 Perl_croak(aTHX_ "panic: kid popen errno read");
2382 pid2 = wait4pid(pid, &status, 0);
2383 } while (pid2 == -1 && errno == EINTR);
2384 errno = errkid; /* Propagate errno from kid */
2389 PerlLIO_close(pp[0]);
2390 return PerlIO_fdopen(p[This], mode);
2392 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2393 return my_syspopen4(aTHX_ NULL, mode, n, args);
2395 Perl_croak(aTHX_ "List form of piped open not implemented");
2396 return (PerlIO *) NULL;
2401 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2402 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2404 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2408 register I32 This, that;
2411 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2415 PERL_ARGS_ASSERT_MY_POPEN;
2417 PERL_FLUSHALL_FOR_CHILD;
2420 return my_syspopen(aTHX_ cmd,mode);
2423 This = (*mode == 'w');
2425 if (doexec && PL_tainting) {
2427 taint_proper("Insecure %s%s", "EXEC");
2429 if (PerlProc_pipe(p) < 0)
2431 if (doexec && PerlProc_pipe(pp) >= 0)
2433 while ((pid = PerlProc_fork()) < 0) {
2434 if (errno != EAGAIN) {
2435 PerlLIO_close(p[This]);
2436 PerlLIO_close(p[that]);
2438 PerlLIO_close(pp[0]);
2439 PerlLIO_close(pp[1]);
2442 Perl_croak(aTHX_ "Can't fork");
2455 PerlLIO_close(pp[0]);
2456 #if defined(HAS_FCNTL) && defined(F_SETFD)
2457 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2460 if (p[THIS] != (*mode == 'r')) {
2461 PerlLIO_dup2(p[THIS], *mode == 'r');
2462 PerlLIO_close(p[THIS]);
2463 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2464 PerlLIO_close(p[THAT]);
2467 PerlLIO_close(p[THAT]);
2470 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2477 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2482 /* may or may not use the shell */
2483 do_exec3(cmd, pp[1], did_pipes);
2486 #endif /* defined OS2 */
2488 #ifdef PERLIO_USING_CRLF
2489 /* Since we circumvent IO layers when we manipulate low-level
2490 filedescriptors directly, need to manually switch to the
2491 default, binary, low-level mode; see PerlIOBuf_open(). */
2492 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2495 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2496 SvREADONLY_off(GvSV(tmpgv));
2497 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2498 SvREADONLY_on(GvSV(tmpgv));
2500 #ifdef THREADS_HAVE_PIDS
2501 PL_ppid = (IV)getppid();
2504 #ifdef PERL_USES_PL_PIDSTATUS
2505 hv_clear(PL_pidstatus); /* we have no children */
2511 do_execfree(); /* free any memory malloced by child on vfork */
2513 PerlLIO_close(pp[1]);
2514 if (p[that] < p[This]) {
2515 PerlLIO_dup2(p[This], p[that]);
2516 PerlLIO_close(p[This]);
2520 PerlLIO_close(p[that]);
2523 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2525 SvUPGRADE(sv,SVt_IV);
2527 PL_forkprocess = pid;
2528 if (did_pipes && pid > 0) {
2533 while (n < sizeof(int)) {
2534 n1 = PerlLIO_read(pp[0],
2535 (void*)(((char*)&errkid)+n),
2541 PerlLIO_close(pp[0]);
2543 if (n) { /* Error */
2545 PerlLIO_close(p[This]);
2546 if (n != sizeof(int))
2547 Perl_croak(aTHX_ "panic: kid popen errno read");
2549 pid2 = wait4pid(pid, &status, 0);
2550 } while (pid2 == -1 && errno == EINTR);
2551 errno = errkid; /* Propagate errno from kid */
2556 PerlLIO_close(pp[0]);
2557 return PerlIO_fdopen(p[This], mode);
2560 #if defined(atarist) || defined(EPOC)
2563 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2565 PERL_ARGS_ASSERT_MY_POPEN;
2566 PERL_FLUSHALL_FOR_CHILD;
2567 /* Call system's popen() to get a FILE *, then import it.
2568 used 0 for 2nd parameter to PerlIO_importFILE;
2571 return PerlIO_importFILE(popen(cmd, mode), 0);
2575 FILE *djgpp_popen();
2577 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2579 PERL_FLUSHALL_FOR_CHILD;
2580 /* Call system's popen() to get a FILE *, then import it.
2581 used 0 for 2nd parameter to PerlIO_importFILE;
2584 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2587 #if defined(__LIBCATAMOUNT__)
2589 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2597 #endif /* !DOSISH */
2599 /* this is called in parent before the fork() */
2601 Perl_atfork_lock(void)
2604 #if defined(USE_ITHREADS)
2605 /* locks must be held in locking order (if any) */
2607 MUTEX_LOCK(&PL_malloc_mutex);
2613 /* this is called in both parent and child after the fork() */
2615 Perl_atfork_unlock(void)
2618 #if defined(USE_ITHREADS)
2619 /* locks must be released in same order as in atfork_lock() */
2621 MUTEX_UNLOCK(&PL_malloc_mutex);
2630 #if defined(HAS_FORK)
2632 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2637 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2638 * handlers elsewhere in the code */
2643 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2644 Perl_croak_nocontext("fork() not available");
2646 #endif /* HAS_FORK */
2651 Perl_dump_fds(pTHX_ const char *const s)
2656 PERL_ARGS_ASSERT_DUMP_FDS;
2658 PerlIO_printf(Perl_debug_log,"%s", s);
2659 for (fd = 0; fd < 32; fd++) {
2660 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2661 PerlIO_printf(Perl_debug_log," %d",fd);
2663 PerlIO_printf(Perl_debug_log,"\n");
2666 #endif /* DUMP_FDS */
2670 dup2(int oldfd, int newfd)
2672 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2675 PerlLIO_close(newfd);
2676 return fcntl(oldfd, F_DUPFD, newfd);
2678 #define DUP2_MAX_FDS 256
2679 int fdtmp[DUP2_MAX_FDS];
2685 PerlLIO_close(newfd);
2686 /* good enough for low fd's... */
2687 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2688 if (fdx >= DUP2_MAX_FDS) {
2696 PerlLIO_close(fdtmp[--fdx]);
2703 #ifdef HAS_SIGACTION
2705 #ifdef MACOS_TRADITIONAL
2706 /* We don't want restart behavior on MacOS */
2711 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2714 struct sigaction act, oact;
2717 /* only "parent" interpreter can diddle signals */
2718 if (PL_curinterp != aTHX)
2719 return (Sighandler_t) SIG_ERR;
2722 act.sa_handler = (void(*)(int))handler;
2723 sigemptyset(&act.sa_mask);
2726 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2727 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2729 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2730 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2731 act.sa_flags |= SA_NOCLDWAIT;
2733 if (sigaction(signo, &act, &oact) == -1)
2734 return (Sighandler_t) SIG_ERR;
2736 return (Sighandler_t) oact.sa_handler;
2740 Perl_rsignal_state(pTHX_ int signo)
2742 struct sigaction oact;
2743 PERL_UNUSED_CONTEXT;
2745 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2746 return (Sighandler_t) SIG_ERR;
2748 return (Sighandler_t) oact.sa_handler;
2752 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2755 struct sigaction act;
2757 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2760 /* only "parent" interpreter can diddle signals */
2761 if (PL_curinterp != aTHX)
2765 act.sa_handler = (void(*)(int))handler;
2766 sigemptyset(&act.sa_mask);
2769 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2770 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2772 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2773 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2774 act.sa_flags |= SA_NOCLDWAIT;
2776 return sigaction(signo, &act, save);
2780 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2784 /* only "parent" interpreter can diddle signals */
2785 if (PL_curinterp != aTHX)
2789 return sigaction(signo, save, (struct sigaction *)NULL);
2792 #else /* !HAS_SIGACTION */
2795 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2797 #if defined(USE_ITHREADS) && !defined(WIN32)
2798 /* only "parent" interpreter can diddle signals */
2799 if (PL_curinterp != aTHX)
2800 return (Sighandler_t) SIG_ERR;
2803 return PerlProc_signal(signo, handler);
2814 Perl_rsignal_state(pTHX_ int signo)
2817 Sighandler_t oldsig;
2819 #if defined(USE_ITHREADS) && !defined(WIN32)
2820 /* only "parent" interpreter can diddle signals */
2821 if (PL_curinterp != aTHX)
2822 return (Sighandler_t) SIG_ERR;
2826 oldsig = PerlProc_signal(signo, sig_trap);
2827 PerlProc_signal(signo, oldsig);
2829 PerlProc_kill(PerlProc_getpid(), signo);
2834 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2836 #if defined(USE_ITHREADS) && !defined(WIN32)
2837 /* only "parent" interpreter can diddle signals */
2838 if (PL_curinterp != aTHX)
2841 *save = PerlProc_signal(signo, handler);
2842 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2846 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2848 #if defined(USE_ITHREADS) && !defined(WIN32)
2849 /* only "parent" interpreter can diddle signals */
2850 if (PL_curinterp != aTHX)
2853 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2856 #endif /* !HAS_SIGACTION */
2857 #endif /* !PERL_MICRO */
2859 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2860 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2862 Perl_my_pclose(pTHX_ PerlIO *ptr)
2865 Sigsave_t hstat, istat, qstat;
2871 int saved_errno = 0;
2873 int saved_win32_errno;
2877 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2879 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2881 *svp = &PL_sv_undef;
2883 if (pid == -1) { /* Opened by popen. */
2884 return my_syspclose(ptr);
2887 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2888 saved_errno = errno;
2890 saved_win32_errno = GetLastError();
2894 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2897 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2898 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2899 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2902 pid2 = wait4pid(pid, &status, 0);
2903 } while (pid2 == -1 && errno == EINTR);
2905 rsignal_restore(SIGHUP, &hstat);
2906 rsignal_restore(SIGINT, &istat);
2907 rsignal_restore(SIGQUIT, &qstat);
2910 SETERRNO(saved_errno, 0);
2913 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2916 #if defined(__LIBCATAMOUNT__)
2918 Perl_my_pclose(pTHX_ PerlIO *ptr)
2923 #endif /* !DOSISH */
2925 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2927 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2931 PERL_ARGS_ASSERT_WAIT4PID;
2934 #ifdef PERL_USES_PL_PIDSTATUS
2937 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2938 pid, rather than a string form. */
2939 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2940 if (svp && *svp != &PL_sv_undef) {
2941 *statusp = SvIVX(*svp);
2942 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2950 hv_iterinit(PL_pidstatus);
2951 if ((entry = hv_iternext(PL_pidstatus))) {
2952 SV * const sv = hv_iterval(PL_pidstatus,entry);
2954 const char * const spid = hv_iterkey(entry,&len);
2956 assert (len == sizeof(Pid_t));
2957 memcpy((char *)&pid, spid, len);
2958 *statusp = SvIVX(sv);
2959 /* The hash iterator is currently on this entry, so simply
2960 calling hv_delete would trigger the lazy delete, which on
2961 aggregate does more work, beacuse next call to hv_iterinit()
2962 would spot the flag, and have to call the delete routine,
2963 while in the meantime any new entries can't re-use that
2965 hv_iterinit(PL_pidstatus);
2966 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2973 # ifdef HAS_WAITPID_RUNTIME
2974 if (!HAS_WAITPID_RUNTIME)
2977 result = PerlProc_waitpid(pid,statusp,flags);
2980 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2981 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
2984 #ifdef PERL_USES_PL_PIDSTATUS
2985 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2990 Perl_croak(aTHX_ "Can't do waitpid with flags");
2992 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2993 pidgone(result,*statusp);
2999 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3002 if (result < 0 && errno == EINTR) {
3007 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3009 #ifdef PERL_USES_PL_PIDSTATUS
3011 Perl_pidgone(pTHX_ Pid_t pid, int status)
3015 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3016 SvUPGRADE(sv,SVt_IV);
3017 SvIV_set(sv, status);
3022 #if defined(atarist) || defined(OS2) || defined(EPOC)
3025 int /* Cannot prototype with I32
3027 my_syspclose(PerlIO *ptr)
3030 Perl_my_pclose(pTHX_ PerlIO *ptr)
3033 /* Needs work for PerlIO ! */
3034 FILE * const f = PerlIO_findFILE(ptr);
3035 const I32 result = pclose(f);
3036 PerlIO_releaseFILE(ptr,f);
3044 Perl_my_pclose(pTHX_ PerlIO *ptr)
3046 /* Needs work for PerlIO ! */
3047 FILE * const f = PerlIO_findFILE(ptr);
3048 I32 result = djgpp_pclose(f);
3049 result = (result << 8) & 0xff00;
3050 PerlIO_releaseFILE(ptr,f);
3056 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
3059 register const char * const frombase = from;
3060 PERL_UNUSED_CONTEXT;
3062 PERL_ARGS_ASSERT_REPEATCPY;
3065 register const char c = *from;
3070 while (count-- > 0) {
3071 for (todo = len; todo > 0; todo--) {
3080 Perl_same_dirent(pTHX_ const char *a, const char *b)
3082 char *fa = strrchr(a,'/');
3083 char *fb = strrchr(b,'/');
3086 SV * const tmpsv = sv_newmortal();
3088 PERL_ARGS_ASSERT_SAME_DIRENT;
3101 sv_setpvn(tmpsv, ".", 1);
3103 sv_setpvn(tmpsv, a, fa - a);
3104 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3107 sv_setpvn(tmpsv, ".", 1);
3109 sv_setpvn(tmpsv, b, fb - b);
3110 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3112 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3113 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3115 #endif /* !HAS_RENAME */
3118 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3119 const char *const *const search_ext, I32 flags)
3122 const char *xfound = NULL;
3123 char *xfailed = NULL;
3124 char tmpbuf[MAXPATHLEN];
3129 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3130 # define SEARCH_EXTS ".bat", ".cmd", NULL
3131 # define MAX_EXT_LEN 4
3134 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3135 # define MAX_EXT_LEN 4
3138 # define SEARCH_EXTS ".pl", ".com", NULL
3139 # define MAX_EXT_LEN 4
3141 /* additional extensions to try in each dir if scriptname not found */
3143 static const char *const exts[] = { SEARCH_EXTS };
3144 const char *const *const ext = search_ext ? search_ext : exts;
3145 int extidx = 0, i = 0;
3146 const char *curext = NULL;
3148 PERL_UNUSED_ARG(search_ext);
3149 # define MAX_EXT_LEN 0
3152 PERL_ARGS_ASSERT_FIND_SCRIPT;
3155 * If dosearch is true and if scriptname does not contain path
3156 * delimiters, search the PATH for scriptname.
3158 * If SEARCH_EXTS is also defined, will look for each
3159 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3160 * while searching the PATH.
3162 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3163 * proceeds as follows:
3164 * If DOSISH or VMSISH:
3165 * + look for ./scriptname{,.foo,.bar}
3166 * + search the PATH for scriptname{,.foo,.bar}
3169 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3170 * this will not look in '.' if it's not in the PATH)
3175 # ifdef ALWAYS_DEFTYPES
3176 len = strlen(scriptname);
3177 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3178 int idx = 0, deftypes = 1;
3181 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3184 int idx = 0, deftypes = 1;
3187 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3189 /* The first time through, just add SEARCH_EXTS to whatever we
3190 * already have, so we can check for default file types. */
3192 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3198 if ((strlen(tmpbuf) + strlen(scriptname)
3199 + MAX_EXT_LEN) >= sizeof tmpbuf)
3200 continue; /* don't search dir with too-long name */
3201 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3205 if (strEQ(scriptname, "-"))
3207 if (dosearch) { /* Look in '.' first. */
3208 const char *cur = scriptname;
3210 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3212 if (strEQ(ext[i++],curext)) {
3213 extidx = -1; /* already has an ext */
3218 DEBUG_p(PerlIO_printf(Perl_debug_log,
3219 "Looking for %s\n",cur));
3220 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3221 && !S_ISDIR(PL_statbuf.st_mode)) {
3229 if (cur == scriptname) {
3230 len = strlen(scriptname);
3231 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3233 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3236 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3237 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3242 #ifdef MACOS_TRADITIONAL
3243 if (dosearch && !strchr(scriptname, ':') &&
3244 (s = PerlEnv_getenv("Commands")))
3246 if (dosearch && !strchr(scriptname, '/')
3248 && !strchr(scriptname, '\\')
3250 && (s = PerlEnv_getenv("PATH")))
3255 bufend = s + strlen(s);
3256 while (s < bufend) {
3257 #ifdef MACOS_TRADITIONAL
3258 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3262 #if defined(atarist) || defined(DOSISH)
3267 && *s != ';'; len++, s++) {
3268 if (len < sizeof tmpbuf)
3271 if (len < sizeof tmpbuf)
3273 #else /* ! (atarist || DOSISH) */
3274 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3277 #endif /* ! (atarist || DOSISH) */
3278 #endif /* MACOS_TRADITIONAL */
3281 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3282 continue; /* don't search dir with too-long name */
3283 #ifdef MACOS_TRADITIONAL
3284 if (len && tmpbuf[len - 1] != ':')
3285 tmpbuf[len++] = ':';
3288 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3289 && tmpbuf[len - 1] != '/'
3290 && tmpbuf[len - 1] != '\\'
3293 tmpbuf[len++] = '/';
3294 if (len == 2 && tmpbuf[0] == '.')
3297 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3301 len = strlen(tmpbuf);
3302 if (extidx > 0) /* reset after previous loop */
3306 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3307 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3308 if (S_ISDIR(PL_statbuf.st_mode)) {
3312 } while ( retval < 0 /* not there */
3313 && extidx>=0 && ext[extidx] /* try an extension? */
3314 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3319 if (S_ISREG(PL_statbuf.st_mode)
3320 && cando(S_IRUSR,TRUE,&PL_statbuf)
3321 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3322 && cando(S_IXUSR,TRUE,&PL_statbuf)
3326 xfound = tmpbuf; /* bingo! */
3330 xfailed = savepv(tmpbuf);
3333 if (!xfound && !seen_dot && !xfailed &&
3334 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3335 || S_ISDIR(PL_statbuf.st_mode)))
3337 seen_dot = 1; /* Disable message. */
3339 if (flags & 1) { /* do or die? */
3340 Perl_croak(aTHX_ "Can't %s %s%s%s",
3341 (xfailed ? "execute" : "find"),
3342 (xfailed ? xfailed : scriptname),
3343 (xfailed ? "" : " on PATH"),
3344 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3349 scriptname = xfound;
3351 return (scriptname ? savepv(scriptname) : NULL);
3354 #ifndef PERL_GET_CONTEXT_DEFINED
3357 Perl_get_context(void)
3360 #if defined(USE_ITHREADS)
3361 # ifdef OLD_PTHREADS_API
3363 if (pthread_getspecific(PL_thr_key, &t))
3364 Perl_croak_nocontext("panic: pthread_getspecific");
3367 # ifdef I_MACH_CTHREADS
3368 return (void*)cthread_data(cthread_self());
3370 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3379 Perl_set_context(void *t)
3382 PERL_ARGS_ASSERT_SET_CONTEXT;
3383 #if defined(USE_ITHREADS)
3384 # ifdef I_MACH_CTHREADS
3385 cthread_set_data(cthread_self(), t);
3387 if (pthread_setspecific(PL_thr_key, t))
3388 Perl_croak_nocontext("panic: pthread_setspecific");
3395 #endif /* !PERL_GET_CONTEXT_DEFINED */
3397 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3406 Perl_get_op_names(pTHX)
3408 PERL_UNUSED_CONTEXT;
3409 return (char **)PL_op_name;
3413 Perl_get_op_descs(pTHX)
3415 PERL_UNUSED_CONTEXT;
3416 return (char **)PL_op_desc;
3420 Perl_get_no_modify(pTHX)
3422 PERL_UNUSED_CONTEXT;
3423 return PL_no_modify;
3427 Perl_get_opargs(pTHX)
3429 PERL_UNUSED_CONTEXT;
3430 return (U32 *)PL_opargs;
3434 Perl_get_ppaddr(pTHX)
3437 PERL_UNUSED_CONTEXT;
3438 return (PPADDR_t*)PL_ppaddr;
3441 #ifndef HAS_GETENV_LEN
3443 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3445 char * const env_trans = PerlEnv_getenv(env_elem);
3446 PERL_UNUSED_CONTEXT;
3447 PERL_ARGS_ASSERT_GETENV_LEN;
3449 *len = strlen(env_trans);
3456 Perl_get_vtbl(pTHX_ int vtbl_id)
3458 const MGVTBL* result;
3459 PERL_UNUSED_CONTEXT;
3463 result = &PL_vtbl_sv;
3466 result = &PL_vtbl_env;
3468 case want_vtbl_envelem:
3469 result = &PL_vtbl_envelem;
3472 result = &PL_vtbl_sig;
3474 case want_vtbl_sigelem:
3475 result = &PL_vtbl_sigelem;
3477 case want_vtbl_pack:
3478 result = &PL_vtbl_pack;
3480 case want_vtbl_packelem:
3481 result = &PL_vtbl_packelem;
3483 case want_vtbl_dbline:
3484 result = &PL_vtbl_dbline;
3487 result = &PL_vtbl_isa;
3489 case want_vtbl_isaelem:
3490 result = &PL_vtbl_isaelem;
3492 case want_vtbl_arylen:
3493 result = &PL_vtbl_arylen;
3495 case want_vtbl_mglob:
3496 result = &PL_vtbl_mglob;
3498 case want_vtbl_nkeys:
3499 result = &PL_vtbl_nkeys;
3501 case want_vtbl_taint:
3502 result = &PL_vtbl_taint;
3504 case want_vtbl_substr:
3505 result = &PL_vtbl_substr;
3508 result = &PL_vtbl_vec;
3511 result = &PL_vtbl_pos;
3514 result = &PL_vtbl_bm;
3517 result = &PL_vtbl_fm;
3519 case want_vtbl_uvar:
3520 result = &PL_vtbl_uvar;
3522 case want_vtbl_defelem:
3523 result = &PL_vtbl_defelem;
3525 case want_vtbl_regexp:
3526 result = &PL_vtbl_regexp;
3528 case want_vtbl_regdata:
3529 result = &PL_vtbl_regdata;
3531 case want_vtbl_regdatum:
3532 result = &PL_vtbl_regdatum;
3534 #ifdef USE_LOCALE_COLLATE
3535 case want_vtbl_collxfrm:
3536 result = &PL_vtbl_collxfrm;
3539 case want_vtbl_amagic:
3540 result = &PL_vtbl_amagic;
3542 case want_vtbl_amagicelem:
3543 result = &PL_vtbl_amagicelem;
3545 case want_vtbl_backref:
3546 result = &PL_vtbl_backref;
3548 case want_vtbl_utf8:
3549 result = &PL_vtbl_utf8;
3555 return (MGVTBL*)result;
3559 Perl_my_fflush_all(pTHX)
3561 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3562 return PerlIO_flush(NULL);
3564 # if defined(HAS__FWALK)
3565 extern int fflush(FILE *);
3566 /* undocumented, unprototyped, but very useful BSDism */
3567 extern void _fwalk(int (*)(FILE *));
3571 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3573 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3574 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3576 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3577 open_max = sysconf(_SC_OPEN_MAX);
3580 open_max = FOPEN_MAX;
3583 open_max = OPEN_MAX;
3594 for (i = 0; i < open_max; i++)
3595 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3596 STDIO_STREAM_ARRAY[i]._file < open_max &&
3597 STDIO_STREAM_ARRAY[i]._flag)
3598 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3602 SETERRNO(EBADF,RMS_IFI);
3609 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3611 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3613 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3614 if (ckWARN(WARN_IO)) {
3615 const char * const direction =
3616 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3618 Perl_warner(aTHX_ packWARN(WARN_IO),
3619 "Filehandle %s opened only for %sput",
3622 Perl_warner(aTHX_ packWARN(WARN_IO),
3623 "Filehandle opened only for %sput", direction);
3630 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3632 warn_type = WARN_CLOSED;
3636 warn_type = WARN_UNOPENED;
3639 if (ckWARN(warn_type)) {
3640 const char * const pars =
3641 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3642 const char * const func =
3644 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3645 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3646 op < 0 ? "" : /* handle phoney cases */
3648 const char * const type =
3650 (OP_IS_SOCKET(op) ||
3651 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3652 "socket" : "filehandle");
3653 if (name && *name) {
3654 Perl_warner(aTHX_ packWARN(warn_type),
3655 "%s%s on %s %s %s", func, pars, vile, type, name);
3656 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3658 aTHX_ packWARN(warn_type),
3659 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3664 Perl_warner(aTHX_ packWARN(warn_type),
3665 "%s%s on %s %s", func, pars, vile, type);
3666 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3668 aTHX_ packWARN(warn_type),
3669 "\t(Are you trying to call %s%s on dirhandle?)\n",
3678 /* in ASCII order, not that it matters */
3679 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3682 Perl_ebcdic_control(pTHX_ int ch)
3690 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3691 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3694 if (ctlp == controllablechars)
3695 return('\177'); /* DEL */
3697 return((unsigned char)(ctlp - controllablechars - 1));
3698 } else { /* Want uncontrol */
3699 if (ch == '\177' || ch == -1)
3701 else if (ch == '\157')
3703 else if (ch == '\174')
3705 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3707 else if (ch == '\155')
3709 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3710 return(controllablechars[ch+1]);
3712 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3717 /* To workaround core dumps from the uninitialised tm_zone we get the
3718 * system to give us a reasonable struct to copy. This fix means that
3719 * strftime uses the tm_zone and tm_gmtoff values returned by
3720 * localtime(time()). That should give the desired result most of the
3721 * time. But probably not always!
3723 * This does not address tzname aspects of NETaa14816.
3728 # ifndef STRUCT_TM_HASZONE
3729 # define STRUCT_TM_HASZONE
3733 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3734 # ifndef HAS_TM_TM_ZONE
3735 # define HAS_TM_TM_ZONE
3740 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3742 #ifdef HAS_TM_TM_ZONE
3744 const struct tm* my_tm;
3745 PERL_ARGS_ASSERT_INIT_TM;
3747 my_tm = localtime(&now);
3749 Copy(my_tm, ptm, 1, struct tm);
3751 PERL_ARGS_ASSERT_INIT_TM;
3752 PERL_UNUSED_ARG(ptm);
3757 * mini_mktime - normalise struct tm values without the localtime()
3758 * semantics (and overhead) of mktime().
3761 Perl_mini_mktime(pTHX_ struct tm *ptm)
3765 int month, mday, year, jday;
3766 int odd_cent, odd_year;
3767 PERL_UNUSED_CONTEXT;
3769 PERL_ARGS_ASSERT_MINI_MKTIME;
3771 #define DAYS_PER_YEAR 365
3772 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3773 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3774 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3775 #define SECS_PER_HOUR (60*60)
3776 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3777 /* parentheses deliberately absent on these two, otherwise they don't work */
3778 #define MONTH_TO_DAYS 153/5
3779 #define DAYS_TO_MONTH 5/153
3780 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3781 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3782 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3783 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3786 * Year/day algorithm notes:
3788 * With a suitable offset for numeric value of the month, one can find
3789 * an offset into the year by considering months to have 30.6 (153/5) days,
3790 * using integer arithmetic (i.e., with truncation). To avoid too much
3791 * messing about with leap days, we consider January and February to be
3792 * the 13th and 14th month of the previous year. After that transformation,
3793 * we need the month index we use to be high by 1 from 'normal human' usage,
3794 * so the month index values we use run from 4 through 15.
3796 * Given that, and the rules for the Gregorian calendar (leap years are those
3797 * divisible by 4 unless also divisible by 100, when they must be divisible
3798 * by 400 instead), we can simply calculate the number of days since some
3799 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3800 * the days we derive from our month index, and adding in the day of the
3801 * month. The value used here is not adjusted for the actual origin which
3802 * it normally would use (1 January A.D. 1), since we're not exposing it.
3803 * We're only building the value so we can turn around and get the
3804 * normalised values for the year, month, day-of-month, and day-of-year.
3806 * For going backward, we need to bias the value we're using so that we find
3807 * the right year value. (Basically, we don't want the contribution of
3808 * March 1st to the number to apply while deriving the year). Having done
3809 * that, we 'count up' the contribution to the year number by accounting for
3810 * full quadracenturies (400-year periods) with their extra leap days, plus
3811 * the contribution from full centuries (to avoid counting in the lost leap
3812 * days), plus the contribution from full quad-years (to count in the normal
3813 * leap days), plus the leftover contribution from any non-leap years.
3814 * At this point, if we were working with an actual leap day, we'll have 0
3815 * days left over. This is also true for March 1st, however. So, we have
3816 * to special-case that result, and (earlier) keep track of the 'odd'
3817 * century and year contributions. If we got 4 extra centuries in a qcent,
3818 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3819 * Otherwise, we add back in the earlier bias we removed (the 123 from
3820 * figuring in March 1st), find the month index (integer division by 30.6),
3821 * and the remainder is the day-of-month. We then have to convert back to
3822 * 'real' months (including fixing January and February from being 14/15 in
3823 * the previous year to being in the proper year). After that, to get
3824 * tm_yday, we work with the normalised year and get a new yearday value for
3825 * January 1st, which we subtract from the yearday value we had earlier,
3826 * representing the date we've re-built. This is done from January 1
3827 * because tm_yday is 0-origin.
3829 * Since POSIX time routines are only guaranteed to work for times since the
3830 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3831 * applies Gregorian calendar rules even to dates before the 16th century
3832 * doesn't bother me. Besides, you'd need cultural context for a given
3833 * date to know whether it was Julian or Gregorian calendar, and that's
3834 * outside the scope for this routine. Since we convert back based on the
3835 * same rules we used to build the yearday, you'll only get strange results
3836 * for input which needed normalising, or for the 'odd' century years which
3837 * were leap years in the Julian calander but not in the Gregorian one.
3838 * I can live with that.
3840 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3841 * that's still outside the scope for POSIX time manipulation, so I don't
3845 year = 1900 + ptm->tm_year;
3846 month = ptm->tm_mon;
3847 mday = ptm->tm_mday;
3848 /* allow given yday with no month & mday to dominate the result */
3849 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3852 jday = 1 + ptm->tm_yday;
3861 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3862 yearday += month*MONTH_TO_DAYS + mday + jday;
3864 * Note that we don't know when leap-seconds were or will be,
3865 * so we have to trust the user if we get something which looks
3866 * like a sensible leap-second. Wild values for seconds will
3867 * be rationalised, however.
3869 if ((unsigned) ptm->tm_sec <= 60) {
3876 secs += 60 * ptm->tm_min;
3877 secs += SECS_PER_HOUR * ptm->tm_hour;
3879 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3880 /* got negative remainder, but need positive time */
3881 /* back off an extra day to compensate */
3882 yearday += (secs/SECS_PER_DAY)-1;
3883 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3886 yearday += (secs/SECS_PER_DAY);
3887 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3890 else if (secs >= SECS_PER_DAY) {
3891 yearday += (secs/SECS_PER_DAY);
3892 secs %= SECS_PER_DAY;
3894 ptm->tm_hour = secs/SECS_PER_HOUR;
3895 secs %= SECS_PER_HOUR;
3896 ptm->tm_min = secs/60;
3898 ptm->tm_sec += secs;
3899 /* done with time of day effects */
3901 * The algorithm for yearday has (so far) left it high by 428.
3902 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3903 * bias it by 123 while trying to figure out what year it
3904 * really represents. Even with this tweak, the reverse
3905 * translation fails for years before A.D. 0001.
3906 * It would still fail for Feb 29, but we catch that one below.
3908 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3909 yearday -= YEAR_ADJUST;
3910 year = (yearday / DAYS_PER_QCENT) * 400;
3911 yearday %= DAYS_PER_QCENT;
3912 odd_cent = yearday / DAYS_PER_CENT;
3913 year += odd_cent * 100;
3914 yearday %= DAYS_PER_CENT;
3915 year += (yearday / DAYS_PER_QYEAR) * 4;
3916 yearday %= DAYS_PER_QYEAR;
3917 odd_year = yearday / DAYS_PER_YEAR;
3919 yearday %= DAYS_PER_YEAR;
3920 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3925 yearday += YEAR_ADJUST; /* recover March 1st crock */
3926 month = yearday*DAYS_TO_MONTH;
3927 yearday -= month*MONTH_TO_DAYS;
3928 /* recover other leap-year adjustment */
3937 ptm->tm_year = year - 1900;
3939 ptm->tm_mday = yearday;
3940 ptm->tm_mon = month;
3944 ptm->tm_mon = month - 1;
3946 /* re-build yearday based on Jan 1 to get tm_yday */
3948 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3949 yearday += 14*MONTH_TO_DAYS + 1;
3950 ptm->tm_yday = jday - yearday;
3951 /* fix tm_wday if not overridden by caller */
3952 if ((unsigned)ptm->tm_wday > 6)
3953 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3957 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)
3965 PERL_ARGS_ASSERT_MY_STRFTIME;
3967 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3970 mytm.tm_hour = hour;
3971 mytm.tm_mday = mday;
3973 mytm.tm_year = year;
3974 mytm.tm_wday = wday;
3975 mytm.tm_yday = yday;
3976 mytm.tm_isdst = isdst;
3978 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3979 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3984 #ifdef HAS_TM_TM_GMTOFF
3985 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3987 #ifdef HAS_TM_TM_ZONE
3988 mytm.tm_zone = mytm2.tm_zone;
3993 Newx(buf, buflen, char);
3994 len = strftime(buf, buflen, fmt, &mytm);
3996 ** The following is needed to handle to the situation where
3997 ** tmpbuf overflows. Basically we want to allocate a buffer
3998 ** and try repeatedly. The reason why it is so complicated
3999 ** is that getting a return value of 0 from strftime can indicate
4000 ** one of the following:
4001 ** 1. buffer overflowed,
4002 ** 2. illegal conversion specifier, or
4003 ** 3. the format string specifies nothing to be returned(not
4004 ** an error). This could be because format is an empty string
4005 ** or it specifies %p that yields an empty string in some locale.
4006 ** If there is a better way to make it portable, go ahead by
4009 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4012 /* Possibly buf overflowed - try again with a bigger buf */
4013 const int fmtlen = strlen(fmt);
4014 int bufsize = fmtlen + buflen;
4016 Newx(buf, bufsize, char);
4018 buflen = strftime(buf, bufsize, fmt, &mytm);
4019 if (buflen > 0 && buflen < bufsize)
4021 /* heuristic to prevent out-of-memory errors */
4022 if (bufsize > 100*fmtlen) {
4028 Renew(buf, bufsize, char);
4033 Perl_croak(aTHX_ "panic: no strftime");
4039 #define SV_CWD_RETURN_UNDEF \
4040 sv_setsv(sv, &PL_sv_undef); \
4043 #define SV_CWD_ISDOT(dp) \
4044 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4045 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4048 =head1 Miscellaneous Functions
4050 =for apidoc getcwd_sv
4052 Fill the sv with current working directory
4057 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4058 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4059 * getcwd(3) if available
4060 * Comments from the orignal:
4061 * This is a faster version of getcwd. It's also more dangerous
4062 * because you might chdir out of a directory that you can't chdir
4066 Perl_getcwd_sv(pTHX_ register SV *sv)
4070 #ifndef INCOMPLETE_TAINTS
4074 PERL_ARGS_ASSERT_GETCWD_SV;
4078 char buf[MAXPATHLEN];
4080 /* Some getcwd()s automatically allocate a buffer of the given
4081 * size from the heap if they are given a NULL buffer pointer.
4082 * The problem is that this behaviour is not portable. */
4083 if (getcwd(buf, sizeof(buf) - 1)) {
4088 sv_setsv(sv, &PL_sv_undef);
4096 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4100 SvUPGRADE(sv, SVt_PV);
4102 if (PerlLIO_lstat(".", &statbuf) < 0) {
4103 SV_CWD_RETURN_UNDEF;
4106 orig_cdev = statbuf.st_dev;
4107 orig_cino = statbuf.st_ino;
4116 if (PerlDir_chdir("..") < 0) {
4117 SV_CWD_RETURN_UNDEF;
4119 if (PerlLIO_stat(".", &statbuf) < 0) {
4120 SV_CWD_RETURN_UNDEF;
4123 cdev = statbuf.st_dev;
4124 cino = statbuf.st_ino;
4126 if (odev == cdev && oino == cino) {
4129 if (!(dir = PerlDir_open("."))) {
4130 SV_CWD_RETURN_UNDEF;
4133 while ((dp = PerlDir_read(dir)) != NULL) {
4135 const int namelen = dp->d_namlen;
4137 const int namelen = strlen(dp->d_name);
4140 if (SV_CWD_ISDOT(dp)) {
4144 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4145 SV_CWD_RETURN_UNDEF;
4148 tdev = statbuf.st_dev;
4149 tino = statbuf.st_ino;
4150 if (tino == oino && tdev == odev) {
4156 SV_CWD_RETURN_UNDEF;
4159 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4160 SV_CWD_RETURN_UNDEF;
4163 SvGROW(sv, pathlen + namelen + 1);
4167 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4170 /* prepend current directory to the front */
4172 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4173 pathlen += (namelen + 1);
4175 #ifdef VOID_CLOSEDIR
4178 if (PerlDir_close(dir) < 0) {
4179 SV_CWD_RETURN_UNDEF;
4185 SvCUR_set(sv, pathlen);
4189 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4190 SV_CWD_RETURN_UNDEF;
4193 if (PerlLIO_stat(".", &statbuf) < 0) {
4194 SV_CWD_RETURN_UNDEF;
4197 cdev = statbuf.st_dev;
4198 cino = statbuf.st_ino;
4200 if (cdev != orig_cdev || cino != orig_cino) {
4201 Perl_croak(aTHX_ "Unstable directory path, "
4202 "current directory changed unexpectedly");
4213 #define VERSION_MAX 0x7FFFFFFF
4215 =for apidoc scan_version
4217 Returns a pointer to the next character after the parsed
4218 version string, as well as upgrading the passed in SV to
4221 Function must be called with an already existing SV like
4224 s = scan_version(s, SV *sv, bool qv);
4226 Performs some preprocessing to the string to ensure that
4227 it has the correct characteristics of a version. Flags the
4228 object if it contains an underscore (which denotes this
4229 is an alpha version). The boolean qv denotes that the version
4230 should be interpreted as if it had multiple decimals, even if
4237 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4246 AV * const av = newAV();
4247 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4249 PERL_ARGS_ASSERT_SCAN_VERSION;
4251 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4253 while (isSPACE(*s)) /* leading whitespace is OK */
4259 s++; /* get past 'v' */
4260 qv = 1; /* force quoted version processing */
4265 /* pre-scan the input string to check for decimals/underbars */
4266 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4271 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4275 else if ( *pos == '_' )
4278 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4280 width = pos - last - 1; /* natural width of sub-version */
4285 if ( alpha && !saw_period )
4286 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4288 if ( alpha && saw_period && width == 0 )
4289 Perl_croak(aTHX_ "Invalid version format (misplaced _ in number)");
4291 if ( saw_period > 1 )
4292 qv = 1; /* force quoted version processing */
4298 (void)hv_stores((HV *)hv, "qv", newSViv(qv));
4300 (void)hv_stores((HV *)hv, "alpha", newSViv(alpha));
4301 if ( !qv && width < 3 )
4302 (void)hv_stores((HV *)hv, "width", newSViv(width));
4304 while (isDIGIT(*pos))
4306 if (!isALPHA(*pos)) {
4312 /* this is atoi() that delimits on underscores */
4313 const char *end = pos;
4317 /* the following if() will only be true after the decimal
4318 * point of a version originally created with a bare
4319 * floating point number, i.e. not quoted in any way
4321 if ( !qv && s > start && saw_period == 1 ) {
4325 rev += (*s - '0') * mult;
4327 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4328 || (PERL_ABS(rev) > VERSION_MAX )) {
4329 if(ckWARN(WARN_OVERFLOW))
4330 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4331 "Integer overflow in version %d",VERSION_MAX);
4342 while (--end >= s) {
4344 rev += (*end - '0') * mult;
4346 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4347 || (PERL_ABS(rev) > VERSION_MAX )) {
4348 if(ckWARN(WARN_OVERFLOW))
4349 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4350 "Integer overflow in version");
4359 /* Append revision */
4360 av_push(av, newSViv(rev));
4365 else if ( *pos == '.' )
4367 else if ( *pos == '_' && isDIGIT(pos[1]) )
4369 else if ( isDIGIT(*pos) )
4376 while ( isDIGIT(*pos) )
4381 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4389 if ( qv ) { /* quoted versions always get at least three terms*/
4390 I32 len = av_len(av);
4391 /* This for loop appears to trigger a compiler bug on OS X, as it
4392 loops infinitely. Yes, len is negative. No, it makes no sense.
4393 Compiler in question is:
4394 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4395 for ( len = 2 - len; len > 0; len-- )
4396 av_push((AV *)sv, newSViv(0));
4400 av_push(av, newSViv(0));
4403 /* need to save off the current version string for later */
4405 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4406 (void)hv_stores((HV *)hv, "original", orig);
4407 (void)hv_stores((HV *)hv, "vinf", newSViv(1));
4409 else if ( s > start ) {
4410 SV * orig = newSVpvn(start,s-start);
4411 if ( qv && saw_period == 1 && *start != 'v' ) {
4412 /* need to insert a v to be consistent */
4413 sv_insert(orig, 0, 0, "v", 1);
4415 (void)hv_stores((HV *)hv, "original", orig);
4418 (void)hv_stores((HV *)hv, "original", newSVpvn("0",1));
4419 av_push(av, newSViv(0));
4422 /* And finally, store the AV in the hash */
4423 (void)hv_stores((HV *)hv, "version", newRV_noinc((SV *)av));
4425 /* fix RT#19517 - special case 'undef' as string */
4426 if ( *s == 'u' && strEQ(s,"undef") ) {
4434 =for apidoc new_version
4436 Returns a new version object based on the passed in SV:
4438 SV *sv = new_version(SV *ver);
4440 Does not alter the passed in ver SV. See "upg_version" if you
4441 want to upgrade the SV.
4447 Perl_new_version(pTHX_ SV *ver)
4450 SV * const rv = newSV(0);
4451 PERL_ARGS_ASSERT_NEW_VERSION;
4452 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4455 AV * const av = newAV();
4457 /* This will get reblessed later if a derived class*/
4458 SV * const hv = newSVrv(rv, "version");
4459 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4464 /* Begin copying all of the elements */
4465 if ( hv_exists((HV *)ver, "qv", 2) )
4466 (void)hv_stores((HV *)hv, "qv", newSViv(1));
4468 if ( hv_exists((HV *)ver, "alpha", 5) )
4469 (void)hv_stores((HV *)hv, "alpha", newSViv(1));
4471 if ( hv_exists((HV*)ver, "width", 5 ) )
4473 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4474 (void)hv_stores((HV *)hv, "width", newSViv(width));
4477 if ( hv_exists((HV*)ver, "original", 8 ) )
4479 SV * pv = *hv_fetchs((HV*)ver, "original", FALSE);
4480 (void)hv_stores((HV *)hv, "original", newSVsv(pv));
4483 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4484 /* This will get reblessed later if a derived class*/
4485 for ( key = 0; key <= av_len(sav); key++ )
4487 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4488 av_push(av, newSViv(rev));
4491 (void)hv_stores((HV *)hv, "version", newRV_noinc((SV *)av));
4496 const MAGIC* const mg = SvVSTRING_mg(ver);
4497 if ( mg ) { /* already a v-string */
4498 const STRLEN len = mg->mg_len;
4499 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4500 sv_setpvn(rv,version,len);
4501 /* this is for consistency with the pure Perl class */
4502 if ( *version != 'v' )
4503 sv_insert(rv, 0, 0, "v", 1);
4508 sv_setsv(rv,ver); /* make a duplicate */
4513 return upg_version(rv, FALSE);
4517 =for apidoc upg_version
4519 In-place upgrade of the supplied SV to a version object.
4521 SV *sv = upg_version(SV *sv, bool qv);
4523 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4524 to force this SV to be interpreted as an "extended" version.
4530 Perl_upg_version(pTHX_ SV *ver, bool qv)
4532 const char *version, *s;
4537 PERL_ARGS_ASSERT_UPG_VERSION;
4539 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4541 /* may get too much accuracy */
4543 #ifdef USE_LOCALE_NUMERIC
4544 char *loc = setlocale(LC_NUMERIC, "C");
4546 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4547 #ifdef USE_LOCALE_NUMERIC
4548 setlocale(LC_NUMERIC, loc);
4550 while (tbuf[len-1] == '0' && len > 0) len--;
4551 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4552 version = savepvn(tbuf, len);
4555 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4556 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4560 else /* must be a string or something like a string */
4563 version = savepv(SvPV(ver,len));
4565 # if PERL_VERSION > 5
4566 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4567 if ( len == 3 && !instr(version,".") && !instr(version,"_") ) {
4568 /* may be a v-string */
4569 SV * const nsv = sv_newmortal();
4573 sv_setpvf(nsv,"v%vd",ver);
4574 pos = nver = savepv(SvPV_nolen(nsv));
4576 /* scan the resulting formatted string */
4577 pos++; /* skip the leading 'v' */
4578 while ( *pos == '.' || isDIGIT(*pos) ) {
4584 /* is definitely a v-string */
4585 if ( saw_period == 2 ) {
4594 s = scan_version(version, ver, qv);
4596 if(ckWARN(WARN_MISC))
4597 Perl_warner(aTHX_ packWARN(WARN_MISC),
4598 "Version string '%s' contains invalid data; "
4599 "ignoring: '%s'", version, s);
4607 Validates that the SV contains a valid version object.
4609 bool vverify(SV *vobj);
4611 Note that it only confirms the bare minimum structure (so as not to get
4612 confused by derived classes which may contain additional hash entries):
4616 =item * The SV contains a [reference to a] hash
4618 =item * The hash contains a "version" key
4620 =item * The "version" key has [a reference to] an AV as its value
4628 Perl_vverify(pTHX_ SV *vs)
4632 PERL_ARGS_ASSERT_VVERIFY;
4637 /* see if the appropriate elements exist */
4638 if ( SvTYPE(vs) == SVt_PVHV
4639 && hv_exists((HV*)vs, "version", 7)
4640 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4641 && SvTYPE(sv) == SVt_PVAV )
4650 Accepts a version object and returns the normalized floating
4651 point representation. Call like:
4655 NOTE: you can pass either the object directly or the SV
4656 contained within the RV.
4662 Perl_vnumify(pTHX_ SV *vs)
4667 SV * const sv = newSV(0);
4670 PERL_ARGS_ASSERT_VNUMIFY;
4676 Perl_croak(aTHX_ "Invalid version object");
4678 /* see if various flags exist */
4679 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4681 if ( hv_exists((HV*)vs, "width", 5 ) )
4682 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4687 /* attempt to retrieve the version array */
4688 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4700 digit = SvIV(*av_fetch(av, 0, 0));
4701 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4702 for ( i = 1 ; i < len ; i++ )
4704 digit = SvIV(*av_fetch(av, i, 0));
4706 const int denom = (width == 2 ? 10 : 100);
4707 const div_t term = div((int)PERL_ABS(digit),denom);
4708 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4711 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4717 digit = SvIV(*av_fetch(av, len, 0));
4718 if ( alpha && width == 3 ) /* alpha version */
4720 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4724 sv_catpvs(sv, "000");
4732 Accepts a version object and returns the normalized string
4733 representation. Call like:
4737 NOTE: you can pass either the object directly or the SV
4738 contained within the RV.
4744 Perl_vnormal(pTHX_ SV *vs)
4748 SV * const sv = newSV(0);
4751 PERL_ARGS_ASSERT_VNORMAL;
4757 Perl_croak(aTHX_ "Invalid version object");
4759 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4761 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4769 digit = SvIV(*av_fetch(av, 0, 0));
4770 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4771 for ( i = 1 ; i < len ; i++ ) {
4772 digit = SvIV(*av_fetch(av, i, 0));
4773 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4778 /* handle last digit specially */
4779 digit = SvIV(*av_fetch(av, len, 0));
4781 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4783 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4786 if ( len <= 2 ) { /* short version, must be at least three */
4787 for ( len = 2 - len; len != 0; len-- )
4794 =for apidoc vstringify
4796 In order to maintain maximum compatibility with earlier versions
4797 of Perl, this function will return either the floating point
4798 notation or the multiple dotted notation, depending on whether
4799 the original version contained 1 or more dots, respectively
4805 Perl_vstringify(pTHX_ SV *vs)
4809 PERL_ARGS_ASSERT_VSTRINGIFY;
4815 Perl_croak(aTHX_ "Invalid version object");
4817 pv = *hv_fetchs((HV*)vs, "original", FALSE);
4821 return &PL_sv_undef;
4827 Version object aware cmp. Both operands must already have been
4828 converted into version objects.
4834 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4837 bool lalpha = FALSE;
4838 bool ralpha = FALSE;
4843 PERL_ARGS_ASSERT_VCMP;
4850 if ( !vverify(lhv) )
4851 Perl_croak(aTHX_ "Invalid version object");
4853 if ( !vverify(rhv) )
4854 Perl_croak(aTHX_ "Invalid version object");
4856 /* get the left hand term */
4857 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4858 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4861 /* and the right hand term */
4862 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4863 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4871 while ( i <= m && retval == 0 )
4873 left = SvIV(*av_fetch(lav,i,0));
4874 right = SvIV(*av_fetch(rav,i,0));
4882 /* tiebreaker for alpha with identical terms */
4883 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4885 if ( lalpha && !ralpha )
4889 else if ( ralpha && !lalpha)
4895 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4899 while ( i <= r && retval == 0 )
4901 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4902 retval = -1; /* not a match after all */
4908 while ( i <= l && retval == 0 )
4910 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4911 retval = +1; /* not a match after all */
4919 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4920 # define EMULATE_SOCKETPAIR_UDP
4923 #ifdef EMULATE_SOCKETPAIR_UDP
4925 S_socketpair_udp (int fd[2]) {
4927 /* Fake a datagram socketpair using UDP to localhost. */
4928 int sockets[2] = {-1, -1};
4929 struct sockaddr_in addresses[2];
4931 Sock_size_t size = sizeof(struct sockaddr_in);
4932 unsigned short port;
4935 memset(&addresses, 0, sizeof(addresses));
4938 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4939 if (sockets[i] == -1)
4940 goto tidy_up_and_fail;
4942 addresses[i].sin_family = AF_INET;
4943 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4944 addresses[i].sin_port = 0; /* kernel choses port. */
4945 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4946 sizeof(struct sockaddr_in)) == -1)
4947 goto tidy_up_and_fail;
4950 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4951 for each connect the other socket to it. */
4954 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4956 goto tidy_up_and_fail;
4957 if (size != sizeof(struct sockaddr_in))
4958 goto abort_tidy_up_and_fail;
4959 /* !1 is 0, !0 is 1 */
4960 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4961 sizeof(struct sockaddr_in)) == -1)
4962 goto tidy_up_and_fail;
4965 /* Now we have 2 sockets connected to each other. I don't trust some other
4966 process not to have already sent a packet to us (by random) so send
4967 a packet from each to the other. */
4970 /* I'm going to send my own port number. As a short.
4971 (Who knows if someone somewhere has sin_port as a bitfield and needs
4972 this routine. (I'm assuming crays have socketpair)) */
4973 port = addresses[i].sin_port;
4974 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4975 if (got != sizeof(port)) {
4977 goto tidy_up_and_fail;
4978 goto abort_tidy_up_and_fail;
4982 /* Packets sent. I don't trust them to have arrived though.
4983 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4984 connect to localhost will use a second kernel thread. In 2.6 the
4985 first thread running the connect() returns before the second completes,
4986 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4987 returns 0. Poor programs have tripped up. One poor program's authors'
4988 had a 50-1 reverse stock split. Not sure how connected these were.)
4989 So I don't trust someone not to have an unpredictable UDP stack.
4993 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4994 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4998 FD_SET((unsigned int)sockets[0], &rset);
4999 FD_SET((unsigned int)sockets[1], &rset);
5001 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5002 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5003 || !FD_ISSET(sockets[1], &rset)) {
5004 /* I hope this is portable and appropriate. */
5006 goto tidy_up_and_fail;
5007 goto abort_tidy_up_and_fail;
5011 /* And the paranoia department even now doesn't trust it to have arrive
5012 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5014 struct sockaddr_in readfrom;
5015 unsigned short buffer[2];
5020 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5021 sizeof(buffer), MSG_DONTWAIT,
5022 (struct sockaddr *) &readfrom, &size);
5024 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5026 (struct sockaddr *) &readfrom, &size);
5030 goto tidy_up_and_fail;
5031 if (got != sizeof(port)
5032 || size != sizeof(struct sockaddr_in)
5033 /* Check other socket sent us its port. */
5034 || buffer[0] != (unsigned short) addresses[!i].sin_port
5035 /* Check kernel says we got the datagram from that socket */
5036 || readfrom.sin_family != addresses[!i].sin_family
5037 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5038 || readfrom.sin_port != addresses[!i].sin_port)
5039 goto abort_tidy_up_and_fail;
5042 /* My caller (my_socketpair) has validated that this is non-NULL */
5045 /* I hereby declare this connection open. May God bless all who cross
5049 abort_tidy_up_and_fail:
5050 errno = ECONNABORTED;
5053 const int save_errno = errno;
5054 if (sockets[0] != -1)
5055 PerlLIO_close(sockets[0]);
5056 if (sockets[1] != -1)
5057 PerlLIO_close(sockets[1]);
5062 #endif /* EMULATE_SOCKETPAIR_UDP */
5064 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5066 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5067 /* Stevens says that family must be AF_LOCAL, protocol 0.
5068 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5073 struct sockaddr_in listen_addr;
5074 struct sockaddr_in connect_addr;
5079 || family != AF_UNIX
5082 errno = EAFNOSUPPORT;
5090 #ifdef EMULATE_SOCKETPAIR_UDP
5091 if (type == SOCK_DGRAM)
5092 return S_socketpair_udp(fd);
5095 listener = PerlSock_socket(AF_INET, type, 0);
5098 memset(&listen_addr, 0, sizeof(listen_addr));
5099 listen_addr.sin_family = AF_INET;
5100 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5101 listen_addr.sin_port = 0; /* kernel choses port. */
5102 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5103 sizeof(listen_addr)) == -1)
5104 goto tidy_up_and_fail;
5105 if (PerlSock_listen(listener, 1) == -1)
5106 goto tidy_up_and_fail;
5108 connector = PerlSock_socket(AF_INET, type, 0);
5109 if (connector == -1)
5110 goto tidy_up_and_fail;
5111 /* We want to find out the port number to connect to. */
5112 size = sizeof(connect_addr);
5113 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5115 goto tidy_up_and_fail;
5116 if (size != sizeof(connect_addr))
5117 goto abort_tidy_up_and_fail;
5118 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5119 sizeof(connect_addr)) == -1)
5120 goto tidy_up_and_fail;
5122 size = sizeof(listen_addr);
5123 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5126 goto tidy_up_and_fail;
5127 if (size != sizeof(listen_addr))
5128 goto abort_tidy_up_and_fail;
5129 PerlLIO_close(listener);
5130 /* Now check we are talking to ourself by matching port and host on the
5132 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5134 goto tidy_up_and_fail;
5135 if (size != sizeof(connect_addr)
5136 || listen_addr.sin_family != connect_addr.sin_family
5137 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5138 || listen_addr.sin_port != connect_addr.sin_port) {
5139 goto abort_tidy_up_and_fail;
5145 abort_tidy_up_and_fail:
5147 errno = ECONNABORTED; /* This would be the standard thing to do. */
5149 # ifdef ECONNREFUSED
5150 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5152 errno = ETIMEDOUT; /* Desperation time. */
5157 const int save_errno = errno;
5159 PerlLIO_close(listener);
5160 if (connector != -1)
5161 PerlLIO_close(connector);
5163 PerlLIO_close(acceptor);
5169 /* In any case have a stub so that there's code corresponding
5170 * to the my_socketpair in global.sym. */
5172 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5173 #ifdef HAS_SOCKETPAIR
5174 return socketpair(family, type, protocol, fd);
5183 =for apidoc sv_nosharing
5185 Dummy routine which "shares" an SV when there is no sharing module present.
5186 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5187 Exists to avoid test for a NULL function pointer and because it could
5188 potentially warn under some level of strict-ness.
5194 Perl_sv_nosharing(pTHX_ SV *sv)
5196 PERL_UNUSED_CONTEXT;
5197 PERL_UNUSED_ARG(sv);
5202 =for apidoc sv_destroyable
5204 Dummy routine which reports that object can be destroyed when there is no
5205 sharing module present. It ignores its single SV argument, and returns
5206 'true'. Exists to avoid test for a NULL function pointer and because it
5207 could potentially warn under some level of strict-ness.
5213 Perl_sv_destroyable(pTHX_ SV *sv)
5215 PERL_UNUSED_CONTEXT;
5216 PERL_UNUSED_ARG(sv);
5221 Perl_parse_unicode_opts(pTHX_ const char **popt)
5223 const char *p = *popt;
5226 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5230 opt = (U32) atoi(p);
5233 if (*p && *p != '\n' && *p != '\r')
5234 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5239 case PERL_UNICODE_STDIN:
5240 opt |= PERL_UNICODE_STDIN_FLAG; break;
5241 case PERL_UNICODE_STDOUT:
5242 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5243 case PERL_UNICODE_STDERR:
5244 opt |= PERL_UNICODE_STDERR_FLAG; break;
5245 case PERL_UNICODE_STD:
5246 opt |= PERL_UNICODE_STD_FLAG; break;
5247 case PERL_UNICODE_IN:
5248 opt |= PERL_UNICODE_IN_FLAG; break;
5249 case PERL_UNICODE_OUT:
5250 opt |= PERL_UNICODE_OUT_FLAG; break;
5251 case PERL_UNICODE_INOUT:
5252 opt |= PERL_UNICODE_INOUT_FLAG; break;
5253 case PERL_UNICODE_LOCALE:
5254 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5255 case PERL_UNICODE_ARGV:
5256 opt |= PERL_UNICODE_ARGV_FLAG; break;
5257 case PERL_UNICODE_UTF8CACHEASSERT:
5258 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5260 if (*p != '\n' && *p != '\r')
5262 "Unknown Unicode option letter '%c'", *p);
5268 opt = PERL_UNICODE_DEFAULT_FLAGS;
5270 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5271 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5272 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5284 * This is really just a quick hack which grabs various garbage
5285 * values. It really should be a real hash algorithm which
5286 * spreads the effect of every input bit onto every output bit,
5287 * if someone who knows about such things would bother to write it.
5288 * Might be a good idea to add that function to CORE as well.
5289 * No numbers below come from careful analysis or anything here,
5290 * except they are primes and SEED_C1 > 1E6 to get a full-width
5291 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5292 * probably be bigger too.
5295 # define SEED_C1 1000003
5296 #define SEED_C4 73819
5298 # define SEED_C1 25747
5299 #define SEED_C4 20639
5303 #define SEED_C5 26107
5305 #ifndef PERL_NO_DEV_RANDOM
5310 # include <starlet.h>
5311 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5312 * in 100-ns units, typically incremented ever 10 ms. */
5313 unsigned int when[2];
5315 # ifdef HAS_GETTIMEOFDAY
5316 struct timeval when;
5322 /* This test is an escape hatch, this symbol isn't set by Configure. */
5323 #ifndef PERL_NO_DEV_RANDOM
5324 #ifndef PERL_RANDOM_DEVICE
5325 /* /dev/random isn't used by default because reads from it will block
5326 * if there isn't enough entropy available. You can compile with
5327 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5328 * is enough real entropy to fill the seed. */
5329 # define PERL_RANDOM_DEVICE "/dev/urandom"
5331 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5333 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5342 _ckvmssts(sys$gettim(when));
5343 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5345 # ifdef HAS_GETTIMEOFDAY
5346 PerlProc_gettimeofday(&when,NULL);
5347 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5350 u = (U32)SEED_C1 * when;
5353 u += SEED_C3 * (U32)PerlProc_getpid();
5354 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5355 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5356 u += SEED_C5 * (U32)PTR2UV(&when);
5362 Perl_get_hash_seed(pTHX)
5365 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5371 if (s && isDIGIT(*s))
5372 myseed = (UV)Atoul(s);
5374 #ifdef USE_HASH_SEED_EXPLICIT
5378 /* Compute a random seed */
5379 (void)seedDrand01((Rand_seed_t)seed());
5380 myseed = (UV)(Drand01() * (NV)UV_MAX);
5381 #if RANDBITS < (UVSIZE * 8)
5382 /* Since there are not enough randbits to to reach all
5383 * the bits of a UV, the low bits might need extra
5384 * help. Sum in another random number that will
5385 * fill in the low bits. */
5387 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
5388 #endif /* RANDBITS < (UVSIZE * 8) */
5389 if (myseed == 0) { /* Superparanoia. */
5390 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5392 Perl_croak(aTHX_ "Your random numbers are not that random");
5395 PL_rehash_seed_set = TRUE;
5402 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5404 const char * const stashpv = CopSTASHPV(c);
5405 const char * const name = HvNAME_get(hv);
5406 PERL_UNUSED_CONTEXT;
5407 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5409 if (stashpv == name)
5411 if (stashpv && name)
5412 if (strEQ(stashpv, name))
5419 #ifdef PERL_GLOBAL_STRUCT
5421 #define PERL_GLOBAL_STRUCT_INIT
5422 #include "opcode.h" /* the ppaddr and check */
5425 Perl_init_global_struct(pTHX)
5427 struct perl_vars *plvarsp = NULL;
5428 # ifdef PERL_GLOBAL_STRUCT
5429 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5430 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5431 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5432 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5433 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5437 plvarsp = PL_VarsPtr;
5438 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5444 # define PERLVAR(var,type) /**/
5445 # define PERLVARA(var,n,type) /**/
5446 # define PERLVARI(var,type,init) plvarsp->var = init;
5447 # define PERLVARIC(var,type,init) plvarsp->var = init;
5448 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5449 # include "perlvars.h"
5455 # ifdef PERL_GLOBAL_STRUCT
5458 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5459 if (!plvarsp->Gppaddr)
5463 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5464 if (!plvarsp->Gcheck)
5466 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5467 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5469 # ifdef PERL_SET_VARS
5470 PERL_SET_VARS(plvarsp);
5472 # undef PERL_GLOBAL_STRUCT_INIT
5477 #endif /* PERL_GLOBAL_STRUCT */
5479 #ifdef PERL_GLOBAL_STRUCT
5482 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5484 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5485 # ifdef PERL_GLOBAL_STRUCT
5486 # ifdef PERL_UNSET_VARS
5487 PERL_UNSET_VARS(plvarsp);
5489 free(plvarsp->Gppaddr);
5490 free(plvarsp->Gcheck);
5491 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5497 #endif /* PERL_GLOBAL_STRUCT */
5502 * PERL_MEM_LOG: the Perl_mem_log_..() will be compiled.
5504 * PERL_MEM_LOG_ENV: if defined, during run time the environment
5505 * variable PERL_MEM_LOG will be consulted, and if the integer value
5506 * of that is true, the logging will happen. (The default is to
5507 * always log if the PERL_MEM_LOG define was in effect.)
5511 * PERL_MEM_LOG_SPRINTF_BUF_SIZE: size of a (stack-allocated) buffer
5512 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5514 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5517 * PERL_MEM_LOG_FD: the file descriptor the Perl_mem_log_...() will
5518 * log to. You can also define in compile time PERL_MEM_LOG_ENV_FD,
5519 * in which case the environment variable PERL_MEM_LOG_FD will be
5520 * consulted for the file descriptor number to use.
5522 #ifndef PERL_MEM_LOG_FD
5523 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5527 Perl_mem_log_alloc(const UV n, const UV typesize, const char *typename, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5529 #ifdef PERL_MEM_LOG_STDERR
5530 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5533 # ifdef PERL_MEM_LOG_ENV
5534 s = getenv("PERL_MEM_LOG");
5535 if (s ? atoi(s) : 0)
5538 /* We can't use SVs or PerlIO for obvious reasons,
5539 * so we'll use stdio and low-level IO instead. */
5540 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5541 # ifdef PERL_MEM_LOG_TIMESTAMP
5543 # ifdef HAS_GETTIMEOFDAY
5544 gettimeofday(&tv, 0);
5546 /* If there are other OS specific ways of hires time than
5547 * gettimeofday() (see ext/Time/HiRes), the easiest way is
5548 * probably that they would be used to fill in the struct
5555 # ifdef PERL_MEM_LOG_TIMESTAMP
5558 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5559 " %s = %"IVdf": %"UVxf"\n",
5560 # ifdef PERL_MEM_LOG_TIMESTAMP
5561 (int)tv.tv_sec, (int)tv.tv_usec,
5563 filename, linenumber, funcname, n, typesize,
5564 typename, n * typesize, PTR2UV(newalloc));
5565 # ifdef PERL_MEM_LOG_ENV_FD
5566 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5567 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5569 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5578 Perl_mem_log_realloc(const UV n, const UV typesize, const char *typename, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5580 #ifdef PERL_MEM_LOG_STDERR
5581 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5584 # ifdef PERL_MEM_LOG_ENV
5585 s = PerlEnv_getenv("PERL_MEM_LOG");
5586 if (s ? atoi(s) : 0)
5589 /* We can't use SVs or PerlIO for obvious reasons,
5590 * so we'll use stdio and low-level IO instead. */
5591 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5592 # ifdef PERL_MEM_LOG_TIMESTAMP
5594 gettimeofday(&tv, 0);
5600 # ifdef PERL_MEM_LOG_TIMESTAMP
5603 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5604 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5605 # ifdef PERL_MEM_LOG_TIMESTAMP
5606 (int)tv.tv_sec, (int)tv.tv_usec,
5608 filename, linenumber, funcname, n, typesize,
5609 typename, n * typesize, PTR2UV(oldalloc),
5611 # ifdef PERL_MEM_LOG_ENV_FD
5612 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5613 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5615 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5624 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5626 #ifdef PERL_MEM_LOG_STDERR
5627 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5630 # ifdef PERL_MEM_LOG_ENV
5631 s = PerlEnv_getenv("PERL_MEM_LOG");
5632 if (s ? atoi(s) : 0)
5635 /* We can't use SVs or PerlIO for obvious reasons,
5636 * so we'll use stdio and low-level IO instead. */
5637 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5638 # ifdef PERL_MEM_LOG_TIMESTAMP
5640 gettimeofday(&tv, 0);
5646 # ifdef PERL_MEM_LOG_TIMESTAMP
5649 "free: %s:%d:%s: %"UVxf"\n",
5650 # ifdef PERL_MEM_LOG_TIMESTAMP
5651 (int)tv.tv_sec, (int)tv.tv_usec,
5653 filename, linenumber, funcname,
5655 # ifdef PERL_MEM_LOG_ENV_FD
5656 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5657 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5659 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5667 #endif /* PERL_MEM_LOG */
5670 =for apidoc my_sprintf
5672 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5673 the length of the string written to the buffer. Only rare pre-ANSI systems
5674 need the wrapper function - usually this is a direct call to C<sprintf>.
5678 #ifndef SPRINTF_RETURNS_STRLEN
5680 Perl_my_sprintf(char *buffer, const char* pat, ...)
5683 PERL_ARGS_ASSERT_MY_SPRINTF;
5684 va_start(args, pat);
5685 vsprintf(buffer, pat, args);
5687 return strlen(buffer);
5692 =for apidoc my_snprintf
5694 The C library C<snprintf> functionality, if available and
5695 standards-compliant (uses C<vsnprintf>, actually). However, if the
5696 C<vsnprintf> is not available, will unfortunately use the unsafe
5697 C<vsprintf> which can overrun the buffer (there is an overrun check,
5698 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5699 getting C<vsnprintf>.
5704 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5709 PERL_ARGS_ASSERT_MY_SNPRINTF;
5710 va_start(ap, format);
5711 #ifdef HAS_VSNPRINTF
5712 retval = vsnprintf(buffer, len, format, ap);
5714 retval = vsprintf(buffer, format, ap);
5717 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5718 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5719 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
5724 =for apidoc my_vsnprintf
5726 The C library C<vsnprintf> if available and standards-compliant.
5727 However, if if the C<vsnprintf> is not available, will unfortunately
5728 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5729 overrun check, but that may be too late). Consider using
5730 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5735 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5742 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5744 Perl_va_copy(ap, apc);
5745 # ifdef HAS_VSNPRINTF
5746 retval = vsnprintf(buffer, len, format, apc);
5748 retval = vsprintf(buffer, format, apc);
5751 # ifdef HAS_VSNPRINTF
5752 retval = vsnprintf(buffer, len, format, ap);
5754 retval = vsprintf(buffer, format, ap);
5756 #endif /* #ifdef NEED_VA_COPY */
5757 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5758 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5759 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
5764 Perl_my_clearenv(pTHX)
5767 #if ! defined(PERL_MICRO)
5768 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5770 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5771 # if defined(USE_ENVIRON_ARRAY)
5772 # if defined(USE_ITHREADS)
5773 /* only the parent thread can clobber the process environment */
5774 if (PL_curinterp == aTHX)
5775 # endif /* USE_ITHREADS */
5777 # if ! defined(PERL_USE_SAFE_PUTENV)
5778 if ( !PL_use_safe_putenv) {
5780 if (environ == PL_origenviron)
5781 environ = (char**)safesysmalloc(sizeof(char*));
5783 for (i = 0; environ[i]; i++)
5784 (void)safesysfree(environ[i]);
5787 # else /* PERL_USE_SAFE_PUTENV */
5788 # if defined(HAS_CLEARENV)
5790 # elif defined(HAS_UNSETENV)
5791 int bsiz = 80; /* Most envvar names will be shorter than this. */
5792 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
5793 char *buf = (char*)safesysmalloc(bufsiz);
5794 while (*environ != NULL) {
5795 char *e = strchr(*environ, '=');
5796 int l = e ? e - *environ : (int)strlen(*environ);
5798 (void)safesysfree(buf);
5799 bsiz = l + 1; /* + 1 for the \0. */
5800 buf = (char*)safesysmalloc(bufsiz);
5802 memcpy(buf, *environ, l);
5804 (void)unsetenv(buf);
5806 (void)safesysfree(buf);
5807 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5808 /* Just null environ and accept the leakage. */
5810 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5811 # endif /* ! PERL_USE_SAFE_PUTENV */
5813 # endif /* USE_ENVIRON_ARRAY */
5814 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5815 #endif /* PERL_MICRO */
5818 #ifdef PERL_IMPLICIT_CONTEXT
5820 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5821 the global PL_my_cxt_index is incremented, and that value is assigned to
5822 that module's static my_cxt_index (who's address is passed as an arg).
5823 Then, for each interpreter this function is called for, it makes sure a
5824 void* slot is available to hang the static data off, by allocating or
5825 extending the interpreter's PL_my_cxt_list array */
5827 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5829 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5833 PERL_ARGS_ASSERT_MY_CXT_INIT;
5835 /* this module hasn't been allocated an index yet */
5836 MUTEX_LOCK(&PL_my_ctx_mutex);
5837 *index = PL_my_cxt_index++;
5838 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5841 /* make sure the array is big enough */
5842 if (PL_my_cxt_size <= *index) {
5843 if (PL_my_cxt_size) {
5844 while (PL_my_cxt_size <= *index)
5845 PL_my_cxt_size *= 2;
5846 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5849 PL_my_cxt_size = 16;
5850 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5853 /* newSV() allocates one more than needed */
5854 p = (void*)SvPVX(newSV(size-1));
5855 PL_my_cxt_list[*index] = p;
5856 Zero(p, size, char);
5860 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5863 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5868 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5870 for (index = 0; index < PL_my_cxt_index; index++) {
5871 const char *key = PL_my_cxt_keys[index];
5872 /* try direct pointer compare first - there are chances to success,
5873 * and it's much faster.
5875 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5882 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5888 PERL_ARGS_ASSERT_MY_CXT_INIT;
5890 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5892 /* this module hasn't been allocated an index yet */
5893 MUTEX_LOCK(&PL_my_ctx_mutex);
5894 index = PL_my_cxt_index++;
5895 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5898 /* make sure the array is big enough */
5899 if (PL_my_cxt_size <= index) {
5900 int old_size = PL_my_cxt_size;
5902 if (PL_my_cxt_size) {
5903 while (PL_my_cxt_size <= index)
5904 PL_my_cxt_size *= 2;
5905 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5906 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5909 PL_my_cxt_size = 16;
5910 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5911 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5913 for (i = old_size; i < PL_my_cxt_size; i++) {
5914 PL_my_cxt_keys[i] = 0;
5915 PL_my_cxt_list[i] = 0;
5918 PL_my_cxt_keys[index] = my_cxt_key;
5919 /* newSV() allocates one more than needed */
5920 p = (void*)SvPVX(newSV(size-1));
5921 PL_my_cxt_list[index] = p;
5922 Zero(p, size, char);
5925 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5926 #endif /* PERL_IMPLICIT_CONTEXT */
5930 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5932 Size_t used, length, copy;
5935 length = strlen(src);
5936 if (size > 0 && used < size - 1) {
5937 copy = (length >= size - used) ? size - used - 1 : length;
5938 memcpy(dst + used, src, copy);
5939 dst[used + copy] = '\0';
5941 return used + length;
5947 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5949 Size_t length, copy;
5951 length = strlen(src);
5953 copy = (length >= size) ? size - 1 : length;
5954 memcpy(dst, src, copy);
5961 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5962 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5963 long _ftol( double ); /* Defined by VC6 C libs. */
5964 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5968 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5971 SV * const dbsv = GvSVn(PL_DBsub);
5972 /* We do not care about using sv to call CV;
5973 * it's for informational purposes only.
5976 PERL_ARGS_ASSERT_GET_DB_SUB;
5979 if (!PERLDB_SUB_NN) {
5980 GV * const gv = CvGV(cv);
5982 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
5983 || strEQ(GvNAME(gv), "END")
5984 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
5985 !( (SvTYPE(*svp) == SVt_PVGV) && (GvCV((GV*)*svp) == cv) )))) {
5986 /* Use GV from the stack as a fallback. */
5987 /* GV is potentially non-unique, or contain different CV. */
5988 SV * const tmp = newRV((SV*)cv);
5989 sv_setsv(dbsv, tmp);
5993 gv_efullname3(dbsv, gv, NULL);
5997 const int type = SvTYPE(dbsv);
5998 if (type < SVt_PVIV && type != SVt_IV)
5999 sv_upgrade(dbsv, SVt_PVIV);
6000 (void)SvIOK_on(dbsv);
6001 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6006 Perl_my_dirfd(pTHX_ DIR * dir) {
6008 /* Most dirfd implementations have problems when passed NULL. */
6013 #elif defined(HAS_DIR_DD_FD)
6016 Perl_die(aTHX_ PL_no_func, "dirfd");
6023 Perl_get_re_arg(pTHX_ SV *sv) {
6030 (tmpsv = (SV*)SvRV(sv)) && /* assign deliberate */
6031 SvTYPE(tmpsv) == SVt_REGEXP)
6033 return (REGEXP*) tmpsv;
6042 * c-indentation-style: bsd
6044 * indent-tabs-mode: t
6047 * ex: set ts=8 sts=4 sw=4 noet: