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)
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(sv, len);
382 (void)SvUPGRADE(sv, SVt_PVBM);
383 if (len == 0) /* TAIL might be on a zero-length string. */
393 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
394 table = (unsigned char*)(SvPVX(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 = (unsigned char*)(SvPVX(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 unsigned char *little = (unsigned char *)SvPV(littlestr,l);
446 register STRLEN littlelen = l;
447 register const I32 multiline = flags & FBMrf_MULTILINE;
449 if ((STRLEN)(bigend - big) < littlelen) {
450 if ( SvTAIL(littlestr)
451 && ((STRLEN)(bigend - big) == littlelen - 1)
453 || (*big == *little &&
454 memEQ(big, little, littlelen - 1))))
459 if (littlelen <= 2) { /* Special-cased */
461 if (littlelen == 1) {
462 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
463 /* Know that bigend != big. */
464 if (bigend[-1] == '\n')
465 return (char *)(bigend - 1);
466 return (char *) bigend;
474 if (SvTAIL(littlestr))
475 return (char *) bigend;
479 return (char*)big; /* Cannot be SvTAIL! */
482 if (SvTAIL(littlestr) && !multiline) {
483 if (bigend[-1] == '\n' && bigend[-2] == *little)
484 return (char*)bigend - 2;
485 if (bigend[-1] == *little)
486 return (char*)bigend - 1;
490 /* This should be better than FBM if c1 == c2, and almost
491 as good otherwise: maybe better since we do less indirection.
492 And we save a lot of memory by caching no table. */
493 register unsigned char c1 = little[0];
494 register unsigned char c2 = little[1];
499 while (s <= bigend) {
509 goto check_1char_anchor;
520 goto check_1char_anchor;
523 while (s <= bigend) {
528 goto check_1char_anchor;
537 check_1char_anchor: /* One char and anchor! */
538 if (SvTAIL(littlestr) && (*bigend == *little))
539 return (char *)bigend; /* bigend is already decremented. */
542 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
543 s = bigend - littlelen;
544 if (s >= big && bigend[-1] == '\n' && *s == *little
545 /* Automatically of length > 2 */
546 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
548 return (char*)s; /* how sweet it is */
551 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
553 return (char*)s + 1; /* how sweet it is */
557 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
558 char *b = ninstr((char*)big,(char*)bigend,
559 (char*)little, (char*)little + littlelen);
561 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
562 /* Chop \n from littlestr: */
563 s = bigend - littlelen + 1;
565 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
574 { /* Do actual FBM. */
575 register const unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
576 register unsigned char *oldlittle;
578 if (littlelen > (STRLEN)(bigend - big))
580 --littlelen; /* Last char found by table lookup */
583 little += littlelen; /* last char */
590 if ((tmp = table[*s])) {
591 if ((s += tmp) < bigend)
595 else { /* less expensive than calling strncmp() */
596 register unsigned char *olds = s;
601 if (*--s == *--little)
603 s = olds + 1; /* here we pay the price for failure */
605 if (s < bigend) /* fake up continue to outer loop */
613 if ( s == bigend && (table[-1] & FBMcf_TAIL)
614 && memEQ((char *)(bigend - littlelen),
615 (char *)(oldlittle - littlelen), littlelen) )
616 return (char*)bigend - littlelen;
621 /* start_shift, end_shift are positive quantities which give offsets
622 of ends of some substring of bigstr.
623 If `last' we want the last occurrence.
624 old_posp is the way of communication between consequent calls if
625 the next call needs to find the .
626 The initial *old_posp should be -1.
628 Note that we take into account SvTAIL, so one can get extra
629 optimizations if _ALL flag is set.
632 /* If SvTAIL is actually due to \Z or \z, this gives false positives
633 if PL_multiline. In fact if !PL_multiline the authoritative answer
634 is not supported yet. */
637 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
639 register unsigned char *s, *x;
640 register unsigned char *big;
642 register I32 previous;
644 register unsigned char *little;
645 register I32 stop_pos;
646 register unsigned char *littleend;
650 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
651 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
653 if ( BmRARE(littlestr) == '\n'
654 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
655 little = (unsigned char *)(SvPVX(littlestr));
656 littleend = little + SvCUR(littlestr);
663 little = (unsigned char *)(SvPVX(littlestr));
664 littleend = little + SvCUR(littlestr);
666 /* The value of pos we can start at: */
667 previous = BmPREVIOUS(littlestr);
668 big = (unsigned char *)(SvPVX(bigstr));
669 /* The value of pos we can stop at: */
670 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
671 if (previous + start_shift > stop_pos) {
673 stop_pos does not include SvTAIL in the count, so this check is incorrect
674 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
677 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
682 while (pos < previous + start_shift) {
683 if (!(pos += PL_screamnext[pos]))
688 if (pos >= stop_pos) break;
689 if (big[pos] != first)
691 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
697 if (s == littleend) {
699 if (!last) return (char *)(big+pos);
702 } while ( pos += PL_screamnext[pos] );
704 return (char *)(big+(*old_posp));
706 if (!SvTAIL(littlestr) || (end_shift > 0))
708 /* Ignore the trailing "\n". This code is not microoptimized */
709 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
710 stop_pos = littleend - little; /* Actual littlestr len */
715 && ((stop_pos == 1) ||
716 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
722 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
724 register const U8 *a = (const U8 *)s1;
725 register const U8 *b = (const U8 *)s2;
727 if (*a != *b && *a != PL_fold[*b])
735 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
737 register const U8 *a = (const U8 *)s1;
738 register const U8 *b = (const U8 *)s2;
740 if (*a != *b && *a != PL_fold_locale[*b])
747 /* copy a string to a safe spot */
750 =head1 Memory Management
754 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
755 string which is a duplicate of C<pv>. The size of the string is
756 determined by C<strlen()>. The memory allocated for the new string can
757 be freed with the C<Safefree()> function.
763 Perl_savepv(pTHX_ const char *pv)
765 register char *newaddr;
766 #ifdef PERL_MALLOC_WRAP
772 #ifdef PERL_MALLOC_WRAP
773 pvlen = strlen(pv)+1;
774 New(902,newaddr,pvlen,char);
776 New(902,newaddr,strlen(pv)+1,char);
778 return strcpy(newaddr,pv);
781 /* same thing but with a known length */
786 Perl's version of what C<strndup()> would be if it existed. Returns a
787 pointer to a newly allocated string which is a duplicate of the first
788 C<len> bytes from C<pv>. The memory allocated for the new string can be
789 freed with the C<Safefree()> function.
795 Perl_savepvn(pTHX_ const char *pv, register I32 len)
797 register char *newaddr;
799 New(903,newaddr,len+1,char);
800 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
802 /* might not be null terminated */
804 return CopyD(pv,newaddr,len,char);
807 return ZeroD(newaddr,len+1,char);
812 =for apidoc savesharedpv
814 A version of C<savepv()> which allocates the duplicate string in memory
815 which is shared between threads.
820 Perl_savesharedpv(pTHX_ const char *pv)
822 register char *newaddr;
826 newaddr = (char*)PerlMemShared_malloc(strlen(pv)+1);
828 PerlLIO_write(PerlIO_fileno(Perl_error_log),
829 PL_no_mem, strlen(PL_no_mem));
832 return strcpy(newaddr,pv);
838 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
839 the passed in SV using C<SvPV()>
845 Perl_savesvpv(pTHX_ SV *sv)
848 const char *pv = SvPV(sv, len);
849 register char *newaddr;
852 New(903,newaddr,len,char);
853 return CopyD(pv,newaddr,len,char);
857 /* the SV for Perl_form() and mess() is not kept in an arena */
866 return sv_2mortal(newSVpvn("",0));
871 /* Create as PVMG now, to avoid any upgrading later */
873 Newz(905, any, 1, XPVMG);
874 SvFLAGS(sv) = SVt_PVMG;
875 SvANY(sv) = (void*)any;
876 SvREFCNT(sv) = 1 << 30; /* practically infinite */
881 #if defined(PERL_IMPLICIT_CONTEXT)
883 Perl_form_nocontext(const char* pat, ...)
889 retval = vform(pat, &args);
893 #endif /* PERL_IMPLICIT_CONTEXT */
896 =head1 Miscellaneous Functions
899 Takes a sprintf-style format pattern and conventional
900 (non-SV) arguments and returns the formatted string.
902 (char *) Perl_form(pTHX_ const char* pat, ...)
904 can be used any place a string (char *) is required:
906 char * s = Perl_form("%d.%d",major,minor);
908 Uses a single private buffer so if you want to format several strings you
909 must explicitly copy the earlier strings away (and free the copies when you
916 Perl_form(pTHX_ const char* pat, ...)
921 retval = vform(pat, &args);
927 Perl_vform(pTHX_ const char *pat, va_list *args)
929 SV *sv = mess_alloc();
930 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
934 #if defined(PERL_IMPLICIT_CONTEXT)
936 Perl_mess_nocontext(const char *pat, ...)
942 retval = vmess(pat, &args);
946 #endif /* PERL_IMPLICIT_CONTEXT */
949 Perl_mess(pTHX_ const char *pat, ...)
954 retval = vmess(pat, &args);
960 S_closest_cop(pTHX_ COP *cop, OP *o)
962 /* Look for PL_op starting from o. cop is the last COP we've seen. */
964 if (!o || o == PL_op) return cop;
966 if (o->op_flags & OPf_KIDS) {
968 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
972 /* If the OP_NEXTSTATE has been optimised away we can still use it
973 * the get the file and line number. */
975 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
978 /* Keep searching, and return when we've found something. */
980 new_cop = closest_cop(cop, kid);
981 if (new_cop) return new_cop;
991 Perl_vmess(pTHX_ const char *pat, va_list *args)
993 SV *sv = mess_alloc();
994 static char dgd[] = " during global destruction.\n";
996 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
997 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1000 * Try and find the file and line for PL_op. This will usually be
1001 * PL_curcop, but it might be a cop that has been optimised away. We
1002 * can try to find such a cop by searching through the optree starting
1003 * from the sibling of PL_curcop.
1006 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1007 if (!cop) cop = PL_curcop;
1010 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1011 OutCopFILE(cop), (IV)CopLINE(cop));
1012 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1013 const bool line_mode = (RsSIMPLE(PL_rs) &&
1014 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1015 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1016 PL_last_in_gv == PL_argvgv ?
1017 "" : GvNAME(PL_last_in_gv),
1018 line_mode ? "line" : "chunk",
1019 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1021 #ifdef USE_5005THREADS
1023 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1025 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1031 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1036 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1037 && (io = GvIO(PL_stderrgv))
1038 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1045 SAVESPTR(PL_stderrgv);
1046 PL_stderrgv = Nullgv;
1048 PUSHSTACKi(PERLSI_MAGIC);
1052 PUSHs(SvTIED_obj((SV*)io, mg));
1053 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1055 call_method("PRINT", G_SCALAR);
1063 /* SFIO can really mess with your errno */
1066 PerlIO *serr = Perl_error_log;
1068 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1069 (void)PerlIO_flush(serr);
1076 /* Common code used by vcroak, vdie and vwarner */
1078 void S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8);
1080 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1081 may have linked against it. */
1083 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1089 SV *msv = vmess(pat, args);
1090 if (PL_errors && SvCUR(PL_errors)) {
1091 sv_catsv(PL_errors, msv);
1092 message = SvPV(PL_errors, *msglen);
1093 SvCUR_set(PL_errors, 0);
1096 message = SvPV(msv,*msglen);
1097 *utf8 = SvUTF8(msv);
1103 DEBUG_S(PerlIO_printf(Perl_debug_log,
1104 "%p: die/croak: message = %s\ndiehook = %p\n",
1105 thr, message, PL_diehook));
1107 S_vdie_common(aTHX_ message, *msglen, *utf8);
1113 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1118 /* sv_2cv might call Perl_croak() */
1119 SV *olddiehook = PL_diehook;
1123 SAVESPTR(PL_diehook);
1124 PL_diehook = Nullsv;
1125 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1127 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1134 msg = newSVpvn(message, msglen);
1135 SvFLAGS(msg) |= utf8;
1143 PUSHSTACKi(PERLSI_DIEHOOK);
1147 call_sv((SV*)cv, G_DISCARD);
1154 Perl_vdie(pTHX_ const char* pat, va_list *args)
1156 const char *message;
1157 const int was_in_eval = PL_in_eval;
1161 DEBUG_S(PerlIO_printf(Perl_debug_log,
1162 "%p: die: curstack = %p, mainstack = %p\n",
1163 thr, PL_curstack, PL_mainstack));
1165 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1167 PL_restartop = die_where(message, msglen);
1168 SvFLAGS(ERRSV) |= utf8;
1169 DEBUG_S(PerlIO_printf(Perl_debug_log,
1170 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1171 thr, PL_restartop, was_in_eval, PL_top_env));
1172 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1174 return PL_restartop;
1177 #if defined(PERL_IMPLICIT_CONTEXT)
1179 Perl_die_nocontext(const char* pat, ...)
1184 va_start(args, pat);
1185 o = vdie(pat, &args);
1189 #endif /* PERL_IMPLICIT_CONTEXT */
1192 Perl_die(pTHX_ const char* pat, ...)
1196 va_start(args, pat);
1197 o = vdie(pat, &args);
1203 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1205 const char *message;
1209 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1212 PL_restartop = die_where(message, msglen);
1213 SvFLAGS(ERRSV) |= utf8;
1217 message = SvPVx(ERRSV, msglen);
1219 write_to_stderr(message, msglen);
1223 #if defined(PERL_IMPLICIT_CONTEXT)
1225 Perl_croak_nocontext(const char *pat, ...)
1229 va_start(args, pat);
1234 #endif /* PERL_IMPLICIT_CONTEXT */
1237 =head1 Warning and Dieing
1241 This is the XSUB-writer's interface to Perl's C<die> function.
1242 Normally call this function the same way you call the C C<printf>
1243 function. Calling C<croak> returns control directly to Perl,
1244 sidestepping the normal C order of execution. See C<warn>.
1246 If you want to throw an exception object, assign the object to
1247 C<$@> and then pass C<Nullch> to croak():
1249 errsv = get_sv("@", TRUE);
1250 sv_setsv(errsv, exception_object);
1257 Perl_croak(pTHX_ const char *pat, ...)
1260 va_start(args, pat);
1267 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1277 msv = vmess(pat, args);
1279 message = SvPV(msv, msglen);
1282 /* sv_2cv might call Perl_warn() */
1283 SV *oldwarnhook = PL_warnhook;
1285 SAVESPTR(PL_warnhook);
1286 PL_warnhook = Nullsv;
1287 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1289 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1295 msg = newSVpvn(message, msglen);
1296 SvFLAGS(msg) |= utf8;
1300 PUSHSTACKi(PERLSI_WARNHOOK);
1304 call_sv((SV*)cv, G_DISCARD);
1311 write_to_stderr(message, msglen);
1314 #if defined(PERL_IMPLICIT_CONTEXT)
1316 Perl_warn_nocontext(const char *pat, ...)
1320 va_start(args, pat);
1324 #endif /* PERL_IMPLICIT_CONTEXT */
1329 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1330 function the same way you call the C C<printf> function. See C<croak>.
1336 Perl_warn(pTHX_ const char *pat, ...)
1339 va_start(args, pat);
1344 #if defined(PERL_IMPLICIT_CONTEXT)
1346 Perl_warner_nocontext(U32 err, const char *pat, ...)
1350 va_start(args, pat);
1351 vwarner(err, pat, &args);
1354 #endif /* PERL_IMPLICIT_CONTEXT */
1357 Perl_warner(pTHX_ U32 err, const char* pat,...)
1360 va_start(args, pat);
1361 vwarner(err, pat, &args);
1366 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1369 SV *msv = vmess(pat, args);
1371 const char *message = SvPV(msv, msglen);
1372 I32 utf8 = SvUTF8(msv);
1374 #ifdef USE_5005THREADS
1375 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1376 #endif /* USE_5005THREADS */
1379 S_vdie_common(aTHX_ message, msglen, utf8);
1382 PL_restartop = die_where(message, msglen);
1383 SvFLAGS(ERRSV) |= utf8;
1386 write_to_stderr(message, msglen);
1390 Perl_vwarn(aTHX_ pat, args);
1394 /* since we've already done strlen() for both nam and val
1395 * we can use that info to make things faster than
1396 * sprintf(s, "%s=%s", nam, val)
1398 #define my_setenv_format(s, nam, nlen, val, vlen) \
1399 Copy(nam, s, nlen, char); \
1401 Copy(val, s+(nlen+1), vlen, char); \
1402 *(s+(nlen+1+vlen)) = '\0'
1404 #ifdef USE_ENVIRON_ARRAY
1405 /* VMS' my_setenv() is in vms.c */
1406 #if !defined(WIN32) && !defined(NETWARE)
1408 Perl_my_setenv(pTHX_ char *nam, char *val)
1411 /* only parent thread can modify process environment */
1412 if (PL_curinterp == aTHX)
1415 #ifndef PERL_USE_SAFE_PUTENV
1416 if (!PL_use_safe_putenv) {
1417 /* most putenv()s leak, so we manipulate environ directly */
1418 register I32 i=setenv_getix(nam); /* where does it go? */
1421 if (environ == PL_origenviron) { /* need we copy environment? */
1427 for (max = i; environ[max]; max++) ;
1428 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1429 for (j=0; j<max; j++) { /* copy environment */
1430 const int len = strlen(environ[j]);
1431 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1432 Copy(environ[j], tmpenv[j], len+1, char);
1434 tmpenv[max] = Nullch;
1435 environ = tmpenv; /* tell exec where it is now */
1438 safesysfree(environ[i]);
1439 while (environ[i]) {
1440 environ[i] = environ[i+1];
1445 if (!environ[i]) { /* does not exist yet */
1446 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1447 environ[i+1] = Nullch; /* make sure it's null terminated */
1450 safesysfree(environ[i]);
1454 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1455 /* all that work just for this */
1456 my_setenv_format(environ[i], nam, nlen, val, vlen);
1459 # if defined(__CYGWIN__) || defined( EPOC)
1460 setenv(nam, val, 1);
1463 int nlen = strlen(nam), vlen;
1468 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1469 /* all that work just for this */
1470 my_setenv_format(new_env, nam, nlen, val, vlen);
1471 (void)putenv(new_env);
1472 # endif /* __CYGWIN__ */
1473 #ifndef PERL_USE_SAFE_PUTENV
1479 #else /* WIN32 || NETWARE */
1482 Perl_my_setenv(pTHX_ const char *nam, char *val)
1484 register char *envstr;
1485 const int nlen = strlen(nam);
1492 New(904, envstr, nlen+vlen+2, char);
1493 my_setenv_format(envstr, nam, nlen, val, vlen);
1494 (void)PerlEnv_putenv(envstr);
1498 #endif /* WIN32 || NETWARE */
1502 Perl_setenv_getix(pTHX_ char *nam)
1504 register I32 i, len = strlen(nam);
1506 for (i = 0; environ[i]; i++) {
1509 strnicmp(environ[i],nam,len) == 0
1511 strnEQ(environ[i],nam,len)
1513 && environ[i][len] == '=')
1514 break; /* strnEQ must come first to avoid */
1515 } /* potential SEGV's */
1518 #endif /* !PERL_MICRO */
1520 #endif /* !VMS && !EPOC*/
1522 #ifdef UNLINK_ALL_VERSIONS
1524 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1528 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1533 /* this is a drop-in replacement for bcopy() */
1534 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1536 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1540 if (from - to >= 0) {
1548 *(--to) = *(--from);
1554 /* this is a drop-in replacement for memset() */
1557 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1567 /* this is a drop-in replacement for bzero() */
1568 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1570 Perl_my_bzero(register char *loc, register I32 len)
1580 /* this is a drop-in replacement for memcmp() */
1581 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1583 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1585 register const U8 *a = (const U8 *)s1;
1586 register const U8 *b = (const U8 *)s2;
1590 if (tmp = *a++ - *b++)
1595 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1599 #ifdef USE_CHAR_VSPRINTF
1604 vsprintf(char *dest, const char *pat, char *args)
1608 fakebuf._ptr = dest;
1609 fakebuf._cnt = 32767;
1613 fakebuf._flag = _IOWRT|_IOSTRG;
1614 _doprnt(pat, args, &fakebuf); /* what a kludge */
1615 (void)putc('\0', &fakebuf);
1616 #ifdef USE_CHAR_VSPRINTF
1619 return 0; /* perl doesn't use return value */
1623 #endif /* HAS_VPRINTF */
1626 #if BYTEORDER != 0x4321
1628 Perl_my_swap(pTHX_ short s)
1630 #if (BYTEORDER & 1) == 0
1633 result = ((s & 255) << 8) + ((s >> 8) & 255);
1641 Perl_my_htonl(pTHX_ long l)
1645 char c[sizeof(long)];
1648 #if BYTEORDER == 0x1234
1649 u.c[0] = (l >> 24) & 255;
1650 u.c[1] = (l >> 16) & 255;
1651 u.c[2] = (l >> 8) & 255;
1655 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1656 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1661 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1662 u.c[o & 0xf] = (l >> s) & 255;
1670 Perl_my_ntohl(pTHX_ long l)
1674 char c[sizeof(long)];
1677 #if BYTEORDER == 0x1234
1678 u.c[0] = (l >> 24) & 255;
1679 u.c[1] = (l >> 16) & 255;
1680 u.c[2] = (l >> 8) & 255;
1684 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1685 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1692 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1693 l |= (u.c[o & 0xf] & 255) << s;
1700 #endif /* BYTEORDER != 0x4321 */
1704 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1705 * If these functions are defined,
1706 * the BYTEORDER is neither 0x1234 nor 0x4321.
1707 * However, this is not assumed.
1711 #define HTOLE(name,type) \
1713 name (register type n) \
1717 char c[sizeof(type)]; \
1720 register I32 s = 0; \
1721 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1722 u.c[i] = (n >> s) & 0xFF; \
1727 #define LETOH(name,type) \
1729 name (register type n) \
1733 char c[sizeof(type)]; \
1736 register I32 s = 0; \
1739 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1740 n |= ((type)(u.c[i] & 0xFF)) << s; \
1746 * Big-endian byte order functions.
1749 #define HTOBE(name,type) \
1751 name (register type n) \
1755 char c[sizeof(type)]; \
1758 register I32 s = 8*(sizeof(u.c)-1); \
1759 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1760 u.c[i] = (n >> s) & 0xFF; \
1765 #define BETOH(name,type) \
1767 name (register type n) \
1771 char c[sizeof(type)]; \
1774 register I32 s = 8*(sizeof(u.c)-1); \
1777 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1778 n |= ((type)(u.c[i] & 0xFF)) << s; \
1784 * If we just can't do it...
1787 #define NOT_AVAIL(name,type) \
1789 name (register type n) \
1791 Perl_croak_nocontext(#name "() not available"); \
1792 return n; /* not reached */ \
1796 #if defined(HAS_HTOVS) && !defined(htovs)
1799 #if defined(HAS_HTOVL) && !defined(htovl)
1802 #if defined(HAS_VTOHS) && !defined(vtohs)
1805 #if defined(HAS_VTOHL) && !defined(vtohl)
1809 #ifdef PERL_NEED_MY_HTOLE16
1811 HTOLE(Perl_my_htole16,U16)
1813 NOT_AVAIL(Perl_my_htole16,U16)
1816 #ifdef PERL_NEED_MY_LETOH16
1818 LETOH(Perl_my_letoh16,U16)
1820 NOT_AVAIL(Perl_my_letoh16,U16)
1823 #ifdef PERL_NEED_MY_HTOBE16
1825 HTOBE(Perl_my_htobe16,U16)
1827 NOT_AVAIL(Perl_my_htobe16,U16)
1830 #ifdef PERL_NEED_MY_BETOH16
1832 BETOH(Perl_my_betoh16,U16)
1834 NOT_AVAIL(Perl_my_betoh16,U16)
1838 #ifdef PERL_NEED_MY_HTOLE32
1840 HTOLE(Perl_my_htole32,U32)
1842 NOT_AVAIL(Perl_my_htole32,U32)
1845 #ifdef PERL_NEED_MY_LETOH32
1847 LETOH(Perl_my_letoh32,U32)
1849 NOT_AVAIL(Perl_my_letoh32,U32)
1852 #ifdef PERL_NEED_MY_HTOBE32
1854 HTOBE(Perl_my_htobe32,U32)
1856 NOT_AVAIL(Perl_my_htobe32,U32)
1859 #ifdef PERL_NEED_MY_BETOH32
1861 BETOH(Perl_my_betoh32,U32)
1863 NOT_AVAIL(Perl_my_betoh32,U32)
1867 #ifdef PERL_NEED_MY_HTOLE64
1869 HTOLE(Perl_my_htole64,U64)
1871 NOT_AVAIL(Perl_my_htole64,U64)
1874 #ifdef PERL_NEED_MY_LETOH64
1876 LETOH(Perl_my_letoh64,U64)
1878 NOT_AVAIL(Perl_my_letoh64,U64)
1881 #ifdef PERL_NEED_MY_HTOBE64
1883 HTOBE(Perl_my_htobe64,U64)
1885 NOT_AVAIL(Perl_my_htobe64,U64)
1888 #ifdef PERL_NEED_MY_BETOH64
1890 BETOH(Perl_my_betoh64,U64)
1892 NOT_AVAIL(Perl_my_betoh64,U64)
1896 #ifdef PERL_NEED_MY_HTOLES
1897 HTOLE(Perl_my_htoles,short)
1899 #ifdef PERL_NEED_MY_LETOHS
1900 LETOH(Perl_my_letohs,short)
1902 #ifdef PERL_NEED_MY_HTOBES
1903 HTOBE(Perl_my_htobes,short)
1905 #ifdef PERL_NEED_MY_BETOHS
1906 BETOH(Perl_my_betohs,short)
1909 #ifdef PERL_NEED_MY_HTOLEI
1910 HTOLE(Perl_my_htolei,int)
1912 #ifdef PERL_NEED_MY_LETOHI
1913 LETOH(Perl_my_letohi,int)
1915 #ifdef PERL_NEED_MY_HTOBEI
1916 HTOBE(Perl_my_htobei,int)
1918 #ifdef PERL_NEED_MY_BETOHI
1919 BETOH(Perl_my_betohi,int)
1922 #ifdef PERL_NEED_MY_HTOLEL
1923 HTOLE(Perl_my_htolel,long)
1925 #ifdef PERL_NEED_MY_LETOHL
1926 LETOH(Perl_my_letohl,long)
1928 #ifdef PERL_NEED_MY_HTOBEL
1929 HTOBE(Perl_my_htobel,long)
1931 #ifdef PERL_NEED_MY_BETOHL
1932 BETOH(Perl_my_betohl,long)
1936 Perl_my_swabn(void *ptr, int n)
1938 register char *s = (char *)ptr;
1939 register char *e = s + (n-1);
1942 for (n /= 2; n > 0; s++, e--, n--) {
1950 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1952 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1954 register I32 This, that;
1960 PERL_FLUSHALL_FOR_CHILD;
1961 This = (*mode == 'w');
1965 taint_proper("Insecure %s%s", "EXEC");
1967 if (PerlProc_pipe(p) < 0)
1969 /* Try for another pipe pair for error return */
1970 if (PerlProc_pipe(pp) >= 0)
1972 while ((pid = PerlProc_fork()) < 0) {
1973 if (errno != EAGAIN) {
1974 PerlLIO_close(p[This]);
1975 PerlLIO_close(p[that]);
1977 PerlLIO_close(pp[0]);
1978 PerlLIO_close(pp[1]);
1990 /* Close parent's end of error status pipe (if any) */
1992 PerlLIO_close(pp[0]);
1993 #if defined(HAS_FCNTL) && defined(F_SETFD)
1994 /* Close error pipe automatically if exec works */
1995 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1998 /* Now dup our end of _the_ pipe to right position */
1999 if (p[THIS] != (*mode == 'r')) {
2000 PerlLIO_dup2(p[THIS], *mode == 'r');
2001 PerlLIO_close(p[THIS]);
2002 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2003 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2006 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2007 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2008 /* No automatic close - do it by hand */
2015 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2021 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2027 do_execfree(); /* free any memory malloced by child on fork */
2029 PerlLIO_close(pp[1]);
2030 /* Keep the lower of the two fd numbers */
2031 if (p[that] < p[This]) {
2032 PerlLIO_dup2(p[This], p[that]);
2033 PerlLIO_close(p[This]);
2037 PerlLIO_close(p[that]); /* close child's end of pipe */
2040 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2042 (void)SvUPGRADE(sv,SVt_IV);
2044 PL_forkprocess = pid;
2045 /* If we managed to get status pipe check for exec fail */
2046 if (did_pipes && pid > 0) {
2050 while (n < sizeof(int)) {
2051 n1 = PerlLIO_read(pp[0],
2052 (void*)(((char*)&errkid)+n),
2058 PerlLIO_close(pp[0]);
2060 if (n) { /* Error */
2062 PerlLIO_close(p[This]);
2063 if (n != sizeof(int))
2064 Perl_croak(aTHX_ "panic: kid popen errno read");
2066 pid2 = wait4pid(pid, &status, 0);
2067 } while (pid2 == -1 && errno == EINTR);
2068 errno = errkid; /* Propagate errno from kid */
2073 PerlLIO_close(pp[0]);
2074 return PerlIO_fdopen(p[This], mode);
2076 Perl_croak(aTHX_ "List form of piped open not implemented");
2077 return (PerlIO *) NULL;
2081 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2082 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2084 Perl_my_popen(pTHX_ char *cmd, char *mode)
2087 register I32 This, that;
2090 I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2094 PERL_FLUSHALL_FOR_CHILD;
2097 return my_syspopen(aTHX_ cmd,mode);
2100 This = (*mode == 'w');
2102 if (doexec && PL_tainting) {
2104 taint_proper("Insecure %s%s", "EXEC");
2106 if (PerlProc_pipe(p) < 0)
2108 if (doexec && PerlProc_pipe(pp) >= 0)
2110 while ((pid = PerlProc_fork()) < 0) {
2111 if (errno != EAGAIN) {
2112 PerlLIO_close(p[This]);
2113 PerlLIO_close(p[that]);
2115 PerlLIO_close(pp[0]);
2116 PerlLIO_close(pp[1]);
2119 Perl_croak(aTHX_ "Can't fork");
2132 PerlLIO_close(pp[0]);
2133 #if defined(HAS_FCNTL) && defined(F_SETFD)
2134 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2137 if (p[THIS] != (*mode == 'r')) {
2138 PerlLIO_dup2(p[THIS], *mode == 'r');
2139 PerlLIO_close(p[THIS]);
2140 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2141 PerlLIO_close(p[THAT]);
2144 PerlLIO_close(p[THAT]);
2147 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2156 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2161 /* may or may not use the shell */
2162 do_exec3(cmd, pp[1], did_pipes);
2165 #endif /* defined OS2 */
2167 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2168 SvREADONLY_off(GvSV(tmpgv));
2169 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2170 SvREADONLY_on(GvSV(tmpgv));
2172 #ifdef THREADS_HAVE_PIDS
2173 PL_ppid = (IV)getppid();
2176 hv_clear(PL_pidstatus); /* we have no children */
2181 do_execfree(); /* free any memory malloced by child on vfork */
2183 PerlLIO_close(pp[1]);
2184 if (p[that] < p[This]) {
2185 PerlLIO_dup2(p[This], p[that]);
2186 PerlLIO_close(p[This]);
2190 PerlLIO_close(p[that]);
2193 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2195 (void)SvUPGRADE(sv,SVt_IV);
2197 PL_forkprocess = pid;
2198 if (did_pipes && pid > 0) {
2202 while (n < sizeof(int)) {
2203 n1 = PerlLIO_read(pp[0],
2204 (void*)(((char*)&errkid)+n),
2210 PerlLIO_close(pp[0]);
2212 if (n) { /* Error */
2214 PerlLIO_close(p[This]);
2215 if (n != sizeof(int))
2216 Perl_croak(aTHX_ "panic: kid popen errno read");
2218 pid2 = wait4pid(pid, &status, 0);
2219 } while (pid2 == -1 && errno == EINTR);
2220 errno = errkid; /* Propagate errno from kid */
2225 PerlLIO_close(pp[0]);
2226 return PerlIO_fdopen(p[This], mode);
2229 #if defined(atarist) || defined(EPOC)
2232 Perl_my_popen(pTHX_ char *cmd, char *mode)
2234 PERL_FLUSHALL_FOR_CHILD;
2235 /* Call system's popen() to get a FILE *, then import it.
2236 used 0 for 2nd parameter to PerlIO_importFILE;
2239 return PerlIO_importFILE(popen(cmd, mode), 0);
2243 FILE *djgpp_popen();
2245 Perl_my_popen(pTHX_ char *cmd, char *mode)
2247 PERL_FLUSHALL_FOR_CHILD;
2248 /* Call system's popen() to get a FILE *, then import it.
2249 used 0 for 2nd parameter to PerlIO_importFILE;
2252 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2257 #endif /* !DOSISH */
2259 /* this is called in parent before the fork() */
2261 Perl_atfork_lock(void)
2263 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2264 /* locks must be held in locking order (if any) */
2266 MUTEX_LOCK(&PL_malloc_mutex);
2272 /* this is called in both parent and child after the fork() */
2274 Perl_atfork_unlock(void)
2276 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2277 /* locks must be released in same order as in atfork_lock() */
2279 MUTEX_UNLOCK(&PL_malloc_mutex);
2288 #if defined(HAS_FORK)
2290 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2295 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2296 * handlers elsewhere in the code */
2301 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2302 Perl_croak_nocontext("fork() not available");
2304 #endif /* HAS_FORK */
2309 Perl_dump_fds(pTHX_ char *s)
2314 PerlIO_printf(Perl_debug_log,"%s", s);
2315 for (fd = 0; fd < 32; fd++) {
2316 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2317 PerlIO_printf(Perl_debug_log," %d",fd);
2319 PerlIO_printf(Perl_debug_log,"\n");
2321 #endif /* DUMP_FDS */
2325 dup2(int oldfd, int newfd)
2327 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2330 PerlLIO_close(newfd);
2331 return fcntl(oldfd, F_DUPFD, newfd);
2333 #define DUP2_MAX_FDS 256
2334 int fdtmp[DUP2_MAX_FDS];
2340 PerlLIO_close(newfd);
2341 /* good enough for low fd's... */
2342 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2343 if (fdx >= DUP2_MAX_FDS) {
2351 PerlLIO_close(fdtmp[--fdx]);
2358 #ifdef HAS_SIGACTION
2360 #ifdef MACOS_TRADITIONAL
2361 /* We don't want restart behavior on MacOS */
2366 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2368 struct sigaction act, oact;
2371 /* only "parent" interpreter can diddle signals */
2372 if (PL_curinterp != aTHX)
2376 act.sa_handler = handler;
2377 sigemptyset(&act.sa_mask);
2380 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2381 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2383 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2384 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2385 act.sa_flags |= SA_NOCLDWAIT;
2387 if (sigaction(signo, &act, &oact) == -1)
2390 return oact.sa_handler;
2394 Perl_rsignal_state(pTHX_ int signo)
2396 struct sigaction oact;
2398 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2401 return oact.sa_handler;
2405 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2407 struct sigaction act;
2410 /* only "parent" interpreter can diddle signals */
2411 if (PL_curinterp != aTHX)
2415 act.sa_handler = handler;
2416 sigemptyset(&act.sa_mask);
2419 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2420 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2422 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2423 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2424 act.sa_flags |= SA_NOCLDWAIT;
2426 return sigaction(signo, &act, save);
2430 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2433 /* only "parent" interpreter can diddle signals */
2434 if (PL_curinterp != aTHX)
2438 return sigaction(signo, save, (struct sigaction *)NULL);
2441 #else /* !HAS_SIGACTION */
2444 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2446 #if defined(USE_ITHREADS) && !defined(WIN32)
2447 /* only "parent" interpreter can diddle signals */
2448 if (PL_curinterp != aTHX)
2452 return PerlProc_signal(signo, handler);
2455 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2456 ignore the implications of this for threading */
2466 Perl_rsignal_state(pTHX_ int signo)
2468 Sighandler_t oldsig;
2470 #if defined(USE_ITHREADS) && !defined(WIN32)
2471 /* only "parent" interpreter can diddle signals */
2472 if (PL_curinterp != aTHX)
2477 oldsig = PerlProc_signal(signo, sig_trap);
2478 PerlProc_signal(signo, oldsig);
2480 PerlProc_kill(PerlProc_getpid(), signo);
2485 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2487 #if defined(USE_ITHREADS) && !defined(WIN32)
2488 /* only "parent" interpreter can diddle signals */
2489 if (PL_curinterp != aTHX)
2492 *save = PerlProc_signal(signo, handler);
2493 return (*save == SIG_ERR) ? -1 : 0;
2497 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2499 #if defined(USE_ITHREADS) && !defined(WIN32)
2500 /* only "parent" interpreter can diddle signals */
2501 if (PL_curinterp != aTHX)
2504 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2507 #endif /* !HAS_SIGACTION */
2508 #endif /* !PERL_MICRO */
2510 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2511 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2513 Perl_my_pclose(pTHX_ PerlIO *ptr)
2515 Sigsave_t hstat, istat, qstat;
2521 int saved_errno = 0;
2523 int saved_vaxc_errno;
2526 int saved_win32_errno;
2530 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2532 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2534 *svp = &PL_sv_undef;
2536 if (pid == -1) { /* Opened by popen. */
2537 return my_syspclose(ptr);
2540 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2541 saved_errno = errno;
2543 saved_vaxc_errno = vaxc$errno;
2546 saved_win32_errno = GetLastError();
2550 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2553 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2554 rsignal_save(SIGINT, SIG_IGN, &istat);
2555 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2558 pid2 = wait4pid(pid, &status, 0);
2559 } while (pid2 == -1 && errno == EINTR);
2561 rsignal_restore(SIGHUP, &hstat);
2562 rsignal_restore(SIGINT, &istat);
2563 rsignal_restore(SIGQUIT, &qstat);
2566 SETERRNO(saved_errno, saved_vaxc_errno);
2569 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2571 #endif /* !DOSISH */
2573 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2575 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2580 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2584 char spid[TYPE_CHARS(IV)];
2587 sprintf(spid, "%"IVdf, (IV)pid);
2588 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2589 if (svp && *svp != &PL_sv_undef) {
2590 *statusp = SvIVX(*svp);
2591 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2598 hv_iterinit(PL_pidstatus);
2599 if ((entry = hv_iternext(PL_pidstatus))) {
2600 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2601 sv = hv_iterval(PL_pidstatus,entry);
2602 *statusp = SvIVX(sv);
2603 sprintf(spid, "%"IVdf, (IV)pid);
2604 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2611 # ifdef HAS_WAITPID_RUNTIME
2612 if (!HAS_WAITPID_RUNTIME)
2615 result = PerlProc_waitpid(pid,statusp,flags);
2618 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2619 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2622 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2626 Perl_croak(aTHX_ "Can't do waitpid with flags");
2628 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2629 pidgone(result,*statusp);
2636 if (result < 0 && errno == EINTR) {
2641 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2645 Perl_pidgone(pTHX_ Pid_t pid, int status)
2648 char spid[TYPE_CHARS(IV)];
2650 sprintf(spid, "%"IVdf, (IV)pid);
2651 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2652 (void)SvUPGRADE(sv,SVt_IV);
2653 SvIV_set(sv, status);
2657 #if defined(atarist) || defined(OS2) || defined(EPOC)
2660 int /* Cannot prototype with I32
2662 my_syspclose(PerlIO *ptr)
2665 Perl_my_pclose(pTHX_ PerlIO *ptr)
2668 /* Needs work for PerlIO ! */
2669 FILE *f = PerlIO_findFILE(ptr);
2670 I32 result = pclose(f);
2671 PerlIO_releaseFILE(ptr,f);
2679 Perl_my_pclose(pTHX_ PerlIO *ptr)
2681 /* Needs work for PerlIO ! */
2682 FILE *f = PerlIO_findFILE(ptr);
2683 I32 result = djgpp_pclose(f);
2684 result = (result << 8) & 0xff00;
2685 PerlIO_releaseFILE(ptr,f);
2691 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2694 register const char *frombase = from;
2697 register const char c = *from;
2702 while (count-- > 0) {
2703 for (todo = len; todo > 0; todo--) {
2712 Perl_same_dirent(pTHX_ char *a, char *b)
2714 char *fa = strrchr(a,'/');
2715 char *fb = strrchr(b,'/');
2718 SV *tmpsv = sv_newmortal();
2731 sv_setpvn(tmpsv, ".", 1);
2733 sv_setpvn(tmpsv, a, fa - a);
2734 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2737 sv_setpvn(tmpsv, ".", 1);
2739 sv_setpvn(tmpsv, b, fb - b);
2740 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2742 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2743 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2745 #endif /* !HAS_RENAME */
2748 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2750 const char *xfound = Nullch;
2751 char *xfailed = Nullch;
2752 char tmpbuf[MAXPATHLEN];
2756 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2757 # define SEARCH_EXTS ".bat", ".cmd", NULL
2758 # define MAX_EXT_LEN 4
2761 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2762 # define MAX_EXT_LEN 4
2765 # define SEARCH_EXTS ".pl", ".com", NULL
2766 # define MAX_EXT_LEN 4
2768 /* additional extensions to try in each dir if scriptname not found */
2770 const char *exts[] = { SEARCH_EXTS };
2771 const char **ext = search_ext ? search_ext : exts;
2772 int extidx = 0, i = 0;
2773 const char *curext = Nullch;
2776 # define MAX_EXT_LEN 0
2780 * If dosearch is true and if scriptname does not contain path
2781 * delimiters, search the PATH for scriptname.
2783 * If SEARCH_EXTS is also defined, will look for each
2784 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2785 * while searching the PATH.
2787 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2788 * proceeds as follows:
2789 * If DOSISH or VMSISH:
2790 * + look for ./scriptname{,.foo,.bar}
2791 * + search the PATH for scriptname{,.foo,.bar}
2794 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2795 * this will not look in '.' if it's not in the PATH)
2800 # ifdef ALWAYS_DEFTYPES
2801 len = strlen(scriptname);
2802 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2803 int hasdir, idx = 0, deftypes = 1;
2806 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2809 int hasdir, idx = 0, deftypes = 1;
2812 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2814 /* The first time through, just add SEARCH_EXTS to whatever we
2815 * already have, so we can check for default file types. */
2817 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2823 if ((strlen(tmpbuf) + strlen(scriptname)
2824 + MAX_EXT_LEN) >= sizeof tmpbuf)
2825 continue; /* don't search dir with too-long name */
2826 strcat(tmpbuf, scriptname);
2830 if (strEQ(scriptname, "-"))
2832 if (dosearch) { /* Look in '.' first. */
2833 char *cur = scriptname;
2835 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2837 if (strEQ(ext[i++],curext)) {
2838 extidx = -1; /* already has an ext */
2843 DEBUG_p(PerlIO_printf(Perl_debug_log,
2844 "Looking for %s\n",cur));
2845 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2846 && !S_ISDIR(PL_statbuf.st_mode)) {
2854 if (cur == scriptname) {
2855 len = strlen(scriptname);
2856 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2858 cur = strcpy(tmpbuf, scriptname);
2860 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2861 && strcpy(tmpbuf+len, ext[extidx++]));
2866 #ifdef MACOS_TRADITIONAL
2867 if (dosearch && !strchr(scriptname, ':') &&
2868 (s = PerlEnv_getenv("Commands")))
2870 if (dosearch && !strchr(scriptname, '/')
2872 && !strchr(scriptname, '\\')
2874 && (s = PerlEnv_getenv("PATH")))
2879 PL_bufend = s + strlen(s);
2880 while (s < PL_bufend) {
2881 #ifdef MACOS_TRADITIONAL
2882 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2886 #if defined(atarist) || defined(DOSISH)
2891 && *s != ';'; len++, s++) {
2892 if (len < sizeof tmpbuf)
2895 if (len < sizeof tmpbuf)
2897 #else /* ! (atarist || DOSISH) */
2898 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2901 #endif /* ! (atarist || DOSISH) */
2902 #endif /* MACOS_TRADITIONAL */
2905 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2906 continue; /* don't search dir with too-long name */
2907 #ifdef MACOS_TRADITIONAL
2908 if (len && tmpbuf[len - 1] != ':')
2909 tmpbuf[len++] = ':';
2912 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2913 && tmpbuf[len - 1] != '/'
2914 && tmpbuf[len - 1] != '\\'
2917 tmpbuf[len++] = '/';
2918 if (len == 2 && tmpbuf[0] == '.')
2921 (void)strcpy(tmpbuf + len, scriptname);
2925 len = strlen(tmpbuf);
2926 if (extidx > 0) /* reset after previous loop */
2930 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2931 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2932 if (S_ISDIR(PL_statbuf.st_mode)) {
2936 } while ( retval < 0 /* not there */
2937 && extidx>=0 && ext[extidx] /* try an extension? */
2938 && strcpy(tmpbuf+len, ext[extidx++])
2943 if (S_ISREG(PL_statbuf.st_mode)
2944 && cando(S_IRUSR,TRUE,&PL_statbuf)
2945 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2946 && cando(S_IXUSR,TRUE,&PL_statbuf)
2950 xfound = tmpbuf; /* bingo! */
2954 xfailed = savepv(tmpbuf);
2957 if (!xfound && !seen_dot && !xfailed &&
2958 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2959 || S_ISDIR(PL_statbuf.st_mode)))
2961 seen_dot = 1; /* Disable message. */
2963 if (flags & 1) { /* do or die? */
2964 Perl_croak(aTHX_ "Can't %s %s%s%s",
2965 (xfailed ? "execute" : "find"),
2966 (xfailed ? xfailed : scriptname),
2967 (xfailed ? "" : " on PATH"),
2968 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2970 scriptname = Nullch;
2974 scriptname = xfound;
2976 return (scriptname ? savepv(scriptname) : Nullch);
2979 #ifndef PERL_GET_CONTEXT_DEFINED
2982 Perl_get_context(void)
2984 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2985 # ifdef OLD_PTHREADS_API
2987 if (pthread_getspecific(PL_thr_key, &t))
2988 Perl_croak_nocontext("panic: pthread_getspecific");
2991 # ifdef I_MACH_CTHREADS
2992 return (void*)cthread_data(cthread_self());
2994 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3003 Perl_set_context(void *t)
3005 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
3006 # ifdef I_MACH_CTHREADS
3007 cthread_set_data(cthread_self(), t);
3009 if (pthread_setspecific(PL_thr_key, t))
3010 Perl_croak_nocontext("panic: pthread_setspecific");
3015 #endif /* !PERL_GET_CONTEXT_DEFINED */
3017 #ifdef USE_5005THREADS
3020 /* Very simplistic scheduler for now */
3024 thr = thr->i.next_run;
3028 Perl_cond_init(pTHX_ perl_cond *cp)
3034 Perl_cond_signal(pTHX_ perl_cond *cp)
3037 perl_cond cond = *cp;
3042 /* Insert t in the runnable queue just ahead of us */
3043 t->i.next_run = thr->i.next_run;
3044 thr->i.next_run->i.prev_run = t;
3045 t->i.prev_run = thr;
3046 thr->i.next_run = t;
3047 thr->i.wait_queue = 0;
3048 /* Remove from the wait queue */
3054 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3057 perl_cond cond, cond_next;
3059 for (cond = *cp; cond; cond = cond_next) {
3061 /* Insert t in the runnable queue just ahead of us */
3062 t->i.next_run = thr->i.next_run;
3063 thr->i.next_run->i.prev_run = t;
3064 t->i.prev_run = thr;
3065 thr->i.next_run = t;
3066 thr->i.wait_queue = 0;
3067 /* Remove from the wait queue */
3068 cond_next = cond->next;
3075 Perl_cond_wait(pTHX_ perl_cond *cp)
3079 if (thr->i.next_run == thr)
3080 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3082 New(666, cond, 1, struct perl_wait_queue);
3086 thr->i.wait_queue = cond;
3087 /* Remove ourselves from runnable queue */
3088 thr->i.next_run->i.prev_run = thr->i.prev_run;
3089 thr->i.prev_run->i.next_run = thr->i.next_run;
3091 #endif /* FAKE_THREADS */
3094 Perl_condpair_magic(pTHX_ SV *sv)
3098 (void)SvUPGRADE(sv, SVt_PVMG);
3099 mg = mg_find(sv, PERL_MAGIC_mutex);
3103 New(53, cp, 1, condpair_t);
3104 MUTEX_INIT(&cp->mutex);
3105 COND_INIT(&cp->owner_cond);
3106 COND_INIT(&cp->cond);
3108 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3109 mg = mg_find(sv, PERL_MAGIC_mutex);
3111 /* someone else beat us to initialising it */
3112 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3113 MUTEX_DESTROY(&cp->mutex);
3114 COND_DESTROY(&cp->owner_cond);
3115 COND_DESTROY(&cp->cond);
3119 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3121 mg->mg_ptr = (char *)cp;
3122 mg->mg_len = sizeof(cp);
3123 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3124 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3125 "%p: condpair_magic %p\n", thr, sv)));
3132 Perl_sv_lock(pTHX_ SV *osv)
3142 mg = condpair_magic(sv);
3143 MUTEX_LOCK(MgMUTEXP(mg));
3144 if (MgOWNER(mg) == thr)
3145 MUTEX_UNLOCK(MgMUTEXP(mg));
3148 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3150 DEBUG_S(PerlIO_printf(Perl_debug_log,
3151 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3152 PTR2UV(thr), PTR2UV(sv)));
3153 MUTEX_UNLOCK(MgMUTEXP(mg));
3154 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3156 UNLOCK_SV_LOCK_MUTEX;
3161 * Make a new perl thread structure using t as a prototype. Some of the
3162 * fields for the new thread are copied from the prototype thread, t,
3163 * so t should not be running in perl at the time this function is
3164 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3165 * thread calling new_struct_thread) clearly satisfies this constraint.
3167 struct perl_thread *
3168 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3170 #if !defined(PERL_IMPLICIT_CONTEXT)
3171 struct perl_thread *thr;
3177 sv = newSVpvn("", 0);
3178 SvGROW(sv, sizeof(struct perl_thread) + 1);
3179 SvCUR_set(sv, sizeof(struct perl_thread));
3180 thr = (Thread) SvPVX(sv);
3182 Poison(thr, 1, struct perl_thread);
3189 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3190 PL_efloatbuf = (char*)NULL;
3193 Zero(thr, 1, struct perl_thread);
3199 PL_curcop = &PL_compiling;
3200 thr->interp = t->interp;
3201 thr->cvcache = newHV();
3202 thr->threadsv = newAV();
3203 thr->specific = newAV();
3204 thr->errsv = newSVpvn("", 0);
3205 thr->flags = THRf_R_JOINABLE;
3207 MUTEX_INIT(&thr->mutex);
3211 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3214 PL_statname = NEWSV(66,0);
3215 PL_errors = newSVpvn("", 0);
3217 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3218 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3219 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3220 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3221 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3223 PL_reginterp_cnt = 0;
3224 PL_lastscream = Nullsv;
3227 PL_reg_start_tmp = 0;
3228 PL_reg_start_tmpl = 0;
3229 PL_reg_poscache = Nullch;
3231 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3233 /* parent thread's data needs to be locked while we make copy */
3234 MUTEX_LOCK(&t->mutex);
3236 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3237 PL_protect = t->Tprotect;
3240 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3241 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3242 PL_curstash = t->Tcurstash; /* always be set to main? */
3244 PL_tainted = t->Ttainted;
3245 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3246 PL_rs = newSVsv(t->Trs);
3247 PL_last_in_gv = Nullgv;
3248 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3249 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3250 PL_chopset = t->Tchopset;
3251 PL_bodytarget = newSVsv(t->Tbodytarget);
3252 PL_toptarget = newSVsv(t->Ttoptarget);
3253 if (t->Tformtarget == t->Ttoptarget)
3254 PL_formtarget = PL_toptarget;
3256 PL_formtarget = PL_bodytarget;
3257 PL_watchaddr = 0; /* XXX */
3258 PL_watchok = 0; /* XXX */
3262 /* Initialise all per-thread SVs that the template thread used */
3263 svp = AvARRAY(t->threadsv);
3264 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3265 if (*svp && *svp != &PL_sv_undef) {
3266 SV *sv = newSVsv(*svp);
3267 av_store(thr->threadsv, i, sv);
3268 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3269 DEBUG_S(PerlIO_printf(Perl_debug_log,
3270 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3274 thr->threadsvp = AvARRAY(thr->threadsv);
3276 MUTEX_LOCK(&PL_threads_mutex);
3278 thr->tid = ++PL_threadnum;
3279 thr->next = t->next;
3282 thr->next->prev = thr;
3283 MUTEX_UNLOCK(&PL_threads_mutex);
3285 /* done copying parent's state */
3286 MUTEX_UNLOCK(&t->mutex);
3288 #ifdef HAVE_THREAD_INTERN
3289 Perl_init_thread_intern(thr);
3290 #endif /* HAVE_THREAD_INTERN */
3293 #endif /* USE_5005THREADS */
3295 #ifdef PERL_GLOBAL_STRUCT
3304 Perl_get_op_names(pTHX)
3310 Perl_get_op_descs(pTHX)
3316 Perl_get_no_modify(pTHX)
3318 return PL_no_modify;
3322 Perl_get_opargs(pTHX)
3328 Perl_get_ppaddr(pTHX)
3330 return (PPADDR_t*)PL_ppaddr;
3333 #ifndef HAS_GETENV_LEN
3335 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3337 char *env_trans = PerlEnv_getenv(env_elem);
3339 *len = strlen(env_trans);
3346 Perl_get_vtbl(pTHX_ int vtbl_id)
3348 MGVTBL* result = Null(MGVTBL*);
3352 result = &PL_vtbl_sv;
3355 result = &PL_vtbl_env;
3357 case want_vtbl_envelem:
3358 result = &PL_vtbl_envelem;
3361 result = &PL_vtbl_sig;
3363 case want_vtbl_sigelem:
3364 result = &PL_vtbl_sigelem;
3366 case want_vtbl_pack:
3367 result = &PL_vtbl_pack;
3369 case want_vtbl_packelem:
3370 result = &PL_vtbl_packelem;
3372 case want_vtbl_dbline:
3373 result = &PL_vtbl_dbline;
3376 result = &PL_vtbl_isa;
3378 case want_vtbl_isaelem:
3379 result = &PL_vtbl_isaelem;
3381 case want_vtbl_arylen:
3382 result = &PL_vtbl_arylen;
3384 case want_vtbl_glob:
3385 result = &PL_vtbl_glob;
3387 case want_vtbl_mglob:
3388 result = &PL_vtbl_mglob;
3390 case want_vtbl_nkeys:
3391 result = &PL_vtbl_nkeys;
3393 case want_vtbl_taint:
3394 result = &PL_vtbl_taint;
3396 case want_vtbl_substr:
3397 result = &PL_vtbl_substr;
3400 result = &PL_vtbl_vec;
3403 result = &PL_vtbl_pos;
3406 result = &PL_vtbl_bm;
3409 result = &PL_vtbl_fm;
3411 case want_vtbl_uvar:
3412 result = &PL_vtbl_uvar;
3414 #ifdef USE_5005THREADS
3415 case want_vtbl_mutex:
3416 result = &PL_vtbl_mutex;
3419 case want_vtbl_defelem:
3420 result = &PL_vtbl_defelem;
3422 case want_vtbl_regexp:
3423 result = &PL_vtbl_regexp;
3425 case want_vtbl_regdata:
3426 result = &PL_vtbl_regdata;
3428 case want_vtbl_regdatum:
3429 result = &PL_vtbl_regdatum;
3431 #ifdef USE_LOCALE_COLLATE
3432 case want_vtbl_collxfrm:
3433 result = &PL_vtbl_collxfrm;
3436 case want_vtbl_amagic:
3437 result = &PL_vtbl_amagic;
3439 case want_vtbl_amagicelem:
3440 result = &PL_vtbl_amagicelem;
3442 case want_vtbl_backref:
3443 result = &PL_vtbl_backref;
3445 case want_vtbl_utf8:
3446 result = &PL_vtbl_utf8;
3453 Perl_my_fflush_all(pTHX)
3455 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3456 return PerlIO_flush(NULL);
3458 # if defined(HAS__FWALK)
3459 extern int fflush(FILE *);
3460 /* undocumented, unprototyped, but very useful BSDism */
3461 extern void _fwalk(int (*)(FILE *));
3465 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3467 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3468 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3470 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3471 open_max = sysconf(_SC_OPEN_MAX);
3474 open_max = FOPEN_MAX;
3477 open_max = OPEN_MAX;
3488 for (i = 0; i < open_max; i++)
3489 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3490 STDIO_STREAM_ARRAY[i]._file < open_max &&
3491 STDIO_STREAM_ARRAY[i]._flag)
3492 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3496 SETERRNO(EBADF,RMS_IFI);
3503 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3506 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3507 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3509 const char *pars = OP_IS_FILETEST(op) ? "" : "()";
3510 const char *type = OP_IS_SOCKET(op)
3511 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3512 ? "socket" : "filehandle";
3513 const char *name = NULL;
3515 if (gv && isGV(gv)) {
3519 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3520 if (ckWARN(WARN_IO)) {
3521 const char *direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3523 Perl_warner(aTHX_ packWARN(WARN_IO),
3524 "Filehandle %s opened only for %sput",
3527 Perl_warner(aTHX_ packWARN(WARN_IO),
3528 "Filehandle opened only for %sput", direction);
3535 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3537 warn_type = WARN_CLOSED;
3541 warn_type = WARN_UNOPENED;
3544 if (ckWARN(warn_type)) {
3545 if (name && *name) {
3546 Perl_warner(aTHX_ packWARN(warn_type),
3547 "%s%s on %s %s %s", func, pars, vile, type, name);
3548 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3550 aTHX_ packWARN(warn_type),
3551 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3556 Perl_warner(aTHX_ packWARN(warn_type),
3557 "%s%s on %s %s", func, pars, vile, type);
3558 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3560 aTHX_ packWARN(warn_type),
3561 "\t(Are you trying to call %s%s on dirhandle?)\n",
3570 /* in ASCII order, not that it matters */
3571 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3574 Perl_ebcdic_control(pTHX_ int ch)
3582 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3583 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3586 if (ctlp == controllablechars)
3587 return('\177'); /* DEL */
3589 return((unsigned char)(ctlp - controllablechars - 1));
3590 } else { /* Want uncontrol */
3591 if (ch == '\177' || ch == -1)
3593 else if (ch == '\157')
3595 else if (ch == '\174')
3597 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3599 else if (ch == '\155')
3601 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3602 return(controllablechars[ch+1]);
3604 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3609 /* To workaround core dumps from the uninitialised tm_zone we get the
3610 * system to give us a reasonable struct to copy. This fix means that
3611 * strftime uses the tm_zone and tm_gmtoff values returned by
3612 * localtime(time()). That should give the desired result most of the
3613 * time. But probably not always!
3615 * This does not address tzname aspects of NETaa14816.
3620 # ifndef STRUCT_TM_HASZONE
3621 # define STRUCT_TM_HASZONE
3625 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3626 # ifndef HAS_TM_TM_ZONE
3627 # define HAS_TM_TM_ZONE
3632 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3634 #ifdef HAS_TM_TM_ZONE
3638 my_tm = localtime(&now);
3640 Copy(my_tm, ptm, 1, struct tm);
3645 * mini_mktime - normalise struct tm values without the localtime()
3646 * semantics (and overhead) of mktime().
3649 Perl_mini_mktime(pTHX_ struct tm *ptm)
3653 int month, mday, year, jday;
3654 int odd_cent, odd_year;
3656 #define DAYS_PER_YEAR 365
3657 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3658 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3659 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3660 #define SECS_PER_HOUR (60*60)
3661 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3662 /* parentheses deliberately absent on these two, otherwise they don't work */
3663 #define MONTH_TO_DAYS 153/5
3664 #define DAYS_TO_MONTH 5/153
3665 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3666 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3667 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3668 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3671 * Year/day algorithm notes:
3673 * With a suitable offset for numeric value of the month, one can find
3674 * an offset into the year by considering months to have 30.6 (153/5) days,
3675 * using integer arithmetic (i.e., with truncation). To avoid too much
3676 * messing about with leap days, we consider January and February to be
3677 * the 13th and 14th month of the previous year. After that transformation,
3678 * we need the month index we use to be high by 1 from 'normal human' usage,
3679 * so the month index values we use run from 4 through 15.
3681 * Given that, and the rules for the Gregorian calendar (leap years are those
3682 * divisible by 4 unless also divisible by 100, when they must be divisible
3683 * by 400 instead), we can simply calculate the number of days since some
3684 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3685 * the days we derive from our month index, and adding in the day of the
3686 * month. The value used here is not adjusted for the actual origin which
3687 * it normally would use (1 January A.D. 1), since we're not exposing it.
3688 * We're only building the value so we can turn around and get the
3689 * normalised values for the year, month, day-of-month, and day-of-year.
3691 * For going backward, we need to bias the value we're using so that we find
3692 * the right year value. (Basically, we don't want the contribution of
3693 * March 1st to the number to apply while deriving the year). Having done
3694 * that, we 'count up' the contribution to the year number by accounting for
3695 * full quadracenturies (400-year periods) with their extra leap days, plus
3696 * the contribution from full centuries (to avoid counting in the lost leap
3697 * days), plus the contribution from full quad-years (to count in the normal
3698 * leap days), plus the leftover contribution from any non-leap years.
3699 * At this point, if we were working with an actual leap day, we'll have 0
3700 * days left over. This is also true for March 1st, however. So, we have
3701 * to special-case that result, and (earlier) keep track of the 'odd'
3702 * century and year contributions. If we got 4 extra centuries in a qcent,
3703 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3704 * Otherwise, we add back in the earlier bias we removed (the 123 from
3705 * figuring in March 1st), find the month index (integer division by 30.6),
3706 * and the remainder is the day-of-month. We then have to convert back to
3707 * 'real' months (including fixing January and February from being 14/15 in
3708 * the previous year to being in the proper year). After that, to get
3709 * tm_yday, we work with the normalised year and get a new yearday value for
3710 * January 1st, which we subtract from the yearday value we had earlier,
3711 * representing the date we've re-built. This is done from January 1
3712 * because tm_yday is 0-origin.
3714 * Since POSIX time routines are only guaranteed to work for times since the
3715 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3716 * applies Gregorian calendar rules even to dates before the 16th century
3717 * doesn't bother me. Besides, you'd need cultural context for a given
3718 * date to know whether it was Julian or Gregorian calendar, and that's
3719 * outside the scope for this routine. Since we convert back based on the
3720 * same rules we used to build the yearday, you'll only get strange results
3721 * for input which needed normalising, or for the 'odd' century years which
3722 * were leap years in the Julian calander but not in the Gregorian one.
3723 * I can live with that.
3725 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3726 * that's still outside the scope for POSIX time manipulation, so I don't
3730 year = 1900 + ptm->tm_year;
3731 month = ptm->tm_mon;
3732 mday = ptm->tm_mday;
3733 /* allow given yday with no month & mday to dominate the result */
3734 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3737 jday = 1 + ptm->tm_yday;
3746 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3747 yearday += month*MONTH_TO_DAYS + mday + jday;
3749 * Note that we don't know when leap-seconds were or will be,
3750 * so we have to trust the user if we get something which looks
3751 * like a sensible leap-second. Wild values for seconds will
3752 * be rationalised, however.
3754 if ((unsigned) ptm->tm_sec <= 60) {
3761 secs += 60 * ptm->tm_min;
3762 secs += SECS_PER_HOUR * ptm->tm_hour;
3764 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3765 /* got negative remainder, but need positive time */
3766 /* back off an extra day to compensate */
3767 yearday += (secs/SECS_PER_DAY)-1;
3768 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3771 yearday += (secs/SECS_PER_DAY);
3772 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3775 else if (secs >= SECS_PER_DAY) {
3776 yearday += (secs/SECS_PER_DAY);
3777 secs %= SECS_PER_DAY;
3779 ptm->tm_hour = secs/SECS_PER_HOUR;
3780 secs %= SECS_PER_HOUR;
3781 ptm->tm_min = secs/60;
3783 ptm->tm_sec += secs;
3784 /* done with time of day effects */
3786 * The algorithm for yearday has (so far) left it high by 428.
3787 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3788 * bias it by 123 while trying to figure out what year it
3789 * really represents. Even with this tweak, the reverse
3790 * translation fails for years before A.D. 0001.
3791 * It would still fail for Feb 29, but we catch that one below.
3793 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3794 yearday -= YEAR_ADJUST;
3795 year = (yearday / DAYS_PER_QCENT) * 400;
3796 yearday %= DAYS_PER_QCENT;
3797 odd_cent = yearday / DAYS_PER_CENT;
3798 year += odd_cent * 100;
3799 yearday %= DAYS_PER_CENT;
3800 year += (yearday / DAYS_PER_QYEAR) * 4;
3801 yearday %= DAYS_PER_QYEAR;
3802 odd_year = yearday / DAYS_PER_YEAR;
3804 yearday %= DAYS_PER_YEAR;
3805 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3810 yearday += YEAR_ADJUST; /* recover March 1st crock */
3811 month = yearday*DAYS_TO_MONTH;
3812 yearday -= month*MONTH_TO_DAYS;
3813 /* recover other leap-year adjustment */
3822 ptm->tm_year = year - 1900;
3824 ptm->tm_mday = yearday;
3825 ptm->tm_mon = month;
3829 ptm->tm_mon = month - 1;
3831 /* re-build yearday based on Jan 1 to get tm_yday */
3833 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3834 yearday += 14*MONTH_TO_DAYS + 1;
3835 ptm->tm_yday = jday - yearday;
3836 /* fix tm_wday if not overridden by caller */
3837 if ((unsigned)ptm->tm_wday > 6)
3838 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3842 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3850 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3853 mytm.tm_hour = hour;
3854 mytm.tm_mday = mday;
3856 mytm.tm_year = year;
3857 mytm.tm_wday = wday;
3858 mytm.tm_yday = yday;
3859 mytm.tm_isdst = isdst;
3861 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3862 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3867 #ifdef HAS_TM_TM_GMTOFF
3868 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3870 #ifdef HAS_TM_TM_ZONE
3871 mytm.tm_zone = mytm2.tm_zone;
3876 New(0, buf, buflen, char);
3877 len = strftime(buf, buflen, fmt, &mytm);
3879 ** The following is needed to handle to the situation where
3880 ** tmpbuf overflows. Basically we want to allocate a buffer
3881 ** and try repeatedly. The reason why it is so complicated
3882 ** is that getting a return value of 0 from strftime can indicate
3883 ** one of the following:
3884 ** 1. buffer overflowed,
3885 ** 2. illegal conversion specifier, or
3886 ** 3. the format string specifies nothing to be returned(not
3887 ** an error). This could be because format is an empty string
3888 ** or it specifies %p that yields an empty string in some locale.
3889 ** If there is a better way to make it portable, go ahead by
3892 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3895 /* Possibly buf overflowed - try again with a bigger buf */
3896 const int fmtlen = strlen(fmt);
3897 const int bufsize = fmtlen + buflen;
3899 New(0, buf, bufsize, char);
3901 buflen = strftime(buf, bufsize, fmt, &mytm);
3902 if (buflen > 0 && buflen < bufsize)
3904 /* heuristic to prevent out-of-memory errors */
3905 if (bufsize > 100*fmtlen) {
3910 Renew(buf, bufsize*2, char);
3915 Perl_croak(aTHX_ "panic: no strftime");
3920 #define SV_CWD_RETURN_UNDEF \
3921 sv_setsv(sv, &PL_sv_undef); \
3924 #define SV_CWD_ISDOT(dp) \
3925 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3926 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3929 =head1 Miscellaneous Functions
3931 =for apidoc getcwd_sv
3933 Fill the sv with current working directory
3938 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3939 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3940 * getcwd(3) if available
3941 * Comments from the orignal:
3942 * This is a faster version of getcwd. It's also more dangerous
3943 * because you might chdir out of a directory that you can't chdir
3947 Perl_getcwd_sv(pTHX_ register SV *sv)
3951 #ifndef INCOMPLETE_TAINTS
3957 char buf[MAXPATHLEN];
3959 /* Some getcwd()s automatically allocate a buffer of the given
3960 * size from the heap if they are given a NULL buffer pointer.
3961 * The problem is that this behaviour is not portable. */
3962 if (getcwd(buf, sizeof(buf) - 1)) {
3963 STRLEN len = strlen(buf);
3964 sv_setpvn(sv, buf, len);
3968 sv_setsv(sv, &PL_sv_undef);
3976 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3977 int namelen, pathlen=0;
3981 (void)SvUPGRADE(sv, SVt_PV);
3983 if (PerlLIO_lstat(".", &statbuf) < 0) {
3984 SV_CWD_RETURN_UNDEF;
3987 orig_cdev = statbuf.st_dev;
3988 orig_cino = statbuf.st_ino;
3996 if (PerlDir_chdir("..") < 0) {
3997 SV_CWD_RETURN_UNDEF;
3999 if (PerlLIO_stat(".", &statbuf) < 0) {
4000 SV_CWD_RETURN_UNDEF;
4003 cdev = statbuf.st_dev;
4004 cino = statbuf.st_ino;
4006 if (odev == cdev && oino == cino) {
4009 if (!(dir = PerlDir_open("."))) {
4010 SV_CWD_RETURN_UNDEF;
4013 while ((dp = PerlDir_read(dir)) != NULL) {
4015 namelen = dp->d_namlen;
4017 namelen = strlen(dp->d_name);
4020 if (SV_CWD_ISDOT(dp)) {
4024 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4025 SV_CWD_RETURN_UNDEF;
4028 tdev = statbuf.st_dev;
4029 tino = statbuf.st_ino;
4030 if (tino == oino && tdev == odev) {
4036 SV_CWD_RETURN_UNDEF;
4039 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4040 SV_CWD_RETURN_UNDEF;
4043 SvGROW(sv, pathlen + namelen + 1);
4047 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4050 /* prepend current directory to the front */
4052 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4053 pathlen += (namelen + 1);
4055 #ifdef VOID_CLOSEDIR
4058 if (PerlDir_close(dir) < 0) {
4059 SV_CWD_RETURN_UNDEF;
4065 SvCUR_set(sv, pathlen);
4069 if (PerlDir_chdir(SvPVX(sv)) < 0) {
4070 SV_CWD_RETURN_UNDEF;
4073 if (PerlLIO_stat(".", &statbuf) < 0) {
4074 SV_CWD_RETURN_UNDEF;
4077 cdev = statbuf.st_dev;
4078 cino = statbuf.st_ino;
4080 if (cdev != orig_cdev || cino != orig_cino) {
4081 Perl_croak(aTHX_ "Unstable directory path, "
4082 "current directory changed unexpectedly");
4093 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4094 # define EMULATE_SOCKETPAIR_UDP
4097 #ifdef EMULATE_SOCKETPAIR_UDP
4099 S_socketpair_udp (int fd[2]) {
4101 /* Fake a datagram socketpair using UDP to localhost. */
4102 int sockets[2] = {-1, -1};
4103 struct sockaddr_in addresses[2];
4105 Sock_size_t size = sizeof(struct sockaddr_in);
4106 unsigned short port;
4109 memset(&addresses, 0, sizeof(addresses));
4112 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4113 if (sockets[i] == -1)
4114 goto tidy_up_and_fail;
4116 addresses[i].sin_family = AF_INET;
4117 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4118 addresses[i].sin_port = 0; /* kernel choses port. */
4119 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4120 sizeof(struct sockaddr_in)) == -1)
4121 goto tidy_up_and_fail;
4124 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4125 for each connect the other socket to it. */
4128 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4130 goto tidy_up_and_fail;
4131 if (size != sizeof(struct sockaddr_in))
4132 goto abort_tidy_up_and_fail;
4133 /* !1 is 0, !0 is 1 */
4134 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4135 sizeof(struct sockaddr_in)) == -1)
4136 goto tidy_up_and_fail;
4139 /* Now we have 2 sockets connected to each other. I don't trust some other
4140 process not to have already sent a packet to us (by random) so send
4141 a packet from each to the other. */
4144 /* I'm going to send my own port number. As a short.
4145 (Who knows if someone somewhere has sin_port as a bitfield and needs
4146 this routine. (I'm assuming crays have socketpair)) */
4147 port = addresses[i].sin_port;
4148 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4149 if (got != sizeof(port)) {
4151 goto tidy_up_and_fail;
4152 goto abort_tidy_up_and_fail;
4156 /* Packets sent. I don't trust them to have arrived though.
4157 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4158 connect to localhost will use a second kernel thread. In 2.6 the
4159 first thread running the connect() returns before the second completes,
4160 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4161 returns 0. Poor programs have tripped up. One poor program's authors'
4162 had a 50-1 reverse stock split. Not sure how connected these were.)
4163 So I don't trust someone not to have an unpredictable UDP stack.
4167 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4168 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4172 FD_SET(sockets[0], &rset);
4173 FD_SET(sockets[1], &rset);
4175 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4176 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4177 || !FD_ISSET(sockets[1], &rset)) {
4178 /* I hope this is portable and appropriate. */
4180 goto tidy_up_and_fail;
4181 goto abort_tidy_up_and_fail;
4185 /* And the paranoia department even now doesn't trust it to have arrive
4186 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4188 struct sockaddr_in readfrom;
4189 unsigned short buffer[2];
4194 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4195 sizeof(buffer), MSG_DONTWAIT,
4196 (struct sockaddr *) &readfrom, &size);
4198 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4200 (struct sockaddr *) &readfrom, &size);
4204 goto tidy_up_and_fail;
4205 if (got != sizeof(port)
4206 || size != sizeof(struct sockaddr_in)
4207 /* Check other socket sent us its port. */
4208 || buffer[0] != (unsigned short) addresses[!i].sin_port
4209 /* Check kernel says we got the datagram from that socket */
4210 || readfrom.sin_family != addresses[!i].sin_family
4211 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4212 || readfrom.sin_port != addresses[!i].sin_port)
4213 goto abort_tidy_up_and_fail;
4216 /* My caller (my_socketpair) has validated that this is non-NULL */
4219 /* I hereby declare this connection open. May God bless all who cross
4223 abort_tidy_up_and_fail:
4224 errno = ECONNABORTED;
4227 int save_errno = errno;
4228 if (sockets[0] != -1)
4229 PerlLIO_close(sockets[0]);
4230 if (sockets[1] != -1)
4231 PerlLIO_close(sockets[1]);
4236 #endif /* EMULATE_SOCKETPAIR_UDP */
4238 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4240 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4241 /* Stevens says that family must be AF_LOCAL, protocol 0.
4242 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4247 struct sockaddr_in listen_addr;
4248 struct sockaddr_in connect_addr;
4253 || family != AF_UNIX
4256 errno = EAFNOSUPPORT;
4264 #ifdef EMULATE_SOCKETPAIR_UDP
4265 if (type == SOCK_DGRAM)
4266 return S_socketpair_udp(fd);
4269 listener = PerlSock_socket(AF_INET, type, 0);
4272 memset(&listen_addr, 0, sizeof(listen_addr));
4273 listen_addr.sin_family = AF_INET;
4274 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4275 listen_addr.sin_port = 0; /* kernel choses port. */
4276 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4277 sizeof(listen_addr)) == -1)
4278 goto tidy_up_and_fail;
4279 if (PerlSock_listen(listener, 1) == -1)
4280 goto tidy_up_and_fail;
4282 connector = PerlSock_socket(AF_INET, type, 0);
4283 if (connector == -1)
4284 goto tidy_up_and_fail;
4285 /* We want to find out the port number to connect to. */
4286 size = sizeof(connect_addr);
4287 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4289 goto tidy_up_and_fail;
4290 if (size != sizeof(connect_addr))
4291 goto abort_tidy_up_and_fail;
4292 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4293 sizeof(connect_addr)) == -1)
4294 goto tidy_up_and_fail;
4296 size = sizeof(listen_addr);
4297 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4300 goto tidy_up_and_fail;
4301 if (size != sizeof(listen_addr))
4302 goto abort_tidy_up_and_fail;
4303 PerlLIO_close(listener);
4304 /* Now check we are talking to ourself by matching port and host on the
4306 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4308 goto tidy_up_and_fail;
4309 if (size != sizeof(connect_addr)
4310 || listen_addr.sin_family != connect_addr.sin_family
4311 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4312 || listen_addr.sin_port != connect_addr.sin_port) {
4313 goto abort_tidy_up_and_fail;
4319 abort_tidy_up_and_fail:
4320 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4323 int save_errno = errno;
4325 PerlLIO_close(listener);
4326 if (connector != -1)
4327 PerlLIO_close(connector);
4329 PerlLIO_close(acceptor);
4335 /* In any case have a stub so that there's code corresponding
4336 * to the my_socketpair in global.sym. */
4338 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4339 #ifdef HAS_SOCKETPAIR
4340 return socketpair(family, type, protocol, fd);
4349 =for apidoc sv_nosharing
4351 Dummy routine which "shares" an SV when there is no sharing module present.
4352 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4353 some level of strict-ness.
4359 Perl_sv_nosharing(pTHX_ SV *sv)
4365 =for apidoc sv_nolocking
4367 Dummy routine which "locks" an SV when there is no locking module present.
4368 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4369 some level of strict-ness.
4375 Perl_sv_nolocking(pTHX_ SV *sv)
4382 =for apidoc sv_nounlocking
4384 Dummy routine which "unlocks" an SV when there is no locking module present.
4385 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4386 some level of strict-ness.
4392 Perl_sv_nounlocking(pTHX_ SV *sv)
4398 Perl_parse_unicode_opts(pTHX_ char **popt)
4400 const char *p = *popt;
4405 opt = (U32) atoi(p);
4406 while (isDIGIT(*p)) p++;
4407 if (*p && *p != '\n' && *p != '\r')
4408 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4413 case PERL_UNICODE_STDIN:
4414 opt |= PERL_UNICODE_STDIN_FLAG; break;
4415 case PERL_UNICODE_STDOUT:
4416 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4417 case PERL_UNICODE_STDERR:
4418 opt |= PERL_UNICODE_STDERR_FLAG; break;
4419 case PERL_UNICODE_STD:
4420 opt |= PERL_UNICODE_STD_FLAG; break;
4421 case PERL_UNICODE_IN:
4422 opt |= PERL_UNICODE_IN_FLAG; break;
4423 case PERL_UNICODE_OUT:
4424 opt |= PERL_UNICODE_OUT_FLAG; break;
4425 case PERL_UNICODE_INOUT:
4426 opt |= PERL_UNICODE_INOUT_FLAG; break;
4427 case PERL_UNICODE_LOCALE:
4428 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4429 case PERL_UNICODE_ARGV:
4430 opt |= PERL_UNICODE_ARGV_FLAG; break;
4432 if (*p != '\n' && *p != '\r')
4434 "Unknown Unicode option letter '%c'", *p);
4440 opt = PERL_UNICODE_DEFAULT_FLAGS;
4442 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4443 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4444 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4455 * This is really just a quick hack which grabs various garbage
4456 * values. It really should be a real hash algorithm which
4457 * spreads the effect of every input bit onto every output bit,
4458 * if someone who knows about such things would bother to write it.
4459 * Might be a good idea to add that function to CORE as well.
4460 * No numbers below come from careful analysis or anything here,
4461 * except they are primes and SEED_C1 > 1E6 to get a full-width
4462 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4463 * probably be bigger too.
4466 # define SEED_C1 1000003
4467 #define SEED_C4 73819
4469 # define SEED_C1 25747
4470 #define SEED_C4 20639
4474 #define SEED_C5 26107
4476 #ifndef PERL_NO_DEV_RANDOM
4481 # include <starlet.h>
4482 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4483 * in 100-ns units, typically incremented ever 10 ms. */
4484 unsigned int when[2];
4486 # ifdef HAS_GETTIMEOFDAY
4487 struct timeval when;
4493 /* This test is an escape hatch, this symbol isn't set by Configure. */
4494 #ifndef PERL_NO_DEV_RANDOM
4495 #ifndef PERL_RANDOM_DEVICE
4496 /* /dev/random isn't used by default because reads from it will block
4497 * if there isn't enough entropy available. You can compile with
4498 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4499 * is enough real entropy to fill the seed. */
4500 # define PERL_RANDOM_DEVICE "/dev/urandom"
4502 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4504 if (PerlLIO_read(fd, &u, sizeof u) != sizeof u)
4513 _ckvmssts(sys$gettim(when));
4514 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4516 # ifdef HAS_GETTIMEOFDAY
4517 PerlProc_gettimeofday(&when,NULL);
4518 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4521 u = (U32)SEED_C1 * when;
4524 u += SEED_C3 * (U32)PerlProc_getpid();
4525 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4526 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4527 u += SEED_C5 * (U32)PTR2UV(&when);
4533 Perl_get_hash_seed(pTHX)
4535 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4539 while (isSPACE(*s)) s++;
4540 if (s && isDIGIT(*s))
4541 myseed = (UV)Atoul(s);
4543 #ifdef USE_HASH_SEED_EXPLICIT
4547 /* Compute a random seed */
4548 (void)seedDrand01((Rand_seed_t)seed());
4549 myseed = (UV)(Drand01() * (NV)UV_MAX);
4550 #if RANDBITS < (UVSIZE * 8)
4551 /* Since there are not enough randbits to to reach all
4552 * the bits of a UV, the low bits might need extra
4553 * help. Sum in another random number that will
4554 * fill in the low bits. */
4556 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4557 #endif /* RANDBITS < (UVSIZE * 8) */
4558 if (myseed == 0) { /* Superparanoia. */
4559 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4561 Perl_croak(aTHX_ "Your random numbers are not that random");
4564 PL_rehash_seed_set = TRUE;