3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 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;
100 header->interpreter = aTHX;
101 /* Link us into the list. */
102 header->prev = &PL_memory_debug_header;
103 header->next = PL_memory_debug_header.next;
104 PL_memory_debug_header.next = header;
105 header->next->prev = header;
109 ptr = (Malloc_t)((char*)ptr+sTHX);
116 return write_no_mem();
121 /* paranoid version of system's realloc() */
124 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
128 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
129 Malloc_t PerlMem_realloc();
130 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
134 PerlIO_printf(Perl_error_log,
135 "Reallocation too large: %lx\n", size) FLUSH;
138 #endif /* HAS_64K_LIMIT */
145 return safesysmalloc(size);
146 #ifdef PERL_TRACK_MEMPOOL
147 where = (Malloc_t)((char*)where-sTHX);
150 struct perl_memory_debug_header *const header
151 = (struct perl_memory_debug_header *)where;
153 if (header->interpreter != aTHX) {
154 Perl_croak_nocontext("panic: realloc from wrong pool");
156 assert(header->next->prev == header);
157 assert(header->prev->next == header);
159 if (header->size > size) {
160 const MEM_SIZE freed_up = header->size - size;
161 char *start_of_freed = ((char *)where) + size;
162 Poison(start_of_freed, freed_up, char);
170 Perl_croak_nocontext("panic: realloc");
172 ptr = (Malloc_t)PerlMem_realloc(where,size);
173 PERL_ALLOC_CHECK(ptr);
175 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
176 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
179 #ifdef PERL_TRACK_MEMPOOL
180 struct perl_memory_debug_header *const header
181 = (struct perl_memory_debug_header *)ptr;
183 header->next->prev = header;
184 header->prev->next = header;
186 ptr = (Malloc_t)((char*)ptr+sTHX);
193 return write_no_mem();
198 /* safe version of system's free() */
201 Perl_safesysfree(Malloc_t where)
203 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
208 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
210 #ifdef PERL_TRACK_MEMPOOL
211 where = (Malloc_t)((char*)where-sTHX);
213 struct perl_memory_debug_header *const header
214 = (struct perl_memory_debug_header *)where;
216 if (header->interpreter != aTHX) {
217 Perl_croak_nocontext("panic: free from wrong pool");
220 Perl_croak_nocontext("panic: duplicate free");
222 if (!(header->next) || header->next->prev != header
223 || header->prev->next != header) {
224 Perl_croak_nocontext("panic: bad free");
226 /* Unlink us from the chain. */
227 header->next->prev = header->prev;
228 header->prev->next = header->next;
230 Poison(where, header->size, char);
232 /* Trigger the duplicate free warning. */
240 /* safe version of system's calloc() */
243 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
249 if (size * count > 0xffff) {
250 PerlIO_printf(Perl_error_log,
251 "Allocation too large: %lx\n", size * count) FLUSH;
254 #endif /* HAS_64K_LIMIT */
256 if ((long)size < 0 || (long)count < 0)
257 Perl_croak_nocontext("panic: calloc");
260 #ifdef PERL_TRACK_MEMPOOL
263 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
264 PERL_ALLOC_CHECK(ptr);
265 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
267 memset((void*)ptr, 0, size);
268 #ifdef PERL_TRACK_MEMPOOL
270 struct perl_memory_debug_header *const header
271 = (struct perl_memory_debug_header *)ptr;
273 header->interpreter = aTHX;
274 /* Link us into the list. */
275 header->prev = &PL_memory_debug_header;
276 header->next = PL_memory_debug_header.next;
277 PL_memory_debug_header.next = header;
278 header->next->prev = header;
282 ptr = (Malloc_t)((char*)ptr+sTHX);
289 return write_no_mem();
292 /* These must be defined when not using Perl's malloc for binary
297 Malloc_t Perl_malloc (MEM_SIZE nbytes)
300 return (Malloc_t)PerlMem_malloc(nbytes);
303 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
306 return (Malloc_t)PerlMem_calloc(elements, size);
309 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
312 return (Malloc_t)PerlMem_realloc(where, nbytes);
315 Free_t Perl_mfree (Malloc_t where)
323 /* copy a string up to some (non-backslashed) delimiter, if any */
326 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
329 for (tolen = 0; from < fromend; from++, tolen++) {
331 if (from[1] == delim)
340 else if (*from == delim)
351 /* return ptr to little string in big string, NULL if not found */
352 /* This routine was donated by Corey Satten. */
355 Perl_instr(pTHX_ register const char *big, register const char *little)
365 register const char *s, *x;
368 for (x=big,s=little; *s; /**/ ) {
379 return (char*)(big-1);
384 /* same as instr but allow embedded nulls */
387 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
392 char first = *little++;
394 bigend -= lend - little;
396 while (big <= bigend) {
399 for (x=big,s=little; s < lend; x++,s++) {
403 return (char*)(big-1);
409 /* reverse of the above--find last substring */
412 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
414 register const char *bigbeg;
415 register const I32 first = *little;
416 register const char * const littleend = lend;
418 if (little >= littleend)
419 return (char*)bigend;
421 big = bigend - (littleend - little++);
422 while (big >= bigbeg) {
423 register const char *s, *x;
426 for (x=big+2,s=little; s < littleend; /**/ ) {
435 return (char*)(big+1);
440 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
442 /* As a space optimization, we do not compile tables for strings of length
443 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
444 special-cased in fbm_instr().
446 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
449 =head1 Miscellaneous Functions
451 =for apidoc fbm_compile
453 Analyses the string in order to make fast searches on it using fbm_instr()
454 -- the Boyer-Moore algorithm.
460 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
463 register const U8 *s;
469 if (flags & FBMcf_TAIL) {
470 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
471 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
472 if (mg && mg->mg_len >= 0)
475 s = (U8*)SvPV_force_mutable(sv, len);
476 SvUPGRADE(sv, SVt_PVBM);
477 if (len == 0) /* TAIL might be on a zero-length string. */
480 const unsigned char *sb;
481 const U8 mlen = (len>255) ? 255 : (U8)len;
484 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
485 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
486 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
487 memset((void*)table, mlen, 256);
488 table[-1] = (U8)flags;
490 sb = s - mlen + 1; /* first char (maybe) */
492 if (table[*s] == mlen)
497 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
500 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
501 for (i = 0; i < len; i++) {
502 if (PL_freq[s[i]] < frequency) {
504 frequency = PL_freq[s[i]];
507 BmRARE(sv) = s[rarest];
508 BmPREVIOUS(sv) = (U16)rarest;
509 BmUSEFUL(sv) = 100; /* Initial value */
510 if (flags & FBMcf_TAIL)
512 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
513 BmRARE(sv),BmPREVIOUS(sv)));
516 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
517 /* If SvTAIL is actually due to \Z or \z, this gives false positives
521 =for apidoc fbm_instr
523 Returns the location of the SV in the string delimited by C<str> and
524 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
525 does not have to be fbm_compiled, but the search will not be as fast
532 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
534 register unsigned char *s;
536 register const unsigned char *little
537 = (const unsigned char *)SvPV_const(littlestr,l);
538 register STRLEN littlelen = l;
539 register const I32 multiline = flags & FBMrf_MULTILINE;
541 if ((STRLEN)(bigend - big) < littlelen) {
542 if ( SvTAIL(littlestr)
543 && ((STRLEN)(bigend - big) == littlelen - 1)
545 || (*big == *little &&
546 memEQ((char *)big, (char *)little, littlelen - 1))))
551 if (littlelen <= 2) { /* Special-cased */
553 if (littlelen == 1) {
554 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
555 /* Know that bigend != big. */
556 if (bigend[-1] == '\n')
557 return (char *)(bigend - 1);
558 return (char *) bigend;
566 if (SvTAIL(littlestr))
567 return (char *) bigend;
571 return (char*)big; /* Cannot be SvTAIL! */
574 if (SvTAIL(littlestr) && !multiline) {
575 if (bigend[-1] == '\n' && bigend[-2] == *little)
576 return (char*)bigend - 2;
577 if (bigend[-1] == *little)
578 return (char*)bigend - 1;
582 /* This should be better than FBM if c1 == c2, and almost
583 as good otherwise: maybe better since we do less indirection.
584 And we save a lot of memory by caching no table. */
585 const unsigned char c1 = little[0];
586 const unsigned char c2 = little[1];
591 while (s <= bigend) {
601 goto check_1char_anchor;
612 goto check_1char_anchor;
615 while (s <= bigend) {
620 goto check_1char_anchor;
629 check_1char_anchor: /* One char and anchor! */
630 if (SvTAIL(littlestr) && (*bigend == *little))
631 return (char *)bigend; /* bigend is already decremented. */
634 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
635 s = bigend - littlelen;
636 if (s >= big && bigend[-1] == '\n' && *s == *little
637 /* Automatically of length > 2 */
638 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
640 return (char*)s; /* how sweet it is */
643 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
645 return (char*)s + 1; /* how sweet it is */
649 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
650 char * const b = ninstr((char*)big,(char*)bigend,
651 (char*)little, (char*)little + littlelen);
653 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
654 /* Chop \n from littlestr: */
655 s = bigend - littlelen + 1;
657 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
666 { /* Do actual FBM. */
667 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
668 register const unsigned char *oldlittle;
670 if (littlelen > (STRLEN)(bigend - big))
672 --littlelen; /* Last char found by table lookup */
675 little += littlelen; /* last char */
681 if ((tmp = table[*s])) {
682 if ((s += tmp) < bigend)
686 else { /* less expensive than calling strncmp() */
687 register unsigned char * const olds = s;
692 if (*--s == *--little)
694 s = olds + 1; /* here we pay the price for failure */
696 if (s < bigend) /* fake up continue to outer loop */
704 if ( s == bigend && (table[-1] & FBMcf_TAIL)
705 && memEQ((char *)(bigend - littlelen),
706 (char *)(oldlittle - littlelen), littlelen) )
707 return (char*)bigend - littlelen;
712 /* start_shift, end_shift are positive quantities which give offsets
713 of ends of some substring of bigstr.
714 If "last" we want the last occurrence.
715 old_posp is the way of communication between consequent calls if
716 the next call needs to find the .
717 The initial *old_posp should be -1.
719 Note that we take into account SvTAIL, so one can get extra
720 optimizations if _ALL flag is set.
723 /* If SvTAIL is actually due to \Z or \z, this gives false positives
724 if PL_multiline. In fact if !PL_multiline the authoritative answer
725 is not supported yet. */
728 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
731 register const unsigned char *big;
733 register I32 previous;
735 register const unsigned char *little;
736 register I32 stop_pos;
737 register const unsigned char *littleend;
741 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
742 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
744 if ( BmRARE(littlestr) == '\n'
745 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
746 little = (const unsigned char *)(SvPVX_const(littlestr));
747 littleend = little + SvCUR(littlestr);
754 little = (const unsigned char *)(SvPVX_const(littlestr));
755 littleend = little + SvCUR(littlestr);
757 /* The value of pos we can start at: */
758 previous = BmPREVIOUS(littlestr);
759 big = (const unsigned char *)(SvPVX_const(bigstr));
760 /* The value of pos we can stop at: */
761 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
762 if (previous + start_shift > stop_pos) {
764 stop_pos does not include SvTAIL in the count, so this check is incorrect
765 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
768 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
773 while (pos < previous + start_shift) {
774 if (!(pos += PL_screamnext[pos]))
779 register const unsigned char *s, *x;
780 if (pos >= stop_pos) break;
781 if (big[pos] != first)
783 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
789 if (s == littleend) {
791 if (!last) return (char *)(big+pos);
794 } while ( pos += PL_screamnext[pos] );
796 return (char *)(big+(*old_posp));
798 if (!SvTAIL(littlestr) || (end_shift > 0))
800 /* Ignore the trailing "\n". This code is not microoptimized */
801 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
802 stop_pos = littleend - little; /* Actual littlestr len */
807 && ((stop_pos == 1) ||
808 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
814 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
816 register const U8 *a = (const U8 *)s1;
817 register const U8 *b = (const U8 *)s2;
819 if (*a != *b && *a != PL_fold[*b])
827 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
830 register const U8 *a = (const U8 *)s1;
831 register const U8 *b = (const U8 *)s2;
833 if (*a != *b && *a != PL_fold_locale[*b])
840 /* copy a string to a safe spot */
843 =head1 Memory Management
847 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
848 string which is a duplicate of C<pv>. The size of the string is
849 determined by C<strlen()>. The memory allocated for the new string can
850 be freed with the C<Safefree()> function.
856 Perl_savepv(pTHX_ const char *pv)
862 const STRLEN pvlen = strlen(pv)+1;
863 Newx(newaddr,pvlen,char);
864 return memcpy(newaddr,pv,pvlen);
869 /* same thing but with a known length */
874 Perl's version of what C<strndup()> would be if it existed. Returns a
875 pointer to a newly allocated string which is a duplicate of the first
876 C<len> bytes from C<pv>. The memory allocated for the new string can be
877 freed with the C<Safefree()> function.
883 Perl_savepvn(pTHX_ const char *pv, register I32 len)
885 register char *newaddr;
887 Newx(newaddr,len+1,char);
888 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
890 /* might not be null terminated */
892 return (char *) CopyD(pv,newaddr,len,char);
895 return (char *) ZeroD(newaddr,len+1,char);
900 =for apidoc savesharedpv
902 A version of C<savepv()> which allocates the duplicate string in memory
903 which is shared between threads.
908 Perl_savesharedpv(pTHX_ const char *pv)
910 register char *newaddr;
915 pvlen = strlen(pv)+1;
916 newaddr = (char*)PerlMemShared_malloc(pvlen);
918 return write_no_mem();
920 return memcpy(newaddr,pv,pvlen);
926 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
927 the passed in SV using C<SvPV()>
933 Perl_savesvpv(pTHX_ SV *sv)
936 const char * const pv = SvPV_const(sv, len);
937 register char *newaddr;
940 Newx(newaddr,len,char);
941 return (char *) CopyD(pv,newaddr,len,char);
945 /* the SV for Perl_form() and mess() is not kept in an arena */
955 return sv_2mortal(newSVpvs(""));
960 /* Create as PVMG now, to avoid any upgrading later */
962 Newxz(any, 1, XPVMG);
963 SvFLAGS(sv) = SVt_PVMG;
964 SvANY(sv) = (void*)any;
966 SvREFCNT(sv) = 1 << 30; /* practically infinite */
971 #if defined(PERL_IMPLICIT_CONTEXT)
973 Perl_form_nocontext(const char* pat, ...)
979 retval = vform(pat, &args);
983 #endif /* PERL_IMPLICIT_CONTEXT */
986 =head1 Miscellaneous Functions
989 Takes a sprintf-style format pattern and conventional
990 (non-SV) arguments and returns the formatted string.
992 (char *) Perl_form(pTHX_ const char* pat, ...)
994 can be used any place a string (char *) is required:
996 char * s = Perl_form("%d.%d",major,minor);
998 Uses a single private buffer so if you want to format several strings you
999 must explicitly copy the earlier strings away (and free the copies when you
1006 Perl_form(pTHX_ const char* pat, ...)
1010 va_start(args, pat);
1011 retval = vform(pat, &args);
1017 Perl_vform(pTHX_ const char *pat, va_list *args)
1019 SV * const sv = mess_alloc();
1020 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1024 #if defined(PERL_IMPLICIT_CONTEXT)
1026 Perl_mess_nocontext(const char *pat, ...)
1031 va_start(args, pat);
1032 retval = vmess(pat, &args);
1036 #endif /* PERL_IMPLICIT_CONTEXT */
1039 Perl_mess(pTHX_ const char *pat, ...)
1043 va_start(args, pat);
1044 retval = vmess(pat, &args);
1050 S_closest_cop(pTHX_ COP *cop, const OP *o)
1053 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1055 if (!o || o == PL_op)
1058 if (o->op_flags & OPf_KIDS) {
1060 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1063 /* If the OP_NEXTSTATE has been optimised away we can still use it
1064 * the get the file and line number. */
1066 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1069 /* Keep searching, and return when we've found something. */
1071 new_cop = closest_cop(cop, kid);
1077 /* Nothing found. */
1083 Perl_vmess(pTHX_ const char *pat, va_list *args)
1086 SV * const sv = mess_alloc();
1087 static const char dgd[] = " during global destruction.\n";
1089 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1090 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1093 * Try and find the file and line for PL_op. This will usually be
1094 * PL_curcop, but it might be a cop that has been optimised away. We
1095 * can try to find such a cop by searching through the optree starting
1096 * from the sibling of PL_curcop.
1099 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1100 if (!cop) cop = PL_curcop;
1103 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1104 OutCopFILE(cop), (IV)CopLINE(cop));
1105 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1106 const bool line_mode = (RsSIMPLE(PL_rs) &&
1107 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1108 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1109 PL_last_in_gv == PL_argvgv ?
1110 "" : GvNAME(PL_last_in_gv),
1111 line_mode ? "line" : "chunk",
1112 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1114 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1120 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1126 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1127 && (io = GvIO(PL_stderrgv))
1128 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1135 SAVESPTR(PL_stderrgv);
1138 PUSHSTACKi(PERLSI_MAGIC);
1142 PUSHs(SvTIED_obj((SV*)io, mg));
1143 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1145 call_method("PRINT", G_SCALAR);
1153 /* SFIO can really mess with your errno */
1154 const int e = errno;
1156 PerlIO * const serr = Perl_error_log;
1158 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1159 (void)PerlIO_flush(serr);
1166 /* Common code used by vcroak, vdie, vwarn and vwarner */
1169 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1175 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1176 /* sv_2cv might call Perl_croak() or Perl_warner() */
1177 SV * const oldhook = *hook;
1184 cv = sv_2cv(oldhook, &stash, &gv, 0);
1186 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1196 if (warn || message) {
1197 msg = newSVpvn(message, msglen);
1198 SvFLAGS(msg) |= utf8;
1206 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1210 call_sv((SV*)cv, G_DISCARD);
1219 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1223 const char *message;
1226 SV * const msv = vmess(pat, args);
1227 if (PL_errors && SvCUR(PL_errors)) {
1228 sv_catsv(PL_errors, msv);
1229 message = SvPV_const(PL_errors, *msglen);
1230 SvCUR_set(PL_errors, 0);
1233 message = SvPV_const(msv,*msglen);
1234 *utf8 = SvUTF8(msv);
1240 DEBUG_S(PerlIO_printf(Perl_debug_log,
1241 "%p: die/croak: message = %s\ndiehook = %p\n",
1242 thr, message, PL_diehook));
1244 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1250 Perl_vdie(pTHX_ const char* pat, va_list *args)
1253 const char *message;
1254 const int was_in_eval = PL_in_eval;
1258 DEBUG_S(PerlIO_printf(Perl_debug_log,
1259 "%p: die: curstack = %p, mainstack = %p\n",
1260 thr, PL_curstack, PL_mainstack));
1262 message = vdie_croak_common(pat, args, &msglen, &utf8);
1264 PL_restartop = die_where(message, msglen);
1265 SvFLAGS(ERRSV) |= utf8;
1266 DEBUG_S(PerlIO_printf(Perl_debug_log,
1267 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1268 thr, PL_restartop, was_in_eval, PL_top_env));
1269 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1271 return PL_restartop;
1274 #if defined(PERL_IMPLICIT_CONTEXT)
1276 Perl_die_nocontext(const char* pat, ...)
1281 va_start(args, pat);
1282 o = vdie(pat, &args);
1286 #endif /* PERL_IMPLICIT_CONTEXT */
1289 Perl_die(pTHX_ const char* pat, ...)
1293 va_start(args, pat);
1294 o = vdie(pat, &args);
1300 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1303 const char *message;
1307 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1310 PL_restartop = die_where(message, msglen);
1311 SvFLAGS(ERRSV) |= utf8;
1315 message = SvPVx_const(ERRSV, msglen);
1317 write_to_stderr(message, msglen);
1321 #if defined(PERL_IMPLICIT_CONTEXT)
1323 Perl_croak_nocontext(const char *pat, ...)
1327 va_start(args, pat);
1332 #endif /* PERL_IMPLICIT_CONTEXT */
1335 =head1 Warning and Dieing
1339 This is the XSUB-writer's interface to Perl's C<die> function.
1340 Normally call this function the same way you call the C C<printf>
1341 function. Calling C<croak> returns control directly to Perl,
1342 sidestepping the normal C order of execution. See C<warn>.
1344 If you want to throw an exception object, assign the object to
1345 C<$@> and then pass C<NULL> to croak():
1347 errsv = get_sv("@", TRUE);
1348 sv_setsv(errsv, exception_object);
1355 Perl_croak(pTHX_ const char *pat, ...)
1358 va_start(args, pat);
1365 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1369 SV * const msv = vmess(pat, args);
1370 const I32 utf8 = SvUTF8(msv);
1371 const char * const message = SvPV_const(msv, msglen);
1374 if (vdie_common(message, msglen, utf8, TRUE))
1378 write_to_stderr(message, msglen);
1381 #if defined(PERL_IMPLICIT_CONTEXT)
1383 Perl_warn_nocontext(const char *pat, ...)
1387 va_start(args, pat);
1391 #endif /* PERL_IMPLICIT_CONTEXT */
1396 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1397 function the same way you call the C C<printf> function. See C<croak>.
1403 Perl_warn(pTHX_ const char *pat, ...)
1406 va_start(args, pat);
1411 #if defined(PERL_IMPLICIT_CONTEXT)
1413 Perl_warner_nocontext(U32 err, const char *pat, ...)
1417 va_start(args, pat);
1418 vwarner(err, pat, &args);
1421 #endif /* PERL_IMPLICIT_CONTEXT */
1424 Perl_warner(pTHX_ U32 err, const char* pat,...)
1427 va_start(args, pat);
1428 vwarner(err, pat, &args);
1433 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1437 SV * const msv = vmess(pat, args);
1439 const char * const message = SvPV_const(msv, msglen);
1440 const I32 utf8 = SvUTF8(msv);
1444 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1447 PL_restartop = die_where(message, msglen);
1448 SvFLAGS(ERRSV) |= utf8;
1451 write_to_stderr(message, msglen);
1455 Perl_vwarn(aTHX_ pat, args);
1459 /* implements the ckWARN? macros */
1462 Perl_ckwarn(pTHX_ U32 w)
1468 && PL_curcop->cop_warnings != pWARN_NONE
1470 PL_curcop->cop_warnings == pWARN_ALL
1471 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1472 || (unpackWARN2(w) &&
1473 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1474 || (unpackWARN3(w) &&
1475 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1476 || (unpackWARN4(w) &&
1477 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1482 isLEXWARN_off && PL_dowarn & G_WARN_ON
1487 /* implements the ckWARN?_d macro */
1490 Perl_ckwarn_d(pTHX_ U32 w)
1495 || PL_curcop->cop_warnings == pWARN_ALL
1497 PL_curcop->cop_warnings != pWARN_NONE
1499 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1500 || (unpackWARN2(w) &&
1501 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1502 || (unpackWARN3(w) &&
1503 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1504 || (unpackWARN4(w) &&
1505 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1513 /* since we've already done strlen() for both nam and val
1514 * we can use that info to make things faster than
1515 * sprintf(s, "%s=%s", nam, val)
1517 #define my_setenv_format(s, nam, nlen, val, vlen) \
1518 Copy(nam, s, nlen, char); \
1520 Copy(val, s+(nlen+1), vlen, char); \
1521 *(s+(nlen+1+vlen)) = '\0'
1523 #ifdef USE_ENVIRON_ARRAY
1524 /* VMS' my_setenv() is in vms.c */
1525 #if !defined(WIN32) && !defined(NETWARE)
1527 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1531 /* only parent thread can modify process environment */
1532 if (PL_curinterp == aTHX)
1535 #ifndef PERL_USE_SAFE_PUTENV
1536 if (!PL_use_safe_putenv) {
1537 /* most putenv()s leak, so we manipulate environ directly */
1538 register I32 i=setenv_getix(nam); /* where does it go? */
1541 if (environ == PL_origenviron) { /* need we copy environment? */
1546 for (max = i; environ[max]; max++) ;
1547 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1548 for (j=0; j<max; j++) { /* copy environment */
1549 const int len = strlen(environ[j]);
1550 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1551 Copy(environ[j], tmpenv[j], len+1, char);
1554 environ = tmpenv; /* tell exec where it is now */
1557 safesysfree(environ[i]);
1558 while (environ[i]) {
1559 environ[i] = environ[i+1];
1564 if (!environ[i]) { /* does not exist yet */
1565 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1566 environ[i+1] = NULL; /* make sure it's null terminated */
1569 safesysfree(environ[i]);
1573 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1574 /* all that work just for this */
1575 my_setenv_format(environ[i], nam, nlen, val, vlen);
1578 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1579 # if defined(HAS_UNSETENV)
1581 (void)unsetenv(nam);
1583 (void)setenv(nam, val, 1);
1585 # else /* ! HAS_UNSETENV */
1586 (void)setenv(nam, val, 1);
1587 # endif /* HAS_UNSETENV */
1589 # if defined(HAS_UNSETENV)
1591 (void)unsetenv(nam);
1593 const int nlen = strlen(nam);
1594 const int vlen = strlen(val);
1595 char * const new_env =
1596 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1597 my_setenv_format(new_env, nam, nlen, val, vlen);
1598 (void)putenv(new_env);
1600 # else /* ! HAS_UNSETENV */
1602 const int nlen = strlen(nam);
1608 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1609 /* all that work just for this */
1610 my_setenv_format(new_env, nam, nlen, val, vlen);
1611 (void)putenv(new_env);
1612 # endif /* HAS_UNSETENV */
1613 # endif /* __CYGWIN__ */
1614 #ifndef PERL_USE_SAFE_PUTENV
1620 #else /* WIN32 || NETWARE */
1623 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1626 register char *envstr;
1627 const int nlen = strlen(nam);
1634 Newx(envstr, nlen+vlen+2, char);
1635 my_setenv_format(envstr, nam, nlen, val, vlen);
1636 (void)PerlEnv_putenv(envstr);
1640 #endif /* WIN32 || NETWARE */
1644 Perl_setenv_getix(pTHX_ const char *nam)
1647 register const I32 len = strlen(nam);
1649 for (i = 0; environ[i]; i++) {
1652 strnicmp(environ[i],nam,len) == 0
1654 strnEQ(environ[i],nam,len)
1656 && environ[i][len] == '=')
1657 break; /* strnEQ must come first to avoid */
1658 } /* potential SEGV's */
1661 #endif /* !PERL_MICRO */
1663 #endif /* !VMS && !EPOC*/
1665 #ifdef UNLINK_ALL_VERSIONS
1667 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1671 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1676 /* this is a drop-in replacement for bcopy() */
1677 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1679 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1681 char * const retval = to;
1683 if (from - to >= 0) {
1691 *(--to) = *(--from);
1697 /* this is a drop-in replacement for memset() */
1700 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1702 char * const retval = loc;
1710 /* this is a drop-in replacement for bzero() */
1711 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1713 Perl_my_bzero(register char *loc, register I32 len)
1715 char * const retval = loc;
1723 /* this is a drop-in replacement for memcmp() */
1724 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1726 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1728 register const U8 *a = (const U8 *)s1;
1729 register const U8 *b = (const U8 *)s2;
1733 if ((tmp = *a++ - *b++))
1738 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1742 #ifdef USE_CHAR_VSPRINTF
1747 vsprintf(char *dest, const char *pat, char *args)
1751 fakebuf._ptr = dest;
1752 fakebuf._cnt = 32767;
1756 fakebuf._flag = _IOWRT|_IOSTRG;
1757 _doprnt(pat, args, &fakebuf); /* what a kludge */
1758 (void)putc('\0', &fakebuf);
1759 #ifdef USE_CHAR_VSPRINTF
1762 return 0; /* perl doesn't use return value */
1766 #endif /* HAS_VPRINTF */
1769 #if BYTEORDER != 0x4321
1771 Perl_my_swap(pTHX_ short s)
1773 #if (BYTEORDER & 1) == 0
1776 result = ((s & 255) << 8) + ((s >> 8) & 255);
1784 Perl_my_htonl(pTHX_ long l)
1788 char c[sizeof(long)];
1791 #if BYTEORDER == 0x1234
1792 u.c[0] = (l >> 24) & 255;
1793 u.c[1] = (l >> 16) & 255;
1794 u.c[2] = (l >> 8) & 255;
1798 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1799 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1804 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1805 u.c[o & 0xf] = (l >> s) & 255;
1813 Perl_my_ntohl(pTHX_ long l)
1817 char c[sizeof(long)];
1820 #if BYTEORDER == 0x1234
1821 u.c[0] = (l >> 24) & 255;
1822 u.c[1] = (l >> 16) & 255;
1823 u.c[2] = (l >> 8) & 255;
1827 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1828 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1835 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1836 l |= (u.c[o & 0xf] & 255) << s;
1843 #endif /* BYTEORDER != 0x4321 */
1847 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1848 * If these functions are defined,
1849 * the BYTEORDER is neither 0x1234 nor 0x4321.
1850 * However, this is not assumed.
1854 #define HTOLE(name,type) \
1856 name (register type n) \
1860 char c[sizeof(type)]; \
1863 register I32 s = 0; \
1864 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1865 u.c[i] = (n >> s) & 0xFF; \
1870 #define LETOH(name,type) \
1872 name (register type n) \
1876 char c[sizeof(type)]; \
1879 register I32 s = 0; \
1882 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1883 n |= ((type)(u.c[i] & 0xFF)) << s; \
1889 * Big-endian byte order functions.
1892 #define HTOBE(name,type) \
1894 name (register type n) \
1898 char c[sizeof(type)]; \
1901 register I32 s = 8*(sizeof(u.c)-1); \
1902 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1903 u.c[i] = (n >> s) & 0xFF; \
1908 #define BETOH(name,type) \
1910 name (register type n) \
1914 char c[sizeof(type)]; \
1917 register I32 s = 8*(sizeof(u.c)-1); \
1920 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1921 n |= ((type)(u.c[i] & 0xFF)) << s; \
1927 * If we just can't do it...
1930 #define NOT_AVAIL(name,type) \
1932 name (register type n) \
1934 Perl_croak_nocontext(#name "() not available"); \
1935 return n; /* not reached */ \
1939 #if defined(HAS_HTOVS) && !defined(htovs)
1942 #if defined(HAS_HTOVL) && !defined(htovl)
1945 #if defined(HAS_VTOHS) && !defined(vtohs)
1948 #if defined(HAS_VTOHL) && !defined(vtohl)
1952 #ifdef PERL_NEED_MY_HTOLE16
1954 HTOLE(Perl_my_htole16,U16)
1956 NOT_AVAIL(Perl_my_htole16,U16)
1959 #ifdef PERL_NEED_MY_LETOH16
1961 LETOH(Perl_my_letoh16,U16)
1963 NOT_AVAIL(Perl_my_letoh16,U16)
1966 #ifdef PERL_NEED_MY_HTOBE16
1968 HTOBE(Perl_my_htobe16,U16)
1970 NOT_AVAIL(Perl_my_htobe16,U16)
1973 #ifdef PERL_NEED_MY_BETOH16
1975 BETOH(Perl_my_betoh16,U16)
1977 NOT_AVAIL(Perl_my_betoh16,U16)
1981 #ifdef PERL_NEED_MY_HTOLE32
1983 HTOLE(Perl_my_htole32,U32)
1985 NOT_AVAIL(Perl_my_htole32,U32)
1988 #ifdef PERL_NEED_MY_LETOH32
1990 LETOH(Perl_my_letoh32,U32)
1992 NOT_AVAIL(Perl_my_letoh32,U32)
1995 #ifdef PERL_NEED_MY_HTOBE32
1997 HTOBE(Perl_my_htobe32,U32)
1999 NOT_AVAIL(Perl_my_htobe32,U32)
2002 #ifdef PERL_NEED_MY_BETOH32
2004 BETOH(Perl_my_betoh32,U32)
2006 NOT_AVAIL(Perl_my_betoh32,U32)
2010 #ifdef PERL_NEED_MY_HTOLE64
2012 HTOLE(Perl_my_htole64,U64)
2014 NOT_AVAIL(Perl_my_htole64,U64)
2017 #ifdef PERL_NEED_MY_LETOH64
2019 LETOH(Perl_my_letoh64,U64)
2021 NOT_AVAIL(Perl_my_letoh64,U64)
2024 #ifdef PERL_NEED_MY_HTOBE64
2026 HTOBE(Perl_my_htobe64,U64)
2028 NOT_AVAIL(Perl_my_htobe64,U64)
2031 #ifdef PERL_NEED_MY_BETOH64
2033 BETOH(Perl_my_betoh64,U64)
2035 NOT_AVAIL(Perl_my_betoh64,U64)
2039 #ifdef PERL_NEED_MY_HTOLES
2040 HTOLE(Perl_my_htoles,short)
2042 #ifdef PERL_NEED_MY_LETOHS
2043 LETOH(Perl_my_letohs,short)
2045 #ifdef PERL_NEED_MY_HTOBES
2046 HTOBE(Perl_my_htobes,short)
2048 #ifdef PERL_NEED_MY_BETOHS
2049 BETOH(Perl_my_betohs,short)
2052 #ifdef PERL_NEED_MY_HTOLEI
2053 HTOLE(Perl_my_htolei,int)
2055 #ifdef PERL_NEED_MY_LETOHI
2056 LETOH(Perl_my_letohi,int)
2058 #ifdef PERL_NEED_MY_HTOBEI
2059 HTOBE(Perl_my_htobei,int)
2061 #ifdef PERL_NEED_MY_BETOHI
2062 BETOH(Perl_my_betohi,int)
2065 #ifdef PERL_NEED_MY_HTOLEL
2066 HTOLE(Perl_my_htolel,long)
2068 #ifdef PERL_NEED_MY_LETOHL
2069 LETOH(Perl_my_letohl,long)
2071 #ifdef PERL_NEED_MY_HTOBEL
2072 HTOBE(Perl_my_htobel,long)
2074 #ifdef PERL_NEED_MY_BETOHL
2075 BETOH(Perl_my_betohl,long)
2079 Perl_my_swabn(void *ptr, int n)
2081 register char *s = (char *)ptr;
2082 register char *e = s + (n-1);
2085 for (n /= 2; n > 0; s++, e--, n--) {
2093 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2095 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2098 register I32 This, that;
2104 PERL_FLUSHALL_FOR_CHILD;
2105 This = (*mode == 'w');
2109 taint_proper("Insecure %s%s", "EXEC");
2111 if (PerlProc_pipe(p) < 0)
2113 /* Try for another pipe pair for error return */
2114 if (PerlProc_pipe(pp) >= 0)
2116 while ((pid = PerlProc_fork()) < 0) {
2117 if (errno != EAGAIN) {
2118 PerlLIO_close(p[This]);
2119 PerlLIO_close(p[that]);
2121 PerlLIO_close(pp[0]);
2122 PerlLIO_close(pp[1]);
2134 /* Close parent's end of error status pipe (if any) */
2136 PerlLIO_close(pp[0]);
2137 #if defined(HAS_FCNTL) && defined(F_SETFD)
2138 /* Close error pipe automatically if exec works */
2139 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2142 /* Now dup our end of _the_ pipe to right position */
2143 if (p[THIS] != (*mode == 'r')) {
2144 PerlLIO_dup2(p[THIS], *mode == 'r');
2145 PerlLIO_close(p[THIS]);
2146 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2147 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2150 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2151 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2152 /* No automatic close - do it by hand */
2159 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2165 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2171 do_execfree(); /* free any memory malloced by child on fork */
2173 PerlLIO_close(pp[1]);
2174 /* Keep the lower of the two fd numbers */
2175 if (p[that] < p[This]) {
2176 PerlLIO_dup2(p[This], p[that]);
2177 PerlLIO_close(p[This]);
2181 PerlLIO_close(p[that]); /* close child's end of pipe */
2184 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2186 SvUPGRADE(sv,SVt_IV);
2188 PL_forkprocess = pid;
2189 /* If we managed to get status pipe check for exec fail */
2190 if (did_pipes && pid > 0) {
2194 while (n < sizeof(int)) {
2195 n1 = PerlLIO_read(pp[0],
2196 (void*)(((char*)&errkid)+n),
2202 PerlLIO_close(pp[0]);
2204 if (n) { /* Error */
2206 PerlLIO_close(p[This]);
2207 if (n != sizeof(int))
2208 Perl_croak(aTHX_ "panic: kid popen errno read");
2210 pid2 = wait4pid(pid, &status, 0);
2211 } while (pid2 == -1 && errno == EINTR);
2212 errno = errkid; /* Propagate errno from kid */
2217 PerlLIO_close(pp[0]);
2218 return PerlIO_fdopen(p[This], mode);
2220 Perl_croak(aTHX_ "List form of piped open not implemented");
2221 return (PerlIO *) NULL;
2225 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2226 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2228 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2232 register I32 This, that;
2235 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2239 PERL_FLUSHALL_FOR_CHILD;
2242 return my_syspopen(aTHX_ cmd,mode);
2245 This = (*mode == 'w');
2247 if (doexec && PL_tainting) {
2249 taint_proper("Insecure %s%s", "EXEC");
2251 if (PerlProc_pipe(p) < 0)
2253 if (doexec && PerlProc_pipe(pp) >= 0)
2255 while ((pid = PerlProc_fork()) < 0) {
2256 if (errno != EAGAIN) {
2257 PerlLIO_close(p[This]);
2258 PerlLIO_close(p[that]);
2260 PerlLIO_close(pp[0]);
2261 PerlLIO_close(pp[1]);
2264 Perl_croak(aTHX_ "Can't fork");
2277 PerlLIO_close(pp[0]);
2278 #if defined(HAS_FCNTL) && defined(F_SETFD)
2279 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2282 if (p[THIS] != (*mode == 'r')) {
2283 PerlLIO_dup2(p[THIS], *mode == 'r');
2284 PerlLIO_close(p[THIS]);
2285 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2286 PerlLIO_close(p[THAT]);
2289 PerlLIO_close(p[THAT]);
2292 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2299 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2304 /* may or may not use the shell */
2305 do_exec3(cmd, pp[1], did_pipes);
2308 #endif /* defined OS2 */
2309 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2310 SvREADONLY_off(GvSV(tmpgv));
2311 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2312 SvREADONLY_on(GvSV(tmpgv));
2314 #ifdef THREADS_HAVE_PIDS
2315 PL_ppid = (IV)getppid();
2318 #ifdef PERL_USES_PL_PIDSTATUS
2319 hv_clear(PL_pidstatus); /* we have no children */
2325 do_execfree(); /* free any memory malloced by child on vfork */
2327 PerlLIO_close(pp[1]);
2328 if (p[that] < p[This]) {
2329 PerlLIO_dup2(p[This], p[that]);
2330 PerlLIO_close(p[This]);
2334 PerlLIO_close(p[that]);
2337 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2339 SvUPGRADE(sv,SVt_IV);
2341 PL_forkprocess = pid;
2342 if (did_pipes && pid > 0) {
2346 while (n < sizeof(int)) {
2347 n1 = PerlLIO_read(pp[0],
2348 (void*)(((char*)&errkid)+n),
2354 PerlLIO_close(pp[0]);
2356 if (n) { /* Error */
2358 PerlLIO_close(p[This]);
2359 if (n != sizeof(int))
2360 Perl_croak(aTHX_ "panic: kid popen errno read");
2362 pid2 = wait4pid(pid, &status, 0);
2363 } while (pid2 == -1 && errno == EINTR);
2364 errno = errkid; /* Propagate errno from kid */
2369 PerlLIO_close(pp[0]);
2370 return PerlIO_fdopen(p[This], mode);
2373 #if defined(atarist) || defined(EPOC)
2376 Perl_my_popen(pTHX_ char *cmd, char *mode)
2378 PERL_FLUSHALL_FOR_CHILD;
2379 /* Call system's popen() to get a FILE *, then import it.
2380 used 0 for 2nd parameter to PerlIO_importFILE;
2383 return PerlIO_importFILE(popen(cmd, mode), 0);
2387 FILE *djgpp_popen();
2389 Perl_my_popen(pTHX_ char *cmd, char *mode)
2391 PERL_FLUSHALL_FOR_CHILD;
2392 /* Call system's popen() to get a FILE *, then import it.
2393 used 0 for 2nd parameter to PerlIO_importFILE;
2396 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2401 #endif /* !DOSISH */
2403 /* this is called in parent before the fork() */
2405 Perl_atfork_lock(void)
2408 #if defined(USE_ITHREADS)
2409 /* locks must be held in locking order (if any) */
2411 MUTEX_LOCK(&PL_malloc_mutex);
2417 /* this is called in both parent and child after the fork() */
2419 Perl_atfork_unlock(void)
2422 #if defined(USE_ITHREADS)
2423 /* locks must be released in same order as in atfork_lock() */
2425 MUTEX_UNLOCK(&PL_malloc_mutex);
2434 #if defined(HAS_FORK)
2436 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2441 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2442 * handlers elsewhere in the code */
2447 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2448 Perl_croak_nocontext("fork() not available");
2450 #endif /* HAS_FORK */
2455 Perl_dump_fds(pTHX_ char *s)
2460 PerlIO_printf(Perl_debug_log,"%s", s);
2461 for (fd = 0; fd < 32; fd++) {
2462 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2463 PerlIO_printf(Perl_debug_log," %d",fd);
2465 PerlIO_printf(Perl_debug_log,"\n");
2468 #endif /* DUMP_FDS */
2472 dup2(int oldfd, int newfd)
2474 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2477 PerlLIO_close(newfd);
2478 return fcntl(oldfd, F_DUPFD, newfd);
2480 #define DUP2_MAX_FDS 256
2481 int fdtmp[DUP2_MAX_FDS];
2487 PerlLIO_close(newfd);
2488 /* good enough for low fd's... */
2489 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2490 if (fdx >= DUP2_MAX_FDS) {
2498 PerlLIO_close(fdtmp[--fdx]);
2505 #ifdef HAS_SIGACTION
2507 #ifdef MACOS_TRADITIONAL
2508 /* We don't want restart behavior on MacOS */
2513 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2516 struct sigaction act, oact;
2519 /* only "parent" interpreter can diddle signals */
2520 if (PL_curinterp != aTHX)
2521 return (Sighandler_t) SIG_ERR;
2524 act.sa_handler = (void(*)(int))handler;
2525 sigemptyset(&act.sa_mask);
2528 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2529 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2531 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2532 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2533 act.sa_flags |= SA_NOCLDWAIT;
2535 if (sigaction(signo, &act, &oact) == -1)
2536 return (Sighandler_t) SIG_ERR;
2538 return (Sighandler_t) oact.sa_handler;
2542 Perl_rsignal_state(pTHX_ int signo)
2544 struct sigaction oact;
2546 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2547 return (Sighandler_t) SIG_ERR;
2549 return (Sighandler_t) oact.sa_handler;
2553 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2556 struct sigaction act;
2559 /* only "parent" interpreter can diddle signals */
2560 if (PL_curinterp != aTHX)
2564 act.sa_handler = (void(*)(int))handler;
2565 sigemptyset(&act.sa_mask);
2568 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2569 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2571 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2572 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2573 act.sa_flags |= SA_NOCLDWAIT;
2575 return sigaction(signo, &act, save);
2579 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2583 /* only "parent" interpreter can diddle signals */
2584 if (PL_curinterp != aTHX)
2588 return sigaction(signo, save, (struct sigaction *)NULL);
2591 #else /* !HAS_SIGACTION */
2594 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2596 #if defined(USE_ITHREADS) && !defined(WIN32)
2597 /* only "parent" interpreter can diddle signals */
2598 if (PL_curinterp != aTHX)
2599 return (Sighandler_t) SIG_ERR;
2602 return PerlProc_signal(signo, handler);
2613 Perl_rsignal_state(pTHX_ int signo)
2616 Sighandler_t oldsig;
2618 #if defined(USE_ITHREADS) && !defined(WIN32)
2619 /* only "parent" interpreter can diddle signals */
2620 if (PL_curinterp != aTHX)
2621 return (Sighandler_t) SIG_ERR;
2625 oldsig = PerlProc_signal(signo, sig_trap);
2626 PerlProc_signal(signo, oldsig);
2628 PerlProc_kill(PerlProc_getpid(), signo);
2633 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2635 #if defined(USE_ITHREADS) && !defined(WIN32)
2636 /* only "parent" interpreter can diddle signals */
2637 if (PL_curinterp != aTHX)
2640 *save = PerlProc_signal(signo, handler);
2641 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2645 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2647 #if defined(USE_ITHREADS) && !defined(WIN32)
2648 /* only "parent" interpreter can diddle signals */
2649 if (PL_curinterp != aTHX)
2652 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2655 #endif /* !HAS_SIGACTION */
2656 #endif /* !PERL_MICRO */
2658 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2659 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2661 Perl_my_pclose(pTHX_ PerlIO *ptr)
2664 Sigsave_t hstat, istat, qstat;
2670 int saved_errno = 0;
2672 int saved_win32_errno;
2676 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2678 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2680 *svp = &PL_sv_undef;
2682 if (pid == -1) { /* Opened by popen. */
2683 return my_syspclose(ptr);
2686 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2687 saved_errno = errno;
2689 saved_win32_errno = GetLastError();
2693 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2696 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2697 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2698 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2701 pid2 = wait4pid(pid, &status, 0);
2702 } while (pid2 == -1 && errno == EINTR);
2704 rsignal_restore(SIGHUP, &hstat);
2705 rsignal_restore(SIGINT, &istat);
2706 rsignal_restore(SIGQUIT, &qstat);
2709 SETERRNO(saved_errno, 0);
2712 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2714 #endif /* !DOSISH */
2716 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2718 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2724 #ifdef PERL_USES_PL_PIDSTATUS
2727 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2728 pid, rather than a string form. */
2729 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2730 if (svp && *svp != &PL_sv_undef) {
2731 *statusp = SvIVX(*svp);
2732 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2740 hv_iterinit(PL_pidstatus);
2741 if ((entry = hv_iternext(PL_pidstatus))) {
2742 SV * const sv = hv_iterval(PL_pidstatus,entry);
2744 const char * const spid = hv_iterkey(entry,&len);
2746 assert (len == sizeof(Pid_t));
2747 memcpy((char *)&pid, spid, len);
2748 *statusp = SvIVX(sv);
2749 /* The hash iterator is currently on this entry, so simply
2750 calling hv_delete would trigger the lazy delete, which on
2751 aggregate does more work, beacuse next call to hv_iterinit()
2752 would spot the flag, and have to call the delete routine,
2753 while in the meantime any new entries can't re-use that
2755 hv_iterinit(PL_pidstatus);
2756 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2763 # ifdef HAS_WAITPID_RUNTIME
2764 if (!HAS_WAITPID_RUNTIME)
2767 result = PerlProc_waitpid(pid,statusp,flags);
2770 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2771 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2774 #ifdef PERL_USES_PL_PIDSTATUS
2775 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2780 Perl_croak(aTHX_ "Can't do waitpid with flags");
2782 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2783 pidgone(result,*statusp);
2789 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2792 if (result < 0 && errno == EINTR) {
2797 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2799 #ifdef PERL_USES_PL_PIDSTATUS
2801 Perl_pidgone(pTHX_ Pid_t pid, int status)
2805 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2806 SvUPGRADE(sv,SVt_IV);
2807 SvIV_set(sv, status);
2812 #if defined(atarist) || defined(OS2) || defined(EPOC)
2815 int /* Cannot prototype with I32
2817 my_syspclose(PerlIO *ptr)
2820 Perl_my_pclose(pTHX_ PerlIO *ptr)
2823 /* Needs work for PerlIO ! */
2824 FILE * const f = PerlIO_findFILE(ptr);
2825 const I32 result = pclose(f);
2826 PerlIO_releaseFILE(ptr,f);
2834 Perl_my_pclose(pTHX_ PerlIO *ptr)
2836 /* Needs work for PerlIO ! */
2837 FILE * const f = PerlIO_findFILE(ptr);
2838 I32 result = djgpp_pclose(f);
2839 result = (result << 8) & 0xff00;
2840 PerlIO_releaseFILE(ptr,f);
2846 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2849 register const char * const frombase = from;
2852 register const char c = *from;
2857 while (count-- > 0) {
2858 for (todo = len; todo > 0; todo--) {
2867 Perl_same_dirent(pTHX_ const char *a, const char *b)
2869 char *fa = strrchr(a,'/');
2870 char *fb = strrchr(b,'/');
2873 SV * const tmpsv = sv_newmortal();
2886 sv_setpvn(tmpsv, ".", 1);
2888 sv_setpvn(tmpsv, a, fa - a);
2889 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2892 sv_setpvn(tmpsv, ".", 1);
2894 sv_setpvn(tmpsv, b, fb - b);
2895 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2897 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2898 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2900 #endif /* !HAS_RENAME */
2903 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2904 const char *const *const search_ext, I32 flags)
2907 const char *xfound = NULL;
2908 char *xfailed = NULL;
2909 char tmpbuf[MAXPATHLEN];
2913 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2914 # define SEARCH_EXTS ".bat", ".cmd", NULL
2915 # define MAX_EXT_LEN 4
2918 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2919 # define MAX_EXT_LEN 4
2922 # define SEARCH_EXTS ".pl", ".com", NULL
2923 # define MAX_EXT_LEN 4
2925 /* additional extensions to try in each dir if scriptname not found */
2927 static const char *const exts[] = { SEARCH_EXTS };
2928 const char *const *const ext = search_ext ? search_ext : exts;
2929 int extidx = 0, i = 0;
2930 const char *curext = NULL;
2932 PERL_UNUSED_ARG(search_ext);
2933 # define MAX_EXT_LEN 0
2937 * If dosearch is true and if scriptname does not contain path
2938 * delimiters, search the PATH for scriptname.
2940 * If SEARCH_EXTS is also defined, will look for each
2941 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2942 * while searching the PATH.
2944 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2945 * proceeds as follows:
2946 * If DOSISH or VMSISH:
2947 * + look for ./scriptname{,.foo,.bar}
2948 * + search the PATH for scriptname{,.foo,.bar}
2951 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2952 * this will not look in '.' if it's not in the PATH)
2957 # ifdef ALWAYS_DEFTYPES
2958 len = strlen(scriptname);
2959 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2960 int idx = 0, deftypes = 1;
2963 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
2966 int idx = 0, deftypes = 1;
2969 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
2971 /* The first time through, just add SEARCH_EXTS to whatever we
2972 * already have, so we can check for default file types. */
2974 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2980 if ((strlen(tmpbuf) + strlen(scriptname)
2981 + MAX_EXT_LEN) >= sizeof tmpbuf)
2982 continue; /* don't search dir with too-long name */
2983 strcat(tmpbuf, scriptname);
2987 if (strEQ(scriptname, "-"))
2989 if (dosearch) { /* Look in '.' first. */
2990 const char *cur = scriptname;
2992 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2994 if (strEQ(ext[i++],curext)) {
2995 extidx = -1; /* already has an ext */
3000 DEBUG_p(PerlIO_printf(Perl_debug_log,
3001 "Looking for %s\n",cur));
3002 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3003 && !S_ISDIR(PL_statbuf.st_mode)) {
3011 if (cur == scriptname) {
3012 len = strlen(scriptname);
3013 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3015 /* FIXME? Convert to memcpy */
3016 cur = strcpy(tmpbuf, scriptname);
3018 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3019 && strcpy(tmpbuf+len, ext[extidx++]));
3024 #ifdef MACOS_TRADITIONAL
3025 if (dosearch && !strchr(scriptname, ':') &&
3026 (s = PerlEnv_getenv("Commands")))
3028 if (dosearch && !strchr(scriptname, '/')
3030 && !strchr(scriptname, '\\')
3032 && (s = PerlEnv_getenv("PATH")))
3037 PL_bufend = s + strlen(s);
3038 while (s < PL_bufend) {
3039 #ifdef MACOS_TRADITIONAL
3040 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3044 #if defined(atarist) || defined(DOSISH)
3049 && *s != ';'; len++, s++) {
3050 if (len < sizeof tmpbuf)
3053 if (len < sizeof tmpbuf)
3055 #else /* ! (atarist || DOSISH) */
3056 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3059 #endif /* ! (atarist || DOSISH) */
3060 #endif /* MACOS_TRADITIONAL */
3063 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3064 continue; /* don't search dir with too-long name */
3065 #ifdef MACOS_TRADITIONAL
3066 if (len && tmpbuf[len - 1] != ':')
3067 tmpbuf[len++] = ':';
3070 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3071 && tmpbuf[len - 1] != '/'
3072 && tmpbuf[len - 1] != '\\'
3075 tmpbuf[len++] = '/';
3076 if (len == 2 && tmpbuf[0] == '.')
3079 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3081 (void)strcpy(tmpbuf + len, scriptname);
3085 len = strlen(tmpbuf);
3086 if (extidx > 0) /* reset after previous loop */
3090 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3091 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3092 if (S_ISDIR(PL_statbuf.st_mode)) {
3096 } while ( retval < 0 /* not there */
3097 && extidx>=0 && ext[extidx] /* try an extension? */
3098 && strcpy(tmpbuf+len, ext[extidx++])
3103 if (S_ISREG(PL_statbuf.st_mode)
3104 && cando(S_IRUSR,TRUE,&PL_statbuf)
3105 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3106 && cando(S_IXUSR,TRUE,&PL_statbuf)
3110 xfound = tmpbuf; /* bingo! */
3114 xfailed = savepv(tmpbuf);
3117 if (!xfound && !seen_dot && !xfailed &&
3118 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3119 || S_ISDIR(PL_statbuf.st_mode)))
3121 seen_dot = 1; /* Disable message. */
3123 if (flags & 1) { /* do or die? */
3124 Perl_croak(aTHX_ "Can't %s %s%s%s",
3125 (xfailed ? "execute" : "find"),
3126 (xfailed ? xfailed : scriptname),
3127 (xfailed ? "" : " on PATH"),
3128 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3133 scriptname = xfound;
3135 return (scriptname ? savepv(scriptname) : NULL);
3138 #ifndef PERL_GET_CONTEXT_DEFINED
3141 Perl_get_context(void)
3144 #if defined(USE_ITHREADS)
3145 # ifdef OLD_PTHREADS_API
3147 if (pthread_getspecific(PL_thr_key, &t))
3148 Perl_croak_nocontext("panic: pthread_getspecific");
3151 # ifdef I_MACH_CTHREADS
3152 return (void*)cthread_data(cthread_self());
3154 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3163 Perl_set_context(void *t)
3166 #if defined(USE_ITHREADS)
3167 # ifdef I_MACH_CTHREADS
3168 cthread_set_data(cthread_self(), t);
3170 if (pthread_setspecific(PL_thr_key, t))
3171 Perl_croak_nocontext("panic: pthread_setspecific");
3178 #endif /* !PERL_GET_CONTEXT_DEFINED */
3180 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3189 Perl_get_op_names(pTHX)
3191 return (char **)PL_op_name;
3195 Perl_get_op_descs(pTHX)
3197 return (char **)PL_op_desc;
3201 Perl_get_no_modify(pTHX)
3203 return PL_no_modify;
3207 Perl_get_opargs(pTHX)
3209 return (U32 *)PL_opargs;
3213 Perl_get_ppaddr(pTHX)
3216 return (PPADDR_t*)PL_ppaddr;
3219 #ifndef HAS_GETENV_LEN
3221 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3223 char * const env_trans = PerlEnv_getenv(env_elem);
3225 *len = strlen(env_trans);
3232 Perl_get_vtbl(pTHX_ int vtbl_id)
3234 const MGVTBL* result;
3238 result = &PL_vtbl_sv;
3241 result = &PL_vtbl_env;
3243 case want_vtbl_envelem:
3244 result = &PL_vtbl_envelem;
3247 result = &PL_vtbl_sig;
3249 case want_vtbl_sigelem:
3250 result = &PL_vtbl_sigelem;
3252 case want_vtbl_pack:
3253 result = &PL_vtbl_pack;
3255 case want_vtbl_packelem:
3256 result = &PL_vtbl_packelem;
3258 case want_vtbl_dbline:
3259 result = &PL_vtbl_dbline;
3262 result = &PL_vtbl_isa;
3264 case want_vtbl_isaelem:
3265 result = &PL_vtbl_isaelem;
3267 case want_vtbl_arylen:
3268 result = &PL_vtbl_arylen;
3270 case want_vtbl_glob:
3271 result = &PL_vtbl_glob;
3273 case want_vtbl_mglob:
3274 result = &PL_vtbl_mglob;
3276 case want_vtbl_nkeys:
3277 result = &PL_vtbl_nkeys;
3279 case want_vtbl_taint:
3280 result = &PL_vtbl_taint;
3282 case want_vtbl_substr:
3283 result = &PL_vtbl_substr;
3286 result = &PL_vtbl_vec;
3289 result = &PL_vtbl_pos;
3292 result = &PL_vtbl_bm;
3295 result = &PL_vtbl_fm;
3297 case want_vtbl_uvar:
3298 result = &PL_vtbl_uvar;
3300 case want_vtbl_defelem:
3301 result = &PL_vtbl_defelem;
3303 case want_vtbl_regexp:
3304 result = &PL_vtbl_regexp;
3306 case want_vtbl_regdata:
3307 result = &PL_vtbl_regdata;
3309 case want_vtbl_regdatum:
3310 result = &PL_vtbl_regdatum;
3312 #ifdef USE_LOCALE_COLLATE
3313 case want_vtbl_collxfrm:
3314 result = &PL_vtbl_collxfrm;
3317 case want_vtbl_amagic:
3318 result = &PL_vtbl_amagic;
3320 case want_vtbl_amagicelem:
3321 result = &PL_vtbl_amagicelem;
3323 case want_vtbl_backref:
3324 result = &PL_vtbl_backref;
3326 case want_vtbl_utf8:
3327 result = &PL_vtbl_utf8;
3330 result = Null(MGVTBL*);
3333 return (MGVTBL*)result;
3337 Perl_my_fflush_all(pTHX)
3339 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3340 return PerlIO_flush(NULL);
3342 # if defined(HAS__FWALK)
3343 extern int fflush(FILE *);
3344 /* undocumented, unprototyped, but very useful BSDism */
3345 extern void _fwalk(int (*)(FILE *));
3349 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3351 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3352 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3354 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3355 open_max = sysconf(_SC_OPEN_MAX);
3358 open_max = FOPEN_MAX;
3361 open_max = OPEN_MAX;
3372 for (i = 0; i < open_max; i++)
3373 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3374 STDIO_STREAM_ARRAY[i]._file < open_max &&
3375 STDIO_STREAM_ARRAY[i]._flag)
3376 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3380 SETERRNO(EBADF,RMS_IFI);
3387 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3389 const char * const func =
3390 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3391 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3393 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3394 const char * const type = OP_IS_SOCKET(op)
3395 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3396 ? "socket" : "filehandle";
3397 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3399 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3400 if (ckWARN(WARN_IO)) {
3401 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3403 Perl_warner(aTHX_ packWARN(WARN_IO),
3404 "Filehandle %s opened only for %sput",
3407 Perl_warner(aTHX_ packWARN(WARN_IO),
3408 "Filehandle opened only for %sput", direction);
3415 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3417 warn_type = WARN_CLOSED;
3421 warn_type = WARN_UNOPENED;
3424 if (ckWARN(warn_type)) {
3425 if (name && *name) {
3426 Perl_warner(aTHX_ packWARN(warn_type),
3427 "%s%s on %s %s %s", func, pars, vile, type, name);
3428 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3430 aTHX_ packWARN(warn_type),
3431 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3436 Perl_warner(aTHX_ packWARN(warn_type),
3437 "%s%s on %s %s", func, pars, vile, type);
3438 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3440 aTHX_ packWARN(warn_type),
3441 "\t(Are you trying to call %s%s on dirhandle?)\n",
3450 /* in ASCII order, not that it matters */
3451 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3454 Perl_ebcdic_control(pTHX_ int ch)
3462 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3463 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3466 if (ctlp == controllablechars)
3467 return('\177'); /* DEL */
3469 return((unsigned char)(ctlp - controllablechars - 1));
3470 } else { /* Want uncontrol */
3471 if (ch == '\177' || ch == -1)
3473 else if (ch == '\157')
3475 else if (ch == '\174')
3477 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3479 else if (ch == '\155')
3481 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3482 return(controllablechars[ch+1]);
3484 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3489 /* To workaround core dumps from the uninitialised tm_zone we get the
3490 * system to give us a reasonable struct to copy. This fix means that
3491 * strftime uses the tm_zone and tm_gmtoff values returned by
3492 * localtime(time()). That should give the desired result most of the
3493 * time. But probably not always!
3495 * This does not address tzname aspects of NETaa14816.
3500 # ifndef STRUCT_TM_HASZONE
3501 # define STRUCT_TM_HASZONE
3505 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3506 # ifndef HAS_TM_TM_ZONE
3507 # define HAS_TM_TM_ZONE
3512 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3514 #ifdef HAS_TM_TM_ZONE
3516 const struct tm* my_tm;
3518 my_tm = localtime(&now);
3520 Copy(my_tm, ptm, 1, struct tm);
3522 PERL_UNUSED_ARG(ptm);
3527 * mini_mktime - normalise struct tm values without the localtime()
3528 * semantics (and overhead) of mktime().
3531 Perl_mini_mktime(pTHX_ struct tm *ptm)
3535 int month, mday, year, jday;
3536 int odd_cent, odd_year;
3538 #define DAYS_PER_YEAR 365
3539 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3540 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3541 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3542 #define SECS_PER_HOUR (60*60)
3543 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3544 /* parentheses deliberately absent on these two, otherwise they don't work */
3545 #define MONTH_TO_DAYS 153/5
3546 #define DAYS_TO_MONTH 5/153
3547 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3548 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3549 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3550 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3553 * Year/day algorithm notes:
3555 * With a suitable offset for numeric value of the month, one can find
3556 * an offset into the year by considering months to have 30.6 (153/5) days,
3557 * using integer arithmetic (i.e., with truncation). To avoid too much
3558 * messing about with leap days, we consider January and February to be
3559 * the 13th and 14th month of the previous year. After that transformation,
3560 * we need the month index we use to be high by 1 from 'normal human' usage,
3561 * so the month index values we use run from 4 through 15.
3563 * Given that, and the rules for the Gregorian calendar (leap years are those
3564 * divisible by 4 unless also divisible by 100, when they must be divisible
3565 * by 400 instead), we can simply calculate the number of days since some
3566 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3567 * the days we derive from our month index, and adding in the day of the
3568 * month. The value used here is not adjusted for the actual origin which
3569 * it normally would use (1 January A.D. 1), since we're not exposing it.
3570 * We're only building the value so we can turn around and get the
3571 * normalised values for the year, month, day-of-month, and day-of-year.
3573 * For going backward, we need to bias the value we're using so that we find
3574 * the right year value. (Basically, we don't want the contribution of
3575 * March 1st to the number to apply while deriving the year). Having done
3576 * that, we 'count up' the contribution to the year number by accounting for
3577 * full quadracenturies (400-year periods) with their extra leap days, plus
3578 * the contribution from full centuries (to avoid counting in the lost leap
3579 * days), plus the contribution from full quad-years (to count in the normal
3580 * leap days), plus the leftover contribution from any non-leap years.
3581 * At this point, if we were working with an actual leap day, we'll have 0
3582 * days left over. This is also true for March 1st, however. So, we have
3583 * to special-case that result, and (earlier) keep track of the 'odd'
3584 * century and year contributions. If we got 4 extra centuries in a qcent,
3585 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3586 * Otherwise, we add back in the earlier bias we removed (the 123 from
3587 * figuring in March 1st), find the month index (integer division by 30.6),
3588 * and the remainder is the day-of-month. We then have to convert back to
3589 * 'real' months (including fixing January and February from being 14/15 in
3590 * the previous year to being in the proper year). After that, to get
3591 * tm_yday, we work with the normalised year and get a new yearday value for
3592 * January 1st, which we subtract from the yearday value we had earlier,
3593 * representing the date we've re-built. This is done from January 1
3594 * because tm_yday is 0-origin.
3596 * Since POSIX time routines are only guaranteed to work for times since the
3597 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3598 * applies Gregorian calendar rules even to dates before the 16th century
3599 * doesn't bother me. Besides, you'd need cultural context for a given
3600 * date to know whether it was Julian or Gregorian calendar, and that's
3601 * outside the scope for this routine. Since we convert back based on the
3602 * same rules we used to build the yearday, you'll only get strange results
3603 * for input which needed normalising, or for the 'odd' century years which
3604 * were leap years in the Julian calander but not in the Gregorian one.
3605 * I can live with that.
3607 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3608 * that's still outside the scope for POSIX time manipulation, so I don't
3612 year = 1900 + ptm->tm_year;
3613 month = ptm->tm_mon;
3614 mday = ptm->tm_mday;
3615 /* allow given yday with no month & mday to dominate the result */
3616 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3619 jday = 1 + ptm->tm_yday;
3628 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3629 yearday += month*MONTH_TO_DAYS + mday + jday;
3631 * Note that we don't know when leap-seconds were or will be,
3632 * so we have to trust the user if we get something which looks
3633 * like a sensible leap-second. Wild values for seconds will
3634 * be rationalised, however.
3636 if ((unsigned) ptm->tm_sec <= 60) {
3643 secs += 60 * ptm->tm_min;
3644 secs += SECS_PER_HOUR * ptm->tm_hour;
3646 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3647 /* got negative remainder, but need positive time */
3648 /* back off an extra day to compensate */
3649 yearday += (secs/SECS_PER_DAY)-1;
3650 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3653 yearday += (secs/SECS_PER_DAY);
3654 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3657 else if (secs >= SECS_PER_DAY) {
3658 yearday += (secs/SECS_PER_DAY);
3659 secs %= SECS_PER_DAY;
3661 ptm->tm_hour = secs/SECS_PER_HOUR;
3662 secs %= SECS_PER_HOUR;
3663 ptm->tm_min = secs/60;
3665 ptm->tm_sec += secs;
3666 /* done with time of day effects */
3668 * The algorithm for yearday has (so far) left it high by 428.
3669 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3670 * bias it by 123 while trying to figure out what year it
3671 * really represents. Even with this tweak, the reverse
3672 * translation fails for years before A.D. 0001.
3673 * It would still fail for Feb 29, but we catch that one below.
3675 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3676 yearday -= YEAR_ADJUST;
3677 year = (yearday / DAYS_PER_QCENT) * 400;
3678 yearday %= DAYS_PER_QCENT;
3679 odd_cent = yearday / DAYS_PER_CENT;
3680 year += odd_cent * 100;
3681 yearday %= DAYS_PER_CENT;
3682 year += (yearday / DAYS_PER_QYEAR) * 4;
3683 yearday %= DAYS_PER_QYEAR;
3684 odd_year = yearday / DAYS_PER_YEAR;
3686 yearday %= DAYS_PER_YEAR;
3687 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3692 yearday += YEAR_ADJUST; /* recover March 1st crock */
3693 month = yearday*DAYS_TO_MONTH;
3694 yearday -= month*MONTH_TO_DAYS;
3695 /* recover other leap-year adjustment */
3704 ptm->tm_year = year - 1900;
3706 ptm->tm_mday = yearday;
3707 ptm->tm_mon = month;
3711 ptm->tm_mon = month - 1;
3713 /* re-build yearday based on Jan 1 to get tm_yday */
3715 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3716 yearday += 14*MONTH_TO_DAYS + 1;
3717 ptm->tm_yday = jday - yearday;
3718 /* fix tm_wday if not overridden by caller */
3719 if ((unsigned)ptm->tm_wday > 6)
3720 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3724 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)
3732 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3735 mytm.tm_hour = hour;
3736 mytm.tm_mday = mday;
3738 mytm.tm_year = year;
3739 mytm.tm_wday = wday;
3740 mytm.tm_yday = yday;
3741 mytm.tm_isdst = isdst;
3743 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3744 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3749 #ifdef HAS_TM_TM_GMTOFF
3750 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3752 #ifdef HAS_TM_TM_ZONE
3753 mytm.tm_zone = mytm2.tm_zone;
3758 Newx(buf, buflen, char);
3759 len = strftime(buf, buflen, fmt, &mytm);
3761 ** The following is needed to handle to the situation where
3762 ** tmpbuf overflows. Basically we want to allocate a buffer
3763 ** and try repeatedly. The reason why it is so complicated
3764 ** is that getting a return value of 0 from strftime can indicate
3765 ** one of the following:
3766 ** 1. buffer overflowed,
3767 ** 2. illegal conversion specifier, or
3768 ** 3. the format string specifies nothing to be returned(not
3769 ** an error). This could be because format is an empty string
3770 ** or it specifies %p that yields an empty string in some locale.
3771 ** If there is a better way to make it portable, go ahead by
3774 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3777 /* Possibly buf overflowed - try again with a bigger buf */
3778 const int fmtlen = strlen(fmt);
3779 const int bufsize = fmtlen + buflen;
3781 Newx(buf, bufsize, char);
3783 buflen = strftime(buf, bufsize, fmt, &mytm);
3784 if (buflen > 0 && buflen < bufsize)
3786 /* heuristic to prevent out-of-memory errors */
3787 if (bufsize > 100*fmtlen) {
3792 Renew(buf, bufsize*2, char);
3797 Perl_croak(aTHX_ "panic: no strftime");
3803 #define SV_CWD_RETURN_UNDEF \
3804 sv_setsv(sv, &PL_sv_undef); \
3807 #define SV_CWD_ISDOT(dp) \
3808 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3809 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3812 =head1 Miscellaneous Functions
3814 =for apidoc getcwd_sv
3816 Fill the sv with current working directory
3821 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3822 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3823 * getcwd(3) if available
3824 * Comments from the orignal:
3825 * This is a faster version of getcwd. It's also more dangerous
3826 * because you might chdir out of a directory that you can't chdir
3830 Perl_getcwd_sv(pTHX_ register SV *sv)
3834 #ifndef INCOMPLETE_TAINTS
3840 char buf[MAXPATHLEN];
3842 /* Some getcwd()s automatically allocate a buffer of the given
3843 * size from the heap if they are given a NULL buffer pointer.
3844 * The problem is that this behaviour is not portable. */
3845 if (getcwd(buf, sizeof(buf) - 1)) {
3850 sv_setsv(sv, &PL_sv_undef);
3858 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3862 SvUPGRADE(sv, SVt_PV);
3864 if (PerlLIO_lstat(".", &statbuf) < 0) {
3865 SV_CWD_RETURN_UNDEF;
3868 orig_cdev = statbuf.st_dev;
3869 orig_cino = statbuf.st_ino;
3878 if (PerlDir_chdir("..") < 0) {
3879 SV_CWD_RETURN_UNDEF;
3881 if (PerlLIO_stat(".", &statbuf) < 0) {
3882 SV_CWD_RETURN_UNDEF;
3885 cdev = statbuf.st_dev;
3886 cino = statbuf.st_ino;
3888 if (odev == cdev && oino == cino) {
3891 if (!(dir = PerlDir_open("."))) {
3892 SV_CWD_RETURN_UNDEF;
3895 while ((dp = PerlDir_read(dir)) != NULL) {
3897 const int namelen = dp->d_namlen;
3899 const int namelen = strlen(dp->d_name);
3902 if (SV_CWD_ISDOT(dp)) {
3906 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3907 SV_CWD_RETURN_UNDEF;
3910 tdev = statbuf.st_dev;
3911 tino = statbuf.st_ino;
3912 if (tino == oino && tdev == odev) {
3918 SV_CWD_RETURN_UNDEF;
3921 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3922 SV_CWD_RETURN_UNDEF;
3925 SvGROW(sv, pathlen + namelen + 1);
3929 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3932 /* prepend current directory to the front */
3934 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3935 pathlen += (namelen + 1);
3937 #ifdef VOID_CLOSEDIR
3940 if (PerlDir_close(dir) < 0) {
3941 SV_CWD_RETURN_UNDEF;
3947 SvCUR_set(sv, pathlen);
3951 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3952 SV_CWD_RETURN_UNDEF;
3955 if (PerlLIO_stat(".", &statbuf) < 0) {
3956 SV_CWD_RETURN_UNDEF;
3959 cdev = statbuf.st_dev;
3960 cino = statbuf.st_ino;
3962 if (cdev != orig_cdev || cino != orig_cino) {
3963 Perl_croak(aTHX_ "Unstable directory path, "
3964 "current directory changed unexpectedly");
3976 =for apidoc scan_version
3978 Returns a pointer to the next character after the parsed
3979 version string, as well as upgrading the passed in SV to
3982 Function must be called with an already existing SV like
3985 s = scan_version(s,SV *sv, bool qv);
3987 Performs some preprocessing to the string to ensure that
3988 it has the correct characteristics of a version. Flags the
3989 object if it contains an underscore (which denotes this
3990 is a alpha version). The boolean qv denotes that the version
3991 should be interpreted as if it had multiple decimals, even if
3998 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4006 AV * const av = newAV();
4007 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4008 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4010 #ifndef NODEFAULT_SHAREKEYS
4011 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4014 while (isSPACE(*s)) /* leading whitespace is OK */
4018 s++; /* get past 'v' */
4019 qv = 1; /* force quoted version processing */
4022 start = last = pos = s;
4024 /* pre-scan the input string to check for decimals/underbars */
4025 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4030 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4034 else if ( *pos == '_' )
4037 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4039 width = pos - last - 1; /* natural width of sub-version */
4044 if ( alpha && !saw_period )
4045 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4047 if ( saw_period > 1 )
4048 qv = 1; /* force quoted version processing */
4053 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4055 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4056 if ( !qv && width < 3 )
4057 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4059 while (isDIGIT(*pos))
4061 if (!isALPHA(*pos)) {
4067 /* this is atoi() that delimits on underscores */
4068 const char *end = pos;
4072 /* the following if() will only be true after the decimal
4073 * point of a version originally created with a bare
4074 * floating point number, i.e. not quoted in any way
4076 if ( !qv && s > start && saw_period == 1 ) {
4080 rev += (*s - '0') * mult;
4082 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4083 Perl_croak(aTHX_ "Integer overflow in version");
4090 while (--end >= s) {
4092 rev += (*end - '0') * mult;
4094 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4095 Perl_croak(aTHX_ "Integer overflow in version");
4100 /* Append revision */
4101 av_push(av, newSViv(rev));
4102 if ( *pos == '.' && isDIGIT(pos[1]) )
4104 else if ( *pos == '_' && isDIGIT(pos[1]) )
4106 else if ( isDIGIT(*pos) )
4113 while ( isDIGIT(*pos) )
4118 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4126 if ( qv ) { /* quoted versions always get at least three terms*/
4127 I32 len = av_len(av);
4128 /* This for loop appears to trigger a compiler bug on OS X, as it
4129 loops infinitely. Yes, len is negative. No, it makes no sense.
4130 Compiler in question is:
4131 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4132 for ( len = 2 - len; len > 0; len-- )
4133 av_push((AV *)sv, newSViv(0));
4137 av_push(av, newSViv(0));
4140 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4141 av_push(av, newSViv(0));
4143 /* And finally, store the AV in the hash */
4144 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4149 =for apidoc new_version
4151 Returns a new version object based on the passed in SV:
4153 SV *sv = new_version(SV *ver);
4155 Does not alter the passed in ver SV. See "upg_version" if you
4156 want to upgrade the SV.
4162 Perl_new_version(pTHX_ SV *ver)
4165 SV * const rv = newSV(0);
4166 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4169 AV * const av = newAV();
4171 /* This will get reblessed later if a derived class*/
4172 SV * const hv = newSVrv(rv, "version");
4173 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4174 #ifndef NODEFAULT_SHAREKEYS
4175 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4181 /* Begin copying all of the elements */
4182 if ( hv_exists((HV *)ver, "qv", 2) )
4183 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4185 if ( hv_exists((HV *)ver, "alpha", 5) )
4186 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4188 if ( hv_exists((HV*)ver, "width", 5 ) )
4190 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4191 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4194 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4195 /* This will get reblessed later if a derived class*/
4196 for ( key = 0; key <= av_len(sav); key++ )
4198 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4199 av_push(av, newSViv(rev));
4202 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4207 const MAGIC* const mg = SvVOK(ver);
4208 if ( mg ) { /* already a v-string */
4209 const STRLEN len = mg->mg_len;
4210 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4211 sv_setpvn(rv,version,len);
4216 sv_setsv(rv,ver); /* make a duplicate */
4221 return upg_version(rv);
4225 =for apidoc upg_version
4227 In-place upgrade of the supplied SV to a version object.
4229 SV *sv = upg_version(SV *sv);
4231 Returns a pointer to the upgraded SV.
4237 Perl_upg_version(pTHX_ SV *ver)
4239 const char *version, *s;
4245 if ( SvNOK(ver) ) /* may get too much accuracy */
4248 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4249 version = savepvn(tbuf, len);
4252 else if ( (mg = SvVOK(ver)) ) { /* already a v-string */
4253 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4257 else /* must be a string or something like a string */
4259 version = savepv(SvPV_nolen(ver));
4261 s = scan_version(version, ver, qv);
4263 if(ckWARN(WARN_MISC))
4264 Perl_warner(aTHX_ packWARN(WARN_MISC),
4265 "Version string '%s' contains invalid data; "
4266 "ignoring: '%s'", version, s);
4274 Validates that the SV contains a valid version object.
4276 bool vverify(SV *vobj);
4278 Note that it only confirms the bare minimum structure (so as not to get
4279 confused by derived classes which may contain additional hash entries):
4283 =item * The SV contains a [reference to a] hash
4285 =item * The hash contains a "version" key
4287 =item * The "version" key has [a reference to] an AV as its value
4295 Perl_vverify(pTHX_ SV *vs)
4301 /* see if the appropriate elements exist */
4302 if ( SvTYPE(vs) == SVt_PVHV
4303 && hv_exists((HV*)vs, "version", 7)
4304 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4305 && SvTYPE(sv) == SVt_PVAV )
4314 Accepts a version object and returns the normalized floating
4315 point representation. Call like:
4319 NOTE: you can pass either the object directly or the SV
4320 contained within the RV.
4326 Perl_vnumify(pTHX_ SV *vs)
4331 SV * const sv = newSV(0);
4337 Perl_croak(aTHX_ "Invalid version object");
4339 /* see if various flags exist */
4340 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4342 if ( hv_exists((HV*)vs, "width", 5 ) )
4343 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4348 /* attempt to retrieve the version array */
4349 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4361 digit = SvIV(*av_fetch(av, 0, 0));
4362 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4363 for ( i = 1 ; i < len ; i++ )
4365 digit = SvIV(*av_fetch(av, i, 0));
4367 const int denom = (width == 2 ? 10 : 100);
4368 const div_t term = div((int)PERL_ABS(digit),denom);
4369 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4372 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4378 digit = SvIV(*av_fetch(av, len, 0));
4379 if ( alpha && width == 3 ) /* alpha version */
4381 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4385 sv_catpvs(sv, "000");
4393 Accepts a version object and returns the normalized string
4394 representation. Call like:
4398 NOTE: you can pass either the object directly or the SV
4399 contained within the RV.
4405 Perl_vnormal(pTHX_ SV *vs)
4409 SV * const sv = newSV(0);
4415 Perl_croak(aTHX_ "Invalid version object");
4417 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4419 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4427 digit = SvIV(*av_fetch(av, 0, 0));
4428 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4429 for ( i = 1 ; i < len ; i++ ) {
4430 digit = SvIV(*av_fetch(av, i, 0));
4431 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4436 /* handle last digit specially */
4437 digit = SvIV(*av_fetch(av, len, 0));
4439 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4441 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4444 if ( len <= 2 ) { /* short version, must be at least three */
4445 for ( len = 2 - len; len != 0; len-- )
4452 =for apidoc vstringify
4454 In order to maintain maximum compatibility with earlier versions
4455 of Perl, this function will return either the floating point
4456 notation or the multiple dotted notation, depending on whether
4457 the original version contained 1 or more dots, respectively
4463 Perl_vstringify(pTHX_ SV *vs)
4469 Perl_croak(aTHX_ "Invalid version object");
4471 if ( hv_exists((HV *)vs, "qv", 2) )
4480 Version object aware cmp. Both operands must already have been
4481 converted into version objects.
4487 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4490 bool lalpha = FALSE;
4491 bool ralpha = FALSE;
4500 if ( !vverify(lhv) )
4501 Perl_croak(aTHX_ "Invalid version object");
4503 if ( !vverify(rhv) )
4504 Perl_croak(aTHX_ "Invalid version object");
4506 /* get the left hand term */
4507 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4508 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4511 /* and the right hand term */
4512 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4513 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4521 while ( i <= m && retval == 0 )
4523 left = SvIV(*av_fetch(lav,i,0));
4524 right = SvIV(*av_fetch(rav,i,0));
4532 /* tiebreaker for alpha with identical terms */
4533 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4535 if ( lalpha && !ralpha )
4539 else if ( ralpha && !lalpha)
4545 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4549 while ( i <= r && retval == 0 )
4551 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4552 retval = -1; /* not a match after all */
4558 while ( i <= l && retval == 0 )
4560 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4561 retval = +1; /* not a match after all */
4569 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4570 # define EMULATE_SOCKETPAIR_UDP
4573 #ifdef EMULATE_SOCKETPAIR_UDP
4575 S_socketpair_udp (int fd[2]) {
4577 /* Fake a datagram socketpair using UDP to localhost. */
4578 int sockets[2] = {-1, -1};
4579 struct sockaddr_in addresses[2];
4581 Sock_size_t size = sizeof(struct sockaddr_in);
4582 unsigned short port;
4585 memset(&addresses, 0, sizeof(addresses));
4588 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4589 if (sockets[i] == -1)
4590 goto tidy_up_and_fail;
4592 addresses[i].sin_family = AF_INET;
4593 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4594 addresses[i].sin_port = 0; /* kernel choses port. */
4595 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4596 sizeof(struct sockaddr_in)) == -1)
4597 goto tidy_up_and_fail;
4600 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4601 for each connect the other socket to it. */
4604 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4606 goto tidy_up_and_fail;
4607 if (size != sizeof(struct sockaddr_in))
4608 goto abort_tidy_up_and_fail;
4609 /* !1 is 0, !0 is 1 */
4610 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4611 sizeof(struct sockaddr_in)) == -1)
4612 goto tidy_up_and_fail;
4615 /* Now we have 2 sockets connected to each other. I don't trust some other
4616 process not to have already sent a packet to us (by random) so send
4617 a packet from each to the other. */
4620 /* I'm going to send my own port number. As a short.
4621 (Who knows if someone somewhere has sin_port as a bitfield and needs
4622 this routine. (I'm assuming crays have socketpair)) */
4623 port = addresses[i].sin_port;
4624 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4625 if (got != sizeof(port)) {
4627 goto tidy_up_and_fail;
4628 goto abort_tidy_up_and_fail;
4632 /* Packets sent. I don't trust them to have arrived though.
4633 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4634 connect to localhost will use a second kernel thread. In 2.6 the
4635 first thread running the connect() returns before the second completes,
4636 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4637 returns 0. Poor programs have tripped up. One poor program's authors'
4638 had a 50-1 reverse stock split. Not sure how connected these were.)
4639 So I don't trust someone not to have an unpredictable UDP stack.
4643 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4644 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4648 FD_SET((unsigned int)sockets[0], &rset);
4649 FD_SET((unsigned int)sockets[1], &rset);
4651 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4652 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4653 || !FD_ISSET(sockets[1], &rset)) {
4654 /* I hope this is portable and appropriate. */
4656 goto tidy_up_and_fail;
4657 goto abort_tidy_up_and_fail;
4661 /* And the paranoia department even now doesn't trust it to have arrive
4662 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4664 struct sockaddr_in readfrom;
4665 unsigned short buffer[2];
4670 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4671 sizeof(buffer), MSG_DONTWAIT,
4672 (struct sockaddr *) &readfrom, &size);
4674 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4676 (struct sockaddr *) &readfrom, &size);
4680 goto tidy_up_and_fail;
4681 if (got != sizeof(port)
4682 || size != sizeof(struct sockaddr_in)
4683 /* Check other socket sent us its port. */
4684 || buffer[0] != (unsigned short) addresses[!i].sin_port
4685 /* Check kernel says we got the datagram from that socket */
4686 || readfrom.sin_family != addresses[!i].sin_family
4687 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4688 || readfrom.sin_port != addresses[!i].sin_port)
4689 goto abort_tidy_up_and_fail;
4692 /* My caller (my_socketpair) has validated that this is non-NULL */
4695 /* I hereby declare this connection open. May God bless all who cross
4699 abort_tidy_up_and_fail:
4700 errno = ECONNABORTED;
4703 const int save_errno = errno;
4704 if (sockets[0] != -1)
4705 PerlLIO_close(sockets[0]);
4706 if (sockets[1] != -1)
4707 PerlLIO_close(sockets[1]);
4712 #endif /* EMULATE_SOCKETPAIR_UDP */
4714 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4716 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4717 /* Stevens says that family must be AF_LOCAL, protocol 0.
4718 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4723 struct sockaddr_in listen_addr;
4724 struct sockaddr_in connect_addr;
4729 || family != AF_UNIX
4732 errno = EAFNOSUPPORT;
4740 #ifdef EMULATE_SOCKETPAIR_UDP
4741 if (type == SOCK_DGRAM)
4742 return S_socketpair_udp(fd);
4745 listener = PerlSock_socket(AF_INET, type, 0);
4748 memset(&listen_addr, 0, sizeof(listen_addr));
4749 listen_addr.sin_family = AF_INET;
4750 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4751 listen_addr.sin_port = 0; /* kernel choses port. */
4752 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4753 sizeof(listen_addr)) == -1)
4754 goto tidy_up_and_fail;
4755 if (PerlSock_listen(listener, 1) == -1)
4756 goto tidy_up_and_fail;
4758 connector = PerlSock_socket(AF_INET, type, 0);
4759 if (connector == -1)
4760 goto tidy_up_and_fail;
4761 /* We want to find out the port number to connect to. */
4762 size = sizeof(connect_addr);
4763 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4765 goto tidy_up_and_fail;
4766 if (size != sizeof(connect_addr))
4767 goto abort_tidy_up_and_fail;
4768 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4769 sizeof(connect_addr)) == -1)
4770 goto tidy_up_and_fail;
4772 size = sizeof(listen_addr);
4773 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4776 goto tidy_up_and_fail;
4777 if (size != sizeof(listen_addr))
4778 goto abort_tidy_up_and_fail;
4779 PerlLIO_close(listener);
4780 /* Now check we are talking to ourself by matching port and host on the
4782 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4784 goto tidy_up_and_fail;
4785 if (size != sizeof(connect_addr)
4786 || listen_addr.sin_family != connect_addr.sin_family
4787 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4788 || listen_addr.sin_port != connect_addr.sin_port) {
4789 goto abort_tidy_up_and_fail;
4795 abort_tidy_up_and_fail:
4797 errno = ECONNABORTED; /* This would be the standard thing to do. */
4799 # ifdef ECONNREFUSED
4800 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4802 errno = ETIMEDOUT; /* Desperation time. */
4807 const int save_errno = errno;
4809 PerlLIO_close(listener);
4810 if (connector != -1)
4811 PerlLIO_close(connector);
4813 PerlLIO_close(acceptor);
4819 /* In any case have a stub so that there's code corresponding
4820 * to the my_socketpair in global.sym. */
4822 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4823 #ifdef HAS_SOCKETPAIR
4824 return socketpair(family, type, protocol, fd);
4833 =for apidoc sv_nosharing
4835 Dummy routine which "shares" an SV when there is no sharing module present.
4836 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4837 Exists to avoid test for a NULL function pointer and because it could
4838 potentially warn under some level of strict-ness.
4844 Perl_sv_nosharing(pTHX_ SV *sv)
4846 PERL_UNUSED_ARG(sv);
4850 Perl_parse_unicode_opts(pTHX_ const char **popt)
4852 const char *p = *popt;
4857 opt = (U32) atoi(p);
4858 while (isDIGIT(*p)) p++;
4859 if (*p && *p != '\n' && *p != '\r')
4860 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4865 case PERL_UNICODE_STDIN:
4866 opt |= PERL_UNICODE_STDIN_FLAG; break;
4867 case PERL_UNICODE_STDOUT:
4868 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4869 case PERL_UNICODE_STDERR:
4870 opt |= PERL_UNICODE_STDERR_FLAG; break;
4871 case PERL_UNICODE_STD:
4872 opt |= PERL_UNICODE_STD_FLAG; break;
4873 case PERL_UNICODE_IN:
4874 opt |= PERL_UNICODE_IN_FLAG; break;
4875 case PERL_UNICODE_OUT:
4876 opt |= PERL_UNICODE_OUT_FLAG; break;
4877 case PERL_UNICODE_INOUT:
4878 opt |= PERL_UNICODE_INOUT_FLAG; break;
4879 case PERL_UNICODE_LOCALE:
4880 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4881 case PERL_UNICODE_ARGV:
4882 opt |= PERL_UNICODE_ARGV_FLAG; break;
4884 if (*p != '\n' && *p != '\r')
4886 "Unknown Unicode option letter '%c'", *p);
4892 opt = PERL_UNICODE_DEFAULT_FLAGS;
4894 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4895 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4896 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4908 * This is really just a quick hack which grabs various garbage
4909 * values. It really should be a real hash algorithm which
4910 * spreads the effect of every input bit onto every output bit,
4911 * if someone who knows about such things would bother to write it.
4912 * Might be a good idea to add that function to CORE as well.
4913 * No numbers below come from careful analysis or anything here,
4914 * except they are primes and SEED_C1 > 1E6 to get a full-width
4915 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4916 * probably be bigger too.
4919 # define SEED_C1 1000003
4920 #define SEED_C4 73819
4922 # define SEED_C1 25747
4923 #define SEED_C4 20639
4927 #define SEED_C5 26107
4929 #ifndef PERL_NO_DEV_RANDOM
4934 # include <starlet.h>
4935 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4936 * in 100-ns units, typically incremented ever 10 ms. */
4937 unsigned int when[2];
4939 # ifdef HAS_GETTIMEOFDAY
4940 struct timeval when;
4946 /* This test is an escape hatch, this symbol isn't set by Configure. */
4947 #ifndef PERL_NO_DEV_RANDOM
4948 #ifndef PERL_RANDOM_DEVICE
4949 /* /dev/random isn't used by default because reads from it will block
4950 * if there isn't enough entropy available. You can compile with
4951 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4952 * is enough real entropy to fill the seed. */
4953 # define PERL_RANDOM_DEVICE "/dev/urandom"
4955 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4957 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4966 _ckvmssts(sys$gettim(when));
4967 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4969 # ifdef HAS_GETTIMEOFDAY
4970 PerlProc_gettimeofday(&when,NULL);
4971 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4974 u = (U32)SEED_C1 * when;
4977 u += SEED_C3 * (U32)PerlProc_getpid();
4978 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4979 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4980 u += SEED_C5 * (U32)PTR2UV(&when);
4986 Perl_get_hash_seed(pTHX)
4989 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4993 while (isSPACE(*s)) s++;
4994 if (s && isDIGIT(*s))
4995 myseed = (UV)Atoul(s);
4997 #ifdef USE_HASH_SEED_EXPLICIT
5001 /* Compute a random seed */
5002 (void)seedDrand01((Rand_seed_t)seed());
5003 myseed = (UV)(Drand01() * (NV)UV_MAX);
5004 #if RANDBITS < (UVSIZE * 8)
5005 /* Since there are not enough randbits to to reach all
5006 * the bits of a UV, the low bits might need extra
5007 * help. Sum in another random number that will
5008 * fill in the low bits. */
5010 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
5011 #endif /* RANDBITS < (UVSIZE * 8) */
5012 if (myseed == 0) { /* Superparanoia. */
5013 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5015 Perl_croak(aTHX_ "Your random numbers are not that random");
5018 PL_rehash_seed_set = TRUE;
5025 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5027 const char * const stashpv = CopSTASHPV(c);
5028 const char * const name = HvNAME_get(hv);
5030 if (stashpv == name)
5032 if (stashpv && name)
5033 if (strEQ(stashpv, name))
5040 #ifdef PERL_GLOBAL_STRUCT
5043 Perl_init_global_struct(pTHX)
5045 struct perl_vars *plvarsp = NULL;
5046 #ifdef PERL_GLOBAL_STRUCT
5047 # define PERL_GLOBAL_STRUCT_INIT
5048 # include "opcode.h" /* the ppaddr and check */
5049 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5050 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5051 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5052 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5053 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5057 plvarsp = PL_VarsPtr;
5058 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5064 # define PERLVAR(var,type) /**/
5065 # define PERLVARA(var,n,type) /**/
5066 # define PERLVARI(var,type,init) plvarsp->var = init;
5067 # define PERLVARIC(var,type,init) plvarsp->var = init;
5068 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5069 # include "perlvars.h"
5075 # ifdef PERL_GLOBAL_STRUCT
5076 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5077 if (!plvarsp->Gppaddr)
5079 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5080 if (!plvarsp->Gcheck)
5082 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5083 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5085 # ifdef PERL_SET_VARS
5086 PERL_SET_VARS(plvarsp);
5088 # undef PERL_GLOBAL_STRUCT_INIT
5093 #endif /* PERL_GLOBAL_STRUCT */
5095 #ifdef PERL_GLOBAL_STRUCT
5098 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5100 #ifdef PERL_GLOBAL_STRUCT
5101 # ifdef PERL_UNSET_VARS
5102 PERL_UNSET_VARS(plvarsp);
5104 free(plvarsp->Gppaddr);
5105 free(plvarsp->Gcheck);
5106 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5112 #endif /* PERL_GLOBAL_STRUCT */
5116 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5119 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)
5121 #ifdef PERL_MEM_LOG_STDERR
5122 /* We can't use PerlIO for obvious reasons. */
5123 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5124 const STRLEN len = my_sprintf(buf,
5125 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5126 " %s = %"IVdf": %"UVxf"\n",
5127 filename, linenumber, funcname, n, typesize,
5128 typename, n * typesize, PTR2UV(newalloc));
5129 PerlLIO_write(2, buf, len);
5135 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)
5137 #ifdef PERL_MEM_LOG_STDERR
5138 /* We can't use PerlIO for obvious reasons. */
5139 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5140 const STRLEN len = my_sprintf(buf, "realloc: %s:%d:%s: %"IVdf" %"UVuf
5141 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5142 filename, linenumber, funcname, n, typesize,
5143 typename, n * typesize, PTR2UV(oldalloc),
5145 PerlLIO_write(2, buf, len);
5151 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5153 #ifdef PERL_MEM_LOG_STDERR
5154 /* We can't use PerlIO for obvious reasons. */
5155 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5156 const STRLEN len = my_sprintf(buf, "free: %s:%d:%s: %"UVxf"\n",
5157 filename, linenumber, funcname,
5159 PerlLIO_write(2, buf, len);
5164 #endif /* PERL_MEM_LOG */
5167 =for apidoc my_sprintf
5169 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5170 the length of the string written to the buffer. Only rare pre-ANSI systems
5171 need the wrapper function - usually this is a direct call to C<sprintf>.
5175 #ifndef SPRINTF_RETURNS_STRLEN
5177 Perl_my_sprintf(char *buffer, const char* pat, ...)
5180 va_start(args, pat);
5181 vsprintf(buffer, pat, args);
5183 return strlen(buffer);
5188 Perl_my_clearenv(pTHX)
5191 #if ! defined(PERL_MICRO)
5192 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5194 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5195 # if defined(USE_ENVIRON_ARRAY)
5196 # if defined(USE_ITHREADS)
5197 /* only the parent thread can clobber the process environment */
5198 if (PL_curinterp == aTHX)
5199 # endif /* USE_ITHREADS */
5201 # if ! defined(PERL_USE_SAFE_PUTENV)
5202 if ( !PL_use_safe_putenv) {
5204 if (environ == PL_origenviron)
5205 environ = (char**)safesysmalloc(sizeof(char*));
5207 for (i = 0; environ[i]; i++)
5208 (void)safesysfree(environ[i]);
5211 # else /* PERL_USE_SAFE_PUTENV */
5212 # if defined(HAS_CLEARENV)
5214 # elif defined(HAS_UNSETENV)
5215 int bsiz = 80; /* Most envvar names will be shorter than this. */
5216 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
5217 while (*environ != NULL) {
5218 char *e = strchr(*environ, '=');
5219 int l = e ? e - *environ : strlen(*environ);
5221 (void)safesysfree(buf);
5223 buf = (char*)safesysmalloc(bsiz * sizeof(char));
5225 strncpy(buf, *environ, l);
5227 (void)unsetenv(buf);
5229 (void)safesysfree(buf);
5230 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5231 /* Just null environ and accept the leakage. */
5233 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5234 # endif /* ! PERL_USE_SAFE_PUTENV */
5236 # endif /* USE_ENVIRON_ARRAY */
5237 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5238 #endif /* PERL_MICRO */
5241 #ifdef PERL_IMPLICIT_CONTEXT
5243 /* implements the MY_CXT_INIT macro. The first time a module is loaded,
5244 the global PL_my_cxt_index is incremented, and that value is assigned to
5245 that module's static my_cxt_index (who's address is passed as an arg).
5246 Then, for each interpreter this function is called for, it makes sure a
5247 void* slot is available to hang the static data off, by allocating or
5248 extending the interpreter's PL_my_cxt_list array */
5251 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5256 /* this module hasn't been allocated an index yet */
5257 MUTEX_LOCK(&PL_my_ctx_mutex);
5258 *index = PL_my_cxt_index++;
5259 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5262 /* make sure the array is big enough */
5263 if (PL_my_cxt_size <= *index) {
5264 if (PL_my_cxt_size) {
5265 while (PL_my_cxt_size <= *index)
5266 PL_my_cxt_size *= 2;
5267 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5270 PL_my_cxt_size = 16;
5271 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5274 /* newSV() allocates one more than needed */
5275 p = (void*)SvPVX(newSV(size-1));
5276 PL_my_cxt_list[*index] = p;
5277 Zero(p, size, char);
5284 * c-indentation-style: bsd
5286 * indent-tabs-mode: t
5289 * ex: set ts=8 sts=4 sw=4 noet: