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 *)ptr)->interpreter = aTHX;
99 ((struct perl_memory_debug_header *)ptr)->size = size;
100 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
102 ptr = (Malloc_t)((char*)ptr+sTHX);
109 return write_no_mem();
114 /* paranoid version of system's realloc() */
117 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
121 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
122 Malloc_t PerlMem_realloc();
123 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
127 PerlIO_printf(Perl_error_log,
128 "Reallocation too large: %lx\n", size) FLUSH;
131 #endif /* HAS_64K_LIMIT */
138 return safesysmalloc(size);
139 #ifdef PERL_TRACK_MEMPOOL
140 where = (Malloc_t)((char*)where-sTHX);
142 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
143 Perl_croak_nocontext("panic: realloc from wrong pool");
146 if (((struct perl_memory_debug_header *)where)->size > size) {
147 const MEM_SIZE freed_up =
148 ((struct perl_memory_debug_header *)where)->size - size;
149 char *start_of_freed = ((char *)where) + size;
150 Poison(start_of_freed, freed_up, char);
152 ((struct perl_memory_debug_header *)where)->size = size;
157 Perl_croak_nocontext("panic: realloc");
159 ptr = (Malloc_t)PerlMem_realloc(where,size);
160 PERL_ALLOC_CHECK(ptr);
162 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
163 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
166 #ifdef PERL_TRACK_MEMPOOL
167 ptr = (Malloc_t)((char*)ptr+sTHX);
174 return write_no_mem();
179 /* safe version of system's free() */
182 Perl_safesysfree(Malloc_t where)
184 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
189 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
191 #ifdef PERL_TRACK_MEMPOOL
192 where = (Malloc_t)((char*)where-sTHX);
193 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
194 Perl_croak_nocontext("panic: free from wrong pool");
198 if (((struct perl_memory_debug_header *)where)->in_use
199 == PERL_POISON_FREE) {
200 Perl_croak_nocontext("panic: duplicate free");
202 if (((struct perl_memory_debug_header *)where)->in_use
203 != PERL_POISON_INUSE) {
204 Perl_croak_nocontext("panic: bad free ");
206 ((struct perl_memory_debug_header *)where)->in_use
209 Poison(where, ((struct perl_memory_debug_header *)where)->size, char);
216 /* safe version of system's calloc() */
219 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
225 if (size * count > 0xffff) {
226 PerlIO_printf(Perl_error_log,
227 "Allocation too large: %lx\n", size * count) FLUSH;
230 #endif /* HAS_64K_LIMIT */
232 if ((long)size < 0 || (long)count < 0)
233 Perl_croak_nocontext("panic: calloc");
236 #ifdef PERL_TRACK_MEMPOOL
239 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
240 PERL_ALLOC_CHECK(ptr);
241 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));
243 memset((void*)ptr, 0, size);
244 #ifdef PERL_TRACK_MEMPOOL
245 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
247 ((struct perl_memory_debug_header *)ptr)->size = size;
248 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
250 ptr = (Malloc_t)((char*)ptr+sTHX);
256 return write_no_mem();
259 /* These must be defined when not using Perl's malloc for binary
264 Malloc_t Perl_malloc (MEM_SIZE nbytes)
267 return (Malloc_t)PerlMem_malloc(nbytes);
270 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
273 return (Malloc_t)PerlMem_calloc(elements, size);
276 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
279 return (Malloc_t)PerlMem_realloc(where, nbytes);
282 Free_t Perl_mfree (Malloc_t where)
290 /* copy a string up to some (non-backslashed) delimiter, if any */
293 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
296 for (tolen = 0; from < fromend; from++, tolen++) {
298 if (from[1] == delim)
307 else if (*from == delim)
318 /* return ptr to little string in big string, NULL if not found */
319 /* This routine was donated by Corey Satten. */
322 Perl_instr(pTHX_ register const char *big, register const char *little)
332 register const char *s, *x;
335 for (x=big,s=little; *s; /**/ ) {
346 return (char*)(big-1);
351 /* same as instr but allow embedded nulls */
354 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
359 char first = *little++;
361 bigend -= lend - little;
363 while (big <= bigend) {
366 for (x=big,s=little; s < lend; x++,s++) {
370 return (char*)(big-1);
376 /* reverse of the above--find last substring */
379 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
381 register const char *bigbeg;
382 register const I32 first = *little;
383 register const char * const littleend = lend;
385 if (little >= littleend)
386 return (char*)bigend;
388 big = bigend - (littleend - little++);
389 while (big >= bigbeg) {
390 register const char *s, *x;
393 for (x=big+2,s=little; s < littleend; /**/ ) {
402 return (char*)(big+1);
407 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
409 /* As a space optimization, we do not compile tables for strings of length
410 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
411 special-cased in fbm_instr().
413 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
416 =head1 Miscellaneous Functions
418 =for apidoc fbm_compile
420 Analyses the string in order to make fast searches on it using fbm_instr()
421 -- the Boyer-Moore algorithm.
427 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
430 register const U8 *s;
436 if (flags & FBMcf_TAIL) {
437 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
438 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
439 if (mg && mg->mg_len >= 0)
442 s = (U8*)SvPV_force_mutable(sv, len);
443 SvUPGRADE(sv, SVt_PVBM);
444 if (len == 0) /* TAIL might be on a zero-length string. */
447 const unsigned char *sb;
448 const U8 mlen = (len>255) ? 255 : (U8)len;
451 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
452 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
453 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
454 memset((void*)table, mlen, 256);
455 table[-1] = (U8)flags;
457 sb = s - mlen + 1; /* first char (maybe) */
459 if (table[*s] == mlen)
464 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
467 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
468 for (i = 0; i < len; i++) {
469 if (PL_freq[s[i]] < frequency) {
471 frequency = PL_freq[s[i]];
474 BmRARE(sv) = s[rarest];
475 BmPREVIOUS(sv) = (U16)rarest;
476 BmUSEFUL(sv) = 100; /* Initial value */
477 if (flags & FBMcf_TAIL)
479 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
480 BmRARE(sv),BmPREVIOUS(sv)));
483 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
484 /* If SvTAIL is actually due to \Z or \z, this gives false positives
488 =for apidoc fbm_instr
490 Returns the location of the SV in the string delimited by C<str> and
491 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
492 does not have to be fbm_compiled, but the search will not be as fast
499 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
501 register unsigned char *s;
503 register const unsigned char *little
504 = (const unsigned char *)SvPV_const(littlestr,l);
505 register STRLEN littlelen = l;
506 register const I32 multiline = flags & FBMrf_MULTILINE;
508 if ((STRLEN)(bigend - big) < littlelen) {
509 if ( SvTAIL(littlestr)
510 && ((STRLEN)(bigend - big) == littlelen - 1)
512 || (*big == *little &&
513 memEQ((char *)big, (char *)little, littlelen - 1))))
518 if (littlelen <= 2) { /* Special-cased */
520 if (littlelen == 1) {
521 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
522 /* Know that bigend != big. */
523 if (bigend[-1] == '\n')
524 return (char *)(bigend - 1);
525 return (char *) bigend;
533 if (SvTAIL(littlestr))
534 return (char *) bigend;
538 return (char*)big; /* Cannot be SvTAIL! */
541 if (SvTAIL(littlestr) && !multiline) {
542 if (bigend[-1] == '\n' && bigend[-2] == *little)
543 return (char*)bigend - 2;
544 if (bigend[-1] == *little)
545 return (char*)bigend - 1;
549 /* This should be better than FBM if c1 == c2, and almost
550 as good otherwise: maybe better since we do less indirection.
551 And we save a lot of memory by caching no table. */
552 const unsigned char c1 = little[0];
553 const unsigned char c2 = little[1];
558 while (s <= bigend) {
568 goto check_1char_anchor;
579 goto check_1char_anchor;
582 while (s <= bigend) {
587 goto check_1char_anchor;
596 check_1char_anchor: /* One char and anchor! */
597 if (SvTAIL(littlestr) && (*bigend == *little))
598 return (char *)bigend; /* bigend is already decremented. */
601 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
602 s = bigend - littlelen;
603 if (s >= big && bigend[-1] == '\n' && *s == *little
604 /* Automatically of length > 2 */
605 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
607 return (char*)s; /* how sweet it is */
610 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
612 return (char*)s + 1; /* how sweet it is */
616 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
617 char * const b = ninstr((char*)big,(char*)bigend,
618 (char*)little, (char*)little + littlelen);
620 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
621 /* Chop \n from littlestr: */
622 s = bigend - littlelen + 1;
624 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
633 { /* Do actual FBM. */
634 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
635 register const unsigned char *oldlittle;
637 if (littlelen > (STRLEN)(bigend - big))
639 --littlelen; /* Last char found by table lookup */
642 little += littlelen; /* last char */
648 if ((tmp = table[*s])) {
649 if ((s += tmp) < bigend)
653 else { /* less expensive than calling strncmp() */
654 register unsigned char * const olds = s;
659 if (*--s == *--little)
661 s = olds + 1; /* here we pay the price for failure */
663 if (s < bigend) /* fake up continue to outer loop */
671 if ( s == bigend && (table[-1] & FBMcf_TAIL)
672 && memEQ((char *)(bigend - littlelen),
673 (char *)(oldlittle - littlelen), littlelen) )
674 return (char*)bigend - littlelen;
679 /* start_shift, end_shift are positive quantities which give offsets
680 of ends of some substring of bigstr.
681 If "last" we want the last occurrence.
682 old_posp is the way of communication between consequent calls if
683 the next call needs to find the .
684 The initial *old_posp should be -1.
686 Note that we take into account SvTAIL, so one can get extra
687 optimizations if _ALL flag is set.
690 /* If SvTAIL is actually due to \Z or \z, this gives false positives
691 if PL_multiline. In fact if !PL_multiline the authoritative answer
692 is not supported yet. */
695 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
698 register const unsigned char *big;
700 register I32 previous;
702 register const unsigned char *little;
703 register I32 stop_pos;
704 register const unsigned char *littleend;
708 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
709 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
711 if ( BmRARE(littlestr) == '\n'
712 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
713 little = (const unsigned char *)(SvPVX_const(littlestr));
714 littleend = little + SvCUR(littlestr);
721 little = (const unsigned char *)(SvPVX_const(littlestr));
722 littleend = little + SvCUR(littlestr);
724 /* The value of pos we can start at: */
725 previous = BmPREVIOUS(littlestr);
726 big = (const unsigned char *)(SvPVX_const(bigstr));
727 /* The value of pos we can stop at: */
728 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
729 if (previous + start_shift > stop_pos) {
731 stop_pos does not include SvTAIL in the count, so this check is incorrect
732 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
735 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
740 while (pos < previous + start_shift) {
741 if (!(pos += PL_screamnext[pos]))
746 register const unsigned char *s, *x;
747 if (pos >= stop_pos) break;
748 if (big[pos] != first)
750 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
756 if (s == littleend) {
758 if (!last) return (char *)(big+pos);
761 } while ( pos += PL_screamnext[pos] );
763 return (char *)(big+(*old_posp));
765 if (!SvTAIL(littlestr) || (end_shift > 0))
767 /* Ignore the trailing "\n". This code is not microoptimized */
768 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
769 stop_pos = littleend - little; /* Actual littlestr len */
774 && ((stop_pos == 1) ||
775 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
781 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
783 register const U8 *a = (const U8 *)s1;
784 register const U8 *b = (const U8 *)s2;
786 if (*a != *b && *a != PL_fold[*b])
794 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
797 register const U8 *a = (const U8 *)s1;
798 register const U8 *b = (const U8 *)s2;
800 if (*a != *b && *a != PL_fold_locale[*b])
807 /* copy a string to a safe spot */
810 =head1 Memory Management
814 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
815 string which is a duplicate of C<pv>. The size of the string is
816 determined by C<strlen()>. The memory allocated for the new string can
817 be freed with the C<Safefree()> function.
823 Perl_savepv(pTHX_ const char *pv)
829 const STRLEN pvlen = strlen(pv)+1;
830 Newx(newaddr,pvlen,char);
831 return memcpy(newaddr,pv,pvlen);
836 /* same thing but with a known length */
841 Perl's version of what C<strndup()> would be if it existed. Returns a
842 pointer to a newly allocated string which is a duplicate of the first
843 C<len> bytes from C<pv>. The memory allocated for the new string can be
844 freed with the C<Safefree()> function.
850 Perl_savepvn(pTHX_ const char *pv, register I32 len)
852 register char *newaddr;
854 Newx(newaddr,len+1,char);
855 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
857 /* might not be null terminated */
859 return (char *) CopyD(pv,newaddr,len,char);
862 return (char *) ZeroD(newaddr,len+1,char);
867 =for apidoc savesharedpv
869 A version of C<savepv()> which allocates the duplicate string in memory
870 which is shared between threads.
875 Perl_savesharedpv(pTHX_ const char *pv)
877 register char *newaddr;
882 pvlen = strlen(pv)+1;
883 newaddr = (char*)PerlMemShared_malloc(pvlen);
885 return write_no_mem();
887 return memcpy(newaddr,pv,pvlen);
893 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
894 the passed in SV using C<SvPV()>
900 Perl_savesvpv(pTHX_ SV *sv)
903 const char * const pv = SvPV_const(sv, len);
904 register char *newaddr;
907 Newx(newaddr,len,char);
908 return (char *) CopyD(pv,newaddr,len,char);
912 /* the SV for Perl_form() and mess() is not kept in an arena */
922 return sv_2mortal(newSVpvs(""));
927 /* Create as PVMG now, to avoid any upgrading later */
929 Newxz(any, 1, XPVMG);
930 SvFLAGS(sv) = SVt_PVMG;
931 SvANY(sv) = (void*)any;
933 SvREFCNT(sv) = 1 << 30; /* practically infinite */
938 #if defined(PERL_IMPLICIT_CONTEXT)
940 Perl_form_nocontext(const char* pat, ...)
946 retval = vform(pat, &args);
950 #endif /* PERL_IMPLICIT_CONTEXT */
953 =head1 Miscellaneous Functions
956 Takes a sprintf-style format pattern and conventional
957 (non-SV) arguments and returns the formatted string.
959 (char *) Perl_form(pTHX_ const char* pat, ...)
961 can be used any place a string (char *) is required:
963 char * s = Perl_form("%d.%d",major,minor);
965 Uses a single private buffer so if you want to format several strings you
966 must explicitly copy the earlier strings away (and free the copies when you
973 Perl_form(pTHX_ const char* pat, ...)
978 retval = vform(pat, &args);
984 Perl_vform(pTHX_ const char *pat, va_list *args)
986 SV * const sv = mess_alloc();
987 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
991 #if defined(PERL_IMPLICIT_CONTEXT)
993 Perl_mess_nocontext(const char *pat, ...)
999 retval = vmess(pat, &args);
1003 #endif /* PERL_IMPLICIT_CONTEXT */
1006 Perl_mess(pTHX_ const char *pat, ...)
1010 va_start(args, pat);
1011 retval = vmess(pat, &args);
1017 S_closest_cop(pTHX_ COP *cop, const OP *o)
1020 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1022 if (!o || o == PL_op)
1025 if (o->op_flags & OPf_KIDS) {
1027 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1030 /* If the OP_NEXTSTATE has been optimised away we can still use it
1031 * the get the file and line number. */
1033 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1036 /* Keep searching, and return when we've found something. */
1038 new_cop = closest_cop(cop, kid);
1044 /* Nothing found. */
1050 Perl_vmess(pTHX_ const char *pat, va_list *args)
1053 SV * const sv = mess_alloc();
1054 static const char dgd[] = " during global destruction.\n";
1056 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1057 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1060 * Try and find the file and line for PL_op. This will usually be
1061 * PL_curcop, but it might be a cop that has been optimised away. We
1062 * can try to find such a cop by searching through the optree starting
1063 * from the sibling of PL_curcop.
1066 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1067 if (!cop) cop = PL_curcop;
1070 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1071 OutCopFILE(cop), (IV)CopLINE(cop));
1072 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1073 const bool line_mode = (RsSIMPLE(PL_rs) &&
1074 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1075 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1076 PL_last_in_gv == PL_argvgv ?
1077 "" : GvNAME(PL_last_in_gv),
1078 line_mode ? "line" : "chunk",
1079 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1081 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1087 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1093 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1094 && (io = GvIO(PL_stderrgv))
1095 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1102 SAVESPTR(PL_stderrgv);
1103 PL_stderrgv = Nullgv;
1105 PUSHSTACKi(PERLSI_MAGIC);
1109 PUSHs(SvTIED_obj((SV*)io, mg));
1110 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1112 call_method("PRINT", G_SCALAR);
1120 /* SFIO can really mess with your errno */
1121 const int e = errno;
1123 PerlIO * const serr = Perl_error_log;
1125 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1126 (void)PerlIO_flush(serr);
1133 /* Common code used by vcroak, vdie and vwarner */
1136 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1142 /* sv_2cv might call Perl_croak() */
1143 SV * const olddiehook = PL_diehook;
1147 SAVESPTR(PL_diehook);
1148 PL_diehook = Nullsv;
1149 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1151 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1158 msg = newSVpvn(message, msglen);
1159 SvFLAGS(msg) |= utf8;
1167 PUSHSTACKi(PERLSI_DIEHOOK);
1171 call_sv((SV*)cv, G_DISCARD);
1178 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1182 const char *message;
1185 SV * const msv = vmess(pat, args);
1186 if (PL_errors && SvCUR(PL_errors)) {
1187 sv_catsv(PL_errors, msv);
1188 message = SvPV_const(PL_errors, *msglen);
1189 SvCUR_set(PL_errors, 0);
1192 message = SvPV_const(msv,*msglen);
1193 *utf8 = SvUTF8(msv);
1199 DEBUG_S(PerlIO_printf(Perl_debug_log,
1200 "%p: die/croak: message = %s\ndiehook = %p\n",
1201 thr, message, PL_diehook));
1203 S_vdie_common(aTHX_ message, *msglen, *utf8);
1209 Perl_vdie(pTHX_ const char* pat, va_list *args)
1212 const char *message;
1213 const int was_in_eval = PL_in_eval;
1217 DEBUG_S(PerlIO_printf(Perl_debug_log,
1218 "%p: die: curstack = %p, mainstack = %p\n",
1219 thr, PL_curstack, PL_mainstack));
1221 message = vdie_croak_common(pat, args, &msglen, &utf8);
1223 PL_restartop = die_where(message, msglen);
1224 SvFLAGS(ERRSV) |= utf8;
1225 DEBUG_S(PerlIO_printf(Perl_debug_log,
1226 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1227 thr, PL_restartop, was_in_eval, PL_top_env));
1228 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1230 return PL_restartop;
1233 #if defined(PERL_IMPLICIT_CONTEXT)
1235 Perl_die_nocontext(const char* pat, ...)
1240 va_start(args, pat);
1241 o = vdie(pat, &args);
1245 #endif /* PERL_IMPLICIT_CONTEXT */
1248 Perl_die(pTHX_ const char* pat, ...)
1252 va_start(args, pat);
1253 o = vdie(pat, &args);
1259 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1262 const char *message;
1266 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1269 PL_restartop = die_where(message, msglen);
1270 SvFLAGS(ERRSV) |= utf8;
1274 message = SvPVx_const(ERRSV, msglen);
1276 write_to_stderr(message, msglen);
1280 #if defined(PERL_IMPLICIT_CONTEXT)
1282 Perl_croak_nocontext(const char *pat, ...)
1286 va_start(args, pat);
1291 #endif /* PERL_IMPLICIT_CONTEXT */
1294 =head1 Warning and Dieing
1298 This is the XSUB-writer's interface to Perl's C<die> function.
1299 Normally call this function the same way you call the C C<printf>
1300 function. Calling C<croak> returns control directly to Perl,
1301 sidestepping the normal C order of execution. See C<warn>.
1303 If you want to throw an exception object, assign the object to
1304 C<$@> and then pass C<Nullch> to croak():
1306 errsv = get_sv("@", TRUE);
1307 sv_setsv(errsv, exception_object);
1314 Perl_croak(pTHX_ const char *pat, ...)
1317 va_start(args, pat);
1324 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1328 SV * const msv = vmess(pat, args);
1329 const I32 utf8 = SvUTF8(msv);
1330 const char * const message = SvPV_const(msv, msglen);
1333 /* sv_2cv might call Perl_warn() */
1334 SV * const oldwarnhook = PL_warnhook;
1340 SAVESPTR(PL_warnhook);
1341 PL_warnhook = Nullsv;
1342 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1344 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1349 SAVESPTR(PL_warnhook);
1350 PL_warnhook = Nullsv;
1352 msg = newSVpvn(message, msglen);
1353 SvFLAGS(msg) |= utf8;
1357 PUSHSTACKi(PERLSI_WARNHOOK);
1361 call_sv((SV*)cv, G_DISCARD);
1368 write_to_stderr(message, msglen);
1371 #if defined(PERL_IMPLICIT_CONTEXT)
1373 Perl_warn_nocontext(const char *pat, ...)
1377 va_start(args, pat);
1381 #endif /* PERL_IMPLICIT_CONTEXT */
1386 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1387 function the same way you call the C C<printf> function. See C<croak>.
1393 Perl_warn(pTHX_ const char *pat, ...)
1396 va_start(args, pat);
1401 #if defined(PERL_IMPLICIT_CONTEXT)
1403 Perl_warner_nocontext(U32 err, const char *pat, ...)
1407 va_start(args, pat);
1408 vwarner(err, pat, &args);
1411 #endif /* PERL_IMPLICIT_CONTEXT */
1414 Perl_warner(pTHX_ U32 err, const char* pat,...)
1417 va_start(args, pat);
1418 vwarner(err, pat, &args);
1423 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1427 SV * const msv = vmess(pat, args);
1429 const char * const message = SvPV_const(msv, msglen);
1430 const I32 utf8 = SvUTF8(msv);
1434 S_vdie_common(aTHX_ message, msglen, utf8);
1437 PL_restartop = die_where(message, msglen);
1438 SvFLAGS(ERRSV) |= utf8;
1441 write_to_stderr(message, msglen);
1445 Perl_vwarn(aTHX_ pat, args);
1449 /* implements the ckWARN? macros */
1452 Perl_ckwarn(pTHX_ U32 w)
1458 && PL_curcop->cop_warnings != pWARN_NONE
1460 PL_curcop->cop_warnings == pWARN_ALL
1461 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1462 || (unpackWARN2(w) &&
1463 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1464 || (unpackWARN3(w) &&
1465 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1466 || (unpackWARN4(w) &&
1467 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1472 isLEXWARN_off && PL_dowarn & G_WARN_ON
1477 /* implements the ckWARN?_d macro */
1480 Perl_ckwarn_d(pTHX_ U32 w)
1485 || PL_curcop->cop_warnings == pWARN_ALL
1487 PL_curcop->cop_warnings != pWARN_NONE
1489 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1490 || (unpackWARN2(w) &&
1491 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1492 || (unpackWARN3(w) &&
1493 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1494 || (unpackWARN4(w) &&
1495 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1503 /* since we've already done strlen() for both nam and val
1504 * we can use that info to make things faster than
1505 * sprintf(s, "%s=%s", nam, val)
1507 #define my_setenv_format(s, nam, nlen, val, vlen) \
1508 Copy(nam, s, nlen, char); \
1510 Copy(val, s+(nlen+1), vlen, char); \
1511 *(s+(nlen+1+vlen)) = '\0'
1513 #ifdef USE_ENVIRON_ARRAY
1514 /* VMS' my_setenv() is in vms.c */
1515 #if !defined(WIN32) && !defined(NETWARE)
1517 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1521 /* only parent thread can modify process environment */
1522 if (PL_curinterp == aTHX)
1525 #ifndef PERL_USE_SAFE_PUTENV
1526 if (!PL_use_safe_putenv) {
1527 /* most putenv()s leak, so we manipulate environ directly */
1528 register I32 i=setenv_getix(nam); /* where does it go? */
1531 if (environ == PL_origenviron) { /* need we copy environment? */
1536 for (max = i; environ[max]; max++) ;
1537 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1538 for (j=0; j<max; j++) { /* copy environment */
1539 const int len = strlen(environ[j]);
1540 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1541 Copy(environ[j], tmpenv[j], len+1, char);
1543 tmpenv[max] = Nullch;
1544 environ = tmpenv; /* tell exec where it is now */
1547 safesysfree(environ[i]);
1548 while (environ[i]) {
1549 environ[i] = environ[i+1];
1554 if (!environ[i]) { /* does not exist yet */
1555 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1556 environ[i+1] = Nullch; /* make sure it's null terminated */
1559 safesysfree(environ[i]);
1563 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1564 /* all that work just for this */
1565 my_setenv_format(environ[i], nam, nlen, val, vlen);
1568 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1569 # if defined(HAS_UNSETENV)
1571 (void)unsetenv(nam);
1573 (void)setenv(nam, val, 1);
1575 # else /* ! HAS_UNSETENV */
1576 (void)setenv(nam, val, 1);
1577 # endif /* HAS_UNSETENV */
1579 # if defined(HAS_UNSETENV)
1581 (void)unsetenv(nam);
1583 const int nlen = strlen(nam);
1584 const int vlen = strlen(val);
1585 char * const new_env =
1586 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1587 my_setenv_format(new_env, nam, nlen, val, vlen);
1588 (void)putenv(new_env);
1590 # else /* ! HAS_UNSETENV */
1592 const int nlen = strlen(nam);
1598 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1599 /* all that work just for this */
1600 my_setenv_format(new_env, nam, nlen, val, vlen);
1601 (void)putenv(new_env);
1602 # endif /* HAS_UNSETENV */
1603 # endif /* __CYGWIN__ */
1604 #ifndef PERL_USE_SAFE_PUTENV
1610 #else /* WIN32 || NETWARE */
1613 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1616 register char *envstr;
1617 const int nlen = strlen(nam);
1624 Newx(envstr, nlen+vlen+2, char);
1625 my_setenv_format(envstr, nam, nlen, val, vlen);
1626 (void)PerlEnv_putenv(envstr);
1630 #endif /* WIN32 || NETWARE */
1634 Perl_setenv_getix(pTHX_ const char *nam)
1637 register const I32 len = strlen(nam);
1639 for (i = 0; environ[i]; i++) {
1642 strnicmp(environ[i],nam,len) == 0
1644 strnEQ(environ[i],nam,len)
1646 && environ[i][len] == '=')
1647 break; /* strnEQ must come first to avoid */
1648 } /* potential SEGV's */
1651 #endif /* !PERL_MICRO */
1653 #endif /* !VMS && !EPOC*/
1655 #ifdef UNLINK_ALL_VERSIONS
1657 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1661 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1666 /* this is a drop-in replacement for bcopy() */
1667 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1669 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1671 char * const retval = to;
1673 if (from - to >= 0) {
1681 *(--to) = *(--from);
1687 /* this is a drop-in replacement for memset() */
1690 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1692 char * const retval = loc;
1700 /* this is a drop-in replacement for bzero() */
1701 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1703 Perl_my_bzero(register char *loc, register I32 len)
1705 char * const retval = loc;
1713 /* this is a drop-in replacement for memcmp() */
1714 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1716 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1718 register const U8 *a = (const U8 *)s1;
1719 register const U8 *b = (const U8 *)s2;
1723 if ((tmp = *a++ - *b++))
1728 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1732 #ifdef USE_CHAR_VSPRINTF
1737 vsprintf(char *dest, const char *pat, char *args)
1741 fakebuf._ptr = dest;
1742 fakebuf._cnt = 32767;
1746 fakebuf._flag = _IOWRT|_IOSTRG;
1747 _doprnt(pat, args, &fakebuf); /* what a kludge */
1748 (void)putc('\0', &fakebuf);
1749 #ifdef USE_CHAR_VSPRINTF
1752 return 0; /* perl doesn't use return value */
1756 #endif /* HAS_VPRINTF */
1759 #if BYTEORDER != 0x4321
1761 Perl_my_swap(pTHX_ short s)
1763 #if (BYTEORDER & 1) == 0
1766 result = ((s & 255) << 8) + ((s >> 8) & 255);
1774 Perl_my_htonl(pTHX_ long l)
1778 char c[sizeof(long)];
1781 #if BYTEORDER == 0x1234
1782 u.c[0] = (l >> 24) & 255;
1783 u.c[1] = (l >> 16) & 255;
1784 u.c[2] = (l >> 8) & 255;
1788 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1789 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1794 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1795 u.c[o & 0xf] = (l >> s) & 255;
1803 Perl_my_ntohl(pTHX_ long l)
1807 char c[sizeof(long)];
1810 #if BYTEORDER == 0x1234
1811 u.c[0] = (l >> 24) & 255;
1812 u.c[1] = (l >> 16) & 255;
1813 u.c[2] = (l >> 8) & 255;
1817 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1818 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1825 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1826 l |= (u.c[o & 0xf] & 255) << s;
1833 #endif /* BYTEORDER != 0x4321 */
1837 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1838 * If these functions are defined,
1839 * the BYTEORDER is neither 0x1234 nor 0x4321.
1840 * However, this is not assumed.
1844 #define HTOLE(name,type) \
1846 name (register type n) \
1850 char c[sizeof(type)]; \
1853 register I32 s = 0; \
1854 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1855 u.c[i] = (n >> s) & 0xFF; \
1860 #define LETOH(name,type) \
1862 name (register type n) \
1866 char c[sizeof(type)]; \
1869 register I32 s = 0; \
1872 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1873 n |= ((type)(u.c[i] & 0xFF)) << s; \
1879 * Big-endian byte order functions.
1882 #define HTOBE(name,type) \
1884 name (register type n) \
1888 char c[sizeof(type)]; \
1891 register I32 s = 8*(sizeof(u.c)-1); \
1892 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1893 u.c[i] = (n >> s) & 0xFF; \
1898 #define BETOH(name,type) \
1900 name (register type n) \
1904 char c[sizeof(type)]; \
1907 register I32 s = 8*(sizeof(u.c)-1); \
1910 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1911 n |= ((type)(u.c[i] & 0xFF)) << s; \
1917 * If we just can't do it...
1920 #define NOT_AVAIL(name,type) \
1922 name (register type n) \
1924 Perl_croak_nocontext(#name "() not available"); \
1925 return n; /* not reached */ \
1929 #if defined(HAS_HTOVS) && !defined(htovs)
1932 #if defined(HAS_HTOVL) && !defined(htovl)
1935 #if defined(HAS_VTOHS) && !defined(vtohs)
1938 #if defined(HAS_VTOHL) && !defined(vtohl)
1942 #ifdef PERL_NEED_MY_HTOLE16
1944 HTOLE(Perl_my_htole16,U16)
1946 NOT_AVAIL(Perl_my_htole16,U16)
1949 #ifdef PERL_NEED_MY_LETOH16
1951 LETOH(Perl_my_letoh16,U16)
1953 NOT_AVAIL(Perl_my_letoh16,U16)
1956 #ifdef PERL_NEED_MY_HTOBE16
1958 HTOBE(Perl_my_htobe16,U16)
1960 NOT_AVAIL(Perl_my_htobe16,U16)
1963 #ifdef PERL_NEED_MY_BETOH16
1965 BETOH(Perl_my_betoh16,U16)
1967 NOT_AVAIL(Perl_my_betoh16,U16)
1971 #ifdef PERL_NEED_MY_HTOLE32
1973 HTOLE(Perl_my_htole32,U32)
1975 NOT_AVAIL(Perl_my_htole32,U32)
1978 #ifdef PERL_NEED_MY_LETOH32
1980 LETOH(Perl_my_letoh32,U32)
1982 NOT_AVAIL(Perl_my_letoh32,U32)
1985 #ifdef PERL_NEED_MY_HTOBE32
1987 HTOBE(Perl_my_htobe32,U32)
1989 NOT_AVAIL(Perl_my_htobe32,U32)
1992 #ifdef PERL_NEED_MY_BETOH32
1994 BETOH(Perl_my_betoh32,U32)
1996 NOT_AVAIL(Perl_my_betoh32,U32)
2000 #ifdef PERL_NEED_MY_HTOLE64
2002 HTOLE(Perl_my_htole64,U64)
2004 NOT_AVAIL(Perl_my_htole64,U64)
2007 #ifdef PERL_NEED_MY_LETOH64
2009 LETOH(Perl_my_letoh64,U64)
2011 NOT_AVAIL(Perl_my_letoh64,U64)
2014 #ifdef PERL_NEED_MY_HTOBE64
2016 HTOBE(Perl_my_htobe64,U64)
2018 NOT_AVAIL(Perl_my_htobe64,U64)
2021 #ifdef PERL_NEED_MY_BETOH64
2023 BETOH(Perl_my_betoh64,U64)
2025 NOT_AVAIL(Perl_my_betoh64,U64)
2029 #ifdef PERL_NEED_MY_HTOLES
2030 HTOLE(Perl_my_htoles,short)
2032 #ifdef PERL_NEED_MY_LETOHS
2033 LETOH(Perl_my_letohs,short)
2035 #ifdef PERL_NEED_MY_HTOBES
2036 HTOBE(Perl_my_htobes,short)
2038 #ifdef PERL_NEED_MY_BETOHS
2039 BETOH(Perl_my_betohs,short)
2042 #ifdef PERL_NEED_MY_HTOLEI
2043 HTOLE(Perl_my_htolei,int)
2045 #ifdef PERL_NEED_MY_LETOHI
2046 LETOH(Perl_my_letohi,int)
2048 #ifdef PERL_NEED_MY_HTOBEI
2049 HTOBE(Perl_my_htobei,int)
2051 #ifdef PERL_NEED_MY_BETOHI
2052 BETOH(Perl_my_betohi,int)
2055 #ifdef PERL_NEED_MY_HTOLEL
2056 HTOLE(Perl_my_htolel,long)
2058 #ifdef PERL_NEED_MY_LETOHL
2059 LETOH(Perl_my_letohl,long)
2061 #ifdef PERL_NEED_MY_HTOBEL
2062 HTOBE(Perl_my_htobel,long)
2064 #ifdef PERL_NEED_MY_BETOHL
2065 BETOH(Perl_my_betohl,long)
2069 Perl_my_swabn(void *ptr, int n)
2071 register char *s = (char *)ptr;
2072 register char *e = s + (n-1);
2075 for (n /= 2; n > 0; s++, e--, n--) {
2083 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2085 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2088 register I32 This, that;
2094 PERL_FLUSHALL_FOR_CHILD;
2095 This = (*mode == 'w');
2099 taint_proper("Insecure %s%s", "EXEC");
2101 if (PerlProc_pipe(p) < 0)
2103 /* Try for another pipe pair for error return */
2104 if (PerlProc_pipe(pp) >= 0)
2106 while ((pid = PerlProc_fork()) < 0) {
2107 if (errno != EAGAIN) {
2108 PerlLIO_close(p[This]);
2109 PerlLIO_close(p[that]);
2111 PerlLIO_close(pp[0]);
2112 PerlLIO_close(pp[1]);
2124 /* Close parent's end of error status pipe (if any) */
2126 PerlLIO_close(pp[0]);
2127 #if defined(HAS_FCNTL) && defined(F_SETFD)
2128 /* Close error pipe automatically if exec works */
2129 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2132 /* Now dup our end of _the_ pipe to right position */
2133 if (p[THIS] != (*mode == 'r')) {
2134 PerlLIO_dup2(p[THIS], *mode == 'r');
2135 PerlLIO_close(p[THIS]);
2136 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2137 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2140 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2141 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2142 /* No automatic close - do it by hand */
2149 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2155 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2161 do_execfree(); /* free any memory malloced by child on fork */
2163 PerlLIO_close(pp[1]);
2164 /* Keep the lower of the two fd numbers */
2165 if (p[that] < p[This]) {
2166 PerlLIO_dup2(p[This], p[that]);
2167 PerlLIO_close(p[This]);
2171 PerlLIO_close(p[that]); /* close child's end of pipe */
2174 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2176 SvUPGRADE(sv,SVt_IV);
2178 PL_forkprocess = pid;
2179 /* If we managed to get status pipe check for exec fail */
2180 if (did_pipes && pid > 0) {
2184 while (n < sizeof(int)) {
2185 n1 = PerlLIO_read(pp[0],
2186 (void*)(((char*)&errkid)+n),
2192 PerlLIO_close(pp[0]);
2194 if (n) { /* Error */
2196 PerlLIO_close(p[This]);
2197 if (n != sizeof(int))
2198 Perl_croak(aTHX_ "panic: kid popen errno read");
2200 pid2 = wait4pid(pid, &status, 0);
2201 } while (pid2 == -1 && errno == EINTR);
2202 errno = errkid; /* Propagate errno from kid */
2207 PerlLIO_close(pp[0]);
2208 return PerlIO_fdopen(p[This], mode);
2210 Perl_croak(aTHX_ "List form of piped open not implemented");
2211 return (PerlIO *) NULL;
2215 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2216 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2218 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2222 register I32 This, that;
2225 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2229 PERL_FLUSHALL_FOR_CHILD;
2232 return my_syspopen(aTHX_ cmd,mode);
2235 This = (*mode == 'w');
2237 if (doexec && PL_tainting) {
2239 taint_proper("Insecure %s%s", "EXEC");
2241 if (PerlProc_pipe(p) < 0)
2243 if (doexec && PerlProc_pipe(pp) >= 0)
2245 while ((pid = PerlProc_fork()) < 0) {
2246 if (errno != EAGAIN) {
2247 PerlLIO_close(p[This]);
2248 PerlLIO_close(p[that]);
2250 PerlLIO_close(pp[0]);
2251 PerlLIO_close(pp[1]);
2254 Perl_croak(aTHX_ "Can't fork");
2267 PerlLIO_close(pp[0]);
2268 #if defined(HAS_FCNTL) && defined(F_SETFD)
2269 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2272 if (p[THIS] != (*mode == 'r')) {
2273 PerlLIO_dup2(p[THIS], *mode == 'r');
2274 PerlLIO_close(p[THIS]);
2275 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2276 PerlLIO_close(p[THAT]);
2279 PerlLIO_close(p[THAT]);
2282 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2289 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2294 /* may or may not use the shell */
2295 do_exec3(cmd, pp[1], did_pipes);
2298 #endif /* defined OS2 */
2299 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2300 SvREADONLY_off(GvSV(tmpgv));
2301 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2302 SvREADONLY_on(GvSV(tmpgv));
2304 #ifdef THREADS_HAVE_PIDS
2305 PL_ppid = (IV)getppid();
2308 #ifdef PERL_USES_PL_PIDSTATUS
2309 hv_clear(PL_pidstatus); /* we have no children */
2315 do_execfree(); /* free any memory malloced by child on vfork */
2317 PerlLIO_close(pp[1]);
2318 if (p[that] < p[This]) {
2319 PerlLIO_dup2(p[This], p[that]);
2320 PerlLIO_close(p[This]);
2324 PerlLIO_close(p[that]);
2327 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2329 SvUPGRADE(sv,SVt_IV);
2331 PL_forkprocess = pid;
2332 if (did_pipes && pid > 0) {
2336 while (n < sizeof(int)) {
2337 n1 = PerlLIO_read(pp[0],
2338 (void*)(((char*)&errkid)+n),
2344 PerlLIO_close(pp[0]);
2346 if (n) { /* Error */
2348 PerlLIO_close(p[This]);
2349 if (n != sizeof(int))
2350 Perl_croak(aTHX_ "panic: kid popen errno read");
2352 pid2 = wait4pid(pid, &status, 0);
2353 } while (pid2 == -1 && errno == EINTR);
2354 errno = errkid; /* Propagate errno from kid */
2359 PerlLIO_close(pp[0]);
2360 return PerlIO_fdopen(p[This], mode);
2363 #if defined(atarist) || defined(EPOC)
2366 Perl_my_popen(pTHX_ char *cmd, char *mode)
2368 PERL_FLUSHALL_FOR_CHILD;
2369 /* Call system's popen() to get a FILE *, then import it.
2370 used 0 for 2nd parameter to PerlIO_importFILE;
2373 return PerlIO_importFILE(popen(cmd, mode), 0);
2377 FILE *djgpp_popen();
2379 Perl_my_popen(pTHX_ char *cmd, char *mode)
2381 PERL_FLUSHALL_FOR_CHILD;
2382 /* Call system's popen() to get a FILE *, then import it.
2383 used 0 for 2nd parameter to PerlIO_importFILE;
2386 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2391 #endif /* !DOSISH */
2393 /* this is called in parent before the fork() */
2395 Perl_atfork_lock(void)
2398 #if defined(USE_ITHREADS)
2399 /* locks must be held in locking order (if any) */
2401 MUTEX_LOCK(&PL_malloc_mutex);
2407 /* this is called in both parent and child after the fork() */
2409 Perl_atfork_unlock(void)
2412 #if defined(USE_ITHREADS)
2413 /* locks must be released in same order as in atfork_lock() */
2415 MUTEX_UNLOCK(&PL_malloc_mutex);
2424 #if defined(HAS_FORK)
2426 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2431 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2432 * handlers elsewhere in the code */
2437 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2438 Perl_croak_nocontext("fork() not available");
2440 #endif /* HAS_FORK */
2445 Perl_dump_fds(pTHX_ char *s)
2450 PerlIO_printf(Perl_debug_log,"%s", s);
2451 for (fd = 0; fd < 32; fd++) {
2452 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2453 PerlIO_printf(Perl_debug_log," %d",fd);
2455 PerlIO_printf(Perl_debug_log,"\n");
2458 #endif /* DUMP_FDS */
2462 dup2(int oldfd, int newfd)
2464 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2467 PerlLIO_close(newfd);
2468 return fcntl(oldfd, F_DUPFD, newfd);
2470 #define DUP2_MAX_FDS 256
2471 int fdtmp[DUP2_MAX_FDS];
2477 PerlLIO_close(newfd);
2478 /* good enough for low fd's... */
2479 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2480 if (fdx >= DUP2_MAX_FDS) {
2488 PerlLIO_close(fdtmp[--fdx]);
2495 #ifdef HAS_SIGACTION
2497 #ifdef MACOS_TRADITIONAL
2498 /* We don't want restart behavior on MacOS */
2503 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2506 struct sigaction act, oact;
2509 /* only "parent" interpreter can diddle signals */
2510 if (PL_curinterp != aTHX)
2511 return (Sighandler_t) SIG_ERR;
2514 act.sa_handler = (void(*)(int))handler;
2515 sigemptyset(&act.sa_mask);
2518 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2519 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2521 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2522 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2523 act.sa_flags |= SA_NOCLDWAIT;
2525 if (sigaction(signo, &act, &oact) == -1)
2526 return (Sighandler_t) SIG_ERR;
2528 return (Sighandler_t) oact.sa_handler;
2532 Perl_rsignal_state(pTHX_ int signo)
2534 struct sigaction oact;
2536 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2537 return (Sighandler_t) SIG_ERR;
2539 return (Sighandler_t) oact.sa_handler;
2543 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2546 struct sigaction act;
2549 /* only "parent" interpreter can diddle signals */
2550 if (PL_curinterp != aTHX)
2554 act.sa_handler = (void(*)(int))handler;
2555 sigemptyset(&act.sa_mask);
2558 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2559 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2561 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2562 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2563 act.sa_flags |= SA_NOCLDWAIT;
2565 return sigaction(signo, &act, save);
2569 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2573 /* only "parent" interpreter can diddle signals */
2574 if (PL_curinterp != aTHX)
2578 return sigaction(signo, save, (struct sigaction *)NULL);
2581 #else /* !HAS_SIGACTION */
2584 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2586 #if defined(USE_ITHREADS) && !defined(WIN32)
2587 /* only "parent" interpreter can diddle signals */
2588 if (PL_curinterp != aTHX)
2589 return (Sighandler_t) SIG_ERR;
2592 return PerlProc_signal(signo, handler);
2603 Perl_rsignal_state(pTHX_ int signo)
2606 Sighandler_t oldsig;
2608 #if defined(USE_ITHREADS) && !defined(WIN32)
2609 /* only "parent" interpreter can diddle signals */
2610 if (PL_curinterp != aTHX)
2611 return (Sighandler_t) SIG_ERR;
2615 oldsig = PerlProc_signal(signo, sig_trap);
2616 PerlProc_signal(signo, oldsig);
2618 PerlProc_kill(PerlProc_getpid(), signo);
2623 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2625 #if defined(USE_ITHREADS) && !defined(WIN32)
2626 /* only "parent" interpreter can diddle signals */
2627 if (PL_curinterp != aTHX)
2630 *save = PerlProc_signal(signo, handler);
2631 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2635 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2637 #if defined(USE_ITHREADS) && !defined(WIN32)
2638 /* only "parent" interpreter can diddle signals */
2639 if (PL_curinterp != aTHX)
2642 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2645 #endif /* !HAS_SIGACTION */
2646 #endif /* !PERL_MICRO */
2648 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2649 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2651 Perl_my_pclose(pTHX_ PerlIO *ptr)
2654 Sigsave_t hstat, istat, qstat;
2660 int saved_errno = 0;
2662 int saved_win32_errno;
2666 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2668 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2670 *svp = &PL_sv_undef;
2672 if (pid == -1) { /* Opened by popen. */
2673 return my_syspclose(ptr);
2676 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2677 saved_errno = errno;
2679 saved_win32_errno = GetLastError();
2683 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2686 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2687 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2688 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2691 pid2 = wait4pid(pid, &status, 0);
2692 } while (pid2 == -1 && errno == EINTR);
2694 rsignal_restore(SIGHUP, &hstat);
2695 rsignal_restore(SIGINT, &istat);
2696 rsignal_restore(SIGQUIT, &qstat);
2699 SETERRNO(saved_errno, 0);
2702 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2704 #endif /* !DOSISH */
2706 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2708 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2714 #ifdef PERL_USES_PL_PIDSTATUS
2717 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2718 pid, rather than a string form. */
2719 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2720 if (svp && *svp != &PL_sv_undef) {
2721 *statusp = SvIVX(*svp);
2722 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2730 hv_iterinit(PL_pidstatus);
2731 if ((entry = hv_iternext(PL_pidstatus))) {
2732 SV * const sv = hv_iterval(PL_pidstatus,entry);
2734 const char * const spid = hv_iterkey(entry,&len);
2736 assert (len == sizeof(Pid_t));
2737 memcpy((char *)&pid, spid, len);
2738 *statusp = SvIVX(sv);
2739 /* The hash iterator is currently on this entry, so simply
2740 calling hv_delete would trigger the lazy delete, which on
2741 aggregate does more work, beacuse next call to hv_iterinit()
2742 would spot the flag, and have to call the delete routine,
2743 while in the meantime any new entries can't re-use that
2745 hv_iterinit(PL_pidstatus);
2746 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2753 # ifdef HAS_WAITPID_RUNTIME
2754 if (!HAS_WAITPID_RUNTIME)
2757 result = PerlProc_waitpid(pid,statusp,flags);
2760 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2761 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2764 #ifdef PERL_USES_PL_PIDSTATUS
2765 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2770 Perl_croak(aTHX_ "Can't do waitpid with flags");
2772 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2773 pidgone(result,*statusp);
2779 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2782 if (result < 0 && errno == EINTR) {
2787 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2789 #ifdef PERL_USES_PL_PIDSTATUS
2791 Perl_pidgone(pTHX_ Pid_t pid, int status)
2795 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2796 SvUPGRADE(sv,SVt_IV);
2797 SvIV_set(sv, status);
2802 #if defined(atarist) || defined(OS2) || defined(EPOC)
2805 int /* Cannot prototype with I32
2807 my_syspclose(PerlIO *ptr)
2810 Perl_my_pclose(pTHX_ PerlIO *ptr)
2813 /* Needs work for PerlIO ! */
2814 FILE * const f = PerlIO_findFILE(ptr);
2815 const I32 result = pclose(f);
2816 PerlIO_releaseFILE(ptr,f);
2824 Perl_my_pclose(pTHX_ PerlIO *ptr)
2826 /* Needs work for PerlIO ! */
2827 FILE * const f = PerlIO_findFILE(ptr);
2828 I32 result = djgpp_pclose(f);
2829 result = (result << 8) & 0xff00;
2830 PerlIO_releaseFILE(ptr,f);
2836 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2839 register const char * const frombase = from;
2842 register const char c = *from;
2847 while (count-- > 0) {
2848 for (todo = len; todo > 0; todo--) {
2857 Perl_same_dirent(pTHX_ const char *a, const char *b)
2859 char *fa = strrchr(a,'/');
2860 char *fb = strrchr(b,'/');
2863 SV * const tmpsv = sv_newmortal();
2876 sv_setpvn(tmpsv, ".", 1);
2878 sv_setpvn(tmpsv, a, fa - a);
2879 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2882 sv_setpvn(tmpsv, ".", 1);
2884 sv_setpvn(tmpsv, b, fb - b);
2885 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2887 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2888 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2890 #endif /* !HAS_RENAME */
2893 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2894 const char *const *const search_ext, I32 flags)
2897 const char *xfound = Nullch;
2898 char *xfailed = Nullch;
2899 char tmpbuf[MAXPATHLEN];
2903 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2904 # define SEARCH_EXTS ".bat", ".cmd", NULL
2905 # define MAX_EXT_LEN 4
2908 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2909 # define MAX_EXT_LEN 4
2912 # define SEARCH_EXTS ".pl", ".com", NULL
2913 # define MAX_EXT_LEN 4
2915 /* additional extensions to try in each dir if scriptname not found */
2917 static const char *const exts[] = { SEARCH_EXTS };
2918 const char *const *const ext = search_ext ? search_ext : exts;
2919 int extidx = 0, i = 0;
2920 const char *curext = Nullch;
2922 PERL_UNUSED_ARG(search_ext);
2923 # define MAX_EXT_LEN 0
2927 * If dosearch is true and if scriptname does not contain path
2928 * delimiters, search the PATH for scriptname.
2930 * If SEARCH_EXTS is also defined, will look for each
2931 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2932 * while searching the PATH.
2934 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2935 * proceeds as follows:
2936 * If DOSISH or VMSISH:
2937 * + look for ./scriptname{,.foo,.bar}
2938 * + search the PATH for scriptname{,.foo,.bar}
2941 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2942 * this will not look in '.' if it's not in the PATH)
2947 # ifdef ALWAYS_DEFTYPES
2948 len = strlen(scriptname);
2949 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2950 int idx = 0, deftypes = 1;
2953 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch);
2956 int idx = 0, deftypes = 1;
2959 const int hasdir = (strpbrk(scriptname,":[</") != Nullch);
2961 /* The first time through, just add SEARCH_EXTS to whatever we
2962 * already have, so we can check for default file types. */
2964 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2970 if ((strlen(tmpbuf) + strlen(scriptname)
2971 + MAX_EXT_LEN) >= sizeof tmpbuf)
2972 continue; /* don't search dir with too-long name */
2973 strcat(tmpbuf, scriptname);
2977 if (strEQ(scriptname, "-"))
2979 if (dosearch) { /* Look in '.' first. */
2980 const char *cur = scriptname;
2982 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2984 if (strEQ(ext[i++],curext)) {
2985 extidx = -1; /* already has an ext */
2990 DEBUG_p(PerlIO_printf(Perl_debug_log,
2991 "Looking for %s\n",cur));
2992 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2993 && !S_ISDIR(PL_statbuf.st_mode)) {
3001 if (cur == scriptname) {
3002 len = strlen(scriptname);
3003 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3005 /* FIXME? Convert to memcpy */
3006 cur = strcpy(tmpbuf, scriptname);
3008 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3009 && strcpy(tmpbuf+len, ext[extidx++]));
3014 #ifdef MACOS_TRADITIONAL
3015 if (dosearch && !strchr(scriptname, ':') &&
3016 (s = PerlEnv_getenv("Commands")))
3018 if (dosearch && !strchr(scriptname, '/')
3020 && !strchr(scriptname, '\\')
3022 && (s = PerlEnv_getenv("PATH")))
3027 PL_bufend = s + strlen(s);
3028 while (s < PL_bufend) {
3029 #ifdef MACOS_TRADITIONAL
3030 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3034 #if defined(atarist) || defined(DOSISH)
3039 && *s != ';'; len++, s++) {
3040 if (len < sizeof tmpbuf)
3043 if (len < sizeof tmpbuf)
3045 #else /* ! (atarist || DOSISH) */
3046 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3049 #endif /* ! (atarist || DOSISH) */
3050 #endif /* MACOS_TRADITIONAL */
3053 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3054 continue; /* don't search dir with too-long name */
3055 #ifdef MACOS_TRADITIONAL
3056 if (len && tmpbuf[len - 1] != ':')
3057 tmpbuf[len++] = ':';
3060 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3061 && tmpbuf[len - 1] != '/'
3062 && tmpbuf[len - 1] != '\\'
3065 tmpbuf[len++] = '/';
3066 if (len == 2 && tmpbuf[0] == '.')
3069 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3071 (void)strcpy(tmpbuf + len, scriptname);
3075 len = strlen(tmpbuf);
3076 if (extidx > 0) /* reset after previous loop */
3080 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3081 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3082 if (S_ISDIR(PL_statbuf.st_mode)) {
3086 } while ( retval < 0 /* not there */
3087 && extidx>=0 && ext[extidx] /* try an extension? */
3088 && strcpy(tmpbuf+len, ext[extidx++])
3093 if (S_ISREG(PL_statbuf.st_mode)
3094 && cando(S_IRUSR,TRUE,&PL_statbuf)
3095 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3096 && cando(S_IXUSR,TRUE,&PL_statbuf)
3100 xfound = tmpbuf; /* bingo! */
3104 xfailed = savepv(tmpbuf);
3107 if (!xfound && !seen_dot && !xfailed &&
3108 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3109 || S_ISDIR(PL_statbuf.st_mode)))
3111 seen_dot = 1; /* Disable message. */
3113 if (flags & 1) { /* do or die? */
3114 Perl_croak(aTHX_ "Can't %s %s%s%s",
3115 (xfailed ? "execute" : "find"),
3116 (xfailed ? xfailed : scriptname),
3117 (xfailed ? "" : " on PATH"),
3118 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3120 scriptname = Nullch;
3123 scriptname = xfound;
3125 return (scriptname ? savepv(scriptname) : Nullch);
3128 #ifndef PERL_GET_CONTEXT_DEFINED
3131 Perl_get_context(void)
3134 #if defined(USE_ITHREADS)
3135 # ifdef OLD_PTHREADS_API
3137 if (pthread_getspecific(PL_thr_key, &t))
3138 Perl_croak_nocontext("panic: pthread_getspecific");
3141 # ifdef I_MACH_CTHREADS
3142 return (void*)cthread_data(cthread_self());
3144 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3153 Perl_set_context(void *t)
3156 #if defined(USE_ITHREADS)
3157 # ifdef I_MACH_CTHREADS
3158 cthread_set_data(cthread_self(), t);
3160 if (pthread_setspecific(PL_thr_key, t))
3161 Perl_croak_nocontext("panic: pthread_setspecific");
3168 #endif /* !PERL_GET_CONTEXT_DEFINED */
3170 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3179 Perl_get_op_names(pTHX)
3181 return (char **)PL_op_name;
3185 Perl_get_op_descs(pTHX)
3187 return (char **)PL_op_desc;
3191 Perl_get_no_modify(pTHX)
3193 return PL_no_modify;
3197 Perl_get_opargs(pTHX)
3199 return (U32 *)PL_opargs;
3203 Perl_get_ppaddr(pTHX)
3206 return (PPADDR_t*)PL_ppaddr;
3209 #ifndef HAS_GETENV_LEN
3211 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3213 char * const env_trans = PerlEnv_getenv(env_elem);
3215 *len = strlen(env_trans);
3222 Perl_get_vtbl(pTHX_ int vtbl_id)
3224 const MGVTBL* result;
3228 result = &PL_vtbl_sv;
3231 result = &PL_vtbl_env;
3233 case want_vtbl_envelem:
3234 result = &PL_vtbl_envelem;
3237 result = &PL_vtbl_sig;
3239 case want_vtbl_sigelem:
3240 result = &PL_vtbl_sigelem;
3242 case want_vtbl_pack:
3243 result = &PL_vtbl_pack;
3245 case want_vtbl_packelem:
3246 result = &PL_vtbl_packelem;
3248 case want_vtbl_dbline:
3249 result = &PL_vtbl_dbline;
3252 result = &PL_vtbl_isa;
3254 case want_vtbl_isaelem:
3255 result = &PL_vtbl_isaelem;
3257 case want_vtbl_arylen:
3258 result = &PL_vtbl_arylen;
3260 case want_vtbl_glob:
3261 result = &PL_vtbl_glob;
3263 case want_vtbl_mglob:
3264 result = &PL_vtbl_mglob;
3266 case want_vtbl_nkeys:
3267 result = &PL_vtbl_nkeys;
3269 case want_vtbl_taint:
3270 result = &PL_vtbl_taint;
3272 case want_vtbl_substr:
3273 result = &PL_vtbl_substr;
3276 result = &PL_vtbl_vec;
3279 result = &PL_vtbl_pos;
3282 result = &PL_vtbl_bm;
3285 result = &PL_vtbl_fm;
3287 case want_vtbl_uvar:
3288 result = &PL_vtbl_uvar;
3290 case want_vtbl_defelem:
3291 result = &PL_vtbl_defelem;
3293 case want_vtbl_regexp:
3294 result = &PL_vtbl_regexp;
3296 case want_vtbl_regdata:
3297 result = &PL_vtbl_regdata;
3299 case want_vtbl_regdatum:
3300 result = &PL_vtbl_regdatum;
3302 #ifdef USE_LOCALE_COLLATE
3303 case want_vtbl_collxfrm:
3304 result = &PL_vtbl_collxfrm;
3307 case want_vtbl_amagic:
3308 result = &PL_vtbl_amagic;
3310 case want_vtbl_amagicelem:
3311 result = &PL_vtbl_amagicelem;
3313 case want_vtbl_backref:
3314 result = &PL_vtbl_backref;
3316 case want_vtbl_utf8:
3317 result = &PL_vtbl_utf8;
3320 result = Null(MGVTBL*);
3323 return (MGVTBL*)result;
3327 Perl_my_fflush_all(pTHX)
3329 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3330 return PerlIO_flush(NULL);
3332 # if defined(HAS__FWALK)
3333 extern int fflush(FILE *);
3334 /* undocumented, unprototyped, but very useful BSDism */
3335 extern void _fwalk(int (*)(FILE *));
3339 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3341 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3342 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3344 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3345 open_max = sysconf(_SC_OPEN_MAX);
3348 open_max = FOPEN_MAX;
3351 open_max = OPEN_MAX;
3362 for (i = 0; i < open_max; i++)
3363 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3364 STDIO_STREAM_ARRAY[i]._file < open_max &&
3365 STDIO_STREAM_ARRAY[i]._flag)
3366 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3370 SETERRNO(EBADF,RMS_IFI);
3377 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3379 const char * const func =
3380 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3381 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3383 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3384 const char * const type = OP_IS_SOCKET(op)
3385 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3386 ? "socket" : "filehandle";
3387 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3389 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3390 if (ckWARN(WARN_IO)) {
3391 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3393 Perl_warner(aTHX_ packWARN(WARN_IO),
3394 "Filehandle %s opened only for %sput",
3397 Perl_warner(aTHX_ packWARN(WARN_IO),
3398 "Filehandle opened only for %sput", direction);
3405 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3407 warn_type = WARN_CLOSED;
3411 warn_type = WARN_UNOPENED;
3414 if (ckWARN(warn_type)) {
3415 if (name && *name) {
3416 Perl_warner(aTHX_ packWARN(warn_type),
3417 "%s%s on %s %s %s", func, pars, vile, type, name);
3418 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3420 aTHX_ packWARN(warn_type),
3421 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3426 Perl_warner(aTHX_ packWARN(warn_type),
3427 "%s%s on %s %s", func, pars, vile, type);
3428 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3430 aTHX_ packWARN(warn_type),
3431 "\t(Are you trying to call %s%s on dirhandle?)\n",
3440 /* in ASCII order, not that it matters */
3441 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3444 Perl_ebcdic_control(pTHX_ int ch)
3452 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3453 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3456 if (ctlp == controllablechars)
3457 return('\177'); /* DEL */
3459 return((unsigned char)(ctlp - controllablechars - 1));
3460 } else { /* Want uncontrol */
3461 if (ch == '\177' || ch == -1)
3463 else if (ch == '\157')
3465 else if (ch == '\174')
3467 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3469 else if (ch == '\155')
3471 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3472 return(controllablechars[ch+1]);
3474 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3479 /* To workaround core dumps from the uninitialised tm_zone we get the
3480 * system to give us a reasonable struct to copy. This fix means that
3481 * strftime uses the tm_zone and tm_gmtoff values returned by
3482 * localtime(time()). That should give the desired result most of the
3483 * time. But probably not always!
3485 * This does not address tzname aspects of NETaa14816.
3490 # ifndef STRUCT_TM_HASZONE
3491 # define STRUCT_TM_HASZONE
3495 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3496 # ifndef HAS_TM_TM_ZONE
3497 # define HAS_TM_TM_ZONE
3502 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3504 #ifdef HAS_TM_TM_ZONE
3506 const struct tm* my_tm;
3508 my_tm = localtime(&now);
3510 Copy(my_tm, ptm, 1, struct tm);
3512 PERL_UNUSED_ARG(ptm);
3517 * mini_mktime - normalise struct tm values without the localtime()
3518 * semantics (and overhead) of mktime().
3521 Perl_mini_mktime(pTHX_ struct tm *ptm)
3525 int month, mday, year, jday;
3526 int odd_cent, odd_year;
3528 #define DAYS_PER_YEAR 365
3529 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3530 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3531 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3532 #define SECS_PER_HOUR (60*60)
3533 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3534 /* parentheses deliberately absent on these two, otherwise they don't work */
3535 #define MONTH_TO_DAYS 153/5
3536 #define DAYS_TO_MONTH 5/153
3537 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3538 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3539 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3540 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3543 * Year/day algorithm notes:
3545 * With a suitable offset for numeric value of the month, one can find
3546 * an offset into the year by considering months to have 30.6 (153/5) days,
3547 * using integer arithmetic (i.e., with truncation). To avoid too much
3548 * messing about with leap days, we consider January and February to be
3549 * the 13th and 14th month of the previous year. After that transformation,
3550 * we need the month index we use to be high by 1 from 'normal human' usage,
3551 * so the month index values we use run from 4 through 15.
3553 * Given that, and the rules for the Gregorian calendar (leap years are those
3554 * divisible by 4 unless also divisible by 100, when they must be divisible
3555 * by 400 instead), we can simply calculate the number of days since some
3556 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3557 * the days we derive from our month index, and adding in the day of the
3558 * month. The value used here is not adjusted for the actual origin which
3559 * it normally would use (1 January A.D. 1), since we're not exposing it.
3560 * We're only building the value so we can turn around and get the
3561 * normalised values for the year, month, day-of-month, and day-of-year.
3563 * For going backward, we need to bias the value we're using so that we find
3564 * the right year value. (Basically, we don't want the contribution of
3565 * March 1st to the number to apply while deriving the year). Having done
3566 * that, we 'count up' the contribution to the year number by accounting for
3567 * full quadracenturies (400-year periods) with their extra leap days, plus
3568 * the contribution from full centuries (to avoid counting in the lost leap
3569 * days), plus the contribution from full quad-years (to count in the normal
3570 * leap days), plus the leftover contribution from any non-leap years.
3571 * At this point, if we were working with an actual leap day, we'll have 0
3572 * days left over. This is also true for March 1st, however. So, we have
3573 * to special-case that result, and (earlier) keep track of the 'odd'
3574 * century and year contributions. If we got 4 extra centuries in a qcent,
3575 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3576 * Otherwise, we add back in the earlier bias we removed (the 123 from
3577 * figuring in March 1st), find the month index (integer division by 30.6),
3578 * and the remainder is the day-of-month. We then have to convert back to
3579 * 'real' months (including fixing January and February from being 14/15 in
3580 * the previous year to being in the proper year). After that, to get
3581 * tm_yday, we work with the normalised year and get a new yearday value for
3582 * January 1st, which we subtract from the yearday value we had earlier,
3583 * representing the date we've re-built. This is done from January 1
3584 * because tm_yday is 0-origin.
3586 * Since POSIX time routines are only guaranteed to work for times since the
3587 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3588 * applies Gregorian calendar rules even to dates before the 16th century
3589 * doesn't bother me. Besides, you'd need cultural context for a given
3590 * date to know whether it was Julian or Gregorian calendar, and that's
3591 * outside the scope for this routine. Since we convert back based on the
3592 * same rules we used to build the yearday, you'll only get strange results
3593 * for input which needed normalising, or for the 'odd' century years which
3594 * were leap years in the Julian calander but not in the Gregorian one.
3595 * I can live with that.
3597 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3598 * that's still outside the scope for POSIX time manipulation, so I don't
3602 year = 1900 + ptm->tm_year;
3603 month = ptm->tm_mon;
3604 mday = ptm->tm_mday;
3605 /* allow given yday with no month & mday to dominate the result */
3606 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3609 jday = 1 + ptm->tm_yday;
3618 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3619 yearday += month*MONTH_TO_DAYS + mday + jday;
3621 * Note that we don't know when leap-seconds were or will be,
3622 * so we have to trust the user if we get something which looks
3623 * like a sensible leap-second. Wild values for seconds will
3624 * be rationalised, however.
3626 if ((unsigned) ptm->tm_sec <= 60) {
3633 secs += 60 * ptm->tm_min;
3634 secs += SECS_PER_HOUR * ptm->tm_hour;
3636 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3637 /* got negative remainder, but need positive time */
3638 /* back off an extra day to compensate */
3639 yearday += (secs/SECS_PER_DAY)-1;
3640 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3643 yearday += (secs/SECS_PER_DAY);
3644 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3647 else if (secs >= SECS_PER_DAY) {
3648 yearday += (secs/SECS_PER_DAY);
3649 secs %= SECS_PER_DAY;
3651 ptm->tm_hour = secs/SECS_PER_HOUR;
3652 secs %= SECS_PER_HOUR;
3653 ptm->tm_min = secs/60;
3655 ptm->tm_sec += secs;
3656 /* done with time of day effects */
3658 * The algorithm for yearday has (so far) left it high by 428.
3659 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3660 * bias it by 123 while trying to figure out what year it
3661 * really represents. Even with this tweak, the reverse
3662 * translation fails for years before A.D. 0001.
3663 * It would still fail for Feb 29, but we catch that one below.
3665 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3666 yearday -= YEAR_ADJUST;
3667 year = (yearday / DAYS_PER_QCENT) * 400;
3668 yearday %= DAYS_PER_QCENT;
3669 odd_cent = yearday / DAYS_PER_CENT;
3670 year += odd_cent * 100;
3671 yearday %= DAYS_PER_CENT;
3672 year += (yearday / DAYS_PER_QYEAR) * 4;
3673 yearday %= DAYS_PER_QYEAR;
3674 odd_year = yearday / DAYS_PER_YEAR;
3676 yearday %= DAYS_PER_YEAR;
3677 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3682 yearday += YEAR_ADJUST; /* recover March 1st crock */
3683 month = yearday*DAYS_TO_MONTH;
3684 yearday -= month*MONTH_TO_DAYS;
3685 /* recover other leap-year adjustment */
3694 ptm->tm_year = year - 1900;
3696 ptm->tm_mday = yearday;
3697 ptm->tm_mon = month;
3701 ptm->tm_mon = month - 1;
3703 /* re-build yearday based on Jan 1 to get tm_yday */
3705 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3706 yearday += 14*MONTH_TO_DAYS + 1;
3707 ptm->tm_yday = jday - yearday;
3708 /* fix tm_wday if not overridden by caller */
3709 if ((unsigned)ptm->tm_wday > 6)
3710 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3714 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)
3722 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3725 mytm.tm_hour = hour;
3726 mytm.tm_mday = mday;
3728 mytm.tm_year = year;
3729 mytm.tm_wday = wday;
3730 mytm.tm_yday = yday;
3731 mytm.tm_isdst = isdst;
3733 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3734 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3739 #ifdef HAS_TM_TM_GMTOFF
3740 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3742 #ifdef HAS_TM_TM_ZONE
3743 mytm.tm_zone = mytm2.tm_zone;
3748 Newx(buf, buflen, char);
3749 len = strftime(buf, buflen, fmt, &mytm);
3751 ** The following is needed to handle to the situation where
3752 ** tmpbuf overflows. Basically we want to allocate a buffer
3753 ** and try repeatedly. The reason why it is so complicated
3754 ** is that getting a return value of 0 from strftime can indicate
3755 ** one of the following:
3756 ** 1. buffer overflowed,
3757 ** 2. illegal conversion specifier, or
3758 ** 3. the format string specifies nothing to be returned(not
3759 ** an error). This could be because format is an empty string
3760 ** or it specifies %p that yields an empty string in some locale.
3761 ** If there is a better way to make it portable, go ahead by
3764 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3767 /* Possibly buf overflowed - try again with a bigger buf */
3768 const int fmtlen = strlen(fmt);
3769 const int bufsize = fmtlen + buflen;
3771 Newx(buf, bufsize, char);
3773 buflen = strftime(buf, bufsize, fmt, &mytm);
3774 if (buflen > 0 && buflen < bufsize)
3776 /* heuristic to prevent out-of-memory errors */
3777 if (bufsize > 100*fmtlen) {
3782 Renew(buf, bufsize*2, char);
3787 Perl_croak(aTHX_ "panic: no strftime");
3793 #define SV_CWD_RETURN_UNDEF \
3794 sv_setsv(sv, &PL_sv_undef); \
3797 #define SV_CWD_ISDOT(dp) \
3798 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3799 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3802 =head1 Miscellaneous Functions
3804 =for apidoc getcwd_sv
3806 Fill the sv with current working directory
3811 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3812 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3813 * getcwd(3) if available
3814 * Comments from the orignal:
3815 * This is a faster version of getcwd. It's also more dangerous
3816 * because you might chdir out of a directory that you can't chdir
3820 Perl_getcwd_sv(pTHX_ register SV *sv)
3824 #ifndef INCOMPLETE_TAINTS
3830 char buf[MAXPATHLEN];
3832 /* Some getcwd()s automatically allocate a buffer of the given
3833 * size from the heap if they are given a NULL buffer pointer.
3834 * The problem is that this behaviour is not portable. */
3835 if (getcwd(buf, sizeof(buf) - 1)) {
3840 sv_setsv(sv, &PL_sv_undef);
3848 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3852 SvUPGRADE(sv, SVt_PV);
3854 if (PerlLIO_lstat(".", &statbuf) < 0) {
3855 SV_CWD_RETURN_UNDEF;
3858 orig_cdev = statbuf.st_dev;
3859 orig_cino = statbuf.st_ino;
3868 if (PerlDir_chdir("..") < 0) {
3869 SV_CWD_RETURN_UNDEF;
3871 if (PerlLIO_stat(".", &statbuf) < 0) {
3872 SV_CWD_RETURN_UNDEF;
3875 cdev = statbuf.st_dev;
3876 cino = statbuf.st_ino;
3878 if (odev == cdev && oino == cino) {
3881 if (!(dir = PerlDir_open("."))) {
3882 SV_CWD_RETURN_UNDEF;
3885 while ((dp = PerlDir_read(dir)) != NULL) {
3887 const int namelen = dp->d_namlen;
3889 const int namelen = strlen(dp->d_name);
3892 if (SV_CWD_ISDOT(dp)) {
3896 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3897 SV_CWD_RETURN_UNDEF;
3900 tdev = statbuf.st_dev;
3901 tino = statbuf.st_ino;
3902 if (tino == oino && tdev == odev) {
3908 SV_CWD_RETURN_UNDEF;
3911 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3912 SV_CWD_RETURN_UNDEF;
3915 SvGROW(sv, pathlen + namelen + 1);
3919 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3922 /* prepend current directory to the front */
3924 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3925 pathlen += (namelen + 1);
3927 #ifdef VOID_CLOSEDIR
3930 if (PerlDir_close(dir) < 0) {
3931 SV_CWD_RETURN_UNDEF;
3937 SvCUR_set(sv, pathlen);
3941 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3942 SV_CWD_RETURN_UNDEF;
3945 if (PerlLIO_stat(".", &statbuf) < 0) {
3946 SV_CWD_RETURN_UNDEF;
3949 cdev = statbuf.st_dev;
3950 cino = statbuf.st_ino;
3952 if (cdev != orig_cdev || cino != orig_cino) {
3953 Perl_croak(aTHX_ "Unstable directory path, "
3954 "current directory changed unexpectedly");
3966 =for apidoc scan_version
3968 Returns a pointer to the next character after the parsed
3969 version string, as well as upgrading the passed in SV to
3972 Function must be called with an already existing SV like
3975 s = scan_version(s,SV *sv, bool qv);
3977 Performs some preprocessing to the string to ensure that
3978 it has the correct characteristics of a version. Flags the
3979 object if it contains an underscore (which denotes this
3980 is a alpha version). The boolean qv denotes that the version
3981 should be interpreted as if it had multiple decimals, even if
3988 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
3996 AV * const av = newAV();
3997 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3998 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4000 #ifndef NODEFAULT_SHAREKEYS
4001 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4004 while (isSPACE(*s)) /* leading whitespace is OK */
4008 s++; /* get past 'v' */
4009 qv = 1; /* force quoted version processing */
4012 start = last = pos = s;
4014 /* pre-scan the input string to check for decimals/underbars */
4015 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4020 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4024 else if ( *pos == '_' )
4027 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4029 width = pos - last - 1; /* natural width of sub-version */
4034 if ( saw_period > 1 )
4035 qv = 1; /* force quoted version processing */
4040 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4042 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4043 if ( !qv && width < 3 )
4044 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4046 while (isDIGIT(*pos))
4048 if (!isALPHA(*pos)) {
4054 /* this is atoi() that delimits on underscores */
4055 const char *end = pos;
4059 /* the following if() will only be true after the decimal
4060 * point of a version originally created with a bare
4061 * floating point number, i.e. not quoted in any way
4063 if ( !qv && s > start && saw_period == 1 ) {
4067 rev += (*s - '0') * mult;
4069 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4070 Perl_croak(aTHX_ "Integer overflow in version");
4077 while (--end >= s) {
4079 rev += (*end - '0') * mult;
4081 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4082 Perl_croak(aTHX_ "Integer overflow in version");
4087 /* Append revision */
4088 av_push(av, newSViv(rev));
4089 if ( *pos == '.' && isDIGIT(pos[1]) )
4091 else if ( *pos == '_' && isDIGIT(pos[1]) )
4093 else if ( isDIGIT(*pos) )
4100 while ( isDIGIT(*pos) )
4105 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4113 if ( qv ) { /* quoted versions always get at least three terms*/
4114 I32 len = av_len(av);
4115 /* This for loop appears to trigger a compiler bug on OS X, as it
4116 loops infinitely. Yes, len is negative. No, it makes no sense.
4117 Compiler in question is:
4118 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4119 for ( len = 2 - len; len > 0; len-- )
4120 av_push((AV *)sv, newSViv(0));
4124 av_push(av, newSViv(0));
4127 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4128 av_push(av, newSViv(0));
4130 /* And finally, store the AV in the hash */
4131 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4136 =for apidoc new_version
4138 Returns a new version object based on the passed in SV:
4140 SV *sv = new_version(SV *ver);
4142 Does not alter the passed in ver SV. See "upg_version" if you
4143 want to upgrade the SV.
4149 Perl_new_version(pTHX_ SV *ver)
4152 SV * const rv = newSV(0);
4153 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4156 AV * const av = newAV();
4158 /* This will get reblessed later if a derived class*/
4159 SV * const hv = newSVrv(rv, "version");
4160 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4161 #ifndef NODEFAULT_SHAREKEYS
4162 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4168 /* Begin copying all of the elements */
4169 if ( hv_exists((HV *)ver, "qv", 2) )
4170 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4172 if ( hv_exists((HV *)ver, "alpha", 5) )
4173 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4175 if ( hv_exists((HV*)ver, "width", 5 ) )
4177 const I32 width = SvIV(*hv_fetch((HV*)ver, "width", 5, FALSE));
4178 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4181 sav = (AV *)SvRV(*hv_fetch((HV*)ver, "version", 7, FALSE));
4182 /* This will get reblessed later if a derived class*/
4183 for ( key = 0; key <= av_len(sav); key++ )
4185 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4186 av_push(av, newSViv(rev));
4189 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4193 if ( SvVOK(ver) ) { /* already a v-string */
4194 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4195 const STRLEN len = mg->mg_len;
4196 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4197 sv_setpvn(rv,version,len);
4202 sv_setsv(rv,ver); /* make a duplicate */
4211 =for apidoc upg_version
4213 In-place upgrade of the supplied SV to a version object.
4215 SV *sv = upg_version(SV *sv);
4217 Returns a pointer to the upgraded SV.
4223 Perl_upg_version(pTHX_ SV *ver)
4228 if ( SvNOK(ver) ) /* may get too much accuracy */
4231 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4232 version = savepvn(tbuf, len);
4235 else if ( SvVOK(ver) ) { /* already a v-string */
4236 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4237 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4241 else /* must be a string or something like a string */
4243 version = savepv(SvPV_nolen(ver));
4245 (void)scan_version(version, ver, qv);
4253 Validates that the SV contains a valid version object.
4255 bool vverify(SV *vobj);
4257 Note that it only confirms the bare minimum structure (so as not to get
4258 confused by derived classes which may contain additional hash entries):
4262 =item * The SV contains a [reference to a] hash
4264 =item * The hash contains a "version" key
4266 =item * The "version" key has [a reference to] an AV as its value
4274 Perl_vverify(pTHX_ SV *vs)
4280 /* see if the appropriate elements exist */
4281 if ( SvTYPE(vs) == SVt_PVHV
4282 && hv_exists((HV*)vs, "version", 7)
4283 && (sv = SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)))
4284 && SvTYPE(sv) == SVt_PVAV )
4293 Accepts a version object and returns the normalized floating
4294 point representation. Call like:
4298 NOTE: you can pass either the object directly or the SV
4299 contained within the RV.
4305 Perl_vnumify(pTHX_ SV *vs)
4310 SV * const sv = newSV(0);
4316 Perl_croak(aTHX_ "Invalid version object");
4318 /* see if various flags exist */
4319 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4321 if ( hv_exists((HV*)vs, "width", 5 ) )
4322 width = SvIV(*hv_fetch((HV*)vs, "width", 5, FALSE));
4327 /* attempt to retrieve the version array */
4328 if ( !(av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)) ) ) {
4340 digit = SvIV(*av_fetch(av, 0, 0));
4341 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4342 for ( i = 1 ; i < len ; i++ )
4344 digit = SvIV(*av_fetch(av, i, 0));
4346 const int denom = (width == 2 ? 10 : 100);
4347 const div_t term = div((int)PERL_ABS(digit),denom);
4348 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4351 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4357 digit = SvIV(*av_fetch(av, len, 0));
4358 if ( alpha && width == 3 ) /* alpha version */
4360 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4364 sv_catpvs(sv, "000");
4372 Accepts a version object and returns the normalized string
4373 representation. Call like:
4377 NOTE: you can pass either the object directly or the SV
4378 contained within the RV.
4384 Perl_vnormal(pTHX_ SV *vs)
4388 SV * const sv = newSV(0);
4394 Perl_croak(aTHX_ "Invalid version object");
4396 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4398 av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE));
4406 digit = SvIV(*av_fetch(av, 0, 0));
4407 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4408 for ( i = 1 ; i < len ; i++ ) {
4409 digit = SvIV(*av_fetch(av, i, 0));
4410 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4415 /* handle last digit specially */
4416 digit = SvIV(*av_fetch(av, len, 0));
4418 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4420 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4423 if ( len <= 2 ) { /* short version, must be at least three */
4424 for ( len = 2 - len; len != 0; len-- )
4431 =for apidoc vstringify
4433 In order to maintain maximum compatibility with earlier versions
4434 of Perl, this function will return either the floating point
4435 notation or the multiple dotted notation, depending on whether
4436 the original version contained 1 or more dots, respectively
4442 Perl_vstringify(pTHX_ SV *vs)
4448 Perl_croak(aTHX_ "Invalid version object");
4450 if ( hv_exists((HV *)vs, "qv", 2) )
4459 Version object aware cmp. Both operands must already have been
4460 converted into version objects.
4466 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4469 bool lalpha = FALSE;
4470 bool ralpha = FALSE;
4479 if ( !vverify(lhv) )
4480 Perl_croak(aTHX_ "Invalid version object");
4482 if ( !vverify(rhv) )
4483 Perl_croak(aTHX_ "Invalid version object");
4485 /* get the left hand term */
4486 lav = (AV *)SvRV(*hv_fetch((HV*)lhv, "version", 7, FALSE));
4487 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4490 /* and the right hand term */
4491 rav = (AV *)SvRV(*hv_fetch((HV*)rhv, "version", 7, FALSE));
4492 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4500 while ( i <= m && retval == 0 )
4502 left = SvIV(*av_fetch(lav,i,0));
4503 right = SvIV(*av_fetch(rav,i,0));
4511 /* tiebreaker for alpha with identical terms */
4512 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4514 if ( lalpha && !ralpha )
4518 else if ( ralpha && !lalpha)
4524 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4528 while ( i <= r && retval == 0 )
4530 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4531 retval = -1; /* not a match after all */
4537 while ( i <= l && retval == 0 )
4539 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4540 retval = +1; /* not a match after all */
4548 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4549 # define EMULATE_SOCKETPAIR_UDP
4552 #ifdef EMULATE_SOCKETPAIR_UDP
4554 S_socketpair_udp (int fd[2]) {
4556 /* Fake a datagram socketpair using UDP to localhost. */
4557 int sockets[2] = {-1, -1};
4558 struct sockaddr_in addresses[2];
4560 Sock_size_t size = sizeof(struct sockaddr_in);
4561 unsigned short port;
4564 memset(&addresses, 0, sizeof(addresses));
4567 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4568 if (sockets[i] == -1)
4569 goto tidy_up_and_fail;
4571 addresses[i].sin_family = AF_INET;
4572 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4573 addresses[i].sin_port = 0; /* kernel choses port. */
4574 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4575 sizeof(struct sockaddr_in)) == -1)
4576 goto tidy_up_and_fail;
4579 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4580 for each connect the other socket to it. */
4583 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4585 goto tidy_up_and_fail;
4586 if (size != sizeof(struct sockaddr_in))
4587 goto abort_tidy_up_and_fail;
4588 /* !1 is 0, !0 is 1 */
4589 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4590 sizeof(struct sockaddr_in)) == -1)
4591 goto tidy_up_and_fail;
4594 /* Now we have 2 sockets connected to each other. I don't trust some other
4595 process not to have already sent a packet to us (by random) so send
4596 a packet from each to the other. */
4599 /* I'm going to send my own port number. As a short.
4600 (Who knows if someone somewhere has sin_port as a bitfield and needs
4601 this routine. (I'm assuming crays have socketpair)) */
4602 port = addresses[i].sin_port;
4603 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4604 if (got != sizeof(port)) {
4606 goto tidy_up_and_fail;
4607 goto abort_tidy_up_and_fail;
4611 /* Packets sent. I don't trust them to have arrived though.
4612 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4613 connect to localhost will use a second kernel thread. In 2.6 the
4614 first thread running the connect() returns before the second completes,
4615 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4616 returns 0. Poor programs have tripped up. One poor program's authors'
4617 had a 50-1 reverse stock split. Not sure how connected these were.)
4618 So I don't trust someone not to have an unpredictable UDP stack.
4622 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4623 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4627 FD_SET(sockets[0], &rset);
4628 FD_SET(sockets[1], &rset);
4630 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4631 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4632 || !FD_ISSET(sockets[1], &rset)) {
4633 /* I hope this is portable and appropriate. */
4635 goto tidy_up_and_fail;
4636 goto abort_tidy_up_and_fail;
4640 /* And the paranoia department even now doesn't trust it to have arrive
4641 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4643 struct sockaddr_in readfrom;
4644 unsigned short buffer[2];
4649 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4650 sizeof(buffer), MSG_DONTWAIT,
4651 (struct sockaddr *) &readfrom, &size);
4653 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4655 (struct sockaddr *) &readfrom, &size);
4659 goto tidy_up_and_fail;
4660 if (got != sizeof(port)
4661 || size != sizeof(struct sockaddr_in)
4662 /* Check other socket sent us its port. */
4663 || buffer[0] != (unsigned short) addresses[!i].sin_port
4664 /* Check kernel says we got the datagram from that socket */
4665 || readfrom.sin_family != addresses[!i].sin_family
4666 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4667 || readfrom.sin_port != addresses[!i].sin_port)
4668 goto abort_tidy_up_and_fail;
4671 /* My caller (my_socketpair) has validated that this is non-NULL */
4674 /* I hereby declare this connection open. May God bless all who cross
4678 abort_tidy_up_and_fail:
4679 errno = ECONNABORTED;
4682 const int save_errno = errno;
4683 if (sockets[0] != -1)
4684 PerlLIO_close(sockets[0]);
4685 if (sockets[1] != -1)
4686 PerlLIO_close(sockets[1]);
4691 #endif /* EMULATE_SOCKETPAIR_UDP */
4693 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4695 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4696 /* Stevens says that family must be AF_LOCAL, protocol 0.
4697 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4702 struct sockaddr_in listen_addr;
4703 struct sockaddr_in connect_addr;
4708 || family != AF_UNIX
4711 errno = EAFNOSUPPORT;
4719 #ifdef EMULATE_SOCKETPAIR_UDP
4720 if (type == SOCK_DGRAM)
4721 return S_socketpair_udp(fd);
4724 listener = PerlSock_socket(AF_INET, type, 0);
4727 memset(&listen_addr, 0, sizeof(listen_addr));
4728 listen_addr.sin_family = AF_INET;
4729 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4730 listen_addr.sin_port = 0; /* kernel choses port. */
4731 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4732 sizeof(listen_addr)) == -1)
4733 goto tidy_up_and_fail;
4734 if (PerlSock_listen(listener, 1) == -1)
4735 goto tidy_up_and_fail;
4737 connector = PerlSock_socket(AF_INET, type, 0);
4738 if (connector == -1)
4739 goto tidy_up_and_fail;
4740 /* We want to find out the port number to connect to. */
4741 size = sizeof(connect_addr);
4742 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4744 goto tidy_up_and_fail;
4745 if (size != sizeof(connect_addr))
4746 goto abort_tidy_up_and_fail;
4747 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4748 sizeof(connect_addr)) == -1)
4749 goto tidy_up_and_fail;
4751 size = sizeof(listen_addr);
4752 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4755 goto tidy_up_and_fail;
4756 if (size != sizeof(listen_addr))
4757 goto abort_tidy_up_and_fail;
4758 PerlLIO_close(listener);
4759 /* Now check we are talking to ourself by matching port and host on the
4761 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4763 goto tidy_up_and_fail;
4764 if (size != sizeof(connect_addr)
4765 || listen_addr.sin_family != connect_addr.sin_family
4766 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4767 || listen_addr.sin_port != connect_addr.sin_port) {
4768 goto abort_tidy_up_and_fail;
4774 abort_tidy_up_and_fail:
4776 errno = ECONNABORTED; /* This would be the standard thing to do. */
4778 # ifdef ECONNREFUSED
4779 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4781 errno = ETIMEDOUT; /* Desperation time. */
4786 const int save_errno = errno;
4788 PerlLIO_close(listener);
4789 if (connector != -1)
4790 PerlLIO_close(connector);
4792 PerlLIO_close(acceptor);
4798 /* In any case have a stub so that there's code corresponding
4799 * to the my_socketpair in global.sym. */
4801 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4802 #ifdef HAS_SOCKETPAIR
4803 return socketpair(family, type, protocol, fd);
4812 =for apidoc sv_nosharing
4814 Dummy routine which "shares" an SV when there is no sharing module present.
4815 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4816 Exists to avoid test for a NULL function pointer and because it could
4817 potentially warn under some level of strict-ness.
4823 Perl_sv_nosharing(pTHX_ SV *sv)
4825 PERL_UNUSED_ARG(sv);
4829 Perl_parse_unicode_opts(pTHX_ const char **popt)
4831 const char *p = *popt;
4836 opt = (U32) atoi(p);
4837 while (isDIGIT(*p)) p++;
4838 if (*p && *p != '\n' && *p != '\r')
4839 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4844 case PERL_UNICODE_STDIN:
4845 opt |= PERL_UNICODE_STDIN_FLAG; break;
4846 case PERL_UNICODE_STDOUT:
4847 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4848 case PERL_UNICODE_STDERR:
4849 opt |= PERL_UNICODE_STDERR_FLAG; break;
4850 case PERL_UNICODE_STD:
4851 opt |= PERL_UNICODE_STD_FLAG; break;
4852 case PERL_UNICODE_IN:
4853 opt |= PERL_UNICODE_IN_FLAG; break;
4854 case PERL_UNICODE_OUT:
4855 opt |= PERL_UNICODE_OUT_FLAG; break;
4856 case PERL_UNICODE_INOUT:
4857 opt |= PERL_UNICODE_INOUT_FLAG; break;
4858 case PERL_UNICODE_LOCALE:
4859 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4860 case PERL_UNICODE_ARGV:
4861 opt |= PERL_UNICODE_ARGV_FLAG; break;
4863 if (*p != '\n' && *p != '\r')
4865 "Unknown Unicode option letter '%c'", *p);
4871 opt = PERL_UNICODE_DEFAULT_FLAGS;
4873 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4874 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4875 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4887 * This is really just a quick hack which grabs various garbage
4888 * values. It really should be a real hash algorithm which
4889 * spreads the effect of every input bit onto every output bit,
4890 * if someone who knows about such things would bother to write it.
4891 * Might be a good idea to add that function to CORE as well.
4892 * No numbers below come from careful analysis or anything here,
4893 * except they are primes and SEED_C1 > 1E6 to get a full-width
4894 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4895 * probably be bigger too.
4898 # define SEED_C1 1000003
4899 #define SEED_C4 73819
4901 # define SEED_C1 25747
4902 #define SEED_C4 20639
4906 #define SEED_C5 26107
4908 #ifndef PERL_NO_DEV_RANDOM
4913 # include <starlet.h>
4914 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4915 * in 100-ns units, typically incremented ever 10 ms. */
4916 unsigned int when[2];
4918 # ifdef HAS_GETTIMEOFDAY
4919 struct timeval when;
4925 /* This test is an escape hatch, this symbol isn't set by Configure. */
4926 #ifndef PERL_NO_DEV_RANDOM
4927 #ifndef PERL_RANDOM_DEVICE
4928 /* /dev/random isn't used by default because reads from it will block
4929 * if there isn't enough entropy available. You can compile with
4930 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4931 * is enough real entropy to fill the seed. */
4932 # define PERL_RANDOM_DEVICE "/dev/urandom"
4934 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4936 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4945 _ckvmssts(sys$gettim(when));
4946 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4948 # ifdef HAS_GETTIMEOFDAY
4949 PerlProc_gettimeofday(&when,NULL);
4950 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4953 u = (U32)SEED_C1 * when;
4956 u += SEED_C3 * (U32)PerlProc_getpid();
4957 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4958 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4959 u += SEED_C5 * (U32)PTR2UV(&when);
4965 Perl_get_hash_seed(pTHX)
4968 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4972 while (isSPACE(*s)) s++;
4973 if (s && isDIGIT(*s))
4974 myseed = (UV)Atoul(s);
4976 #ifdef USE_HASH_SEED_EXPLICIT
4980 /* Compute a random seed */
4981 (void)seedDrand01((Rand_seed_t)seed());
4982 myseed = (UV)(Drand01() * (NV)UV_MAX);
4983 #if RANDBITS < (UVSIZE * 8)
4984 /* Since there are not enough randbits to to reach all
4985 * the bits of a UV, the low bits might need extra
4986 * help. Sum in another random number that will
4987 * fill in the low bits. */
4989 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4990 #endif /* RANDBITS < (UVSIZE * 8) */
4991 if (myseed == 0) { /* Superparanoia. */
4992 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4994 Perl_croak(aTHX_ "Your random numbers are not that random");
4997 PL_rehash_seed_set = TRUE;
5004 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5006 const char * const stashpv = CopSTASHPV(c);
5007 const char * const name = HvNAME_get(hv);
5009 if (stashpv == name)
5011 if (stashpv && name)
5012 if (strEQ(stashpv, name))
5019 #ifdef PERL_GLOBAL_STRUCT
5022 Perl_init_global_struct(pTHX)
5024 struct perl_vars *plvarsp = NULL;
5025 #ifdef PERL_GLOBAL_STRUCT
5026 # define PERL_GLOBAL_STRUCT_INIT
5027 # include "opcode.h" /* the ppaddr and check */
5028 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5029 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5030 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5031 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5032 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5036 plvarsp = PL_VarsPtr;
5037 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5043 # define PERLVAR(var,type) /**/
5044 # define PERLVARA(var,n,type) /**/
5045 # define PERLVARI(var,type,init) plvarsp->var = init;
5046 # define PERLVARIC(var,type,init) plvarsp->var = init;
5047 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5048 # include "perlvars.h"
5054 # ifdef PERL_GLOBAL_STRUCT
5055 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5056 if (!plvarsp->Gppaddr)
5058 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5059 if (!plvarsp->Gcheck)
5061 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5062 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5064 # ifdef PERL_SET_VARS
5065 PERL_SET_VARS(plvarsp);
5067 # undef PERL_GLOBAL_STRUCT_INIT
5072 #endif /* PERL_GLOBAL_STRUCT */
5074 #ifdef PERL_GLOBAL_STRUCT
5077 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5079 #ifdef PERL_GLOBAL_STRUCT
5080 # ifdef PERL_UNSET_VARS
5081 PERL_UNSET_VARS(plvarsp);
5083 free(plvarsp->Gppaddr);
5084 free(plvarsp->Gcheck);
5085 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5091 #endif /* PERL_GLOBAL_STRUCT */
5095 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5098 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)
5100 #ifdef PERL_MEM_LOG_STDERR
5101 /* We can't use PerlIO for obvious reasons. */
5102 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5103 const STRLEN len = my_sprintf(buf,
5104 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5105 " %s = %"IVdf": %"UVxf"\n",
5106 filename, linenumber, funcname, n, typesize,
5107 typename, n * typesize, PTR2UV(newalloc));
5108 PerlLIO_write(2, buf, len);
5114 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)
5116 #ifdef PERL_MEM_LOG_STDERR
5117 /* We can't use PerlIO for obvious reasons. */
5118 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5119 const STRLEN len = my_sprintf(buf, "realloc: %s:%d:%s: %"IVdf" %"UVuf
5120 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5121 filename, linenumber, funcname, n, typesize,
5122 typename, n * typesize, PTR2UV(oldalloc),
5124 PerlLIO_write(2, buf, len);
5130 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5132 #ifdef PERL_MEM_LOG_STDERR
5133 /* We can't use PerlIO for obvious reasons. */
5134 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5135 const STRLEN len = my_sprintf(buf, "free: %s:%d:%s: %"UVxf"\n",
5136 filename, linenumber, funcname,
5138 PerlLIO_write(2, buf, len);
5143 #endif /* PERL_MEM_LOG */
5146 =for apidoc my_sprintf
5148 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5149 the length of the string written to the buffer. Only rare pre-ANSI systems
5150 need the wrapper function - usually this is a direct call to C<sprintf>.
5154 #ifndef SPRINTF_RETURNS_STRLEN
5156 Perl_my_sprintf(char *buffer, const char* pat, ...)
5159 va_start(args, pat);
5160 vsprintf(buffer, pat, args);
5162 return strlen(buffer);
5167 Perl_my_clearenv(pTHX)
5170 #if ! defined(PERL_MICRO)
5171 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5173 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5174 # if defined(USE_ENVIRON_ARRAY)
5175 # if defined(USE_ITHREADS)
5176 /* only the parent thread can clobber the process environment */
5177 if (PL_curinterp == aTHX)
5178 # endif /* USE_ITHREADS */
5180 # if ! defined(PERL_USE_SAFE_PUTENV)
5181 if ( !PL_use_safe_putenv) {
5183 if (environ == PL_origenviron)
5184 environ = (char**)safesysmalloc(sizeof(char*));
5186 for (i = 0; environ[i]; i++)
5187 (void)safesysfree(environ[i]);
5190 # else /* PERL_USE_SAFE_PUTENV */
5191 # if defined(HAS_CLEARENV)
5193 # elif defined(HAS_UNSETENV)
5194 int bsiz = 80; /* Most envvar names will be shorter than this. */
5195 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
5196 while (*environ != NULL) {
5197 char *e = strchr(*environ, '=');
5198 int l = e ? e - *environ : strlen(*environ);
5200 (void)safesysfree(buf);
5202 buf = (char*)safesysmalloc(bsiz * sizeof(char));
5204 strncpy(buf, *environ, l);
5206 (void)unsetenv(buf);
5208 (void)safesysfree(buf);
5209 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5210 /* Just null environ and accept the leakage. */
5212 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5213 # endif /* ! PERL_USE_SAFE_PUTENV */
5215 # endif /* USE_ENVIRON_ARRAY */
5216 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5217 #endif /* PERL_MICRO */
5220 #ifdef PERL_IMPLICIT_CONTEXT
5222 /* implements the MY_CXT_INIT macro. The first time a module is loaded,
5223 the global PL_my_cxt_index is incremented, and that value is assigned to
5224 that module's static my_cxt_index (who's address is passed as an arg).
5225 Then, for each interpreter this function is called for, it makes sure a
5226 void* slot is available to hang the static data off, by allocating or
5227 extending the interpreter's PL_my_cxt_list array */
5230 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5235 /* this module hasn't been allocated an index yet */
5236 MUTEX_LOCK(&PL_my_ctx_mutex);
5237 *index = PL_my_cxt_index++;
5238 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5241 /* make sure the array is big enough */
5242 if (PL_my_cxt_size <= *index) {
5243 if (PL_my_cxt_size) {
5244 while (PL_my_cxt_size <= *index)
5245 PL_my_cxt_size *= 2;
5246 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5249 PL_my_cxt_size = 16;
5250 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5253 /* newSV() allocates one more than needed */
5254 p = (void*)SvPVX(newSV(size-1));
5255 PL_my_cxt_list[*index] = p;
5256 Zero(p, size, char);
5263 * c-indentation-style: bsd
5265 * indent-tabs-mode: t
5268 * ex: set ts=8 sts=4 sw=4 noet: