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++));
158 /* safe version of system's calloc() */
161 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
167 if (size * count > 0xffff) {
168 PerlIO_printf(Perl_error_log,
169 "Allocation too large: %lx\n", size * count) FLUSH;
172 #endif /* HAS_64K_LIMIT */
174 if ((long)size < 0 || (long)count < 0)
175 Perl_croak_nocontext("panic: calloc");
178 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
179 PERL_ALLOC_CHECK(ptr);
180 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));
182 memset((void*)ptr, 0, size);
188 /* Can't use PerlIO to write as it allocates memory */
189 PerlLIO_write(PerlIO_fileno(Perl_error_log),
190 PL_no_mem, strlen(PL_no_mem));
197 /* These must be defined when not using Perl's malloc for binary
202 Malloc_t Perl_malloc (MEM_SIZE nbytes)
205 return (Malloc_t)PerlMem_malloc(nbytes);
208 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
211 return (Malloc_t)PerlMem_calloc(elements, size);
214 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
217 return (Malloc_t)PerlMem_realloc(where, nbytes);
220 Free_t Perl_mfree (Malloc_t where)
228 /* copy a string up to some (non-backslashed) delimiter, if any */
231 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
234 for (tolen = 0; from < fromend; from++, tolen++) {
236 if (from[1] == delim)
245 else if (*from == delim)
256 /* return ptr to little string in big string, NULL if not found */
257 /* This routine was donated by Corey Satten. */
260 Perl_instr(pTHX_ register const char *big, register const char *little)
270 register const char *s, *x;
273 for (x=big,s=little; *s; /**/ ) {
282 return (char*)(big-1);
287 /* same as instr but allow embedded nulls */
290 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
292 register const I32 first = *little;
293 register const char *littleend = lend;
295 if (!first && little >= littleend)
297 if (bigend - big < littleend - little)
299 bigend -= littleend - little++;
300 while (big <= bigend) {
301 register const char *s, *x;
304 for (x=big,s=little; s < littleend; /**/ ) {
311 return (char*)(big-1);
316 /* reverse of the above--find last substring */
319 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
321 register const char *bigbeg;
322 register const I32 first = *little;
323 register const char *littleend = lend;
325 if (!first && little >= littleend)
326 return (char*)bigend;
328 big = bigend - (littleend - little++);
329 while (big >= bigbeg) {
330 register const char *s, *x;
333 for (x=big+2,s=little; s < littleend; /**/ ) {
340 return (char*)(big+1);
345 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
347 /* As a space optimization, we do not compile tables for strings of length
348 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
349 special-cased in fbm_instr().
351 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
354 =head1 Miscellaneous Functions
356 =for apidoc fbm_compile
358 Analyses the string in order to make fast searches on it using fbm_instr()
359 -- the Boyer-Moore algorithm.
365 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
367 const register U8 *s;
373 if (flags & FBMcf_TAIL) {
374 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
375 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
376 if (mg && mg->mg_len >= 0)
379 s = (U8*)SvPV_force_mutable(sv, len);
380 (void)SvUPGRADE(sv, SVt_PVBM);
381 if (len == 0) /* TAIL might be on a zero-length string. */
384 const unsigned char *sb;
385 const U8 mlen = (len>255) ? 255 : (U8)len;
388 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
389 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
390 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
391 memset((void*)table, mlen, 256);
392 table[-1] = (U8)flags;
394 sb = s - mlen + 1; /* first char (maybe) */
396 if (table[*s] == mlen)
401 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
404 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
405 for (i = 0; i < len; i++) {
406 if (PL_freq[s[i]] < frequency) {
408 frequency = PL_freq[s[i]];
411 BmRARE(sv) = s[rarest];
412 BmPREVIOUS(sv) = (U16)rarest;
413 BmUSEFUL(sv) = 100; /* Initial value */
414 if (flags & FBMcf_TAIL)
416 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
417 BmRARE(sv),BmPREVIOUS(sv)));
420 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
421 /* If SvTAIL is actually due to \Z or \z, this gives false positives
425 =for apidoc fbm_instr
427 Returns the location of the SV in the string delimited by C<str> and
428 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
429 does not have to be fbm_compiled, but the search will not be as fast
436 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
438 register unsigned char *s;
440 register const unsigned char *little
441 = (const unsigned char *)SvPV_const(littlestr,l);
442 register STRLEN littlelen = l;
443 register const I32 multiline = flags & FBMrf_MULTILINE;
445 if ((STRLEN)(bigend - big) < littlelen) {
446 if ( SvTAIL(littlestr)
447 && ((STRLEN)(bigend - big) == littlelen - 1)
449 || (*big == *little &&
450 memEQ((char *)big, (char *)little, littlelen - 1))))
455 if (littlelen <= 2) { /* Special-cased */
457 if (littlelen == 1) {
458 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
459 /* Know that bigend != big. */
460 if (bigend[-1] == '\n')
461 return (char *)(bigend - 1);
462 return (char *) bigend;
470 if (SvTAIL(littlestr))
471 return (char *) bigend;
475 return (char*)big; /* Cannot be SvTAIL! */
478 if (SvTAIL(littlestr) && !multiline) {
479 if (bigend[-1] == '\n' && bigend[-2] == *little)
480 return (char*)bigend - 2;
481 if (bigend[-1] == *little)
482 return (char*)bigend - 1;
486 /* This should be better than FBM if c1 == c2, and almost
487 as good otherwise: maybe better since we do less indirection.
488 And we save a lot of memory by caching no table. */
489 const unsigned char c1 = little[0];
490 const unsigned char c2 = little[1];
495 while (s <= bigend) {
505 goto check_1char_anchor;
516 goto check_1char_anchor;
519 while (s <= bigend) {
524 goto check_1char_anchor;
533 check_1char_anchor: /* One char and anchor! */
534 if (SvTAIL(littlestr) && (*bigend == *little))
535 return (char *)bigend; /* bigend is already decremented. */
538 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
539 s = bigend - littlelen;
540 if (s >= big && bigend[-1] == '\n' && *s == *little
541 /* Automatically of length > 2 */
542 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
544 return (char*)s; /* how sweet it is */
547 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
549 return (char*)s + 1; /* how sweet it is */
553 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
554 char *b = ninstr((char*)big,(char*)bigend,
555 (char*)little, (char*)little + littlelen);
557 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
558 /* Chop \n from littlestr: */
559 s = bigend - littlelen + 1;
561 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
570 { /* Do actual FBM. */
571 register const unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
572 const register unsigned char *oldlittle;
574 if (littlelen > (STRLEN)(bigend - big))
576 --littlelen; /* Last char found by table lookup */
579 little += littlelen; /* last char */
585 if ((tmp = table[*s])) {
586 if ((s += tmp) < bigend)
590 else { /* less expensive than calling strncmp() */
591 register unsigned char * const olds = s;
596 if (*--s == *--little)
598 s = olds + 1; /* here we pay the price for failure */
600 if (s < bigend) /* fake up continue to outer loop */
608 if ( s == bigend && (table[-1] & FBMcf_TAIL)
609 && memEQ((char *)(bigend - littlelen),
610 (char *)(oldlittle - littlelen), littlelen) )
611 return (char*)bigend - littlelen;
616 /* start_shift, end_shift are positive quantities which give offsets
617 of ends of some substring of bigstr.
618 If "last" we want the last occurrence.
619 old_posp is the way of communication between consequent calls if
620 the next call needs to find the .
621 The initial *old_posp should be -1.
623 Note that we take into account SvTAIL, so one can get extra
624 optimizations if _ALL flag is set.
627 /* If SvTAIL is actually due to \Z or \z, this gives false positives
628 if PL_multiline. In fact if !PL_multiline the authoritative answer
629 is not supported yet. */
632 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
634 const register unsigned char *big;
636 register I32 previous;
638 const register unsigned char *little;
639 register I32 stop_pos;
640 const register unsigned char *littleend;
644 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
645 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
647 if ( BmRARE(littlestr) == '\n'
648 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
649 little = (const unsigned char *)(SvPVX_const(littlestr));
650 littleend = little + SvCUR(littlestr);
657 little = (const unsigned char *)(SvPVX_const(littlestr));
658 littleend = little + SvCUR(littlestr);
660 /* The value of pos we can start at: */
661 previous = BmPREVIOUS(littlestr);
662 big = (const unsigned char *)(SvPVX_const(bigstr));
663 /* The value of pos we can stop at: */
664 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
665 if (previous + start_shift > stop_pos) {
667 stop_pos does not include SvTAIL in the count, so this check is incorrect
668 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
671 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
676 while (pos < previous + start_shift) {
677 if (!(pos += PL_screamnext[pos]))
682 const register unsigned char *s, *x;
683 if (pos >= stop_pos) break;
684 if (big[pos] != first)
686 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
692 if (s == littleend) {
694 if (!last) return (char *)(big+pos);
697 } while ( pos += PL_screamnext[pos] );
699 return (char *)(big+(*old_posp));
701 if (!SvTAIL(littlestr) || (end_shift > 0))
703 /* Ignore the trailing "\n". This code is not microoptimized */
704 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
705 stop_pos = littleend - little; /* Actual littlestr len */
710 && ((stop_pos == 1) ||
711 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
717 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
719 register const U8 *a = (const U8 *)s1;
720 register const U8 *b = (const U8 *)s2;
722 if (*a != *b && *a != PL_fold[*b])
730 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
732 register const U8 *a = (const U8 *)s1;
733 register const U8 *b = (const U8 *)s2;
735 if (*a != *b && *a != PL_fold_locale[*b])
742 /* copy a string to a safe spot */
745 =head1 Memory Management
749 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
750 string which is a duplicate of C<pv>. The size of the string is
751 determined by C<strlen()>. The memory allocated for the new string can
752 be freed with the C<Safefree()> function.
758 Perl_savepv(pTHX_ const char *pv)
764 const STRLEN pvlen = strlen(pv)+1;
765 Newx(newaddr,pvlen,char);
766 return memcpy(newaddr,pv,pvlen);
771 /* same thing but with a known length */
776 Perl's version of what C<strndup()> would be if it existed. Returns a
777 pointer to a newly allocated string which is a duplicate of the first
778 C<len> bytes from C<pv>. The memory allocated for the new string can be
779 freed with the C<Safefree()> function.
785 Perl_savepvn(pTHX_ const char *pv, register I32 len)
787 register char *newaddr;
789 Newx(newaddr,len+1,char);
790 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
792 /* might not be null terminated */
794 return (char *) CopyD(pv,newaddr,len,char);
797 return (char *) ZeroD(newaddr,len+1,char);
802 =for apidoc savesharedpv
804 A version of C<savepv()> which allocates the duplicate string in memory
805 which is shared between threads.
810 Perl_savesharedpv(pTHX_ const char *pv)
812 register char *newaddr;
817 pvlen = strlen(pv)+1;
818 newaddr = (char*)PerlMemShared_malloc(pvlen);
820 PerlLIO_write(PerlIO_fileno(Perl_error_log),
821 PL_no_mem, strlen(PL_no_mem));
824 return memcpy(newaddr,pv,pvlen);
830 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
831 the passed in SV using C<SvPV()>
837 Perl_savesvpv(pTHX_ SV *sv)
840 const char *pv = SvPV_const(sv, len);
841 register char *newaddr;
844 Newx(newaddr,len,char);
845 return (char *) CopyD(pv,newaddr,len,char);
849 /* the SV for Perl_form() and mess() is not kept in an arena */
858 return sv_2mortal(newSVpvn("",0));
863 /* Create as PVMG now, to avoid any upgrading later */
865 Newxz(any, 1, XPVMG);
866 SvFLAGS(sv) = SVt_PVMG;
867 SvANY(sv) = (void*)any;
868 SvREFCNT(sv) = 1 << 30; /* practically infinite */
873 #if defined(PERL_IMPLICIT_CONTEXT)
875 Perl_form_nocontext(const char* pat, ...)
881 retval = vform(pat, &args);
885 #endif /* PERL_IMPLICIT_CONTEXT */
888 =head1 Miscellaneous Functions
891 Takes a sprintf-style format pattern and conventional
892 (non-SV) arguments and returns the formatted string.
894 (char *) Perl_form(pTHX_ const char* pat, ...)
896 can be used any place a string (char *) is required:
898 char * s = Perl_form("%d.%d",major,minor);
900 Uses a single private buffer so if you want to format several strings you
901 must explicitly copy the earlier strings away (and free the copies when you
908 Perl_form(pTHX_ const char* pat, ...)
913 retval = vform(pat, &args);
919 Perl_vform(pTHX_ const char *pat, va_list *args)
921 SV * const sv = mess_alloc();
922 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
926 #if defined(PERL_IMPLICIT_CONTEXT)
928 Perl_mess_nocontext(const char *pat, ...)
934 retval = vmess(pat, &args);
938 #endif /* PERL_IMPLICIT_CONTEXT */
941 Perl_mess(pTHX_ const char *pat, ...)
946 retval = vmess(pat, &args);
952 S_closest_cop(pTHX_ COP *cop, const OP *o)
954 /* Look for PL_op starting from o. cop is the last COP we've seen. */
956 if (!o || o == PL_op) return cop;
958 if (o->op_flags & OPf_KIDS) {
960 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
964 /* If the OP_NEXTSTATE has been optimised away we can still use it
965 * the get the file and line number. */
967 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
970 /* Keep searching, and return when we've found something. */
972 new_cop = closest_cop(cop, kid);
973 if (new_cop) return new_cop;
983 Perl_vmess(pTHX_ const char *pat, va_list *args)
985 SV *sv = mess_alloc();
986 static const char dgd[] = " during global destruction.\n";
988 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
989 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
992 * Try and find the file and line for PL_op. This will usually be
993 * PL_curcop, but it might be a cop that has been optimised away. We
994 * can try to find such a cop by searching through the optree starting
995 * from the sibling of PL_curcop.
998 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
999 if (!cop) cop = PL_curcop;
1002 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1003 OutCopFILE(cop), (IV)CopLINE(cop));
1004 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1005 const bool line_mode = (RsSIMPLE(PL_rs) &&
1006 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1007 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1008 PL_last_in_gv == PL_argvgv ?
1009 "" : GvNAME(PL_last_in_gv),
1010 line_mode ? "line" : "chunk",
1011 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1013 #ifdef USE_5005THREADS
1015 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1017 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1023 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1028 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1029 && (io = GvIO(PL_stderrgv))
1030 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1037 SAVESPTR(PL_stderrgv);
1038 PL_stderrgv = Nullgv;
1040 PUSHSTACKi(PERLSI_MAGIC);
1044 PUSHs(SvTIED_obj((SV*)io, mg));
1045 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1047 call_method("PRINT", G_SCALAR);
1055 /* SFIO can really mess with your errno */
1056 const int e = errno;
1058 PerlIO * const serr = Perl_error_log;
1060 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1061 (void)PerlIO_flush(serr);
1068 /* Common code used by vcroak, vdie and vwarner */
1070 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1071 may have linked against it. */
1073 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1078 /* sv_2cv might call Perl_croak() */
1079 SV * const olddiehook = PL_diehook;
1083 SAVESPTR(PL_diehook);
1084 PL_diehook = Nullsv;
1085 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1087 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1094 msg = newSVpvn(message, msglen);
1095 SvFLAGS(msg) |= utf8;
1103 PUSHSTACKi(PERLSI_DIEHOOK);
1107 call_sv((SV*)cv, G_DISCARD);
1113 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1114 may have linked against it. */
1116 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1119 const char *message;
1122 SV * const msv = vmess(pat, args);
1123 if (PL_errors && SvCUR(PL_errors)) {
1124 sv_catsv(PL_errors, msv);
1125 message = SvPV_const(PL_errors, *msglen);
1126 SvCUR_set(PL_errors, 0);
1129 message = SvPV_const(msv,*msglen);
1130 *utf8 = SvUTF8(msv);
1136 DEBUG_S(PerlIO_printf(Perl_debug_log,
1137 "%p: die/croak: message = %s\ndiehook = %p\n",
1138 thr, message, PL_diehook));
1140 S_vdie_common(aTHX_ message, *msglen, *utf8);
1142 /* Cast because we're not changing function prototypes in maint, and this
1143 function isn't actually static. */
1144 return (char *) message;
1148 Perl_vdie(pTHX_ const char* pat, va_list *args)
1150 const char *message;
1151 const int was_in_eval = PL_in_eval;
1155 DEBUG_S(PerlIO_printf(Perl_debug_log,
1156 "%p: die: curstack = %p, mainstack = %p\n",
1157 thr, PL_curstack, PL_mainstack));
1159 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1161 PL_restartop = die_where((char *)message, msglen);
1162 SvFLAGS(ERRSV) |= utf8;
1163 DEBUG_S(PerlIO_printf(Perl_debug_log,
1164 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1165 thr, PL_restartop, was_in_eval, PL_top_env));
1166 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1168 return PL_restartop;
1171 #if defined(PERL_IMPLICIT_CONTEXT)
1173 Perl_die_nocontext(const char* pat, ...)
1178 va_start(args, pat);
1179 o = vdie(pat, &args);
1183 #endif /* PERL_IMPLICIT_CONTEXT */
1186 Perl_die(pTHX_ const char* pat, ...)
1190 va_start(args, pat);
1191 o = vdie(pat, &args);
1197 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1199 const char *message;
1203 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1206 PL_restartop = die_where((char *) message, msglen);
1207 SvFLAGS(ERRSV) |= utf8;
1211 message = SvPVx_const(ERRSV, msglen);
1213 write_to_stderr(message, msglen);
1217 #if defined(PERL_IMPLICIT_CONTEXT)
1219 Perl_croak_nocontext(const char *pat, ...)
1223 va_start(args, pat);
1228 #endif /* PERL_IMPLICIT_CONTEXT */
1231 =head1 Warning and Dieing
1235 This is the XSUB-writer's interface to Perl's C<die> function.
1236 Normally call this function the same way you call the C C<printf>
1237 function. Calling C<croak> returns control directly to Perl,
1238 sidestepping the normal C order of execution. See C<warn>.
1240 If you want to throw an exception object, assign the object to
1241 C<$@> and then pass C<Nullch> to croak():
1243 errsv = get_sv("@", TRUE);
1244 sv_setsv(errsv, exception_object);
1251 Perl_croak(pTHX_ const char *pat, ...)
1254 va_start(args, pat);
1261 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1264 SV * const msv = vmess(pat, args);
1265 const I32 utf8 = SvUTF8(msv);
1266 const char * const message = SvPV_const(msv, msglen);
1269 /* sv_2cv might call Perl_warn() */
1270 SV * const oldwarnhook = PL_warnhook;
1276 SAVESPTR(PL_warnhook);
1277 PL_warnhook = Nullsv;
1278 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1280 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1285 SAVESPTR(PL_warnhook);
1286 PL_warnhook = Nullsv;
1288 msg = newSVpvn(message, msglen);
1289 SvFLAGS(msg) |= utf8;
1293 PUSHSTACKi(PERLSI_WARNHOOK);
1297 call_sv((SV*)cv, G_DISCARD);
1304 write_to_stderr(message, msglen);
1307 #if defined(PERL_IMPLICIT_CONTEXT)
1309 Perl_warn_nocontext(const char *pat, ...)
1313 va_start(args, pat);
1317 #endif /* PERL_IMPLICIT_CONTEXT */
1322 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1323 function the same way you call the C C<printf> function. See C<croak>.
1329 Perl_warn(pTHX_ const char *pat, ...)
1332 va_start(args, pat);
1337 #if defined(PERL_IMPLICIT_CONTEXT)
1339 Perl_warner_nocontext(U32 err, const char *pat, ...)
1343 va_start(args, pat);
1344 vwarner(err, pat, &args);
1347 #endif /* PERL_IMPLICIT_CONTEXT */
1350 Perl_warner(pTHX_ U32 err, const char* pat,...)
1353 va_start(args, pat);
1354 vwarner(err, pat, &args);
1359 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1362 SV * const msv = vmess(pat, args);
1364 const char *message = SvPV_const(msv, msglen);
1365 const I32 utf8 = SvUTF8(msv);
1367 #ifdef USE_5005THREADS
1368 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1369 #endif /* USE_5005THREADS */
1372 S_vdie_common(aTHX_ message, msglen, utf8);
1375 PL_restartop = die_where((char *) message, msglen);
1376 SvFLAGS(ERRSV) |= utf8;
1379 write_to_stderr(message, msglen);
1383 Perl_vwarn(aTHX_ pat, args);
1387 /* implements the ckWARN? macros */
1390 Perl_ckwarn(pTHX_ U32 w)
1395 && PL_curcop->cop_warnings != pWARN_NONE
1397 PL_curcop->cop_warnings == pWARN_ALL
1398 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1399 || (unpackWARN2(w) &&
1400 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1401 || (unpackWARN3(w) &&
1402 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1403 || (unpackWARN4(w) &&
1404 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1409 isLEXWARN_off && PL_dowarn & G_WARN_ON
1414 /* implements the ckWARN?_d macro */
1417 Perl_ckwarn_d(pTHX_ U32 w)
1421 || PL_curcop->cop_warnings == pWARN_ALL
1423 PL_curcop->cop_warnings != pWARN_NONE
1425 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1426 || (unpackWARN2(w) &&
1427 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1428 || (unpackWARN3(w) &&
1429 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1430 || (unpackWARN4(w) &&
1431 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1439 /* since we've already done strlen() for both nam and val
1440 * we can use that info to make things faster than
1441 * sprintf(s, "%s=%s", nam, val)
1443 #define my_setenv_format(s, nam, nlen, val, vlen) \
1444 Copy(nam, s, nlen, char); \
1446 Copy(val, s+(nlen+1), vlen, char); \
1447 *(s+(nlen+1+vlen)) = '\0'
1449 #ifdef USE_ENVIRON_ARRAY
1450 /* VMS' my_setenv() is in vms.c */
1451 #if !defined(WIN32) && !defined(NETWARE)
1453 Perl_my_setenv(pTHX_ char *nam, char *val)
1456 /* only parent thread can modify process environment */
1457 if (PL_curinterp == aTHX)
1460 #ifndef PERL_USE_SAFE_PUTENV
1461 if (!PL_use_safe_putenv) {
1462 /* most putenv()s leak, so we manipulate environ directly */
1463 register I32 i=setenv_getix(nam); /* where does it go? */
1466 if (environ == PL_origenviron) { /* need we copy environment? */
1471 for (max = i; environ[max]; max++) ;
1472 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1473 for (j=0; j<max; j++) { /* copy environment */
1474 const int len = strlen(environ[j]);
1475 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1476 Copy(environ[j], tmpenv[j], len+1, char);
1478 tmpenv[max] = Nullch;
1479 environ = tmpenv; /* tell exec where it is now */
1482 safesysfree(environ[i]);
1483 while (environ[i]) {
1484 environ[i] = environ[i+1];
1489 if (!environ[i]) { /* does not exist yet */
1490 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1491 environ[i+1] = Nullch; /* make sure it's null terminated */
1494 safesysfree(environ[i]);
1498 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1499 /* all that work just for this */
1500 my_setenv_format(environ[i], nam, nlen, val, vlen);
1503 # if defined(__CYGWIN__) || defined(EPOC) || defined(SYMBIAN)
1504 # if defined(HAS_UNSETENV)
1506 (void)unsetenv(nam);
1508 (void)setenv(nam, val, 1);
1510 # else /* ! HAS_UNSETENV */
1511 (void)setenv(nam, val, 1);
1512 # endif /* HAS_UNSETENV */
1514 # if defined(HAS_UNSETENV)
1516 (void)unsetenv(nam);
1518 int nlen = strlen(nam);
1519 int vlen = strlen(val);
1521 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1522 my_setenv_format(new_env, nam, nlen, val, vlen);
1523 (void)putenv(new_env);
1525 # else /* ! HAS_UNSETENV */
1527 int nlen = strlen(nam), vlen;
1532 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1533 /* all that work just for this */
1534 my_setenv_format(new_env, nam, nlen, val, vlen);
1535 (void)putenv(new_env);
1536 # endif /* HAS_UNSETENV */
1537 # endif /* __CYGWIN__ */
1538 #ifndef PERL_USE_SAFE_PUTENV
1544 #else /* WIN32 || NETWARE */
1547 Perl_my_setenv(pTHX_ char *nam, char *val)
1549 register char *envstr;
1550 const int nlen = strlen(nam);
1557 Newx(envstr, nlen+vlen+2, char);
1558 my_setenv_format(envstr, nam, nlen, val, vlen);
1559 (void)PerlEnv_putenv(envstr);
1563 #endif /* WIN32 || NETWARE */
1567 Perl_setenv_getix(pTHX_ char *nam)
1570 const register I32 len = strlen(nam);
1572 for (i = 0; environ[i]; i++) {
1575 strnicmp(environ[i],nam,len) == 0
1577 strnEQ(environ[i],nam,len)
1579 && environ[i][len] == '=')
1580 break; /* strnEQ must come first to avoid */
1581 } /* potential SEGV's */
1584 #endif /* !PERL_MICRO */
1586 #endif /* !VMS && !EPOC*/
1588 #ifdef UNLINK_ALL_VERSIONS
1590 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1594 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1599 /* this is a drop-in replacement for bcopy() */
1600 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1602 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1604 char * const retval = to;
1606 if (from - to >= 0) {
1614 *(--to) = *(--from);
1620 /* this is a drop-in replacement for memset() */
1623 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1625 char * const retval = loc;
1633 /* this is a drop-in replacement for bzero() */
1634 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1636 Perl_my_bzero(register char *loc, register I32 len)
1638 char * const retval = loc;
1646 /* this is a drop-in replacement for memcmp() */
1647 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1649 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1651 register const U8 *a = (const U8 *)s1;
1652 register const U8 *b = (const U8 *)s2;
1656 if ((tmp = *a++ - *b++))
1661 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1665 #ifdef USE_CHAR_VSPRINTF
1670 vsprintf(char *dest, const char *pat, char *args)
1674 fakebuf._ptr = dest;
1675 fakebuf._cnt = 32767;
1679 fakebuf._flag = _IOWRT|_IOSTRG;
1680 _doprnt(pat, args, &fakebuf); /* what a kludge */
1681 (void)putc('\0', &fakebuf);
1682 #ifdef USE_CHAR_VSPRINTF
1685 return 0; /* perl doesn't use return value */
1689 #endif /* HAS_VPRINTF */
1692 #if BYTEORDER != 0x4321
1694 Perl_my_swap(pTHX_ short s)
1696 #if (BYTEORDER & 1) == 0
1699 result = ((s & 255) << 8) + ((s >> 8) & 255);
1707 Perl_my_htonl(pTHX_ long l)
1711 char c[sizeof(long)];
1714 #if BYTEORDER == 0x1234
1715 u.c[0] = (l >> 24) & 255;
1716 u.c[1] = (l >> 16) & 255;
1717 u.c[2] = (l >> 8) & 255;
1721 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1722 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1727 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1728 u.c[o & 0xf] = (l >> s) & 255;
1736 Perl_my_ntohl(pTHX_ long l)
1740 char c[sizeof(long)];
1743 #if BYTEORDER == 0x1234
1744 u.c[0] = (l >> 24) & 255;
1745 u.c[1] = (l >> 16) & 255;
1746 u.c[2] = (l >> 8) & 255;
1750 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1751 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1758 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1759 l |= (u.c[o & 0xf] & 255) << s;
1766 #endif /* BYTEORDER != 0x4321 */
1770 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1771 * If these functions are defined,
1772 * the BYTEORDER is neither 0x1234 nor 0x4321.
1773 * However, this is not assumed.
1777 #define HTOLE(name,type) \
1779 name (register type n) \
1783 char c[sizeof(type)]; \
1786 register I32 s = 0; \
1787 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1788 u.c[i] = (n >> s) & 0xFF; \
1793 #define LETOH(name,type) \
1795 name (register type n) \
1799 char c[sizeof(type)]; \
1802 register I32 s = 0; \
1805 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1806 n |= ((type)(u.c[i] & 0xFF)) << s; \
1812 * Big-endian byte order functions.
1815 #define HTOBE(name,type) \
1817 name (register type n) \
1821 char c[sizeof(type)]; \
1824 register I32 s = 8*(sizeof(u.c)-1); \
1825 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1826 u.c[i] = (n >> s) & 0xFF; \
1831 #define BETOH(name,type) \
1833 name (register type n) \
1837 char c[sizeof(type)]; \
1840 register I32 s = 8*(sizeof(u.c)-1); \
1843 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1844 n |= ((type)(u.c[i] & 0xFF)) << s; \
1850 * If we just can't do it...
1853 #define NOT_AVAIL(name,type) \
1855 name (register type n) \
1857 Perl_croak_nocontext(#name "() not available"); \
1858 return n; /* not reached */ \
1862 #if defined(HAS_HTOVS) && !defined(htovs)
1865 #if defined(HAS_HTOVL) && !defined(htovl)
1868 #if defined(HAS_VTOHS) && !defined(vtohs)
1871 #if defined(HAS_VTOHL) && !defined(vtohl)
1875 #ifdef PERL_NEED_MY_HTOLE16
1877 HTOLE(Perl_my_htole16,U16)
1879 NOT_AVAIL(Perl_my_htole16,U16)
1882 #ifdef PERL_NEED_MY_LETOH16
1884 LETOH(Perl_my_letoh16,U16)
1886 NOT_AVAIL(Perl_my_letoh16,U16)
1889 #ifdef PERL_NEED_MY_HTOBE16
1891 HTOBE(Perl_my_htobe16,U16)
1893 NOT_AVAIL(Perl_my_htobe16,U16)
1896 #ifdef PERL_NEED_MY_BETOH16
1898 BETOH(Perl_my_betoh16,U16)
1900 NOT_AVAIL(Perl_my_betoh16,U16)
1904 #ifdef PERL_NEED_MY_HTOLE32
1906 HTOLE(Perl_my_htole32,U32)
1908 NOT_AVAIL(Perl_my_htole32,U32)
1911 #ifdef PERL_NEED_MY_LETOH32
1913 LETOH(Perl_my_letoh32,U32)
1915 NOT_AVAIL(Perl_my_letoh32,U32)
1918 #ifdef PERL_NEED_MY_HTOBE32
1920 HTOBE(Perl_my_htobe32,U32)
1922 NOT_AVAIL(Perl_my_htobe32,U32)
1925 #ifdef PERL_NEED_MY_BETOH32
1927 BETOH(Perl_my_betoh32,U32)
1929 NOT_AVAIL(Perl_my_betoh32,U32)
1933 #ifdef PERL_NEED_MY_HTOLE64
1935 HTOLE(Perl_my_htole64,U64)
1937 NOT_AVAIL(Perl_my_htole64,U64)
1940 #ifdef PERL_NEED_MY_LETOH64
1942 LETOH(Perl_my_letoh64,U64)
1944 NOT_AVAIL(Perl_my_letoh64,U64)
1947 #ifdef PERL_NEED_MY_HTOBE64
1949 HTOBE(Perl_my_htobe64,U64)
1951 NOT_AVAIL(Perl_my_htobe64,U64)
1954 #ifdef PERL_NEED_MY_BETOH64
1956 BETOH(Perl_my_betoh64,U64)
1958 NOT_AVAIL(Perl_my_betoh64,U64)
1962 #ifdef PERL_NEED_MY_HTOLES
1963 HTOLE(Perl_my_htoles,short)
1965 #ifdef PERL_NEED_MY_LETOHS
1966 LETOH(Perl_my_letohs,short)
1968 #ifdef PERL_NEED_MY_HTOBES
1969 HTOBE(Perl_my_htobes,short)
1971 #ifdef PERL_NEED_MY_BETOHS
1972 BETOH(Perl_my_betohs,short)
1975 #ifdef PERL_NEED_MY_HTOLEI
1976 HTOLE(Perl_my_htolei,int)
1978 #ifdef PERL_NEED_MY_LETOHI
1979 LETOH(Perl_my_letohi,int)
1981 #ifdef PERL_NEED_MY_HTOBEI
1982 HTOBE(Perl_my_htobei,int)
1984 #ifdef PERL_NEED_MY_BETOHI
1985 BETOH(Perl_my_betohi,int)
1988 #ifdef PERL_NEED_MY_HTOLEL
1989 HTOLE(Perl_my_htolel,long)
1991 #ifdef PERL_NEED_MY_LETOHL
1992 LETOH(Perl_my_letohl,long)
1994 #ifdef PERL_NEED_MY_HTOBEL
1995 HTOBE(Perl_my_htobel,long)
1997 #ifdef PERL_NEED_MY_BETOHL
1998 BETOH(Perl_my_betohl,long)
2002 Perl_my_swabn(void *ptr, int n)
2004 register char *s = (char *)ptr;
2005 register char *e = s + (n-1);
2008 for (n /= 2; n > 0; s++, e--, n--) {
2016 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2018 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2020 register I32 This, that;
2026 PERL_FLUSHALL_FOR_CHILD;
2027 This = (*mode == 'w');
2031 taint_proper("Insecure %s%s", "EXEC");
2033 if (PerlProc_pipe(p) < 0)
2035 /* Try for another pipe pair for error return */
2036 if (PerlProc_pipe(pp) >= 0)
2038 while ((pid = PerlProc_fork()) < 0) {
2039 if (errno != EAGAIN) {
2040 PerlLIO_close(p[This]);
2041 PerlLIO_close(p[that]);
2043 PerlLIO_close(pp[0]);
2044 PerlLIO_close(pp[1]);
2056 /* Close parent's end of error status pipe (if any) */
2058 PerlLIO_close(pp[0]);
2059 #if defined(HAS_FCNTL) && defined(F_SETFD)
2060 /* Close error pipe automatically if exec works */
2061 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2064 /* Now dup our end of _the_ pipe to right position */
2065 if (p[THIS] != (*mode == 'r')) {
2066 PerlLIO_dup2(p[THIS], *mode == 'r');
2067 PerlLIO_close(p[THIS]);
2068 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2069 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2072 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2073 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2074 /* No automatic close - do it by hand */
2081 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2087 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2093 do_execfree(); /* free any memory malloced by child on fork */
2095 PerlLIO_close(pp[1]);
2096 /* Keep the lower of the two fd numbers */
2097 if (p[that] < p[This]) {
2098 PerlLIO_dup2(p[This], p[that]);
2099 PerlLIO_close(p[This]);
2103 PerlLIO_close(p[that]); /* close child's end of pipe */
2106 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2108 (void)SvUPGRADE(sv,SVt_IV);
2110 PL_forkprocess = pid;
2111 /* If we managed to get status pipe check for exec fail */
2112 if (did_pipes && pid > 0) {
2116 while (n < sizeof(int)) {
2117 n1 = PerlLIO_read(pp[0],
2118 (void*)(((char*)&errkid)+n),
2124 PerlLIO_close(pp[0]);
2126 if (n) { /* Error */
2128 PerlLIO_close(p[This]);
2129 if (n != sizeof(int))
2130 Perl_croak(aTHX_ "panic: kid popen errno read");
2132 pid2 = wait4pid(pid, &status, 0);
2133 } while (pid2 == -1 && errno == EINTR);
2134 errno = errkid; /* Propagate errno from kid */
2139 PerlLIO_close(pp[0]);
2140 return PerlIO_fdopen(p[This], mode);
2142 Perl_croak(aTHX_ "List form of piped open not implemented");
2143 return (PerlIO *) NULL;
2147 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2148 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2150 Perl_my_popen(pTHX_ char *cmd, char *mode)
2153 register I32 This, that;
2156 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2160 PERL_FLUSHALL_FOR_CHILD;
2163 return my_syspopen(aTHX_ cmd,mode);
2166 This = (*mode == 'w');
2168 if (doexec && PL_tainting) {
2170 taint_proper("Insecure %s%s", "EXEC");
2172 if (PerlProc_pipe(p) < 0)
2174 if (doexec && PerlProc_pipe(pp) >= 0)
2176 while ((pid = PerlProc_fork()) < 0) {
2177 if (errno != EAGAIN) {
2178 PerlLIO_close(p[This]);
2179 PerlLIO_close(p[that]);
2181 PerlLIO_close(pp[0]);
2182 PerlLIO_close(pp[1]);
2185 Perl_croak(aTHX_ "Can't fork");
2198 PerlLIO_close(pp[0]);
2199 #if defined(HAS_FCNTL) && defined(F_SETFD)
2200 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2203 if (p[THIS] != (*mode == 'r')) {
2204 PerlLIO_dup2(p[THIS], *mode == 'r');
2205 PerlLIO_close(p[THIS]);
2206 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2207 PerlLIO_close(p[THAT]);
2210 PerlLIO_close(p[THAT]);
2213 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2220 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2225 /* may or may not use the shell */
2226 do_exec3(cmd, pp[1], did_pipes);
2229 #endif /* defined OS2 */
2230 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2231 SvREADONLY_off(GvSV(tmpgv));
2232 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2233 SvREADONLY_on(GvSV(tmpgv));
2235 #ifdef THREADS_HAVE_PIDS
2236 PL_ppid = (IV)getppid();
2239 hv_clear(PL_pidstatus); /* we have no children */
2244 do_execfree(); /* free any memory malloced by child on vfork */
2246 PerlLIO_close(pp[1]);
2247 if (p[that] < p[This]) {
2248 PerlLIO_dup2(p[This], p[that]);
2249 PerlLIO_close(p[This]);
2253 PerlLIO_close(p[that]);
2256 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2258 (void)SvUPGRADE(sv,SVt_IV);
2260 PL_forkprocess = pid;
2261 if (did_pipes && pid > 0) {
2265 while (n < sizeof(int)) {
2266 n1 = PerlLIO_read(pp[0],
2267 (void*)(((char*)&errkid)+n),
2273 PerlLIO_close(pp[0]);
2275 if (n) { /* Error */
2277 PerlLIO_close(p[This]);
2278 if (n != sizeof(int))
2279 Perl_croak(aTHX_ "panic: kid popen errno read");
2281 pid2 = wait4pid(pid, &status, 0);
2282 } while (pid2 == -1 && errno == EINTR);
2283 errno = errkid; /* Propagate errno from kid */
2288 PerlLIO_close(pp[0]);
2289 return PerlIO_fdopen(p[This], mode);
2292 #if defined(atarist) || defined(EPOC)
2295 Perl_my_popen(pTHX_ char *cmd, char *mode)
2297 PERL_FLUSHALL_FOR_CHILD;
2298 /* Call system's popen() to get a FILE *, then import it.
2299 used 0 for 2nd parameter to PerlIO_importFILE;
2302 return PerlIO_importFILE(popen(cmd, mode), 0);
2306 FILE *djgpp_popen();
2308 Perl_my_popen(pTHX_ char *cmd, char *mode)
2310 PERL_FLUSHALL_FOR_CHILD;
2311 /* Call system's popen() to get a FILE *, then import it.
2312 used 0 for 2nd parameter to PerlIO_importFILE;
2315 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2320 #endif /* !DOSISH */
2322 /* this is called in parent before the fork() */
2324 Perl_atfork_lock(void)
2326 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2327 /* locks must be held in locking order (if any) */
2329 MUTEX_LOCK(&PL_malloc_mutex);
2335 /* this is called in both parent and child after the fork() */
2337 Perl_atfork_unlock(void)
2339 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2340 /* locks must be released in same order as in atfork_lock() */
2342 MUTEX_UNLOCK(&PL_malloc_mutex);
2351 #if defined(HAS_FORK)
2353 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2358 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2359 * handlers elsewhere in the code */
2364 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2365 Perl_croak_nocontext("fork() not available");
2367 #endif /* HAS_FORK */
2372 Perl_dump_fds(pTHX_ char *s)
2377 PerlIO_printf(Perl_debug_log,"%s", s);
2378 for (fd = 0; fd < 32; fd++) {
2379 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2380 PerlIO_printf(Perl_debug_log," %d",fd);
2382 PerlIO_printf(Perl_debug_log,"\n");
2385 #endif /* DUMP_FDS */
2389 dup2(int oldfd, int newfd)
2391 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2394 PerlLIO_close(newfd);
2395 return fcntl(oldfd, F_DUPFD, newfd);
2397 #define DUP2_MAX_FDS 256
2398 int fdtmp[DUP2_MAX_FDS];
2404 PerlLIO_close(newfd);
2405 /* good enough for low fd's... */
2406 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2407 if (fdx >= DUP2_MAX_FDS) {
2415 PerlLIO_close(fdtmp[--fdx]);
2422 #ifdef HAS_SIGACTION
2424 #ifdef MACOS_TRADITIONAL
2425 /* We don't want restart behavior on MacOS */
2430 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2432 struct sigaction act, oact;
2435 /* only "parent" interpreter can diddle signals */
2436 if (PL_curinterp != aTHX)
2440 act.sa_handler = handler;
2441 sigemptyset(&act.sa_mask);
2444 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2445 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2447 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2448 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2449 act.sa_flags |= SA_NOCLDWAIT;
2451 if (sigaction(signo, &act, &oact) == -1)
2454 return oact.sa_handler;
2458 Perl_rsignal_state(pTHX_ int signo)
2460 struct sigaction oact;
2462 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2465 return oact.sa_handler;
2469 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2471 struct sigaction act;
2474 /* only "parent" interpreter can diddle signals */
2475 if (PL_curinterp != aTHX)
2479 act.sa_handler = handler;
2480 sigemptyset(&act.sa_mask);
2483 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2484 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2486 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2487 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2488 act.sa_flags |= SA_NOCLDWAIT;
2490 return sigaction(signo, &act, save);
2494 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2497 /* only "parent" interpreter can diddle signals */
2498 if (PL_curinterp != aTHX)
2502 return sigaction(signo, save, (struct sigaction *)NULL);
2505 #else /* !HAS_SIGACTION */
2508 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2510 #if defined(USE_ITHREADS) && !defined(WIN32)
2511 /* only "parent" interpreter can diddle signals */
2512 if (PL_curinterp != aTHX)
2516 return PerlProc_signal(signo, handler);
2519 static int PL_sig_trapped; /* XXX signals are process-wide anyway, so we
2520 ignore the implications of this for threading */
2530 Perl_rsignal_state(pTHX_ int signo)
2532 Sighandler_t oldsig;
2534 #if defined(USE_ITHREADS) && !defined(WIN32)
2535 /* only "parent" interpreter can diddle signals */
2536 if (PL_curinterp != aTHX)
2541 oldsig = PerlProc_signal(signo, sig_trap);
2542 PerlProc_signal(signo, oldsig);
2544 PerlProc_kill(PerlProc_getpid(), signo);
2549 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2551 #if defined(USE_ITHREADS) && !defined(WIN32)
2552 /* only "parent" interpreter can diddle signals */
2553 if (PL_curinterp != aTHX)
2556 *save = PerlProc_signal(signo, handler);
2557 return (*save == SIG_ERR) ? -1 : 0;
2561 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2563 #if defined(USE_ITHREADS) && !defined(WIN32)
2564 /* only "parent" interpreter can diddle signals */
2565 if (PL_curinterp != aTHX)
2568 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2571 #endif /* !HAS_SIGACTION */
2572 #endif /* !PERL_MICRO */
2574 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2575 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2577 Perl_my_pclose(pTHX_ PerlIO *ptr)
2579 Sigsave_t hstat, istat, qstat;
2585 int saved_errno = 0;
2587 int saved_vaxc_errno;
2590 int saved_win32_errno;
2594 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2596 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2598 *svp = &PL_sv_undef;
2600 if (pid == -1) { /* Opened by popen. */
2601 return my_syspclose(ptr);
2604 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2605 saved_errno = errno;
2607 saved_vaxc_errno = vaxc$errno;
2610 saved_win32_errno = GetLastError();
2614 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2617 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2618 rsignal_save(SIGINT, SIG_IGN, &istat);
2619 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2622 pid2 = wait4pid(pid, &status, 0);
2623 } while (pid2 == -1 && errno == EINTR);
2625 rsignal_restore(SIGHUP, &hstat);
2626 rsignal_restore(SIGINT, &istat);
2627 rsignal_restore(SIGQUIT, &qstat);
2630 SETERRNO(saved_errno, saved_vaxc_errno);
2633 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2635 #endif /* !DOSISH */
2637 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2639 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2644 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2646 char spid[TYPE_CHARS(IV)];
2650 sprintf(spid, "%"IVdf, (IV)pid);
2651 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2652 if (svp && *svp != &PL_sv_undef) {
2653 *statusp = SvIVX(*svp);
2654 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2661 hv_iterinit(PL_pidstatus);
2662 if ((entry = hv_iternext(PL_pidstatus))) {
2663 SV *sv = hv_iterval(PL_pidstatus,entry);
2665 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2666 *statusp = SvIVX(sv);
2667 sprintf(spid, "%"IVdf, (IV)pid);
2668 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2675 # ifdef HAS_WAITPID_RUNTIME
2676 if (!HAS_WAITPID_RUNTIME)
2679 result = PerlProc_waitpid(pid,statusp,flags);
2682 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2683 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2686 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2687 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2692 Perl_croak(aTHX_ "Can't do waitpid with flags");
2694 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2695 pidgone(result,*statusp);
2701 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2704 if (result < 0 && errno == EINTR) {
2709 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2712 Perl_pidgone(pTHX_ Pid_t pid, int status)
2715 char spid[TYPE_CHARS(IV)];
2717 sprintf(spid, "%"IVdf, (IV)pid);
2718 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2719 (void)SvUPGRADE(sv,SVt_IV);
2720 SvIV_set(sv, status);
2724 #if defined(atarist) || defined(OS2) || defined(EPOC)
2727 int /* Cannot prototype with I32
2729 my_syspclose(PerlIO *ptr)
2732 Perl_my_pclose(pTHX_ PerlIO *ptr)
2735 /* Needs work for PerlIO ! */
2736 FILE *f = PerlIO_findFILE(ptr);
2737 I32 result = pclose(f);
2738 PerlIO_releaseFILE(ptr,f);
2746 Perl_my_pclose(pTHX_ PerlIO *ptr)
2748 /* Needs work for PerlIO ! */
2749 FILE *f = PerlIO_findFILE(ptr);
2750 I32 result = djgpp_pclose(f);
2751 result = (result << 8) & 0xff00;
2752 PerlIO_releaseFILE(ptr,f);
2758 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2761 register const char *frombase = from;
2764 register const char c = *from;
2769 while (count-- > 0) {
2770 for (todo = len; todo > 0; todo--) {
2779 Perl_same_dirent(pTHX_ char *a, char *b)
2781 char *fa = strrchr(a,'/');
2782 char *fb = strrchr(b,'/');
2785 SV *tmpsv = sv_newmortal();
2798 sv_setpvn(tmpsv, ".", 1);
2800 sv_setpvn(tmpsv, a, fa - a);
2801 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2804 sv_setpvn(tmpsv, ".", 1);
2806 sv_setpvn(tmpsv, b, fb - b);
2807 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2809 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2810 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2812 #endif /* !HAS_RENAME */
2815 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext,
2818 const char *xfound = Nullch;
2819 char *xfailed = Nullch;
2820 char tmpbuf[MAXPATHLEN];
2824 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2825 # define SEARCH_EXTS ".bat", ".cmd", NULL
2826 # define MAX_EXT_LEN 4
2829 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2830 # define MAX_EXT_LEN 4
2833 # define SEARCH_EXTS ".pl", ".com", NULL
2834 # define MAX_EXT_LEN 4
2836 /* additional extensions to try in each dir if scriptname not found */
2838 const char *const exts[] = { SEARCH_EXTS };
2839 const char *const *const ext =
2840 search_ext ? (const char *const *const)search_ext : exts;
2841 int extidx = 0, i = 0;
2842 const char *curext = Nullch;
2844 PERL_UNUSED_ARG(search_ext);
2845 # define MAX_EXT_LEN 0
2849 * If dosearch is true and if scriptname does not contain path
2850 * delimiters, search the PATH for scriptname.
2852 * If SEARCH_EXTS is also defined, will look for each
2853 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2854 * while searching the PATH.
2856 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2857 * proceeds as follows:
2858 * If DOSISH or VMSISH:
2859 * + look for ./scriptname{,.foo,.bar}
2860 * + search the PATH for scriptname{,.foo,.bar}
2863 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2864 * this will not look in '.' if it's not in the PATH)
2869 # ifdef ALWAYS_DEFTYPES
2870 len = strlen(scriptname);
2871 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2872 int hasdir, idx = 0, deftypes = 1;
2875 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2878 int hasdir, idx = 0, deftypes = 1;
2881 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2883 /* The first time through, just add SEARCH_EXTS to whatever we
2884 * already have, so we can check for default file types. */
2886 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2892 if ((strlen(tmpbuf) + strlen(scriptname)
2893 + MAX_EXT_LEN) >= sizeof tmpbuf)
2894 continue; /* don't search dir with too-long name */
2895 strcat(tmpbuf, scriptname);
2899 if (strEQ(scriptname, "-"))
2901 if (dosearch) { /* Look in '.' first. */
2902 char *cur = scriptname;
2904 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2906 if (strEQ(ext[i++],curext)) {
2907 extidx = -1; /* already has an ext */
2912 DEBUG_p(PerlIO_printf(Perl_debug_log,
2913 "Looking for %s\n",cur));
2914 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2915 && !S_ISDIR(PL_statbuf.st_mode)) {
2923 if (cur == scriptname) {
2924 len = strlen(scriptname);
2925 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2927 /* FIXME? Convert to memcpy */
2928 cur = strcpy(tmpbuf, scriptname);
2930 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2931 && strcpy(tmpbuf+len, ext[extidx++]));
2936 #ifdef MACOS_TRADITIONAL
2937 if (dosearch && !strchr(scriptname, ':') &&
2938 (s = PerlEnv_getenv("Commands")))
2940 if (dosearch && !strchr(scriptname, '/')
2942 && !strchr(scriptname, '\\')
2944 && (s = PerlEnv_getenv("PATH")))
2949 PL_bufend = s + strlen(s);
2950 while (s < PL_bufend) {
2951 #ifdef MACOS_TRADITIONAL
2952 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2956 #if defined(atarist) || defined(DOSISH)
2961 && *s != ';'; len++, s++) {
2962 if (len < sizeof tmpbuf)
2965 if (len < sizeof tmpbuf)
2967 #else /* ! (atarist || DOSISH) */
2968 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2971 #endif /* ! (atarist || DOSISH) */
2972 #endif /* MACOS_TRADITIONAL */
2975 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2976 continue; /* don't search dir with too-long name */
2977 #ifdef MACOS_TRADITIONAL
2978 if (len && tmpbuf[len - 1] != ':')
2979 tmpbuf[len++] = ':';
2982 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2983 && tmpbuf[len - 1] != '/'
2984 && tmpbuf[len - 1] != '\\'
2987 tmpbuf[len++] = '/';
2988 if (len == 2 && tmpbuf[0] == '.')
2991 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
2993 (void)strcpy(tmpbuf + len, scriptname);
2997 len = strlen(tmpbuf);
2998 if (extidx > 0) /* reset after previous loop */
3002 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3003 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3004 if (S_ISDIR(PL_statbuf.st_mode)) {
3008 } while ( retval < 0 /* not there */
3009 && extidx>=0 && ext[extidx] /* try an extension? */
3010 && strcpy(tmpbuf+len, ext[extidx++])
3015 if (S_ISREG(PL_statbuf.st_mode)
3016 && cando(S_IRUSR,TRUE,&PL_statbuf)
3017 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3018 && cando(S_IXUSR,TRUE,&PL_statbuf)
3022 xfound = tmpbuf; /* bingo! */
3026 xfailed = savepv(tmpbuf);
3029 if (!xfound && !seen_dot && !xfailed &&
3030 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3031 || S_ISDIR(PL_statbuf.st_mode)))
3033 seen_dot = 1; /* Disable message. */
3035 if (flags & 1) { /* do or die? */
3036 Perl_croak(aTHX_ "Can't %s %s%s%s",
3037 (xfailed ? "execute" : "find"),
3038 (xfailed ? xfailed : scriptname),
3039 (xfailed ? "" : " on PATH"),
3040 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3042 scriptname = Nullch;
3045 /* Cast because we're not changing function prototypes in maint. */
3046 scriptname = (char *) xfound;
3048 return (scriptname ? savepv(scriptname) : Nullch);
3051 #ifndef PERL_GET_CONTEXT_DEFINED
3054 Perl_get_context(void)
3056 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
3057 # ifdef OLD_PTHREADS_API
3059 if (pthread_getspecific(PL_thr_key, &t))
3060 Perl_croak_nocontext("panic: pthread_getspecific");
3063 # ifdef I_MACH_CTHREADS
3064 return (void*)cthread_data(cthread_self());
3066 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3075 Perl_set_context(void *t)
3077 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
3078 # ifdef I_MACH_CTHREADS
3079 cthread_set_data(cthread_self(), t);
3081 if (pthread_setspecific(PL_thr_key, t))
3082 Perl_croak_nocontext("panic: pthread_setspecific");
3089 #endif /* !PERL_GET_CONTEXT_DEFINED */
3091 #ifdef USE_5005THREADS
3094 /* Very simplistic scheduler for now */
3098 thr = thr->i.next_run;
3102 Perl_cond_init(pTHX_ perl_cond *cp)
3108 Perl_cond_signal(pTHX_ perl_cond *cp)
3111 perl_cond cond = *cp;
3116 /* Insert t in the runnable queue just ahead of us */
3117 t->i.next_run = thr->i.next_run;
3118 thr->i.next_run->i.prev_run = t;
3119 t->i.prev_run = thr;
3120 thr->i.next_run = t;
3121 thr->i.wait_queue = 0;
3122 /* Remove from the wait queue */
3128 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3131 perl_cond cond, cond_next;
3133 for (cond = *cp; cond; cond = cond_next) {
3135 /* Insert t in the runnable queue just ahead of us */
3136 t->i.next_run = thr->i.next_run;
3137 thr->i.next_run->i.prev_run = t;
3138 t->i.prev_run = thr;
3139 thr->i.next_run = t;
3140 thr->i.wait_queue = 0;
3141 /* Remove from the wait queue */
3142 cond_next = cond->next;
3149 Perl_cond_wait(pTHX_ perl_cond *cp)
3153 if (thr->i.next_run == thr)
3154 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3156 New(666, cond, 1, struct perl_wait_queue);
3160 thr->i.wait_queue = cond;
3161 /* Remove ourselves from runnable queue */
3162 thr->i.next_run->i.prev_run = thr->i.prev_run;
3163 thr->i.prev_run->i.next_run = thr->i.next_run;
3165 #endif /* FAKE_THREADS */
3168 Perl_condpair_magic(pTHX_ SV *sv)
3172 (void)SvUPGRADE(sv, SVt_PVMG);
3173 mg = mg_find(sv, PERL_MAGIC_mutex);
3177 New(53, cp, 1, condpair_t);
3178 MUTEX_INIT(&cp->mutex);
3179 COND_INIT(&cp->owner_cond);
3180 COND_INIT(&cp->cond);
3182 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3183 mg = mg_find(sv, PERL_MAGIC_mutex);
3185 /* someone else beat us to initialising it */
3186 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3187 MUTEX_DESTROY(&cp->mutex);
3188 COND_DESTROY(&cp->owner_cond);
3189 COND_DESTROY(&cp->cond);
3193 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3195 mg->mg_ptr = (char *)cp;
3196 mg->mg_len = sizeof(cp);
3197 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3198 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3199 "%p: condpair_magic %p\n", thr, sv)));
3206 Perl_sv_lock(pTHX_ SV *osv)
3216 mg = condpair_magic(sv);
3217 MUTEX_LOCK(MgMUTEXP(mg));
3218 if (MgOWNER(mg) == thr)
3219 MUTEX_UNLOCK(MgMUTEXP(mg));
3222 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3224 DEBUG_S(PerlIO_printf(Perl_debug_log,
3225 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3226 PTR2UV(thr), PTR2UV(sv)));
3227 MUTEX_UNLOCK(MgMUTEXP(mg));
3228 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3230 UNLOCK_SV_LOCK_MUTEX;
3235 * Make a new perl thread structure using t as a prototype. Some of the
3236 * fields for the new thread are copied from the prototype thread, t,
3237 * so t should not be running in perl at the time this function is
3238 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3239 * thread calling new_struct_thread) clearly satisfies this constraint.
3241 struct perl_thread *
3242 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3244 #if !defined(PERL_IMPLICIT_CONTEXT)
3245 struct perl_thread *thr;
3251 sv = newSVpvn("", 0);
3252 SvGROW(sv, sizeof(struct perl_thread) + 1);
3253 SvCUR_set(sv, sizeof(struct perl_thread));
3254 thr = (Thread) SvPVX(sv);
3256 Poison(thr, 1, struct perl_thread);
3263 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3264 PL_efloatbuf = (char*)NULL;
3267 Zero(thr, 1, struct perl_thread);
3273 PL_curcop = &PL_compiling;
3274 thr->interp = t->interp;
3275 thr->cvcache = newHV();
3276 thr->threadsv = newAV();
3277 thr->specific = newAV();
3278 thr->errsv = newSVpvn("", 0);
3279 thr->flags = THRf_R_JOINABLE;
3281 MUTEX_INIT(&thr->mutex);
3285 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3288 PL_statname = NEWSV(66,0);
3289 PL_errors = newSVpvn("", 0);
3291 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3292 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3293 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3294 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3295 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3297 PL_reginterp_cnt = 0;
3298 PL_lastscream = Nullsv;
3301 PL_reg_start_tmp = 0;
3302 PL_reg_start_tmpl = 0;
3303 PL_reg_poscache = Nullch;
3305 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3307 /* parent thread's data needs to be locked while we make copy */
3308 MUTEX_LOCK(&t->mutex);
3310 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3311 PL_protect = t->Tprotect;
3314 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3315 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3316 PL_curstash = t->Tcurstash; /* always be set to main? */
3318 PL_tainted = t->Ttainted;
3319 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3320 PL_rs = newSVsv(t->Trs);
3321 PL_last_in_gv = Nullgv;
3322 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3323 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3324 PL_chopset = t->Tchopset;
3325 PL_bodytarget = newSVsv(t->Tbodytarget);
3326 PL_toptarget = newSVsv(t->Ttoptarget);
3327 if (t->Tformtarget == t->Ttoptarget)
3328 PL_formtarget = PL_toptarget;
3330 PL_formtarget = PL_bodytarget;
3331 PL_watchaddr = 0; /* XXX */
3332 PL_watchok = 0; /* XXX */
3336 /* Initialise all per-thread SVs that the template thread used */
3337 svp = AvARRAY(t->threadsv);
3338 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3339 if (*svp && *svp != &PL_sv_undef) {
3340 SV *sv = newSVsv(*svp);
3341 av_store(thr->threadsv, i, sv);
3342 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3343 DEBUG_S(PerlIO_printf(Perl_debug_log,
3344 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3348 thr->threadsvp = AvARRAY(thr->threadsv);
3350 MUTEX_LOCK(&PL_threads_mutex);
3352 thr->tid = ++PL_threadnum;
3353 thr->next = t->next;
3356 thr->next->prev = thr;
3357 MUTEX_UNLOCK(&PL_threads_mutex);
3359 /* done copying parent's state */
3360 MUTEX_UNLOCK(&t->mutex);
3362 #ifdef HAVE_THREAD_INTERN
3363 Perl_init_thread_intern(thr);
3364 #endif /* HAVE_THREAD_INTERN */
3367 #endif /* USE_5005THREADS */
3369 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3378 Perl_get_op_names(pTHX)
3380 return (char **)PL_op_name;
3384 Perl_get_op_descs(pTHX)
3386 return (char **)PL_op_desc;
3390 Perl_get_no_modify(pTHX)
3392 /* Cast because we're not changing function prototypes in maint. */
3393 return (char *) PL_no_modify;
3397 Perl_get_opargs(pTHX)
3399 return (U32 *)PL_opargs;
3403 Perl_get_ppaddr(pTHX)
3405 return (PPADDR_t*)PL_ppaddr;
3408 #ifndef HAS_GETENV_LEN
3410 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3412 char * const env_trans = PerlEnv_getenv(env_elem);
3414 *len = strlen(env_trans);
3421 Perl_get_vtbl(pTHX_ int vtbl_id)
3423 const MGVTBL* result = Null(MGVTBL*);
3427 result = &PL_vtbl_sv;
3430 result = &PL_vtbl_env;
3432 case want_vtbl_envelem:
3433 result = &PL_vtbl_envelem;
3436 result = &PL_vtbl_sig;
3438 case want_vtbl_sigelem:
3439 result = &PL_vtbl_sigelem;
3441 case want_vtbl_pack:
3442 result = &PL_vtbl_pack;
3444 case want_vtbl_packelem:
3445 result = &PL_vtbl_packelem;
3447 case want_vtbl_dbline:
3448 result = &PL_vtbl_dbline;
3451 result = &PL_vtbl_isa;
3453 case want_vtbl_isaelem:
3454 result = &PL_vtbl_isaelem;
3456 case want_vtbl_arylen:
3457 result = &PL_vtbl_arylen;
3459 case want_vtbl_glob:
3460 result = &PL_vtbl_glob;
3462 case want_vtbl_mglob:
3463 result = &PL_vtbl_mglob;
3465 case want_vtbl_nkeys:
3466 result = &PL_vtbl_nkeys;
3468 case want_vtbl_taint:
3469 result = &PL_vtbl_taint;
3471 case want_vtbl_substr:
3472 result = &PL_vtbl_substr;
3475 result = &PL_vtbl_vec;
3478 result = &PL_vtbl_pos;
3481 result = &PL_vtbl_bm;
3484 result = &PL_vtbl_fm;
3486 case want_vtbl_uvar:
3487 result = &PL_vtbl_uvar;
3489 #ifdef USE_5005THREADS
3490 case want_vtbl_mutex:
3491 result = &PL_vtbl_mutex;
3494 case want_vtbl_defelem:
3495 result = &PL_vtbl_defelem;
3497 case want_vtbl_regexp:
3498 result = &PL_vtbl_regexp;
3500 case want_vtbl_regdata:
3501 result = &PL_vtbl_regdata;
3503 case want_vtbl_regdatum:
3504 result = &PL_vtbl_regdatum;
3506 #ifdef USE_LOCALE_COLLATE
3507 case want_vtbl_collxfrm:
3508 result = &PL_vtbl_collxfrm;
3511 case want_vtbl_amagic:
3512 result = &PL_vtbl_amagic;
3514 case want_vtbl_amagicelem:
3515 result = &PL_vtbl_amagicelem;
3517 case want_vtbl_backref:
3518 result = &PL_vtbl_backref;
3520 case want_vtbl_utf8:
3521 result = &PL_vtbl_utf8;
3524 return (MGVTBL*)result;
3528 Perl_my_fflush_all(pTHX)
3530 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3531 return PerlIO_flush(NULL);
3533 # if defined(HAS__FWALK)
3534 extern int fflush(FILE *);
3535 /* undocumented, unprototyped, but very useful BSDism */
3536 extern void _fwalk(int (*)(FILE *));
3540 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3542 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3543 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3545 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3546 open_max = sysconf(_SC_OPEN_MAX);
3549 open_max = FOPEN_MAX;
3552 open_max = OPEN_MAX;
3563 for (i = 0; i < open_max; i++)
3564 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3565 STDIO_STREAM_ARRAY[i]._file < open_max &&
3566 STDIO_STREAM_ARRAY[i]._flag)
3567 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3571 SETERRNO(EBADF,RMS_IFI);
3578 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3580 const char * const func =
3581 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3582 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3584 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3585 const char * const type = OP_IS_SOCKET(op)
3586 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3587 ? "socket" : "filehandle";
3588 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3590 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3591 if (ckWARN(WARN_IO)) {
3592 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3594 Perl_warner(aTHX_ packWARN(WARN_IO),
3595 "Filehandle %s opened only for %sput",
3598 Perl_warner(aTHX_ packWARN(WARN_IO),
3599 "Filehandle opened only for %sput", direction);
3606 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3608 warn_type = WARN_CLOSED;
3612 warn_type = WARN_UNOPENED;
3615 if (ckWARN(warn_type)) {
3616 if (name && *name) {
3617 Perl_warner(aTHX_ packWARN(warn_type),
3618 "%s%s on %s %s %s", func, pars, vile, type, name);
3619 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3621 aTHX_ packWARN(warn_type),
3622 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3627 Perl_warner(aTHX_ packWARN(warn_type),
3628 "%s%s on %s %s", func, pars, vile, type);
3629 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3631 aTHX_ packWARN(warn_type),
3632 "\t(Are you trying to call %s%s on dirhandle?)\n",
3641 /* in ASCII order, not that it matters */
3642 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3645 Perl_ebcdic_control(pTHX_ int ch)
3653 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3654 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3657 if (ctlp == controllablechars)
3658 return('\177'); /* DEL */
3660 return((unsigned char)(ctlp - controllablechars - 1));
3661 } else { /* Want uncontrol */
3662 if (ch == '\177' || ch == -1)
3664 else if (ch == '\157')
3666 else if (ch == '\174')
3668 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3670 else if (ch == '\155')
3672 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3673 return(controllablechars[ch+1]);
3675 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3680 /* To workaround core dumps from the uninitialised tm_zone we get the
3681 * system to give us a reasonable struct to copy. This fix means that
3682 * strftime uses the tm_zone and tm_gmtoff values returned by
3683 * localtime(time()). That should give the desired result most of the
3684 * time. But probably not always!
3686 * This does not address tzname aspects of NETaa14816.
3691 # ifndef STRUCT_TM_HASZONE
3692 # define STRUCT_TM_HASZONE
3696 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3697 # ifndef HAS_TM_TM_ZONE
3698 # define HAS_TM_TM_ZONE
3703 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3705 #ifdef HAS_TM_TM_ZONE
3707 const struct tm* my_tm;
3709 my_tm = localtime(&now);
3711 Copy(my_tm, ptm, 1, struct tm);
3713 PERL_UNUSED_ARG(ptm);
3718 * mini_mktime - normalise struct tm values without the localtime()
3719 * semantics (and overhead) of mktime().
3722 Perl_mini_mktime(pTHX_ struct tm *ptm)
3726 int month, mday, year, jday;
3727 int odd_cent, odd_year;
3729 #define DAYS_PER_YEAR 365
3730 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3731 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3732 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3733 #define SECS_PER_HOUR (60*60)
3734 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3735 /* parentheses deliberately absent on these two, otherwise they don't work */
3736 #define MONTH_TO_DAYS 153/5
3737 #define DAYS_TO_MONTH 5/153
3738 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3739 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3740 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3741 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3744 * Year/day algorithm notes:
3746 * With a suitable offset for numeric value of the month, one can find
3747 * an offset into the year by considering months to have 30.6 (153/5) days,
3748 * using integer arithmetic (i.e., with truncation). To avoid too much
3749 * messing about with leap days, we consider January and February to be
3750 * the 13th and 14th month of the previous year. After that transformation,
3751 * we need the month index we use to be high by 1 from 'normal human' usage,
3752 * so the month index values we use run from 4 through 15.
3754 * Given that, and the rules for the Gregorian calendar (leap years are those
3755 * divisible by 4 unless also divisible by 100, when they must be divisible
3756 * by 400 instead), we can simply calculate the number of days since some
3757 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3758 * the days we derive from our month index, and adding in the day of the
3759 * month. The value used here is not adjusted for the actual origin which
3760 * it normally would use (1 January A.D. 1), since we're not exposing it.
3761 * We're only building the value so we can turn around and get the
3762 * normalised values for the year, month, day-of-month, and day-of-year.
3764 * For going backward, we need to bias the value we're using so that we find
3765 * the right year value. (Basically, we don't want the contribution of
3766 * March 1st to the number to apply while deriving the year). Having done
3767 * that, we 'count up' the contribution to the year number by accounting for
3768 * full quadracenturies (400-year periods) with their extra leap days, plus
3769 * the contribution from full centuries (to avoid counting in the lost leap
3770 * days), plus the contribution from full quad-years (to count in the normal
3771 * leap days), plus the leftover contribution from any non-leap years.
3772 * At this point, if we were working with an actual leap day, we'll have 0
3773 * days left over. This is also true for March 1st, however. So, we have
3774 * to special-case that result, and (earlier) keep track of the 'odd'
3775 * century and year contributions. If we got 4 extra centuries in a qcent,
3776 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3777 * Otherwise, we add back in the earlier bias we removed (the 123 from
3778 * figuring in March 1st), find the month index (integer division by 30.6),
3779 * and the remainder is the day-of-month. We then have to convert back to
3780 * 'real' months (including fixing January and February from being 14/15 in
3781 * the previous year to being in the proper year). After that, to get
3782 * tm_yday, we work with the normalised year and get a new yearday value for
3783 * January 1st, which we subtract from the yearday value we had earlier,
3784 * representing the date we've re-built. This is done from January 1
3785 * because tm_yday is 0-origin.
3787 * Since POSIX time routines are only guaranteed to work for times since the
3788 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3789 * applies Gregorian calendar rules even to dates before the 16th century
3790 * doesn't bother me. Besides, you'd need cultural context for a given
3791 * date to know whether it was Julian or Gregorian calendar, and that's
3792 * outside the scope for this routine. Since we convert back based on the
3793 * same rules we used to build the yearday, you'll only get strange results
3794 * for input which needed normalising, or for the 'odd' century years which
3795 * were leap years in the Julian calander but not in the Gregorian one.
3796 * I can live with that.
3798 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3799 * that's still outside the scope for POSIX time manipulation, so I don't
3803 year = 1900 + ptm->tm_year;
3804 month = ptm->tm_mon;
3805 mday = ptm->tm_mday;
3806 /* allow given yday with no month & mday to dominate the result */
3807 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3810 jday = 1 + ptm->tm_yday;
3819 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3820 yearday += month*MONTH_TO_DAYS + mday + jday;
3822 * Note that we don't know when leap-seconds were or will be,
3823 * so we have to trust the user if we get something which looks
3824 * like a sensible leap-second. Wild values for seconds will
3825 * be rationalised, however.
3827 if ((unsigned) ptm->tm_sec <= 60) {
3834 secs += 60 * ptm->tm_min;
3835 secs += SECS_PER_HOUR * ptm->tm_hour;
3837 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3838 /* got negative remainder, but need positive time */
3839 /* back off an extra day to compensate */
3840 yearday += (secs/SECS_PER_DAY)-1;
3841 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3844 yearday += (secs/SECS_PER_DAY);
3845 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3848 else if (secs >= SECS_PER_DAY) {
3849 yearday += (secs/SECS_PER_DAY);
3850 secs %= SECS_PER_DAY;
3852 ptm->tm_hour = secs/SECS_PER_HOUR;
3853 secs %= SECS_PER_HOUR;
3854 ptm->tm_min = secs/60;
3856 ptm->tm_sec += secs;
3857 /* done with time of day effects */
3859 * The algorithm for yearday has (so far) left it high by 428.
3860 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3861 * bias it by 123 while trying to figure out what year it
3862 * really represents. Even with this tweak, the reverse
3863 * translation fails for years before A.D. 0001.
3864 * It would still fail for Feb 29, but we catch that one below.
3866 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3867 yearday -= YEAR_ADJUST;
3868 year = (yearday / DAYS_PER_QCENT) * 400;
3869 yearday %= DAYS_PER_QCENT;
3870 odd_cent = yearday / DAYS_PER_CENT;
3871 year += odd_cent * 100;
3872 yearday %= DAYS_PER_CENT;
3873 year += (yearday / DAYS_PER_QYEAR) * 4;
3874 yearday %= DAYS_PER_QYEAR;
3875 odd_year = yearday / DAYS_PER_YEAR;
3877 yearday %= DAYS_PER_YEAR;
3878 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3883 yearday += YEAR_ADJUST; /* recover March 1st crock */
3884 month = yearday*DAYS_TO_MONTH;
3885 yearday -= month*MONTH_TO_DAYS;
3886 /* recover other leap-year adjustment */
3895 ptm->tm_year = year - 1900;
3897 ptm->tm_mday = yearday;
3898 ptm->tm_mon = month;
3902 ptm->tm_mon = month - 1;
3904 /* re-build yearday based on Jan 1 to get tm_yday */
3906 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3907 yearday += 14*MONTH_TO_DAYS + 1;
3908 ptm->tm_yday = jday - yearday;
3909 /* fix tm_wday if not overridden by caller */
3910 if ((unsigned)ptm->tm_wday > 6)
3911 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3915 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3923 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3926 mytm.tm_hour = hour;
3927 mytm.tm_mday = mday;
3929 mytm.tm_year = year;
3930 mytm.tm_wday = wday;
3931 mytm.tm_yday = yday;
3932 mytm.tm_isdst = isdst;
3934 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3935 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3940 #ifdef HAS_TM_TM_GMTOFF
3941 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3943 #ifdef HAS_TM_TM_ZONE
3944 mytm.tm_zone = mytm2.tm_zone;
3949 Newx(buf, buflen, char);
3950 len = strftime(buf, buflen, fmt, &mytm);
3952 ** The following is needed to handle to the situation where
3953 ** tmpbuf overflows. Basically we want to allocate a buffer
3954 ** and try repeatedly. The reason why it is so complicated
3955 ** is that getting a return value of 0 from strftime can indicate
3956 ** one of the following:
3957 ** 1. buffer overflowed,
3958 ** 2. illegal conversion specifier, or
3959 ** 3. the format string specifies nothing to be returned(not
3960 ** an error). This could be because format is an empty string
3961 ** or it specifies %p that yields an empty string in some locale.
3962 ** If there is a better way to make it portable, go ahead by
3965 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3968 /* Possibly buf overflowed - try again with a bigger buf */
3969 const int fmtlen = strlen(fmt);
3970 const int bufsize = fmtlen + buflen;
3972 Newx(buf, bufsize, char);
3974 buflen = strftime(buf, bufsize, fmt, &mytm);
3975 if (buflen > 0 && buflen < bufsize)
3977 /* heuristic to prevent out-of-memory errors */
3978 if (bufsize > 100*fmtlen) {
3983 Renew(buf, bufsize*2, char);
3988 Perl_croak(aTHX_ "panic: no strftime");
3994 #define SV_CWD_RETURN_UNDEF \
3995 sv_setsv(sv, &PL_sv_undef); \
3998 #define SV_CWD_ISDOT(dp) \
3999 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4000 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4003 =head1 Miscellaneous Functions
4005 =for apidoc getcwd_sv
4007 Fill the sv with current working directory
4012 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4013 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4014 * getcwd(3) if available
4015 * Comments from the orignal:
4016 * This is a faster version of getcwd. It's also more dangerous
4017 * because you might chdir out of a directory that you can't chdir
4021 Perl_getcwd_sv(pTHX_ register SV *sv)
4025 #ifndef INCOMPLETE_TAINTS
4031 char buf[MAXPATHLEN];
4033 /* Some getcwd()s automatically allocate a buffer of the given
4034 * size from the heap if they are given a NULL buffer pointer.
4035 * The problem is that this behaviour is not portable. */
4036 if (getcwd(buf, sizeof(buf) - 1)) {
4037 sv_setpvn(sv, buf, strlen(buf));
4041 sv_setsv(sv, &PL_sv_undef);
4049 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4053 (void)SvUPGRADE(sv, SVt_PV);
4055 if (PerlLIO_lstat(".", &statbuf) < 0) {
4056 SV_CWD_RETURN_UNDEF;
4059 orig_cdev = statbuf.st_dev;
4060 orig_cino = statbuf.st_ino;
4069 if (PerlDir_chdir("..") < 0) {
4070 SV_CWD_RETURN_UNDEF;
4072 if (PerlLIO_stat(".", &statbuf) < 0) {
4073 SV_CWD_RETURN_UNDEF;
4076 cdev = statbuf.st_dev;
4077 cino = statbuf.st_ino;
4079 if (odev == cdev && oino == cino) {
4082 if (!(dir = PerlDir_open("."))) {
4083 SV_CWD_RETURN_UNDEF;
4086 while ((dp = PerlDir_read(dir)) != NULL) {
4088 const int namelen = dp->d_namlen;
4090 const int namelen = strlen(dp->d_name);
4093 if (SV_CWD_ISDOT(dp)) {
4097 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4098 SV_CWD_RETURN_UNDEF;
4101 tdev = statbuf.st_dev;
4102 tino = statbuf.st_ino;
4103 if (tino == oino && tdev == odev) {
4109 SV_CWD_RETURN_UNDEF;
4112 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4113 SV_CWD_RETURN_UNDEF;
4116 SvGROW(sv, pathlen + namelen + 1);
4120 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4123 /* prepend current directory to the front */
4125 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4126 pathlen += (namelen + 1);
4128 #ifdef VOID_CLOSEDIR
4131 if (PerlDir_close(dir) < 0) {
4132 SV_CWD_RETURN_UNDEF;
4138 SvCUR_set(sv, pathlen);
4142 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4143 SV_CWD_RETURN_UNDEF;
4146 if (PerlLIO_stat(".", &statbuf) < 0) {
4147 SV_CWD_RETURN_UNDEF;
4150 cdev = statbuf.st_dev;
4151 cino = statbuf.st_ino;
4153 if (cdev != orig_cdev || cino != orig_cino) {
4154 Perl_croak(aTHX_ "Unstable directory path, "
4155 "current directory changed unexpectedly");
4166 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4167 # define EMULATE_SOCKETPAIR_UDP
4170 #ifdef EMULATE_SOCKETPAIR_UDP
4172 S_socketpair_udp (int fd[2]) {
4174 /* Fake a datagram socketpair using UDP to localhost. */
4175 int sockets[2] = {-1, -1};
4176 struct sockaddr_in addresses[2];
4178 Sock_size_t size = sizeof(struct sockaddr_in);
4179 unsigned short port;
4182 memset(&addresses, 0, sizeof(addresses));
4185 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4186 if (sockets[i] == -1)
4187 goto tidy_up_and_fail;
4189 addresses[i].sin_family = AF_INET;
4190 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4191 addresses[i].sin_port = 0; /* kernel choses port. */
4192 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4193 sizeof(struct sockaddr_in)) == -1)
4194 goto tidy_up_and_fail;
4197 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4198 for each connect the other socket to it. */
4201 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4203 goto tidy_up_and_fail;
4204 if (size != sizeof(struct sockaddr_in))
4205 goto abort_tidy_up_and_fail;
4206 /* !1 is 0, !0 is 1 */
4207 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4208 sizeof(struct sockaddr_in)) == -1)
4209 goto tidy_up_and_fail;
4212 /* Now we have 2 sockets connected to each other. I don't trust some other
4213 process not to have already sent a packet to us (by random) so send
4214 a packet from each to the other. */
4217 /* I'm going to send my own port number. As a short.
4218 (Who knows if someone somewhere has sin_port as a bitfield and needs
4219 this routine. (I'm assuming crays have socketpair)) */
4220 port = addresses[i].sin_port;
4221 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4222 if (got != sizeof(port)) {
4224 goto tidy_up_and_fail;
4225 goto abort_tidy_up_and_fail;
4229 /* Packets sent. I don't trust them to have arrived though.
4230 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4231 connect to localhost will use a second kernel thread. In 2.6 the
4232 first thread running the connect() returns before the second completes,
4233 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4234 returns 0. Poor programs have tripped up. One poor program's authors'
4235 had a 50-1 reverse stock split. Not sure how connected these were.)
4236 So I don't trust someone not to have an unpredictable UDP stack.
4240 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4241 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4245 FD_SET(sockets[0], &rset);
4246 FD_SET(sockets[1], &rset);
4248 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4249 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4250 || !FD_ISSET(sockets[1], &rset)) {
4251 /* I hope this is portable and appropriate. */
4253 goto tidy_up_and_fail;
4254 goto abort_tidy_up_and_fail;
4258 /* And the paranoia department even now doesn't trust it to have arrive
4259 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4261 struct sockaddr_in readfrom;
4262 unsigned short buffer[2];
4267 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4268 sizeof(buffer), MSG_DONTWAIT,
4269 (struct sockaddr *) &readfrom, &size);
4271 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4273 (struct sockaddr *) &readfrom, &size);
4277 goto tidy_up_and_fail;
4278 if (got != sizeof(port)
4279 || size != sizeof(struct sockaddr_in)
4280 /* Check other socket sent us its port. */
4281 || buffer[0] != (unsigned short) addresses[!i].sin_port
4282 /* Check kernel says we got the datagram from that socket */
4283 || readfrom.sin_family != addresses[!i].sin_family
4284 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4285 || readfrom.sin_port != addresses[!i].sin_port)
4286 goto abort_tidy_up_and_fail;
4289 /* My caller (my_socketpair) has validated that this is non-NULL */
4292 /* I hereby declare this connection open. May God bless all who cross
4296 abort_tidy_up_and_fail:
4297 errno = ECONNABORTED;
4300 const int save_errno = errno;
4301 if (sockets[0] != -1)
4302 PerlLIO_close(sockets[0]);
4303 if (sockets[1] != -1)
4304 PerlLIO_close(sockets[1]);
4309 #endif /* EMULATE_SOCKETPAIR_UDP */
4311 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4313 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4314 /* Stevens says that family must be AF_LOCAL, protocol 0.
4315 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4320 struct sockaddr_in listen_addr;
4321 struct sockaddr_in connect_addr;
4326 || family != AF_UNIX
4329 errno = EAFNOSUPPORT;
4337 #ifdef EMULATE_SOCKETPAIR_UDP
4338 if (type == SOCK_DGRAM)
4339 return S_socketpair_udp(fd);
4342 listener = PerlSock_socket(AF_INET, type, 0);
4345 memset(&listen_addr, 0, sizeof(listen_addr));
4346 listen_addr.sin_family = AF_INET;
4347 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4348 listen_addr.sin_port = 0; /* kernel choses port. */
4349 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4350 sizeof(listen_addr)) == -1)
4351 goto tidy_up_and_fail;
4352 if (PerlSock_listen(listener, 1) == -1)
4353 goto tidy_up_and_fail;
4355 connector = PerlSock_socket(AF_INET, type, 0);
4356 if (connector == -1)
4357 goto tidy_up_and_fail;
4358 /* We want to find out the port number to connect to. */
4359 size = sizeof(connect_addr);
4360 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4362 goto tidy_up_and_fail;
4363 if (size != sizeof(connect_addr))
4364 goto abort_tidy_up_and_fail;
4365 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4366 sizeof(connect_addr)) == -1)
4367 goto tidy_up_and_fail;
4369 size = sizeof(listen_addr);
4370 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4373 goto tidy_up_and_fail;
4374 if (size != sizeof(listen_addr))
4375 goto abort_tidy_up_and_fail;
4376 PerlLIO_close(listener);
4377 /* Now check we are talking to ourself by matching port and host on the
4379 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4381 goto tidy_up_and_fail;
4382 if (size != sizeof(connect_addr)
4383 || listen_addr.sin_family != connect_addr.sin_family
4384 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4385 || listen_addr.sin_port != connect_addr.sin_port) {
4386 goto abort_tidy_up_and_fail;
4392 abort_tidy_up_and_fail:
4394 errno = ECONNABORTED; /* This would be the standard thing to do. */
4396 # ifdef ECONNREFUSED
4397 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4399 errno = ETIMEDOUT; /* Desperation time. */
4404 int save_errno = errno;
4406 PerlLIO_close(listener);
4407 if (connector != -1)
4408 PerlLIO_close(connector);
4410 PerlLIO_close(acceptor);
4416 /* In any case have a stub so that there's code corresponding
4417 * to the my_socketpair in global.sym. */
4419 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4420 #ifdef HAS_SOCKETPAIR
4421 return socketpair(family, type, protocol, fd);
4430 =for apidoc sv_nosharing
4432 Dummy routine which "shares" an SV when there is no sharing module present.
4433 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4434 some level of strict-ness.
4440 Perl_sv_nosharing(pTHX_ SV *sv)
4442 PERL_UNUSED_ARG(sv);
4446 =for apidoc sv_nolocking
4448 Dummy routine which "locks" an SV when there is no locking module present.
4449 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4450 some level of strict-ness.
4456 Perl_sv_nolocking(pTHX_ SV *sv)
4458 PERL_UNUSED_ARG(sv);
4463 =for apidoc sv_nounlocking
4465 Dummy routine which "unlocks" an SV when there is no locking module present.
4466 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4467 some level of strict-ness.
4473 Perl_sv_nounlocking(pTHX_ SV *sv)
4475 PERL_UNUSED_ARG(sv);
4479 Perl_parse_unicode_opts(pTHX_ char **popt)
4481 const char *p = *popt;
4486 opt = (U32) atoi(p);
4487 while (isDIGIT(*p)) p++;
4488 if (*p && *p != '\n' && *p != '\r')
4489 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4494 case PERL_UNICODE_STDIN:
4495 opt |= PERL_UNICODE_STDIN_FLAG; break;
4496 case PERL_UNICODE_STDOUT:
4497 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4498 case PERL_UNICODE_STDERR:
4499 opt |= PERL_UNICODE_STDERR_FLAG; break;
4500 case PERL_UNICODE_STD:
4501 opt |= PERL_UNICODE_STD_FLAG; break;
4502 case PERL_UNICODE_IN:
4503 opt |= PERL_UNICODE_IN_FLAG; break;
4504 case PERL_UNICODE_OUT:
4505 opt |= PERL_UNICODE_OUT_FLAG; break;
4506 case PERL_UNICODE_INOUT:
4507 opt |= PERL_UNICODE_INOUT_FLAG; break;
4508 case PERL_UNICODE_LOCALE:
4509 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4510 case PERL_UNICODE_ARGV:
4511 opt |= PERL_UNICODE_ARGV_FLAG; break;
4513 if (*p != '\n' && *p != '\r')
4515 "Unknown Unicode option letter '%c'", *p);
4521 opt = PERL_UNICODE_DEFAULT_FLAGS;
4523 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4524 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4525 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4527 /* Cast because we're not changing function prototypes in maint. */
4537 * This is really just a quick hack which grabs various garbage
4538 * values. It really should be a real hash algorithm which
4539 * spreads the effect of every input bit onto every output bit,
4540 * if someone who knows about such things would bother to write it.
4541 * Might be a good idea to add that function to CORE as well.
4542 * No numbers below come from careful analysis or anything here,
4543 * except they are primes and SEED_C1 > 1E6 to get a full-width
4544 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4545 * probably be bigger too.
4548 # define SEED_C1 1000003
4549 #define SEED_C4 73819
4551 # define SEED_C1 25747
4552 #define SEED_C4 20639
4556 #define SEED_C5 26107
4558 #ifndef PERL_NO_DEV_RANDOM
4563 # include <starlet.h>
4564 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4565 * in 100-ns units, typically incremented ever 10 ms. */
4566 unsigned int when[2];
4568 # ifdef HAS_GETTIMEOFDAY
4569 struct timeval when;
4575 /* This test is an escape hatch, this symbol isn't set by Configure. */
4576 #ifndef PERL_NO_DEV_RANDOM
4577 #ifndef PERL_RANDOM_DEVICE
4578 /* /dev/random isn't used by default because reads from it will block
4579 * if there isn't enough entropy available. You can compile with
4580 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4581 * is enough real entropy to fill the seed. */
4582 # define PERL_RANDOM_DEVICE "/dev/urandom"
4584 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4586 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4595 _ckvmssts(sys$gettim(when));
4596 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4598 # ifdef HAS_GETTIMEOFDAY
4599 PerlProc_gettimeofday(&when,NULL);
4600 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4603 u = (U32)SEED_C1 * when;
4606 u += SEED_C3 * (U32)PerlProc_getpid();
4607 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4608 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4609 u += SEED_C5 * (U32)PTR2UV(&when);
4615 Perl_get_hash_seed(pTHX)
4617 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4621 while (isSPACE(*s)) s++;
4622 if (s && isDIGIT(*s))
4623 myseed = (UV)Atoul(s);
4625 #ifdef USE_HASH_SEED_EXPLICIT
4629 /* Compute a random seed */
4630 (void)seedDrand01((Rand_seed_t)seed());
4631 myseed = (UV)(Drand01() * (NV)UV_MAX);
4632 #if RANDBITS < (UVSIZE * 8)
4633 /* Since there are not enough randbits to to reach all
4634 * the bits of a UV, the low bits might need extra
4635 * help. Sum in another random number that will
4636 * fill in the low bits. */
4638 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4639 #endif /* RANDBITS < (UVSIZE * 8) */
4640 if (myseed == 0) { /* Superparanoia. */
4641 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4643 Perl_croak(aTHX_ "Your random numbers are not that random");
4646 PL_rehash_seed_set = TRUE;
4653 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
4655 const char * const stashpv = CopSTASHPV(c);
4656 const char * const name = HvNAME_get(hv);
4658 if (stashpv == name)
4660 if (stashpv && name)
4661 if (strEQ(stashpv, name))
4668 Perl_my_clearenv(pTHX)
4670 #if ! defined(PERL_MICRO)
4671 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
4673 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
4674 # if defined(USE_ENVIRON_ARRAY)
4675 # if defined(USE_ITHREADS)
4676 /* only the parent thread can clobber the process environment */
4677 if (PL_curinterp == aTHX)
4678 # endif /* USE_ITHREADS */
4680 # if ! defined(PERL_USE_SAFE_PUTENV)
4681 if ( !PL_use_safe_putenv) {
4683 if (environ == PL_origenviron)
4684 environ = (char**)safesysmalloc(sizeof(char*));
4686 for (i = 0; environ[i]; i++)
4687 (void)safesysfree(environ[i]);
4690 # else /* PERL_USE_SAFE_PUTENV */
4691 # if defined(HAS_CLEARENV)
4693 # elif defined(HAS_UNSETENV)
4694 int bsiz = 80; /* Most envvar names will be shorter than this. */
4695 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
4696 while (*environ != NULL) {
4697 char *e = strchr(*environ, '=');
4698 int l = e ? e - *environ : strlen(*environ);
4700 (void)safesysfree(buf);
4702 buf = (char*)safesysmalloc(bsiz * sizeof(char));
4704 strncpy(buf, *environ, l);
4706 (void)unsetenv(buf);
4708 (void)safesysfree(buf);
4709 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
4710 /* Just null environ and accept the leakage. */
4712 # endif /* HAS_CLEARENV || HAS_UNSETENV */
4713 # endif /* ! PERL_USE_SAFE_PUTENV */
4715 # endif /* USE_ENVIRON_ARRAY */
4716 # endif /* PERL_IMPLICIT_SYS || WIN32 */
4717 #endif /* PERL_MICRO */
4722 * c-indentation-style: bsd
4724 * indent-tabs-mode: t
4727 * ex: set ts=8 sts=4 sw=4 noet: