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 /* MUST do this fixup first, before doing ANYTHING else, as anything else
182 might allocate memory/free/move memory, and until we do the fixup, it
183 may well be chasing (and writing to) free memory. */
184 #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);
204 /* In particular, must do that fixup above before logging anything via
205 *printf(), as it can reallocate memory, which can cause SEGVs. */
207 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
208 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
217 return write_no_mem();
222 /* safe version of system's free() */
225 Perl_safesysfree(Malloc_t where)
227 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
232 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
234 #ifdef PERL_TRACK_MEMPOOL
235 where = (Malloc_t)((char*)where-sTHX);
237 struct perl_memory_debug_header *const header
238 = (struct perl_memory_debug_header *)where;
240 if (header->interpreter != aTHX) {
241 Perl_croak_nocontext("panic: free from wrong pool");
244 Perl_croak_nocontext("panic: duplicate free");
246 if (!(header->next) || header->next->prev != header
247 || header->prev->next != header) {
248 Perl_croak_nocontext("panic: bad free");
250 /* Unlink us from the chain. */
251 header->next->prev = header->prev;
252 header->prev->next = header->next;
254 PoisonNew(where, header->size, char);
256 /* Trigger the duplicate free warning. */
264 /* safe version of system's calloc() */
267 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
271 MEM_SIZE total_size = 0;
273 /* Even though calloc() for zero bytes is strange, be robust. */
274 if (size && (count <= MEM_SIZE_MAX / size))
275 total_size = size * count;
277 Perl_croak_nocontext(PL_memory_wrap);
278 #ifdef PERL_TRACK_MEMPOOL
279 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
282 Perl_croak_nocontext(PL_memory_wrap);
285 if (total_size > 0xffff) {
286 PerlIO_printf(Perl_error_log,
287 "Allocation too large: %lx\n", total_size) FLUSH;
290 #endif /* HAS_64K_LIMIT */
292 if ((long)size < 0 || (long)count < 0)
293 Perl_croak_nocontext("panic: calloc");
295 #ifdef PERL_TRACK_MEMPOOL
296 /* Have to use malloc() because we've added some space for our tracking
298 /* malloc(0) is non-portable. */
299 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
301 /* Use calloc() because it might save a memset() if the memory is fresh
302 and clean from the OS. */
304 ptr = (Malloc_t)PerlMem_calloc(count, size);
305 else /* calloc(0) is non-portable. */
306 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
308 PERL_ALLOC_CHECK(ptr);
309 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));
311 #ifdef PERL_TRACK_MEMPOOL
313 struct perl_memory_debug_header *const header
314 = (struct perl_memory_debug_header *)ptr;
316 memset((void*)ptr, 0, total_size);
317 header->interpreter = aTHX;
318 /* Link us into the list. */
319 header->prev = &PL_memory_debug_header;
320 header->next = PL_memory_debug_header.next;
321 PL_memory_debug_header.next = header;
322 header->next->prev = header;
324 header->size = total_size;
326 ptr = (Malloc_t)((char*)ptr+sTHX);
333 return write_no_mem();
336 /* These must be defined when not using Perl's malloc for binary
341 Malloc_t Perl_malloc (MEM_SIZE nbytes)
344 return (Malloc_t)PerlMem_malloc(nbytes);
347 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
350 return (Malloc_t)PerlMem_calloc(elements, size);
353 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
356 return (Malloc_t)PerlMem_realloc(where, nbytes);
359 Free_t Perl_mfree (Malloc_t where)
367 /* copy a string up to some (non-backslashed) delimiter, if any */
370 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
375 PERL_ARGS_ASSERT_DELIMCPY;
377 for (tolen = 0; from < fromend; from++, tolen++) {
379 if (from[1] != delim) {
386 else if (*from == delim)
397 /* return ptr to little string in big string, NULL if not found */
398 /* This routine was donated by Corey Satten. */
401 Perl_instr(pTHX_ register const char *big, register const char *little)
406 PERL_ARGS_ASSERT_INSTR;
414 register const char *s, *x;
417 for (x=big,s=little; *s; /**/ ) {
428 return (char*)(big-1);
433 /* same as instr but allow embedded nulls */
436 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
438 PERL_ARGS_ASSERT_NINSTR;
443 const char first = *little;
445 bigend -= lend - little++;
447 while (big <= bigend) {
448 if (*big++ == first) {
449 for (x=big,s=little; s < lend; x++,s++) {
453 return (char*)(big-1);
460 /* reverse of the above--find last substring */
463 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
465 register const char *bigbeg;
466 register const I32 first = *little;
467 register const char * const littleend = lend;
470 PERL_ARGS_ASSERT_RNINSTR;
472 if (little >= littleend)
473 return (char*)bigend;
475 big = bigend - (littleend - little++);
476 while (big >= bigbeg) {
477 register const char *s, *x;
480 for (x=big+2,s=little; s < littleend; /**/ ) {
489 return (char*)(big+1);
494 /* As a space optimization, we do not compile tables for strings of length
495 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
496 special-cased in fbm_instr().
498 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
501 =head1 Miscellaneous Functions
503 =for apidoc fbm_compile
505 Analyses the string in order to make fast searches on it using fbm_instr()
506 -- the Boyer-Moore algorithm.
512 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
515 register const U8 *s;
521 PERL_ARGS_ASSERT_FBM_COMPILE;
523 if (flags & FBMcf_TAIL) {
524 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
525 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
526 if (mg && mg->mg_len >= 0)
529 s = (U8*)SvPV_force_mutable(sv, len);
530 if (len == 0) /* TAIL might be on a zero-length string. */
532 SvUPGRADE(sv, SVt_PVGV);
537 const unsigned char *sb;
538 const U8 mlen = (len>255) ? 255 : (U8)len;
541 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
543 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
544 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
545 memset((void*)table, mlen, 256);
547 sb = s - mlen + 1; /* first char (maybe) */
549 if (table[*s] == mlen)
554 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
556 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
558 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
559 for (i = 0; i < len; i++) {
560 if (PL_freq[s[i]] < frequency) {
562 frequency = PL_freq[s[i]];
565 BmFLAGS(sv) = (U8)flags;
566 BmRARE(sv) = s[rarest];
567 BmPREVIOUS(sv) = rarest;
568 BmUSEFUL(sv) = 100; /* Initial value */
569 if (flags & FBMcf_TAIL)
571 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
572 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
575 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
576 /* If SvTAIL is actually due to \Z or \z, this gives false positives
580 =for apidoc fbm_instr
582 Returns the location of the SV in the string delimited by C<str> and
583 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
584 does not have to be fbm_compiled, but the search will not be as fast
591 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
593 register unsigned char *s;
595 register const unsigned char *little
596 = (const unsigned char *)SvPV_const(littlestr,l);
597 register STRLEN littlelen = l;
598 register const I32 multiline = flags & FBMrf_MULTILINE;
600 PERL_ARGS_ASSERT_FBM_INSTR;
602 if ((STRLEN)(bigend - big) < littlelen) {
603 if ( SvTAIL(littlestr)
604 && ((STRLEN)(bigend - big) == littlelen - 1)
606 || (*big == *little &&
607 memEQ((char *)big, (char *)little, littlelen - 1))))
612 if (littlelen <= 2) { /* Special-cased */
614 if (littlelen == 1) {
615 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
616 /* Know that bigend != big. */
617 if (bigend[-1] == '\n')
618 return (char *)(bigend - 1);
619 return (char *) bigend;
627 if (SvTAIL(littlestr))
628 return (char *) bigend;
632 return (char*)big; /* Cannot be SvTAIL! */
635 if (SvTAIL(littlestr) && !multiline) {
636 if (bigend[-1] == '\n' && bigend[-2] == *little)
637 return (char*)bigend - 2;
638 if (bigend[-1] == *little)
639 return (char*)bigend - 1;
643 /* This should be better than FBM if c1 == c2, and almost
644 as good otherwise: maybe better since we do less indirection.
645 And we save a lot of memory by caching no table. */
646 const unsigned char c1 = little[0];
647 const unsigned char c2 = little[1];
652 while (s <= bigend) {
662 goto check_1char_anchor;
673 goto check_1char_anchor;
676 while (s <= bigend) {
681 goto check_1char_anchor;
690 check_1char_anchor: /* One char and anchor! */
691 if (SvTAIL(littlestr) && (*bigend == *little))
692 return (char *)bigend; /* bigend is already decremented. */
695 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
696 s = bigend - littlelen;
697 if (s >= big && bigend[-1] == '\n' && *s == *little
698 /* Automatically of length > 2 */
699 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
701 return (char*)s; /* how sweet it is */
704 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
706 return (char*)s + 1; /* how sweet it is */
710 if (!SvVALID(littlestr)) {
711 char * const b = ninstr((char*)big,(char*)bigend,
712 (char*)little, (char*)little + littlelen);
714 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
715 /* Chop \n from littlestr: */
716 s = bigend - littlelen + 1;
718 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
728 if (littlelen > (STRLEN)(bigend - big))
732 register const unsigned char * const table
733 = little + littlelen + PERL_FBM_TABLE_OFFSET;
734 register const unsigned char *oldlittle;
736 --littlelen; /* Last char found by table lookup */
739 little += littlelen; /* last char */
745 if ((tmp = table[*s])) {
746 if ((s += tmp) < bigend)
750 else { /* less expensive than calling strncmp() */
751 register unsigned char * const olds = s;
756 if (*--s == *--little)
758 s = olds + 1; /* here we pay the price for failure */
760 if (s < bigend) /* fake up continue to outer loop */
769 && (BmFLAGS(littlestr) & FBMcf_TAIL)
770 && memEQ((char *)(bigend - littlelen),
771 (char *)(oldlittle - littlelen), littlelen) )
772 return (char*)bigend - littlelen;
777 /* start_shift, end_shift are positive quantities which give offsets
778 of ends of some substring of bigstr.
779 If "last" we want the last occurrence.
780 old_posp is the way of communication between consequent calls if
781 the next call needs to find the .
782 The initial *old_posp should be -1.
784 Note that we take into account SvTAIL, so one can get extra
785 optimizations if _ALL flag is set.
788 /* If SvTAIL is actually due to \Z or \z, this gives false positives
789 if PL_multiline. In fact if !PL_multiline the authoritative answer
790 is not supported yet. */
793 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
796 register const unsigned char *big;
798 register I32 previous;
800 register const unsigned char *little;
801 register I32 stop_pos;
802 register const unsigned char *littleend;
805 PERL_ARGS_ASSERT_SCREAMINSTR;
807 assert(SvTYPE(littlestr) == SVt_PVGV);
808 assert(SvVALID(littlestr));
811 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
812 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
814 if ( BmRARE(littlestr) == '\n'
815 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
816 little = (const unsigned char *)(SvPVX_const(littlestr));
817 littleend = little + SvCUR(littlestr);
824 little = (const unsigned char *)(SvPVX_const(littlestr));
825 littleend = little + SvCUR(littlestr);
827 /* The value of pos we can start at: */
828 previous = BmPREVIOUS(littlestr);
829 big = (const unsigned char *)(SvPVX_const(bigstr));
830 /* The value of pos we can stop at: */
831 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
832 if (previous + start_shift > stop_pos) {
834 stop_pos does not include SvTAIL in the count, so this check is incorrect
835 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
838 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
843 while (pos < previous + start_shift) {
844 if (!(pos += PL_screamnext[pos]))
849 register const unsigned char *s, *x;
850 if (pos >= stop_pos) break;
851 if (big[pos] != first)
853 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
859 if (s == littleend) {
861 if (!last) return (char *)(big+pos);
864 } while ( pos += PL_screamnext[pos] );
866 return (char *)(big+(*old_posp));
868 if (!SvTAIL(littlestr) || (end_shift > 0))
870 /* Ignore the trailing "\n". This code is not microoptimized */
871 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
872 stop_pos = littleend - little; /* Actual littlestr len */
877 && ((stop_pos == 1) ||
878 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
884 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
886 register const U8 *a = (const U8 *)s1;
887 register const U8 *b = (const U8 *)s2;
890 PERL_ARGS_ASSERT_IBCMP;
893 if (*a != *b && *a != PL_fold[*b])
901 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
904 register const U8 *a = (const U8 *)s1;
905 register const U8 *b = (const U8 *)s2;
908 PERL_ARGS_ASSERT_IBCMP_LOCALE;
911 if (*a != *b && *a != PL_fold_locale[*b])
918 /* copy a string to a safe spot */
921 =head1 Memory Management
925 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
926 string which is a duplicate of C<pv>. The size of the string is
927 determined by C<strlen()>. The memory allocated for the new string can
928 be freed with the C<Safefree()> function.
934 Perl_savepv(pTHX_ const char *pv)
941 const STRLEN pvlen = strlen(pv)+1;
942 Newx(newaddr, pvlen, char);
943 return (char*)memcpy(newaddr, pv, pvlen);
947 /* same thing but with a known length */
952 Perl's version of what C<strndup()> would be if it existed. Returns a
953 pointer to a newly allocated string which is a duplicate of the first
954 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
955 the new string can be freed with the C<Safefree()> function.
961 Perl_savepvn(pTHX_ const char *pv, register I32 len)
963 register char *newaddr;
966 Newx(newaddr,len+1,char);
967 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
969 /* might not be null terminated */
971 return (char *) CopyD(pv,newaddr,len,char);
974 return (char *) ZeroD(newaddr,len+1,char);
979 =for apidoc savesharedpv
981 A version of C<savepv()> which allocates the duplicate string in memory
982 which is shared between threads.
987 Perl_savesharedpv(pTHX_ const char *pv)
989 register char *newaddr;
994 pvlen = strlen(pv)+1;
995 newaddr = (char*)PerlMemShared_malloc(pvlen);
997 return write_no_mem();
999 return (char*)memcpy(newaddr, pv, pvlen);
1003 =for apidoc savesharedpvn
1005 A version of C<savepvn()> which allocates the duplicate string in memory
1006 which is shared between threads. (With the specific difference that a NULL
1007 pointer is not acceptable)
1012 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1014 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1016 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1019 return write_no_mem();
1021 newaddr[len] = '\0';
1022 return (char*)memcpy(newaddr, pv, len);
1026 =for apidoc savesvpv
1028 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1029 the passed in SV using C<SvPV()>
1035 Perl_savesvpv(pTHX_ SV *sv)
1038 const char * const pv = SvPV_const(sv, len);
1039 register char *newaddr;
1041 PERL_ARGS_ASSERT_SAVESVPV;
1044 Newx(newaddr,len,char);
1045 return (char *) CopyD(pv,newaddr,len,char);
1049 /* the SV for Perl_form() and mess() is not kept in an arena */
1059 return newSVpvs_flags("", SVs_TEMP);
1064 /* Create as PVMG now, to avoid any upgrading later */
1066 Newxz(any, 1, XPVMG);
1067 SvFLAGS(sv) = SVt_PVMG;
1068 SvANY(sv) = (void*)any;
1070 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1075 #if defined(PERL_IMPLICIT_CONTEXT)
1077 Perl_form_nocontext(const char* pat, ...)
1082 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1083 va_start(args, pat);
1084 retval = vform(pat, &args);
1088 #endif /* PERL_IMPLICIT_CONTEXT */
1091 =head1 Miscellaneous Functions
1094 Takes a sprintf-style format pattern and conventional
1095 (non-SV) arguments and returns the formatted string.
1097 (char *) Perl_form(pTHX_ const char* pat, ...)
1099 can be used any place a string (char *) is required:
1101 char * s = Perl_form("%d.%d",major,minor);
1103 Uses a single private buffer so if you want to format several strings you
1104 must explicitly copy the earlier strings away (and free the copies when you
1111 Perl_form(pTHX_ const char* pat, ...)
1115 PERL_ARGS_ASSERT_FORM;
1116 va_start(args, pat);
1117 retval = vform(pat, &args);
1123 Perl_vform(pTHX_ const char *pat, va_list *args)
1125 SV * const sv = mess_alloc();
1126 PERL_ARGS_ASSERT_VFORM;
1127 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1131 #if defined(PERL_IMPLICIT_CONTEXT)
1133 Perl_mess_nocontext(const char *pat, ...)
1138 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1139 va_start(args, pat);
1140 retval = vmess(pat, &args);
1144 #endif /* PERL_IMPLICIT_CONTEXT */
1147 Perl_mess(pTHX_ const char *pat, ...)
1151 PERL_ARGS_ASSERT_MESS;
1152 va_start(args, pat);
1153 retval = vmess(pat, &args);
1159 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1162 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1164 PERL_ARGS_ASSERT_CLOSEST_COP;
1166 if (!o || o == PL_op)
1169 if (o->op_flags & OPf_KIDS) {
1171 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1174 /* If the OP_NEXTSTATE has been optimised away we can still use it
1175 * the get the file and line number. */
1177 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1178 cop = (const COP *)kid;
1180 /* Keep searching, and return when we've found something. */
1182 new_cop = closest_cop(cop, kid);
1188 /* Nothing found. */
1194 Perl_vmess(pTHX_ const char *pat, va_list *args)
1197 SV * const sv = mess_alloc();
1199 PERL_ARGS_ASSERT_VMESS;
1201 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1202 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1204 * Try and find the file and line for PL_op. This will usually be
1205 * PL_curcop, but it might be a cop that has been optimised away. We
1206 * can try to find such a cop by searching through the optree starting
1207 * from the sibling of PL_curcop.
1210 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1215 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1216 OutCopFILE(cop), (IV)CopLINE(cop));
1217 /* Seems that GvIO() can be untrustworthy during global destruction. */
1218 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1219 && IoLINES(GvIOp(PL_last_in_gv)))
1221 const bool line_mode = (RsSIMPLE(PL_rs) &&
1222 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1223 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1224 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1225 line_mode ? "line" : "chunk",
1226 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1229 sv_catpvs(sv, " during global destruction");
1230 sv_catpvs(sv, ".\n");
1236 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1242 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1244 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1245 && (io = GvIO(PL_stderrgv))
1246 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1253 SAVESPTR(PL_stderrgv);
1256 PUSHSTACKi(PERLSI_MAGIC);
1260 PUSHs(SvTIED_obj((SV*)io, mg));
1261 mPUSHp(message, msglen);
1263 call_method("PRINT", G_SCALAR);
1271 /* SFIO can really mess with your errno */
1272 const int e = errno;
1274 PerlIO * const serr = Perl_error_log;
1276 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1277 (void)PerlIO_flush(serr);
1284 /* Common code used by vcroak, vdie, vwarn and vwarner */
1287 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1293 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1294 /* sv_2cv might call Perl_croak() or Perl_warner() */
1295 SV * const oldhook = *hook;
1302 cv = sv_2cv(oldhook, &stash, &gv, 0);
1304 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1314 if (warn || message) {
1315 msg = newSVpvn_flags(message, msglen, utf8);
1323 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1327 call_sv((SV*)cv, G_DISCARD);
1336 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1340 const char *message;
1343 SV * const msv = vmess(pat, args);
1344 if (PL_errors && SvCUR(PL_errors)) {
1345 sv_catsv(PL_errors, msv);
1346 message = SvPV_const(PL_errors, *msglen);
1347 SvCUR_set(PL_errors, 0);
1350 message = SvPV_const(msv,*msglen);
1351 *utf8 = SvUTF8(msv);
1358 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1364 Perl_vdie(pTHX_ const char* pat, va_list *args)
1367 const char *message;
1368 const int was_in_eval = PL_in_eval;
1372 message = vdie_croak_common(pat, args, &msglen, &utf8);
1374 PL_restartop = die_where(message, msglen);
1375 SvFLAGS(ERRSV) |= utf8;
1376 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1378 return PL_restartop;
1381 #if defined(PERL_IMPLICIT_CONTEXT)
1383 Perl_die_nocontext(const char* pat, ...)
1388 PERL_ARGS_ASSERT_DIE_NOCONTEXT;
1389 va_start(args, pat);
1390 o = vdie(pat, &args);
1394 #endif /* PERL_IMPLICIT_CONTEXT */
1397 Perl_die(pTHX_ const char* pat, ...)
1401 va_start(args, pat);
1402 o = vdie(pat, &args);
1408 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1411 const char *message;
1415 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1418 PL_restartop = die_where(message, msglen);
1419 SvFLAGS(ERRSV) |= utf8;
1423 message = SvPVx_const(ERRSV, msglen);
1425 write_to_stderr(message, msglen);
1429 #if defined(PERL_IMPLICIT_CONTEXT)
1431 Perl_croak_nocontext(const char *pat, ...)
1435 va_start(args, pat);
1440 #endif /* PERL_IMPLICIT_CONTEXT */
1443 =head1 Warning and Dieing
1447 This is the XSUB-writer's interface to Perl's C<die> function.
1448 Normally call this function the same way you call the C C<printf>
1449 function. Calling C<croak> returns control directly to Perl,
1450 sidestepping the normal C order of execution. See C<warn>.
1452 If you want to throw an exception object, assign the object to
1453 C<$@> and then pass C<NULL> to croak():
1455 errsv = get_sv("@", TRUE);
1456 sv_setsv(errsv, exception_object);
1463 Perl_croak(pTHX_ const char *pat, ...)
1466 va_start(args, pat);
1473 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1477 SV * const msv = vmess(pat, args);
1478 const I32 utf8 = SvUTF8(msv);
1479 const char * const message = SvPV_const(msv, msglen);
1481 PERL_ARGS_ASSERT_VWARN;
1484 if (vdie_common(message, msglen, utf8, TRUE))
1488 write_to_stderr(message, msglen);
1491 #if defined(PERL_IMPLICIT_CONTEXT)
1493 Perl_warn_nocontext(const char *pat, ...)
1497 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1498 va_start(args, pat);
1502 #endif /* PERL_IMPLICIT_CONTEXT */
1507 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1508 function the same way you call the C C<printf> function. See C<croak>.
1514 Perl_warn(pTHX_ const char *pat, ...)
1517 PERL_ARGS_ASSERT_WARN;
1518 va_start(args, pat);
1523 #if defined(PERL_IMPLICIT_CONTEXT)
1525 Perl_warner_nocontext(U32 err, const char *pat, ...)
1529 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1530 va_start(args, pat);
1531 vwarner(err, pat, &args);
1534 #endif /* PERL_IMPLICIT_CONTEXT */
1537 Perl_warner(pTHX_ U32 err, const char* pat,...)
1540 PERL_ARGS_ASSERT_WARNER;
1541 va_start(args, pat);
1542 vwarner(err, pat, &args);
1547 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1550 PERL_ARGS_ASSERT_VWARNER;
1551 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1552 SV * const msv = vmess(pat, args);
1554 const char * const message = SvPV_const(msv, msglen);
1555 const I32 utf8 = SvUTF8(msv);
1559 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1562 PL_restartop = die_where(message, msglen);
1563 SvFLAGS(ERRSV) |= utf8;
1566 write_to_stderr(message, msglen);
1570 Perl_vwarn(aTHX_ pat, args);
1574 /* implements the ckWARN? macros */
1577 Perl_ckwarn(pTHX_ U32 w)
1583 && PL_curcop->cop_warnings != pWARN_NONE
1585 PL_curcop->cop_warnings == pWARN_ALL
1586 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1587 || (unpackWARN2(w) &&
1588 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1589 || (unpackWARN3(w) &&
1590 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1591 || (unpackWARN4(w) &&
1592 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1597 isLEXWARN_off && PL_dowarn & G_WARN_ON
1602 /* implements the ckWARN?_d macro */
1605 Perl_ckwarn_d(pTHX_ U32 w)
1610 || PL_curcop->cop_warnings == pWARN_ALL
1612 PL_curcop->cop_warnings != pWARN_NONE
1614 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1615 || (unpackWARN2(w) &&
1616 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1617 || (unpackWARN3(w) &&
1618 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1619 || (unpackWARN4(w) &&
1620 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1626 /* Set buffer=NULL to get a new one. */
1628 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1630 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1631 PERL_UNUSED_CONTEXT;
1632 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1635 (specialWARN(buffer) ?
1636 PerlMemShared_malloc(len_wanted) :
1637 PerlMemShared_realloc(buffer, len_wanted));
1639 Copy(bits, (buffer + 1), size, char);
1643 /* since we've already done strlen() for both nam and val
1644 * we can use that info to make things faster than
1645 * sprintf(s, "%s=%s", nam, val)
1647 #define my_setenv_format(s, nam, nlen, val, vlen) \
1648 Copy(nam, s, nlen, char); \
1650 Copy(val, s+(nlen+1), vlen, char); \
1651 *(s+(nlen+1+vlen)) = '\0'
1653 #ifdef USE_ENVIRON_ARRAY
1654 /* VMS' my_setenv() is in vms.c */
1655 #if !defined(WIN32) && !defined(NETWARE)
1657 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1661 /* only parent thread can modify process environment */
1662 if (PL_curinterp == aTHX)
1665 #ifndef PERL_USE_SAFE_PUTENV
1666 if (!PL_use_safe_putenv) {
1667 /* most putenv()s leak, so we manipulate environ directly */
1668 register I32 i=setenv_getix(nam); /* where does it go? */
1671 if (environ == PL_origenviron) { /* need we copy environment? */
1677 while (environ[max])
1679 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1680 for (j=0; j<max; j++) { /* copy environment */
1681 const int len = strlen(environ[j]);
1682 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1683 Copy(environ[j], tmpenv[j], len+1, char);
1686 environ = tmpenv; /* tell exec where it is now */
1689 safesysfree(environ[i]);
1690 while (environ[i]) {
1691 environ[i] = environ[i+1];
1696 if (!environ[i]) { /* does not exist yet */
1697 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1698 environ[i+1] = NULL; /* make sure it's null terminated */
1701 safesysfree(environ[i]);
1705 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1706 /* all that work just for this */
1707 my_setenv_format(environ[i], nam, nlen, val, vlen);
1710 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1711 # if defined(HAS_UNSETENV)
1713 (void)unsetenv(nam);
1715 (void)setenv(nam, val, 1);
1717 # else /* ! HAS_UNSETENV */
1718 (void)setenv(nam, val, 1);
1719 # endif /* HAS_UNSETENV */
1721 # if defined(HAS_UNSETENV)
1723 (void)unsetenv(nam);
1725 const int nlen = strlen(nam);
1726 const int vlen = strlen(val);
1727 char * const new_env =
1728 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1729 my_setenv_format(new_env, nam, nlen, val, vlen);
1730 (void)putenv(new_env);
1732 # else /* ! HAS_UNSETENV */
1734 const int nlen = strlen(nam);
1740 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1741 /* all that work just for this */
1742 my_setenv_format(new_env, nam, nlen, val, vlen);
1743 (void)putenv(new_env);
1744 # endif /* HAS_UNSETENV */
1745 # endif /* __CYGWIN__ */
1746 #ifndef PERL_USE_SAFE_PUTENV
1752 #else /* WIN32 || NETWARE */
1755 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1758 register char *envstr;
1759 const int nlen = strlen(nam);
1766 Newx(envstr, nlen+vlen+2, char);
1767 my_setenv_format(envstr, nam, nlen, val, vlen);
1768 (void)PerlEnv_putenv(envstr);
1772 #endif /* WIN32 || NETWARE */
1776 Perl_setenv_getix(pTHX_ const char *nam)
1779 register const I32 len = strlen(nam);
1781 PERL_ARGS_ASSERT_SETENV_GETIX;
1782 PERL_UNUSED_CONTEXT;
1784 for (i = 0; environ[i]; i++) {
1787 strnicmp(environ[i],nam,len) == 0
1789 strnEQ(environ[i],nam,len)
1791 && environ[i][len] == '=')
1792 break; /* strnEQ must come first to avoid */
1793 } /* potential SEGV's */
1796 #endif /* !PERL_MICRO */
1798 #endif /* !VMS && !EPOC*/
1800 #ifdef UNLINK_ALL_VERSIONS
1802 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1806 PERL_ARGS_ASSERT_UNLNK;
1808 while (PerlLIO_unlink(f) >= 0)
1810 return retries ? 0 : -1;
1814 /* this is a drop-in replacement for bcopy() */
1815 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1817 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1819 char * const retval = to;
1821 PERL_ARGS_ASSERT_MY_BCOPY;
1823 if (from - to >= 0) {
1831 *(--to) = *(--from);
1837 /* this is a drop-in replacement for memset() */
1840 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1842 char * const retval = loc;
1844 PERL_ARGS_ASSERT_MY_MEMSET;
1852 /* this is a drop-in replacement for bzero() */
1853 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1855 Perl_my_bzero(register char *loc, register I32 len)
1857 char * const retval = loc;
1859 PERL_ARGS_ASSERT_MY_BZERO;
1867 /* this is a drop-in replacement for memcmp() */
1868 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1870 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1872 register const U8 *a = (const U8 *)s1;
1873 register const U8 *b = (const U8 *)s2;
1876 PERL_ARGS_ASSERT_MY_MEMCMP;
1879 if ((tmp = *a++ - *b++))
1884 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1887 /* This vsprintf replacement should generally never get used, since
1888 vsprintf was available in both System V and BSD 2.11. (There may
1889 be some cross-compilation or embedded set-ups where it is needed,
1892 If you encounter a problem in this function, it's probably a symptom
1893 that Configure failed to detect your system's vprintf() function.
1894 See the section on "item vsprintf" in the INSTALL file.
1896 This version may compile on systems with BSD-ish <stdio.h>,
1897 but probably won't on others.
1900 #ifdef USE_CHAR_VSPRINTF
1905 vsprintf(char *dest, const char *pat, void *args)
1909 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
1910 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
1911 FILE_cnt(&fakebuf) = 32767;
1913 /* These probably won't compile -- If you really need
1914 this, you'll have to figure out some other method. */
1915 fakebuf._ptr = dest;
1916 fakebuf._cnt = 32767;
1921 fakebuf._flag = _IOWRT|_IOSTRG;
1922 _doprnt(pat, args, &fakebuf); /* what a kludge */
1923 #if defined(STDIO_PTR_LVALUE)
1924 *(FILE_ptr(&fakebuf)++) = '\0';
1926 /* PerlIO has probably #defined away fputc, but we want it here. */
1928 # undef fputc /* XXX Should really restore it later */
1930 (void)fputc('\0', &fakebuf);
1932 #ifdef USE_CHAR_VSPRINTF
1935 return 0; /* perl doesn't use return value */
1939 #endif /* HAS_VPRINTF */
1942 #if BYTEORDER != 0x4321
1944 Perl_my_swap(pTHX_ short s)
1946 #if (BYTEORDER & 1) == 0
1949 result = ((s & 255) << 8) + ((s >> 8) & 255);
1957 Perl_my_htonl(pTHX_ long l)
1961 char c[sizeof(long)];
1964 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
1965 #if BYTEORDER == 0x12345678
1968 u.c[0] = (l >> 24) & 255;
1969 u.c[1] = (l >> 16) & 255;
1970 u.c[2] = (l >> 8) & 255;
1974 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1975 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1980 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1981 u.c[o & 0xf] = (l >> s) & 255;
1989 Perl_my_ntohl(pTHX_ long l)
1993 char c[sizeof(long)];
1996 #if BYTEORDER == 0x1234
1997 u.c[0] = (l >> 24) & 255;
1998 u.c[1] = (l >> 16) & 255;
1999 u.c[2] = (l >> 8) & 255;
2003 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2004 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2011 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2012 l |= (u.c[o & 0xf] & 255) << s;
2019 #endif /* BYTEORDER != 0x4321 */
2023 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2024 * If these functions are defined,
2025 * the BYTEORDER is neither 0x1234 nor 0x4321.
2026 * However, this is not assumed.
2030 #define HTOLE(name,type) \
2032 name (register type n) \
2036 char c[sizeof(type)]; \
2039 register U32 s = 0; \
2040 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2041 u.c[i] = (n >> s) & 0xFF; \
2046 #define LETOH(name,type) \
2048 name (register type n) \
2052 char c[sizeof(type)]; \
2055 register U32 s = 0; \
2058 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2059 n |= ((type)(u.c[i] & 0xFF)) << s; \
2065 * Big-endian byte order functions.
2068 #define HTOBE(name,type) \
2070 name (register type n) \
2074 char c[sizeof(type)]; \
2077 register U32 s = 8*(sizeof(u.c)-1); \
2078 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2079 u.c[i] = (n >> s) & 0xFF; \
2084 #define BETOH(name,type) \
2086 name (register type n) \
2090 char c[sizeof(type)]; \
2093 register U32 s = 8*(sizeof(u.c)-1); \
2096 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2097 n |= ((type)(u.c[i] & 0xFF)) << s; \
2103 * If we just can't do it...
2106 #define NOT_AVAIL(name,type) \
2108 name (register type n) \
2110 Perl_croak_nocontext(#name "() not available"); \
2111 return n; /* not reached */ \
2115 #if defined(HAS_HTOVS) && !defined(htovs)
2118 #if defined(HAS_HTOVL) && !defined(htovl)
2121 #if defined(HAS_VTOHS) && !defined(vtohs)
2124 #if defined(HAS_VTOHL) && !defined(vtohl)
2128 #ifdef PERL_NEED_MY_HTOLE16
2130 HTOLE(Perl_my_htole16,U16)
2132 NOT_AVAIL(Perl_my_htole16,U16)
2135 #ifdef PERL_NEED_MY_LETOH16
2137 LETOH(Perl_my_letoh16,U16)
2139 NOT_AVAIL(Perl_my_letoh16,U16)
2142 #ifdef PERL_NEED_MY_HTOBE16
2144 HTOBE(Perl_my_htobe16,U16)
2146 NOT_AVAIL(Perl_my_htobe16,U16)
2149 #ifdef PERL_NEED_MY_BETOH16
2151 BETOH(Perl_my_betoh16,U16)
2153 NOT_AVAIL(Perl_my_betoh16,U16)
2157 #ifdef PERL_NEED_MY_HTOLE32
2159 HTOLE(Perl_my_htole32,U32)
2161 NOT_AVAIL(Perl_my_htole32,U32)
2164 #ifdef PERL_NEED_MY_LETOH32
2166 LETOH(Perl_my_letoh32,U32)
2168 NOT_AVAIL(Perl_my_letoh32,U32)
2171 #ifdef PERL_NEED_MY_HTOBE32
2173 HTOBE(Perl_my_htobe32,U32)
2175 NOT_AVAIL(Perl_my_htobe32,U32)
2178 #ifdef PERL_NEED_MY_BETOH32
2180 BETOH(Perl_my_betoh32,U32)
2182 NOT_AVAIL(Perl_my_betoh32,U32)
2186 #ifdef PERL_NEED_MY_HTOLE64
2188 HTOLE(Perl_my_htole64,U64)
2190 NOT_AVAIL(Perl_my_htole64,U64)
2193 #ifdef PERL_NEED_MY_LETOH64
2195 LETOH(Perl_my_letoh64,U64)
2197 NOT_AVAIL(Perl_my_letoh64,U64)
2200 #ifdef PERL_NEED_MY_HTOBE64
2202 HTOBE(Perl_my_htobe64,U64)
2204 NOT_AVAIL(Perl_my_htobe64,U64)
2207 #ifdef PERL_NEED_MY_BETOH64
2209 BETOH(Perl_my_betoh64,U64)
2211 NOT_AVAIL(Perl_my_betoh64,U64)
2215 #ifdef PERL_NEED_MY_HTOLES
2216 HTOLE(Perl_my_htoles,short)
2218 #ifdef PERL_NEED_MY_LETOHS
2219 LETOH(Perl_my_letohs,short)
2221 #ifdef PERL_NEED_MY_HTOBES
2222 HTOBE(Perl_my_htobes,short)
2224 #ifdef PERL_NEED_MY_BETOHS
2225 BETOH(Perl_my_betohs,short)
2228 #ifdef PERL_NEED_MY_HTOLEI
2229 HTOLE(Perl_my_htolei,int)
2231 #ifdef PERL_NEED_MY_LETOHI
2232 LETOH(Perl_my_letohi,int)
2234 #ifdef PERL_NEED_MY_HTOBEI
2235 HTOBE(Perl_my_htobei,int)
2237 #ifdef PERL_NEED_MY_BETOHI
2238 BETOH(Perl_my_betohi,int)
2241 #ifdef PERL_NEED_MY_HTOLEL
2242 HTOLE(Perl_my_htolel,long)
2244 #ifdef PERL_NEED_MY_LETOHL
2245 LETOH(Perl_my_letohl,long)
2247 #ifdef PERL_NEED_MY_HTOBEL
2248 HTOBE(Perl_my_htobel,long)
2250 #ifdef PERL_NEED_MY_BETOHL
2251 BETOH(Perl_my_betohl,long)
2255 Perl_my_swabn(void *ptr, int n)
2257 register char *s = (char *)ptr;
2258 register char *e = s + (n-1);
2261 PERL_ARGS_ASSERT_MY_SWABN;
2263 for (n /= 2; n > 0; s++, e--, n--) {
2271 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2273 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2276 register I32 This, that;
2282 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2284 PERL_FLUSHALL_FOR_CHILD;
2285 This = (*mode == 'w');
2289 taint_proper("Insecure %s%s", "EXEC");
2291 if (PerlProc_pipe(p) < 0)
2293 /* Try for another pipe pair for error return */
2294 if (PerlProc_pipe(pp) >= 0)
2296 while ((pid = PerlProc_fork()) < 0) {
2297 if (errno != EAGAIN) {
2298 PerlLIO_close(p[This]);
2299 PerlLIO_close(p[that]);
2301 PerlLIO_close(pp[0]);
2302 PerlLIO_close(pp[1]);
2314 /* Close parent's end of error status pipe (if any) */
2316 PerlLIO_close(pp[0]);
2317 #if defined(HAS_FCNTL) && defined(F_SETFD)
2318 /* Close error pipe automatically if exec works */
2319 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2322 /* Now dup our end of _the_ pipe to right position */
2323 if (p[THIS] != (*mode == 'r')) {
2324 PerlLIO_dup2(p[THIS], *mode == 'r');
2325 PerlLIO_close(p[THIS]);
2326 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2327 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2330 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2331 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2332 /* No automatic close - do it by hand */
2339 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2345 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2351 do_execfree(); /* free any memory malloced by child on fork */
2353 PerlLIO_close(pp[1]);
2354 /* Keep the lower of the two fd numbers */
2355 if (p[that] < p[This]) {
2356 PerlLIO_dup2(p[This], p[that]);
2357 PerlLIO_close(p[This]);
2361 PerlLIO_close(p[that]); /* close child's end of pipe */
2364 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2366 SvUPGRADE(sv,SVt_IV);
2368 PL_forkprocess = pid;
2369 /* If we managed to get status pipe check for exec fail */
2370 if (did_pipes && pid > 0) {
2375 while (n < sizeof(int)) {
2376 n1 = PerlLIO_read(pp[0],
2377 (void*)(((char*)&errkid)+n),
2383 PerlLIO_close(pp[0]);
2385 if (n) { /* Error */
2387 PerlLIO_close(p[This]);
2388 if (n != sizeof(int))
2389 Perl_croak(aTHX_ "panic: kid popen errno read");
2391 pid2 = wait4pid(pid, &status, 0);
2392 } while (pid2 == -1 && errno == EINTR);
2393 errno = errkid; /* Propagate errno from kid */
2398 PerlLIO_close(pp[0]);
2399 return PerlIO_fdopen(p[This], mode);
2401 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2402 return my_syspopen4(aTHX_ NULL, mode, n, args);
2404 Perl_croak(aTHX_ "List form of piped open not implemented");
2405 return (PerlIO *) NULL;
2410 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2411 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2413 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2417 register I32 This, that;
2420 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2424 PERL_ARGS_ASSERT_MY_POPEN;
2426 PERL_FLUSHALL_FOR_CHILD;
2429 return my_syspopen(aTHX_ cmd,mode);
2432 This = (*mode == 'w');
2434 if (doexec && PL_tainting) {
2436 taint_proper("Insecure %s%s", "EXEC");
2438 if (PerlProc_pipe(p) < 0)
2440 if (doexec && PerlProc_pipe(pp) >= 0)
2442 while ((pid = PerlProc_fork()) < 0) {
2443 if (errno != EAGAIN) {
2444 PerlLIO_close(p[This]);
2445 PerlLIO_close(p[that]);
2447 PerlLIO_close(pp[0]);
2448 PerlLIO_close(pp[1]);
2451 Perl_croak(aTHX_ "Can't fork");
2464 PerlLIO_close(pp[0]);
2465 #if defined(HAS_FCNTL) && defined(F_SETFD)
2466 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2469 if (p[THIS] != (*mode == 'r')) {
2470 PerlLIO_dup2(p[THIS], *mode == 'r');
2471 PerlLIO_close(p[THIS]);
2472 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2473 PerlLIO_close(p[THAT]);
2476 PerlLIO_close(p[THAT]);
2479 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2486 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2491 /* may or may not use the shell */
2492 do_exec3(cmd, pp[1], did_pipes);
2495 #endif /* defined OS2 */
2497 #ifdef PERLIO_USING_CRLF
2498 /* Since we circumvent IO layers when we manipulate low-level
2499 filedescriptors directly, need to manually switch to the
2500 default, binary, low-level mode; see PerlIOBuf_open(). */
2501 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2504 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2505 SvREADONLY_off(GvSV(tmpgv));
2506 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2507 SvREADONLY_on(GvSV(tmpgv));
2509 #ifdef THREADS_HAVE_PIDS
2510 PL_ppid = (IV)getppid();
2513 #ifdef PERL_USES_PL_PIDSTATUS
2514 hv_clear(PL_pidstatus); /* we have no children */
2520 do_execfree(); /* free any memory malloced by child on vfork */
2522 PerlLIO_close(pp[1]);
2523 if (p[that] < p[This]) {
2524 PerlLIO_dup2(p[This], p[that]);
2525 PerlLIO_close(p[This]);
2529 PerlLIO_close(p[that]);
2532 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2534 SvUPGRADE(sv,SVt_IV);
2536 PL_forkprocess = pid;
2537 if (did_pipes && pid > 0) {
2542 while (n < sizeof(int)) {
2543 n1 = PerlLIO_read(pp[0],
2544 (void*)(((char*)&errkid)+n),
2550 PerlLIO_close(pp[0]);
2552 if (n) { /* Error */
2554 PerlLIO_close(p[This]);
2555 if (n != sizeof(int))
2556 Perl_croak(aTHX_ "panic: kid popen errno read");
2558 pid2 = wait4pid(pid, &status, 0);
2559 } while (pid2 == -1 && errno == EINTR);
2560 errno = errkid; /* Propagate errno from kid */
2565 PerlLIO_close(pp[0]);
2566 return PerlIO_fdopen(p[This], mode);
2569 #if defined(atarist) || defined(EPOC)
2572 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2574 PERL_ARGS_ASSERT_MY_POPEN;
2575 PERL_FLUSHALL_FOR_CHILD;
2576 /* Call system's popen() to get a FILE *, then import it.
2577 used 0 for 2nd parameter to PerlIO_importFILE;
2580 return PerlIO_importFILE(popen(cmd, mode), 0);
2584 FILE *djgpp_popen();
2586 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2588 PERL_FLUSHALL_FOR_CHILD;
2589 /* Call system's popen() to get a FILE *, then import it.
2590 used 0 for 2nd parameter to PerlIO_importFILE;
2593 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2596 #if defined(__LIBCATAMOUNT__)
2598 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2606 #endif /* !DOSISH */
2608 /* this is called in parent before the fork() */
2610 Perl_atfork_lock(void)
2613 #if defined(USE_ITHREADS)
2614 /* locks must be held in locking order (if any) */
2616 MUTEX_LOCK(&PL_malloc_mutex);
2622 /* this is called in both parent and child after the fork() */
2624 Perl_atfork_unlock(void)
2627 #if defined(USE_ITHREADS)
2628 /* locks must be released in same order as in atfork_lock() */
2630 MUTEX_UNLOCK(&PL_malloc_mutex);
2639 #if defined(HAS_FORK)
2641 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2646 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2647 * handlers elsewhere in the code */
2652 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2653 Perl_croak_nocontext("fork() not available");
2655 #endif /* HAS_FORK */
2660 Perl_dump_fds(pTHX_ const char *const s)
2665 PERL_ARGS_ASSERT_DUMP_FDS;
2667 PerlIO_printf(Perl_debug_log,"%s", s);
2668 for (fd = 0; fd < 32; fd++) {
2669 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2670 PerlIO_printf(Perl_debug_log," %d",fd);
2672 PerlIO_printf(Perl_debug_log,"\n");
2675 #endif /* DUMP_FDS */
2679 dup2(int oldfd, int newfd)
2681 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2684 PerlLIO_close(newfd);
2685 return fcntl(oldfd, F_DUPFD, newfd);
2687 #define DUP2_MAX_FDS 256
2688 int fdtmp[DUP2_MAX_FDS];
2694 PerlLIO_close(newfd);
2695 /* good enough for low fd's... */
2696 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2697 if (fdx >= DUP2_MAX_FDS) {
2705 PerlLIO_close(fdtmp[--fdx]);
2712 #ifdef HAS_SIGACTION
2714 #ifdef MACOS_TRADITIONAL
2715 /* We don't want restart behavior on MacOS */
2720 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2723 struct sigaction act, oact;
2726 /* only "parent" interpreter can diddle signals */
2727 if (PL_curinterp != aTHX)
2728 return (Sighandler_t) SIG_ERR;
2731 act.sa_handler = (void(*)(int))handler;
2732 sigemptyset(&act.sa_mask);
2735 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2736 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2738 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2739 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2740 act.sa_flags |= SA_NOCLDWAIT;
2742 if (sigaction(signo, &act, &oact) == -1)
2743 return (Sighandler_t) SIG_ERR;
2745 return (Sighandler_t) oact.sa_handler;
2749 Perl_rsignal_state(pTHX_ int signo)
2751 struct sigaction oact;
2752 PERL_UNUSED_CONTEXT;
2754 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2755 return (Sighandler_t) SIG_ERR;
2757 return (Sighandler_t) oact.sa_handler;
2761 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2764 struct sigaction act;
2766 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2769 /* only "parent" interpreter can diddle signals */
2770 if (PL_curinterp != aTHX)
2774 act.sa_handler = (void(*)(int))handler;
2775 sigemptyset(&act.sa_mask);
2778 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2779 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2781 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2782 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2783 act.sa_flags |= SA_NOCLDWAIT;
2785 return sigaction(signo, &act, save);
2789 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2793 /* only "parent" interpreter can diddle signals */
2794 if (PL_curinterp != aTHX)
2798 return sigaction(signo, save, (struct sigaction *)NULL);
2801 #else /* !HAS_SIGACTION */
2804 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2806 #if defined(USE_ITHREADS) && !defined(WIN32)
2807 /* only "parent" interpreter can diddle signals */
2808 if (PL_curinterp != aTHX)
2809 return (Sighandler_t) SIG_ERR;
2812 return PerlProc_signal(signo, handler);
2823 Perl_rsignal_state(pTHX_ int signo)
2826 Sighandler_t oldsig;
2828 #if defined(USE_ITHREADS) && !defined(WIN32)
2829 /* only "parent" interpreter can diddle signals */
2830 if (PL_curinterp != aTHX)
2831 return (Sighandler_t) SIG_ERR;
2835 oldsig = PerlProc_signal(signo, sig_trap);
2836 PerlProc_signal(signo, oldsig);
2838 PerlProc_kill(PerlProc_getpid(), signo);
2843 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2845 #if defined(USE_ITHREADS) && !defined(WIN32)
2846 /* only "parent" interpreter can diddle signals */
2847 if (PL_curinterp != aTHX)
2850 *save = PerlProc_signal(signo, handler);
2851 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2855 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2857 #if defined(USE_ITHREADS) && !defined(WIN32)
2858 /* only "parent" interpreter can diddle signals */
2859 if (PL_curinterp != aTHX)
2862 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2865 #endif /* !HAS_SIGACTION */
2866 #endif /* !PERL_MICRO */
2868 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2869 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2871 Perl_my_pclose(pTHX_ PerlIO *ptr)
2874 Sigsave_t hstat, istat, qstat;
2880 int saved_errno = 0;
2882 int saved_win32_errno;
2886 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2888 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2890 *svp = &PL_sv_undef;
2892 if (pid == -1) { /* Opened by popen. */
2893 return my_syspclose(ptr);
2896 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2897 saved_errno = errno;
2899 saved_win32_errno = GetLastError();
2903 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2906 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2907 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2908 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2911 pid2 = wait4pid(pid, &status, 0);
2912 } while (pid2 == -1 && errno == EINTR);
2914 rsignal_restore(SIGHUP, &hstat);
2915 rsignal_restore(SIGINT, &istat);
2916 rsignal_restore(SIGQUIT, &qstat);
2919 SETERRNO(saved_errno, 0);
2922 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2925 #if defined(__LIBCATAMOUNT__)
2927 Perl_my_pclose(pTHX_ PerlIO *ptr)
2932 #endif /* !DOSISH */
2934 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL) && !defined(__LIBCATAMOUNT__)
2936 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2940 PERL_ARGS_ASSERT_WAIT4PID;
2943 #ifdef PERL_USES_PL_PIDSTATUS
2946 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2947 pid, rather than a string form. */
2948 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2949 if (svp && *svp != &PL_sv_undef) {
2950 *statusp = SvIVX(*svp);
2951 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2959 hv_iterinit(PL_pidstatus);
2960 if ((entry = hv_iternext(PL_pidstatus))) {
2961 SV * const sv = hv_iterval(PL_pidstatus,entry);
2963 const char * const spid = hv_iterkey(entry,&len);
2965 assert (len == sizeof(Pid_t));
2966 memcpy((char *)&pid, spid, len);
2967 *statusp = SvIVX(sv);
2968 /* The hash iterator is currently on this entry, so simply
2969 calling hv_delete would trigger the lazy delete, which on
2970 aggregate does more work, beacuse next call to hv_iterinit()
2971 would spot the flag, and have to call the delete routine,
2972 while in the meantime any new entries can't re-use that
2974 hv_iterinit(PL_pidstatus);
2975 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2982 # ifdef HAS_WAITPID_RUNTIME
2983 if (!HAS_WAITPID_RUNTIME)
2986 result = PerlProc_waitpid(pid,statusp,flags);
2989 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2990 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
2993 #ifdef PERL_USES_PL_PIDSTATUS
2994 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2999 Perl_croak(aTHX_ "Can't do waitpid with flags");
3001 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3002 pidgone(result,*statusp);
3008 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3011 if (result < 0 && errno == EINTR) {
3013 errno = EINTR; /* reset in case a signal handler changed $! */
3017 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3019 #ifdef PERL_USES_PL_PIDSTATUS
3021 Perl_pidgone(pTHX_ Pid_t pid, int status)
3025 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3026 SvUPGRADE(sv,SVt_IV);
3027 SvIV_set(sv, status);
3032 #if defined(atarist) || defined(OS2) || defined(EPOC)
3035 int /* Cannot prototype with I32
3037 my_syspclose(PerlIO *ptr)
3040 Perl_my_pclose(pTHX_ PerlIO *ptr)
3043 /* Needs work for PerlIO ! */
3044 FILE * const f = PerlIO_findFILE(ptr);
3045 const I32 result = pclose(f);
3046 PerlIO_releaseFILE(ptr,f);
3054 Perl_my_pclose(pTHX_ PerlIO *ptr)
3056 /* Needs work for PerlIO ! */
3057 FILE * const f = PerlIO_findFILE(ptr);
3058 I32 result = djgpp_pclose(f);
3059 result = (result << 8) & 0xff00;
3060 PerlIO_releaseFILE(ptr,f);
3066 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
3069 register const char * const frombase = from;
3070 PERL_UNUSED_CONTEXT;
3072 PERL_ARGS_ASSERT_REPEATCPY;
3075 register const char c = *from;
3080 while (count-- > 0) {
3081 for (todo = len; todo > 0; todo--) {
3090 Perl_same_dirent(pTHX_ const char *a, const char *b)
3092 char *fa = strrchr(a,'/');
3093 char *fb = strrchr(b,'/');
3096 SV * const tmpsv = sv_newmortal();
3098 PERL_ARGS_ASSERT_SAME_DIRENT;
3111 sv_setpvn(tmpsv, ".", 1);
3113 sv_setpvn(tmpsv, a, fa - a);
3114 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3117 sv_setpvn(tmpsv, ".", 1);
3119 sv_setpvn(tmpsv, b, fb - b);
3120 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3122 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3123 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3125 #endif /* !HAS_RENAME */
3128 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3129 const char *const *const search_ext, I32 flags)
3132 const char *xfound = NULL;
3133 char *xfailed = NULL;
3134 char tmpbuf[MAXPATHLEN];
3139 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3140 # define SEARCH_EXTS ".bat", ".cmd", NULL
3141 # define MAX_EXT_LEN 4
3144 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3145 # define MAX_EXT_LEN 4
3148 # define SEARCH_EXTS ".pl", ".com", NULL
3149 # define MAX_EXT_LEN 4
3151 /* additional extensions to try in each dir if scriptname not found */
3153 static const char *const exts[] = { SEARCH_EXTS };
3154 const char *const *const ext = search_ext ? search_ext : exts;
3155 int extidx = 0, i = 0;
3156 const char *curext = NULL;
3158 PERL_UNUSED_ARG(search_ext);
3159 # define MAX_EXT_LEN 0
3162 PERL_ARGS_ASSERT_FIND_SCRIPT;
3165 * If dosearch is true and if scriptname does not contain path
3166 * delimiters, search the PATH for scriptname.
3168 * If SEARCH_EXTS is also defined, will look for each
3169 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3170 * while searching the PATH.
3172 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3173 * proceeds as follows:
3174 * If DOSISH or VMSISH:
3175 * + look for ./scriptname{,.foo,.bar}
3176 * + search the PATH for scriptname{,.foo,.bar}
3179 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3180 * this will not look in '.' if it's not in the PATH)
3185 # ifdef ALWAYS_DEFTYPES
3186 len = strlen(scriptname);
3187 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3188 int idx = 0, deftypes = 1;
3191 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3194 int idx = 0, deftypes = 1;
3197 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3199 /* The first time through, just add SEARCH_EXTS to whatever we
3200 * already have, so we can check for default file types. */
3202 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3208 if ((strlen(tmpbuf) + strlen(scriptname)
3209 + MAX_EXT_LEN) >= sizeof tmpbuf)
3210 continue; /* don't search dir with too-long name */
3211 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3215 if (strEQ(scriptname, "-"))
3217 if (dosearch) { /* Look in '.' first. */
3218 const char *cur = scriptname;
3220 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3222 if (strEQ(ext[i++],curext)) {
3223 extidx = -1; /* already has an ext */
3228 DEBUG_p(PerlIO_printf(Perl_debug_log,
3229 "Looking for %s\n",cur));
3230 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3231 && !S_ISDIR(PL_statbuf.st_mode)) {
3239 if (cur == scriptname) {
3240 len = strlen(scriptname);
3241 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3243 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3246 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3247 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3252 #ifdef MACOS_TRADITIONAL
3253 if (dosearch && !strchr(scriptname, ':') &&
3254 (s = PerlEnv_getenv("Commands")))
3256 if (dosearch && !strchr(scriptname, '/')
3258 && !strchr(scriptname, '\\')
3260 && (s = PerlEnv_getenv("PATH")))
3265 bufend = s + strlen(s);
3266 while (s < bufend) {
3267 #ifdef MACOS_TRADITIONAL
3268 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3272 #if defined(atarist) || defined(DOSISH)
3277 && *s != ';'; len++, s++) {
3278 if (len < sizeof tmpbuf)
3281 if (len < sizeof tmpbuf)
3283 #else /* ! (atarist || DOSISH) */
3284 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3287 #endif /* ! (atarist || DOSISH) */
3288 #endif /* MACOS_TRADITIONAL */
3291 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3292 continue; /* don't search dir with too-long name */
3293 #ifdef MACOS_TRADITIONAL
3294 if (len && tmpbuf[len - 1] != ':')
3295 tmpbuf[len++] = ':';
3298 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3299 && tmpbuf[len - 1] != '/'
3300 && tmpbuf[len - 1] != '\\'
3303 tmpbuf[len++] = '/';
3304 if (len == 2 && tmpbuf[0] == '.')
3307 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3311 len = strlen(tmpbuf);
3312 if (extidx > 0) /* reset after previous loop */
3316 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3317 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3318 if (S_ISDIR(PL_statbuf.st_mode)) {
3322 } while ( retval < 0 /* not there */
3323 && extidx>=0 && ext[extidx] /* try an extension? */
3324 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3329 if (S_ISREG(PL_statbuf.st_mode)
3330 && cando(S_IRUSR,TRUE,&PL_statbuf)
3331 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3332 && cando(S_IXUSR,TRUE,&PL_statbuf)
3336 xfound = tmpbuf; /* bingo! */
3340 xfailed = savepv(tmpbuf);
3343 if (!xfound && !seen_dot && !xfailed &&
3344 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3345 || S_ISDIR(PL_statbuf.st_mode)))
3347 seen_dot = 1; /* Disable message. */
3349 if (flags & 1) { /* do or die? */
3350 Perl_croak(aTHX_ "Can't %s %s%s%s",
3351 (xfailed ? "execute" : "find"),
3352 (xfailed ? xfailed : scriptname),
3353 (xfailed ? "" : " on PATH"),
3354 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3359 scriptname = xfound;
3361 return (scriptname ? savepv(scriptname) : NULL);
3364 #ifndef PERL_GET_CONTEXT_DEFINED
3367 Perl_get_context(void)
3370 #if defined(USE_ITHREADS)
3371 # ifdef OLD_PTHREADS_API
3373 if (pthread_getspecific(PL_thr_key, &t))
3374 Perl_croak_nocontext("panic: pthread_getspecific");
3377 # ifdef I_MACH_CTHREADS
3378 return (void*)cthread_data(cthread_self());
3380 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3389 Perl_set_context(void *t)
3392 PERL_ARGS_ASSERT_SET_CONTEXT;
3393 #if defined(USE_ITHREADS)
3394 # ifdef I_MACH_CTHREADS
3395 cthread_set_data(cthread_self(), t);
3397 if (pthread_setspecific(PL_thr_key, t))
3398 Perl_croak_nocontext("panic: pthread_setspecific");
3405 #endif /* !PERL_GET_CONTEXT_DEFINED */
3407 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3416 Perl_get_op_names(pTHX)
3418 PERL_UNUSED_CONTEXT;
3419 return (char **)PL_op_name;
3423 Perl_get_op_descs(pTHX)
3425 PERL_UNUSED_CONTEXT;
3426 return (char **)PL_op_desc;
3430 Perl_get_no_modify(pTHX)
3432 PERL_UNUSED_CONTEXT;
3433 return PL_no_modify;
3437 Perl_get_opargs(pTHX)
3439 PERL_UNUSED_CONTEXT;
3440 return (U32 *)PL_opargs;
3444 Perl_get_ppaddr(pTHX)
3447 PERL_UNUSED_CONTEXT;
3448 return (PPADDR_t*)PL_ppaddr;
3451 #ifndef HAS_GETENV_LEN
3453 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3455 char * const env_trans = PerlEnv_getenv(env_elem);
3456 PERL_UNUSED_CONTEXT;
3457 PERL_ARGS_ASSERT_GETENV_LEN;
3459 *len = strlen(env_trans);
3466 Perl_get_vtbl(pTHX_ int vtbl_id)
3468 const MGVTBL* result;
3469 PERL_UNUSED_CONTEXT;
3473 result = &PL_vtbl_sv;
3476 result = &PL_vtbl_env;
3478 case want_vtbl_envelem:
3479 result = &PL_vtbl_envelem;
3482 result = &PL_vtbl_sig;
3484 case want_vtbl_sigelem:
3485 result = &PL_vtbl_sigelem;
3487 case want_vtbl_pack:
3488 result = &PL_vtbl_pack;
3490 case want_vtbl_packelem:
3491 result = &PL_vtbl_packelem;
3493 case want_vtbl_dbline:
3494 result = &PL_vtbl_dbline;
3497 result = &PL_vtbl_isa;
3499 case want_vtbl_isaelem:
3500 result = &PL_vtbl_isaelem;
3502 case want_vtbl_arylen:
3503 result = &PL_vtbl_arylen;
3505 case want_vtbl_mglob:
3506 result = &PL_vtbl_mglob;
3508 case want_vtbl_nkeys:
3509 result = &PL_vtbl_nkeys;
3511 case want_vtbl_taint:
3512 result = &PL_vtbl_taint;
3514 case want_vtbl_substr:
3515 result = &PL_vtbl_substr;
3518 result = &PL_vtbl_vec;
3521 result = &PL_vtbl_pos;
3524 result = &PL_vtbl_bm;
3527 result = &PL_vtbl_fm;
3529 case want_vtbl_uvar:
3530 result = &PL_vtbl_uvar;
3532 case want_vtbl_defelem:
3533 result = &PL_vtbl_defelem;
3535 case want_vtbl_regexp:
3536 result = &PL_vtbl_regexp;
3538 case want_vtbl_regdata:
3539 result = &PL_vtbl_regdata;
3541 case want_vtbl_regdatum:
3542 result = &PL_vtbl_regdatum;
3544 #ifdef USE_LOCALE_COLLATE
3545 case want_vtbl_collxfrm:
3546 result = &PL_vtbl_collxfrm;
3549 case want_vtbl_amagic:
3550 result = &PL_vtbl_amagic;
3552 case want_vtbl_amagicelem:
3553 result = &PL_vtbl_amagicelem;
3555 case want_vtbl_backref:
3556 result = &PL_vtbl_backref;
3558 case want_vtbl_utf8:
3559 result = &PL_vtbl_utf8;
3565 return (MGVTBL*)result;
3569 Perl_my_fflush_all(pTHX)
3571 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3572 return PerlIO_flush(NULL);
3574 # if defined(HAS__FWALK)
3575 extern int fflush(FILE *);
3576 /* undocumented, unprototyped, but very useful BSDism */
3577 extern void _fwalk(int (*)(FILE *));
3581 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3583 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3584 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3586 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3587 open_max = sysconf(_SC_OPEN_MAX);
3590 open_max = FOPEN_MAX;
3593 open_max = OPEN_MAX;
3604 for (i = 0; i < open_max; i++)
3605 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3606 STDIO_STREAM_ARRAY[i]._file < open_max &&
3607 STDIO_STREAM_ARRAY[i]._flag)
3608 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3612 SETERRNO(EBADF,RMS_IFI);
3619 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3621 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3623 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3624 if (ckWARN(WARN_IO)) {
3625 const char * const direction =
3626 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3628 Perl_warner(aTHX_ packWARN(WARN_IO),
3629 "Filehandle %s opened only for %sput",
3632 Perl_warner(aTHX_ packWARN(WARN_IO),
3633 "Filehandle opened only for %sput", direction);
3640 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3642 warn_type = WARN_CLOSED;
3646 warn_type = WARN_UNOPENED;
3649 if (ckWARN(warn_type)) {
3650 const char * const pars =
3651 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3652 const char * const func =
3654 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3655 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3656 op < 0 ? "" : /* handle phoney cases */
3658 const char * const type =
3660 (OP_IS_SOCKET(op) ||
3661 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3662 "socket" : "filehandle");
3663 if (name && *name) {
3664 Perl_warner(aTHX_ packWARN(warn_type),
3665 "%s%s on %s %s %s", func, pars, vile, type, name);
3666 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3668 aTHX_ packWARN(warn_type),
3669 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3674 Perl_warner(aTHX_ packWARN(warn_type),
3675 "%s%s on %s %s", func, pars, vile, type);
3676 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3678 aTHX_ packWARN(warn_type),
3679 "\t(Are you trying to call %s%s on dirhandle?)\n",
3688 /* in ASCII order, not that it matters */
3689 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3692 Perl_ebcdic_control(pTHX_ int ch)
3700 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3701 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3704 if (ctlp == controllablechars)
3705 return('\177'); /* DEL */
3707 return((unsigned char)(ctlp - controllablechars - 1));
3708 } else { /* Want uncontrol */
3709 if (ch == '\177' || ch == -1)
3711 else if (ch == '\157')
3713 else if (ch == '\174')
3715 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3717 else if (ch == '\155')
3719 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3720 return(controllablechars[ch+1]);
3722 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3727 /* To workaround core dumps from the uninitialised tm_zone we get the
3728 * system to give us a reasonable struct to copy. This fix means that
3729 * strftime uses the tm_zone and tm_gmtoff values returned by
3730 * localtime(time()). That should give the desired result most of the
3731 * time. But probably not always!
3733 * This does not address tzname aspects of NETaa14816.
3738 # ifndef STRUCT_TM_HASZONE
3739 # define STRUCT_TM_HASZONE
3743 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3744 # ifndef HAS_TM_TM_ZONE
3745 # define HAS_TM_TM_ZONE
3750 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3752 #ifdef HAS_TM_TM_ZONE
3754 const struct tm* my_tm;
3755 PERL_ARGS_ASSERT_INIT_TM;
3757 my_tm = localtime(&now);
3759 Copy(my_tm, ptm, 1, struct tm);
3761 PERL_ARGS_ASSERT_INIT_TM;
3762 PERL_UNUSED_ARG(ptm);
3767 * mini_mktime - normalise struct tm values without the localtime()
3768 * semantics (and overhead) of mktime().
3771 Perl_mini_mktime(pTHX_ struct tm *ptm)
3775 int month, mday, year, jday;
3776 int odd_cent, odd_year;
3777 PERL_UNUSED_CONTEXT;
3779 PERL_ARGS_ASSERT_MINI_MKTIME;
3781 #define DAYS_PER_YEAR 365
3782 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3783 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3784 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3785 #define SECS_PER_HOUR (60*60)
3786 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3787 /* parentheses deliberately absent on these two, otherwise they don't work */
3788 #define MONTH_TO_DAYS 153/5
3789 #define DAYS_TO_MONTH 5/153
3790 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3791 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3792 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3793 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3796 * Year/day algorithm notes:
3798 * With a suitable offset for numeric value of the month, one can find
3799 * an offset into the year by considering months to have 30.6 (153/5) days,
3800 * using integer arithmetic (i.e., with truncation). To avoid too much
3801 * messing about with leap days, we consider January and February to be
3802 * the 13th and 14th month of the previous year. After that transformation,
3803 * we need the month index we use to be high by 1 from 'normal human' usage,
3804 * so the month index values we use run from 4 through 15.
3806 * Given that, and the rules for the Gregorian calendar (leap years are those
3807 * divisible by 4 unless also divisible by 100, when they must be divisible
3808 * by 400 instead), we can simply calculate the number of days since some
3809 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3810 * the days we derive from our month index, and adding in the day of the
3811 * month. The value used here is not adjusted for the actual origin which
3812 * it normally would use (1 January A.D. 1), since we're not exposing it.
3813 * We're only building the value so we can turn around and get the
3814 * normalised values for the year, month, day-of-month, and day-of-year.
3816 * For going backward, we need to bias the value we're using so that we find
3817 * the right year value. (Basically, we don't want the contribution of
3818 * March 1st to the number to apply while deriving the year). Having done
3819 * that, we 'count up' the contribution to the year number by accounting for
3820 * full quadracenturies (400-year periods) with their extra leap days, plus
3821 * the contribution from full centuries (to avoid counting in the lost leap
3822 * days), plus the contribution from full quad-years (to count in the normal
3823 * leap days), plus the leftover contribution from any non-leap years.
3824 * At this point, if we were working with an actual leap day, we'll have 0
3825 * days left over. This is also true for March 1st, however. So, we have
3826 * to special-case that result, and (earlier) keep track of the 'odd'
3827 * century and year contributions. If we got 4 extra centuries in a qcent,
3828 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3829 * Otherwise, we add back in the earlier bias we removed (the 123 from
3830 * figuring in March 1st), find the month index (integer division by 30.6),
3831 * and the remainder is the day-of-month. We then have to convert back to
3832 * 'real' months (including fixing January and February from being 14/15 in
3833 * the previous year to being in the proper year). After that, to get
3834 * tm_yday, we work with the normalised year and get a new yearday value for
3835 * January 1st, which we subtract from the yearday value we had earlier,
3836 * representing the date we've re-built. This is done from January 1
3837 * because tm_yday is 0-origin.
3839 * Since POSIX time routines are only guaranteed to work for times since the
3840 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3841 * applies Gregorian calendar rules even to dates before the 16th century
3842 * doesn't bother me. Besides, you'd need cultural context for a given
3843 * date to know whether it was Julian or Gregorian calendar, and that's
3844 * outside the scope for this routine. Since we convert back based on the
3845 * same rules we used to build the yearday, you'll only get strange results
3846 * for input which needed normalising, or for the 'odd' century years which
3847 * were leap years in the Julian calander but not in the Gregorian one.
3848 * I can live with that.
3850 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3851 * that's still outside the scope for POSIX time manipulation, so I don't
3855 year = 1900 + ptm->tm_year;
3856 month = ptm->tm_mon;
3857 mday = ptm->tm_mday;
3858 /* allow given yday with no month & mday to dominate the result */
3859 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3862 jday = 1 + ptm->tm_yday;
3871 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3872 yearday += month*MONTH_TO_DAYS + mday + jday;
3874 * Note that we don't know when leap-seconds were or will be,
3875 * so we have to trust the user if we get something which looks
3876 * like a sensible leap-second. Wild values for seconds will
3877 * be rationalised, however.
3879 if ((unsigned) ptm->tm_sec <= 60) {
3886 secs += 60 * ptm->tm_min;
3887 secs += SECS_PER_HOUR * ptm->tm_hour;
3889 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3890 /* got negative remainder, but need positive time */
3891 /* back off an extra day to compensate */
3892 yearday += (secs/SECS_PER_DAY)-1;
3893 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3896 yearday += (secs/SECS_PER_DAY);
3897 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3900 else if (secs >= SECS_PER_DAY) {
3901 yearday += (secs/SECS_PER_DAY);
3902 secs %= SECS_PER_DAY;
3904 ptm->tm_hour = secs/SECS_PER_HOUR;
3905 secs %= SECS_PER_HOUR;
3906 ptm->tm_min = secs/60;
3908 ptm->tm_sec += secs;
3909 /* done with time of day effects */
3911 * The algorithm for yearday has (so far) left it high by 428.
3912 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3913 * bias it by 123 while trying to figure out what year it
3914 * really represents. Even with this tweak, the reverse
3915 * translation fails for years before A.D. 0001.
3916 * It would still fail for Feb 29, but we catch that one below.
3918 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3919 yearday -= YEAR_ADJUST;
3920 year = (yearday / DAYS_PER_QCENT) * 400;
3921 yearday %= DAYS_PER_QCENT;
3922 odd_cent = yearday / DAYS_PER_CENT;
3923 year += odd_cent * 100;
3924 yearday %= DAYS_PER_CENT;
3925 year += (yearday / DAYS_PER_QYEAR) * 4;
3926 yearday %= DAYS_PER_QYEAR;
3927 odd_year = yearday / DAYS_PER_YEAR;
3929 yearday %= DAYS_PER_YEAR;
3930 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3935 yearday += YEAR_ADJUST; /* recover March 1st crock */
3936 month = yearday*DAYS_TO_MONTH;
3937 yearday -= month*MONTH_TO_DAYS;
3938 /* recover other leap-year adjustment */
3947 ptm->tm_year = year - 1900;
3949 ptm->tm_mday = yearday;
3950 ptm->tm_mon = month;
3954 ptm->tm_mon = month - 1;
3956 /* re-build yearday based on Jan 1 to get tm_yday */
3958 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3959 yearday += 14*MONTH_TO_DAYS + 1;
3960 ptm->tm_yday = jday - yearday;
3961 /* fix tm_wday if not overridden by caller */
3962 if ((unsigned)ptm->tm_wday > 6)
3963 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3967 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)
3975 PERL_ARGS_ASSERT_MY_STRFTIME;
3977 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3980 mytm.tm_hour = hour;
3981 mytm.tm_mday = mday;
3983 mytm.tm_year = year;
3984 mytm.tm_wday = wday;
3985 mytm.tm_yday = yday;
3986 mytm.tm_isdst = isdst;
3988 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3989 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3994 #ifdef HAS_TM_TM_GMTOFF
3995 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3997 #ifdef HAS_TM_TM_ZONE
3998 mytm.tm_zone = mytm2.tm_zone;
4003 Newx(buf, buflen, char);
4004 len = strftime(buf, buflen, fmt, &mytm);
4006 ** The following is needed to handle to the situation where
4007 ** tmpbuf overflows. Basically we want to allocate a buffer
4008 ** and try repeatedly. The reason why it is so complicated
4009 ** is that getting a return value of 0 from strftime can indicate
4010 ** one of the following:
4011 ** 1. buffer overflowed,
4012 ** 2. illegal conversion specifier, or
4013 ** 3. the format string specifies nothing to be returned(not
4014 ** an error). This could be because format is an empty string
4015 ** or it specifies %p that yields an empty string in some locale.
4016 ** If there is a better way to make it portable, go ahead by
4019 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4022 /* Possibly buf overflowed - try again with a bigger buf */
4023 const int fmtlen = strlen(fmt);
4024 int bufsize = fmtlen + buflen;
4026 Newx(buf, bufsize, char);
4028 buflen = strftime(buf, bufsize, fmt, &mytm);
4029 if (buflen > 0 && buflen < bufsize)
4031 /* heuristic to prevent out-of-memory errors */
4032 if (bufsize > 100*fmtlen) {
4038 Renew(buf, bufsize, char);
4043 Perl_croak(aTHX_ "panic: no strftime");
4049 #define SV_CWD_RETURN_UNDEF \
4050 sv_setsv(sv, &PL_sv_undef); \
4053 #define SV_CWD_ISDOT(dp) \
4054 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4055 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4058 =head1 Miscellaneous Functions
4060 =for apidoc getcwd_sv
4062 Fill the sv with current working directory
4067 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4068 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4069 * getcwd(3) if available
4070 * Comments from the orignal:
4071 * This is a faster version of getcwd. It's also more dangerous
4072 * because you might chdir out of a directory that you can't chdir
4076 Perl_getcwd_sv(pTHX_ register SV *sv)
4080 #ifndef INCOMPLETE_TAINTS
4084 PERL_ARGS_ASSERT_GETCWD_SV;
4088 char buf[MAXPATHLEN];
4090 /* Some getcwd()s automatically allocate a buffer of the given
4091 * size from the heap if they are given a NULL buffer pointer.
4092 * The problem is that this behaviour is not portable. */
4093 if (getcwd(buf, sizeof(buf) - 1)) {
4098 sv_setsv(sv, &PL_sv_undef);
4106 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4110 SvUPGRADE(sv, SVt_PV);
4112 if (PerlLIO_lstat(".", &statbuf) < 0) {
4113 SV_CWD_RETURN_UNDEF;
4116 orig_cdev = statbuf.st_dev;
4117 orig_cino = statbuf.st_ino;
4126 if (PerlDir_chdir("..") < 0) {
4127 SV_CWD_RETURN_UNDEF;
4129 if (PerlLIO_stat(".", &statbuf) < 0) {
4130 SV_CWD_RETURN_UNDEF;
4133 cdev = statbuf.st_dev;
4134 cino = statbuf.st_ino;
4136 if (odev == cdev && oino == cino) {
4139 if (!(dir = PerlDir_open("."))) {
4140 SV_CWD_RETURN_UNDEF;
4143 while ((dp = PerlDir_read(dir)) != NULL) {
4145 const int namelen = dp->d_namlen;
4147 const int namelen = strlen(dp->d_name);
4150 if (SV_CWD_ISDOT(dp)) {
4154 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4155 SV_CWD_RETURN_UNDEF;
4158 tdev = statbuf.st_dev;
4159 tino = statbuf.st_ino;
4160 if (tino == oino && tdev == odev) {
4166 SV_CWD_RETURN_UNDEF;
4169 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4170 SV_CWD_RETURN_UNDEF;
4173 SvGROW(sv, pathlen + namelen + 1);
4177 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4180 /* prepend current directory to the front */
4182 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4183 pathlen += (namelen + 1);
4185 #ifdef VOID_CLOSEDIR
4188 if (PerlDir_close(dir) < 0) {
4189 SV_CWD_RETURN_UNDEF;
4195 SvCUR_set(sv, pathlen);
4199 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4200 SV_CWD_RETURN_UNDEF;
4203 if (PerlLIO_stat(".", &statbuf) < 0) {
4204 SV_CWD_RETURN_UNDEF;
4207 cdev = statbuf.st_dev;
4208 cino = statbuf.st_ino;
4210 if (cdev != orig_cdev || cino != orig_cino) {
4211 Perl_croak(aTHX_ "Unstable directory path, "
4212 "current directory changed unexpectedly");
4223 #define VERSION_MAX 0x7FFFFFFF
4225 =for apidoc scan_version
4227 Returns a pointer to the next character after the parsed
4228 version string, as well as upgrading the passed in SV to
4231 Function must be called with an already existing SV like
4234 s = scan_version(s, SV *sv, bool qv);
4236 Performs some preprocessing to the string to ensure that
4237 it has the correct characteristics of a version. Flags the
4238 object if it contains an underscore (which denotes this
4239 is an alpha version). The boolean qv denotes that the version
4240 should be interpreted as if it had multiple decimals, even if
4247 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4256 AV * const av = newAV();
4257 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4259 PERL_ARGS_ASSERT_SCAN_VERSION;
4261 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4263 while (isSPACE(*s)) /* leading whitespace is OK */
4269 s++; /* get past 'v' */
4270 qv = 1; /* force quoted version processing */
4275 /* pre-scan the input string to check for decimals/underbars */
4276 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4281 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4285 else if ( *pos == '_' )
4288 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4290 width = pos - last - 1; /* natural width of sub-version */
4295 if ( alpha && !saw_period )
4296 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4298 if ( alpha && saw_period && width == 0 )
4299 Perl_croak(aTHX_ "Invalid version format (misplaced _ in number)");
4301 if ( saw_period > 1 )
4302 qv = 1; /* force quoted version processing */
4308 (void)hv_stores((HV *)hv, "qv", newSViv(qv));
4310 (void)hv_stores((HV *)hv, "alpha", newSViv(alpha));
4311 if ( !qv && width < 3 )
4312 (void)hv_stores((HV *)hv, "width", newSViv(width));
4314 while (isDIGIT(*pos))
4316 if (!isALPHA(*pos)) {
4322 /* this is atoi() that delimits on underscores */
4323 const char *end = pos;
4327 /* the following if() will only be true after the decimal
4328 * point of a version originally created with a bare
4329 * floating point number, i.e. not quoted in any way
4331 if ( !qv && s > start && saw_period == 1 ) {
4335 rev += (*s - '0') * mult;
4337 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4338 || (PERL_ABS(rev) > VERSION_MAX )) {
4339 if(ckWARN(WARN_OVERFLOW))
4340 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4341 "Integer overflow in version %d",VERSION_MAX);
4352 while (--end >= s) {
4354 rev += (*end - '0') * mult;
4356 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4357 || (PERL_ABS(rev) > VERSION_MAX )) {
4358 if(ckWARN(WARN_OVERFLOW))
4359 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4360 "Integer overflow in version");
4369 /* Append revision */
4370 av_push(av, newSViv(rev));
4375 else if ( *pos == '.' )
4377 else if ( *pos == '_' && isDIGIT(pos[1]) )
4379 else if ( isDIGIT(*pos) )
4386 while ( isDIGIT(*pos) )
4391 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4399 if ( qv ) { /* quoted versions always get at least three terms*/
4400 I32 len = av_len(av);
4401 /* This for loop appears to trigger a compiler bug on OS X, as it
4402 loops infinitely. Yes, len is negative. No, it makes no sense.
4403 Compiler in question is:
4404 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4405 for ( len = 2 - len; len > 0; len-- )
4406 av_push((AV *)sv, newSViv(0));
4410 av_push(av, newSViv(0));
4413 /* need to save off the current version string for later */
4415 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4416 (void)hv_stores((HV *)hv, "original", orig);
4417 (void)hv_stores((HV *)hv, "vinf", newSViv(1));
4419 else if ( s > start ) {
4420 SV * orig = newSVpvn(start,s-start);
4421 if ( qv && saw_period == 1 && *start != 'v' ) {
4422 /* need to insert a v to be consistent */
4423 sv_insert(orig, 0, 0, "v", 1);
4425 (void)hv_stores((HV *)hv, "original", orig);
4428 (void)hv_stores((HV *)hv, "original", newSVpvn("0",1));
4429 av_push(av, newSViv(0));
4432 /* And finally, store the AV in the hash */
4433 (void)hv_stores((HV *)hv, "version", newRV_noinc((SV *)av));
4435 /* fix RT#19517 - special case 'undef' as string */
4436 if ( *s == 'u' && strEQ(s,"undef") ) {
4444 =for apidoc new_version
4446 Returns a new version object based on the passed in SV:
4448 SV *sv = new_version(SV *ver);
4450 Does not alter the passed in ver SV. See "upg_version" if you
4451 want to upgrade the SV.
4457 Perl_new_version(pTHX_ SV *ver)
4460 SV * const rv = newSV(0);
4461 PERL_ARGS_ASSERT_NEW_VERSION;
4462 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4465 AV * const av = newAV();
4467 /* This will get reblessed later if a derived class*/
4468 SV * const hv = newSVrv(rv, "version");
4469 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4474 /* Begin copying all of the elements */
4475 if ( hv_exists((HV *)ver, "qv", 2) )
4476 (void)hv_stores((HV *)hv, "qv", newSViv(1));
4478 if ( hv_exists((HV *)ver, "alpha", 5) )
4479 (void)hv_stores((HV *)hv, "alpha", newSViv(1));
4481 if ( hv_exists((HV*)ver, "width", 5 ) )
4483 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4484 (void)hv_stores((HV *)hv, "width", newSViv(width));
4487 if ( hv_exists((HV*)ver, "original", 8 ) )
4489 SV * pv = *hv_fetchs((HV*)ver, "original", FALSE);
4490 (void)hv_stores((HV *)hv, "original", newSVsv(pv));
4493 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4494 /* This will get reblessed later if a derived class*/
4495 for ( key = 0; key <= av_len(sav); key++ )
4497 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4498 av_push(av, newSViv(rev));
4501 (void)hv_stores((HV *)hv, "version", newRV_noinc((SV *)av));
4506 const MAGIC* const mg = SvVSTRING_mg(ver);
4507 if ( mg ) { /* already a v-string */
4508 const STRLEN len = mg->mg_len;
4509 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4510 sv_setpvn(rv,version,len);
4511 /* this is for consistency with the pure Perl class */
4512 if ( *version != 'v' )
4513 sv_insert(rv, 0, 0, "v", 1);
4518 sv_setsv(rv,ver); /* make a duplicate */
4523 return upg_version(rv, FALSE);
4527 =for apidoc upg_version
4529 In-place upgrade of the supplied SV to a version object.
4531 SV *sv = upg_version(SV *sv, bool qv);
4533 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4534 to force this SV to be interpreted as an "extended" version.
4540 Perl_upg_version(pTHX_ SV *ver, bool qv)
4542 const char *version, *s;
4547 PERL_ARGS_ASSERT_UPG_VERSION;
4549 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4551 /* may get too much accuracy */
4553 #ifdef USE_LOCALE_NUMERIC
4554 char *loc = setlocale(LC_NUMERIC, "C");
4556 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4557 #ifdef USE_LOCALE_NUMERIC
4558 setlocale(LC_NUMERIC, loc);
4560 while (tbuf[len-1] == '0' && len > 0) len--;
4561 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4562 version = savepvn(tbuf, len);
4565 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4566 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4570 else /* must be a string or something like a string */
4573 version = savepv(SvPV(ver,len));
4575 # if PERL_VERSION > 5
4576 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4577 if ( len == 3 && !instr(version,".") && !instr(version,"_") ) {
4578 /* may be a v-string */
4579 SV * const nsv = sv_newmortal();
4583 sv_setpvf(nsv,"v%vd",ver);
4584 pos = nver = savepv(SvPV_nolen(nsv));
4586 /* scan the resulting formatted string */
4587 pos++; /* skip the leading 'v' */
4588 while ( *pos == '.' || isDIGIT(*pos) ) {
4594 /* is definitely a v-string */
4595 if ( saw_period == 2 ) {
4604 s = scan_version(version, ver, qv);
4606 if(ckWARN(WARN_MISC))
4607 Perl_warner(aTHX_ packWARN(WARN_MISC),
4608 "Version string '%s' contains invalid data; "
4609 "ignoring: '%s'", version, s);
4617 Validates that the SV contains a valid version object.
4619 bool vverify(SV *vobj);
4621 Note that it only confirms the bare minimum structure (so as not to get
4622 confused by derived classes which may contain additional hash entries):
4626 =item * The SV contains a [reference to a] hash
4628 =item * The hash contains a "version" key
4630 =item * The "version" key has [a reference to] an AV as its value
4638 Perl_vverify(pTHX_ SV *vs)
4642 PERL_ARGS_ASSERT_VVERIFY;
4647 /* see if the appropriate elements exist */
4648 if ( SvTYPE(vs) == SVt_PVHV
4649 && hv_exists((HV*)vs, "version", 7)
4650 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4651 && SvTYPE(sv) == SVt_PVAV )
4660 Accepts a version object and returns the normalized floating
4661 point representation. Call like:
4665 NOTE: you can pass either the object directly or the SV
4666 contained within the RV.
4672 Perl_vnumify(pTHX_ SV *vs)
4677 SV * const sv = newSV(0);
4680 PERL_ARGS_ASSERT_VNUMIFY;
4686 Perl_croak(aTHX_ "Invalid version object");
4688 /* see if various flags exist */
4689 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4691 if ( hv_exists((HV*)vs, "width", 5 ) )
4692 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4697 /* attempt to retrieve the version array */
4698 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4710 digit = SvIV(*av_fetch(av, 0, 0));
4711 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4712 for ( i = 1 ; i < len ; i++ )
4714 digit = SvIV(*av_fetch(av, i, 0));
4716 const int denom = (width == 2 ? 10 : 100);
4717 const div_t term = div((int)PERL_ABS(digit),denom);
4718 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4721 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4727 digit = SvIV(*av_fetch(av, len, 0));
4728 if ( alpha && width == 3 ) /* alpha version */
4730 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4734 sv_catpvs(sv, "000");
4742 Accepts a version object and returns the normalized string
4743 representation. Call like:
4747 NOTE: you can pass either the object directly or the SV
4748 contained within the RV.
4754 Perl_vnormal(pTHX_ SV *vs)
4758 SV * const sv = newSV(0);
4761 PERL_ARGS_ASSERT_VNORMAL;
4767 Perl_croak(aTHX_ "Invalid version object");
4769 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4771 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4779 digit = SvIV(*av_fetch(av, 0, 0));
4780 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4781 for ( i = 1 ; i < len ; i++ ) {
4782 digit = SvIV(*av_fetch(av, i, 0));
4783 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4788 /* handle last digit specially */
4789 digit = SvIV(*av_fetch(av, len, 0));
4791 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4793 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4796 if ( len <= 2 ) { /* short version, must be at least three */
4797 for ( len = 2 - len; len != 0; len-- )
4804 =for apidoc vstringify
4806 In order to maintain maximum compatibility with earlier versions
4807 of Perl, this function will return either the floating point
4808 notation or the multiple dotted notation, depending on whether
4809 the original version contained 1 or more dots, respectively
4815 Perl_vstringify(pTHX_ SV *vs)
4817 PERL_ARGS_ASSERT_VSTRINGIFY;
4823 Perl_croak(aTHX_ "Invalid version object");
4825 if (hv_exists((HV*)vs, "original", sizeof("original") - 1)) {
4827 pv = *hv_fetchs((HV*)vs, "original", FALSE);
4831 return &PL_sv_undef;
4834 if ( hv_exists((HV *)vs, "qv", 2) )
4844 Version object aware cmp. Both operands must already have been
4845 converted into version objects.
4851 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4854 bool lalpha = FALSE;
4855 bool ralpha = FALSE;
4860 PERL_ARGS_ASSERT_VCMP;
4867 if ( !vverify(lhv) )
4868 Perl_croak(aTHX_ "Invalid version object");
4870 if ( !vverify(rhv) )
4871 Perl_croak(aTHX_ "Invalid version object");
4873 /* get the left hand term */
4874 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4875 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4878 /* and the right hand term */
4879 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4880 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4888 while ( i <= m && retval == 0 )
4890 left = SvIV(*av_fetch(lav,i,0));
4891 right = SvIV(*av_fetch(rav,i,0));
4899 /* tiebreaker for alpha with identical terms */
4900 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4902 if ( lalpha && !ralpha )
4906 else if ( ralpha && !lalpha)
4912 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4916 while ( i <= r && retval == 0 )
4918 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4919 retval = -1; /* not a match after all */
4925 while ( i <= l && retval == 0 )
4927 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4928 retval = +1; /* not a match after all */
4936 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4937 # define EMULATE_SOCKETPAIR_UDP
4940 #ifdef EMULATE_SOCKETPAIR_UDP
4942 S_socketpair_udp (int fd[2]) {
4944 /* Fake a datagram socketpair using UDP to localhost. */
4945 int sockets[2] = {-1, -1};
4946 struct sockaddr_in addresses[2];
4948 Sock_size_t size = sizeof(struct sockaddr_in);
4949 unsigned short port;
4952 memset(&addresses, 0, sizeof(addresses));
4955 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4956 if (sockets[i] == -1)
4957 goto tidy_up_and_fail;
4959 addresses[i].sin_family = AF_INET;
4960 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4961 addresses[i].sin_port = 0; /* kernel choses port. */
4962 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4963 sizeof(struct sockaddr_in)) == -1)
4964 goto tidy_up_and_fail;
4967 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4968 for each connect the other socket to it. */
4971 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4973 goto tidy_up_and_fail;
4974 if (size != sizeof(struct sockaddr_in))
4975 goto abort_tidy_up_and_fail;
4976 /* !1 is 0, !0 is 1 */
4977 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4978 sizeof(struct sockaddr_in)) == -1)
4979 goto tidy_up_and_fail;
4982 /* Now we have 2 sockets connected to each other. I don't trust some other
4983 process not to have already sent a packet to us (by random) so send
4984 a packet from each to the other. */
4987 /* I'm going to send my own port number. As a short.
4988 (Who knows if someone somewhere has sin_port as a bitfield and needs
4989 this routine. (I'm assuming crays have socketpair)) */
4990 port = addresses[i].sin_port;
4991 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4992 if (got != sizeof(port)) {
4994 goto tidy_up_and_fail;
4995 goto abort_tidy_up_and_fail;
4999 /* Packets sent. I don't trust them to have arrived though.
5000 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5001 connect to localhost will use a second kernel thread. In 2.6 the
5002 first thread running the connect() returns before the second completes,
5003 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5004 returns 0. Poor programs have tripped up. One poor program's authors'
5005 had a 50-1 reverse stock split. Not sure how connected these were.)
5006 So I don't trust someone not to have an unpredictable UDP stack.
5010 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5011 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5015 FD_SET((unsigned int)sockets[0], &rset);
5016 FD_SET((unsigned int)sockets[1], &rset);
5018 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5019 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5020 || !FD_ISSET(sockets[1], &rset)) {
5021 /* I hope this is portable and appropriate. */
5023 goto tidy_up_and_fail;
5024 goto abort_tidy_up_and_fail;
5028 /* And the paranoia department even now doesn't trust it to have arrive
5029 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5031 struct sockaddr_in readfrom;
5032 unsigned short buffer[2];
5037 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5038 sizeof(buffer), MSG_DONTWAIT,
5039 (struct sockaddr *) &readfrom, &size);
5041 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5043 (struct sockaddr *) &readfrom, &size);
5047 goto tidy_up_and_fail;
5048 if (got != sizeof(port)
5049 || size != sizeof(struct sockaddr_in)
5050 /* Check other socket sent us its port. */
5051 || buffer[0] != (unsigned short) addresses[!i].sin_port
5052 /* Check kernel says we got the datagram from that socket */
5053 || readfrom.sin_family != addresses[!i].sin_family
5054 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5055 || readfrom.sin_port != addresses[!i].sin_port)
5056 goto abort_tidy_up_and_fail;
5059 /* My caller (my_socketpair) has validated that this is non-NULL */
5062 /* I hereby declare this connection open. May God bless all who cross
5066 abort_tidy_up_and_fail:
5067 errno = ECONNABORTED;
5070 const int save_errno = errno;
5071 if (sockets[0] != -1)
5072 PerlLIO_close(sockets[0]);
5073 if (sockets[1] != -1)
5074 PerlLIO_close(sockets[1]);
5079 #endif /* EMULATE_SOCKETPAIR_UDP */
5081 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5083 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5084 /* Stevens says that family must be AF_LOCAL, protocol 0.
5085 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5090 struct sockaddr_in listen_addr;
5091 struct sockaddr_in connect_addr;
5096 || family != AF_UNIX
5099 errno = EAFNOSUPPORT;
5107 #ifdef EMULATE_SOCKETPAIR_UDP
5108 if (type == SOCK_DGRAM)
5109 return S_socketpair_udp(fd);
5112 listener = PerlSock_socket(AF_INET, type, 0);
5115 memset(&listen_addr, 0, sizeof(listen_addr));
5116 listen_addr.sin_family = AF_INET;
5117 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5118 listen_addr.sin_port = 0; /* kernel choses port. */
5119 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5120 sizeof(listen_addr)) == -1)
5121 goto tidy_up_and_fail;
5122 if (PerlSock_listen(listener, 1) == -1)
5123 goto tidy_up_and_fail;
5125 connector = PerlSock_socket(AF_INET, type, 0);
5126 if (connector == -1)
5127 goto tidy_up_and_fail;
5128 /* We want to find out the port number to connect to. */
5129 size = sizeof(connect_addr);
5130 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5132 goto tidy_up_and_fail;
5133 if (size != sizeof(connect_addr))
5134 goto abort_tidy_up_and_fail;
5135 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5136 sizeof(connect_addr)) == -1)
5137 goto tidy_up_and_fail;
5139 size = sizeof(listen_addr);
5140 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5143 goto tidy_up_and_fail;
5144 if (size != sizeof(listen_addr))
5145 goto abort_tidy_up_and_fail;
5146 PerlLIO_close(listener);
5147 /* Now check we are talking to ourself by matching port and host on the
5149 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5151 goto tidy_up_and_fail;
5152 if (size != sizeof(connect_addr)
5153 || listen_addr.sin_family != connect_addr.sin_family
5154 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5155 || listen_addr.sin_port != connect_addr.sin_port) {
5156 goto abort_tidy_up_and_fail;
5162 abort_tidy_up_and_fail:
5164 errno = ECONNABORTED; /* This would be the standard thing to do. */
5166 # ifdef ECONNREFUSED
5167 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5169 errno = ETIMEDOUT; /* Desperation time. */
5174 const int save_errno = errno;
5176 PerlLIO_close(listener);
5177 if (connector != -1)
5178 PerlLIO_close(connector);
5180 PerlLIO_close(acceptor);
5186 /* In any case have a stub so that there's code corresponding
5187 * to the my_socketpair in global.sym. */
5189 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5190 #ifdef HAS_SOCKETPAIR
5191 return socketpair(family, type, protocol, fd);
5200 =for apidoc sv_nosharing
5202 Dummy routine which "shares" an SV when there is no sharing module present.
5203 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5204 Exists to avoid test for a NULL function pointer and because it could
5205 potentially warn under some level of strict-ness.
5211 Perl_sv_nosharing(pTHX_ SV *sv)
5213 PERL_UNUSED_CONTEXT;
5214 PERL_UNUSED_ARG(sv);
5219 =for apidoc sv_destroyable
5221 Dummy routine which reports that object can be destroyed when there is no
5222 sharing module present. It ignores its single SV argument, and returns
5223 'true'. Exists to avoid test for a NULL function pointer and because it
5224 could potentially warn under some level of strict-ness.
5230 Perl_sv_destroyable(pTHX_ SV *sv)
5232 PERL_UNUSED_CONTEXT;
5233 PERL_UNUSED_ARG(sv);
5238 Perl_parse_unicode_opts(pTHX_ const char **popt)
5240 const char *p = *popt;
5243 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5247 opt = (U32) atoi(p);
5250 if (*p && *p != '\n' && *p != '\r')
5251 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5256 case PERL_UNICODE_STDIN:
5257 opt |= PERL_UNICODE_STDIN_FLAG; break;
5258 case PERL_UNICODE_STDOUT:
5259 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5260 case PERL_UNICODE_STDERR:
5261 opt |= PERL_UNICODE_STDERR_FLAG; break;
5262 case PERL_UNICODE_STD:
5263 opt |= PERL_UNICODE_STD_FLAG; break;
5264 case PERL_UNICODE_IN:
5265 opt |= PERL_UNICODE_IN_FLAG; break;
5266 case PERL_UNICODE_OUT:
5267 opt |= PERL_UNICODE_OUT_FLAG; break;
5268 case PERL_UNICODE_INOUT:
5269 opt |= PERL_UNICODE_INOUT_FLAG; break;
5270 case PERL_UNICODE_LOCALE:
5271 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5272 case PERL_UNICODE_ARGV:
5273 opt |= PERL_UNICODE_ARGV_FLAG; break;
5274 case PERL_UNICODE_UTF8CACHEASSERT:
5275 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5277 if (*p != '\n' && *p != '\r')
5279 "Unknown Unicode option letter '%c'", *p);
5285 opt = PERL_UNICODE_DEFAULT_FLAGS;
5287 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5288 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5289 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5301 * This is really just a quick hack which grabs various garbage
5302 * values. It really should be a real hash algorithm which
5303 * spreads the effect of every input bit onto every output bit,
5304 * if someone who knows about such things would bother to write it.
5305 * Might be a good idea to add that function to CORE as well.
5306 * No numbers below come from careful analysis or anything here,
5307 * except they are primes and SEED_C1 > 1E6 to get a full-width
5308 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5309 * probably be bigger too.
5312 # define SEED_C1 1000003
5313 #define SEED_C4 73819
5315 # define SEED_C1 25747
5316 #define SEED_C4 20639
5320 #define SEED_C5 26107
5322 #ifndef PERL_NO_DEV_RANDOM
5327 # include <starlet.h>
5328 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5329 * in 100-ns units, typically incremented ever 10 ms. */
5330 unsigned int when[2];
5332 # ifdef HAS_GETTIMEOFDAY
5333 struct timeval when;
5339 /* This test is an escape hatch, this symbol isn't set by Configure. */
5340 #ifndef PERL_NO_DEV_RANDOM
5341 #ifndef PERL_RANDOM_DEVICE
5342 /* /dev/random isn't used by default because reads from it will block
5343 * if there isn't enough entropy available. You can compile with
5344 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5345 * is enough real entropy to fill the seed. */
5346 # define PERL_RANDOM_DEVICE "/dev/urandom"
5348 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5350 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5359 _ckvmssts(sys$gettim(when));
5360 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5362 # ifdef HAS_GETTIMEOFDAY
5363 PerlProc_gettimeofday(&when,NULL);
5364 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5367 u = (U32)SEED_C1 * when;
5370 u += SEED_C3 * (U32)PerlProc_getpid();
5371 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5372 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5373 u += SEED_C5 * (U32)PTR2UV(&when);
5379 Perl_get_hash_seed(pTHX)
5382 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5388 if (s && isDIGIT(*s))
5389 myseed = (UV)Atoul(s);
5391 #ifdef USE_HASH_SEED_EXPLICIT
5395 /* Compute a random seed */
5396 (void)seedDrand01((Rand_seed_t)seed());
5397 myseed = (UV)(Drand01() * (NV)UV_MAX);
5398 #if RANDBITS < (UVSIZE * 8)
5399 /* Since there are not enough randbits to to reach all
5400 * the bits of a UV, the low bits might need extra
5401 * help. Sum in another random number that will
5402 * fill in the low bits. */
5404 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
5405 #endif /* RANDBITS < (UVSIZE * 8) */
5406 if (myseed == 0) { /* Superparanoia. */
5407 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5409 Perl_croak(aTHX_ "Your random numbers are not that random");
5412 PL_rehash_seed_set = TRUE;
5419 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5421 const char * const stashpv = CopSTASHPV(c);
5422 const char * const name = HvNAME_get(hv);
5423 PERL_UNUSED_CONTEXT;
5424 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5426 if (stashpv == name)
5428 if (stashpv && name)
5429 if (strEQ(stashpv, name))
5436 #ifdef PERL_GLOBAL_STRUCT
5438 #define PERL_GLOBAL_STRUCT_INIT
5439 #include "opcode.h" /* the ppaddr and check */
5442 Perl_init_global_struct(pTHX)
5444 struct perl_vars *plvarsp = NULL;
5445 # ifdef PERL_GLOBAL_STRUCT
5446 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5447 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5448 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5449 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5450 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5454 plvarsp = PL_VarsPtr;
5455 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5461 # define PERLVAR(var,type) /**/
5462 # define PERLVARA(var,n,type) /**/
5463 # define PERLVARI(var,type,init) plvarsp->var = init;
5464 # define PERLVARIC(var,type,init) plvarsp->var = init;
5465 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5466 # include "perlvars.h"
5472 # ifdef PERL_GLOBAL_STRUCT
5475 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5476 if (!plvarsp->Gppaddr)
5480 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5481 if (!plvarsp->Gcheck)
5483 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5484 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5486 # ifdef PERL_SET_VARS
5487 PERL_SET_VARS(plvarsp);
5489 # undef PERL_GLOBAL_STRUCT_INIT
5494 #endif /* PERL_GLOBAL_STRUCT */
5496 #ifdef PERL_GLOBAL_STRUCT
5499 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5501 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5502 # ifdef PERL_GLOBAL_STRUCT
5503 # ifdef PERL_UNSET_VARS
5504 PERL_UNSET_VARS(plvarsp);
5506 free(plvarsp->Gppaddr);
5507 free(plvarsp->Gcheck);
5508 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5514 #endif /* PERL_GLOBAL_STRUCT */
5519 * PERL_MEM_LOG: the Perl_mem_log_..() will be compiled.
5521 * PERL_MEM_LOG_ENV: if defined, during run time the environment
5522 * variable PERL_MEM_LOG will be consulted, and if the integer value
5523 * of that is true, the logging will happen. (The default is to
5524 * always log if the PERL_MEM_LOG define was in effect.)
5528 * PERL_MEM_LOG_SPRINTF_BUF_SIZE: size of a (stack-allocated) buffer
5529 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5531 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5534 * PERL_MEM_LOG_FD: the file descriptor the Perl_mem_log_...() will
5535 * log to. You can also define in compile time PERL_MEM_LOG_ENV_FD,
5536 * in which case the environment variable PERL_MEM_LOG_FD will be
5537 * consulted for the file descriptor number to use.
5539 #ifndef PERL_MEM_LOG_FD
5540 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5544 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)
5546 #ifdef PERL_MEM_LOG_STDERR
5547 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5550 # ifdef PERL_MEM_LOG_ENV
5551 s = getenv("PERL_MEM_LOG");
5552 if (s ? atoi(s) : 0)
5555 /* We can't use SVs or PerlIO for obvious reasons,
5556 * so we'll use stdio and low-level IO instead. */
5557 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5558 # ifdef PERL_MEM_LOG_TIMESTAMP
5560 # ifdef HAS_GETTIMEOFDAY
5561 gettimeofday(&tv, 0);
5563 /* If there are other OS specific ways of hires time than
5564 * gettimeofday() (see ext/Time/HiRes), the easiest way is
5565 * probably that they would be used to fill in the struct
5572 # ifdef PERL_MEM_LOG_TIMESTAMP
5575 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5576 " %s = %"IVdf": %"UVxf"\n",
5577 # ifdef PERL_MEM_LOG_TIMESTAMP
5578 (int)tv.tv_sec, (int)tv.tv_usec,
5580 filename, linenumber, funcname, n, typesize,
5581 typename, n * typesize, PTR2UV(newalloc));
5582 # ifdef PERL_MEM_LOG_ENV_FD
5583 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5584 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5586 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5595 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)
5597 #ifdef PERL_MEM_LOG_STDERR
5598 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5601 # ifdef PERL_MEM_LOG_ENV
5602 s = PerlEnv_getenv("PERL_MEM_LOG");
5603 if (s ? atoi(s) : 0)
5606 /* We can't use SVs or PerlIO for obvious reasons,
5607 * so we'll use stdio and low-level IO instead. */
5608 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5609 # ifdef PERL_MEM_LOG_TIMESTAMP
5611 gettimeofday(&tv, 0);
5617 # ifdef PERL_MEM_LOG_TIMESTAMP
5620 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5621 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5622 # ifdef PERL_MEM_LOG_TIMESTAMP
5623 (int)tv.tv_sec, (int)tv.tv_usec,
5625 filename, linenumber, funcname, n, typesize,
5626 typename, n * typesize, PTR2UV(oldalloc),
5628 # ifdef PERL_MEM_LOG_ENV_FD
5629 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5630 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5632 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5641 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5643 #ifdef PERL_MEM_LOG_STDERR
5644 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5647 # ifdef PERL_MEM_LOG_ENV
5648 s = PerlEnv_getenv("PERL_MEM_LOG");
5649 if (s ? atoi(s) : 0)
5652 /* We can't use SVs or PerlIO for obvious reasons,
5653 * so we'll use stdio and low-level IO instead. */
5654 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5655 # ifdef PERL_MEM_LOG_TIMESTAMP
5657 gettimeofday(&tv, 0);
5663 # ifdef PERL_MEM_LOG_TIMESTAMP
5666 "free: %s:%d:%s: %"UVxf"\n",
5667 # ifdef PERL_MEM_LOG_TIMESTAMP
5668 (int)tv.tv_sec, (int)tv.tv_usec,
5670 filename, linenumber, funcname,
5672 # ifdef PERL_MEM_LOG_ENV_FD
5673 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5674 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5676 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5684 #endif /* PERL_MEM_LOG */
5687 =for apidoc my_sprintf
5689 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5690 the length of the string written to the buffer. Only rare pre-ANSI systems
5691 need the wrapper function - usually this is a direct call to C<sprintf>.
5695 #ifndef SPRINTF_RETURNS_STRLEN
5697 Perl_my_sprintf(char *buffer, const char* pat, ...)
5700 PERL_ARGS_ASSERT_MY_SPRINTF;
5701 va_start(args, pat);
5702 vsprintf(buffer, pat, args);
5704 return strlen(buffer);
5709 =for apidoc my_snprintf
5711 The C library C<snprintf> functionality, if available and
5712 standards-compliant (uses C<vsnprintf>, actually). However, if the
5713 C<vsnprintf> is not available, will unfortunately use the unsafe
5714 C<vsprintf> which can overrun the buffer (there is an overrun check,
5715 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5716 getting C<vsnprintf>.
5721 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5726 PERL_ARGS_ASSERT_MY_SNPRINTF;
5727 va_start(ap, format);
5728 #ifdef HAS_VSNPRINTF
5729 retval = vsnprintf(buffer, len, format, ap);
5731 retval = vsprintf(buffer, format, ap);
5734 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5735 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5736 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
5741 =for apidoc my_vsnprintf
5743 The C library C<vsnprintf> if available and standards-compliant.
5744 However, if if the C<vsnprintf> is not available, will unfortunately
5745 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5746 overrun check, but that may be too late). Consider using
5747 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5752 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5759 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5761 Perl_va_copy(ap, apc);
5762 # ifdef HAS_VSNPRINTF
5763 retval = vsnprintf(buffer, len, format, apc);
5765 retval = vsprintf(buffer, format, apc);
5768 # ifdef HAS_VSNPRINTF
5769 retval = vsnprintf(buffer, len, format, ap);
5771 retval = vsprintf(buffer, format, ap);
5773 #endif /* #ifdef NEED_VA_COPY */
5774 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5775 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5776 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
5781 Perl_my_clearenv(pTHX)
5784 #if ! defined(PERL_MICRO)
5785 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5787 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5788 # if defined(USE_ENVIRON_ARRAY)
5789 # if defined(USE_ITHREADS)
5790 /* only the parent thread can clobber the process environment */
5791 if (PL_curinterp == aTHX)
5792 # endif /* USE_ITHREADS */
5794 # if ! defined(PERL_USE_SAFE_PUTENV)
5795 if ( !PL_use_safe_putenv) {
5797 if (environ == PL_origenviron)
5798 environ = (char**)safesysmalloc(sizeof(char*));
5800 for (i = 0; environ[i]; i++)
5801 (void)safesysfree(environ[i]);
5804 # else /* PERL_USE_SAFE_PUTENV */
5805 # if defined(HAS_CLEARENV)
5807 # elif defined(HAS_UNSETENV)
5808 int bsiz = 80; /* Most envvar names will be shorter than this. */
5809 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
5810 char *buf = (char*)safesysmalloc(bufsiz);
5811 while (*environ != NULL) {
5812 char *e = strchr(*environ, '=');
5813 int l = e ? e - *environ : (int)strlen(*environ);
5815 (void)safesysfree(buf);
5816 bsiz = l + 1; /* + 1 for the \0. */
5817 buf = (char*)safesysmalloc(bufsiz);
5819 memcpy(buf, *environ, l);
5821 (void)unsetenv(buf);
5823 (void)safesysfree(buf);
5824 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5825 /* Just null environ and accept the leakage. */
5827 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5828 # endif /* ! PERL_USE_SAFE_PUTENV */
5830 # endif /* USE_ENVIRON_ARRAY */
5831 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5832 #endif /* PERL_MICRO */
5835 #ifdef PERL_IMPLICIT_CONTEXT
5837 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5838 the global PL_my_cxt_index is incremented, and that value is assigned to
5839 that module's static my_cxt_index (who's address is passed as an arg).
5840 Then, for each interpreter this function is called for, it makes sure a
5841 void* slot is available to hang the static data off, by allocating or
5842 extending the interpreter's PL_my_cxt_list array */
5844 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5846 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5850 PERL_ARGS_ASSERT_MY_CXT_INIT;
5852 /* this module hasn't been allocated an index yet */
5853 MUTEX_LOCK(&PL_my_ctx_mutex);
5854 *index = PL_my_cxt_index++;
5855 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5858 /* make sure the array is big enough */
5859 if (PL_my_cxt_size <= *index) {
5860 if (PL_my_cxt_size) {
5861 while (PL_my_cxt_size <= *index)
5862 PL_my_cxt_size *= 2;
5863 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5866 PL_my_cxt_size = 16;
5867 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5870 /* newSV() allocates one more than needed */
5871 p = (void*)SvPVX(newSV(size-1));
5872 PL_my_cxt_list[*index] = p;
5873 Zero(p, size, char);
5877 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5880 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5885 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5887 for (index = 0; index < PL_my_cxt_index; index++) {
5888 const char *key = PL_my_cxt_keys[index];
5889 /* try direct pointer compare first - there are chances to success,
5890 * and it's much faster.
5892 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5899 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5905 PERL_ARGS_ASSERT_MY_CXT_INIT;
5907 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5909 /* this module hasn't been allocated an index yet */
5910 MUTEX_LOCK(&PL_my_ctx_mutex);
5911 index = PL_my_cxt_index++;
5912 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5915 /* make sure the array is big enough */
5916 if (PL_my_cxt_size <= index) {
5917 int old_size = PL_my_cxt_size;
5919 if (PL_my_cxt_size) {
5920 while (PL_my_cxt_size <= index)
5921 PL_my_cxt_size *= 2;
5922 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5923 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5926 PL_my_cxt_size = 16;
5927 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5928 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5930 for (i = old_size; i < PL_my_cxt_size; i++) {
5931 PL_my_cxt_keys[i] = 0;
5932 PL_my_cxt_list[i] = 0;
5935 PL_my_cxt_keys[index] = my_cxt_key;
5936 /* newSV() allocates one more than needed */
5937 p = (void*)SvPVX(newSV(size-1));
5938 PL_my_cxt_list[index] = p;
5939 Zero(p, size, char);
5942 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5943 #endif /* PERL_IMPLICIT_CONTEXT */
5947 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5949 Size_t used, length, copy;
5952 length = strlen(src);
5953 if (size > 0 && used < size - 1) {
5954 copy = (length >= size - used) ? size - used - 1 : length;
5955 memcpy(dst + used, src, copy);
5956 dst[used + copy] = '\0';
5958 return used + length;
5964 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5966 Size_t length, copy;
5968 length = strlen(src);
5970 copy = (length >= size) ? size - 1 : length;
5971 memcpy(dst, src, copy);
5978 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5979 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5980 long _ftol( double ); /* Defined by VC6 C libs. */
5981 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5985 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5988 SV * const dbsv = GvSVn(PL_DBsub);
5989 /* We do not care about using sv to call CV;
5990 * it's for informational purposes only.
5993 PERL_ARGS_ASSERT_GET_DB_SUB;
5996 if (!PERLDB_SUB_NN) {
5997 GV * const gv = CvGV(cv);
5999 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6000 || strEQ(GvNAME(gv), "END")
6001 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6002 !( (SvTYPE(*svp) == SVt_PVGV) && (GvCV((GV*)*svp) == cv) )))) {
6003 /* Use GV from the stack as a fallback. */
6004 /* GV is potentially non-unique, or contain different CV. */
6005 SV * const tmp = newRV((SV*)cv);
6006 sv_setsv(dbsv, tmp);
6010 gv_efullname3(dbsv, gv, NULL);
6014 const int type = SvTYPE(dbsv);
6015 if (type < SVt_PVIV && type != SVt_IV)
6016 sv_upgrade(dbsv, SVt_PVIV);
6017 (void)SvIOK_on(dbsv);
6018 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6023 Perl_my_dirfd(pTHX_ DIR * dir) {
6025 /* Most dirfd implementations have problems when passed NULL. */
6030 #elif defined(HAS_DIR_DD_FD)
6033 Perl_die(aTHX_ PL_no_func, "dirfd");
6040 Perl_get_re_arg(pTHX_ SV *sv) {
6047 (tmpsv = (SV*)SvRV(sv)) && /* assign deliberate */
6048 SvTYPE(tmpsv) == SVt_REGEXP)
6050 return (REGEXP*) tmpsv;
6059 * c-indentation-style: bsd
6061 * indent-tabs-mode: t
6064 * ex: set ts=8 sts=4 sw=4 noet: