3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content." --Gandalf
16 /* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
23 #define PERL_IN_UTIL_C
29 # define SIG_ERR ((Sighandler_t) -1)
34 /* Missing protos on LynxOS */
39 # include <sys/wait.h>
44 # include <sys/select.h>
50 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51 # define FD_CLOEXEC 1 /* NeXT needs this */
54 /* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
64 /* Can't use PerlIO to write as it allocates memory */
65 PerlLIO_write(PerlIO_fileno(Perl_error_log),
66 PL_no_mem, strlen(PL_no_mem));
68 NORETURN_FUNCTION_END;
71 /* paranoid version of system's malloc() */
74 Perl_safesysmalloc(MEM_SIZE size)
80 PerlIO_printf(Perl_error_log,
81 "Allocation too large: %lx\n", size) FLUSH;
84 #endif /* HAS_64K_LIMIT */
85 #ifdef PERL_TRACK_MEMPOOL
90 Perl_croak_nocontext("panic: malloc");
92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
93 PERL_ALLOC_CHECK(ptr);
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
96 #ifdef PERL_TRACK_MEMPOOL
97 struct perl_memory_debug_header *const header
98 = (struct perl_memory_debug_header *)ptr;
102 PoisonNew(((char *)ptr), size, char);
105 #ifdef PERL_TRACK_MEMPOOL
106 header->interpreter = aTHX;
107 /* Link us into the list. */
108 header->prev = &PL_memory_debug_header;
109 header->next = PL_memory_debug_header.next;
110 PL_memory_debug_header.next = header;
111 header->next->prev = header;
115 ptr = (Malloc_t)((char*)ptr+sTHX);
122 return write_no_mem();
127 /* paranoid version of system's realloc() */
130 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
134 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
135 Malloc_t PerlMem_realloc();
136 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
140 PerlIO_printf(Perl_error_log,
141 "Reallocation too large: %lx\n", size) FLUSH;
144 #endif /* HAS_64K_LIMIT */
151 return safesysmalloc(size);
152 #ifdef PERL_TRACK_MEMPOOL
153 where = (Malloc_t)((char*)where-sTHX);
156 struct perl_memory_debug_header *const header
157 = (struct perl_memory_debug_header *)where;
159 if (header->interpreter != aTHX) {
160 Perl_croak_nocontext("panic: realloc from wrong pool");
162 assert(header->next->prev == header);
163 assert(header->prev->next == header);
165 if (header->size > size) {
166 const MEM_SIZE freed_up = header->size - size;
167 char *start_of_freed = ((char *)where) + size;
168 PoisonFree(start_of_freed, freed_up, char);
176 Perl_croak_nocontext("panic: realloc");
178 ptr = (Malloc_t)PerlMem_realloc(where,size);
179 PERL_ALLOC_CHECK(ptr);
181 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
182 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
185 #ifdef PERL_TRACK_MEMPOOL
186 struct perl_memory_debug_header *const header
187 = (struct perl_memory_debug_header *)ptr;
190 if (header->size < size) {
191 const MEM_SIZE fresh = size - header->size;
192 char *start_of_fresh = ((char *)ptr) + size;
193 PoisonNew(start_of_fresh, fresh, char);
197 header->next->prev = header;
198 header->prev->next = header;
200 ptr = (Malloc_t)((char*)ptr+sTHX);
207 return write_no_mem();
212 /* safe version of system's free() */
215 Perl_safesysfree(Malloc_t where)
217 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
222 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
224 #ifdef PERL_TRACK_MEMPOOL
225 where = (Malloc_t)((char*)where-sTHX);
227 struct perl_memory_debug_header *const header
228 = (struct perl_memory_debug_header *)where;
230 if (header->interpreter != aTHX) {
231 Perl_croak_nocontext("panic: free from wrong pool");
234 Perl_croak_nocontext("panic: duplicate free");
236 if (!(header->next) || header->next->prev != header
237 || header->prev->next != header) {
238 Perl_croak_nocontext("panic: bad free");
240 /* Unlink us from the chain. */
241 header->next->prev = header->prev;
242 header->prev->next = header->next;
244 PoisonNew(where, header->size, char);
246 /* Trigger the duplicate free warning. */
254 /* safe version of system's calloc() */
257 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
263 if (size * count > 0xffff) {
264 PerlIO_printf(Perl_error_log,
265 "Allocation too large: %lx\n", size * count) FLUSH;
268 #endif /* HAS_64K_LIMIT */
270 if ((long)size < 0 || (long)count < 0)
271 Perl_croak_nocontext("panic: calloc");
274 #ifdef PERL_TRACK_MEMPOOL
277 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
278 PERL_ALLOC_CHECK(ptr);
279 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));
281 memset((void*)ptr, 0, size);
282 #ifdef PERL_TRACK_MEMPOOL
284 struct perl_memory_debug_header *const header
285 = (struct perl_memory_debug_header *)ptr;
287 header->interpreter = aTHX;
288 /* Link us into the list. */
289 header->prev = &PL_memory_debug_header;
290 header->next = PL_memory_debug_header.next;
291 PL_memory_debug_header.next = header;
292 header->next->prev = header;
296 ptr = (Malloc_t)((char*)ptr+sTHX);
303 return write_no_mem();
306 /* These must be defined when not using Perl's malloc for binary
311 Malloc_t Perl_malloc (MEM_SIZE nbytes)
314 return (Malloc_t)PerlMem_malloc(nbytes);
317 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
320 return (Malloc_t)PerlMem_calloc(elements, size);
323 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
326 return (Malloc_t)PerlMem_realloc(where, nbytes);
329 Free_t Perl_mfree (Malloc_t where)
337 /* copy a string up to some (non-backslashed) delimiter, if any */
340 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
345 for (tolen = 0; from < fromend; from++, tolen++) {
347 if (from[1] != delim) {
354 else if (*from == delim)
365 /* return ptr to little string in big string, NULL if not found */
366 /* This routine was donated by Corey Satten. */
369 Perl_instr(pTHX_ register const char *big, register const char *little)
380 register const char *s, *x;
383 for (x=big,s=little; *s; /**/ ) {
394 return (char*)(big-1);
399 /* same as instr but allow embedded nulls */
402 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
408 char first = *little++;
410 bigend -= lend - little;
412 while (big <= bigend) {
415 for (x=big,s=little; s < lend; x++,s++) {
419 return (char*)(big-1);
425 /* reverse of the above--find last substring */
428 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
430 register const char *bigbeg;
431 register const I32 first = *little;
432 register const char * const littleend = lend;
435 if (little >= littleend)
436 return (char*)bigend;
438 big = bigend - (littleend - little++);
439 while (big >= bigbeg) {
440 register const char *s, *x;
443 for (x=big+2,s=little; s < littleend; /**/ ) {
452 return (char*)(big+1);
457 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
459 /* As a space optimization, we do not compile tables for strings of length
460 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
461 special-cased in fbm_instr().
463 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
466 =head1 Miscellaneous Functions
468 =for apidoc fbm_compile
470 Analyses the string in order to make fast searches on it using fbm_instr()
471 -- the Boyer-Moore algorithm.
477 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
480 register const U8 *s;
486 if (flags & FBMcf_TAIL) {
487 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
488 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
489 if (mg && mg->mg_len >= 0)
492 s = (U8*)SvPV_force_mutable(sv, len);
493 if (len == 0) /* TAIL might be on a zero-length string. */
495 SvUPGRADE(sv, SVt_PVBM);
498 const unsigned char *sb;
499 const U8 mlen = (len>255) ? 255 : (U8)len;
502 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
503 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
504 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
505 memset((void*)table, mlen, 256);
506 table[-1] = (U8)flags;
508 sb = s - mlen + 1; /* first char (maybe) */
510 if (table[*s] == mlen)
515 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
518 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
519 for (i = 0; i < len; i++) {
520 if (PL_freq[s[i]] < frequency) {
522 frequency = PL_freq[s[i]];
525 BmRARE(sv) = s[rarest];
526 BmPREVIOUS(sv) = (U16)rarest;
527 BmUSEFUL(sv) = 100; /* Initial value */
528 if (flags & FBMcf_TAIL)
530 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
531 BmRARE(sv),BmPREVIOUS(sv)));
534 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
535 /* If SvTAIL is actually due to \Z or \z, this gives false positives
539 =for apidoc fbm_instr
541 Returns the location of the SV in the string delimited by C<str> and
542 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
543 does not have to be fbm_compiled, but the search will not be as fast
550 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
552 register unsigned char *s;
554 register const unsigned char *little
555 = (const unsigned char *)SvPV_const(littlestr,l);
556 register STRLEN littlelen = l;
557 register const I32 multiline = flags & FBMrf_MULTILINE;
559 if ((STRLEN)(bigend - big) < littlelen) {
560 if ( SvTAIL(littlestr)
561 && ((STRLEN)(bigend - big) == littlelen - 1)
563 || (*big == *little &&
564 memEQ((char *)big, (char *)little, littlelen - 1))))
569 if (littlelen <= 2) { /* Special-cased */
571 if (littlelen == 1) {
572 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
573 /* Know that bigend != big. */
574 if (bigend[-1] == '\n')
575 return (char *)(bigend - 1);
576 return (char *) bigend;
584 if (SvTAIL(littlestr))
585 return (char *) bigend;
589 return (char*)big; /* Cannot be SvTAIL! */
592 if (SvTAIL(littlestr) && !multiline) {
593 if (bigend[-1] == '\n' && bigend[-2] == *little)
594 return (char*)bigend - 2;
595 if (bigend[-1] == *little)
596 return (char*)bigend - 1;
600 /* This should be better than FBM if c1 == c2, and almost
601 as good otherwise: maybe better since we do less indirection.
602 And we save a lot of memory by caching no table. */
603 const unsigned char c1 = little[0];
604 const unsigned char c2 = little[1];
609 while (s <= bigend) {
619 goto check_1char_anchor;
630 goto check_1char_anchor;
633 while (s <= bigend) {
638 goto check_1char_anchor;
647 check_1char_anchor: /* One char and anchor! */
648 if (SvTAIL(littlestr) && (*bigend == *little))
649 return (char *)bigend; /* bigend is already decremented. */
652 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
653 s = bigend - littlelen;
654 if (s >= big && bigend[-1] == '\n' && *s == *little
655 /* Automatically of length > 2 */
656 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
658 return (char*)s; /* how sweet it is */
661 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
663 return (char*)s + 1; /* how sweet it is */
667 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
668 char * const b = ninstr((char*)big,(char*)bigend,
669 (char*)little, (char*)little + littlelen);
671 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
672 /* Chop \n from littlestr: */
673 s = bigend - littlelen + 1;
675 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
685 if (littlelen > (STRLEN)(bigend - big))
689 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
690 register const unsigned char *oldlittle;
692 --littlelen; /* Last char found by table lookup */
695 little += littlelen; /* last char */
701 if ((tmp = table[*s])) {
702 if ((s += tmp) < bigend)
706 else { /* less expensive than calling strncmp() */
707 register unsigned char * const olds = s;
712 if (*--s == *--little)
714 s = olds + 1; /* here we pay the price for failure */
716 if (s < bigend) /* fake up continue to outer loop */
724 if ( s == bigend && (table[-1] & FBMcf_TAIL)
725 && memEQ((char *)(bigend - littlelen),
726 (char *)(oldlittle - littlelen), littlelen) )
727 return (char*)bigend - littlelen;
732 /* start_shift, end_shift are positive quantities which give offsets
733 of ends of some substring of bigstr.
734 If "last" we want the last occurrence.
735 old_posp is the way of communication between consequent calls if
736 the next call needs to find the .
737 The initial *old_posp should be -1.
739 Note that we take into account SvTAIL, so one can get extra
740 optimizations if _ALL flag is set.
743 /* If SvTAIL is actually due to \Z or \z, this gives false positives
744 if PL_multiline. In fact if !PL_multiline the authoritative answer
745 is not supported yet. */
748 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
751 register const unsigned char *big;
753 register I32 previous;
755 register const unsigned char *little;
756 register I32 stop_pos;
757 register const unsigned char *littleend;
760 assert(SvTYPE(littlestr) == SVt_PVBM);
763 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
764 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
766 if ( BmRARE(littlestr) == '\n'
767 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
768 little = (const unsigned char *)(SvPVX_const(littlestr));
769 littleend = little + SvCUR(littlestr);
776 little = (const unsigned char *)(SvPVX_const(littlestr));
777 littleend = little + SvCUR(littlestr);
779 /* The value of pos we can start at: */
780 previous = BmPREVIOUS(littlestr);
781 big = (const unsigned char *)(SvPVX_const(bigstr));
782 /* The value of pos we can stop at: */
783 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
784 if (previous + start_shift > stop_pos) {
786 stop_pos does not include SvTAIL in the count, so this check is incorrect
787 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
790 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
795 while (pos < previous + start_shift) {
796 if (!(pos += PL_screamnext[pos]))
801 register const unsigned char *s, *x;
802 if (pos >= stop_pos) break;
803 if (big[pos] != first)
805 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
811 if (s == littleend) {
813 if (!last) return (char *)(big+pos);
816 } while ( pos += PL_screamnext[pos] );
818 return (char *)(big+(*old_posp));
820 if (!SvTAIL(littlestr) || (end_shift > 0))
822 /* Ignore the trailing "\n". This code is not microoptimized */
823 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
824 stop_pos = littleend - little; /* Actual littlestr len */
829 && ((stop_pos == 1) ||
830 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
836 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
838 register const U8 *a = (const U8 *)s1;
839 register const U8 *b = (const U8 *)s2;
843 if (*a != *b && *a != PL_fold[*b])
851 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
854 register const U8 *a = (const U8 *)s1;
855 register const U8 *b = (const U8 *)s2;
859 if (*a != *b && *a != PL_fold_locale[*b])
866 /* copy a string to a safe spot */
869 =head1 Memory Management
873 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
874 string which is a duplicate of C<pv>. The size of the string is
875 determined by C<strlen()>. The memory allocated for the new string can
876 be freed with the C<Safefree()> function.
882 Perl_savepv(pTHX_ const char *pv)
889 const STRLEN pvlen = strlen(pv)+1;
890 Newx(newaddr, pvlen, char);
891 return (char*)memcpy(newaddr, pv, pvlen);
895 /* same thing but with a known length */
900 Perl's version of what C<strndup()> would be if it existed. Returns a
901 pointer to a newly allocated string which is a duplicate of the first
902 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
903 the new string can be freed with the C<Safefree()> function.
909 Perl_savepvn(pTHX_ const char *pv, register I32 len)
911 register char *newaddr;
914 Newx(newaddr,len+1,char);
915 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
917 /* might not be null terminated */
919 return (char *) CopyD(pv,newaddr,len,char);
922 return (char *) ZeroD(newaddr,len+1,char);
927 =for apidoc savesharedpv
929 A version of C<savepv()> which allocates the duplicate string in memory
930 which is shared between threads.
935 Perl_savesharedpv(pTHX_ const char *pv)
937 register char *newaddr;
942 pvlen = strlen(pv)+1;
943 newaddr = (char*)PerlMemShared_malloc(pvlen);
945 return write_no_mem();
947 return (char*)memcpy(newaddr, pv, pvlen);
953 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
954 the passed in SV using C<SvPV()>
960 Perl_savesvpv(pTHX_ SV *sv)
963 const char * const pv = SvPV_const(sv, len);
964 register char *newaddr;
967 Newx(newaddr,len,char);
968 return (char *) CopyD(pv,newaddr,len,char);
972 /* the SV for Perl_form() and mess() is not kept in an arena */
982 return sv_2mortal(newSVpvs(""));
987 /* Create as PVMG now, to avoid any upgrading later */
989 Newxz(any, 1, XPVMG);
990 SvFLAGS(sv) = SVt_PVMG;
991 SvANY(sv) = (void*)any;
993 SvREFCNT(sv) = 1 << 30; /* practically infinite */
998 #if defined(PERL_IMPLICIT_CONTEXT)
1000 Perl_form_nocontext(const char* pat, ...)
1005 va_start(args, pat);
1006 retval = vform(pat, &args);
1010 #endif /* PERL_IMPLICIT_CONTEXT */
1013 =head1 Miscellaneous Functions
1016 Takes a sprintf-style format pattern and conventional
1017 (non-SV) arguments and returns the formatted string.
1019 (char *) Perl_form(pTHX_ const char* pat, ...)
1021 can be used any place a string (char *) is required:
1023 char * s = Perl_form("%d.%d",major,minor);
1025 Uses a single private buffer so if you want to format several strings you
1026 must explicitly copy the earlier strings away (and free the copies when you
1033 Perl_form(pTHX_ const char* pat, ...)
1037 va_start(args, pat);
1038 retval = vform(pat, &args);
1044 Perl_vform(pTHX_ const char *pat, va_list *args)
1046 SV * const sv = mess_alloc();
1047 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1051 #if defined(PERL_IMPLICIT_CONTEXT)
1053 Perl_mess_nocontext(const char *pat, ...)
1058 va_start(args, pat);
1059 retval = vmess(pat, &args);
1063 #endif /* PERL_IMPLICIT_CONTEXT */
1066 Perl_mess(pTHX_ const char *pat, ...)
1070 va_start(args, pat);
1071 retval = vmess(pat, &args);
1077 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1080 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1082 if (!o || o == PL_op)
1085 if (o->op_flags & OPf_KIDS) {
1087 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1090 /* If the OP_NEXTSTATE has been optimised away we can still use it
1091 * the get the file and line number. */
1093 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1094 cop = (const COP *)kid;
1096 /* Keep searching, and return when we've found something. */
1098 new_cop = closest_cop(cop, kid);
1104 /* Nothing found. */
1110 Perl_vmess(pTHX_ const char *pat, va_list *args)
1113 SV * const sv = mess_alloc();
1115 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1116 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1118 * Try and find the file and line for PL_op. This will usually be
1119 * PL_curcop, but it might be a cop that has been optimised away. We
1120 * can try to find such a cop by searching through the optree starting
1121 * from the sibling of PL_curcop.
1124 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1129 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1130 OutCopFILE(cop), (IV)CopLINE(cop));
1131 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1132 const bool line_mode = (RsSIMPLE(PL_rs) &&
1133 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1134 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1135 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1136 line_mode ? "line" : "chunk",
1137 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1140 sv_catpvs(sv, " during global destruction");
1141 sv_catpvs(sv, ".\n");
1147 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1153 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1154 && (io = GvIO(PL_stderrgv))
1155 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1162 SAVESPTR(PL_stderrgv);
1165 PUSHSTACKi(PERLSI_MAGIC);
1169 PUSHs(SvTIED_obj((SV*)io, mg));
1170 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1172 call_method("PRINT", G_SCALAR);
1180 /* SFIO can really mess with your errno */
1181 const int e = errno;
1183 PerlIO * const serr = Perl_error_log;
1185 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1186 (void)PerlIO_flush(serr);
1193 /* Common code used by vcroak, vdie, vwarn and vwarner */
1196 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1202 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1203 /* sv_2cv might call Perl_croak() or Perl_warner() */
1204 SV * const oldhook = *hook;
1211 cv = sv_2cv(oldhook, &stash, &gv, 0);
1213 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1223 if (warn || message) {
1224 msg = newSVpvn(message, msglen);
1225 SvFLAGS(msg) |= utf8;
1233 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1237 call_sv((SV*)cv, G_DISCARD);
1246 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1250 const char *message;
1253 SV * const msv = vmess(pat, args);
1254 if (PL_errors && SvCUR(PL_errors)) {
1255 sv_catsv(PL_errors, msv);
1256 message = SvPV_const(PL_errors, *msglen);
1257 SvCUR_set(PL_errors, 0);
1260 message = SvPV_const(msv,*msglen);
1261 *utf8 = SvUTF8(msv);
1267 DEBUG_S(PerlIO_printf(Perl_debug_log,
1268 "%p: die/croak: message = %s\ndiehook = %p\n",
1269 thr, message, PL_diehook));
1271 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1277 Perl_vdie(pTHX_ const char* pat, va_list *args)
1280 const char *message;
1281 const int was_in_eval = PL_in_eval;
1285 DEBUG_S(PerlIO_printf(Perl_debug_log,
1286 "%p: die: curstack = %p, mainstack = %p\n",
1287 thr, PL_curstack, PL_mainstack));
1289 message = vdie_croak_common(pat, args, &msglen, &utf8);
1291 PL_restartop = die_where(message, msglen);
1292 SvFLAGS(ERRSV) |= utf8;
1293 DEBUG_S(PerlIO_printf(Perl_debug_log,
1294 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1295 thr, PL_restartop, was_in_eval, PL_top_env));
1296 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1298 return PL_restartop;
1301 #if defined(PERL_IMPLICIT_CONTEXT)
1303 Perl_die_nocontext(const char* pat, ...)
1308 va_start(args, pat);
1309 o = vdie(pat, &args);
1313 #endif /* PERL_IMPLICIT_CONTEXT */
1316 Perl_die(pTHX_ const char* pat, ...)
1320 va_start(args, pat);
1321 o = vdie(pat, &args);
1327 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1330 const char *message;
1334 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1337 PL_restartop = die_where(message, msglen);
1338 SvFLAGS(ERRSV) |= utf8;
1342 message = SvPVx_const(ERRSV, msglen);
1344 write_to_stderr(message, msglen);
1348 #if defined(PERL_IMPLICIT_CONTEXT)
1350 Perl_croak_nocontext(const char *pat, ...)
1354 va_start(args, pat);
1359 #endif /* PERL_IMPLICIT_CONTEXT */
1362 =head1 Warning and Dieing
1366 This is the XSUB-writer's interface to Perl's C<die> function.
1367 Normally call this function the same way you call the C C<printf>
1368 function. Calling C<croak> returns control directly to Perl,
1369 sidestepping the normal C order of execution. See C<warn>.
1371 If you want to throw an exception object, assign the object to
1372 C<$@> and then pass C<NULL> to croak():
1374 errsv = get_sv("@", TRUE);
1375 sv_setsv(errsv, exception_object);
1382 Perl_croak(pTHX_ const char *pat, ...)
1385 va_start(args, pat);
1392 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1396 SV * const msv = vmess(pat, args);
1397 const I32 utf8 = SvUTF8(msv);
1398 const char * const message = SvPV_const(msv, msglen);
1401 if (vdie_common(message, msglen, utf8, TRUE))
1405 write_to_stderr(message, msglen);
1408 #if defined(PERL_IMPLICIT_CONTEXT)
1410 Perl_warn_nocontext(const char *pat, ...)
1414 va_start(args, pat);
1418 #endif /* PERL_IMPLICIT_CONTEXT */
1423 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1424 function the same way you call the C C<printf> function. See C<croak>.
1430 Perl_warn(pTHX_ const char *pat, ...)
1433 va_start(args, pat);
1438 #if defined(PERL_IMPLICIT_CONTEXT)
1440 Perl_warner_nocontext(U32 err, const char *pat, ...)
1444 va_start(args, pat);
1445 vwarner(err, pat, &args);
1448 #endif /* PERL_IMPLICIT_CONTEXT */
1451 Perl_warner(pTHX_ U32 err, const char* pat,...)
1454 va_start(args, pat);
1455 vwarner(err, pat, &args);
1460 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1463 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1464 SV * const msv = vmess(pat, args);
1466 const char * const message = SvPV_const(msv, msglen);
1467 const I32 utf8 = SvUTF8(msv);
1471 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1474 PL_restartop = die_where(message, msglen);
1475 SvFLAGS(ERRSV) |= utf8;
1478 write_to_stderr(message, msglen);
1482 Perl_vwarn(aTHX_ pat, args);
1486 /* implements the ckWARN? macros */
1489 Perl_ckwarn(pTHX_ U32 w)
1495 && PL_curcop->cop_warnings != pWARN_NONE
1497 PL_curcop->cop_warnings == pWARN_ALL
1498 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1499 || (unpackWARN2(w) &&
1500 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1501 || (unpackWARN3(w) &&
1502 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1503 || (unpackWARN4(w) &&
1504 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1509 isLEXWARN_off && PL_dowarn & G_WARN_ON
1514 /* implements the ckWARN?_d macro */
1517 Perl_ckwarn_d(pTHX_ U32 w)
1522 || PL_curcop->cop_warnings == pWARN_ALL
1524 PL_curcop->cop_warnings != pWARN_NONE
1526 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1527 || (unpackWARN2(w) &&
1528 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1529 || (unpackWARN3(w) &&
1530 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1531 || (unpackWARN4(w) &&
1532 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1538 /* Set buffer=NULL to get a new one. */
1540 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1542 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1543 PERL_UNUSED_CONTEXT;
1546 (specialWARN(buffer) ?
1547 PerlMemShared_malloc(len_wanted) :
1548 PerlMemShared_realloc(buffer, len_wanted));
1550 Copy(bits, (buffer + 1), size, char);
1554 /* since we've already done strlen() for both nam and val
1555 * we can use that info to make things faster than
1556 * sprintf(s, "%s=%s", nam, val)
1558 #define my_setenv_format(s, nam, nlen, val, vlen) \
1559 Copy(nam, s, nlen, char); \
1561 Copy(val, s+(nlen+1), vlen, char); \
1562 *(s+(nlen+1+vlen)) = '\0'
1564 #ifdef USE_ENVIRON_ARRAY
1565 /* VMS' my_setenv() is in vms.c */
1566 #if !defined(WIN32) && !defined(NETWARE)
1568 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1572 /* only parent thread can modify process environment */
1573 if (PL_curinterp == aTHX)
1576 #ifndef PERL_USE_SAFE_PUTENV
1577 if (!PL_use_safe_putenv) {
1578 /* most putenv()s leak, so we manipulate environ directly */
1579 register I32 i=setenv_getix(nam); /* where does it go? */
1582 if (environ == PL_origenviron) { /* need we copy environment? */
1588 while (environ[max])
1590 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1591 for (j=0; j<max; j++) { /* copy environment */
1592 const int len = strlen(environ[j]);
1593 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1594 Copy(environ[j], tmpenv[j], len+1, char);
1597 environ = tmpenv; /* tell exec where it is now */
1600 safesysfree(environ[i]);
1601 while (environ[i]) {
1602 environ[i] = environ[i+1];
1607 if (!environ[i]) { /* does not exist yet */
1608 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1609 environ[i+1] = NULL; /* make sure it's null terminated */
1612 safesysfree(environ[i]);
1616 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1617 /* all that work just for this */
1618 my_setenv_format(environ[i], nam, nlen, val, vlen);
1621 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1622 # if defined(HAS_UNSETENV)
1624 (void)unsetenv(nam);
1626 (void)setenv(nam, val, 1);
1628 # else /* ! HAS_UNSETENV */
1629 (void)setenv(nam, val, 1);
1630 # endif /* HAS_UNSETENV */
1632 # if defined(HAS_UNSETENV)
1634 (void)unsetenv(nam);
1636 const int nlen = strlen(nam);
1637 const int vlen = strlen(val);
1638 char * const new_env =
1639 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1640 my_setenv_format(new_env, nam, nlen, val, vlen);
1641 (void)putenv(new_env);
1643 # else /* ! HAS_UNSETENV */
1645 const int nlen = strlen(nam);
1651 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1652 /* all that work just for this */
1653 my_setenv_format(new_env, nam, nlen, val, vlen);
1654 (void)putenv(new_env);
1655 # endif /* HAS_UNSETENV */
1656 # endif /* __CYGWIN__ */
1657 #ifndef PERL_USE_SAFE_PUTENV
1663 #else /* WIN32 || NETWARE */
1666 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1669 register char *envstr;
1670 const int nlen = strlen(nam);
1677 Newx(envstr, nlen+vlen+2, char);
1678 my_setenv_format(envstr, nam, nlen, val, vlen);
1679 (void)PerlEnv_putenv(envstr);
1683 #endif /* WIN32 || NETWARE */
1687 Perl_setenv_getix(pTHX_ const char *nam)
1690 register const I32 len = strlen(nam);
1691 PERL_UNUSED_CONTEXT;
1693 for (i = 0; environ[i]; i++) {
1696 strnicmp(environ[i],nam,len) == 0
1698 strnEQ(environ[i],nam,len)
1700 && environ[i][len] == '=')
1701 break; /* strnEQ must come first to avoid */
1702 } /* potential SEGV's */
1705 #endif /* !PERL_MICRO */
1707 #endif /* !VMS && !EPOC*/
1709 #ifdef UNLINK_ALL_VERSIONS
1711 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1715 while (PerlLIO_unlink(f) >= 0)
1717 return retries ? 0 : -1;
1721 /* this is a drop-in replacement for bcopy() */
1722 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1724 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1726 char * const retval = to;
1728 if (from - to >= 0) {
1736 *(--to) = *(--from);
1742 /* this is a drop-in replacement for memset() */
1745 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1747 char * const retval = loc;
1755 /* this is a drop-in replacement for bzero() */
1756 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1758 Perl_my_bzero(register char *loc, register I32 len)
1760 char * const retval = loc;
1768 /* this is a drop-in replacement for memcmp() */
1769 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1771 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1773 register const U8 *a = (const U8 *)s1;
1774 register const U8 *b = (const U8 *)s2;
1778 if ((tmp = *a++ - *b++))
1783 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1787 #ifdef USE_CHAR_VSPRINTF
1792 vsprintf(char *dest, const char *pat, char *args)
1796 fakebuf._ptr = dest;
1797 fakebuf._cnt = 32767;
1801 fakebuf._flag = _IOWRT|_IOSTRG;
1802 _doprnt(pat, args, &fakebuf); /* what a kludge */
1803 (void)putc('\0', &fakebuf);
1804 #ifdef USE_CHAR_VSPRINTF
1807 return 0; /* perl doesn't use return value */
1811 #endif /* HAS_VPRINTF */
1814 #if BYTEORDER != 0x4321
1816 Perl_my_swap(pTHX_ short s)
1818 #if (BYTEORDER & 1) == 0
1821 result = ((s & 255) << 8) + ((s >> 8) & 255);
1829 Perl_my_htonl(pTHX_ long l)
1833 char c[sizeof(long)];
1836 #if BYTEORDER == 0x1234
1837 u.c[0] = (l >> 24) & 255;
1838 u.c[1] = (l >> 16) & 255;
1839 u.c[2] = (l >> 8) & 255;
1843 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1844 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1849 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1850 u.c[o & 0xf] = (l >> s) & 255;
1858 Perl_my_ntohl(pTHX_ long l)
1862 char c[sizeof(long)];
1865 #if BYTEORDER == 0x1234
1866 u.c[0] = (l >> 24) & 255;
1867 u.c[1] = (l >> 16) & 255;
1868 u.c[2] = (l >> 8) & 255;
1872 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1873 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1880 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1881 l |= (u.c[o & 0xf] & 255) << s;
1888 #endif /* BYTEORDER != 0x4321 */
1892 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1893 * If these functions are defined,
1894 * the BYTEORDER is neither 0x1234 nor 0x4321.
1895 * However, this is not assumed.
1899 #define HTOLE(name,type) \
1901 name (register type n) \
1905 char c[sizeof(type)]; \
1908 register U32 s = 0; \
1909 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1910 u.c[i] = (n >> s) & 0xFF; \
1915 #define LETOH(name,type) \
1917 name (register type n) \
1921 char c[sizeof(type)]; \
1924 register U32 s = 0; \
1927 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1928 n |= ((type)(u.c[i] & 0xFF)) << s; \
1934 * Big-endian byte order functions.
1937 #define HTOBE(name,type) \
1939 name (register type n) \
1943 char c[sizeof(type)]; \
1946 register U32 s = 8*(sizeof(u.c)-1); \
1947 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1948 u.c[i] = (n >> s) & 0xFF; \
1953 #define BETOH(name,type) \
1955 name (register type n) \
1959 char c[sizeof(type)]; \
1962 register U32 s = 8*(sizeof(u.c)-1); \
1965 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1966 n |= ((type)(u.c[i] & 0xFF)) << s; \
1972 * If we just can't do it...
1975 #define NOT_AVAIL(name,type) \
1977 name (register type n) \
1979 Perl_croak_nocontext(#name "() not available"); \
1980 return n; /* not reached */ \
1984 #if defined(HAS_HTOVS) && !defined(htovs)
1987 #if defined(HAS_HTOVL) && !defined(htovl)
1990 #if defined(HAS_VTOHS) && !defined(vtohs)
1993 #if defined(HAS_VTOHL) && !defined(vtohl)
1997 #ifdef PERL_NEED_MY_HTOLE16
1999 HTOLE(Perl_my_htole16,U16)
2001 NOT_AVAIL(Perl_my_htole16,U16)
2004 #ifdef PERL_NEED_MY_LETOH16
2006 LETOH(Perl_my_letoh16,U16)
2008 NOT_AVAIL(Perl_my_letoh16,U16)
2011 #ifdef PERL_NEED_MY_HTOBE16
2013 HTOBE(Perl_my_htobe16,U16)
2015 NOT_AVAIL(Perl_my_htobe16,U16)
2018 #ifdef PERL_NEED_MY_BETOH16
2020 BETOH(Perl_my_betoh16,U16)
2022 NOT_AVAIL(Perl_my_betoh16,U16)
2026 #ifdef PERL_NEED_MY_HTOLE32
2028 HTOLE(Perl_my_htole32,U32)
2030 NOT_AVAIL(Perl_my_htole32,U32)
2033 #ifdef PERL_NEED_MY_LETOH32
2035 LETOH(Perl_my_letoh32,U32)
2037 NOT_AVAIL(Perl_my_letoh32,U32)
2040 #ifdef PERL_NEED_MY_HTOBE32
2042 HTOBE(Perl_my_htobe32,U32)
2044 NOT_AVAIL(Perl_my_htobe32,U32)
2047 #ifdef PERL_NEED_MY_BETOH32
2049 BETOH(Perl_my_betoh32,U32)
2051 NOT_AVAIL(Perl_my_betoh32,U32)
2055 #ifdef PERL_NEED_MY_HTOLE64
2057 HTOLE(Perl_my_htole64,U64)
2059 NOT_AVAIL(Perl_my_htole64,U64)
2062 #ifdef PERL_NEED_MY_LETOH64
2064 LETOH(Perl_my_letoh64,U64)
2066 NOT_AVAIL(Perl_my_letoh64,U64)
2069 #ifdef PERL_NEED_MY_HTOBE64
2071 HTOBE(Perl_my_htobe64,U64)
2073 NOT_AVAIL(Perl_my_htobe64,U64)
2076 #ifdef PERL_NEED_MY_BETOH64
2078 BETOH(Perl_my_betoh64,U64)
2080 NOT_AVAIL(Perl_my_betoh64,U64)
2084 #ifdef PERL_NEED_MY_HTOLES
2085 HTOLE(Perl_my_htoles,short)
2087 #ifdef PERL_NEED_MY_LETOHS
2088 LETOH(Perl_my_letohs,short)
2090 #ifdef PERL_NEED_MY_HTOBES
2091 HTOBE(Perl_my_htobes,short)
2093 #ifdef PERL_NEED_MY_BETOHS
2094 BETOH(Perl_my_betohs,short)
2097 #ifdef PERL_NEED_MY_HTOLEI
2098 HTOLE(Perl_my_htolei,int)
2100 #ifdef PERL_NEED_MY_LETOHI
2101 LETOH(Perl_my_letohi,int)
2103 #ifdef PERL_NEED_MY_HTOBEI
2104 HTOBE(Perl_my_htobei,int)
2106 #ifdef PERL_NEED_MY_BETOHI
2107 BETOH(Perl_my_betohi,int)
2110 #ifdef PERL_NEED_MY_HTOLEL
2111 HTOLE(Perl_my_htolel,long)
2113 #ifdef PERL_NEED_MY_LETOHL
2114 LETOH(Perl_my_letohl,long)
2116 #ifdef PERL_NEED_MY_HTOBEL
2117 HTOBE(Perl_my_htobel,long)
2119 #ifdef PERL_NEED_MY_BETOHL
2120 BETOH(Perl_my_betohl,long)
2124 Perl_my_swabn(void *ptr, int n)
2126 register char *s = (char *)ptr;
2127 register char *e = s + (n-1);
2130 for (n /= 2; n > 0; s++, e--, n--) {
2138 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2140 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2143 register I32 This, that;
2149 PERL_FLUSHALL_FOR_CHILD;
2150 This = (*mode == 'w');
2154 taint_proper("Insecure %s%s", "EXEC");
2156 if (PerlProc_pipe(p) < 0)
2158 /* Try for another pipe pair for error return */
2159 if (PerlProc_pipe(pp) >= 0)
2161 while ((pid = PerlProc_fork()) < 0) {
2162 if (errno != EAGAIN) {
2163 PerlLIO_close(p[This]);
2164 PerlLIO_close(p[that]);
2166 PerlLIO_close(pp[0]);
2167 PerlLIO_close(pp[1]);
2179 /* Close parent's end of error status pipe (if any) */
2181 PerlLIO_close(pp[0]);
2182 #if defined(HAS_FCNTL) && defined(F_SETFD)
2183 /* Close error pipe automatically if exec works */
2184 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2187 /* Now dup our end of _the_ pipe to right position */
2188 if (p[THIS] != (*mode == 'r')) {
2189 PerlLIO_dup2(p[THIS], *mode == 'r');
2190 PerlLIO_close(p[THIS]);
2191 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2192 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2195 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2196 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2197 /* No automatic close - do it by hand */
2204 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2210 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2216 do_execfree(); /* free any memory malloced by child on fork */
2218 PerlLIO_close(pp[1]);
2219 /* Keep the lower of the two fd numbers */
2220 if (p[that] < p[This]) {
2221 PerlLIO_dup2(p[This], p[that]);
2222 PerlLIO_close(p[This]);
2226 PerlLIO_close(p[that]); /* close child's end of pipe */
2229 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2231 SvUPGRADE(sv,SVt_IV);
2233 PL_forkprocess = pid;
2234 /* If we managed to get status pipe check for exec fail */
2235 if (did_pipes && pid > 0) {
2240 while (n < sizeof(int)) {
2241 n1 = PerlLIO_read(pp[0],
2242 (void*)(((char*)&errkid)+n),
2248 PerlLIO_close(pp[0]);
2250 if (n) { /* Error */
2252 PerlLIO_close(p[This]);
2253 if (n != sizeof(int))
2254 Perl_croak(aTHX_ "panic: kid popen errno read");
2256 pid2 = wait4pid(pid, &status, 0);
2257 } while (pid2 == -1 && errno == EINTR);
2258 errno = errkid; /* Propagate errno from kid */
2263 PerlLIO_close(pp[0]);
2264 return PerlIO_fdopen(p[This], mode);
2266 Perl_croak(aTHX_ "List form of piped open not implemented");
2267 return (PerlIO *) NULL;
2271 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2272 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2274 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2278 register I32 This, that;
2281 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2285 PERL_FLUSHALL_FOR_CHILD;
2288 return my_syspopen(aTHX_ cmd,mode);
2291 This = (*mode == 'w');
2293 if (doexec && PL_tainting) {
2295 taint_proper("Insecure %s%s", "EXEC");
2297 if (PerlProc_pipe(p) < 0)
2299 if (doexec && PerlProc_pipe(pp) >= 0)
2301 while ((pid = PerlProc_fork()) < 0) {
2302 if (errno != EAGAIN) {
2303 PerlLIO_close(p[This]);
2304 PerlLIO_close(p[that]);
2306 PerlLIO_close(pp[0]);
2307 PerlLIO_close(pp[1]);
2310 Perl_croak(aTHX_ "Can't fork");
2323 PerlLIO_close(pp[0]);
2324 #if defined(HAS_FCNTL) && defined(F_SETFD)
2325 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2328 if (p[THIS] != (*mode == 'r')) {
2329 PerlLIO_dup2(p[THIS], *mode == 'r');
2330 PerlLIO_close(p[THIS]);
2331 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2332 PerlLIO_close(p[THAT]);
2335 PerlLIO_close(p[THAT]);
2338 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2345 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2350 /* may or may not use the shell */
2351 do_exec3(cmd, pp[1], did_pipes);
2354 #endif /* defined OS2 */
2355 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2356 SvREADONLY_off(GvSV(tmpgv));
2357 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2358 SvREADONLY_on(GvSV(tmpgv));
2360 #ifdef THREADS_HAVE_PIDS
2361 PL_ppid = (IV)getppid();
2364 #ifdef PERL_USES_PL_PIDSTATUS
2365 hv_clear(PL_pidstatus); /* we have no children */
2371 do_execfree(); /* free any memory malloced by child on vfork */
2373 PerlLIO_close(pp[1]);
2374 if (p[that] < p[This]) {
2375 PerlLIO_dup2(p[This], p[that]);
2376 PerlLIO_close(p[This]);
2380 PerlLIO_close(p[that]);
2383 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2385 SvUPGRADE(sv,SVt_IV);
2387 PL_forkprocess = pid;
2388 if (did_pipes && pid > 0) {
2393 while (n < sizeof(int)) {
2394 n1 = PerlLIO_read(pp[0],
2395 (void*)(((char*)&errkid)+n),
2401 PerlLIO_close(pp[0]);
2403 if (n) { /* Error */
2405 PerlLIO_close(p[This]);
2406 if (n != sizeof(int))
2407 Perl_croak(aTHX_ "panic: kid popen errno read");
2409 pid2 = wait4pid(pid, &status, 0);
2410 } while (pid2 == -1 && errno == EINTR);
2411 errno = errkid; /* Propagate errno from kid */
2416 PerlLIO_close(pp[0]);
2417 return PerlIO_fdopen(p[This], mode);
2420 #if defined(atarist) || defined(EPOC)
2423 Perl_my_popen((pTHX_ const char *cmd, const char *mode)
2425 PERL_FLUSHALL_FOR_CHILD;
2426 /* Call system's popen() to get a FILE *, then import it.
2427 used 0 for 2nd parameter to PerlIO_importFILE;
2430 return PerlIO_importFILE(popen(cmd, mode), 0);
2434 FILE *djgpp_popen();
2436 Perl_my_popen((pTHX_ const char *cmd, const char *mode)
2438 PERL_FLUSHALL_FOR_CHILD;
2439 /* Call system's popen() to get a FILE *, then import it.
2440 used 0 for 2nd parameter to PerlIO_importFILE;
2443 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2448 #endif /* !DOSISH */
2450 /* this is called in parent before the fork() */
2452 Perl_atfork_lock(void)
2455 #if defined(USE_ITHREADS)
2456 /* locks must be held in locking order (if any) */
2458 MUTEX_LOCK(&PL_malloc_mutex);
2464 /* this is called in both parent and child after the fork() */
2466 Perl_atfork_unlock(void)
2469 #if defined(USE_ITHREADS)
2470 /* locks must be released in same order as in atfork_lock() */
2472 MUTEX_UNLOCK(&PL_malloc_mutex);
2481 #if defined(HAS_FORK)
2483 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2488 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2489 * handlers elsewhere in the code */
2494 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2495 Perl_croak_nocontext("fork() not available");
2497 #endif /* HAS_FORK */
2502 Perl_dump_fds(pTHX_ char *s)
2507 PerlIO_printf(Perl_debug_log,"%s", s);
2508 for (fd = 0; fd < 32; fd++) {
2509 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2510 PerlIO_printf(Perl_debug_log," %d",fd);
2512 PerlIO_printf(Perl_debug_log,"\n");
2515 #endif /* DUMP_FDS */
2519 dup2(int oldfd, int newfd)
2521 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2524 PerlLIO_close(newfd);
2525 return fcntl(oldfd, F_DUPFD, newfd);
2527 #define DUP2_MAX_FDS 256
2528 int fdtmp[DUP2_MAX_FDS];
2534 PerlLIO_close(newfd);
2535 /* good enough for low fd's... */
2536 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2537 if (fdx >= DUP2_MAX_FDS) {
2545 PerlLIO_close(fdtmp[--fdx]);
2552 #ifdef HAS_SIGACTION
2554 #ifdef MACOS_TRADITIONAL
2555 /* We don't want restart behavior on MacOS */
2560 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2563 struct sigaction act, oact;
2566 /* only "parent" interpreter can diddle signals */
2567 if (PL_curinterp != aTHX)
2568 return (Sighandler_t) SIG_ERR;
2571 act.sa_handler = (void(*)(int))handler;
2572 sigemptyset(&act.sa_mask);
2575 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2576 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2578 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2579 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2580 act.sa_flags |= SA_NOCLDWAIT;
2582 if (sigaction(signo, &act, &oact) == -1)
2583 return (Sighandler_t) SIG_ERR;
2585 return (Sighandler_t) oact.sa_handler;
2589 Perl_rsignal_state(pTHX_ int signo)
2591 struct sigaction oact;
2592 PERL_UNUSED_CONTEXT;
2594 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2595 return (Sighandler_t) SIG_ERR;
2597 return (Sighandler_t) oact.sa_handler;
2601 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2604 struct sigaction act;
2607 /* only "parent" interpreter can diddle signals */
2608 if (PL_curinterp != aTHX)
2612 act.sa_handler = (void(*)(int))handler;
2613 sigemptyset(&act.sa_mask);
2616 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2617 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2619 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2620 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2621 act.sa_flags |= SA_NOCLDWAIT;
2623 return sigaction(signo, &act, save);
2627 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2631 /* only "parent" interpreter can diddle signals */
2632 if (PL_curinterp != aTHX)
2636 return sigaction(signo, save, (struct sigaction *)NULL);
2639 #else /* !HAS_SIGACTION */
2642 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2644 #if defined(USE_ITHREADS) && !defined(WIN32)
2645 /* only "parent" interpreter can diddle signals */
2646 if (PL_curinterp != aTHX)
2647 return (Sighandler_t) SIG_ERR;
2650 return PerlProc_signal(signo, handler);
2661 Perl_rsignal_state(pTHX_ int signo)
2664 Sighandler_t oldsig;
2666 #if defined(USE_ITHREADS) && !defined(WIN32)
2667 /* only "parent" interpreter can diddle signals */
2668 if (PL_curinterp != aTHX)
2669 return (Sighandler_t) SIG_ERR;
2673 oldsig = PerlProc_signal(signo, sig_trap);
2674 PerlProc_signal(signo, oldsig);
2676 PerlProc_kill(PerlProc_getpid(), signo);
2681 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2683 #if defined(USE_ITHREADS) && !defined(WIN32)
2684 /* only "parent" interpreter can diddle signals */
2685 if (PL_curinterp != aTHX)
2688 *save = PerlProc_signal(signo, handler);
2689 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2693 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2695 #if defined(USE_ITHREADS) && !defined(WIN32)
2696 /* only "parent" interpreter can diddle signals */
2697 if (PL_curinterp != aTHX)
2700 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2703 #endif /* !HAS_SIGACTION */
2704 #endif /* !PERL_MICRO */
2706 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2707 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2709 Perl_my_pclose(pTHX_ PerlIO *ptr)
2712 Sigsave_t hstat, istat, qstat;
2718 int saved_errno = 0;
2720 int saved_win32_errno;
2724 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2726 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2728 *svp = &PL_sv_undef;
2730 if (pid == -1) { /* Opened by popen. */
2731 return my_syspclose(ptr);
2734 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2735 saved_errno = errno;
2737 saved_win32_errno = GetLastError();
2741 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2744 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2745 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2746 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2749 pid2 = wait4pid(pid, &status, 0);
2750 } while (pid2 == -1 && errno == EINTR);
2752 rsignal_restore(SIGHUP, &hstat);
2753 rsignal_restore(SIGINT, &istat);
2754 rsignal_restore(SIGQUIT, &qstat);
2757 SETERRNO(saved_errno, 0);
2760 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2762 #endif /* !DOSISH */
2764 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2766 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2772 #ifdef PERL_USES_PL_PIDSTATUS
2775 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2776 pid, rather than a string form. */
2777 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2778 if (svp && *svp != &PL_sv_undef) {
2779 *statusp = SvIVX(*svp);
2780 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2788 hv_iterinit(PL_pidstatus);
2789 if ((entry = hv_iternext(PL_pidstatus))) {
2790 SV * const sv = hv_iterval(PL_pidstatus,entry);
2792 const char * const spid = hv_iterkey(entry,&len);
2794 assert (len == sizeof(Pid_t));
2795 memcpy((char *)&pid, spid, len);
2796 *statusp = SvIVX(sv);
2797 /* The hash iterator is currently on this entry, so simply
2798 calling hv_delete would trigger the lazy delete, which on
2799 aggregate does more work, beacuse next call to hv_iterinit()
2800 would spot the flag, and have to call the delete routine,
2801 while in the meantime any new entries can't re-use that
2803 hv_iterinit(PL_pidstatus);
2804 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2811 # ifdef HAS_WAITPID_RUNTIME
2812 if (!HAS_WAITPID_RUNTIME)
2815 result = PerlProc_waitpid(pid,statusp,flags);
2818 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2819 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
2822 #ifdef PERL_USES_PL_PIDSTATUS
2823 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2828 Perl_croak(aTHX_ "Can't do waitpid with flags");
2830 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2831 pidgone(result,*statusp);
2837 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2840 if (result < 0 && errno == EINTR) {
2845 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2847 #ifdef PERL_USES_PL_PIDSTATUS
2849 Perl_pidgone(pTHX_ Pid_t pid, int status)
2853 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2854 SvUPGRADE(sv,SVt_IV);
2855 SvIV_set(sv, status);
2860 #if defined(atarist) || defined(OS2) || defined(EPOC)
2863 int /* Cannot prototype with I32
2865 my_syspclose(PerlIO *ptr)
2868 Perl_my_pclose(pTHX_ PerlIO *ptr)
2871 /* Needs work for PerlIO ! */
2872 FILE * const f = PerlIO_findFILE(ptr);
2873 const I32 result = pclose(f);
2874 PerlIO_releaseFILE(ptr,f);
2882 Perl_my_pclose(pTHX_ PerlIO *ptr)
2884 /* Needs work for PerlIO ! */
2885 FILE * const f = PerlIO_findFILE(ptr);
2886 I32 result = djgpp_pclose(f);
2887 result = (result << 8) & 0xff00;
2888 PerlIO_releaseFILE(ptr,f);
2894 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2897 register const char * const frombase = from;
2898 PERL_UNUSED_CONTEXT;
2901 register const char c = *from;
2906 while (count-- > 0) {
2907 for (todo = len; todo > 0; todo--) {
2916 Perl_same_dirent(pTHX_ const char *a, const char *b)
2918 char *fa = strrchr(a,'/');
2919 char *fb = strrchr(b,'/');
2922 SV * const tmpsv = sv_newmortal();
2935 sv_setpvn(tmpsv, ".", 1);
2937 sv_setpvn(tmpsv, a, fa - a);
2938 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2941 sv_setpvn(tmpsv, ".", 1);
2943 sv_setpvn(tmpsv, b, fb - b);
2944 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2946 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2947 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2949 #endif /* !HAS_RENAME */
2952 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2953 const char *const *const search_ext, I32 flags)
2956 const char *xfound = NULL;
2957 char *xfailed = NULL;
2958 char tmpbuf[MAXPATHLEN];
2962 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2963 # define SEARCH_EXTS ".bat", ".cmd", NULL
2964 # define MAX_EXT_LEN 4
2967 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2968 # define MAX_EXT_LEN 4
2971 # define SEARCH_EXTS ".pl", ".com", NULL
2972 # define MAX_EXT_LEN 4
2974 /* additional extensions to try in each dir if scriptname not found */
2976 static const char *const exts[] = { SEARCH_EXTS };
2977 const char *const *const ext = search_ext ? search_ext : exts;
2978 int extidx = 0, i = 0;
2979 const char *curext = NULL;
2981 PERL_UNUSED_ARG(search_ext);
2982 # define MAX_EXT_LEN 0
2986 * If dosearch is true and if scriptname does not contain path
2987 * delimiters, search the PATH for scriptname.
2989 * If SEARCH_EXTS is also defined, will look for each
2990 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2991 * while searching the PATH.
2993 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2994 * proceeds as follows:
2995 * If DOSISH or VMSISH:
2996 * + look for ./scriptname{,.foo,.bar}
2997 * + search the PATH for scriptname{,.foo,.bar}
3000 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3001 * this will not look in '.' if it's not in the PATH)
3006 # ifdef ALWAYS_DEFTYPES
3007 len = strlen(scriptname);
3008 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3009 int idx = 0, deftypes = 1;
3012 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3015 int idx = 0, deftypes = 1;
3018 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3020 /* The first time through, just add SEARCH_EXTS to whatever we
3021 * already have, so we can check for default file types. */
3023 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3029 if ((strlen(tmpbuf) + strlen(scriptname)
3030 + MAX_EXT_LEN) >= sizeof tmpbuf)
3031 continue; /* don't search dir with too-long name */
3032 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3036 if (strEQ(scriptname, "-"))
3038 if (dosearch) { /* Look in '.' first. */
3039 const char *cur = scriptname;
3041 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3043 if (strEQ(ext[i++],curext)) {
3044 extidx = -1; /* already has an ext */
3049 DEBUG_p(PerlIO_printf(Perl_debug_log,
3050 "Looking for %s\n",cur));
3051 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3052 && !S_ISDIR(PL_statbuf.st_mode)) {
3060 if (cur == scriptname) {
3061 len = strlen(scriptname);
3062 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3064 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3067 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3068 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3073 #ifdef MACOS_TRADITIONAL
3074 if (dosearch && !strchr(scriptname, ':') &&
3075 (s = PerlEnv_getenv("Commands")))
3077 if (dosearch && !strchr(scriptname, '/')
3079 && !strchr(scriptname, '\\')
3081 && (s = PerlEnv_getenv("PATH")))
3086 PL_bufend = s + strlen(s);
3087 while (s < PL_bufend) {
3088 #ifdef MACOS_TRADITIONAL
3089 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3093 #if defined(atarist) || defined(DOSISH)
3098 && *s != ';'; len++, s++) {
3099 if (len < sizeof tmpbuf)
3102 if (len < sizeof tmpbuf)
3104 #else /* ! (atarist || DOSISH) */
3105 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3108 #endif /* ! (atarist || DOSISH) */
3109 #endif /* MACOS_TRADITIONAL */
3112 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3113 continue; /* don't search dir with too-long name */
3114 #ifdef MACOS_TRADITIONAL
3115 if (len && tmpbuf[len - 1] != ':')
3116 tmpbuf[len++] = ':';
3119 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3120 && tmpbuf[len - 1] != '/'
3121 && tmpbuf[len - 1] != '\\'
3124 tmpbuf[len++] = '/';
3125 if (len == 2 && tmpbuf[0] == '.')
3128 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3132 len = strlen(tmpbuf);
3133 if (extidx > 0) /* reset after previous loop */
3137 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3138 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3139 if (S_ISDIR(PL_statbuf.st_mode)) {
3143 } while ( retval < 0 /* not there */
3144 && extidx>=0 && ext[extidx] /* try an extension? */
3145 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3150 if (S_ISREG(PL_statbuf.st_mode)
3151 && cando(S_IRUSR,TRUE,&PL_statbuf)
3152 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3153 && cando(S_IXUSR,TRUE,&PL_statbuf)
3157 xfound = tmpbuf; /* bingo! */
3161 xfailed = savepv(tmpbuf);
3164 if (!xfound && !seen_dot && !xfailed &&
3165 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3166 || S_ISDIR(PL_statbuf.st_mode)))
3168 seen_dot = 1; /* Disable message. */
3170 if (flags & 1) { /* do or die? */
3171 Perl_croak(aTHX_ "Can't %s %s%s%s",
3172 (xfailed ? "execute" : "find"),
3173 (xfailed ? xfailed : scriptname),
3174 (xfailed ? "" : " on PATH"),
3175 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3180 scriptname = xfound;
3182 return (scriptname ? savepv(scriptname) : NULL);
3185 #ifndef PERL_GET_CONTEXT_DEFINED
3188 Perl_get_context(void)
3191 #if defined(USE_ITHREADS)
3192 # ifdef OLD_PTHREADS_API
3194 if (pthread_getspecific(PL_thr_key, &t))
3195 Perl_croak_nocontext("panic: pthread_getspecific");
3198 # ifdef I_MACH_CTHREADS
3199 return (void*)cthread_data(cthread_self());
3201 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3210 Perl_set_context(void *t)
3213 #if defined(USE_ITHREADS)
3214 # ifdef I_MACH_CTHREADS
3215 cthread_set_data(cthread_self(), t);
3217 if (pthread_setspecific(PL_thr_key, t))
3218 Perl_croak_nocontext("panic: pthread_setspecific");
3225 #endif /* !PERL_GET_CONTEXT_DEFINED */
3227 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3236 Perl_get_op_names(pTHX)
3238 PERL_UNUSED_CONTEXT;
3239 return (char **)PL_op_name;
3243 Perl_get_op_descs(pTHX)
3245 PERL_UNUSED_CONTEXT;
3246 return (char **)PL_op_desc;
3250 Perl_get_no_modify(pTHX)
3252 PERL_UNUSED_CONTEXT;
3253 return PL_no_modify;
3257 Perl_get_opargs(pTHX)
3259 PERL_UNUSED_CONTEXT;
3260 return (U32 *)PL_opargs;
3264 Perl_get_ppaddr(pTHX)
3267 PERL_UNUSED_CONTEXT;
3268 return (PPADDR_t*)PL_ppaddr;
3271 #ifndef HAS_GETENV_LEN
3273 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3275 char * const env_trans = PerlEnv_getenv(env_elem);
3276 PERL_UNUSED_CONTEXT;
3278 *len = strlen(env_trans);
3285 Perl_get_vtbl(pTHX_ int vtbl_id)
3287 const MGVTBL* result;
3288 PERL_UNUSED_CONTEXT;
3292 result = &PL_vtbl_sv;
3295 result = &PL_vtbl_env;
3297 case want_vtbl_envelem:
3298 result = &PL_vtbl_envelem;
3301 result = &PL_vtbl_sig;
3303 case want_vtbl_sigelem:
3304 result = &PL_vtbl_sigelem;
3306 case want_vtbl_pack:
3307 result = &PL_vtbl_pack;
3309 case want_vtbl_packelem:
3310 result = &PL_vtbl_packelem;
3312 case want_vtbl_dbline:
3313 result = &PL_vtbl_dbline;
3316 result = &PL_vtbl_isa;
3318 case want_vtbl_isaelem:
3319 result = &PL_vtbl_isaelem;
3321 case want_vtbl_arylen:
3322 result = &PL_vtbl_arylen;
3324 case want_vtbl_mglob:
3325 result = &PL_vtbl_mglob;
3327 case want_vtbl_nkeys:
3328 result = &PL_vtbl_nkeys;
3330 case want_vtbl_taint:
3331 result = &PL_vtbl_taint;
3333 case want_vtbl_substr:
3334 result = &PL_vtbl_substr;
3337 result = &PL_vtbl_vec;
3340 result = &PL_vtbl_pos;
3343 result = &PL_vtbl_bm;
3346 result = &PL_vtbl_fm;
3348 case want_vtbl_uvar:
3349 result = &PL_vtbl_uvar;
3351 case want_vtbl_defelem:
3352 result = &PL_vtbl_defelem;
3354 case want_vtbl_regexp:
3355 result = &PL_vtbl_regexp;
3357 case want_vtbl_regdata:
3358 result = &PL_vtbl_regdata;
3360 case want_vtbl_regdatum:
3361 result = &PL_vtbl_regdatum;
3363 #ifdef USE_LOCALE_COLLATE
3364 case want_vtbl_collxfrm:
3365 result = &PL_vtbl_collxfrm;
3368 case want_vtbl_amagic:
3369 result = &PL_vtbl_amagic;
3371 case want_vtbl_amagicelem:
3372 result = &PL_vtbl_amagicelem;
3374 case want_vtbl_backref:
3375 result = &PL_vtbl_backref;
3377 case want_vtbl_utf8:
3378 result = &PL_vtbl_utf8;
3384 return (MGVTBL*)result;
3388 Perl_my_fflush_all(pTHX)
3390 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3391 return PerlIO_flush(NULL);
3393 # if defined(HAS__FWALK)
3394 extern int fflush(FILE *);
3395 /* undocumented, unprototyped, but very useful BSDism */
3396 extern void _fwalk(int (*)(FILE *));
3400 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3402 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3403 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3405 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3406 open_max = sysconf(_SC_OPEN_MAX);
3409 open_max = FOPEN_MAX;
3412 open_max = OPEN_MAX;
3423 for (i = 0; i < open_max; i++)
3424 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3425 STDIO_STREAM_ARRAY[i]._file < open_max &&
3426 STDIO_STREAM_ARRAY[i]._flag)
3427 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3431 SETERRNO(EBADF,RMS_IFI);
3438 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3440 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3442 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3443 if (ckWARN(WARN_IO)) {
3444 const char * const direction =
3445 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3447 Perl_warner(aTHX_ packWARN(WARN_IO),
3448 "Filehandle %s opened only for %sput",
3451 Perl_warner(aTHX_ packWARN(WARN_IO),
3452 "Filehandle opened only for %sput", direction);
3459 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3461 warn_type = WARN_CLOSED;
3465 warn_type = WARN_UNOPENED;
3468 if (ckWARN(warn_type)) {
3469 const char * const pars =
3470 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3471 const char * const func =
3473 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3474 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3475 op < 0 ? "" : /* handle phoney cases */
3477 const char * const type =
3479 (OP_IS_SOCKET(op) ||
3480 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3481 "socket" : "filehandle");
3482 if (name && *name) {
3483 Perl_warner(aTHX_ packWARN(warn_type),
3484 "%s%s on %s %s %s", func, pars, vile, type, name);
3485 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3487 aTHX_ packWARN(warn_type),
3488 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3493 Perl_warner(aTHX_ packWARN(warn_type),
3494 "%s%s on %s %s", func, pars, vile, type);
3495 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3497 aTHX_ packWARN(warn_type),
3498 "\t(Are you trying to call %s%s on dirhandle?)\n",
3507 /* in ASCII order, not that it matters */
3508 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3511 Perl_ebcdic_control(pTHX_ int ch)
3519 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3520 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3523 if (ctlp == controllablechars)
3524 return('\177'); /* DEL */
3526 return((unsigned char)(ctlp - controllablechars - 1));
3527 } else { /* Want uncontrol */
3528 if (ch == '\177' || ch == -1)
3530 else if (ch == '\157')
3532 else if (ch == '\174')
3534 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3536 else if (ch == '\155')
3538 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3539 return(controllablechars[ch+1]);
3541 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3546 /* To workaround core dumps from the uninitialised tm_zone we get the
3547 * system to give us a reasonable struct to copy. This fix means that
3548 * strftime uses the tm_zone and tm_gmtoff values returned by
3549 * localtime(time()). That should give the desired result most of the
3550 * time. But probably not always!
3552 * This does not address tzname aspects of NETaa14816.
3557 # ifndef STRUCT_TM_HASZONE
3558 # define STRUCT_TM_HASZONE
3562 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3563 # ifndef HAS_TM_TM_ZONE
3564 # define HAS_TM_TM_ZONE
3569 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3571 #ifdef HAS_TM_TM_ZONE
3573 const struct tm* my_tm;
3575 my_tm = localtime(&now);
3577 Copy(my_tm, ptm, 1, struct tm);
3579 PERL_UNUSED_ARG(ptm);
3584 * mini_mktime - normalise struct tm values without the localtime()
3585 * semantics (and overhead) of mktime().
3588 Perl_mini_mktime(pTHX_ struct tm *ptm)
3592 int month, mday, year, jday;
3593 int odd_cent, odd_year;
3594 PERL_UNUSED_CONTEXT;
3596 #define DAYS_PER_YEAR 365
3597 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3598 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3599 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3600 #define SECS_PER_HOUR (60*60)
3601 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3602 /* parentheses deliberately absent on these two, otherwise they don't work */
3603 #define MONTH_TO_DAYS 153/5
3604 #define DAYS_TO_MONTH 5/153
3605 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3606 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3607 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3608 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3611 * Year/day algorithm notes:
3613 * With a suitable offset for numeric value of the month, one can find
3614 * an offset into the year by considering months to have 30.6 (153/5) days,
3615 * using integer arithmetic (i.e., with truncation). To avoid too much
3616 * messing about with leap days, we consider January and February to be
3617 * the 13th and 14th month of the previous year. After that transformation,
3618 * we need the month index we use to be high by 1 from 'normal human' usage,
3619 * so the month index values we use run from 4 through 15.
3621 * Given that, and the rules for the Gregorian calendar (leap years are those
3622 * divisible by 4 unless also divisible by 100, when they must be divisible
3623 * by 400 instead), we can simply calculate the number of days since some
3624 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3625 * the days we derive from our month index, and adding in the day of the
3626 * month. The value used here is not adjusted for the actual origin which
3627 * it normally would use (1 January A.D. 1), since we're not exposing it.
3628 * We're only building the value so we can turn around and get the
3629 * normalised values for the year, month, day-of-month, and day-of-year.
3631 * For going backward, we need to bias the value we're using so that we find
3632 * the right year value. (Basically, we don't want the contribution of
3633 * March 1st to the number to apply while deriving the year). Having done
3634 * that, we 'count up' the contribution to the year number by accounting for
3635 * full quadracenturies (400-year periods) with their extra leap days, plus
3636 * the contribution from full centuries (to avoid counting in the lost leap
3637 * days), plus the contribution from full quad-years (to count in the normal
3638 * leap days), plus the leftover contribution from any non-leap years.
3639 * At this point, if we were working with an actual leap day, we'll have 0
3640 * days left over. This is also true for March 1st, however. So, we have
3641 * to special-case that result, and (earlier) keep track of the 'odd'
3642 * century and year contributions. If we got 4 extra centuries in a qcent,
3643 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3644 * Otherwise, we add back in the earlier bias we removed (the 123 from
3645 * figuring in March 1st), find the month index (integer division by 30.6),
3646 * and the remainder is the day-of-month. We then have to convert back to
3647 * 'real' months (including fixing January and February from being 14/15 in
3648 * the previous year to being in the proper year). After that, to get
3649 * tm_yday, we work with the normalised year and get a new yearday value for
3650 * January 1st, which we subtract from the yearday value we had earlier,
3651 * representing the date we've re-built. This is done from January 1
3652 * because tm_yday is 0-origin.
3654 * Since POSIX time routines are only guaranteed to work for times since the
3655 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3656 * applies Gregorian calendar rules even to dates before the 16th century
3657 * doesn't bother me. Besides, you'd need cultural context for a given
3658 * date to know whether it was Julian or Gregorian calendar, and that's
3659 * outside the scope for this routine. Since we convert back based on the
3660 * same rules we used to build the yearday, you'll only get strange results
3661 * for input which needed normalising, or for the 'odd' century years which
3662 * were leap years in the Julian calander but not in the Gregorian one.
3663 * I can live with that.
3665 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3666 * that's still outside the scope for POSIX time manipulation, so I don't
3670 year = 1900 + ptm->tm_year;
3671 month = ptm->tm_mon;
3672 mday = ptm->tm_mday;
3673 /* allow given yday with no month & mday to dominate the result */
3674 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3677 jday = 1 + ptm->tm_yday;
3686 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3687 yearday += month*MONTH_TO_DAYS + mday + jday;
3689 * Note that we don't know when leap-seconds were or will be,
3690 * so we have to trust the user if we get something which looks
3691 * like a sensible leap-second. Wild values for seconds will
3692 * be rationalised, however.
3694 if ((unsigned) ptm->tm_sec <= 60) {
3701 secs += 60 * ptm->tm_min;
3702 secs += SECS_PER_HOUR * ptm->tm_hour;
3704 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3705 /* got negative remainder, but need positive time */
3706 /* back off an extra day to compensate */
3707 yearday += (secs/SECS_PER_DAY)-1;
3708 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3711 yearday += (secs/SECS_PER_DAY);
3712 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3715 else if (secs >= SECS_PER_DAY) {
3716 yearday += (secs/SECS_PER_DAY);
3717 secs %= SECS_PER_DAY;
3719 ptm->tm_hour = secs/SECS_PER_HOUR;
3720 secs %= SECS_PER_HOUR;
3721 ptm->tm_min = secs/60;
3723 ptm->tm_sec += secs;
3724 /* done with time of day effects */
3726 * The algorithm for yearday has (so far) left it high by 428.
3727 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3728 * bias it by 123 while trying to figure out what year it
3729 * really represents. Even with this tweak, the reverse
3730 * translation fails for years before A.D. 0001.
3731 * It would still fail for Feb 29, but we catch that one below.
3733 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3734 yearday -= YEAR_ADJUST;
3735 year = (yearday / DAYS_PER_QCENT) * 400;
3736 yearday %= DAYS_PER_QCENT;
3737 odd_cent = yearday / DAYS_PER_CENT;
3738 year += odd_cent * 100;
3739 yearday %= DAYS_PER_CENT;
3740 year += (yearday / DAYS_PER_QYEAR) * 4;
3741 yearday %= DAYS_PER_QYEAR;
3742 odd_year = yearday / DAYS_PER_YEAR;
3744 yearday %= DAYS_PER_YEAR;
3745 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3750 yearday += YEAR_ADJUST; /* recover March 1st crock */
3751 month = yearday*DAYS_TO_MONTH;
3752 yearday -= month*MONTH_TO_DAYS;
3753 /* recover other leap-year adjustment */
3762 ptm->tm_year = year - 1900;
3764 ptm->tm_mday = yearday;
3765 ptm->tm_mon = month;
3769 ptm->tm_mon = month - 1;
3771 /* re-build yearday based on Jan 1 to get tm_yday */
3773 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3774 yearday += 14*MONTH_TO_DAYS + 1;
3775 ptm->tm_yday = jday - yearday;
3776 /* fix tm_wday if not overridden by caller */
3777 if ((unsigned)ptm->tm_wday > 6)
3778 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3782 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)
3790 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3793 mytm.tm_hour = hour;
3794 mytm.tm_mday = mday;
3796 mytm.tm_year = year;
3797 mytm.tm_wday = wday;
3798 mytm.tm_yday = yday;
3799 mytm.tm_isdst = isdst;
3801 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3802 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3807 #ifdef HAS_TM_TM_GMTOFF
3808 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3810 #ifdef HAS_TM_TM_ZONE
3811 mytm.tm_zone = mytm2.tm_zone;
3816 Newx(buf, buflen, char);
3817 len = strftime(buf, buflen, fmt, &mytm);
3819 ** The following is needed to handle to the situation where
3820 ** tmpbuf overflows. Basically we want to allocate a buffer
3821 ** and try repeatedly. The reason why it is so complicated
3822 ** is that getting a return value of 0 from strftime can indicate
3823 ** one of the following:
3824 ** 1. buffer overflowed,
3825 ** 2. illegal conversion specifier, or
3826 ** 3. the format string specifies nothing to be returned(not
3827 ** an error). This could be because format is an empty string
3828 ** or it specifies %p that yields an empty string in some locale.
3829 ** If there is a better way to make it portable, go ahead by
3832 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3835 /* Possibly buf overflowed - try again with a bigger buf */
3836 const int fmtlen = strlen(fmt);
3837 int bufsize = fmtlen + buflen;
3839 Newx(buf, bufsize, char);
3841 buflen = strftime(buf, bufsize, fmt, &mytm);
3842 if (buflen > 0 && buflen < bufsize)
3844 /* heuristic to prevent out-of-memory errors */
3845 if (bufsize > 100*fmtlen) {
3851 Renew(buf, bufsize, char);
3856 Perl_croak(aTHX_ "panic: no strftime");
3862 #define SV_CWD_RETURN_UNDEF \
3863 sv_setsv(sv, &PL_sv_undef); \
3866 #define SV_CWD_ISDOT(dp) \
3867 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3868 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3871 =head1 Miscellaneous Functions
3873 =for apidoc getcwd_sv
3875 Fill the sv with current working directory
3880 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3881 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3882 * getcwd(3) if available
3883 * Comments from the orignal:
3884 * This is a faster version of getcwd. It's also more dangerous
3885 * because you might chdir out of a directory that you can't chdir
3889 Perl_getcwd_sv(pTHX_ register SV *sv)
3893 #ifndef INCOMPLETE_TAINTS
3899 char buf[MAXPATHLEN];
3901 /* Some getcwd()s automatically allocate a buffer of the given
3902 * size from the heap if they are given a NULL buffer pointer.
3903 * The problem is that this behaviour is not portable. */
3904 if (getcwd(buf, sizeof(buf) - 1)) {
3909 sv_setsv(sv, &PL_sv_undef);
3917 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3921 SvUPGRADE(sv, SVt_PV);
3923 if (PerlLIO_lstat(".", &statbuf) < 0) {
3924 SV_CWD_RETURN_UNDEF;
3927 orig_cdev = statbuf.st_dev;
3928 orig_cino = statbuf.st_ino;
3937 if (PerlDir_chdir("..") < 0) {
3938 SV_CWD_RETURN_UNDEF;
3940 if (PerlLIO_stat(".", &statbuf) < 0) {
3941 SV_CWD_RETURN_UNDEF;
3944 cdev = statbuf.st_dev;
3945 cino = statbuf.st_ino;
3947 if (odev == cdev && oino == cino) {
3950 if (!(dir = PerlDir_open("."))) {
3951 SV_CWD_RETURN_UNDEF;
3954 while ((dp = PerlDir_read(dir)) != NULL) {
3956 const int namelen = dp->d_namlen;
3958 const int namelen = strlen(dp->d_name);
3961 if (SV_CWD_ISDOT(dp)) {
3965 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3966 SV_CWD_RETURN_UNDEF;
3969 tdev = statbuf.st_dev;
3970 tino = statbuf.st_ino;
3971 if (tino == oino && tdev == odev) {
3977 SV_CWD_RETURN_UNDEF;
3980 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3981 SV_CWD_RETURN_UNDEF;
3984 SvGROW(sv, pathlen + namelen + 1);
3988 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3991 /* prepend current directory to the front */
3993 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3994 pathlen += (namelen + 1);
3996 #ifdef VOID_CLOSEDIR
3999 if (PerlDir_close(dir) < 0) {
4000 SV_CWD_RETURN_UNDEF;
4006 SvCUR_set(sv, pathlen);
4010 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4011 SV_CWD_RETURN_UNDEF;
4014 if (PerlLIO_stat(".", &statbuf) < 0) {
4015 SV_CWD_RETURN_UNDEF;
4018 cdev = statbuf.st_dev;
4019 cino = statbuf.st_ino;
4021 if (cdev != orig_cdev || cino != orig_cino) {
4022 Perl_croak(aTHX_ "Unstable directory path, "
4023 "current directory changed unexpectedly");
4035 =for apidoc scan_version
4037 Returns a pointer to the next character after the parsed
4038 version string, as well as upgrading the passed in SV to
4041 Function must be called with an already existing SV like
4044 s = scan_version(s,SV *sv, bool qv);
4046 Performs some preprocessing to the string to ensure that
4047 it has the correct characteristics of a version. Flags the
4048 object if it contains an underscore (which denotes this
4049 is a alpha version). The boolean qv denotes that the version
4050 should be interpreted as if it had multiple decimals, even if
4057 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4065 AV * const av = newAV();
4066 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4067 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4069 #ifndef NODEFAULT_SHAREKEYS
4070 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4073 while (isSPACE(*s)) /* leading whitespace is OK */
4077 s++; /* get past 'v' */
4078 qv = 1; /* force quoted version processing */
4081 start = last = pos = s;
4083 /* pre-scan the input string to check for decimals/underbars */
4084 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4089 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4093 else if ( *pos == '_' )
4096 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4098 width = pos - last - 1; /* natural width of sub-version */
4103 if ( alpha && !saw_period )
4104 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4106 if ( saw_period > 1 )
4107 qv = 1; /* force quoted version processing */
4112 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4114 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4115 if ( !qv && width < 3 )
4116 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4118 while (isDIGIT(*pos))
4120 if (!isALPHA(*pos)) {
4126 /* this is atoi() that delimits on underscores */
4127 const char *end = pos;
4131 /* the following if() will only be true after the decimal
4132 * point of a version originally created with a bare
4133 * floating point number, i.e. not quoted in any way
4135 if ( !qv && s > start && saw_period == 1 ) {
4139 rev += (*s - '0') * mult;
4141 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4142 Perl_croak(aTHX_ "Integer overflow in version");
4149 while (--end >= s) {
4151 rev += (*end - '0') * mult;
4153 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4154 Perl_croak(aTHX_ "Integer overflow in version");
4159 /* Append revision */
4160 av_push(av, newSViv(rev));
4163 else if ( *pos == '_' && isDIGIT(pos[1]) )
4165 else if ( isDIGIT(*pos) )
4172 while ( isDIGIT(*pos) )
4177 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4185 if ( qv ) { /* quoted versions always get at least three terms*/
4186 I32 len = av_len(av);
4187 /* This for loop appears to trigger a compiler bug on OS X, as it
4188 loops infinitely. Yes, len is negative. No, it makes no sense.
4189 Compiler in question is:
4190 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4191 for ( len = 2 - len; len > 0; len-- )
4192 av_push((AV *)sv, newSViv(0));
4196 av_push(av, newSViv(0));
4199 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4200 av_push(av, newSViv(0));
4202 /* fix RT#19517 - special case 'undef' as string */
4203 if ( *s == 'u' && strEQ(s,"undef") ) {
4207 /* And finally, store the AV in the hash */
4208 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4213 =for apidoc new_version
4215 Returns a new version object based on the passed in SV:
4217 SV *sv = new_version(SV *ver);
4219 Does not alter the passed in ver SV. See "upg_version" if you
4220 want to upgrade the SV.
4226 Perl_new_version(pTHX_ SV *ver)
4229 SV * const rv = newSV(0);
4230 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4233 AV * const av = newAV();
4235 /* This will get reblessed later if a derived class*/
4236 SV * const hv = newSVrv(rv, "version");
4237 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4238 #ifndef NODEFAULT_SHAREKEYS
4239 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4245 /* Begin copying all of the elements */
4246 if ( hv_exists((HV *)ver, "qv", 2) )
4247 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4249 if ( hv_exists((HV *)ver, "alpha", 5) )
4250 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4252 if ( hv_exists((HV*)ver, "width", 5 ) )
4254 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4255 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4258 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4259 /* This will get reblessed later if a derived class*/
4260 for ( key = 0; key <= av_len(sav); key++ )
4262 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4263 av_push(av, newSViv(rev));
4266 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4271 const MAGIC* const mg = SvVSTRING_mg(ver);
4272 if ( mg ) { /* already a v-string */
4273 const STRLEN len = mg->mg_len;
4274 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4275 sv_setpvn(rv,version,len);
4280 sv_setsv(rv,ver); /* make a duplicate */
4285 return upg_version(rv);
4289 =for apidoc upg_version
4291 In-place upgrade of the supplied SV to a version object.
4293 SV *sv = upg_version(SV *sv);
4295 Returns a pointer to the upgraded SV.
4301 Perl_upg_version(pTHX_ SV *ver)
4303 const char *version, *s;
4309 if ( SvNOK(ver) ) /* may get too much accuracy */
4312 #ifdef USE_LOCALE_NUMERIC
4313 char *loc = setlocale(LC_NUMERIC, "C");
4315 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4316 #ifdef USE_LOCALE_NUMERIC
4317 setlocale(LC_NUMERIC, loc);
4319 while (tbuf[len-1] == '0' && len > 0) len--;
4320 version = savepvn(tbuf, len);
4323 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4324 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4328 else /* must be a string or something like a string */
4330 version = savepv(SvPV_nolen(ver));
4333 s = scan_version(version, ver, qv);
4335 if(ckWARN(WARN_MISC))
4336 Perl_warner(aTHX_ packWARN(WARN_MISC),
4337 "Version string '%s' contains invalid data; "
4338 "ignoring: '%s'", version, s);
4346 Validates that the SV contains a valid version object.
4348 bool vverify(SV *vobj);
4350 Note that it only confirms the bare minimum structure (so as not to get
4351 confused by derived classes which may contain additional hash entries):
4355 =item * The SV contains a [reference to a] hash
4357 =item * The hash contains a "version" key
4359 =item * The "version" key has [a reference to] an AV as its value
4367 Perl_vverify(pTHX_ SV *vs)
4373 /* see if the appropriate elements exist */
4374 if ( SvTYPE(vs) == SVt_PVHV
4375 && hv_exists((HV*)vs, "version", 7)
4376 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4377 && SvTYPE(sv) == SVt_PVAV )
4386 Accepts a version object and returns the normalized floating
4387 point representation. Call like:
4391 NOTE: you can pass either the object directly or the SV
4392 contained within the RV.
4398 Perl_vnumify(pTHX_ SV *vs)
4403 SV * const sv = newSV(0);
4409 Perl_croak(aTHX_ "Invalid version object");
4411 /* see if various flags exist */
4412 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4414 if ( hv_exists((HV*)vs, "width", 5 ) )
4415 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4420 /* attempt to retrieve the version array */
4421 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4433 digit = SvIV(*av_fetch(av, 0, 0));
4434 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4435 for ( i = 1 ; i < len ; i++ )
4437 digit = SvIV(*av_fetch(av, i, 0));
4439 const int denom = (width == 2 ? 10 : 100);
4440 const div_t term = div((int)PERL_ABS(digit),denom);
4441 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4444 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4450 digit = SvIV(*av_fetch(av, len, 0));
4451 if ( alpha && width == 3 ) /* alpha version */
4453 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4457 sv_catpvs(sv, "000");
4465 Accepts a version object and returns the normalized string
4466 representation. Call like:
4470 NOTE: you can pass either the object directly or the SV
4471 contained within the RV.
4477 Perl_vnormal(pTHX_ SV *vs)
4481 SV * const sv = newSV(0);
4487 Perl_croak(aTHX_ "Invalid version object");
4489 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4491 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4499 digit = SvIV(*av_fetch(av, 0, 0));
4500 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4501 for ( i = 1 ; i < len ; i++ ) {
4502 digit = SvIV(*av_fetch(av, i, 0));
4503 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4508 /* handle last digit specially */
4509 digit = SvIV(*av_fetch(av, len, 0));
4511 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4513 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4516 if ( len <= 2 ) { /* short version, must be at least three */
4517 for ( len = 2 - len; len != 0; len-- )
4524 =for apidoc vstringify
4526 In order to maintain maximum compatibility with earlier versions
4527 of Perl, this function will return either the floating point
4528 notation or the multiple dotted notation, depending on whether
4529 the original version contained 1 or more dots, respectively
4535 Perl_vstringify(pTHX_ SV *vs)
4541 Perl_croak(aTHX_ "Invalid version object");
4543 if ( hv_exists((HV *)vs, "qv", 2) )
4552 Version object aware cmp. Both operands must already have been
4553 converted into version objects.
4559 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4562 bool lalpha = FALSE;
4563 bool ralpha = FALSE;
4572 if ( !vverify(lhv) )
4573 Perl_croak(aTHX_ "Invalid version object");
4575 if ( !vverify(rhv) )
4576 Perl_croak(aTHX_ "Invalid version object");
4578 /* get the left hand term */
4579 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4580 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4583 /* and the right hand term */
4584 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4585 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4593 while ( i <= m && retval == 0 )
4595 left = SvIV(*av_fetch(lav,i,0));
4596 right = SvIV(*av_fetch(rav,i,0));
4604 /* tiebreaker for alpha with identical terms */
4605 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4607 if ( lalpha && !ralpha )
4611 else if ( ralpha && !lalpha)
4617 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4621 while ( i <= r && retval == 0 )
4623 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4624 retval = -1; /* not a match after all */
4630 while ( i <= l && retval == 0 )
4632 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4633 retval = +1; /* not a match after all */
4641 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4642 # define EMULATE_SOCKETPAIR_UDP
4645 #ifdef EMULATE_SOCKETPAIR_UDP
4647 S_socketpair_udp (int fd[2]) {
4649 /* Fake a datagram socketpair using UDP to localhost. */
4650 int sockets[2] = {-1, -1};
4651 struct sockaddr_in addresses[2];
4653 Sock_size_t size = sizeof(struct sockaddr_in);
4654 unsigned short port;
4657 memset(&addresses, 0, sizeof(addresses));
4660 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4661 if (sockets[i] == -1)
4662 goto tidy_up_and_fail;
4664 addresses[i].sin_family = AF_INET;
4665 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4666 addresses[i].sin_port = 0; /* kernel choses port. */
4667 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4668 sizeof(struct sockaddr_in)) == -1)
4669 goto tidy_up_and_fail;
4672 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4673 for each connect the other socket to it. */
4676 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4678 goto tidy_up_and_fail;
4679 if (size != sizeof(struct sockaddr_in))
4680 goto abort_tidy_up_and_fail;
4681 /* !1 is 0, !0 is 1 */
4682 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4683 sizeof(struct sockaddr_in)) == -1)
4684 goto tidy_up_and_fail;
4687 /* Now we have 2 sockets connected to each other. I don't trust some other
4688 process not to have already sent a packet to us (by random) so send
4689 a packet from each to the other. */
4692 /* I'm going to send my own port number. As a short.
4693 (Who knows if someone somewhere has sin_port as a bitfield and needs
4694 this routine. (I'm assuming crays have socketpair)) */
4695 port = addresses[i].sin_port;
4696 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4697 if (got != sizeof(port)) {
4699 goto tidy_up_and_fail;
4700 goto abort_tidy_up_and_fail;
4704 /* Packets sent. I don't trust them to have arrived though.
4705 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4706 connect to localhost will use a second kernel thread. In 2.6 the
4707 first thread running the connect() returns before the second completes,
4708 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4709 returns 0. Poor programs have tripped up. One poor program's authors'
4710 had a 50-1 reverse stock split. Not sure how connected these were.)
4711 So I don't trust someone not to have an unpredictable UDP stack.
4715 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4716 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4720 FD_SET((unsigned int)sockets[0], &rset);
4721 FD_SET((unsigned int)sockets[1], &rset);
4723 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4724 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4725 || !FD_ISSET(sockets[1], &rset)) {
4726 /* I hope this is portable and appropriate. */
4728 goto tidy_up_and_fail;
4729 goto abort_tidy_up_and_fail;
4733 /* And the paranoia department even now doesn't trust it to have arrive
4734 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4736 struct sockaddr_in readfrom;
4737 unsigned short buffer[2];
4742 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4743 sizeof(buffer), MSG_DONTWAIT,
4744 (struct sockaddr *) &readfrom, &size);
4746 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4748 (struct sockaddr *) &readfrom, &size);
4752 goto tidy_up_and_fail;
4753 if (got != sizeof(port)
4754 || size != sizeof(struct sockaddr_in)
4755 /* Check other socket sent us its port. */
4756 || buffer[0] != (unsigned short) addresses[!i].sin_port
4757 /* Check kernel says we got the datagram from that socket */
4758 || readfrom.sin_family != addresses[!i].sin_family
4759 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4760 || readfrom.sin_port != addresses[!i].sin_port)
4761 goto abort_tidy_up_and_fail;
4764 /* My caller (my_socketpair) has validated that this is non-NULL */
4767 /* I hereby declare this connection open. May God bless all who cross
4771 abort_tidy_up_and_fail:
4772 errno = ECONNABORTED;
4775 const int save_errno = errno;
4776 if (sockets[0] != -1)
4777 PerlLIO_close(sockets[0]);
4778 if (sockets[1] != -1)
4779 PerlLIO_close(sockets[1]);
4784 #endif /* EMULATE_SOCKETPAIR_UDP */
4786 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4788 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4789 /* Stevens says that family must be AF_LOCAL, protocol 0.
4790 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4795 struct sockaddr_in listen_addr;
4796 struct sockaddr_in connect_addr;
4801 || family != AF_UNIX
4804 errno = EAFNOSUPPORT;
4812 #ifdef EMULATE_SOCKETPAIR_UDP
4813 if (type == SOCK_DGRAM)
4814 return S_socketpair_udp(fd);
4817 listener = PerlSock_socket(AF_INET, type, 0);
4820 memset(&listen_addr, 0, sizeof(listen_addr));
4821 listen_addr.sin_family = AF_INET;
4822 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4823 listen_addr.sin_port = 0; /* kernel choses port. */
4824 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4825 sizeof(listen_addr)) == -1)
4826 goto tidy_up_and_fail;
4827 if (PerlSock_listen(listener, 1) == -1)
4828 goto tidy_up_and_fail;
4830 connector = PerlSock_socket(AF_INET, type, 0);
4831 if (connector == -1)
4832 goto tidy_up_and_fail;
4833 /* We want to find out the port number to connect to. */
4834 size = sizeof(connect_addr);
4835 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4837 goto tidy_up_and_fail;
4838 if (size != sizeof(connect_addr))
4839 goto abort_tidy_up_and_fail;
4840 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4841 sizeof(connect_addr)) == -1)
4842 goto tidy_up_and_fail;
4844 size = sizeof(listen_addr);
4845 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4848 goto tidy_up_and_fail;
4849 if (size != sizeof(listen_addr))
4850 goto abort_tidy_up_and_fail;
4851 PerlLIO_close(listener);
4852 /* Now check we are talking to ourself by matching port and host on the
4854 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4856 goto tidy_up_and_fail;
4857 if (size != sizeof(connect_addr)
4858 || listen_addr.sin_family != connect_addr.sin_family
4859 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4860 || listen_addr.sin_port != connect_addr.sin_port) {
4861 goto abort_tidy_up_and_fail;
4867 abort_tidy_up_and_fail:
4869 errno = ECONNABORTED; /* This would be the standard thing to do. */
4871 # ifdef ECONNREFUSED
4872 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4874 errno = ETIMEDOUT; /* Desperation time. */
4879 const int save_errno = errno;
4881 PerlLIO_close(listener);
4882 if (connector != -1)
4883 PerlLIO_close(connector);
4885 PerlLIO_close(acceptor);
4891 /* In any case have a stub so that there's code corresponding
4892 * to the my_socketpair in global.sym. */
4894 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4895 #ifdef HAS_SOCKETPAIR
4896 return socketpair(family, type, protocol, fd);
4905 =for apidoc sv_nosharing
4907 Dummy routine which "shares" an SV when there is no sharing module present.
4908 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4909 Exists to avoid test for a NULL function pointer and because it could
4910 potentially warn under some level of strict-ness.
4916 Perl_sv_nosharing(pTHX_ SV *sv)
4918 PERL_UNUSED_CONTEXT;
4919 PERL_UNUSED_ARG(sv);
4923 Perl_parse_unicode_opts(pTHX_ const char **popt)
4925 const char *p = *popt;
4930 opt = (U32) atoi(p);
4933 if (*p && *p != '\n' && *p != '\r')
4934 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4939 case PERL_UNICODE_STDIN:
4940 opt |= PERL_UNICODE_STDIN_FLAG; break;
4941 case PERL_UNICODE_STDOUT:
4942 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4943 case PERL_UNICODE_STDERR:
4944 opt |= PERL_UNICODE_STDERR_FLAG; break;
4945 case PERL_UNICODE_STD:
4946 opt |= PERL_UNICODE_STD_FLAG; break;
4947 case PERL_UNICODE_IN:
4948 opt |= PERL_UNICODE_IN_FLAG; break;
4949 case PERL_UNICODE_OUT:
4950 opt |= PERL_UNICODE_OUT_FLAG; break;
4951 case PERL_UNICODE_INOUT:
4952 opt |= PERL_UNICODE_INOUT_FLAG; break;
4953 case PERL_UNICODE_LOCALE:
4954 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4955 case PERL_UNICODE_ARGV:
4956 opt |= PERL_UNICODE_ARGV_FLAG; break;
4957 case PERL_UNICODE_UTF8CACHEASSERT:
4958 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4960 if (*p != '\n' && *p != '\r')
4962 "Unknown Unicode option letter '%c'", *p);
4968 opt = PERL_UNICODE_DEFAULT_FLAGS;
4970 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4971 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4972 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4984 * This is really just a quick hack which grabs various garbage
4985 * values. It really should be a real hash algorithm which
4986 * spreads the effect of every input bit onto every output bit,
4987 * if someone who knows about such things would bother to write it.
4988 * Might be a good idea to add that function to CORE as well.
4989 * No numbers below come from careful analysis or anything here,
4990 * except they are primes and SEED_C1 > 1E6 to get a full-width
4991 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4992 * probably be bigger too.
4995 # define SEED_C1 1000003
4996 #define SEED_C4 73819
4998 # define SEED_C1 25747
4999 #define SEED_C4 20639
5003 #define SEED_C5 26107
5005 #ifndef PERL_NO_DEV_RANDOM
5010 # include <starlet.h>
5011 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5012 * in 100-ns units, typically incremented ever 10 ms. */
5013 unsigned int when[2];
5015 # ifdef HAS_GETTIMEOFDAY
5016 struct timeval when;
5022 /* This test is an escape hatch, this symbol isn't set by Configure. */
5023 #ifndef PERL_NO_DEV_RANDOM
5024 #ifndef PERL_RANDOM_DEVICE
5025 /* /dev/random isn't used by default because reads from it will block
5026 * if there isn't enough entropy available. You can compile with
5027 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5028 * is enough real entropy to fill the seed. */
5029 # define PERL_RANDOM_DEVICE "/dev/urandom"
5031 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5033 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5042 _ckvmssts(sys$gettim(when));
5043 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5045 # ifdef HAS_GETTIMEOFDAY
5046 PerlProc_gettimeofday(&when,NULL);
5047 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5050 u = (U32)SEED_C1 * when;
5053 u += SEED_C3 * (U32)PerlProc_getpid();
5054 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5055 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5056 u += SEED_C5 * (U32)PTR2UV(&when);
5062 Perl_get_hash_seed(pTHX)
5065 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5071 if (s && isDIGIT(*s))
5072 myseed = (UV)Atoul(s);
5074 #ifdef USE_HASH_SEED_EXPLICIT
5078 /* Compute a random seed */
5079 (void)seedDrand01((Rand_seed_t)seed());
5080 myseed = (UV)(Drand01() * (NV)UV_MAX);
5081 #if RANDBITS < (UVSIZE * 8)
5082 /* Since there are not enough randbits to to reach all
5083 * the bits of a UV, the low bits might need extra
5084 * help. Sum in another random number that will
5085 * fill in the low bits. */
5087 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
5088 #endif /* RANDBITS < (UVSIZE * 8) */
5089 if (myseed == 0) { /* Superparanoia. */
5090 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5092 Perl_croak(aTHX_ "Your random numbers are not that random");
5095 PL_rehash_seed_set = TRUE;
5102 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5104 const char * const stashpv = CopSTASHPV(c);
5105 const char * const name = HvNAME_get(hv);
5106 PERL_UNUSED_CONTEXT;
5108 if (stashpv == name)
5110 if (stashpv && name)
5111 if (strEQ(stashpv, name))
5118 #ifdef PERL_GLOBAL_STRUCT
5121 Perl_init_global_struct(pTHX)
5123 struct perl_vars *plvarsp = NULL;
5124 #ifdef PERL_GLOBAL_STRUCT
5125 # define PERL_GLOBAL_STRUCT_INIT
5126 # include "opcode.h" /* the ppaddr and check */
5127 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5128 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5129 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5130 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5131 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5135 plvarsp = PL_VarsPtr;
5136 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5142 # define PERLVAR(var,type) /**/
5143 # define PERLVARA(var,n,type) /**/
5144 # define PERLVARI(var,type,init) plvarsp->var = init;
5145 # define PERLVARIC(var,type,init) plvarsp->var = init;
5146 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5147 # include "perlvars.h"
5153 # ifdef PERL_GLOBAL_STRUCT
5154 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5155 if (!plvarsp->Gppaddr)
5157 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5158 if (!plvarsp->Gcheck)
5160 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5161 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5163 # ifdef PERL_SET_VARS
5164 PERL_SET_VARS(plvarsp);
5166 # undef PERL_GLOBAL_STRUCT_INIT
5171 #endif /* PERL_GLOBAL_STRUCT */
5173 #ifdef PERL_GLOBAL_STRUCT
5176 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5178 #ifdef PERL_GLOBAL_STRUCT
5179 # ifdef PERL_UNSET_VARS
5180 PERL_UNSET_VARS(plvarsp);
5182 free(plvarsp->Gppaddr);
5183 free(plvarsp->Gcheck);
5184 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5190 #endif /* PERL_GLOBAL_STRUCT */
5195 * PERL_MEM_LOG: the Perl_mem_log_..() will be compiled.
5197 * PERL_MEM_LOG_ENV: if defined, during run time the environment
5198 * variable PERL_MEM_LOG will be consulted, and if the integer value
5199 * of that is true, the logging will happen. (The default is to
5200 * always log if the PERL_MEM_LOG define was in effect.)
5204 * PERL_MEM_LOG_SPRINTF_BUF_SIZE: size of a (stack-allocated) buffer
5205 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5207 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5210 * PERL_MEM_LOG_FD: the file descriptor the Perl_mem_log_...() will
5211 * log to. You can also define in compile time PERL_MEM_LOG_ENV_FD,
5212 * in which case the environment variable PERL_MEM_LOG_FD will be
5213 * consulted for the file descriptor number to use.
5215 #ifndef PERL_MEM_LOG_FD
5216 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5220 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)
5222 #ifdef PERL_MEM_LOG_STDERR
5223 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5226 # ifdef PERL_MEM_LOG_ENV
5227 s = getenv("PERL_MEM_LOG");
5228 if (s ? atoi(s) : 0)
5231 /* We can't use SVs or PerlIO for obvious reasons,
5232 * so we'll use stdio and low-level IO instead. */
5233 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5234 # ifdef PERL_MEM_LOG_TIMESTAMP
5236 # ifdef HAS_GETTIMEOFDAY
5237 gettimeofday(&tv, 0);
5239 /* If there are other OS specific ways of hires time than
5240 * gettimeofday() (see ext/Time/HiRes), the easiest way is
5241 * probably that they would be used to fill in the struct
5248 # ifdef PERL_MEM_LOG_TIMESTAMP
5251 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5252 " %s = %"IVdf": %"UVxf"\n",
5253 # ifdef PERL_MEM_LOG_TIMESTAMP
5254 (int)tv.tv_sec, (int)tv.tv_usec,
5256 filename, linenumber, funcname, n, typesize,
5257 typename, n * typesize, PTR2UV(newalloc));
5258 # ifdef PERL_MEM_LOG_ENV_FD
5259 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5260 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5262 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5271 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)
5273 #ifdef PERL_MEM_LOG_STDERR
5274 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5277 # ifdef PERL_MEM_LOG_ENV
5278 s = PerlEnv_getenv("PERL_MEM_LOG");
5279 if (s ? atoi(s) : 0)
5282 /* We can't use SVs or PerlIO for obvious reasons,
5283 * so we'll use stdio and low-level IO instead. */
5284 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5285 # ifdef PERL_MEM_LOG_TIMESTAMP
5287 gettimeofday(&tv, 0);
5293 # ifdef PERL_MEM_LOG_TIMESTAMP
5296 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5297 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5298 # ifdef PERL_MEM_LOG_TIMESTAMP
5299 (int)tv.tv_sec, (int)tv.tv_usec,
5301 filename, linenumber, funcname, n, typesize,
5302 typename, n * typesize, PTR2UV(oldalloc),
5304 # ifdef PERL_MEM_LOG_ENV_FD
5305 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5306 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5308 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5317 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5319 #ifdef PERL_MEM_LOG_STDERR
5320 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5323 # ifdef PERL_MEM_LOG_ENV
5324 s = PerlEnv_getenv("PERL_MEM_LOG");
5325 if (s ? atoi(s) : 0)
5328 /* We can't use SVs or PerlIO for obvious reasons,
5329 * so we'll use stdio and low-level IO instead. */
5330 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5331 # ifdef PERL_MEM_LOG_TIMESTAMP
5333 gettimeofday(&tv, 0);
5339 # ifdef PERL_MEM_LOG_TIMESTAMP
5342 "free: %s:%d:%s: %"UVxf"\n",
5343 # ifdef PERL_MEM_LOG_TIMESTAMP
5344 (int)tv.tv_sec, (int)tv.tv_usec,
5346 filename, linenumber, funcname,
5348 # ifdef PERL_MEM_LOG_ENV_FD
5349 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5350 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5352 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5360 #endif /* PERL_MEM_LOG */
5363 =for apidoc my_sprintf
5365 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5366 the length of the string written to the buffer. Only rare pre-ANSI systems
5367 need the wrapper function - usually this is a direct call to C<sprintf>.
5371 #ifndef SPRINTF_RETURNS_STRLEN
5373 Perl_my_sprintf(char *buffer, const char* pat, ...)
5376 va_start(args, pat);
5377 vsprintf(buffer, pat, args);
5379 return strlen(buffer);
5384 =for apidoc my_snprintf
5386 The C library C<snprintf> functionality, if available and
5387 standards-compliant (uses C<vsnprintf>, actually). However, if the
5388 C<vsnprintf> is not available, will unfortunately use the unsafe
5389 C<vsprintf> which can overrun the buffer (there is an overrun check,
5390 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5391 getting C<vsnprintf>.
5396 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5401 va_start(ap, format);
5402 #ifdef HAS_VSNPRINTF
5403 retval = vsnprintf(buffer, len, format, ap);
5405 retval = vsprintf(buffer, format, ap);
5408 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5409 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5410 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
5415 =for apidoc my_vsnprintf
5417 The C library C<vsnprintf> if available and standards-compliant.
5418 However, if if the C<vsnprintf> is not available, will unfortunately
5419 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5420 overrun check, but that may be too late). Consider using
5421 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5426 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5432 Perl_va_copy(ap, apc);
5433 # ifdef HAS_VSNPRINTF
5434 retval = vsnprintf(buffer, len, format, apc);
5436 retval = vsprintf(buffer, format, apc);
5439 # ifdef HAS_VSNPRINTF
5440 retval = vsnprintf(buffer, len, format, ap);
5442 retval = vsprintf(buffer, format, ap);
5444 #endif /* #ifdef NEED_VA_COPY */
5445 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5446 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5447 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
5452 Perl_my_clearenv(pTHX)
5455 #if ! defined(PERL_MICRO)
5456 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5458 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5459 # if defined(USE_ENVIRON_ARRAY)
5460 # if defined(USE_ITHREADS)
5461 /* only the parent thread can clobber the process environment */
5462 if (PL_curinterp == aTHX)
5463 # endif /* USE_ITHREADS */
5465 # if ! defined(PERL_USE_SAFE_PUTENV)
5466 if ( !PL_use_safe_putenv) {
5468 if (environ == PL_origenviron)
5469 environ = (char**)safesysmalloc(sizeof(char*));
5471 for (i = 0; environ[i]; i++)
5472 (void)safesysfree(environ[i]);
5475 # else /* PERL_USE_SAFE_PUTENV */
5476 # if defined(HAS_CLEARENV)
5478 # elif defined(HAS_UNSETENV)
5479 int bsiz = 80; /* Most envvar names will be shorter than this. */
5480 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
5481 char *buf = (char*)safesysmalloc(bufsiz);
5482 while (*environ != NULL) {
5483 char *e = strchr(*environ, '=');
5484 int l = e ? e - *environ : (int)strlen(*environ);
5486 (void)safesysfree(buf);
5487 bsiz = l + 1; /* + 1 for the \0. */
5488 buf = (char*)safesysmalloc(bufsiz);
5490 my_strlcpy(buf, *environ, l + 1);
5491 (void)unsetenv(buf);
5493 (void)safesysfree(buf);
5494 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5495 /* Just null environ and accept the leakage. */
5497 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5498 # endif /* ! PERL_USE_SAFE_PUTENV */
5500 # endif /* USE_ENVIRON_ARRAY */
5501 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5502 #endif /* PERL_MICRO */
5505 #ifdef PERL_IMPLICIT_CONTEXT
5507 /* implements the MY_CXT_INIT macro. The first time a module is loaded,
5508 the global PL_my_cxt_index is incremented, and that value is assigned to
5509 that module's static my_cxt_index (who's address is passed as an arg).
5510 Then, for each interpreter this function is called for, it makes sure a
5511 void* slot is available to hang the static data off, by allocating or
5512 extending the interpreter's PL_my_cxt_list array */
5515 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5520 /* this module hasn't been allocated an index yet */
5521 MUTEX_LOCK(&PL_my_ctx_mutex);
5522 *index = PL_my_cxt_index++;
5523 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5526 /* make sure the array is big enough */
5527 if (PL_my_cxt_size <= *index) {
5528 if (PL_my_cxt_size) {
5529 while (PL_my_cxt_size <= *index)
5530 PL_my_cxt_size *= 2;
5531 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5534 PL_my_cxt_size = 16;
5535 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5538 /* newSV() allocates one more than needed */
5539 p = (void*)SvPVX(newSV(size-1));
5540 PL_my_cxt_list[*index] = p;
5541 Zero(p, size, char);
5548 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5550 Size_t used, length, copy;
5553 length = strlen(src);
5554 if (size > 0 && used < size - 1) {
5555 copy = (length >= size - used) ? size - used - 1 : length;
5556 memcpy(dst + used, src, copy);
5557 dst[used + copy] = '\0';
5559 return used + length;
5565 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5567 Size_t length, copy;
5569 length = strlen(src);
5571 copy = (length >= size) ? size - 1 : length;
5572 memcpy(dst, src, copy);
5580 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5583 SV * const dbsv = GvSVn(PL_DBsub);
5584 /* We do not care about using sv to call CV;
5585 * it's for informational purposes only.
5589 if (!PERLDB_SUB_NN) {
5590 GV * const gv = CvGV(cv);
5592 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
5593 || strEQ(GvNAME(gv), "END")
5594 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
5595 !( (SvTYPE(*svp) == SVt_PVGV) && (GvCV((GV*)*svp) == cv) )))) {
5596 /* Use GV from the stack as a fallback. */
5597 /* GV is potentially non-unique, or contain different CV. */
5598 SV * const tmp = newRV((SV*)cv);
5599 sv_setsv(dbsv, tmp);
5603 gv_efullname3(dbsv, gv, NULL);
5607 const int type = SvTYPE(dbsv);
5608 if (type < SVt_PVIV && type != SVt_IV)
5609 sv_upgrade(dbsv, SVt_PVIV);
5610 (void)SvIOK_on(dbsv);
5611 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5617 * c-indentation-style: bsd
5619 * indent-tabs-mode: t
5622 * ex: set ts=8 sts=4 sw=4 noet: