3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content." --Gandalf
16 /* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
23 #define PERL_IN_UTIL_C
29 # define SIG_ERR ((Sighandler_t) -1)
34 /* Missing protos on LynxOS */
39 # include <sys/wait.h>
44 # include <sys/select.h>
50 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51 # define FD_CLOEXEC 1 /* NeXT needs this */
54 /* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
60 /* paranoid version of system's malloc() */
63 Perl_safesysmalloc(MEM_SIZE size)
69 PerlIO_printf(Perl_error_log,
70 "Allocation too large: %lx\n", size) FLUSH;
73 #endif /* HAS_64K_LIMIT */
76 Perl_croak_nocontext("panic: malloc");
78 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
79 PERL_ALLOC_CHECK(ptr);
80 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
86 /* Can't use PerlIO to write as it allocates memory */
87 PerlLIO_write(PerlIO_fileno(Perl_error_log),
88 PL_no_mem, strlen(PL_no_mem));
95 /* paranoid version of system's realloc() */
98 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
102 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
103 Malloc_t PerlMem_realloc();
104 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
108 PerlIO_printf(Perl_error_log,
109 "Reallocation too large: %lx\n", size) FLUSH;
112 #endif /* HAS_64K_LIMIT */
119 return safesysmalloc(size);
122 Perl_croak_nocontext("panic: realloc");
124 ptr = (Malloc_t)PerlMem_realloc(where,size);
125 PERL_ALLOC_CHECK(ptr);
127 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
128 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
135 /* Can't use PerlIO to write as it allocates memory */
136 PerlLIO_write(PerlIO_fileno(Perl_error_log),
137 PL_no_mem, strlen(PL_no_mem));
144 /* safe version of system's free() */
147 Perl_safesysfree(Malloc_t where)
149 #ifdef PERL_IMPLICIT_SYS
152 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
159 /* safe version of system's calloc() */
162 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
168 if (size * count > 0xffff) {
169 PerlIO_printf(Perl_error_log,
170 "Allocation too large: %lx\n", size * count) FLUSH;
173 #endif /* HAS_64K_LIMIT */
175 if ((long)size < 0 || (long)count < 0)
176 Perl_croak_nocontext("panic: calloc");
179 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
180 PERL_ALLOC_CHECK(ptr);
181 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));
183 memset((void*)ptr, 0, size);
189 /* Can't use PerlIO to write as it allocates memory */
190 PerlLIO_write(PerlIO_fileno(Perl_error_log),
191 PL_no_mem, strlen(PL_no_mem));
198 /* These must be defined when not using Perl's malloc for binary
203 Malloc_t Perl_malloc (MEM_SIZE nbytes)
206 return (Malloc_t)PerlMem_malloc(nbytes);
209 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
212 return (Malloc_t)PerlMem_calloc(elements, size);
215 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
218 return (Malloc_t)PerlMem_realloc(where, nbytes);
221 Free_t Perl_mfree (Malloc_t where)
229 /* copy a string up to some (non-backslashed) delimiter, if any */
232 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
235 for (tolen = 0; from < fromend; from++, tolen++) {
237 if (from[1] == delim)
246 else if (*from == delim)
257 /* return ptr to little string in big string, NULL if not found */
258 /* This routine was donated by Corey Satten. */
261 Perl_instr(pTHX_ register const char *big, register const char *little)
263 register const char *s, *x;
274 for (x=big,s=little; *s; /**/ ) {
283 return (char*)(big-1);
288 /* same as instr but allow embedded nulls */
291 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
293 register const char *s, *x;
294 register const I32 first = *little;
295 register const char *littleend = lend;
297 if (!first && little >= littleend)
299 if (bigend - big < littleend - little)
301 bigend -= littleend - little++;
302 while (big <= bigend) {
305 for (x=big,s=little; s < littleend; /**/ ) {
312 return (char*)(big-1);
317 /* reverse of the above--find last substring */
320 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
322 register const char *bigbeg;
323 register const char *s, *x;
324 register const I32 first = *little;
325 register const char *littleend = lend;
327 if (!first && little >= littleend)
328 return (char*)bigend;
330 big = bigend - (littleend - little++);
331 while (big >= bigbeg) {
334 for (x=big+2,s=little; s < littleend; /**/ ) {
341 return (char*)(big+1);
346 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
348 /* As a space optimization, we do not compile tables for strings of length
349 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
350 special-cased in fbm_instr().
352 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
355 =head1 Miscellaneous Functions
357 =for apidoc fbm_compile
359 Analyses the string in order to make fast searches on it using fbm_instr()
360 -- the Boyer-Moore algorithm.
366 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
368 const register U8 *s;
375 if (flags & FBMcf_TAIL) {
376 MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
377 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
378 if (mg && mg->mg_len >= 0)
381 s = (U8*)SvPV_force_mutable(sv, len);
382 (void)SvUPGRADE(sv, SVt_PVBM);
383 if (len == 0) /* TAIL might be on a zero-length string. */
387 const unsigned char *sb;
393 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
394 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
395 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
396 memset((void*)table, mlen, 256);
397 table[-1] = (U8)flags;
399 sb = s - mlen + 1; /* first char (maybe) */
401 if (table[*s] == mlen)
406 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
409 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
410 for (i = 0; i < len; i++) {
411 if (PL_freq[s[i]] < frequency) {
413 frequency = PL_freq[s[i]];
416 BmRARE(sv) = s[rarest];
417 BmPREVIOUS(sv) = (U16)rarest;
418 BmUSEFUL(sv) = 100; /* Initial value */
419 if (flags & FBMcf_TAIL)
421 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
422 BmRARE(sv),BmPREVIOUS(sv)));
425 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
426 /* If SvTAIL is actually due to \Z or \z, this gives false positives
430 =for apidoc fbm_instr
432 Returns the location of the SV in the string delimited by C<str> and
433 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
434 does not have to be fbm_compiled, but the search will not be as fast
441 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
443 register unsigned char *s;
445 register const unsigned char *little
446 = (const unsigned char *)SvPV_const(littlestr,l);
447 register STRLEN littlelen = l;
448 register const I32 multiline = flags & FBMrf_MULTILINE;
450 if ((STRLEN)(bigend - big) < littlelen) {
451 if ( SvTAIL(littlestr)
452 && ((STRLEN)(bigend - big) == littlelen - 1)
454 || (*big == *little &&
455 memEQ(big, little, littlelen - 1))))
460 if (littlelen <= 2) { /* Special-cased */
462 if (littlelen == 1) {
463 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
464 /* Know that bigend != big. */
465 if (bigend[-1] == '\n')
466 return (char *)(bigend - 1);
467 return (char *) bigend;
475 if (SvTAIL(littlestr))
476 return (char *) bigend;
480 return (char*)big; /* Cannot be SvTAIL! */
483 if (SvTAIL(littlestr) && !multiline) {
484 if (bigend[-1] == '\n' && bigend[-2] == *little)
485 return (char*)bigend - 2;
486 if (bigend[-1] == *little)
487 return (char*)bigend - 1;
491 /* This should be better than FBM if c1 == c2, and almost
492 as good otherwise: maybe better since we do less indirection.
493 And we save a lot of memory by caching no table. */
494 register unsigned char c1 = little[0];
495 register unsigned char c2 = little[1];
500 while (s <= bigend) {
510 goto check_1char_anchor;
521 goto check_1char_anchor;
524 while (s <= bigend) {
529 goto check_1char_anchor;
538 check_1char_anchor: /* One char and anchor! */
539 if (SvTAIL(littlestr) && (*bigend == *little))
540 return (char *)bigend; /* bigend is already decremented. */
543 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
544 s = bigend - littlelen;
545 if (s >= big && bigend[-1] == '\n' && *s == *little
546 /* Automatically of length > 2 */
547 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
549 return (char*)s; /* how sweet it is */
552 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
554 return (char*)s + 1; /* how sweet it is */
558 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
559 char *b = ninstr((char*)big,(char*)bigend,
560 (char*)little, (char*)little + littlelen);
562 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
563 /* Chop \n from littlestr: */
564 s = bigend - littlelen + 1;
566 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
575 { /* Do actual FBM. */
576 register const unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
577 const register unsigned char *oldlittle;
579 if (littlelen > (STRLEN)(bigend - big))
581 --littlelen; /* Last char found by table lookup */
584 little += littlelen; /* last char */
591 if ((tmp = table[*s])) {
592 if ((s += tmp) < bigend)
596 else { /* less expensive than calling strncmp() */
597 register unsigned char *olds = s;
602 if (*--s == *--little)
604 s = olds + 1; /* here we pay the price for failure */
606 if (s < bigend) /* fake up continue to outer loop */
614 if ( s == bigend && (table[-1] & FBMcf_TAIL)
615 && memEQ((char *)(bigend - littlelen),
616 (char *)(oldlittle - littlelen), littlelen) )
617 return (char*)bigend - littlelen;
622 /* start_shift, end_shift are positive quantities which give offsets
623 of ends of some substring of bigstr.
624 If "last" we want the last occurrence.
625 old_posp is the way of communication between consequent calls if
626 the next call needs to find the .
627 The initial *old_posp should be -1.
629 Note that we take into account SvTAIL, so one can get extra
630 optimizations if _ALL flag is set.
633 /* If SvTAIL is actually due to \Z or \z, this gives false positives
634 if PL_multiline. In fact if !PL_multiline the authoritative answer
635 is not supported yet. */
638 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
640 register unsigned char *s, *x;
641 register unsigned char *big;
643 register I32 previous;
645 register unsigned char *little;
646 register I32 stop_pos;
647 register unsigned char *littleend;
651 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
652 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
654 if ( BmRARE(littlestr) == '\n'
655 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
656 little = (unsigned char *)(SvPVX(littlestr));
657 littleend = little + SvCUR(littlestr);
664 little = (unsigned char *)(SvPVX(littlestr));
665 littleend = little + SvCUR(littlestr);
667 /* The value of pos we can start at: */
668 previous = BmPREVIOUS(littlestr);
669 big = (unsigned char *)(SvPVX(bigstr));
670 /* The value of pos we can stop at: */
671 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
672 if (previous + start_shift > stop_pos) {
674 stop_pos does not include SvTAIL in the count, so this check is incorrect
675 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
678 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
683 while (pos < previous + start_shift) {
684 if (!(pos += PL_screamnext[pos]))
689 if (pos >= stop_pos) break;
690 if (big[pos] != first)
692 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
698 if (s == littleend) {
700 if (!last) return (char *)(big+pos);
703 } while ( pos += PL_screamnext[pos] );
705 return (char *)(big+(*old_posp));
707 if (!SvTAIL(littlestr) || (end_shift > 0))
709 /* Ignore the trailing "\n". This code is not microoptimized */
710 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
711 stop_pos = littleend - little; /* Actual littlestr len */
716 && ((stop_pos == 1) ||
717 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
723 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
725 register const U8 *a = (const U8 *)s1;
726 register const U8 *b = (const U8 *)s2;
728 if (*a != *b && *a != PL_fold[*b])
736 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
738 register const U8 *a = (const U8 *)s1;
739 register const U8 *b = (const U8 *)s2;
741 if (*a != *b && *a != PL_fold_locale[*b])
748 /* copy a string to a safe spot */
751 =head1 Memory Management
755 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
756 string which is a duplicate of C<pv>. The size of the string is
757 determined by C<strlen()>. The memory allocated for the new string can
758 be freed with the C<Safefree()> function.
764 Perl_savepv(pTHX_ const char *pv)
766 register char *newaddr;
767 #ifdef PERL_MALLOC_WRAP
773 #ifdef PERL_MALLOC_WRAP
774 pvlen = strlen(pv)+1;
775 New(902,newaddr,pvlen,char);
777 New(902,newaddr,strlen(pv)+1,char);
779 return strcpy(newaddr,pv);
782 /* same thing but with a known length */
787 Perl's version of what C<strndup()> would be if it existed. Returns a
788 pointer to a newly allocated string which is a duplicate of the first
789 C<len> bytes from C<pv>. The memory allocated for the new string can be
790 freed with the C<Safefree()> function.
796 Perl_savepvn(pTHX_ const char *pv, register I32 len)
798 register char *newaddr;
800 New(903,newaddr,len+1,char);
801 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
803 /* might not be null terminated */
805 return (char *) CopyD(pv,newaddr,len,char);
808 return (char *) ZeroD(newaddr,len+1,char);
813 =for apidoc savesharedpv
815 A version of C<savepv()> which allocates the duplicate string in memory
816 which is shared between threads.
821 Perl_savesharedpv(pTHX_ const char *pv)
823 register char *newaddr;
827 newaddr = (char*)PerlMemShared_malloc(strlen(pv)+1);
829 PerlLIO_write(PerlIO_fileno(Perl_error_log),
830 PL_no_mem, strlen(PL_no_mem));
833 return strcpy(newaddr,pv);
839 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
840 the passed in SV using C<SvPV()>
846 Perl_savesvpv(pTHX_ SV *sv)
849 const char *pv = SvPV(sv, len);
850 register char *newaddr;
853 New(903,newaddr,len,char);
854 return (char *) CopyD(pv,newaddr,len,char);
858 /* the SV for Perl_form() and mess() is not kept in an arena */
867 return sv_2mortal(newSVpvn("",0));
872 /* Create as PVMG now, to avoid any upgrading later */
874 Newz(905, any, 1, XPVMG);
875 SvFLAGS(sv) = SVt_PVMG;
876 SvANY(sv) = (void*)any;
877 SvREFCNT(sv) = 1 << 30; /* practically infinite */
882 #if defined(PERL_IMPLICIT_CONTEXT)
884 Perl_form_nocontext(const char* pat, ...)
890 retval = vform(pat, &args);
894 #endif /* PERL_IMPLICIT_CONTEXT */
897 =head1 Miscellaneous Functions
900 Takes a sprintf-style format pattern and conventional
901 (non-SV) arguments and returns the formatted string.
903 (char *) Perl_form(pTHX_ const char* pat, ...)
905 can be used any place a string (char *) is required:
907 char * s = Perl_form("%d.%d",major,minor);
909 Uses a single private buffer so if you want to format several strings you
910 must explicitly copy the earlier strings away (and free the copies when you
917 Perl_form(pTHX_ const char* pat, ...)
922 retval = vform(pat, &args);
928 Perl_vform(pTHX_ const char *pat, va_list *args)
930 SV *sv = mess_alloc();
931 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
935 #if defined(PERL_IMPLICIT_CONTEXT)
937 Perl_mess_nocontext(const char *pat, ...)
943 retval = vmess(pat, &args);
947 #endif /* PERL_IMPLICIT_CONTEXT */
950 Perl_mess(pTHX_ const char *pat, ...)
955 retval = vmess(pat, &args);
961 S_closest_cop(pTHX_ COP *cop, OP *o)
963 /* Look for PL_op starting from o. cop is the last COP we've seen. */
965 if (!o || o == PL_op) return cop;
967 if (o->op_flags & OPf_KIDS) {
969 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
973 /* If the OP_NEXTSTATE has been optimised away we can still use it
974 * the get the file and line number. */
976 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
979 /* Keep searching, and return when we've found something. */
981 new_cop = closest_cop(cop, kid);
982 if (new_cop) return new_cop;
992 Perl_vmess(pTHX_ const char *pat, va_list *args)
994 SV *sv = mess_alloc();
995 static char dgd[] = " during global destruction.\n";
997 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
998 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1001 * Try and find the file and line for PL_op. This will usually be
1002 * PL_curcop, but it might be a cop that has been optimised away. We
1003 * can try to find such a cop by searching through the optree starting
1004 * from the sibling of PL_curcop.
1007 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1008 if (!cop) cop = PL_curcop;
1011 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1012 OutCopFILE(cop), (IV)CopLINE(cop));
1013 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1014 const bool line_mode = (RsSIMPLE(PL_rs) &&
1015 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1016 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1017 PL_last_in_gv == PL_argvgv ?
1018 "" : GvNAME(PL_last_in_gv),
1019 line_mode ? "line" : "chunk",
1020 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1022 #ifdef USE_5005THREADS
1024 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1026 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1032 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1037 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1038 && (io = GvIO(PL_stderrgv))
1039 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1046 SAVESPTR(PL_stderrgv);
1047 PL_stderrgv = Nullgv;
1049 PUSHSTACKi(PERLSI_MAGIC);
1053 PUSHs(SvTIED_obj((SV*)io, mg));
1054 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1056 call_method("PRINT", G_SCALAR);
1064 /* SFIO can really mess with your errno */
1067 PerlIO *serr = Perl_error_log;
1069 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1070 (void)PerlIO_flush(serr);
1077 /* Common code used by vcroak, vdie and vwarner */
1079 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1080 may have linked against it. */
1082 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1087 /* sv_2cv might call Perl_croak() */
1088 SV *olddiehook = PL_diehook;
1092 SAVESPTR(PL_diehook);
1093 PL_diehook = Nullsv;
1094 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1096 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1103 msg = newSVpvn(message, msglen);
1104 SvFLAGS(msg) |= utf8;
1112 PUSHSTACKi(PERLSI_DIEHOOK);
1116 call_sv((SV*)cv, G_DISCARD);
1122 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1123 may have linked against it. */
1125 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1131 SV *msv = vmess(pat, args);
1132 if (PL_errors && SvCUR(PL_errors)) {
1133 sv_catsv(PL_errors, msv);
1134 message = SvPV(PL_errors, *msglen);
1135 SvCUR_set(PL_errors, 0);
1138 message = SvPV(msv,*msglen);
1139 *utf8 = SvUTF8(msv);
1145 DEBUG_S(PerlIO_printf(Perl_debug_log,
1146 "%p: die/croak: message = %s\ndiehook = %p\n",
1147 thr, message, PL_diehook));
1149 S_vdie_common(aTHX_ message, *msglen, *utf8);
1155 Perl_vdie(pTHX_ const char* pat, va_list *args)
1157 const char *message;
1158 const int was_in_eval = PL_in_eval;
1162 DEBUG_S(PerlIO_printf(Perl_debug_log,
1163 "%p: die: curstack = %p, mainstack = %p\n",
1164 thr, PL_curstack, PL_mainstack));
1166 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1168 PL_restartop = die_where(message, msglen);
1169 SvFLAGS(ERRSV) |= utf8;
1170 DEBUG_S(PerlIO_printf(Perl_debug_log,
1171 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1172 thr, PL_restartop, was_in_eval, PL_top_env));
1173 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1175 return PL_restartop;
1178 #if defined(PERL_IMPLICIT_CONTEXT)
1180 Perl_die_nocontext(const char* pat, ...)
1185 va_start(args, pat);
1186 o = vdie(pat, &args);
1190 #endif /* PERL_IMPLICIT_CONTEXT */
1193 Perl_die(pTHX_ const char* pat, ...)
1197 va_start(args, pat);
1198 o = vdie(pat, &args);
1204 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1206 const char *message;
1210 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1213 PL_restartop = die_where(message, msglen);
1214 SvFLAGS(ERRSV) |= utf8;
1218 message = SvPVx(ERRSV, msglen);
1220 write_to_stderr(message, msglen);
1224 #if defined(PERL_IMPLICIT_CONTEXT)
1226 Perl_croak_nocontext(const char *pat, ...)
1230 va_start(args, pat);
1235 #endif /* PERL_IMPLICIT_CONTEXT */
1238 =head1 Warning and Dieing
1242 This is the XSUB-writer's interface to Perl's C<die> function.
1243 Normally call this function the same way you call the C C<printf>
1244 function. Calling C<croak> returns control directly to Perl,
1245 sidestepping the normal C order of execution. See C<warn>.
1247 If you want to throw an exception object, assign the object to
1248 C<$@> and then pass C<Nullch> to croak():
1250 errsv = get_sv("@", TRUE);
1251 sv_setsv(errsv, exception_object);
1258 Perl_croak(pTHX_ const char *pat, ...)
1261 va_start(args, pat);
1268 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1278 msv = vmess(pat, args);
1280 message = SvPV(msv, msglen);
1283 /* sv_2cv might call Perl_warn() */
1284 SV *oldwarnhook = PL_warnhook;
1286 SAVESPTR(PL_warnhook);
1287 PL_warnhook = Nullsv;
1288 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1290 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1296 msg = newSVpvn(message, msglen);
1297 SvFLAGS(msg) |= utf8;
1301 PUSHSTACKi(PERLSI_WARNHOOK);
1305 call_sv((SV*)cv, G_DISCARD);
1312 write_to_stderr(message, msglen);
1315 #if defined(PERL_IMPLICIT_CONTEXT)
1317 Perl_warn_nocontext(const char *pat, ...)
1321 va_start(args, pat);
1325 #endif /* PERL_IMPLICIT_CONTEXT */
1330 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1331 function the same way you call the C C<printf> function. See C<croak>.
1337 Perl_warn(pTHX_ const char *pat, ...)
1340 va_start(args, pat);
1345 #if defined(PERL_IMPLICIT_CONTEXT)
1347 Perl_warner_nocontext(U32 err, const char *pat, ...)
1351 va_start(args, pat);
1352 vwarner(err, pat, &args);
1355 #endif /* PERL_IMPLICIT_CONTEXT */
1358 Perl_warner(pTHX_ U32 err, const char* pat,...)
1361 va_start(args, pat);
1362 vwarner(err, pat, &args);
1367 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1370 SV * const msv = vmess(pat, args);
1372 const char *message = SvPV(msv, msglen);
1373 const I32 utf8 = SvUTF8(msv);
1375 #ifdef USE_5005THREADS
1376 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1377 #endif /* USE_5005THREADS */
1380 S_vdie_common(aTHX_ message, msglen, utf8);
1383 PL_restartop = die_where(message, msglen);
1384 SvFLAGS(ERRSV) |= utf8;
1387 write_to_stderr(message, msglen);
1391 Perl_vwarn(aTHX_ pat, args);
1395 /* since we've already done strlen() for both nam and val
1396 * we can use that info to make things faster than
1397 * sprintf(s, "%s=%s", nam, val)
1399 #define my_setenv_format(s, nam, nlen, val, vlen) \
1400 Copy(nam, s, nlen, char); \
1402 Copy(val, s+(nlen+1), vlen, char); \
1403 *(s+(nlen+1+vlen)) = '\0'
1405 #ifdef USE_ENVIRON_ARRAY
1406 /* VMS' my_setenv() is in vms.c */
1407 #if !defined(WIN32) && !defined(NETWARE)
1409 Perl_my_setenv(pTHX_ char *nam, char *val)
1412 /* only parent thread can modify process environment */
1413 if (PL_curinterp == aTHX)
1416 #ifndef PERL_USE_SAFE_PUTENV
1417 if (!PL_use_safe_putenv) {
1418 /* most putenv()s leak, so we manipulate environ directly */
1419 register I32 i=setenv_getix(nam); /* where does it go? */
1422 if (environ == PL_origenviron) { /* need we copy environment? */
1428 for (max = i; environ[max]; max++) ;
1429 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1430 for (j=0; j<max; j++) { /* copy environment */
1431 const int len = strlen(environ[j]);
1432 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1433 Copy(environ[j], tmpenv[j], len+1, char);
1435 tmpenv[max] = Nullch;
1436 environ = tmpenv; /* tell exec where it is now */
1439 safesysfree(environ[i]);
1440 while (environ[i]) {
1441 environ[i] = environ[i+1];
1446 if (!environ[i]) { /* does not exist yet */
1447 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1448 environ[i+1] = Nullch; /* make sure it's null terminated */
1451 safesysfree(environ[i]);
1455 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1456 /* all that work just for this */
1457 my_setenv_format(environ[i], nam, nlen, val, vlen);
1460 # if defined(__CYGWIN__) || defined( EPOC)
1461 setenv(nam, val, 1);
1464 int nlen = strlen(nam), vlen;
1469 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1470 /* all that work just for this */
1471 my_setenv_format(new_env, nam, nlen, val, vlen);
1472 (void)putenv(new_env);
1473 # endif /* __CYGWIN__ */
1474 #ifndef PERL_USE_SAFE_PUTENV
1480 #else /* WIN32 || NETWARE */
1483 Perl_my_setenv(pTHX_ const char *nam, char *val)
1485 register char *envstr;
1486 const int nlen = strlen(nam);
1493 New(904, envstr, nlen+vlen+2, char);
1494 my_setenv_format(envstr, nam, nlen, val, vlen);
1495 (void)PerlEnv_putenv(envstr);
1499 #endif /* WIN32 || NETWARE */
1503 Perl_setenv_getix(pTHX_ char *nam)
1505 register I32 i, len = strlen(nam);
1507 for (i = 0; environ[i]; i++) {
1510 strnicmp(environ[i],nam,len) == 0
1512 strnEQ(environ[i],nam,len)
1514 && environ[i][len] == '=')
1515 break; /* strnEQ must come first to avoid */
1516 } /* potential SEGV's */
1519 #endif /* !PERL_MICRO */
1521 #endif /* !VMS && !EPOC*/
1523 #ifdef UNLINK_ALL_VERSIONS
1525 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1529 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1534 /* this is a drop-in replacement for bcopy() */
1535 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1537 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1541 if (from - to >= 0) {
1549 *(--to) = *(--from);
1555 /* this is a drop-in replacement for memset() */
1558 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1568 /* this is a drop-in replacement for bzero() */
1569 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1571 Perl_my_bzero(register char *loc, register I32 len)
1581 /* this is a drop-in replacement for memcmp() */
1582 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1584 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1586 register const U8 *a = (const U8 *)s1;
1587 register const U8 *b = (const U8 *)s2;
1591 if (tmp = *a++ - *b++)
1596 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1600 #ifdef USE_CHAR_VSPRINTF
1605 vsprintf(char *dest, const char *pat, char *args)
1609 fakebuf._ptr = dest;
1610 fakebuf._cnt = 32767;
1614 fakebuf._flag = _IOWRT|_IOSTRG;
1615 _doprnt(pat, args, &fakebuf); /* what a kludge */
1616 (void)putc('\0', &fakebuf);
1617 #ifdef USE_CHAR_VSPRINTF
1620 return 0; /* perl doesn't use return value */
1624 #endif /* HAS_VPRINTF */
1627 #if BYTEORDER != 0x4321
1629 Perl_my_swap(pTHX_ short s)
1631 #if (BYTEORDER & 1) == 0
1634 result = ((s & 255) << 8) + ((s >> 8) & 255);
1642 Perl_my_htonl(pTHX_ long l)
1646 char c[sizeof(long)];
1649 #if BYTEORDER == 0x1234
1650 u.c[0] = (l >> 24) & 255;
1651 u.c[1] = (l >> 16) & 255;
1652 u.c[2] = (l >> 8) & 255;
1656 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1657 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1662 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1663 u.c[o & 0xf] = (l >> s) & 255;
1671 Perl_my_ntohl(pTHX_ long l)
1675 char c[sizeof(long)];
1678 #if BYTEORDER == 0x1234
1679 u.c[0] = (l >> 24) & 255;
1680 u.c[1] = (l >> 16) & 255;
1681 u.c[2] = (l >> 8) & 255;
1685 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1686 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1693 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1694 l |= (u.c[o & 0xf] & 255) << s;
1701 #endif /* BYTEORDER != 0x4321 */
1705 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1706 * If these functions are defined,
1707 * the BYTEORDER is neither 0x1234 nor 0x4321.
1708 * However, this is not assumed.
1712 #define HTOLE(name,type) \
1714 name (register type n) \
1718 char c[sizeof(type)]; \
1721 register I32 s = 0; \
1722 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1723 u.c[i] = (n >> s) & 0xFF; \
1728 #define LETOH(name,type) \
1730 name (register type n) \
1734 char c[sizeof(type)]; \
1737 register I32 s = 0; \
1740 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1741 n |= ((type)(u.c[i] & 0xFF)) << s; \
1747 * Big-endian byte order functions.
1750 #define HTOBE(name,type) \
1752 name (register type n) \
1756 char c[sizeof(type)]; \
1759 register I32 s = 8*(sizeof(u.c)-1); \
1760 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1761 u.c[i] = (n >> s) & 0xFF; \
1766 #define BETOH(name,type) \
1768 name (register type n) \
1772 char c[sizeof(type)]; \
1775 register I32 s = 8*(sizeof(u.c)-1); \
1778 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1779 n |= ((type)(u.c[i] & 0xFF)) << s; \
1785 * If we just can't do it...
1788 #define NOT_AVAIL(name,type) \
1790 name (register type n) \
1792 Perl_croak_nocontext(#name "() not available"); \
1793 return n; /* not reached */ \
1797 #if defined(HAS_HTOVS) && !defined(htovs)
1800 #if defined(HAS_HTOVL) && !defined(htovl)
1803 #if defined(HAS_VTOHS) && !defined(vtohs)
1806 #if defined(HAS_VTOHL) && !defined(vtohl)
1810 #ifdef PERL_NEED_MY_HTOLE16
1812 HTOLE(Perl_my_htole16,U16)
1814 NOT_AVAIL(Perl_my_htole16,U16)
1817 #ifdef PERL_NEED_MY_LETOH16
1819 LETOH(Perl_my_letoh16,U16)
1821 NOT_AVAIL(Perl_my_letoh16,U16)
1824 #ifdef PERL_NEED_MY_HTOBE16
1826 HTOBE(Perl_my_htobe16,U16)
1828 NOT_AVAIL(Perl_my_htobe16,U16)
1831 #ifdef PERL_NEED_MY_BETOH16
1833 BETOH(Perl_my_betoh16,U16)
1835 NOT_AVAIL(Perl_my_betoh16,U16)
1839 #ifdef PERL_NEED_MY_HTOLE32
1841 HTOLE(Perl_my_htole32,U32)
1843 NOT_AVAIL(Perl_my_htole32,U32)
1846 #ifdef PERL_NEED_MY_LETOH32
1848 LETOH(Perl_my_letoh32,U32)
1850 NOT_AVAIL(Perl_my_letoh32,U32)
1853 #ifdef PERL_NEED_MY_HTOBE32
1855 HTOBE(Perl_my_htobe32,U32)
1857 NOT_AVAIL(Perl_my_htobe32,U32)
1860 #ifdef PERL_NEED_MY_BETOH32
1862 BETOH(Perl_my_betoh32,U32)
1864 NOT_AVAIL(Perl_my_betoh32,U32)
1868 #ifdef PERL_NEED_MY_HTOLE64
1870 HTOLE(Perl_my_htole64,U64)
1872 NOT_AVAIL(Perl_my_htole64,U64)
1875 #ifdef PERL_NEED_MY_LETOH64
1877 LETOH(Perl_my_letoh64,U64)
1879 NOT_AVAIL(Perl_my_letoh64,U64)
1882 #ifdef PERL_NEED_MY_HTOBE64
1884 HTOBE(Perl_my_htobe64,U64)
1886 NOT_AVAIL(Perl_my_htobe64,U64)
1889 #ifdef PERL_NEED_MY_BETOH64
1891 BETOH(Perl_my_betoh64,U64)
1893 NOT_AVAIL(Perl_my_betoh64,U64)
1897 #ifdef PERL_NEED_MY_HTOLES
1898 HTOLE(Perl_my_htoles,short)
1900 #ifdef PERL_NEED_MY_LETOHS
1901 LETOH(Perl_my_letohs,short)
1903 #ifdef PERL_NEED_MY_HTOBES
1904 HTOBE(Perl_my_htobes,short)
1906 #ifdef PERL_NEED_MY_BETOHS
1907 BETOH(Perl_my_betohs,short)
1910 #ifdef PERL_NEED_MY_HTOLEI
1911 HTOLE(Perl_my_htolei,int)
1913 #ifdef PERL_NEED_MY_LETOHI
1914 LETOH(Perl_my_letohi,int)
1916 #ifdef PERL_NEED_MY_HTOBEI
1917 HTOBE(Perl_my_htobei,int)
1919 #ifdef PERL_NEED_MY_BETOHI
1920 BETOH(Perl_my_betohi,int)
1923 #ifdef PERL_NEED_MY_HTOLEL
1924 HTOLE(Perl_my_htolel,long)
1926 #ifdef PERL_NEED_MY_LETOHL
1927 LETOH(Perl_my_letohl,long)
1929 #ifdef PERL_NEED_MY_HTOBEL
1930 HTOBE(Perl_my_htobel,long)
1932 #ifdef PERL_NEED_MY_BETOHL
1933 BETOH(Perl_my_betohl,long)
1937 Perl_my_swabn(void *ptr, int n)
1939 register char *s = (char *)ptr;
1940 register char *e = s + (n-1);
1943 for (n /= 2; n > 0; s++, e--, n--) {
1951 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1953 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1955 register I32 This, that;
1961 PERL_FLUSHALL_FOR_CHILD;
1962 This = (*mode == 'w');
1966 taint_proper("Insecure %s%s", "EXEC");
1968 if (PerlProc_pipe(p) < 0)
1970 /* Try for another pipe pair for error return */
1971 if (PerlProc_pipe(pp) >= 0)
1973 while ((pid = PerlProc_fork()) < 0) {
1974 if (errno != EAGAIN) {
1975 PerlLIO_close(p[This]);
1976 PerlLIO_close(p[that]);
1978 PerlLIO_close(pp[0]);
1979 PerlLIO_close(pp[1]);
1991 /* Close parent's end of error status pipe (if any) */
1993 PerlLIO_close(pp[0]);
1994 #if defined(HAS_FCNTL) && defined(F_SETFD)
1995 /* Close error pipe automatically if exec works */
1996 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1999 /* Now dup our end of _the_ pipe to right position */
2000 if (p[THIS] != (*mode == 'r')) {
2001 PerlLIO_dup2(p[THIS], *mode == 'r');
2002 PerlLIO_close(p[THIS]);
2003 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2004 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2007 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2008 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2009 /* No automatic close - do it by hand */
2016 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2022 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2028 do_execfree(); /* free any memory malloced by child on fork */
2030 PerlLIO_close(pp[1]);
2031 /* Keep the lower of the two fd numbers */
2032 if (p[that] < p[This]) {
2033 PerlLIO_dup2(p[This], p[that]);
2034 PerlLIO_close(p[This]);
2038 PerlLIO_close(p[that]); /* close child's end of pipe */
2041 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2043 (void)SvUPGRADE(sv,SVt_IV);
2045 PL_forkprocess = pid;
2046 /* If we managed to get status pipe check for exec fail */
2047 if (did_pipes && pid > 0) {
2051 while (n < sizeof(int)) {
2052 n1 = PerlLIO_read(pp[0],
2053 (void*)(((char*)&errkid)+n),
2059 PerlLIO_close(pp[0]);
2061 if (n) { /* Error */
2063 PerlLIO_close(p[This]);
2064 if (n != sizeof(int))
2065 Perl_croak(aTHX_ "panic: kid popen errno read");
2067 pid2 = wait4pid(pid, &status, 0);
2068 } while (pid2 == -1 && errno == EINTR);
2069 errno = errkid; /* Propagate errno from kid */
2074 PerlLIO_close(pp[0]);
2075 return PerlIO_fdopen(p[This], mode);
2077 Perl_croak(aTHX_ "List form of piped open not implemented");
2078 return (PerlIO *) NULL;
2082 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2083 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2085 Perl_my_popen(pTHX_ char *cmd, char *mode)
2088 register I32 This, that;
2091 I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2095 PERL_FLUSHALL_FOR_CHILD;
2098 return my_syspopen(aTHX_ cmd,mode);
2101 This = (*mode == 'w');
2103 if (doexec && PL_tainting) {
2105 taint_proper("Insecure %s%s", "EXEC");
2107 if (PerlProc_pipe(p) < 0)
2109 if (doexec && PerlProc_pipe(pp) >= 0)
2111 while ((pid = PerlProc_fork()) < 0) {
2112 if (errno != EAGAIN) {
2113 PerlLIO_close(p[This]);
2114 PerlLIO_close(p[that]);
2116 PerlLIO_close(pp[0]);
2117 PerlLIO_close(pp[1]);
2120 Perl_croak(aTHX_ "Can't fork");
2133 PerlLIO_close(pp[0]);
2134 #if defined(HAS_FCNTL) && defined(F_SETFD)
2135 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2138 if (p[THIS] != (*mode == 'r')) {
2139 PerlLIO_dup2(p[THIS], *mode == 'r');
2140 PerlLIO_close(p[THIS]);
2141 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2142 PerlLIO_close(p[THAT]);
2145 PerlLIO_close(p[THAT]);
2148 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2157 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2162 /* may or may not use the shell */
2163 do_exec3(cmd, pp[1], did_pipes);
2166 #endif /* defined OS2 */
2168 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2169 SvREADONLY_off(GvSV(tmpgv));
2170 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2171 SvREADONLY_on(GvSV(tmpgv));
2173 #ifdef THREADS_HAVE_PIDS
2174 PL_ppid = (IV)getppid();
2177 hv_clear(PL_pidstatus); /* we have no children */
2182 do_execfree(); /* free any memory malloced by child on vfork */
2184 PerlLIO_close(pp[1]);
2185 if (p[that] < p[This]) {
2186 PerlLIO_dup2(p[This], p[that]);
2187 PerlLIO_close(p[This]);
2191 PerlLIO_close(p[that]);
2194 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2196 (void)SvUPGRADE(sv,SVt_IV);
2198 PL_forkprocess = pid;
2199 if (did_pipes && pid > 0) {
2203 while (n < sizeof(int)) {
2204 n1 = PerlLIO_read(pp[0],
2205 (void*)(((char*)&errkid)+n),
2211 PerlLIO_close(pp[0]);
2213 if (n) { /* Error */
2215 PerlLIO_close(p[This]);
2216 if (n != sizeof(int))
2217 Perl_croak(aTHX_ "panic: kid popen errno read");
2219 pid2 = wait4pid(pid, &status, 0);
2220 } while (pid2 == -1 && errno == EINTR);
2221 errno = errkid; /* Propagate errno from kid */
2226 PerlLIO_close(pp[0]);
2227 return PerlIO_fdopen(p[This], mode);
2230 #if defined(atarist) || defined(EPOC)
2233 Perl_my_popen(pTHX_ char *cmd, char *mode)
2235 PERL_FLUSHALL_FOR_CHILD;
2236 /* Call system's popen() to get a FILE *, then import it.
2237 used 0 for 2nd parameter to PerlIO_importFILE;
2240 return PerlIO_importFILE(popen(cmd, mode), 0);
2244 FILE *djgpp_popen();
2246 Perl_my_popen(pTHX_ char *cmd, char *mode)
2248 PERL_FLUSHALL_FOR_CHILD;
2249 /* Call system's popen() to get a FILE *, then import it.
2250 used 0 for 2nd parameter to PerlIO_importFILE;
2253 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2258 #endif /* !DOSISH */
2260 /* this is called in parent before the fork() */
2262 Perl_atfork_lock(void)
2264 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2265 /* locks must be held in locking order (if any) */
2267 MUTEX_LOCK(&PL_malloc_mutex);
2273 /* this is called in both parent and child after the fork() */
2275 Perl_atfork_unlock(void)
2277 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2278 /* locks must be released in same order as in atfork_lock() */
2280 MUTEX_UNLOCK(&PL_malloc_mutex);
2289 #if defined(HAS_FORK)
2291 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2296 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2297 * handlers elsewhere in the code */
2302 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2303 Perl_croak_nocontext("fork() not available");
2305 #endif /* HAS_FORK */
2310 Perl_dump_fds(pTHX_ char *s)
2315 PerlIO_printf(Perl_debug_log,"%s", s);
2316 for (fd = 0; fd < 32; fd++) {
2317 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2318 PerlIO_printf(Perl_debug_log," %d",fd);
2320 PerlIO_printf(Perl_debug_log,"\n");
2322 #endif /* DUMP_FDS */
2326 dup2(int oldfd, int newfd)
2328 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2331 PerlLIO_close(newfd);
2332 return fcntl(oldfd, F_DUPFD, newfd);
2334 #define DUP2_MAX_FDS 256
2335 int fdtmp[DUP2_MAX_FDS];
2341 PerlLIO_close(newfd);
2342 /* good enough for low fd's... */
2343 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2344 if (fdx >= DUP2_MAX_FDS) {
2352 PerlLIO_close(fdtmp[--fdx]);
2359 #ifdef HAS_SIGACTION
2361 #ifdef MACOS_TRADITIONAL
2362 /* We don't want restart behavior on MacOS */
2367 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2369 struct sigaction act, oact;
2372 /* only "parent" interpreter can diddle signals */
2373 if (PL_curinterp != aTHX)
2377 act.sa_handler = handler;
2378 sigemptyset(&act.sa_mask);
2381 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2382 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2384 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2385 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2386 act.sa_flags |= SA_NOCLDWAIT;
2388 if (sigaction(signo, &act, &oact) == -1)
2391 return oact.sa_handler;
2395 Perl_rsignal_state(pTHX_ int signo)
2397 struct sigaction oact;
2399 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2402 return oact.sa_handler;
2406 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2408 struct sigaction act;
2411 /* only "parent" interpreter can diddle signals */
2412 if (PL_curinterp != aTHX)
2416 act.sa_handler = handler;
2417 sigemptyset(&act.sa_mask);
2420 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2421 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2423 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2424 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2425 act.sa_flags |= SA_NOCLDWAIT;
2427 return sigaction(signo, &act, save);
2431 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2434 /* only "parent" interpreter can diddle signals */
2435 if (PL_curinterp != aTHX)
2439 return sigaction(signo, save, (struct sigaction *)NULL);
2442 #else /* !HAS_SIGACTION */
2445 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2447 #if defined(USE_ITHREADS) && !defined(WIN32)
2448 /* only "parent" interpreter can diddle signals */
2449 if (PL_curinterp != aTHX)
2453 return PerlProc_signal(signo, handler);
2456 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2457 ignore the implications of this for threading */
2467 Perl_rsignal_state(pTHX_ int signo)
2469 Sighandler_t oldsig;
2471 #if defined(USE_ITHREADS) && !defined(WIN32)
2472 /* only "parent" interpreter can diddle signals */
2473 if (PL_curinterp != aTHX)
2478 oldsig = PerlProc_signal(signo, sig_trap);
2479 PerlProc_signal(signo, oldsig);
2481 PerlProc_kill(PerlProc_getpid(), signo);
2486 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2488 #if defined(USE_ITHREADS) && !defined(WIN32)
2489 /* only "parent" interpreter can diddle signals */
2490 if (PL_curinterp != aTHX)
2493 *save = PerlProc_signal(signo, handler);
2494 return (*save == SIG_ERR) ? -1 : 0;
2498 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2500 #if defined(USE_ITHREADS) && !defined(WIN32)
2501 /* only "parent" interpreter can diddle signals */
2502 if (PL_curinterp != aTHX)
2505 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2508 #endif /* !HAS_SIGACTION */
2509 #endif /* !PERL_MICRO */
2511 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2512 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2514 Perl_my_pclose(pTHX_ PerlIO *ptr)
2516 Sigsave_t hstat, istat, qstat;
2522 int saved_errno = 0;
2524 int saved_vaxc_errno;
2527 int saved_win32_errno;
2531 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2533 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2535 *svp = &PL_sv_undef;
2537 if (pid == -1) { /* Opened by popen. */
2538 return my_syspclose(ptr);
2541 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2542 saved_errno = errno;
2544 saved_vaxc_errno = vaxc$errno;
2547 saved_win32_errno = GetLastError();
2551 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2554 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2555 rsignal_save(SIGINT, SIG_IGN, &istat);
2556 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2559 pid2 = wait4pid(pid, &status, 0);
2560 } while (pid2 == -1 && errno == EINTR);
2562 rsignal_restore(SIGHUP, &hstat);
2563 rsignal_restore(SIGINT, &istat);
2564 rsignal_restore(SIGQUIT, &qstat);
2567 SETERRNO(saved_errno, saved_vaxc_errno);
2570 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2572 #endif /* !DOSISH */
2574 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2576 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2581 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2585 char spid[TYPE_CHARS(IV)];
2588 sprintf(spid, "%"IVdf, (IV)pid);
2589 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2590 if (svp && *svp != &PL_sv_undef) {
2591 *statusp = SvIVX(*svp);
2592 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2599 hv_iterinit(PL_pidstatus);
2600 if ((entry = hv_iternext(PL_pidstatus))) {
2601 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2602 sv = hv_iterval(PL_pidstatus,entry);
2603 *statusp = SvIVX(sv);
2604 sprintf(spid, "%"IVdf, (IV)pid);
2605 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2612 # ifdef HAS_WAITPID_RUNTIME
2613 if (!HAS_WAITPID_RUNTIME)
2616 result = PerlProc_waitpid(pid,statusp,flags);
2619 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2620 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2623 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2627 Perl_croak(aTHX_ "Can't do waitpid with flags");
2629 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2630 pidgone(result,*statusp);
2637 if (result < 0 && errno == EINTR) {
2642 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2646 Perl_pidgone(pTHX_ Pid_t pid, int status)
2649 char spid[TYPE_CHARS(IV)];
2651 sprintf(spid, "%"IVdf, (IV)pid);
2652 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2653 (void)SvUPGRADE(sv,SVt_IV);
2654 SvIV_set(sv, status);
2658 #if defined(atarist) || defined(OS2) || defined(EPOC)
2661 int /* Cannot prototype with I32
2663 my_syspclose(PerlIO *ptr)
2666 Perl_my_pclose(pTHX_ PerlIO *ptr)
2669 /* Needs work for PerlIO ! */
2670 FILE *f = PerlIO_findFILE(ptr);
2671 I32 result = pclose(f);
2672 PerlIO_releaseFILE(ptr,f);
2680 Perl_my_pclose(pTHX_ PerlIO *ptr)
2682 /* Needs work for PerlIO ! */
2683 FILE *f = PerlIO_findFILE(ptr);
2684 I32 result = djgpp_pclose(f);
2685 result = (result << 8) & 0xff00;
2686 PerlIO_releaseFILE(ptr,f);
2692 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2695 register const char *frombase = from;
2698 register const char c = *from;
2703 while (count-- > 0) {
2704 for (todo = len; todo > 0; todo--) {
2713 Perl_same_dirent(pTHX_ char *a, char *b)
2715 char *fa = strrchr(a,'/');
2716 char *fb = strrchr(b,'/');
2719 SV *tmpsv = sv_newmortal();
2732 sv_setpvn(tmpsv, ".", 1);
2734 sv_setpvn(tmpsv, a, fa - a);
2735 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2738 sv_setpvn(tmpsv, ".", 1);
2740 sv_setpvn(tmpsv, b, fb - b);
2741 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2743 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2744 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2746 #endif /* !HAS_RENAME */
2749 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2751 const char *xfound = Nullch;
2752 char *xfailed = Nullch;
2753 char tmpbuf[MAXPATHLEN];
2757 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2758 # define SEARCH_EXTS ".bat", ".cmd", NULL
2759 # define MAX_EXT_LEN 4
2762 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2763 # define MAX_EXT_LEN 4
2766 # define SEARCH_EXTS ".pl", ".com", NULL
2767 # define MAX_EXT_LEN 4
2769 /* additional extensions to try in each dir if scriptname not found */
2771 const char *exts[] = { SEARCH_EXTS };
2772 const char **ext = search_ext ? search_ext : exts;
2773 int extidx = 0, i = 0;
2774 const char *curext = Nullch;
2777 # define MAX_EXT_LEN 0
2781 * If dosearch is true and if scriptname does not contain path
2782 * delimiters, search the PATH for scriptname.
2784 * If SEARCH_EXTS is also defined, will look for each
2785 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2786 * while searching the PATH.
2788 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2789 * proceeds as follows:
2790 * If DOSISH or VMSISH:
2791 * + look for ./scriptname{,.foo,.bar}
2792 * + search the PATH for scriptname{,.foo,.bar}
2795 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2796 * this will not look in '.' if it's not in the PATH)
2801 # ifdef ALWAYS_DEFTYPES
2802 len = strlen(scriptname);
2803 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2804 int hasdir, idx = 0, deftypes = 1;
2807 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2810 int hasdir, idx = 0, deftypes = 1;
2813 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2815 /* The first time through, just add SEARCH_EXTS to whatever we
2816 * already have, so we can check for default file types. */
2818 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2824 if ((strlen(tmpbuf) + strlen(scriptname)
2825 + MAX_EXT_LEN) >= sizeof tmpbuf)
2826 continue; /* don't search dir with too-long name */
2827 strcat(tmpbuf, scriptname);
2831 if (strEQ(scriptname, "-"))
2833 if (dosearch) { /* Look in '.' first. */
2834 char *cur = scriptname;
2836 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2838 if (strEQ(ext[i++],curext)) {
2839 extidx = -1; /* already has an ext */
2844 DEBUG_p(PerlIO_printf(Perl_debug_log,
2845 "Looking for %s\n",cur));
2846 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2847 && !S_ISDIR(PL_statbuf.st_mode)) {
2855 if (cur == scriptname) {
2856 len = strlen(scriptname);
2857 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2859 cur = strcpy(tmpbuf, scriptname);
2861 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2862 && strcpy(tmpbuf+len, ext[extidx++]));
2867 #ifdef MACOS_TRADITIONAL
2868 if (dosearch && !strchr(scriptname, ':') &&
2869 (s = PerlEnv_getenv("Commands")))
2871 if (dosearch && !strchr(scriptname, '/')
2873 && !strchr(scriptname, '\\')
2875 && (s = PerlEnv_getenv("PATH")))
2880 PL_bufend = s + strlen(s);
2881 while (s < PL_bufend) {
2882 #ifdef MACOS_TRADITIONAL
2883 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2887 #if defined(atarist) || defined(DOSISH)
2892 && *s != ';'; len++, s++) {
2893 if (len < sizeof tmpbuf)
2896 if (len < sizeof tmpbuf)
2898 #else /* ! (atarist || DOSISH) */
2899 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2902 #endif /* ! (atarist || DOSISH) */
2903 #endif /* MACOS_TRADITIONAL */
2906 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2907 continue; /* don't search dir with too-long name */
2908 #ifdef MACOS_TRADITIONAL
2909 if (len && tmpbuf[len - 1] != ':')
2910 tmpbuf[len++] = ':';
2913 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2914 && tmpbuf[len - 1] != '/'
2915 && tmpbuf[len - 1] != '\\'
2918 tmpbuf[len++] = '/';
2919 if (len == 2 && tmpbuf[0] == '.')
2922 (void)strcpy(tmpbuf + len, scriptname);
2926 len = strlen(tmpbuf);
2927 if (extidx > 0) /* reset after previous loop */
2931 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2932 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2933 if (S_ISDIR(PL_statbuf.st_mode)) {
2937 } while ( retval < 0 /* not there */
2938 && extidx>=0 && ext[extidx] /* try an extension? */
2939 && strcpy(tmpbuf+len, ext[extidx++])
2944 if (S_ISREG(PL_statbuf.st_mode)
2945 && cando(S_IRUSR,TRUE,&PL_statbuf)
2946 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2947 && cando(S_IXUSR,TRUE,&PL_statbuf)
2951 xfound = tmpbuf; /* bingo! */
2955 xfailed = savepv(tmpbuf);
2958 if (!xfound && !seen_dot && !xfailed &&
2959 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2960 || S_ISDIR(PL_statbuf.st_mode)))
2962 seen_dot = 1; /* Disable message. */
2964 if (flags & 1) { /* do or die? */
2965 Perl_croak(aTHX_ "Can't %s %s%s%s",
2966 (xfailed ? "execute" : "find"),
2967 (xfailed ? xfailed : scriptname),
2968 (xfailed ? "" : " on PATH"),
2969 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2971 scriptname = Nullch;
2975 scriptname = xfound;
2977 return (scriptname ? savepv(scriptname) : Nullch);
2980 #ifndef PERL_GET_CONTEXT_DEFINED
2983 Perl_get_context(void)
2985 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2986 # ifdef OLD_PTHREADS_API
2988 if (pthread_getspecific(PL_thr_key, &t))
2989 Perl_croak_nocontext("panic: pthread_getspecific");
2992 # ifdef I_MACH_CTHREADS
2993 return (void*)cthread_data(cthread_self());
2995 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3004 Perl_set_context(void *t)
3006 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
3007 # ifdef I_MACH_CTHREADS
3008 cthread_set_data(cthread_self(), t);
3010 if (pthread_setspecific(PL_thr_key, t))
3011 Perl_croak_nocontext("panic: pthread_setspecific");
3018 #endif /* !PERL_GET_CONTEXT_DEFINED */
3020 #ifdef USE_5005THREADS
3023 /* Very simplistic scheduler for now */
3027 thr = thr->i.next_run;
3031 Perl_cond_init(pTHX_ perl_cond *cp)
3037 Perl_cond_signal(pTHX_ perl_cond *cp)
3040 perl_cond cond = *cp;
3045 /* Insert t in the runnable queue just ahead of us */
3046 t->i.next_run = thr->i.next_run;
3047 thr->i.next_run->i.prev_run = t;
3048 t->i.prev_run = thr;
3049 thr->i.next_run = t;
3050 thr->i.wait_queue = 0;
3051 /* Remove from the wait queue */
3057 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3060 perl_cond cond, cond_next;
3062 for (cond = *cp; cond; cond = cond_next) {
3064 /* Insert t in the runnable queue just ahead of us */
3065 t->i.next_run = thr->i.next_run;
3066 thr->i.next_run->i.prev_run = t;
3067 t->i.prev_run = thr;
3068 thr->i.next_run = t;
3069 thr->i.wait_queue = 0;
3070 /* Remove from the wait queue */
3071 cond_next = cond->next;
3078 Perl_cond_wait(pTHX_ perl_cond *cp)
3082 if (thr->i.next_run == thr)
3083 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3085 New(666, cond, 1, struct perl_wait_queue);
3089 thr->i.wait_queue = cond;
3090 /* Remove ourselves from runnable queue */
3091 thr->i.next_run->i.prev_run = thr->i.prev_run;
3092 thr->i.prev_run->i.next_run = thr->i.next_run;
3094 #endif /* FAKE_THREADS */
3097 Perl_condpair_magic(pTHX_ SV *sv)
3101 (void)SvUPGRADE(sv, SVt_PVMG);
3102 mg = mg_find(sv, PERL_MAGIC_mutex);
3106 New(53, cp, 1, condpair_t);
3107 MUTEX_INIT(&cp->mutex);
3108 COND_INIT(&cp->owner_cond);
3109 COND_INIT(&cp->cond);
3111 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3112 mg = mg_find(sv, PERL_MAGIC_mutex);
3114 /* someone else beat us to initialising it */
3115 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3116 MUTEX_DESTROY(&cp->mutex);
3117 COND_DESTROY(&cp->owner_cond);
3118 COND_DESTROY(&cp->cond);
3122 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3124 mg->mg_ptr = (char *)cp;
3125 mg->mg_len = sizeof(cp);
3126 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3127 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3128 "%p: condpair_magic %p\n", thr, sv)));
3135 Perl_sv_lock(pTHX_ SV *osv)
3145 mg = condpair_magic(sv);
3146 MUTEX_LOCK(MgMUTEXP(mg));
3147 if (MgOWNER(mg) == thr)
3148 MUTEX_UNLOCK(MgMUTEXP(mg));
3151 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3153 DEBUG_S(PerlIO_printf(Perl_debug_log,
3154 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3155 PTR2UV(thr), PTR2UV(sv)));
3156 MUTEX_UNLOCK(MgMUTEXP(mg));
3157 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3159 UNLOCK_SV_LOCK_MUTEX;
3164 * Make a new perl thread structure using t as a prototype. Some of the
3165 * fields for the new thread are copied from the prototype thread, t,
3166 * so t should not be running in perl at the time this function is
3167 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3168 * thread calling new_struct_thread) clearly satisfies this constraint.
3170 struct perl_thread *
3171 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3173 #if !defined(PERL_IMPLICIT_CONTEXT)
3174 struct perl_thread *thr;
3180 sv = newSVpvn("", 0);
3181 SvGROW(sv, sizeof(struct perl_thread) + 1);
3182 SvCUR_set(sv, sizeof(struct perl_thread));
3183 thr = (Thread) SvPVX(sv);
3185 Poison(thr, 1, struct perl_thread);
3192 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3193 PL_efloatbuf = (char*)NULL;
3196 Zero(thr, 1, struct perl_thread);
3202 PL_curcop = &PL_compiling;
3203 thr->interp = t->interp;
3204 thr->cvcache = newHV();
3205 thr->threadsv = newAV();
3206 thr->specific = newAV();
3207 thr->errsv = newSVpvn("", 0);
3208 thr->flags = THRf_R_JOINABLE;
3210 MUTEX_INIT(&thr->mutex);
3214 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3217 PL_statname = NEWSV(66,0);
3218 PL_errors = newSVpvn("", 0);
3220 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3221 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3222 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3223 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3224 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3226 PL_reginterp_cnt = 0;
3227 PL_lastscream = Nullsv;
3230 PL_reg_start_tmp = 0;
3231 PL_reg_start_tmpl = 0;
3232 PL_reg_poscache = Nullch;
3234 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3236 /* parent thread's data needs to be locked while we make copy */
3237 MUTEX_LOCK(&t->mutex);
3239 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3240 PL_protect = t->Tprotect;
3243 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3244 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3245 PL_curstash = t->Tcurstash; /* always be set to main? */
3247 PL_tainted = t->Ttainted;
3248 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3249 PL_rs = newSVsv(t->Trs);
3250 PL_last_in_gv = Nullgv;
3251 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3252 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3253 PL_chopset = t->Tchopset;
3254 PL_bodytarget = newSVsv(t->Tbodytarget);
3255 PL_toptarget = newSVsv(t->Ttoptarget);
3256 if (t->Tformtarget == t->Ttoptarget)
3257 PL_formtarget = PL_toptarget;
3259 PL_formtarget = PL_bodytarget;
3260 PL_watchaddr = 0; /* XXX */
3261 PL_watchok = 0; /* XXX */
3265 /* Initialise all per-thread SVs that the template thread used */
3266 svp = AvARRAY(t->threadsv);
3267 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3268 if (*svp && *svp != &PL_sv_undef) {
3269 SV *sv = newSVsv(*svp);
3270 av_store(thr->threadsv, i, sv);
3271 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3272 DEBUG_S(PerlIO_printf(Perl_debug_log,
3273 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3277 thr->threadsvp = AvARRAY(thr->threadsv);
3279 MUTEX_LOCK(&PL_threads_mutex);
3281 thr->tid = ++PL_threadnum;
3282 thr->next = t->next;
3285 thr->next->prev = thr;
3286 MUTEX_UNLOCK(&PL_threads_mutex);
3288 /* done copying parent's state */
3289 MUTEX_UNLOCK(&t->mutex);
3291 #ifdef HAVE_THREAD_INTERN
3292 Perl_init_thread_intern(thr);
3293 #endif /* HAVE_THREAD_INTERN */
3296 #endif /* USE_5005THREADS */
3298 #ifdef PERL_GLOBAL_STRUCT
3307 Perl_get_op_names(pTHX)
3313 Perl_get_op_descs(pTHX)
3319 Perl_get_no_modify(pTHX)
3321 return PL_no_modify;
3325 Perl_get_opargs(pTHX)
3331 Perl_get_ppaddr(pTHX)
3333 return (PPADDR_t*)PL_ppaddr;
3336 #ifndef HAS_GETENV_LEN
3338 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3340 char *env_trans = PerlEnv_getenv(env_elem);
3342 *len = strlen(env_trans);
3349 Perl_get_vtbl(pTHX_ int vtbl_id)
3351 MGVTBL* result = Null(MGVTBL*);
3355 result = &PL_vtbl_sv;
3358 result = &PL_vtbl_env;
3360 case want_vtbl_envelem:
3361 result = &PL_vtbl_envelem;
3364 result = &PL_vtbl_sig;
3366 case want_vtbl_sigelem:
3367 result = &PL_vtbl_sigelem;
3369 case want_vtbl_pack:
3370 result = &PL_vtbl_pack;
3372 case want_vtbl_packelem:
3373 result = &PL_vtbl_packelem;
3375 case want_vtbl_dbline:
3376 result = &PL_vtbl_dbline;
3379 result = &PL_vtbl_isa;
3381 case want_vtbl_isaelem:
3382 result = &PL_vtbl_isaelem;
3384 case want_vtbl_arylen:
3385 result = &PL_vtbl_arylen;
3387 case want_vtbl_glob:
3388 result = &PL_vtbl_glob;
3390 case want_vtbl_mglob:
3391 result = &PL_vtbl_mglob;
3393 case want_vtbl_nkeys:
3394 result = &PL_vtbl_nkeys;
3396 case want_vtbl_taint:
3397 result = &PL_vtbl_taint;
3399 case want_vtbl_substr:
3400 result = &PL_vtbl_substr;
3403 result = &PL_vtbl_vec;
3406 result = &PL_vtbl_pos;
3409 result = &PL_vtbl_bm;
3412 result = &PL_vtbl_fm;
3414 case want_vtbl_uvar:
3415 result = &PL_vtbl_uvar;
3417 #ifdef USE_5005THREADS
3418 case want_vtbl_mutex:
3419 result = &PL_vtbl_mutex;
3422 case want_vtbl_defelem:
3423 result = &PL_vtbl_defelem;
3425 case want_vtbl_regexp:
3426 result = &PL_vtbl_regexp;
3428 case want_vtbl_regdata:
3429 result = &PL_vtbl_regdata;
3431 case want_vtbl_regdatum:
3432 result = &PL_vtbl_regdatum;
3434 #ifdef USE_LOCALE_COLLATE
3435 case want_vtbl_collxfrm:
3436 result = &PL_vtbl_collxfrm;
3439 case want_vtbl_amagic:
3440 result = &PL_vtbl_amagic;
3442 case want_vtbl_amagicelem:
3443 result = &PL_vtbl_amagicelem;
3445 case want_vtbl_backref:
3446 result = &PL_vtbl_backref;
3448 case want_vtbl_utf8:
3449 result = &PL_vtbl_utf8;
3456 Perl_my_fflush_all(pTHX)
3458 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3459 return PerlIO_flush(NULL);
3461 # if defined(HAS__FWALK)
3462 extern int fflush(FILE *);
3463 /* undocumented, unprototyped, but very useful BSDism */
3464 extern void _fwalk(int (*)(FILE *));
3468 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3470 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3471 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3473 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3474 open_max = sysconf(_SC_OPEN_MAX);
3477 open_max = FOPEN_MAX;
3480 open_max = OPEN_MAX;
3491 for (i = 0; i < open_max; i++)
3492 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3493 STDIO_STREAM_ARRAY[i]._file < open_max &&
3494 STDIO_STREAM_ARRAY[i]._flag)
3495 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3499 SETERRNO(EBADF,RMS_IFI);
3506 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3509 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3510 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3512 const char *pars = OP_IS_FILETEST(op) ? "" : "()";
3513 const char *type = OP_IS_SOCKET(op)
3514 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3515 ? "socket" : "filehandle";
3516 const char *name = NULL;
3518 if (gv && isGV(gv)) {
3522 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3523 if (ckWARN(WARN_IO)) {
3524 const char *direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3526 Perl_warner(aTHX_ packWARN(WARN_IO),
3527 "Filehandle %s opened only for %sput",
3530 Perl_warner(aTHX_ packWARN(WARN_IO),
3531 "Filehandle opened only for %sput", direction);
3538 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3540 warn_type = WARN_CLOSED;
3544 warn_type = WARN_UNOPENED;
3547 if (ckWARN(warn_type)) {
3548 if (name && *name) {
3549 Perl_warner(aTHX_ packWARN(warn_type),
3550 "%s%s on %s %s %s", func, pars, vile, type, name);
3551 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3553 aTHX_ packWARN(warn_type),
3554 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3559 Perl_warner(aTHX_ packWARN(warn_type),
3560 "%s%s on %s %s", func, pars, vile, type);
3561 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3563 aTHX_ packWARN(warn_type),
3564 "\t(Are you trying to call %s%s on dirhandle?)\n",
3573 /* in ASCII order, not that it matters */
3574 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3577 Perl_ebcdic_control(pTHX_ int ch)
3585 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3586 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3589 if (ctlp == controllablechars)
3590 return('\177'); /* DEL */
3592 return((unsigned char)(ctlp - controllablechars - 1));
3593 } else { /* Want uncontrol */
3594 if (ch == '\177' || ch == -1)
3596 else if (ch == '\157')
3598 else if (ch == '\174')
3600 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3602 else if (ch == '\155')
3604 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3605 return(controllablechars[ch+1]);
3607 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3612 /* To workaround core dumps from the uninitialised tm_zone we get the
3613 * system to give us a reasonable struct to copy. This fix means that
3614 * strftime uses the tm_zone and tm_gmtoff values returned by
3615 * localtime(time()). That should give the desired result most of the
3616 * time. But probably not always!
3618 * This does not address tzname aspects of NETaa14816.
3623 # ifndef STRUCT_TM_HASZONE
3624 # define STRUCT_TM_HASZONE
3628 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3629 # ifndef HAS_TM_TM_ZONE
3630 # define HAS_TM_TM_ZONE
3635 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3637 #ifdef HAS_TM_TM_ZONE
3641 my_tm = localtime(&now);
3643 Copy(my_tm, ptm, 1, struct tm);
3648 * mini_mktime - normalise struct tm values without the localtime()
3649 * semantics (and overhead) of mktime().
3652 Perl_mini_mktime(pTHX_ struct tm *ptm)
3656 int month, mday, year, jday;
3657 int odd_cent, odd_year;
3659 #define DAYS_PER_YEAR 365
3660 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3661 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3662 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3663 #define SECS_PER_HOUR (60*60)
3664 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3665 /* parentheses deliberately absent on these two, otherwise they don't work */
3666 #define MONTH_TO_DAYS 153/5
3667 #define DAYS_TO_MONTH 5/153
3668 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3669 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3670 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3671 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3674 * Year/day algorithm notes:
3676 * With a suitable offset for numeric value of the month, one can find
3677 * an offset into the year by considering months to have 30.6 (153/5) days,
3678 * using integer arithmetic (i.e., with truncation). To avoid too much
3679 * messing about with leap days, we consider January and February to be
3680 * the 13th and 14th month of the previous year. After that transformation,
3681 * we need the month index we use to be high by 1 from 'normal human' usage,
3682 * so the month index values we use run from 4 through 15.
3684 * Given that, and the rules for the Gregorian calendar (leap years are those
3685 * divisible by 4 unless also divisible by 100, when they must be divisible
3686 * by 400 instead), we can simply calculate the number of days since some
3687 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3688 * the days we derive from our month index, and adding in the day of the
3689 * month. The value used here is not adjusted for the actual origin which
3690 * it normally would use (1 January A.D. 1), since we're not exposing it.
3691 * We're only building the value so we can turn around and get the
3692 * normalised values for the year, month, day-of-month, and day-of-year.
3694 * For going backward, we need to bias the value we're using so that we find
3695 * the right year value. (Basically, we don't want the contribution of
3696 * March 1st to the number to apply while deriving the year). Having done
3697 * that, we 'count up' the contribution to the year number by accounting for
3698 * full quadracenturies (400-year periods) with their extra leap days, plus
3699 * the contribution from full centuries (to avoid counting in the lost leap
3700 * days), plus the contribution from full quad-years (to count in the normal
3701 * leap days), plus the leftover contribution from any non-leap years.
3702 * At this point, if we were working with an actual leap day, we'll have 0
3703 * days left over. This is also true for March 1st, however. So, we have
3704 * to special-case that result, and (earlier) keep track of the 'odd'
3705 * century and year contributions. If we got 4 extra centuries in a qcent,
3706 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3707 * Otherwise, we add back in the earlier bias we removed (the 123 from
3708 * figuring in March 1st), find the month index (integer division by 30.6),
3709 * and the remainder is the day-of-month. We then have to convert back to
3710 * 'real' months (including fixing January and February from being 14/15 in
3711 * the previous year to being in the proper year). After that, to get
3712 * tm_yday, we work with the normalised year and get a new yearday value for
3713 * January 1st, which we subtract from the yearday value we had earlier,
3714 * representing the date we've re-built. This is done from January 1
3715 * because tm_yday is 0-origin.
3717 * Since POSIX time routines are only guaranteed to work for times since the
3718 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3719 * applies Gregorian calendar rules even to dates before the 16th century
3720 * doesn't bother me. Besides, you'd need cultural context for a given
3721 * date to know whether it was Julian or Gregorian calendar, and that's
3722 * outside the scope for this routine. Since we convert back based on the
3723 * same rules we used to build the yearday, you'll only get strange results
3724 * for input which needed normalising, or for the 'odd' century years which
3725 * were leap years in the Julian calander but not in the Gregorian one.
3726 * I can live with that.
3728 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3729 * that's still outside the scope for POSIX time manipulation, so I don't
3733 year = 1900 + ptm->tm_year;
3734 month = ptm->tm_mon;
3735 mday = ptm->tm_mday;
3736 /* allow given yday with no month & mday to dominate the result */
3737 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3740 jday = 1 + ptm->tm_yday;
3749 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3750 yearday += month*MONTH_TO_DAYS + mday + jday;
3752 * Note that we don't know when leap-seconds were or will be,
3753 * so we have to trust the user if we get something which looks
3754 * like a sensible leap-second. Wild values for seconds will
3755 * be rationalised, however.
3757 if ((unsigned) ptm->tm_sec <= 60) {
3764 secs += 60 * ptm->tm_min;
3765 secs += SECS_PER_HOUR * ptm->tm_hour;
3767 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3768 /* got negative remainder, but need positive time */
3769 /* back off an extra day to compensate */
3770 yearday += (secs/SECS_PER_DAY)-1;
3771 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3774 yearday += (secs/SECS_PER_DAY);
3775 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3778 else if (secs >= SECS_PER_DAY) {
3779 yearday += (secs/SECS_PER_DAY);
3780 secs %= SECS_PER_DAY;
3782 ptm->tm_hour = secs/SECS_PER_HOUR;
3783 secs %= SECS_PER_HOUR;
3784 ptm->tm_min = secs/60;
3786 ptm->tm_sec += secs;
3787 /* done with time of day effects */
3789 * The algorithm for yearday has (so far) left it high by 428.
3790 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3791 * bias it by 123 while trying to figure out what year it
3792 * really represents. Even with this tweak, the reverse
3793 * translation fails for years before A.D. 0001.
3794 * It would still fail for Feb 29, but we catch that one below.
3796 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3797 yearday -= YEAR_ADJUST;
3798 year = (yearday / DAYS_PER_QCENT) * 400;
3799 yearday %= DAYS_PER_QCENT;
3800 odd_cent = yearday / DAYS_PER_CENT;
3801 year += odd_cent * 100;
3802 yearday %= DAYS_PER_CENT;
3803 year += (yearday / DAYS_PER_QYEAR) * 4;
3804 yearday %= DAYS_PER_QYEAR;
3805 odd_year = yearday / DAYS_PER_YEAR;
3807 yearday %= DAYS_PER_YEAR;
3808 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3813 yearday += YEAR_ADJUST; /* recover March 1st crock */
3814 month = yearday*DAYS_TO_MONTH;
3815 yearday -= month*MONTH_TO_DAYS;
3816 /* recover other leap-year adjustment */
3825 ptm->tm_year = year - 1900;
3827 ptm->tm_mday = yearday;
3828 ptm->tm_mon = month;
3832 ptm->tm_mon = month - 1;
3834 /* re-build yearday based on Jan 1 to get tm_yday */
3836 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3837 yearday += 14*MONTH_TO_DAYS + 1;
3838 ptm->tm_yday = jday - yearday;
3839 /* fix tm_wday if not overridden by caller */
3840 if ((unsigned)ptm->tm_wday > 6)
3841 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3845 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3853 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3856 mytm.tm_hour = hour;
3857 mytm.tm_mday = mday;
3859 mytm.tm_year = year;
3860 mytm.tm_wday = wday;
3861 mytm.tm_yday = yday;
3862 mytm.tm_isdst = isdst;
3864 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3865 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3870 #ifdef HAS_TM_TM_GMTOFF
3871 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3873 #ifdef HAS_TM_TM_ZONE
3874 mytm.tm_zone = mytm2.tm_zone;
3879 New(0, buf, buflen, char);
3880 len = strftime(buf, buflen, fmt, &mytm);
3882 ** The following is needed to handle to the situation where
3883 ** tmpbuf overflows. Basically we want to allocate a buffer
3884 ** and try repeatedly. The reason why it is so complicated
3885 ** is that getting a return value of 0 from strftime can indicate
3886 ** one of the following:
3887 ** 1. buffer overflowed,
3888 ** 2. illegal conversion specifier, or
3889 ** 3. the format string specifies nothing to be returned(not
3890 ** an error). This could be because format is an empty string
3891 ** or it specifies %p that yields an empty string in some locale.
3892 ** If there is a better way to make it portable, go ahead by
3895 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3898 /* Possibly buf overflowed - try again with a bigger buf */
3899 const int fmtlen = strlen(fmt);
3900 const int bufsize = fmtlen + buflen;
3902 New(0, buf, bufsize, char);
3904 buflen = strftime(buf, bufsize, fmt, &mytm);
3905 if (buflen > 0 && buflen < bufsize)
3907 /* heuristic to prevent out-of-memory errors */
3908 if (bufsize > 100*fmtlen) {
3913 Renew(buf, bufsize*2, char);
3918 Perl_croak(aTHX_ "panic: no strftime");
3923 #define SV_CWD_RETURN_UNDEF \
3924 sv_setsv(sv, &PL_sv_undef); \
3927 #define SV_CWD_ISDOT(dp) \
3928 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3929 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3932 =head1 Miscellaneous Functions
3934 =for apidoc getcwd_sv
3936 Fill the sv with current working directory
3941 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3942 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3943 * getcwd(3) if available
3944 * Comments from the orignal:
3945 * This is a faster version of getcwd. It's also more dangerous
3946 * because you might chdir out of a directory that you can't chdir
3950 Perl_getcwd_sv(pTHX_ register SV *sv)
3954 #ifndef INCOMPLETE_TAINTS
3960 char buf[MAXPATHLEN];
3962 /* Some getcwd()s automatically allocate a buffer of the given
3963 * size from the heap if they are given a NULL buffer pointer.
3964 * The problem is that this behaviour is not portable. */
3965 if (getcwd(buf, sizeof(buf) - 1)) {
3966 sv_setpvn(sv, buf, strlen(buf));
3970 sv_setsv(sv, &PL_sv_undef);
3978 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3982 (void)SvUPGRADE(sv, SVt_PV);
3984 if (PerlLIO_lstat(".", &statbuf) < 0) {
3985 SV_CWD_RETURN_UNDEF;
3988 orig_cdev = statbuf.st_dev;
3989 orig_cino = statbuf.st_ino;
3998 if (PerlDir_chdir("..") < 0) {
3999 SV_CWD_RETURN_UNDEF;
4001 if (PerlLIO_stat(".", &statbuf) < 0) {
4002 SV_CWD_RETURN_UNDEF;
4005 cdev = statbuf.st_dev;
4006 cino = statbuf.st_ino;
4008 if (odev == cdev && oino == cino) {
4011 if (!(dir = PerlDir_open("."))) {
4012 SV_CWD_RETURN_UNDEF;
4015 while ((dp = PerlDir_read(dir)) != NULL) {
4017 const int namelen = dp->d_namlen;
4019 const int namelen = strlen(dp->d_name);
4022 if (SV_CWD_ISDOT(dp)) {
4026 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4027 SV_CWD_RETURN_UNDEF;
4030 tdev = statbuf.st_dev;
4031 tino = statbuf.st_ino;
4032 if (tino == oino && tdev == odev) {
4038 SV_CWD_RETURN_UNDEF;
4041 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4042 SV_CWD_RETURN_UNDEF;
4045 SvGROW(sv, pathlen + namelen + 1);
4049 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4052 /* prepend current directory to the front */
4054 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4055 pathlen += (namelen + 1);
4057 #ifdef VOID_CLOSEDIR
4060 if (PerlDir_close(dir) < 0) {
4061 SV_CWD_RETURN_UNDEF;
4067 SvCUR_set(sv, pathlen);
4071 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4072 SV_CWD_RETURN_UNDEF;
4075 if (PerlLIO_stat(".", &statbuf) < 0) {
4076 SV_CWD_RETURN_UNDEF;
4079 cdev = statbuf.st_dev;
4080 cino = statbuf.st_ino;
4082 if (cdev != orig_cdev || cino != orig_cino) {
4083 Perl_croak(aTHX_ "Unstable directory path, "
4084 "current directory changed unexpectedly");
4095 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4096 # define EMULATE_SOCKETPAIR_UDP
4099 #ifdef EMULATE_SOCKETPAIR_UDP
4101 S_socketpair_udp (int fd[2]) {
4103 /* Fake a datagram socketpair using UDP to localhost. */
4104 int sockets[2] = {-1, -1};
4105 struct sockaddr_in addresses[2];
4107 Sock_size_t size = sizeof(struct sockaddr_in);
4108 unsigned short port;
4111 memset(&addresses, 0, sizeof(addresses));
4114 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4115 if (sockets[i] == -1)
4116 goto tidy_up_and_fail;
4118 addresses[i].sin_family = AF_INET;
4119 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4120 addresses[i].sin_port = 0; /* kernel choses port. */
4121 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4122 sizeof(struct sockaddr_in)) == -1)
4123 goto tidy_up_and_fail;
4126 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4127 for each connect the other socket to it. */
4130 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4132 goto tidy_up_and_fail;
4133 if (size != sizeof(struct sockaddr_in))
4134 goto abort_tidy_up_and_fail;
4135 /* !1 is 0, !0 is 1 */
4136 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4137 sizeof(struct sockaddr_in)) == -1)
4138 goto tidy_up_and_fail;
4141 /* Now we have 2 sockets connected to each other. I don't trust some other
4142 process not to have already sent a packet to us (by random) so send
4143 a packet from each to the other. */
4146 /* I'm going to send my own port number. As a short.
4147 (Who knows if someone somewhere has sin_port as a bitfield and needs
4148 this routine. (I'm assuming crays have socketpair)) */
4149 port = addresses[i].sin_port;
4150 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4151 if (got != sizeof(port)) {
4153 goto tidy_up_and_fail;
4154 goto abort_tidy_up_and_fail;
4158 /* Packets sent. I don't trust them to have arrived though.
4159 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4160 connect to localhost will use a second kernel thread. In 2.6 the
4161 first thread running the connect() returns before the second completes,
4162 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4163 returns 0. Poor programs have tripped up. One poor program's authors'
4164 had a 50-1 reverse stock split. Not sure how connected these were.)
4165 So I don't trust someone not to have an unpredictable UDP stack.
4169 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4170 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4174 FD_SET(sockets[0], &rset);
4175 FD_SET(sockets[1], &rset);
4177 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4178 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4179 || !FD_ISSET(sockets[1], &rset)) {
4180 /* I hope this is portable and appropriate. */
4182 goto tidy_up_and_fail;
4183 goto abort_tidy_up_and_fail;
4187 /* And the paranoia department even now doesn't trust it to have arrive
4188 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4190 struct sockaddr_in readfrom;
4191 unsigned short buffer[2];
4196 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4197 sizeof(buffer), MSG_DONTWAIT,
4198 (struct sockaddr *) &readfrom, &size);
4200 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4202 (struct sockaddr *) &readfrom, &size);
4206 goto tidy_up_and_fail;
4207 if (got != sizeof(port)
4208 || size != sizeof(struct sockaddr_in)
4209 /* Check other socket sent us its port. */
4210 || buffer[0] != (unsigned short) addresses[!i].sin_port
4211 /* Check kernel says we got the datagram from that socket */
4212 || readfrom.sin_family != addresses[!i].sin_family
4213 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4214 || readfrom.sin_port != addresses[!i].sin_port)
4215 goto abort_tidy_up_and_fail;
4218 /* My caller (my_socketpair) has validated that this is non-NULL */
4221 /* I hereby declare this connection open. May God bless all who cross
4225 abort_tidy_up_and_fail:
4226 errno = ECONNABORTED;
4229 const int save_errno = errno;
4230 if (sockets[0] != -1)
4231 PerlLIO_close(sockets[0]);
4232 if (sockets[1] != -1)
4233 PerlLIO_close(sockets[1]);
4238 #endif /* EMULATE_SOCKETPAIR_UDP */
4240 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4242 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4243 /* Stevens says that family must be AF_LOCAL, protocol 0.
4244 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4249 struct sockaddr_in listen_addr;
4250 struct sockaddr_in connect_addr;
4255 || family != AF_UNIX
4258 errno = EAFNOSUPPORT;
4266 #ifdef EMULATE_SOCKETPAIR_UDP
4267 if (type == SOCK_DGRAM)
4268 return S_socketpair_udp(fd);
4271 listener = PerlSock_socket(AF_INET, type, 0);
4274 memset(&listen_addr, 0, sizeof(listen_addr));
4275 listen_addr.sin_family = AF_INET;
4276 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4277 listen_addr.sin_port = 0; /* kernel choses port. */
4278 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4279 sizeof(listen_addr)) == -1)
4280 goto tidy_up_and_fail;
4281 if (PerlSock_listen(listener, 1) == -1)
4282 goto tidy_up_and_fail;
4284 connector = PerlSock_socket(AF_INET, type, 0);
4285 if (connector == -1)
4286 goto tidy_up_and_fail;
4287 /* We want to find out the port number to connect to. */
4288 size = sizeof(connect_addr);
4289 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4291 goto tidy_up_and_fail;
4292 if (size != sizeof(connect_addr))
4293 goto abort_tidy_up_and_fail;
4294 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4295 sizeof(connect_addr)) == -1)
4296 goto tidy_up_and_fail;
4298 size = sizeof(listen_addr);
4299 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4302 goto tidy_up_and_fail;
4303 if (size != sizeof(listen_addr))
4304 goto abort_tidy_up_and_fail;
4305 PerlLIO_close(listener);
4306 /* Now check we are talking to ourself by matching port and host on the
4308 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4310 goto tidy_up_and_fail;
4311 if (size != sizeof(connect_addr)
4312 || listen_addr.sin_family != connect_addr.sin_family
4313 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4314 || listen_addr.sin_port != connect_addr.sin_port) {
4315 goto abort_tidy_up_and_fail;
4321 abort_tidy_up_and_fail:
4322 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4325 int save_errno = errno;
4327 PerlLIO_close(listener);
4328 if (connector != -1)
4329 PerlLIO_close(connector);
4331 PerlLIO_close(acceptor);
4337 /* In any case have a stub so that there's code corresponding
4338 * to the my_socketpair in global.sym. */
4340 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4341 #ifdef HAS_SOCKETPAIR
4342 return socketpair(family, type, protocol, fd);
4351 =for apidoc sv_nosharing
4353 Dummy routine which "shares" an SV when there is no sharing module present.
4354 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4355 some level of strict-ness.
4361 Perl_sv_nosharing(pTHX_ SV *sv)
4367 =for apidoc sv_nolocking
4369 Dummy routine which "locks" an SV when there is no locking module present.
4370 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4371 some level of strict-ness.
4377 Perl_sv_nolocking(pTHX_ SV *sv)
4384 =for apidoc sv_nounlocking
4386 Dummy routine which "unlocks" an SV when there is no locking module present.
4387 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4388 some level of strict-ness.
4394 Perl_sv_nounlocking(pTHX_ SV *sv)
4400 Perl_parse_unicode_opts(pTHX_ char **popt)
4402 const char *p = *popt;
4407 opt = (U32) atoi(p);
4408 while (isDIGIT(*p)) p++;
4409 if (*p && *p != '\n' && *p != '\r')
4410 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4415 case PERL_UNICODE_STDIN:
4416 opt |= PERL_UNICODE_STDIN_FLAG; break;
4417 case PERL_UNICODE_STDOUT:
4418 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4419 case PERL_UNICODE_STDERR:
4420 opt |= PERL_UNICODE_STDERR_FLAG; break;
4421 case PERL_UNICODE_STD:
4422 opt |= PERL_UNICODE_STD_FLAG; break;
4423 case PERL_UNICODE_IN:
4424 opt |= PERL_UNICODE_IN_FLAG; break;
4425 case PERL_UNICODE_OUT:
4426 opt |= PERL_UNICODE_OUT_FLAG; break;
4427 case PERL_UNICODE_INOUT:
4428 opt |= PERL_UNICODE_INOUT_FLAG; break;
4429 case PERL_UNICODE_LOCALE:
4430 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4431 case PERL_UNICODE_ARGV:
4432 opt |= PERL_UNICODE_ARGV_FLAG; break;
4434 if (*p != '\n' && *p != '\r')
4436 "Unknown Unicode option letter '%c'", *p);
4442 opt = PERL_UNICODE_DEFAULT_FLAGS;
4444 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4445 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4446 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4457 * This is really just a quick hack which grabs various garbage
4458 * values. It really should be a real hash algorithm which
4459 * spreads the effect of every input bit onto every output bit,
4460 * if someone who knows about such things would bother to write it.
4461 * Might be a good idea to add that function to CORE as well.
4462 * No numbers below come from careful analysis or anything here,
4463 * except they are primes and SEED_C1 > 1E6 to get a full-width
4464 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4465 * probably be bigger too.
4468 # define SEED_C1 1000003
4469 #define SEED_C4 73819
4471 # define SEED_C1 25747
4472 #define SEED_C4 20639
4476 #define SEED_C5 26107
4478 #ifndef PERL_NO_DEV_RANDOM
4483 # include <starlet.h>
4484 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4485 * in 100-ns units, typically incremented ever 10 ms. */
4486 unsigned int when[2];
4488 # ifdef HAS_GETTIMEOFDAY
4489 struct timeval when;
4495 /* This test is an escape hatch, this symbol isn't set by Configure. */
4496 #ifndef PERL_NO_DEV_RANDOM
4497 #ifndef PERL_RANDOM_DEVICE
4498 /* /dev/random isn't used by default because reads from it will block
4499 * if there isn't enough entropy available. You can compile with
4500 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4501 * is enough real entropy to fill the seed. */
4502 # define PERL_RANDOM_DEVICE "/dev/urandom"
4504 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4506 if (PerlLIO_read(fd, &u, sizeof u) != sizeof u)
4515 _ckvmssts(sys$gettim(when));
4516 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4518 # ifdef HAS_GETTIMEOFDAY
4519 PerlProc_gettimeofday(&when,NULL);
4520 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4523 u = (U32)SEED_C1 * when;
4526 u += SEED_C3 * (U32)PerlProc_getpid();
4527 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4528 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4529 u += SEED_C5 * (U32)PTR2UV(&when);
4535 Perl_get_hash_seed(pTHX)
4537 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4541 while (isSPACE(*s)) s++;
4542 if (s && isDIGIT(*s))
4543 myseed = (UV)Atoul(s);
4545 #ifdef USE_HASH_SEED_EXPLICIT
4549 /* Compute a random seed */
4550 (void)seedDrand01((Rand_seed_t)seed());
4551 myseed = (UV)(Drand01() * (NV)UV_MAX);
4552 #if RANDBITS < (UVSIZE * 8)
4553 /* Since there are not enough randbits to to reach all
4554 * the bits of a UV, the low bits might need extra
4555 * help. Sum in another random number that will
4556 * fill in the low bits. */
4558 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4559 #endif /* RANDBITS < (UVSIZE * 8) */
4560 if (myseed == 0) { /* Superparanoia. */
4561 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4563 Perl_croak(aTHX_ "Your random numbers are not that random");
4566 PL_rehash_seed_set = TRUE;
4572 * c-indentation-style: bsd
4574 * indent-tabs-mode: t
4577 * ex: set ts=8 sts=4 sw=4 noet: