3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 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.
63 /* Can't use PerlIO to write as it allocates memory */
64 PerlLIO_write(PerlIO_fileno(Perl_error_log),
65 PL_no_mem, strlen(PL_no_mem));
67 NORETURN_FUNCTION_END;
70 /* paranoid version of system's malloc() */
73 Perl_safesysmalloc(MEM_SIZE size)
79 PerlIO_printf(Perl_error_log,
80 "Allocation too large: %lx\n", size) FLUSH;
83 #endif /* HAS_64K_LIMIT */
84 #ifdef PERL_TRACK_MEMPOOL
89 Perl_croak_nocontext("panic: malloc");
91 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
92 PERL_ALLOC_CHECK(ptr);
93 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
95 #ifdef PERL_TRACK_MEMPOOL
96 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
98 ((struct perl_memory_debug_header *)ptr)->size = size;
99 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
101 ptr = (Malloc_t)((char*)ptr+sTHX);
108 return write_no_mem();
113 /* paranoid version of system's realloc() */
116 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
120 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
121 Malloc_t PerlMem_realloc();
122 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
126 PerlIO_printf(Perl_error_log,
127 "Reallocation too large: %lx\n", size) FLUSH;
130 #endif /* HAS_64K_LIMIT */
137 return safesysmalloc(size);
138 #ifdef PERL_TRACK_MEMPOOL
139 where = (Malloc_t)((char*)where-sTHX);
141 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
142 /* int *nowhere = NULL; *nowhere = 0; */
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)
185 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
188 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
190 #ifdef PERL_TRACK_MEMPOOL
191 where = (Malloc_t)((char*)where-sTHX);
192 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
193 /* int *nowhere = NULL; *nowhere = 0; */
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_ register const char *big, register const char *bigend, const char *little, const char *lend)
356 register const I32 first = *little;
357 register const char * const littleend = lend;
359 if (little >= littleend)
361 if (bigend - big < littleend - little)
363 bigend -= littleend - little++;
364 while (big <= bigend) {
365 register const char *s, *x;
368 for (x=big,s=little; s < littleend; /**/ ) {
377 return (char*)(big-1);
382 /* reverse of the above--find last substring */
385 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
387 register const char *bigbeg;
388 register const I32 first = *little;
389 register const char * const littleend = lend;
391 if (little >= littleend)
392 return (char*)bigend;
394 big = bigend - (littleend - little++);
395 while (big >= bigbeg) {
396 register const char *s, *x;
399 for (x=big+2,s=little; s < littleend; /**/ ) {
408 return (char*)(big+1);
413 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
415 /* As a space optimization, we do not compile tables for strings of length
416 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
417 special-cased in fbm_instr().
419 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
422 =head1 Miscellaneous Functions
424 =for apidoc fbm_compile
426 Analyses the string in order to make fast searches on it using fbm_instr()
427 -- the Boyer-Moore algorithm.
433 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
435 register const U8 *s;
441 if (flags & FBMcf_TAIL) {
442 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
443 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
444 if (mg && mg->mg_len >= 0)
447 s = (U8*)SvPV_force_mutable(sv, len);
448 SvUPGRADE(sv, SVt_PVBM);
449 if (len == 0) /* TAIL might be on a zero-length string. */
452 const unsigned char *sb;
453 const U8 mlen = (len>255) ? 255 : (U8)len;
456 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
457 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
458 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
459 memset((void*)table, mlen, 256);
460 table[-1] = (U8)flags;
462 sb = s - mlen + 1; /* first char (maybe) */
464 if (table[*s] == mlen)
469 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
472 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
473 for (i = 0; i < len; i++) {
474 if (PL_freq[s[i]] < frequency) {
476 frequency = PL_freq[s[i]];
479 BmRARE(sv) = s[rarest];
480 BmPREVIOUS(sv) = (U16)rarest;
481 BmUSEFUL(sv) = 100; /* Initial value */
482 if (flags & FBMcf_TAIL)
484 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
485 BmRARE(sv),BmPREVIOUS(sv)));
488 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
489 /* If SvTAIL is actually due to \Z or \z, this gives false positives
493 =for apidoc fbm_instr
495 Returns the location of the SV in the string delimited by C<str> and
496 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
497 does not have to be fbm_compiled, but the search will not be as fast
504 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
506 register unsigned char *s;
508 register const unsigned char *little
509 = (const unsigned char *)SvPV_const(littlestr,l);
510 register STRLEN littlelen = l;
511 register const I32 multiline = flags & FBMrf_MULTILINE;
513 if ((STRLEN)(bigend - big) < littlelen) {
514 if ( SvTAIL(littlestr)
515 && ((STRLEN)(bigend - big) == littlelen - 1)
517 || (*big == *little &&
518 memEQ((char *)big, (char *)little, littlelen - 1))))
523 if (littlelen <= 2) { /* Special-cased */
525 if (littlelen == 1) {
526 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
527 /* Know that bigend != big. */
528 if (bigend[-1] == '\n')
529 return (char *)(bigend - 1);
530 return (char *) bigend;
538 if (SvTAIL(littlestr))
539 return (char *) bigend;
543 return (char*)big; /* Cannot be SvTAIL! */
546 if (SvTAIL(littlestr) && !multiline) {
547 if (bigend[-1] == '\n' && bigend[-2] == *little)
548 return (char*)bigend - 2;
549 if (bigend[-1] == *little)
550 return (char*)bigend - 1;
554 /* This should be better than FBM if c1 == c2, and almost
555 as good otherwise: maybe better since we do less indirection.
556 And we save a lot of memory by caching no table. */
557 const unsigned char c1 = little[0];
558 const unsigned char c2 = little[1];
563 while (s <= bigend) {
573 goto check_1char_anchor;
584 goto check_1char_anchor;
587 while (s <= bigend) {
592 goto check_1char_anchor;
601 check_1char_anchor: /* One char and anchor! */
602 if (SvTAIL(littlestr) && (*bigend == *little))
603 return (char *)bigend; /* bigend is already decremented. */
606 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
607 s = bigend - littlelen;
608 if (s >= big && bigend[-1] == '\n' && *s == *little
609 /* Automatically of length > 2 */
610 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
612 return (char*)s; /* how sweet it is */
615 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
617 return (char*)s + 1; /* how sweet it is */
621 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
622 char * const b = ninstr((char*)big,(char*)bigend,
623 (char*)little, (char*)little + littlelen);
625 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
626 /* Chop \n from littlestr: */
627 s = bigend - littlelen + 1;
629 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
638 { /* Do actual FBM. */
639 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
640 register const unsigned char *oldlittle;
642 if (littlelen > (STRLEN)(bigend - big))
644 --littlelen; /* Last char found by table lookup */
647 little += littlelen; /* last char */
653 if ((tmp = table[*s])) {
654 if ((s += tmp) < bigend)
658 else { /* less expensive than calling strncmp() */
659 register unsigned char * const olds = s;
664 if (*--s == *--little)
666 s = olds + 1; /* here we pay the price for failure */
668 if (s < bigend) /* fake up continue to outer loop */
676 if ( s == bigend && (table[-1] & FBMcf_TAIL)
677 && memEQ((char *)(bigend - littlelen),
678 (char *)(oldlittle - littlelen), littlelen) )
679 return (char*)bigend - littlelen;
684 /* start_shift, end_shift are positive quantities which give offsets
685 of ends of some substring of bigstr.
686 If "last" we want the last occurrence.
687 old_posp is the way of communication between consequent calls if
688 the next call needs to find the .
689 The initial *old_posp should be -1.
691 Note that we take into account SvTAIL, so one can get extra
692 optimizations if _ALL flag is set.
695 /* If SvTAIL is actually due to \Z or \z, this gives false positives
696 if PL_multiline. In fact if !PL_multiline the authoritative answer
697 is not supported yet. */
700 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
702 register const unsigned char *big;
704 register I32 previous;
706 register const unsigned char *little;
707 register I32 stop_pos;
708 register const unsigned char *littleend;
712 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
713 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
715 if ( BmRARE(littlestr) == '\n'
716 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
717 little = (const unsigned char *)(SvPVX_const(littlestr));
718 littleend = little + SvCUR(littlestr);
725 little = (const unsigned char *)(SvPVX_const(littlestr));
726 littleend = little + SvCUR(littlestr);
728 /* The value of pos we can start at: */
729 previous = BmPREVIOUS(littlestr);
730 big = (const unsigned char *)(SvPVX_const(bigstr));
731 /* The value of pos we can stop at: */
732 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
733 if (previous + start_shift > stop_pos) {
735 stop_pos does not include SvTAIL in the count, so this check is incorrect
736 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
739 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
744 while (pos < previous + start_shift) {
745 if (!(pos += PL_screamnext[pos]))
750 register const unsigned char *s, *x;
751 if (pos >= stop_pos) break;
752 if (big[pos] != first)
754 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
760 if (s == littleend) {
762 if (!last) return (char *)(big+pos);
765 } while ( pos += PL_screamnext[pos] );
767 return (char *)(big+(*old_posp));
769 if (!SvTAIL(littlestr) || (end_shift > 0))
771 /* Ignore the trailing "\n". This code is not microoptimized */
772 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
773 stop_pos = littleend - little; /* Actual littlestr len */
778 && ((stop_pos == 1) ||
779 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
785 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
787 register const U8 *a = (const U8 *)s1;
788 register const U8 *b = (const U8 *)s2;
790 if (*a != *b && *a != PL_fold[*b])
798 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
801 register const U8 *a = (const U8 *)s1;
802 register const U8 *b = (const U8 *)s2;
804 if (*a != *b && *a != PL_fold_locale[*b])
811 /* copy a string to a safe spot */
814 =head1 Memory Management
818 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
819 string which is a duplicate of C<pv>. The size of the string is
820 determined by C<strlen()>. The memory allocated for the new string can
821 be freed with the C<Safefree()> function.
827 Perl_savepv(pTHX_ const char *pv)
833 const STRLEN pvlen = strlen(pv)+1;
834 Newx(newaddr,pvlen,char);
835 return memcpy(newaddr,pv,pvlen);
840 /* same thing but with a known length */
845 Perl's version of what C<strndup()> would be if it existed. Returns a
846 pointer to a newly allocated string which is a duplicate of the first
847 C<len> bytes from C<pv>. The memory allocated for the new string can be
848 freed with the C<Safefree()> function.
854 Perl_savepvn(pTHX_ const char *pv, register I32 len)
856 register char *newaddr;
858 Newx(newaddr,len+1,char);
859 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
861 /* might not be null terminated */
863 return (char *) CopyD(pv,newaddr,len,char);
866 return (char *) ZeroD(newaddr,len+1,char);
871 =for apidoc savesharedpv
873 A version of C<savepv()> which allocates the duplicate string in memory
874 which is shared between threads.
879 Perl_savesharedpv(pTHX_ const char *pv)
881 register char *newaddr;
886 pvlen = strlen(pv)+1;
887 newaddr = (char*)PerlMemShared_malloc(pvlen);
889 return write_no_mem();
891 return memcpy(newaddr,pv,pvlen);
897 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
898 the passed in SV using C<SvPV()>
904 Perl_savesvpv(pTHX_ SV *sv)
907 const char * const pv = SvPV_const(sv, len);
908 register char *newaddr;
911 Newx(newaddr,len,char);
912 return (char *) CopyD(pv,newaddr,len,char);
916 /* the SV for Perl_form() and mess() is not kept in an arena */
925 return sv_2mortal(newSVpvn("",0));
930 /* Create as PVMG now, to avoid any upgrading later */
932 Newxz(any, 1, XPVMG);
933 SvFLAGS(sv) = SVt_PVMG;
934 SvANY(sv) = (void*)any;
936 SvREFCNT(sv) = 1 << 30; /* practically infinite */
941 #if defined(PERL_IMPLICIT_CONTEXT)
943 Perl_form_nocontext(const char* pat, ...)
949 retval = vform(pat, &args);
953 #endif /* PERL_IMPLICIT_CONTEXT */
956 =head1 Miscellaneous Functions
959 Takes a sprintf-style format pattern and conventional
960 (non-SV) arguments and returns the formatted string.
962 (char *) Perl_form(pTHX_ const char* pat, ...)
964 can be used any place a string (char *) is required:
966 char * s = Perl_form("%d.%d",major,minor);
968 Uses a single private buffer so if you want to format several strings you
969 must explicitly copy the earlier strings away (and free the copies when you
976 Perl_form(pTHX_ const char* pat, ...)
981 retval = vform(pat, &args);
987 Perl_vform(pTHX_ const char *pat, va_list *args)
989 SV * const sv = mess_alloc();
990 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
994 #if defined(PERL_IMPLICIT_CONTEXT)
996 Perl_mess_nocontext(const char *pat, ...)
1001 va_start(args, pat);
1002 retval = vmess(pat, &args);
1006 #endif /* PERL_IMPLICIT_CONTEXT */
1009 Perl_mess(pTHX_ const char *pat, ...)
1013 va_start(args, pat);
1014 retval = vmess(pat, &args);
1020 S_closest_cop(pTHX_ COP *cop, const OP *o)
1022 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1024 if (!o || o == PL_op)
1027 if (o->op_flags & OPf_KIDS) {
1029 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1032 /* If the OP_NEXTSTATE has been optimised away we can still use it
1033 * the get the file and line number. */
1035 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1038 /* Keep searching, and return when we've found something. */
1040 new_cop = closest_cop(cop, kid);
1046 /* Nothing found. */
1052 Perl_vmess(pTHX_ const char *pat, va_list *args)
1054 SV * const sv = mess_alloc();
1055 static const char dgd[] = " during global destruction.\n";
1057 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1058 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1061 * Try and find the file and line for PL_op. This will usually be
1062 * PL_curcop, but it might be a cop that has been optimised away. We
1063 * can try to find such a cop by searching through the optree starting
1064 * from the sibling of PL_curcop.
1067 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1068 if (!cop) cop = PL_curcop;
1071 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1072 OutCopFILE(cop), (IV)CopLINE(cop));
1073 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1074 const bool line_mode = (RsSIMPLE(PL_rs) &&
1075 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1076 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1077 PL_last_in_gv == PL_argvgv ?
1078 "" : GvNAME(PL_last_in_gv),
1079 line_mode ? "line" : "chunk",
1080 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1082 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1088 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1094 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1095 && (io = GvIO(PL_stderrgv))
1096 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1103 SAVESPTR(PL_stderrgv);
1104 PL_stderrgv = Nullgv;
1106 PUSHSTACKi(PERLSI_MAGIC);
1110 PUSHs(SvTIED_obj((SV*)io, mg));
1111 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1113 call_method("PRINT", G_SCALAR);
1121 /* SFIO can really mess with your errno */
1122 const int e = errno;
1124 PerlIO * const serr = Perl_error_log;
1126 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1127 (void)PerlIO_flush(serr);
1134 /* Common code used by vcroak, vdie and vwarner */
1137 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)
1211 const char *message;
1212 const int was_in_eval = PL_in_eval;
1216 DEBUG_S(PerlIO_printf(Perl_debug_log,
1217 "%p: die: curstack = %p, mainstack = %p\n",
1218 thr, PL_curstack, PL_mainstack));
1220 message = vdie_croak_common(pat, args, &msglen, &utf8);
1222 PL_restartop = die_where(message, msglen);
1223 SvFLAGS(ERRSV) |= utf8;
1224 DEBUG_S(PerlIO_printf(Perl_debug_log,
1225 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1226 thr, PL_restartop, was_in_eval, PL_top_env));
1227 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1229 return PL_restartop;
1232 #if defined(PERL_IMPLICIT_CONTEXT)
1234 Perl_die_nocontext(const char* pat, ...)
1239 va_start(args, pat);
1240 o = vdie(pat, &args);
1244 #endif /* PERL_IMPLICIT_CONTEXT */
1247 Perl_die(pTHX_ const char* pat, ...)
1251 va_start(args, pat);
1252 o = vdie(pat, &args);
1258 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1260 const char *message;
1264 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1267 PL_restartop = die_where(message, msglen);
1268 SvFLAGS(ERRSV) |= utf8;
1272 message = SvPVx_const(ERRSV, msglen);
1274 write_to_stderr(message, msglen);
1278 #if defined(PERL_IMPLICIT_CONTEXT)
1280 Perl_croak_nocontext(const char *pat, ...)
1284 va_start(args, pat);
1289 #endif /* PERL_IMPLICIT_CONTEXT */
1292 =head1 Warning and Dieing
1296 This is the XSUB-writer's interface to Perl's C<die> function.
1297 Normally call this function the same way you call the C C<printf>
1298 function. Calling C<croak> returns control directly to Perl,
1299 sidestepping the normal C order of execution. See C<warn>.
1301 If you want to throw an exception object, assign the object to
1302 C<$@> and then pass C<Nullch> to croak():
1304 errsv = get_sv("@", TRUE);
1305 sv_setsv(errsv, exception_object);
1312 Perl_croak(pTHX_ const char *pat, ...)
1315 va_start(args, pat);
1322 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1326 SV * const msv = vmess(pat, args);
1327 const I32 utf8 = SvUTF8(msv);
1328 const char * const message = SvPV_const(msv, msglen);
1331 /* sv_2cv might call Perl_warn() */
1332 SV * const oldwarnhook = PL_warnhook;
1338 SAVESPTR(PL_warnhook);
1339 PL_warnhook = Nullsv;
1340 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1342 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1347 SAVESPTR(PL_warnhook);
1348 PL_warnhook = Nullsv;
1350 msg = newSVpvn(message, msglen);
1351 SvFLAGS(msg) |= utf8;
1355 PUSHSTACKi(PERLSI_WARNHOOK);
1359 call_sv((SV*)cv, G_DISCARD);
1366 write_to_stderr(message, msglen);
1369 #if defined(PERL_IMPLICIT_CONTEXT)
1371 Perl_warn_nocontext(const char *pat, ...)
1375 va_start(args, pat);
1379 #endif /* PERL_IMPLICIT_CONTEXT */
1384 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1385 function the same way you call the C C<printf> function. See C<croak>.
1391 Perl_warn(pTHX_ const char *pat, ...)
1394 va_start(args, pat);
1399 #if defined(PERL_IMPLICIT_CONTEXT)
1401 Perl_warner_nocontext(U32 err, const char *pat, ...)
1405 va_start(args, pat);
1406 vwarner(err, pat, &args);
1409 #endif /* PERL_IMPLICIT_CONTEXT */
1412 Perl_warner(pTHX_ U32 err, const char* pat,...)
1415 va_start(args, pat);
1416 vwarner(err, pat, &args);
1421 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1425 SV * const msv = vmess(pat, args);
1427 const char * const message = SvPV_const(msv, msglen);
1428 const I32 utf8 = SvUTF8(msv);
1432 S_vdie_common(aTHX_ message, msglen, utf8);
1435 PL_restartop = die_where(message, msglen);
1436 SvFLAGS(ERRSV) |= utf8;
1439 write_to_stderr(message, msglen);
1443 Perl_vwarn(aTHX_ pat, args);
1447 /* implements the ckWARN? macros */
1450 Perl_ckwarn(pTHX_ U32 w)
1455 && PL_curcop->cop_warnings != pWARN_NONE
1457 PL_curcop->cop_warnings == pWARN_ALL
1458 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1459 || (unpackWARN2(w) &&
1460 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1461 || (unpackWARN3(w) &&
1462 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1463 || (unpackWARN4(w) &&
1464 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1469 isLEXWARN_off && PL_dowarn & G_WARN_ON
1474 /* implements the ckWARN?_d macro */
1477 Perl_ckwarn_d(pTHX_ U32 w)
1481 || PL_curcop->cop_warnings == pWARN_ALL
1483 PL_curcop->cop_warnings != pWARN_NONE
1485 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1486 || (unpackWARN2(w) &&
1487 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1488 || (unpackWARN3(w) &&
1489 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1490 || (unpackWARN4(w) &&
1491 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1499 /* since we've already done strlen() for both nam and val
1500 * we can use that info to make things faster than
1501 * sprintf(s, "%s=%s", nam, val)
1503 #define my_setenv_format(s, nam, nlen, val, vlen) \
1504 Copy(nam, s, nlen, char); \
1506 Copy(val, s+(nlen+1), vlen, char); \
1507 *(s+(nlen+1+vlen)) = '\0'
1509 #ifdef USE_ENVIRON_ARRAY
1510 /* VMS' my_setenv() is in vms.c */
1511 #if !defined(WIN32) && !defined(NETWARE)
1513 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1517 /* only parent thread can modify process environment */
1518 if (PL_curinterp == aTHX)
1521 #ifndef PERL_USE_SAFE_PUTENV
1522 if (!PL_use_safe_putenv) {
1523 /* most putenv()s leak, so we manipulate environ directly */
1524 register I32 i=setenv_getix(nam); /* where does it go? */
1527 if (environ == PL_origenviron) { /* need we copy environment? */
1532 for (max = i; environ[max]; max++) ;
1533 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1534 for (j=0; j<max; j++) { /* copy environment */
1535 const int len = strlen(environ[j]);
1536 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1537 Copy(environ[j], tmpenv[j], len+1, char);
1539 tmpenv[max] = Nullch;
1540 environ = tmpenv; /* tell exec where it is now */
1543 safesysfree(environ[i]);
1544 while (environ[i]) {
1545 environ[i] = environ[i+1];
1550 if (!environ[i]) { /* does not exist yet */
1551 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1552 environ[i+1] = Nullch; /* make sure it's null terminated */
1555 safesysfree(environ[i]);
1559 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1560 /* all that work just for this */
1561 my_setenv_format(environ[i], nam, nlen, val, vlen);
1564 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1565 # if defined(HAS_UNSETENV)
1567 (void)unsetenv(nam);
1569 (void)setenv(nam, val, 1);
1571 # else /* ! HAS_UNSETENV */
1572 (void)setenv(nam, val, 1);
1573 # endif /* HAS_UNSETENV */
1575 # if defined(HAS_UNSETENV)
1577 (void)unsetenv(nam);
1579 const int nlen = strlen(nam);
1580 const int vlen = strlen(val);
1581 char * const new_env =
1582 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1583 my_setenv_format(new_env, nam, nlen, val, vlen);
1584 (void)putenv(new_env);
1586 # else /* ! HAS_UNSETENV */
1588 const int nlen = strlen(nam);
1594 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1595 /* all that work just for this */
1596 my_setenv_format(new_env, nam, nlen, val, vlen);
1597 (void)putenv(new_env);
1598 # endif /* HAS_UNSETENV */
1599 # endif /* __CYGWIN__ */
1600 #ifndef PERL_USE_SAFE_PUTENV
1606 #else /* WIN32 || NETWARE */
1609 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1612 register char *envstr;
1613 const int nlen = strlen(nam);
1620 Newx(envstr, nlen+vlen+2, char);
1621 my_setenv_format(envstr, nam, nlen, val, vlen);
1622 (void)PerlEnv_putenv(envstr);
1626 #endif /* WIN32 || NETWARE */
1630 Perl_setenv_getix(pTHX_ const char *nam)
1633 register const I32 len = strlen(nam);
1635 for (i = 0; environ[i]; i++) {
1638 strnicmp(environ[i],nam,len) == 0
1640 strnEQ(environ[i],nam,len)
1642 && environ[i][len] == '=')
1643 break; /* strnEQ must come first to avoid */
1644 } /* potential SEGV's */
1647 #endif /* !PERL_MICRO */
1649 #endif /* !VMS && !EPOC*/
1651 #ifdef UNLINK_ALL_VERSIONS
1653 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1657 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1662 /* this is a drop-in replacement for bcopy() */
1663 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1665 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1667 char * const retval = to;
1669 if (from - to >= 0) {
1677 *(--to) = *(--from);
1683 /* this is a drop-in replacement for memset() */
1686 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1688 char * const retval = loc;
1696 /* this is a drop-in replacement for bzero() */
1697 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1699 Perl_my_bzero(register char *loc, register I32 len)
1701 char * const retval = loc;
1709 /* this is a drop-in replacement for memcmp() */
1710 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1712 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1714 register const U8 *a = (const U8 *)s1;
1715 register const U8 *b = (const U8 *)s2;
1719 if ((tmp = *a++ - *b++))
1724 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1728 #ifdef USE_CHAR_VSPRINTF
1733 vsprintf(char *dest, const char *pat, char *args)
1737 fakebuf._ptr = dest;
1738 fakebuf._cnt = 32767;
1742 fakebuf._flag = _IOWRT|_IOSTRG;
1743 _doprnt(pat, args, &fakebuf); /* what a kludge */
1744 (void)putc('\0', &fakebuf);
1745 #ifdef USE_CHAR_VSPRINTF
1748 return 0; /* perl doesn't use return value */
1752 #endif /* HAS_VPRINTF */
1755 #if BYTEORDER != 0x4321
1757 Perl_my_swap(pTHX_ short s)
1759 #if (BYTEORDER & 1) == 0
1762 result = ((s & 255) << 8) + ((s >> 8) & 255);
1770 Perl_my_htonl(pTHX_ long l)
1774 char c[sizeof(long)];
1777 #if BYTEORDER == 0x1234
1778 u.c[0] = (l >> 24) & 255;
1779 u.c[1] = (l >> 16) & 255;
1780 u.c[2] = (l >> 8) & 255;
1784 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1785 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1790 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1791 u.c[o & 0xf] = (l >> s) & 255;
1799 Perl_my_ntohl(pTHX_ long l)
1803 char c[sizeof(long)];
1806 #if BYTEORDER == 0x1234
1807 u.c[0] = (l >> 24) & 255;
1808 u.c[1] = (l >> 16) & 255;
1809 u.c[2] = (l >> 8) & 255;
1813 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1814 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1821 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1822 l |= (u.c[o & 0xf] & 255) << s;
1829 #endif /* BYTEORDER != 0x4321 */
1833 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1834 * If these functions are defined,
1835 * the BYTEORDER is neither 0x1234 nor 0x4321.
1836 * However, this is not assumed.
1840 #define HTOLE(name,type) \
1842 name (register type n) \
1846 char c[sizeof(type)]; \
1849 register I32 s = 0; \
1850 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1851 u.c[i] = (n >> s) & 0xFF; \
1856 #define LETOH(name,type) \
1858 name (register type n) \
1862 char c[sizeof(type)]; \
1865 register I32 s = 0; \
1868 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1869 n |= ((type)(u.c[i] & 0xFF)) << s; \
1875 * Big-endian byte order functions.
1878 #define HTOBE(name,type) \
1880 name (register type n) \
1884 char c[sizeof(type)]; \
1887 register I32 s = 8*(sizeof(u.c)-1); \
1888 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1889 u.c[i] = (n >> s) & 0xFF; \
1894 #define BETOH(name,type) \
1896 name (register type n) \
1900 char c[sizeof(type)]; \
1903 register I32 s = 8*(sizeof(u.c)-1); \
1906 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1907 n |= ((type)(u.c[i] & 0xFF)) << s; \
1913 * If we just can't do it...
1916 #define NOT_AVAIL(name,type) \
1918 name (register type n) \
1920 Perl_croak_nocontext(#name "() not available"); \
1921 return n; /* not reached */ \
1925 #if defined(HAS_HTOVS) && !defined(htovs)
1928 #if defined(HAS_HTOVL) && !defined(htovl)
1931 #if defined(HAS_VTOHS) && !defined(vtohs)
1934 #if defined(HAS_VTOHL) && !defined(vtohl)
1938 #ifdef PERL_NEED_MY_HTOLE16
1940 HTOLE(Perl_my_htole16,U16)
1942 NOT_AVAIL(Perl_my_htole16,U16)
1945 #ifdef PERL_NEED_MY_LETOH16
1947 LETOH(Perl_my_letoh16,U16)
1949 NOT_AVAIL(Perl_my_letoh16,U16)
1952 #ifdef PERL_NEED_MY_HTOBE16
1954 HTOBE(Perl_my_htobe16,U16)
1956 NOT_AVAIL(Perl_my_htobe16,U16)
1959 #ifdef PERL_NEED_MY_BETOH16
1961 BETOH(Perl_my_betoh16,U16)
1963 NOT_AVAIL(Perl_my_betoh16,U16)
1967 #ifdef PERL_NEED_MY_HTOLE32
1969 HTOLE(Perl_my_htole32,U32)
1971 NOT_AVAIL(Perl_my_htole32,U32)
1974 #ifdef PERL_NEED_MY_LETOH32
1976 LETOH(Perl_my_letoh32,U32)
1978 NOT_AVAIL(Perl_my_letoh32,U32)
1981 #ifdef PERL_NEED_MY_HTOBE32
1983 HTOBE(Perl_my_htobe32,U32)
1985 NOT_AVAIL(Perl_my_htobe32,U32)
1988 #ifdef PERL_NEED_MY_BETOH32
1990 BETOH(Perl_my_betoh32,U32)
1992 NOT_AVAIL(Perl_my_betoh32,U32)
1996 #ifdef PERL_NEED_MY_HTOLE64
1998 HTOLE(Perl_my_htole64,U64)
2000 NOT_AVAIL(Perl_my_htole64,U64)
2003 #ifdef PERL_NEED_MY_LETOH64
2005 LETOH(Perl_my_letoh64,U64)
2007 NOT_AVAIL(Perl_my_letoh64,U64)
2010 #ifdef PERL_NEED_MY_HTOBE64
2012 HTOBE(Perl_my_htobe64,U64)
2014 NOT_AVAIL(Perl_my_htobe64,U64)
2017 #ifdef PERL_NEED_MY_BETOH64
2019 BETOH(Perl_my_betoh64,U64)
2021 NOT_AVAIL(Perl_my_betoh64,U64)
2025 #ifdef PERL_NEED_MY_HTOLES
2026 HTOLE(Perl_my_htoles,short)
2028 #ifdef PERL_NEED_MY_LETOHS
2029 LETOH(Perl_my_letohs,short)
2031 #ifdef PERL_NEED_MY_HTOBES
2032 HTOBE(Perl_my_htobes,short)
2034 #ifdef PERL_NEED_MY_BETOHS
2035 BETOH(Perl_my_betohs,short)
2038 #ifdef PERL_NEED_MY_HTOLEI
2039 HTOLE(Perl_my_htolei,int)
2041 #ifdef PERL_NEED_MY_LETOHI
2042 LETOH(Perl_my_letohi,int)
2044 #ifdef PERL_NEED_MY_HTOBEI
2045 HTOBE(Perl_my_htobei,int)
2047 #ifdef PERL_NEED_MY_BETOHI
2048 BETOH(Perl_my_betohi,int)
2051 #ifdef PERL_NEED_MY_HTOLEL
2052 HTOLE(Perl_my_htolel,long)
2054 #ifdef PERL_NEED_MY_LETOHL
2055 LETOH(Perl_my_letohl,long)
2057 #ifdef PERL_NEED_MY_HTOBEL
2058 HTOBE(Perl_my_htobel,long)
2060 #ifdef PERL_NEED_MY_BETOHL
2061 BETOH(Perl_my_betohl,long)
2065 Perl_my_swabn(void *ptr, int n)
2067 register char *s = (char *)ptr;
2068 register char *e = s + (n-1);
2071 for (n /= 2; n > 0; s++, e--, n--) {
2079 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2081 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2083 register I32 This, that;
2089 PERL_FLUSHALL_FOR_CHILD;
2090 This = (*mode == 'w');
2094 taint_proper("Insecure %s%s", "EXEC");
2096 if (PerlProc_pipe(p) < 0)
2098 /* Try for another pipe pair for error return */
2099 if (PerlProc_pipe(pp) >= 0)
2101 while ((pid = PerlProc_fork()) < 0) {
2102 if (errno != EAGAIN) {
2103 PerlLIO_close(p[This]);
2104 PerlLIO_close(p[that]);
2106 PerlLIO_close(pp[0]);
2107 PerlLIO_close(pp[1]);
2119 /* Close parent's end of error status pipe (if any) */
2121 PerlLIO_close(pp[0]);
2122 #if defined(HAS_FCNTL) && defined(F_SETFD)
2123 /* Close error pipe automatically if exec works */
2124 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2127 /* Now dup our end of _the_ pipe to right position */
2128 if (p[THIS] != (*mode == 'r')) {
2129 PerlLIO_dup2(p[THIS], *mode == 'r');
2130 PerlLIO_close(p[THIS]);
2131 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2132 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2135 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2136 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2137 /* No automatic close - do it by hand */
2144 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2150 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2156 do_execfree(); /* free any memory malloced by child on fork */
2158 PerlLIO_close(pp[1]);
2159 /* Keep the lower of the two fd numbers */
2160 if (p[that] < p[This]) {
2161 PerlLIO_dup2(p[This], p[that]);
2162 PerlLIO_close(p[This]);
2166 PerlLIO_close(p[that]); /* close child's end of pipe */
2169 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2171 SvUPGRADE(sv,SVt_IV);
2173 PL_forkprocess = pid;
2174 /* If we managed to get status pipe check for exec fail */
2175 if (did_pipes && pid > 0) {
2179 while (n < sizeof(int)) {
2180 n1 = PerlLIO_read(pp[0],
2181 (void*)(((char*)&errkid)+n),
2187 PerlLIO_close(pp[0]);
2189 if (n) { /* Error */
2191 PerlLIO_close(p[This]);
2192 if (n != sizeof(int))
2193 Perl_croak(aTHX_ "panic: kid popen errno read");
2195 pid2 = wait4pid(pid, &status, 0);
2196 } while (pid2 == -1 && errno == EINTR);
2197 errno = errkid; /* Propagate errno from kid */
2202 PerlLIO_close(pp[0]);
2203 return PerlIO_fdopen(p[This], mode);
2205 Perl_croak(aTHX_ "List form of piped open not implemented");
2206 return (PerlIO *) NULL;
2210 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2211 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2213 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2216 register I32 This, that;
2219 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2223 PERL_FLUSHALL_FOR_CHILD;
2226 return my_syspopen(aTHX_ cmd,mode);
2229 This = (*mode == 'w');
2231 if (doexec && PL_tainting) {
2233 taint_proper("Insecure %s%s", "EXEC");
2235 if (PerlProc_pipe(p) < 0)
2237 if (doexec && PerlProc_pipe(pp) >= 0)
2239 while ((pid = PerlProc_fork()) < 0) {
2240 if (errno != EAGAIN) {
2241 PerlLIO_close(p[This]);
2242 PerlLIO_close(p[that]);
2244 PerlLIO_close(pp[0]);
2245 PerlLIO_close(pp[1]);
2248 Perl_croak(aTHX_ "Can't fork");
2261 PerlLIO_close(pp[0]);
2262 #if defined(HAS_FCNTL) && defined(F_SETFD)
2263 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2266 if (p[THIS] != (*mode == 'r')) {
2267 PerlLIO_dup2(p[THIS], *mode == 'r');
2268 PerlLIO_close(p[THIS]);
2269 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2270 PerlLIO_close(p[THAT]);
2273 PerlLIO_close(p[THAT]);
2276 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2283 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2288 /* may or may not use the shell */
2289 do_exec3(cmd, pp[1], did_pipes);
2292 #endif /* defined OS2 */
2293 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2294 SvREADONLY_off(GvSV(tmpgv));
2295 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2296 SvREADONLY_on(GvSV(tmpgv));
2298 #ifdef THREADS_HAVE_PIDS
2299 PL_ppid = (IV)getppid();
2302 #ifdef PERL_USES_PL_PIDSTATUS
2303 hv_clear(PL_pidstatus); /* we have no children */
2309 do_execfree(); /* free any memory malloced by child on vfork */
2311 PerlLIO_close(pp[1]);
2312 if (p[that] < p[This]) {
2313 PerlLIO_dup2(p[This], p[that]);
2314 PerlLIO_close(p[This]);
2318 PerlLIO_close(p[that]);
2321 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2323 SvUPGRADE(sv,SVt_IV);
2325 PL_forkprocess = pid;
2326 if (did_pipes && pid > 0) {
2330 while (n < sizeof(int)) {
2331 n1 = PerlLIO_read(pp[0],
2332 (void*)(((char*)&errkid)+n),
2338 PerlLIO_close(pp[0]);
2340 if (n) { /* Error */
2342 PerlLIO_close(p[This]);
2343 if (n != sizeof(int))
2344 Perl_croak(aTHX_ "panic: kid popen errno read");
2346 pid2 = wait4pid(pid, &status, 0);
2347 } while (pid2 == -1 && errno == EINTR);
2348 errno = errkid; /* Propagate errno from kid */
2353 PerlLIO_close(pp[0]);
2354 return PerlIO_fdopen(p[This], mode);
2357 #if defined(atarist) || defined(EPOC)
2360 Perl_my_popen(pTHX_ char *cmd, char *mode)
2362 PERL_FLUSHALL_FOR_CHILD;
2363 /* Call system's popen() to get a FILE *, then import it.
2364 used 0 for 2nd parameter to PerlIO_importFILE;
2367 return PerlIO_importFILE(popen(cmd, mode), 0);
2371 FILE *djgpp_popen();
2373 Perl_my_popen(pTHX_ char *cmd, char *mode)
2375 PERL_FLUSHALL_FOR_CHILD;
2376 /* Call system's popen() to get a FILE *, then import it.
2377 used 0 for 2nd parameter to PerlIO_importFILE;
2380 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2385 #endif /* !DOSISH */
2387 /* this is called in parent before the fork() */
2389 Perl_atfork_lock(void)
2392 #if defined(USE_ITHREADS)
2393 /* locks must be held in locking order (if any) */
2395 MUTEX_LOCK(&PL_malloc_mutex);
2401 /* this is called in both parent and child after the fork() */
2403 Perl_atfork_unlock(void)
2406 #if defined(USE_ITHREADS)
2407 /* locks must be released in same order as in atfork_lock() */
2409 MUTEX_UNLOCK(&PL_malloc_mutex);
2418 #if defined(HAS_FORK)
2420 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2425 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2426 * handlers elsewhere in the code */
2431 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2432 Perl_croak_nocontext("fork() not available");
2434 #endif /* HAS_FORK */
2439 Perl_dump_fds(pTHX_ char *s)
2444 PerlIO_printf(Perl_debug_log,"%s", s);
2445 for (fd = 0; fd < 32; fd++) {
2446 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2447 PerlIO_printf(Perl_debug_log," %d",fd);
2449 PerlIO_printf(Perl_debug_log,"\n");
2452 #endif /* DUMP_FDS */
2456 dup2(int oldfd, int newfd)
2458 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2461 PerlLIO_close(newfd);
2462 return fcntl(oldfd, F_DUPFD, newfd);
2464 #define DUP2_MAX_FDS 256
2465 int fdtmp[DUP2_MAX_FDS];
2471 PerlLIO_close(newfd);
2472 /* good enough for low fd's... */
2473 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2474 if (fdx >= DUP2_MAX_FDS) {
2482 PerlLIO_close(fdtmp[--fdx]);
2489 #ifdef HAS_SIGACTION
2491 #ifdef MACOS_TRADITIONAL
2492 /* We don't want restart behavior on MacOS */
2497 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2500 struct sigaction act, oact;
2503 /* only "parent" interpreter can diddle signals */
2504 if (PL_curinterp != aTHX)
2505 return (Sighandler_t) SIG_ERR;
2508 act.sa_handler = (void(*)(int))handler;
2509 sigemptyset(&act.sa_mask);
2512 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2513 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2515 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2516 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2517 act.sa_flags |= SA_NOCLDWAIT;
2519 if (sigaction(signo, &act, &oact) == -1)
2520 return (Sighandler_t) SIG_ERR;
2522 return (Sighandler_t) oact.sa_handler;
2526 Perl_rsignal_state(pTHX_ int signo)
2528 struct sigaction oact;
2530 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2531 return (Sighandler_t) SIG_ERR;
2533 return (Sighandler_t) oact.sa_handler;
2537 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2540 struct sigaction act;
2543 /* only "parent" interpreter can diddle signals */
2544 if (PL_curinterp != aTHX)
2548 act.sa_handler = (void(*)(int))handler;
2549 sigemptyset(&act.sa_mask);
2552 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2553 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2555 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2556 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2557 act.sa_flags |= SA_NOCLDWAIT;
2559 return sigaction(signo, &act, save);
2563 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2567 /* only "parent" interpreter can diddle signals */
2568 if (PL_curinterp != aTHX)
2572 return sigaction(signo, save, (struct sigaction *)NULL);
2575 #else /* !HAS_SIGACTION */
2578 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2580 #if defined(USE_ITHREADS) && !defined(WIN32)
2581 /* only "parent" interpreter can diddle signals */
2582 if (PL_curinterp != aTHX)
2583 return (Sighandler_t) SIG_ERR;
2586 return PerlProc_signal(signo, handler);
2597 Perl_rsignal_state(pTHX_ int signo)
2600 Sighandler_t oldsig;
2602 #if defined(USE_ITHREADS) && !defined(WIN32)
2603 /* only "parent" interpreter can diddle signals */
2604 if (PL_curinterp != aTHX)
2605 return (Sighandler_t) SIG_ERR;
2609 oldsig = PerlProc_signal(signo, sig_trap);
2610 PerlProc_signal(signo, oldsig);
2612 PerlProc_kill(PerlProc_getpid(), signo);
2617 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2619 #if defined(USE_ITHREADS) && !defined(WIN32)
2620 /* only "parent" interpreter can diddle signals */
2621 if (PL_curinterp != aTHX)
2624 *save = PerlProc_signal(signo, handler);
2625 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2629 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2631 #if defined(USE_ITHREADS) && !defined(WIN32)
2632 /* only "parent" interpreter can diddle signals */
2633 if (PL_curinterp != aTHX)
2636 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2639 #endif /* !HAS_SIGACTION */
2640 #endif /* !PERL_MICRO */
2642 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2643 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2645 Perl_my_pclose(pTHX_ PerlIO *ptr)
2647 Sigsave_t hstat, istat, qstat;
2653 int saved_errno = 0;
2655 int saved_win32_errno;
2659 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2661 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2663 *svp = &PL_sv_undef;
2665 if (pid == -1) { /* Opened by popen. */
2666 return my_syspclose(ptr);
2669 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2670 saved_errno = errno;
2672 saved_win32_errno = GetLastError();
2676 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2679 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2680 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2681 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2684 pid2 = wait4pid(pid, &status, 0);
2685 } while (pid2 == -1 && errno == EINTR);
2687 rsignal_restore(SIGHUP, &hstat);
2688 rsignal_restore(SIGINT, &istat);
2689 rsignal_restore(SIGQUIT, &qstat);
2692 SETERRNO(saved_errno, 0);
2695 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2697 #endif /* !DOSISH */
2699 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2701 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2706 #ifdef PERL_USES_PL_PIDSTATUS
2709 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2710 pid, rather than a string form. */
2711 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2712 if (svp && *svp != &PL_sv_undef) {
2713 *statusp = SvIVX(*svp);
2714 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2722 hv_iterinit(PL_pidstatus);
2723 if ((entry = hv_iternext(PL_pidstatus))) {
2724 SV * const sv = hv_iterval(PL_pidstatus,entry);
2726 const char * const spid = hv_iterkey(entry,&len);
2728 assert (len == sizeof(Pid_t));
2729 memcpy((char *)&pid, spid, len);
2730 *statusp = SvIVX(sv);
2731 /* The hash iterator is currently on this entry, so simply
2732 calling hv_delete would trigger the lazy delete, which on
2733 aggregate does more work, beacuse next call to hv_iterinit()
2734 would spot the flag, and have to call the delete routine,
2735 while in the meantime any new entries can't re-use that
2737 hv_iterinit(PL_pidstatus);
2738 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2745 # ifdef HAS_WAITPID_RUNTIME
2746 if (!HAS_WAITPID_RUNTIME)
2749 result = PerlProc_waitpid(pid,statusp,flags);
2752 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2753 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2756 #ifdef PERL_USES_PL_PIDSTATUS
2757 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2762 Perl_croak(aTHX_ "Can't do waitpid with flags");
2764 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2765 pidgone(result,*statusp);
2771 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2774 if (result < 0 && errno == EINTR) {
2779 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2781 #ifdef PERL_USES_PL_PIDSTATUS
2783 Perl_pidgone(pTHX_ Pid_t pid, int status)
2787 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2788 SvUPGRADE(sv,SVt_IV);
2789 SvIV_set(sv, status);
2794 #if defined(atarist) || defined(OS2) || defined(EPOC)
2797 int /* Cannot prototype with I32
2799 my_syspclose(PerlIO *ptr)
2802 Perl_my_pclose(pTHX_ PerlIO *ptr)
2805 /* Needs work for PerlIO ! */
2806 FILE * const f = PerlIO_findFILE(ptr);
2807 const I32 result = pclose(f);
2808 PerlIO_releaseFILE(ptr,f);
2816 Perl_my_pclose(pTHX_ PerlIO *ptr)
2818 /* Needs work for PerlIO ! */
2819 FILE * const f = PerlIO_findFILE(ptr);
2820 I32 result = djgpp_pclose(f);
2821 result = (result << 8) & 0xff00;
2822 PerlIO_releaseFILE(ptr,f);
2828 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2831 register const char * const frombase = from;
2834 register const char c = *from;
2839 while (count-- > 0) {
2840 for (todo = len; todo > 0; todo--) {
2849 Perl_same_dirent(pTHX_ const char *a, const char *b)
2851 char *fa = strrchr(a,'/');
2852 char *fb = strrchr(b,'/');
2855 SV * const tmpsv = sv_newmortal();
2868 sv_setpvn(tmpsv, ".", 1);
2870 sv_setpvn(tmpsv, a, fa - a);
2871 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2874 sv_setpvn(tmpsv, ".", 1);
2876 sv_setpvn(tmpsv, b, fb - b);
2877 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2879 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2880 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2882 #endif /* !HAS_RENAME */
2885 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2886 const char *const *const search_ext, I32 flags)
2888 const char *xfound = Nullch;
2889 char *xfailed = Nullch;
2890 char tmpbuf[MAXPATHLEN];
2894 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2895 # define SEARCH_EXTS ".bat", ".cmd", NULL
2896 # define MAX_EXT_LEN 4
2899 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2900 # define MAX_EXT_LEN 4
2903 # define SEARCH_EXTS ".pl", ".com", NULL
2904 # define MAX_EXT_LEN 4
2906 /* additional extensions to try in each dir if scriptname not found */
2908 static const char *const exts[] = { SEARCH_EXTS };
2909 const char *const *const ext = search_ext ? search_ext : exts;
2910 int extidx = 0, i = 0;
2911 const char *curext = Nullch;
2913 PERL_UNUSED_ARG(search_ext);
2914 # define MAX_EXT_LEN 0
2918 * If dosearch is true and if scriptname does not contain path
2919 * delimiters, search the PATH for scriptname.
2921 * If SEARCH_EXTS is also defined, will look for each
2922 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2923 * while searching the PATH.
2925 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2926 * proceeds as follows:
2927 * If DOSISH or VMSISH:
2928 * + look for ./scriptname{,.foo,.bar}
2929 * + search the PATH for scriptname{,.foo,.bar}
2932 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2933 * this will not look in '.' if it's not in the PATH)
2938 # ifdef ALWAYS_DEFTYPES
2939 len = strlen(scriptname);
2940 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2941 int idx = 0, deftypes = 1;
2944 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch);
2947 int idx = 0, deftypes = 1;
2950 const int hasdir = (strpbrk(scriptname,":[</") != Nullch);
2952 /* The first time through, just add SEARCH_EXTS to whatever we
2953 * already have, so we can check for default file types. */
2955 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2961 if ((strlen(tmpbuf) + strlen(scriptname)
2962 + MAX_EXT_LEN) >= sizeof tmpbuf)
2963 continue; /* don't search dir with too-long name */
2964 strcat(tmpbuf, scriptname);
2968 if (strEQ(scriptname, "-"))
2970 if (dosearch) { /* Look in '.' first. */
2971 const char *cur = scriptname;
2973 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2975 if (strEQ(ext[i++],curext)) {
2976 extidx = -1; /* already has an ext */
2981 DEBUG_p(PerlIO_printf(Perl_debug_log,
2982 "Looking for %s\n",cur));
2983 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2984 && !S_ISDIR(PL_statbuf.st_mode)) {
2992 if (cur == scriptname) {
2993 len = strlen(scriptname);
2994 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2996 /* FIXME? Convert to memcpy */
2997 cur = strcpy(tmpbuf, scriptname);
2999 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3000 && strcpy(tmpbuf+len, ext[extidx++]));
3005 #ifdef MACOS_TRADITIONAL
3006 if (dosearch && !strchr(scriptname, ':') &&
3007 (s = PerlEnv_getenv("Commands")))
3009 if (dosearch && !strchr(scriptname, '/')
3011 && !strchr(scriptname, '\\')
3013 && (s = PerlEnv_getenv("PATH")))
3018 PL_bufend = s + strlen(s);
3019 while (s < PL_bufend) {
3020 #ifdef MACOS_TRADITIONAL
3021 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3025 #if defined(atarist) || defined(DOSISH)
3030 && *s != ';'; len++, s++) {
3031 if (len < sizeof tmpbuf)
3034 if (len < sizeof tmpbuf)
3036 #else /* ! (atarist || DOSISH) */
3037 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3040 #endif /* ! (atarist || DOSISH) */
3041 #endif /* MACOS_TRADITIONAL */
3044 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3045 continue; /* don't search dir with too-long name */
3046 #ifdef MACOS_TRADITIONAL
3047 if (len && tmpbuf[len - 1] != ':')
3048 tmpbuf[len++] = ':';
3051 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3052 && tmpbuf[len - 1] != '/'
3053 && tmpbuf[len - 1] != '\\'
3056 tmpbuf[len++] = '/';
3057 if (len == 2 && tmpbuf[0] == '.')
3060 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3062 (void)strcpy(tmpbuf + len, scriptname);
3066 len = strlen(tmpbuf);
3067 if (extidx > 0) /* reset after previous loop */
3071 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3072 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3073 if (S_ISDIR(PL_statbuf.st_mode)) {
3077 } while ( retval < 0 /* not there */
3078 && extidx>=0 && ext[extidx] /* try an extension? */
3079 && strcpy(tmpbuf+len, ext[extidx++])
3084 if (S_ISREG(PL_statbuf.st_mode)
3085 && cando(S_IRUSR,TRUE,&PL_statbuf)
3086 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3087 && cando(S_IXUSR,TRUE,&PL_statbuf)
3091 xfound = tmpbuf; /* bingo! */
3095 xfailed = savepv(tmpbuf);
3098 if (!xfound && !seen_dot && !xfailed &&
3099 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3100 || S_ISDIR(PL_statbuf.st_mode)))
3102 seen_dot = 1; /* Disable message. */
3104 if (flags & 1) { /* do or die? */
3105 Perl_croak(aTHX_ "Can't %s %s%s%s",
3106 (xfailed ? "execute" : "find"),
3107 (xfailed ? xfailed : scriptname),
3108 (xfailed ? "" : " on PATH"),
3109 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3111 scriptname = Nullch;
3114 scriptname = xfound;
3116 return (scriptname ? savepv(scriptname) : Nullch);
3119 #ifndef PERL_GET_CONTEXT_DEFINED
3122 Perl_get_context(void)
3125 #if defined(USE_ITHREADS)
3126 # ifdef OLD_PTHREADS_API
3128 if (pthread_getspecific(PL_thr_key, &t))
3129 Perl_croak_nocontext("panic: pthread_getspecific");
3132 # ifdef I_MACH_CTHREADS
3133 return (void*)cthread_data(cthread_self());
3135 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3144 Perl_set_context(void *t)
3147 #if defined(USE_ITHREADS)
3148 # ifdef I_MACH_CTHREADS
3149 cthread_set_data(cthread_self(), t);
3151 if (pthread_setspecific(PL_thr_key, t))
3152 Perl_croak_nocontext("panic: pthread_setspecific");
3159 #endif /* !PERL_GET_CONTEXT_DEFINED */
3161 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3170 Perl_get_op_names(pTHX)
3172 return (char **)PL_op_name;
3176 Perl_get_op_descs(pTHX)
3178 return (char **)PL_op_desc;
3182 Perl_get_no_modify(pTHX)
3184 return PL_no_modify;
3188 Perl_get_opargs(pTHX)
3190 return (U32 *)PL_opargs;
3194 Perl_get_ppaddr(pTHX)
3197 return (PPADDR_t*)PL_ppaddr;
3200 #ifndef HAS_GETENV_LEN
3202 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3204 char * const env_trans = PerlEnv_getenv(env_elem);
3206 *len = strlen(env_trans);
3213 Perl_get_vtbl(pTHX_ int vtbl_id)
3215 const MGVTBL* result;
3219 result = &PL_vtbl_sv;
3222 result = &PL_vtbl_env;
3224 case want_vtbl_envelem:
3225 result = &PL_vtbl_envelem;
3228 result = &PL_vtbl_sig;
3230 case want_vtbl_sigelem:
3231 result = &PL_vtbl_sigelem;
3233 case want_vtbl_pack:
3234 result = &PL_vtbl_pack;
3236 case want_vtbl_packelem:
3237 result = &PL_vtbl_packelem;
3239 case want_vtbl_dbline:
3240 result = &PL_vtbl_dbline;
3243 result = &PL_vtbl_isa;
3245 case want_vtbl_isaelem:
3246 result = &PL_vtbl_isaelem;
3248 case want_vtbl_arylen:
3249 result = &PL_vtbl_arylen;
3251 case want_vtbl_glob:
3252 result = &PL_vtbl_glob;
3254 case want_vtbl_mglob:
3255 result = &PL_vtbl_mglob;
3257 case want_vtbl_nkeys:
3258 result = &PL_vtbl_nkeys;
3260 case want_vtbl_taint:
3261 result = &PL_vtbl_taint;
3263 case want_vtbl_substr:
3264 result = &PL_vtbl_substr;
3267 result = &PL_vtbl_vec;
3270 result = &PL_vtbl_pos;
3273 result = &PL_vtbl_bm;
3276 result = &PL_vtbl_fm;
3278 case want_vtbl_uvar:
3279 result = &PL_vtbl_uvar;
3281 case want_vtbl_defelem:
3282 result = &PL_vtbl_defelem;
3284 case want_vtbl_regexp:
3285 result = &PL_vtbl_regexp;
3287 case want_vtbl_regdata:
3288 result = &PL_vtbl_regdata;
3290 case want_vtbl_regdatum:
3291 result = &PL_vtbl_regdatum;
3293 #ifdef USE_LOCALE_COLLATE
3294 case want_vtbl_collxfrm:
3295 result = &PL_vtbl_collxfrm;
3298 case want_vtbl_amagic:
3299 result = &PL_vtbl_amagic;
3301 case want_vtbl_amagicelem:
3302 result = &PL_vtbl_amagicelem;
3304 case want_vtbl_backref:
3305 result = &PL_vtbl_backref;
3307 case want_vtbl_utf8:
3308 result = &PL_vtbl_utf8;
3311 result = Null(MGVTBL*);
3314 return (MGVTBL*)result;
3318 Perl_my_fflush_all(pTHX)
3320 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3321 return PerlIO_flush(NULL);
3323 # if defined(HAS__FWALK)
3324 extern int fflush(FILE *);
3325 /* undocumented, unprototyped, but very useful BSDism */
3326 extern void _fwalk(int (*)(FILE *));
3330 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3332 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3333 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3335 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3336 open_max = sysconf(_SC_OPEN_MAX);
3339 open_max = FOPEN_MAX;
3342 open_max = OPEN_MAX;
3353 for (i = 0; i < open_max; i++)
3354 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3355 STDIO_STREAM_ARRAY[i]._file < open_max &&
3356 STDIO_STREAM_ARRAY[i]._flag)
3357 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3361 SETERRNO(EBADF,RMS_IFI);
3368 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3370 const char * const func =
3371 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3372 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3374 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3375 const char * const type = OP_IS_SOCKET(op)
3376 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3377 ? "socket" : "filehandle";
3378 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3380 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3381 if (ckWARN(WARN_IO)) {
3382 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3384 Perl_warner(aTHX_ packWARN(WARN_IO),
3385 "Filehandle %s opened only for %sput",
3388 Perl_warner(aTHX_ packWARN(WARN_IO),
3389 "Filehandle opened only for %sput", direction);
3396 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3398 warn_type = WARN_CLOSED;
3402 warn_type = WARN_UNOPENED;
3405 if (ckWARN(warn_type)) {
3406 if (name && *name) {
3407 Perl_warner(aTHX_ packWARN(warn_type),
3408 "%s%s on %s %s %s", func, pars, vile, type, name);
3409 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3411 aTHX_ packWARN(warn_type),
3412 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3417 Perl_warner(aTHX_ packWARN(warn_type),
3418 "%s%s on %s %s", func, pars, vile, type);
3419 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3421 aTHX_ packWARN(warn_type),
3422 "\t(Are you trying to call %s%s on dirhandle?)\n",
3431 /* in ASCII order, not that it matters */
3432 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3435 Perl_ebcdic_control(pTHX_ int ch)
3443 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3444 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3447 if (ctlp == controllablechars)
3448 return('\177'); /* DEL */
3450 return((unsigned char)(ctlp - controllablechars - 1));
3451 } else { /* Want uncontrol */
3452 if (ch == '\177' || ch == -1)
3454 else if (ch == '\157')
3456 else if (ch == '\174')
3458 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3460 else if (ch == '\155')
3462 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3463 return(controllablechars[ch+1]);
3465 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3470 /* To workaround core dumps from the uninitialised tm_zone we get the
3471 * system to give us a reasonable struct to copy. This fix means that
3472 * strftime uses the tm_zone and tm_gmtoff values returned by
3473 * localtime(time()). That should give the desired result most of the
3474 * time. But probably not always!
3476 * This does not address tzname aspects of NETaa14816.
3481 # ifndef STRUCT_TM_HASZONE
3482 # define STRUCT_TM_HASZONE
3486 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3487 # ifndef HAS_TM_TM_ZONE
3488 # define HAS_TM_TM_ZONE
3493 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3495 #ifdef HAS_TM_TM_ZONE
3497 const struct tm* my_tm;
3499 my_tm = localtime(&now);
3501 Copy(my_tm, ptm, 1, struct tm);
3503 PERL_UNUSED_ARG(ptm);
3508 * mini_mktime - normalise struct tm values without the localtime()
3509 * semantics (and overhead) of mktime().
3512 Perl_mini_mktime(pTHX_ struct tm *ptm)
3516 int month, mday, year, jday;
3517 int odd_cent, odd_year;
3519 #define DAYS_PER_YEAR 365
3520 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3521 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3522 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3523 #define SECS_PER_HOUR (60*60)
3524 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3525 /* parentheses deliberately absent on these two, otherwise they don't work */
3526 #define MONTH_TO_DAYS 153/5
3527 #define DAYS_TO_MONTH 5/153
3528 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3529 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3530 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3531 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3534 * Year/day algorithm notes:
3536 * With a suitable offset for numeric value of the month, one can find
3537 * an offset into the year by considering months to have 30.6 (153/5) days,
3538 * using integer arithmetic (i.e., with truncation). To avoid too much
3539 * messing about with leap days, we consider January and February to be
3540 * the 13th and 14th month of the previous year. After that transformation,
3541 * we need the month index we use to be high by 1 from 'normal human' usage,
3542 * so the month index values we use run from 4 through 15.
3544 * Given that, and the rules for the Gregorian calendar (leap years are those
3545 * divisible by 4 unless also divisible by 100, when they must be divisible
3546 * by 400 instead), we can simply calculate the number of days since some
3547 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3548 * the days we derive from our month index, and adding in the day of the
3549 * month. The value used here is not adjusted for the actual origin which
3550 * it normally would use (1 January A.D. 1), since we're not exposing it.
3551 * We're only building the value so we can turn around and get the
3552 * normalised values for the year, month, day-of-month, and day-of-year.
3554 * For going backward, we need to bias the value we're using so that we find
3555 * the right year value. (Basically, we don't want the contribution of
3556 * March 1st to the number to apply while deriving the year). Having done
3557 * that, we 'count up' the contribution to the year number by accounting for
3558 * full quadracenturies (400-year periods) with their extra leap days, plus
3559 * the contribution from full centuries (to avoid counting in the lost leap
3560 * days), plus the contribution from full quad-years (to count in the normal
3561 * leap days), plus the leftover contribution from any non-leap years.
3562 * At this point, if we were working with an actual leap day, we'll have 0
3563 * days left over. This is also true for March 1st, however. So, we have
3564 * to special-case that result, and (earlier) keep track of the 'odd'
3565 * century and year contributions. If we got 4 extra centuries in a qcent,
3566 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3567 * Otherwise, we add back in the earlier bias we removed (the 123 from
3568 * figuring in March 1st), find the month index (integer division by 30.6),
3569 * and the remainder is the day-of-month. We then have to convert back to
3570 * 'real' months (including fixing January and February from being 14/15 in
3571 * the previous year to being in the proper year). After that, to get
3572 * tm_yday, we work with the normalised year and get a new yearday value for
3573 * January 1st, which we subtract from the yearday value we had earlier,
3574 * representing the date we've re-built. This is done from January 1
3575 * because tm_yday is 0-origin.
3577 * Since POSIX time routines are only guaranteed to work for times since the
3578 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3579 * applies Gregorian calendar rules even to dates before the 16th century
3580 * doesn't bother me. Besides, you'd need cultural context for a given
3581 * date to know whether it was Julian or Gregorian calendar, and that's
3582 * outside the scope for this routine. Since we convert back based on the
3583 * same rules we used to build the yearday, you'll only get strange results
3584 * for input which needed normalising, or for the 'odd' century years which
3585 * were leap years in the Julian calander but not in the Gregorian one.
3586 * I can live with that.
3588 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3589 * that's still outside the scope for POSIX time manipulation, so I don't
3593 year = 1900 + ptm->tm_year;
3594 month = ptm->tm_mon;
3595 mday = ptm->tm_mday;
3596 /* allow given yday with no month & mday to dominate the result */
3597 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3600 jday = 1 + ptm->tm_yday;
3609 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3610 yearday += month*MONTH_TO_DAYS + mday + jday;
3612 * Note that we don't know when leap-seconds were or will be,
3613 * so we have to trust the user if we get something which looks
3614 * like a sensible leap-second. Wild values for seconds will
3615 * be rationalised, however.
3617 if ((unsigned) ptm->tm_sec <= 60) {
3624 secs += 60 * ptm->tm_min;
3625 secs += SECS_PER_HOUR * ptm->tm_hour;
3627 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3628 /* got negative remainder, but need positive time */
3629 /* back off an extra day to compensate */
3630 yearday += (secs/SECS_PER_DAY)-1;
3631 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3634 yearday += (secs/SECS_PER_DAY);
3635 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3638 else if (secs >= SECS_PER_DAY) {
3639 yearday += (secs/SECS_PER_DAY);
3640 secs %= SECS_PER_DAY;
3642 ptm->tm_hour = secs/SECS_PER_HOUR;
3643 secs %= SECS_PER_HOUR;
3644 ptm->tm_min = secs/60;
3646 ptm->tm_sec += secs;
3647 /* done with time of day effects */
3649 * The algorithm for yearday has (so far) left it high by 428.
3650 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3651 * bias it by 123 while trying to figure out what year it
3652 * really represents. Even with this tweak, the reverse
3653 * translation fails for years before A.D. 0001.
3654 * It would still fail for Feb 29, but we catch that one below.
3656 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3657 yearday -= YEAR_ADJUST;
3658 year = (yearday / DAYS_PER_QCENT) * 400;
3659 yearday %= DAYS_PER_QCENT;
3660 odd_cent = yearday / DAYS_PER_CENT;
3661 year += odd_cent * 100;
3662 yearday %= DAYS_PER_CENT;
3663 year += (yearday / DAYS_PER_QYEAR) * 4;
3664 yearday %= DAYS_PER_QYEAR;
3665 odd_year = yearday / DAYS_PER_YEAR;
3667 yearday %= DAYS_PER_YEAR;
3668 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3673 yearday += YEAR_ADJUST; /* recover March 1st crock */
3674 month = yearday*DAYS_TO_MONTH;
3675 yearday -= month*MONTH_TO_DAYS;
3676 /* recover other leap-year adjustment */
3685 ptm->tm_year = year - 1900;
3687 ptm->tm_mday = yearday;
3688 ptm->tm_mon = month;
3692 ptm->tm_mon = month - 1;
3694 /* re-build yearday based on Jan 1 to get tm_yday */
3696 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3697 yearday += 14*MONTH_TO_DAYS + 1;
3698 ptm->tm_yday = jday - yearday;
3699 /* fix tm_wday if not overridden by caller */
3700 if ((unsigned)ptm->tm_wday > 6)
3701 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3705 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)
3713 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3716 mytm.tm_hour = hour;
3717 mytm.tm_mday = mday;
3719 mytm.tm_year = year;
3720 mytm.tm_wday = wday;
3721 mytm.tm_yday = yday;
3722 mytm.tm_isdst = isdst;
3724 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3725 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3730 #ifdef HAS_TM_TM_GMTOFF
3731 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3733 #ifdef HAS_TM_TM_ZONE
3734 mytm.tm_zone = mytm2.tm_zone;
3739 Newx(buf, buflen, char);
3740 len = strftime(buf, buflen, fmt, &mytm);
3742 ** The following is needed to handle to the situation where
3743 ** tmpbuf overflows. Basically we want to allocate a buffer
3744 ** and try repeatedly. The reason why it is so complicated
3745 ** is that getting a return value of 0 from strftime can indicate
3746 ** one of the following:
3747 ** 1. buffer overflowed,
3748 ** 2. illegal conversion specifier, or
3749 ** 3. the format string specifies nothing to be returned(not
3750 ** an error). This could be because format is an empty string
3751 ** or it specifies %p that yields an empty string in some locale.
3752 ** If there is a better way to make it portable, go ahead by
3755 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3758 /* Possibly buf overflowed - try again with a bigger buf */
3759 const int fmtlen = strlen(fmt);
3760 const int bufsize = fmtlen + buflen;
3762 Newx(buf, bufsize, char);
3764 buflen = strftime(buf, bufsize, fmt, &mytm);
3765 if (buflen > 0 && buflen < bufsize)
3767 /* heuristic to prevent out-of-memory errors */
3768 if (bufsize > 100*fmtlen) {
3773 Renew(buf, bufsize*2, char);
3778 Perl_croak(aTHX_ "panic: no strftime");
3784 #define SV_CWD_RETURN_UNDEF \
3785 sv_setsv(sv, &PL_sv_undef); \
3788 #define SV_CWD_ISDOT(dp) \
3789 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3790 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3793 =head1 Miscellaneous Functions
3795 =for apidoc getcwd_sv
3797 Fill the sv with current working directory
3802 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3803 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3804 * getcwd(3) if available
3805 * Comments from the orignal:
3806 * This is a faster version of getcwd. It's also more dangerous
3807 * because you might chdir out of a directory that you can't chdir
3811 Perl_getcwd_sv(pTHX_ register SV *sv)
3815 #ifndef INCOMPLETE_TAINTS
3821 char buf[MAXPATHLEN];
3823 /* Some getcwd()s automatically allocate a buffer of the given
3824 * size from the heap if they are given a NULL buffer pointer.
3825 * The problem is that this behaviour is not portable. */
3826 if (getcwd(buf, sizeof(buf) - 1)) {
3831 sv_setsv(sv, &PL_sv_undef);
3839 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3843 SvUPGRADE(sv, SVt_PV);
3845 if (PerlLIO_lstat(".", &statbuf) < 0) {
3846 SV_CWD_RETURN_UNDEF;
3849 orig_cdev = statbuf.st_dev;
3850 orig_cino = statbuf.st_ino;
3859 if (PerlDir_chdir("..") < 0) {
3860 SV_CWD_RETURN_UNDEF;
3862 if (PerlLIO_stat(".", &statbuf) < 0) {
3863 SV_CWD_RETURN_UNDEF;
3866 cdev = statbuf.st_dev;
3867 cino = statbuf.st_ino;
3869 if (odev == cdev && oino == cino) {
3872 if (!(dir = PerlDir_open("."))) {
3873 SV_CWD_RETURN_UNDEF;
3876 while ((dp = PerlDir_read(dir)) != NULL) {
3878 const int namelen = dp->d_namlen;
3880 const int namelen = strlen(dp->d_name);
3883 if (SV_CWD_ISDOT(dp)) {
3887 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3888 SV_CWD_RETURN_UNDEF;
3891 tdev = statbuf.st_dev;
3892 tino = statbuf.st_ino;
3893 if (tino == oino && tdev == odev) {
3899 SV_CWD_RETURN_UNDEF;
3902 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3903 SV_CWD_RETURN_UNDEF;
3906 SvGROW(sv, pathlen + namelen + 1);
3910 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3913 /* prepend current directory to the front */
3915 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3916 pathlen += (namelen + 1);
3918 #ifdef VOID_CLOSEDIR
3921 if (PerlDir_close(dir) < 0) {
3922 SV_CWD_RETURN_UNDEF;
3928 SvCUR_set(sv, pathlen);
3932 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3933 SV_CWD_RETURN_UNDEF;
3936 if (PerlLIO_stat(".", &statbuf) < 0) {
3937 SV_CWD_RETURN_UNDEF;
3940 cdev = statbuf.st_dev;
3941 cino = statbuf.st_ino;
3943 if (cdev != orig_cdev || cino != orig_cino) {
3944 Perl_croak(aTHX_ "Unstable directory path, "
3945 "current directory changed unexpectedly");
3957 =for apidoc scan_version
3959 Returns a pointer to the next character after the parsed
3960 version string, as well as upgrading the passed in SV to
3963 Function must be called with an already existing SV like
3966 s = scan_version(s,SV *sv, bool qv);
3968 Performs some preprocessing to the string to ensure that
3969 it has the correct characteristics of a version. Flags the
3970 object if it contains an underscore (which denotes this
3971 is a alpha version). The boolean qv denotes that the version
3972 should be interpreted as if it had multiple decimals, even if
3979 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
3987 AV * const av = newAV();
3988 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3989 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
3991 #ifndef NODEFAULT_SHAREKEYS
3992 HvSHAREKEYS_on(hv); /* key-sharing on by default */
3995 while (isSPACE(*s)) /* leading whitespace is OK */
3999 s++; /* get past 'v' */
4000 qv = 1; /* force quoted version processing */
4003 start = last = pos = s;
4005 /* pre-scan the input string to check for decimals/underbars */
4006 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4011 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4015 else if ( *pos == '_' )
4018 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4020 width = pos - last - 1; /* natural width of sub-version */
4025 if ( saw_period > 1 )
4026 qv = 1; /* force quoted version processing */
4031 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4033 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4034 if ( !qv && width < 3 )
4035 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4037 while (isDIGIT(*pos))
4039 if (!isALPHA(*pos)) {
4045 /* this is atoi() that delimits on underscores */
4046 const char *end = pos;
4050 /* the following if() will only be true after the decimal
4051 * point of a version originally created with a bare
4052 * floating point number, i.e. not quoted in any way
4054 if ( !qv && s > start && saw_period == 1 ) {
4058 rev += (*s - '0') * mult;
4060 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4061 Perl_croak(aTHX_ "Integer overflow in version");
4068 while (--end >= s) {
4070 rev += (*end - '0') * mult;
4072 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4073 Perl_croak(aTHX_ "Integer overflow in version");
4078 /* Append revision */
4079 av_push(av, newSViv(rev));
4080 if ( *pos == '.' && isDIGIT(pos[1]) )
4082 else if ( *pos == '_' && isDIGIT(pos[1]) )
4084 else if ( isDIGIT(*pos) )
4091 while ( isDIGIT(*pos) )
4096 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4104 if ( qv ) { /* quoted versions always get at least three terms*/
4105 I32 len = av_len(av);
4106 /* This for loop appears to trigger a compiler bug on OS X, as it
4107 loops infinitely. Yes, len is negative. No, it makes no sense.
4108 Compiler in question is:
4109 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4110 for ( len = 2 - len; len > 0; len-- )
4111 av_push((AV *)sv, newSViv(0));
4115 av_push(av, newSViv(0));
4118 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4119 av_push(av, newSViv(0));
4121 /* And finally, store the AV in the hash */
4122 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4127 =for apidoc new_version
4129 Returns a new version object based on the passed in SV:
4131 SV *sv = new_version(SV *ver);
4133 Does not alter the passed in ver SV. See "upg_version" if you
4134 want to upgrade the SV.
4140 Perl_new_version(pTHX_ SV *ver)
4142 SV * const rv = newSV(0);
4143 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4146 AV * const av = newAV();
4148 /* This will get reblessed later if a derived class*/
4149 SV * const hv = newSVrv(rv, "version");
4150 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4151 #ifndef NODEFAULT_SHAREKEYS
4152 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4158 /* Begin copying all of the elements */
4159 if ( hv_exists((HV *)ver, "qv", 2) )
4160 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4162 if ( hv_exists((HV *)ver, "alpha", 5) )
4163 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4165 if ( hv_exists((HV*)ver, "width", 5 ) )
4167 const I32 width = SvIV(*hv_fetch((HV*)ver, "width", 5, FALSE));
4168 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4171 sav = (AV *)SvRV(*hv_fetch((HV*)ver, "version", 7, FALSE));
4172 /* This will get reblessed later if a derived class*/
4173 for ( key = 0; key <= av_len(sav); key++ )
4175 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4176 av_push(av, newSViv(rev));
4179 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4183 if ( SvVOK(ver) ) { /* already a v-string */
4184 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4185 const STRLEN len = mg->mg_len;
4186 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4187 sv_setpvn(rv,version,len);
4192 sv_setsv(rv,ver); /* make a duplicate */
4201 =for apidoc upg_version
4203 In-place upgrade of the supplied SV to a version object.
4205 SV *sv = upg_version(SV *sv);
4207 Returns a pointer to the upgraded SV.
4213 Perl_upg_version(pTHX_ SV *ver)
4218 if ( SvNOK(ver) ) /* may get too much accuracy */
4221 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4222 version = savepvn(tbuf, len);
4225 else if ( SvVOK(ver) ) { /* already a v-string */
4226 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4227 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4231 else /* must be a string or something like a string */
4233 version = savepv(SvPV_nolen(ver));
4235 (void)scan_version(version, ver, qv);
4243 Validates that the SV contains a valid version object.
4245 bool vverify(SV *vobj);
4247 Note that it only confirms the bare minimum structure (so as not to get
4248 confused by derived classes which may contain additional hash entries):
4252 =item * The SV contains a [reference to a] hash
4254 =item * The hash contains a "version" key
4256 =item * The "version" key has [a reference to] an AV as its value
4264 Perl_vverify(pTHX_ SV *vs)
4270 /* see if the appropriate elements exist */
4271 if ( SvTYPE(vs) == SVt_PVHV
4272 && hv_exists((HV*)vs, "version", 7)
4273 && (sv = SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)))
4274 && SvTYPE(sv) == SVt_PVAV )
4283 Accepts a version object and returns the normalized floating
4284 point representation. Call like:
4288 NOTE: you can pass either the object directly or the SV
4289 contained within the RV.
4295 Perl_vnumify(pTHX_ SV *vs)
4300 SV * const sv = newSV(0);
4306 Perl_croak(aTHX_ "Invalid version object");
4308 /* see if various flags exist */
4309 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4311 if ( hv_exists((HV*)vs, "width", 5 ) )
4312 width = SvIV(*hv_fetch((HV*)vs, "width", 5, FALSE));
4317 /* attempt to retrieve the version array */
4318 if ( !(av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)) ) ) {
4319 sv_catpvn(sv,"0",1);
4326 sv_catpvn(sv,"0",1);
4330 digit = SvIV(*av_fetch(av, 0, 0));
4331 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4332 for ( i = 1 ; i < len ; i++ )
4334 digit = SvIV(*av_fetch(av, i, 0));
4336 const int denom = (width == 2 ? 10 : 100);
4337 const div_t term = div((int)PERL_ABS(digit),denom);
4338 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4341 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4347 digit = SvIV(*av_fetch(av, len, 0));
4348 if ( alpha && width == 3 ) /* alpha version */
4349 sv_catpvn(sv,"_",1);
4350 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4354 sv_catpvn(sv,"000",3);
4362 Accepts a version object and returns the normalized string
4363 representation. Call like:
4367 NOTE: you can pass either the object directly or the SV
4368 contained within the RV.
4374 Perl_vnormal(pTHX_ SV *vs)
4378 SV * const sv = newSV(0);
4384 Perl_croak(aTHX_ "Invalid version object");
4386 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4388 av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE));
4396 digit = SvIV(*av_fetch(av, 0, 0));
4397 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4398 for ( i = 1 ; i < len ; i++ ) {
4399 digit = SvIV(*av_fetch(av, i, 0));
4400 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4405 /* handle last digit specially */
4406 digit = SvIV(*av_fetch(av, len, 0));
4408 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4410 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4413 if ( len <= 2 ) { /* short version, must be at least three */
4414 for ( len = 2 - len; len != 0; len-- )
4415 sv_catpvn(sv,".0",2);
4421 =for apidoc vstringify
4423 In order to maintain maximum compatibility with earlier versions
4424 of Perl, this function will return either the floating point
4425 notation or the multiple dotted notation, depending on whether
4426 the original version contained 1 or more dots, respectively
4432 Perl_vstringify(pTHX_ SV *vs)
4438 Perl_croak(aTHX_ "Invalid version object");
4440 if ( hv_exists((HV *)vs, "qv", 2) )
4449 Version object aware cmp. Both operands must already have been
4450 converted into version objects.
4456 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4459 bool lalpha = FALSE;
4460 bool ralpha = FALSE;
4469 if ( !vverify(lhv) )
4470 Perl_croak(aTHX_ "Invalid version object");
4472 if ( !vverify(rhv) )
4473 Perl_croak(aTHX_ "Invalid version object");
4475 /* get the left hand term */
4476 lav = (AV *)SvRV(*hv_fetch((HV*)lhv, "version", 7, FALSE));
4477 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4480 /* and the right hand term */
4481 rav = (AV *)SvRV(*hv_fetch((HV*)rhv, "version", 7, FALSE));
4482 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4490 while ( i <= m && retval == 0 )
4492 left = SvIV(*av_fetch(lav,i,0));
4493 right = SvIV(*av_fetch(rav,i,0));
4501 /* tiebreaker for alpha with identical terms */
4502 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4504 if ( lalpha && !ralpha )
4508 else if ( ralpha && !lalpha)
4514 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4518 while ( i <= r && retval == 0 )
4520 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4521 retval = -1; /* not a match after all */
4527 while ( i <= l && retval == 0 )
4529 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4530 retval = +1; /* not a match after all */
4538 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4539 # define EMULATE_SOCKETPAIR_UDP
4542 #ifdef EMULATE_SOCKETPAIR_UDP
4544 S_socketpair_udp (int fd[2]) {
4546 /* Fake a datagram socketpair using UDP to localhost. */
4547 int sockets[2] = {-1, -1};
4548 struct sockaddr_in addresses[2];
4550 Sock_size_t size = sizeof(struct sockaddr_in);
4551 unsigned short port;
4554 memset(&addresses, 0, sizeof(addresses));
4557 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4558 if (sockets[i] == -1)
4559 goto tidy_up_and_fail;
4561 addresses[i].sin_family = AF_INET;
4562 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4563 addresses[i].sin_port = 0; /* kernel choses port. */
4564 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4565 sizeof(struct sockaddr_in)) == -1)
4566 goto tidy_up_and_fail;
4569 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4570 for each connect the other socket to it. */
4573 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4575 goto tidy_up_and_fail;
4576 if (size != sizeof(struct sockaddr_in))
4577 goto abort_tidy_up_and_fail;
4578 /* !1 is 0, !0 is 1 */
4579 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4580 sizeof(struct sockaddr_in)) == -1)
4581 goto tidy_up_and_fail;
4584 /* Now we have 2 sockets connected to each other. I don't trust some other
4585 process not to have already sent a packet to us (by random) so send
4586 a packet from each to the other. */
4589 /* I'm going to send my own port number. As a short.
4590 (Who knows if someone somewhere has sin_port as a bitfield and needs
4591 this routine. (I'm assuming crays have socketpair)) */
4592 port = addresses[i].sin_port;
4593 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4594 if (got != sizeof(port)) {
4596 goto tidy_up_and_fail;
4597 goto abort_tidy_up_and_fail;
4601 /* Packets sent. I don't trust them to have arrived though.
4602 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4603 connect to localhost will use a second kernel thread. In 2.6 the
4604 first thread running the connect() returns before the second completes,
4605 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4606 returns 0. Poor programs have tripped up. One poor program's authors'
4607 had a 50-1 reverse stock split. Not sure how connected these were.)
4608 So I don't trust someone not to have an unpredictable UDP stack.
4612 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4613 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4617 FD_SET(sockets[0], &rset);
4618 FD_SET(sockets[1], &rset);
4620 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4621 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4622 || !FD_ISSET(sockets[1], &rset)) {
4623 /* I hope this is portable and appropriate. */
4625 goto tidy_up_and_fail;
4626 goto abort_tidy_up_and_fail;
4630 /* And the paranoia department even now doesn't trust it to have arrive
4631 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4633 struct sockaddr_in readfrom;
4634 unsigned short buffer[2];
4639 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4640 sizeof(buffer), MSG_DONTWAIT,
4641 (struct sockaddr *) &readfrom, &size);
4643 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4645 (struct sockaddr *) &readfrom, &size);
4649 goto tidy_up_and_fail;
4650 if (got != sizeof(port)
4651 || size != sizeof(struct sockaddr_in)
4652 /* Check other socket sent us its port. */
4653 || buffer[0] != (unsigned short) addresses[!i].sin_port
4654 /* Check kernel says we got the datagram from that socket */
4655 || readfrom.sin_family != addresses[!i].sin_family
4656 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4657 || readfrom.sin_port != addresses[!i].sin_port)
4658 goto abort_tidy_up_and_fail;
4661 /* My caller (my_socketpair) has validated that this is non-NULL */
4664 /* I hereby declare this connection open. May God bless all who cross
4668 abort_tidy_up_and_fail:
4669 errno = ECONNABORTED;
4672 const int save_errno = errno;
4673 if (sockets[0] != -1)
4674 PerlLIO_close(sockets[0]);
4675 if (sockets[1] != -1)
4676 PerlLIO_close(sockets[1]);
4681 #endif /* EMULATE_SOCKETPAIR_UDP */
4683 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4685 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4686 /* Stevens says that family must be AF_LOCAL, protocol 0.
4687 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4692 struct sockaddr_in listen_addr;
4693 struct sockaddr_in connect_addr;
4698 || family != AF_UNIX
4701 errno = EAFNOSUPPORT;
4709 #ifdef EMULATE_SOCKETPAIR_UDP
4710 if (type == SOCK_DGRAM)
4711 return S_socketpair_udp(fd);
4714 listener = PerlSock_socket(AF_INET, type, 0);
4717 memset(&listen_addr, 0, sizeof(listen_addr));
4718 listen_addr.sin_family = AF_INET;
4719 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4720 listen_addr.sin_port = 0; /* kernel choses port. */
4721 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4722 sizeof(listen_addr)) == -1)
4723 goto tidy_up_and_fail;
4724 if (PerlSock_listen(listener, 1) == -1)
4725 goto tidy_up_and_fail;
4727 connector = PerlSock_socket(AF_INET, type, 0);
4728 if (connector == -1)
4729 goto tidy_up_and_fail;
4730 /* We want to find out the port number to connect to. */
4731 size = sizeof(connect_addr);
4732 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4734 goto tidy_up_and_fail;
4735 if (size != sizeof(connect_addr))
4736 goto abort_tidy_up_and_fail;
4737 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4738 sizeof(connect_addr)) == -1)
4739 goto tidy_up_and_fail;
4741 size = sizeof(listen_addr);
4742 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4745 goto tidy_up_and_fail;
4746 if (size != sizeof(listen_addr))
4747 goto abort_tidy_up_and_fail;
4748 PerlLIO_close(listener);
4749 /* Now check we are talking to ourself by matching port and host on the
4751 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4753 goto tidy_up_and_fail;
4754 if (size != sizeof(connect_addr)
4755 || listen_addr.sin_family != connect_addr.sin_family
4756 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4757 || listen_addr.sin_port != connect_addr.sin_port) {
4758 goto abort_tidy_up_and_fail;
4764 abort_tidy_up_and_fail:
4766 errno = ECONNABORTED; /* This would be the standard thing to do. */
4768 # ifdef ECONNREFUSED
4769 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4771 errno = ETIMEDOUT; /* Desperation time. */
4776 const int save_errno = errno;
4778 PerlLIO_close(listener);
4779 if (connector != -1)
4780 PerlLIO_close(connector);
4782 PerlLIO_close(acceptor);
4788 /* In any case have a stub so that there's code corresponding
4789 * to the my_socketpair in global.sym. */
4791 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4792 #ifdef HAS_SOCKETPAIR
4793 return socketpair(family, type, protocol, fd);
4802 =for apidoc sv_nosharing
4804 Dummy routine which "shares" an SV when there is no sharing module present.
4805 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4806 Exists to avoid test for a NULL function pointer and because it could
4807 potentially warn under some level of strict-ness.
4813 Perl_sv_nosharing(pTHX_ SV *sv)
4815 PERL_UNUSED_ARG(sv);
4819 Perl_parse_unicode_opts(pTHX_ const char **popt)
4821 const char *p = *popt;
4826 opt = (U32) atoi(p);
4827 while (isDIGIT(*p)) p++;
4828 if (*p && *p != '\n' && *p != '\r')
4829 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4834 case PERL_UNICODE_STDIN:
4835 opt |= PERL_UNICODE_STDIN_FLAG; break;
4836 case PERL_UNICODE_STDOUT:
4837 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4838 case PERL_UNICODE_STDERR:
4839 opt |= PERL_UNICODE_STDERR_FLAG; break;
4840 case PERL_UNICODE_STD:
4841 opt |= PERL_UNICODE_STD_FLAG; break;
4842 case PERL_UNICODE_IN:
4843 opt |= PERL_UNICODE_IN_FLAG; break;
4844 case PERL_UNICODE_OUT:
4845 opt |= PERL_UNICODE_OUT_FLAG; break;
4846 case PERL_UNICODE_INOUT:
4847 opt |= PERL_UNICODE_INOUT_FLAG; break;
4848 case PERL_UNICODE_LOCALE:
4849 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4850 case PERL_UNICODE_ARGV:
4851 opt |= PERL_UNICODE_ARGV_FLAG; break;
4853 if (*p != '\n' && *p != '\r')
4855 "Unknown Unicode option letter '%c'", *p);
4861 opt = PERL_UNICODE_DEFAULT_FLAGS;
4863 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4864 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4865 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4876 * This is really just a quick hack which grabs various garbage
4877 * values. It really should be a real hash algorithm which
4878 * spreads the effect of every input bit onto every output bit,
4879 * if someone who knows about such things would bother to write it.
4880 * Might be a good idea to add that function to CORE as well.
4881 * No numbers below come from careful analysis or anything here,
4882 * except they are primes and SEED_C1 > 1E6 to get a full-width
4883 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4884 * probably be bigger too.
4887 # define SEED_C1 1000003
4888 #define SEED_C4 73819
4890 # define SEED_C1 25747
4891 #define SEED_C4 20639
4895 #define SEED_C5 26107
4897 #ifndef PERL_NO_DEV_RANDOM
4902 # include <starlet.h>
4903 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4904 * in 100-ns units, typically incremented ever 10 ms. */
4905 unsigned int when[2];
4907 # ifdef HAS_GETTIMEOFDAY
4908 struct timeval when;
4914 /* This test is an escape hatch, this symbol isn't set by Configure. */
4915 #ifndef PERL_NO_DEV_RANDOM
4916 #ifndef PERL_RANDOM_DEVICE
4917 /* /dev/random isn't used by default because reads from it will block
4918 * if there isn't enough entropy available. You can compile with
4919 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4920 * is enough real entropy to fill the seed. */
4921 # define PERL_RANDOM_DEVICE "/dev/urandom"
4923 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4925 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4934 _ckvmssts(sys$gettim(when));
4935 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4937 # ifdef HAS_GETTIMEOFDAY
4938 PerlProc_gettimeofday(&when,NULL);
4939 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4942 u = (U32)SEED_C1 * when;
4945 u += SEED_C3 * (U32)PerlProc_getpid();
4946 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4947 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4948 u += SEED_C5 * (U32)PTR2UV(&when);
4954 Perl_get_hash_seed(pTHX)
4956 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4960 while (isSPACE(*s)) s++;
4961 if (s && isDIGIT(*s))
4962 myseed = (UV)Atoul(s);
4964 #ifdef USE_HASH_SEED_EXPLICIT
4968 /* Compute a random seed */
4969 (void)seedDrand01((Rand_seed_t)seed());
4970 myseed = (UV)(Drand01() * (NV)UV_MAX);
4971 #if RANDBITS < (UVSIZE * 8)
4972 /* Since there are not enough randbits to to reach all
4973 * the bits of a UV, the low bits might need extra
4974 * help. Sum in another random number that will
4975 * fill in the low bits. */
4977 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4978 #endif /* RANDBITS < (UVSIZE * 8) */
4979 if (myseed == 0) { /* Superparanoia. */
4980 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4982 Perl_croak(aTHX_ "Your random numbers are not that random");
4985 PL_rehash_seed_set = TRUE;
4992 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
4994 const char * const stashpv = CopSTASHPV(c);
4995 const char * const name = HvNAME_get(hv);
4997 if (stashpv == name)
4999 if (stashpv && name)
5000 if (strEQ(stashpv, name))
5007 #ifdef PERL_GLOBAL_STRUCT
5010 Perl_init_global_struct(pTHX)
5012 struct perl_vars *plvarsp = NULL;
5013 #ifdef PERL_GLOBAL_STRUCT
5014 # define PERL_GLOBAL_STRUCT_INIT
5015 # include "opcode.h" /* the ppaddr and check */
5016 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5017 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5018 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5019 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5020 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5024 plvarsp = PL_VarsPtr;
5025 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5031 # define PERLVAR(var,type) /**/
5032 # define PERLVARA(var,n,type) /**/
5033 # define PERLVARI(var,type,init) plvarsp->var = init;
5034 # define PERLVARIC(var,type,init) plvarsp->var = init;
5035 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5036 # include "perlvars.h"
5042 # ifdef PERL_GLOBAL_STRUCT
5043 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5044 if (!plvarsp->Gppaddr)
5046 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5047 if (!plvarsp->Gcheck)
5049 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5050 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5052 # ifdef PERL_SET_VARS
5053 PERL_SET_VARS(plvarsp);
5055 # undef PERL_GLOBAL_STRUCT_INIT
5060 #endif /* PERL_GLOBAL_STRUCT */
5062 #ifdef PERL_GLOBAL_STRUCT
5065 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5067 #ifdef PERL_GLOBAL_STRUCT
5068 # ifdef PERL_UNSET_VARS
5069 PERL_UNSET_VARS(plvarsp);
5071 free(plvarsp->Gppaddr);
5072 free(plvarsp->Gcheck);
5073 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5079 #endif /* PERL_GLOBAL_STRUCT */
5083 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5086 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)
5088 #ifdef PERL_MEM_LOG_STDERR
5089 /* We can't use PerlIO for obvious reasons. */
5090 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5091 const STRLEN len = my_sprintf(buf,
5092 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5093 " %s = %"IVdf": %"UVxf"\n",
5094 filename, linenumber, funcname, n, typesize,
5095 typename, n * typesize, PTR2UV(newalloc));
5096 PerlLIO_write(2, buf, len);
5102 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)
5104 #ifdef PERL_MEM_LOG_STDERR
5105 /* We can't use PerlIO for obvious reasons. */
5106 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5107 const STRLEN len = my_sprintf(buf, "realloc: %s:%d:%s: %"IVdf" %"UVuf
5108 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5109 filename, linenumber, funcname, n, typesize,
5110 typename, n * typesize, PTR2UV(oldalloc),
5112 PerlLIO_write(2, buf, len);
5118 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5120 #ifdef PERL_MEM_LOG_STDERR
5121 /* We can't use PerlIO for obvious reasons. */
5122 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5123 const STRLEN len = my_sprintf(buf, "free: %s:%d:%s: %"UVxf"\n",
5124 filename, linenumber, funcname,
5126 PerlLIO_write(2, buf, len);
5131 #endif /* PERL_MEM_LOG */
5134 =for apidoc my_sprintf
5136 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5137 the length of the string written to the buffer. Only rare pre-ANSI systems
5138 need the wrapper function - usually this is a direct call to C<sprintf>.
5142 #ifndef SPRINTF_RETURNS_STRLEN
5144 Perl_my_sprintf(char *buffer, const char* pat, ...)
5147 va_start(args, pat);
5148 vsprintf(buffer, pat, args);
5150 return strlen(buffer);
5155 Perl_my_clearenv(pTHX)
5158 #if ! defined(PERL_MICRO)
5159 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5161 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5162 # if defined(USE_ENVIRON_ARRAY)
5163 # if defined(USE_ITHREADS)
5164 /* only the parent thread can clobber the process environment */
5165 if (PL_curinterp == aTHX)
5166 # endif /* USE_ITHREADS */
5168 # if ! defined(PERL_USE_SAFE_PUTENV)
5169 if ( !PL_use_safe_putenv) {
5171 if (environ == PL_origenviron)
5172 environ = (char**)safesysmalloc(sizeof(char*));
5174 for (i = 0; environ[i]; i++)
5175 (void)safesysfree(environ[i]);
5178 # else /* PERL_USE_SAFE_PUTENV */
5179 # if defined(HAS_CLEARENV)
5181 # elif defined(HAS_UNSETENV)
5182 int bsiz = 80; /* Most envvar names will be shorter than this. */
5183 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
5184 while (*environ != NULL) {
5185 char *e = strchr(*environ, '=');
5186 int l = e ? e - *environ : strlen(*environ);
5188 (void)safesysfree(buf);
5190 buf = (char*)safesysmalloc(bsiz * sizeof(char));
5192 strncpy(buf, *environ, l);
5194 (void)unsetenv(buf);
5196 (void)safesysfree(buf);
5197 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5198 /* Just null environ and accept the leakage. */
5200 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5201 # endif /* ! PERL_USE_SAFE_PUTENV */
5203 # endif /* USE_ENVIRON_ARRAY */
5204 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5205 #endif /* PERL_MICRO */
5210 * c-indentation-style: bsd
5212 * indent-tabs-mode: t
5215 * ex: set ts=8 sts=4 sw=4 noet: