3 * Copyright (c) 1991-2001, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12 * not content." --Gandalf
16 #define PERL_IN_UTIL_C
20 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
25 # define SIG_ERR ((Sighandler_t) -1)
33 /* Put this after #includes because fork and vfork prototypes may
41 # include <sys/wait.h>
48 long xcount[MAXXCOUNT];
49 long lastxcount[MAXXCOUNT];
50 long xycount[MAXXCOUNT][MAXYCOUNT];
51 long lastxycount[MAXXCOUNT][MAXYCOUNT];
55 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
56 # define FD_CLOEXEC 1 /* NeXT needs this */
59 /* paranoid version of system's malloc() */
61 /* NOTE: Do not call the next three routines directly. Use the macros
62 * in handy.h, so that we can easily redefine everything to do tracking of
63 * allocated hunks back to the original New to track down any memory leaks.
64 * XXX This advice seems to be widely ignored :-( --AD August 1996.
68 Perl_safesysmalloc(MEM_SIZE size)
74 PerlIO_printf(Perl_error_log,
75 "Allocation too large: %lx\n", size) FLUSH;
78 #endif /* HAS_64K_LIMIT */
81 Perl_croak_nocontext("panic: malloc");
83 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
84 PERL_ALLOC_CHECK(ptr);
85 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
91 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
98 /* paranoid version of system's realloc() */
101 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
105 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
106 Malloc_t PerlMem_realloc();
107 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
111 PerlIO_printf(Perl_error_log,
112 "Reallocation too large: %lx\n", size) FLUSH;
115 #endif /* HAS_64K_LIMIT */
122 return safesysmalloc(size);
125 Perl_croak_nocontext("panic: realloc");
127 ptr = (Malloc_t)PerlMem_realloc(where,size);
128 PERL_ALLOC_CHECK(ptr);
130 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
131 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
138 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
145 /* safe version of system's free() */
148 Perl_safesysfree(Malloc_t where)
150 #ifdef PERL_IMPLICIT_SYS
153 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
160 /* safe version of system's calloc() */
163 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
169 if (size * count > 0xffff) {
170 PerlIO_printf(Perl_error_log,
171 "Allocation too large: %lx\n", size * count) FLUSH;
174 #endif /* HAS_64K_LIMIT */
176 if ((long)size < 0 || (long)count < 0)
177 Perl_croak_nocontext("panic: calloc");
180 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
181 PERL_ALLOC_CHECK(ptr);
182 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));
184 memset((void*)ptr, 0, size);
190 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
199 struct mem_test_strut {
207 # define ALIGN sizeof(struct mem_test_strut)
209 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
210 # define typeof_chunk(ch) \
211 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
212 # define set_typeof_chunk(ch,t) \
213 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
214 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
217 ? ((size) - 1)/8 + 5 \
221 Perl_safexmalloc(I32 x, MEM_SIZE size)
223 register char* where = (char*)safemalloc(size + ALIGN);
226 xycount[x][SIZE_TO_Y(size)]++;
227 set_typeof_chunk(where, x);
228 sizeof_chunk(where) = size;
229 return (Malloc_t)(where + ALIGN);
233 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
235 char *where = (char*)wh;
238 return safexmalloc(0,size);
241 MEM_SIZE old = sizeof_chunk(where - ALIGN);
242 int t = typeof_chunk(where - ALIGN);
243 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
245 xycount[t][SIZE_TO_Y(old)]--;
246 xycount[t][SIZE_TO_Y(size)]++;
247 xcount[t] += size - old;
248 sizeof_chunk(new) = size;
249 return (Malloc_t)(new + ALIGN);
254 Perl_safexfree(Malloc_t wh)
257 char *where = (char*)wh;
263 size = sizeof_chunk(where);
264 x = where[0] + 100 * where[1];
266 xycount[x][SIZE_TO_Y(size)]--;
271 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
273 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
275 xycount[x][SIZE_TO_Y(size)]++;
276 memset((void*)(where + ALIGN), 0, size * count);
277 set_typeof_chunk(where, x);
278 sizeof_chunk(where) = size;
279 return (Malloc_t)(where + ALIGN);
283 S_xstat(pTHX_ int flag)
285 register I32 i, j, total = 0;
286 I32 subtot[MAXYCOUNT];
288 for (j = 0; j < MAXYCOUNT; j++) {
292 PerlIO_printf(Perl_debug_log, " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
293 for (i = 0; i < MAXXCOUNT; i++) {
295 for (j = 0; j < MAXYCOUNT; j++) {
296 subtot[j] += xycount[i][j];
299 ? xcount[i] /* Have something */
301 ? xcount[i] != lastxcount[i] /* Changed */
302 : xcount[i] > lastxcount[i])) { /* Growed */
303 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
304 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
305 lastxcount[i] = xcount[i];
306 for (j = 0; j < MAXYCOUNT; j++) {
308 ? xycount[i][j] /* Have something */
310 ? xycount[i][j] != lastxycount[i][j] /* Changed */
311 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
312 PerlIO_printf(Perl_debug_log,"%3ld ",
314 ? xycount[i][j] - lastxycount[i][j]
316 lastxycount[i][j] = xycount[i][j];
318 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
321 PerlIO_printf(Perl_debug_log, "\n");
325 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
326 for (j = 0; j < MAXYCOUNT; j++) {
328 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
330 PerlIO_printf(Perl_debug_log, " . ");
333 PerlIO_printf(Perl_debug_log, "\n");
337 #endif /* LEAKTEST */
339 /* copy a string up to some (non-backslashed) delimiter, if any */
342 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
345 for (tolen = 0; from < fromend; from++, tolen++) {
347 if (from[1] == delim)
356 else if (*from == delim)
367 /* return ptr to little string in big string, NULL if not found */
368 /* This routine was donated by Corey Satten. */
371 Perl_instr(pTHX_ register const char *big, register const char *little)
373 register const char *s, *x;
384 for (x=big,s=little; *s; /**/ ) {
393 return (char*)(big-1);
398 /* same as instr but allow embedded nulls */
401 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
403 register const char *s, *x;
404 register I32 first = *little;
405 register const char *littleend = lend;
407 if (!first && little >= littleend)
409 if (bigend - big < littleend - little)
411 bigend -= littleend - little++;
412 while (big <= bigend) {
415 for (x=big,s=little; s < littleend; /**/ ) {
422 return (char*)(big-1);
427 /* reverse of the above--find last substring */
430 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
432 register const char *bigbeg;
433 register const char *s, *x;
434 register I32 first = *little;
435 register const char *littleend = lend;
437 if (!first && little >= littleend)
438 return (char*)bigend;
440 big = bigend - (littleend - little++);
441 while (big >= bigbeg) {
444 for (x=big+2,s=little; s < littleend; /**/ ) {
451 return (char*)(big+1);
456 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
458 /* As a space optimization, we do not compile tables for strings of length
459 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
460 special-cased in fbm_instr().
462 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
465 =for apidoc fbm_compile
467 Analyses the string in order to make fast searches on it using fbm_instr()
468 -- the Boyer-Moore algorithm.
474 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
483 if (flags & FBMcf_TAIL)
484 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
485 s = (U8*)SvPV_force(sv, len);
486 (void)SvUPGRADE(sv, SVt_PVBM);
487 if (len == 0) /* TAIL might be on on a zero-length string. */
497 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
498 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
499 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
500 memset((void*)table, mlen, 256);
501 table[-1] = (U8)flags;
503 sb = s - mlen + 1; /* first char (maybe) */
505 if (table[*s] == mlen)
510 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
513 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
514 for (i = 0; i < len; i++) {
515 if (PL_freq[s[i]] < frequency) {
517 frequency = PL_freq[s[i]];
520 BmRARE(sv) = s[rarest];
521 BmPREVIOUS(sv) = rarest;
522 BmUSEFUL(sv) = 100; /* Initial value */
523 if (flags & FBMcf_TAIL)
525 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
526 BmRARE(sv),BmPREVIOUS(sv)));
529 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
530 /* If SvTAIL is actually due to \Z or \z, this gives false positives
534 =for apidoc fbm_instr
536 Returns the location of the SV in the string delimited by C<str> and
537 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
538 does not have to be fbm_compiled, but the search will not be as fast
545 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
547 register unsigned char *s;
549 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
550 register STRLEN littlelen = l;
551 register I32 multiline = flags & FBMrf_MULTILINE;
553 if (bigend - big < littlelen) {
554 if ( SvTAIL(littlestr)
555 && (bigend - big == littlelen - 1)
557 || (*big == *little &&
558 memEQ((char *)big, (char *)little, littlelen - 1))))
563 if (littlelen <= 2) { /* Special-cased */
565 if (littlelen == 1) {
566 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
567 /* Know that bigend != big. */
568 if (bigend[-1] == '\n')
569 return (char *)(bigend - 1);
570 return (char *) bigend;
578 if (SvTAIL(littlestr))
579 return (char *) bigend;
583 return (char*)big; /* Cannot be SvTAIL! */
586 if (SvTAIL(littlestr) && !multiline) {
587 if (bigend[-1] == '\n' && bigend[-2] == *little)
588 return (char*)bigend - 2;
589 if (bigend[-1] == *little)
590 return (char*)bigend - 1;
594 /* This should be better than FBM if c1 == c2, and almost
595 as good otherwise: maybe better since we do less indirection.
596 And we save a lot of memory by caching no table. */
597 register unsigned char c1 = little[0];
598 register unsigned char c2 = little[1];
603 while (s <= bigend) {
613 goto check_1char_anchor;
624 goto check_1char_anchor;
627 while (s <= bigend) {
632 goto check_1char_anchor;
641 check_1char_anchor: /* One char and anchor! */
642 if (SvTAIL(littlestr) && (*bigend == *little))
643 return (char *)bigend; /* bigend is already decremented. */
646 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
647 s = bigend - littlelen;
648 if (s >= big && bigend[-1] == '\n' && *s == *little
649 /* Automatically of length > 2 */
650 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
652 return (char*)s; /* how sweet it is */
655 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
657 return (char*)s + 1; /* how sweet it is */
661 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
662 char *b = ninstr((char*)big,(char*)bigend,
663 (char*)little, (char*)little + littlelen);
665 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
666 /* Chop \n from littlestr: */
667 s = bigend - littlelen + 1;
669 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
678 { /* Do actual FBM. */
679 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
680 register unsigned char *oldlittle;
682 if (littlelen > bigend - big)
684 --littlelen; /* Last char found by table lookup */
687 little += littlelen; /* last char */
694 if ((tmp = table[*s])) {
696 if (bigend - s > tmp) {
702 if ((s += tmp) < bigend)
707 else { /* less expensive than calling strncmp() */
708 register unsigned char *olds = s;
713 if (*--s == *--little)
715 s = olds + 1; /* here we pay the price for failure */
717 if (s < bigend) /* fake up continue to outer loop */
725 if ( s == bigend && (table[-1] & FBMcf_TAIL)
726 && memEQ((char *)(bigend - littlelen),
727 (char *)(oldlittle - littlelen), littlelen) )
728 return (char*)bigend - littlelen;
733 /* start_shift, end_shift are positive quantities which give offsets
734 of ends of some substring of bigstr.
735 If `last' we want the last occurence.
736 old_posp is the way of communication between consequent calls if
737 the next call needs to find the .
738 The initial *old_posp should be -1.
740 Note that we take into account SvTAIL, so one can get extra
741 optimizations if _ALL flag is set.
744 /* If SvTAIL is actually due to \Z or \z, this gives false positives
745 if PL_multiline. In fact if !PL_multiline the autoritative answer
746 is not supported yet. */
749 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
751 register unsigned char *s, *x;
752 register unsigned char *big;
754 register I32 previous;
756 register unsigned char *little;
757 register I32 stop_pos;
758 register unsigned char *littleend;
762 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
763 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
765 if ( BmRARE(littlestr) == '\n'
766 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
767 little = (unsigned char *)(SvPVX(littlestr));
768 littleend = little + SvCUR(littlestr);
775 little = (unsigned char *)(SvPVX(littlestr));
776 littleend = little + SvCUR(littlestr);
778 /* The value of pos we can start at: */
779 previous = BmPREVIOUS(littlestr);
780 big = (unsigned char *)(SvPVX(bigstr));
781 /* The value of pos we can stop at: */
782 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
783 if (previous + start_shift > stop_pos) {
784 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
788 while (pos < previous + start_shift) {
789 if (!(pos += PL_screamnext[pos]))
794 if (pos >= stop_pos) break;
795 if (big[pos-previous] != first)
797 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
803 if (s == littleend) {
805 if (!last) return (char *)(big+pos-previous);
808 } while ( pos += PL_screamnext[pos] );
809 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
810 #else /* !POINTERRIGOR */
813 if (pos >= stop_pos) break;
814 if (big[pos] != first)
816 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
822 if (s == littleend) {
824 if (!last) return (char *)(big+pos);
827 } while ( pos += PL_screamnext[pos] );
829 return (char *)(big+(*old_posp));
830 #endif /* POINTERRIGOR */
832 if (!SvTAIL(littlestr) || (end_shift > 0))
834 /* Ignore the trailing "\n". This code is not microoptimized */
835 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
836 stop_pos = littleend - little; /* Actual littlestr len */
841 && ((stop_pos == 1) ||
842 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
848 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
850 register U8 *a = (U8 *)s1;
851 register U8 *b = (U8 *)s2;
853 if (*a != *b && *a != PL_fold[*b])
861 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
863 register U8 *a = (U8 *)s1;
864 register U8 *b = (U8 *)s2;
866 if (*a != *b && *a != PL_fold_locale[*b])
873 /* copy a string to a safe spot */
878 Copy a string to a safe spot. This does not use an SV.
884 Perl_savepv(pTHX_ const char *sv)
886 register char *newaddr;
888 New(902,newaddr,strlen(sv)+1,char);
889 (void)strcpy(newaddr,sv);
893 /* same thing but with a known length */
898 Copy a string to a safe spot. The C<len> indicates number of bytes to
899 copy. This does not use an SV.
905 Perl_savepvn(pTHX_ const char *sv, register I32 len)
907 register char *newaddr;
909 New(903,newaddr,len+1,char);
910 Copy(sv,newaddr,len,char); /* might not be null terminated */
911 newaddr[len] = '\0'; /* is now */
915 /* the SV for Perl_form() and mess() is not kept in an arena */
924 return sv_2mortal(newSVpvn("",0));
929 /* Create as PVMG now, to avoid any upgrading later */
931 Newz(905, any, 1, XPVMG);
932 SvFLAGS(sv) = SVt_PVMG;
933 SvANY(sv) = (void*)any;
934 SvREFCNT(sv) = 1 << 30; /* practically infinite */
939 #if defined(PERL_IMPLICIT_CONTEXT)
941 Perl_form_nocontext(const char* pat, ...)
947 retval = vform(pat, &args);
951 #endif /* PERL_IMPLICIT_CONTEXT */
954 Perl_form(pTHX_ const char* pat, ...)
959 retval = vform(pat, &args);
965 Perl_vform(pTHX_ const char *pat, va_list *args)
967 SV *sv = mess_alloc();
968 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
972 #if defined(PERL_IMPLICIT_CONTEXT)
974 Perl_mess_nocontext(const char *pat, ...)
980 retval = vmess(pat, &args);
984 #endif /* PERL_IMPLICIT_CONTEXT */
987 Perl_mess(pTHX_ const char *pat, ...)
992 retval = vmess(pat, &args);
998 Perl_vmess(pTHX_ const char *pat, va_list *args)
1000 SV *sv = mess_alloc();
1001 static char dgd[] = " during global destruction.\n";
1003 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1004 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1005 if (CopLINE(PL_curcop))
1006 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1007 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1008 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1009 bool line_mode = (RsSIMPLE(PL_rs) &&
1010 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1011 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1012 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1013 line_mode ? "line" : "chunk",
1014 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1018 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1020 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1026 Perl_vdie(pTHX_ const char* pat, va_list *args)
1029 int was_in_eval = PL_in_eval;
1036 DEBUG_S(PerlIO_printf(Perl_debug_log,
1037 "%p: die: curstack = %p, mainstack = %p\n",
1038 thr, PL_curstack, PL_mainstack));
1041 msv = vmess(pat, args);
1042 if (PL_errors && SvCUR(PL_errors)) {
1043 sv_catsv(PL_errors, msv);
1044 message = SvPV(PL_errors, msglen);
1045 SvCUR_set(PL_errors, 0);
1048 message = SvPV(msv,msglen);
1055 DEBUG_S(PerlIO_printf(Perl_debug_log,
1056 "%p: die: message = %s\ndiehook = %p\n",
1057 thr, message, PL_diehook));
1059 /* sv_2cv might call Perl_croak() */
1060 SV *olddiehook = PL_diehook;
1062 SAVESPTR(PL_diehook);
1063 PL_diehook = Nullsv;
1064 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1066 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1073 msg = newSVpvn(message, msglen);
1081 PUSHSTACKi(PERLSI_DIEHOOK);
1085 call_sv((SV*)cv, G_DISCARD);
1091 PL_restartop = die_where(message, msglen);
1092 DEBUG_S(PerlIO_printf(Perl_debug_log,
1093 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1094 thr, PL_restartop, was_in_eval, PL_top_env));
1095 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1097 return PL_restartop;
1100 #if defined(PERL_IMPLICIT_CONTEXT)
1102 Perl_die_nocontext(const char* pat, ...)
1107 va_start(args, pat);
1108 o = vdie(pat, &args);
1112 #endif /* PERL_IMPLICIT_CONTEXT */
1115 Perl_die(pTHX_ const char* pat, ...)
1119 va_start(args, pat);
1120 o = vdie(pat, &args);
1126 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1136 msv = vmess(pat, args);
1137 if (PL_errors && SvCUR(PL_errors)) {
1138 sv_catsv(PL_errors, msv);
1139 message = SvPV(PL_errors, msglen);
1140 SvCUR_set(PL_errors, 0);
1143 message = SvPV(msv,msglen);
1150 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1151 PTR2UV(thr), message));
1154 /* sv_2cv might call Perl_croak() */
1155 SV *olddiehook = PL_diehook;
1157 SAVESPTR(PL_diehook);
1158 PL_diehook = Nullsv;
1159 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1161 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1168 msg = newSVpvn(message, msglen);
1176 PUSHSTACKi(PERLSI_DIEHOOK);
1180 call_sv((SV*)cv, G_DISCARD);
1186 PL_restartop = die_where(message, msglen);
1191 /* SFIO can really mess with your errno */
1194 PerlIO *serr = Perl_error_log;
1196 PerlIO_write(serr, message, msglen);
1197 (void)PerlIO_flush(serr);
1205 #if defined(PERL_IMPLICIT_CONTEXT)
1207 Perl_croak_nocontext(const char *pat, ...)
1211 va_start(args, pat);
1216 #endif /* PERL_IMPLICIT_CONTEXT */
1221 This is the XSUB-writer's interface to Perl's C<die> function.
1222 Normally use this function the same way you use the C C<printf>
1223 function. See C<warn>.
1225 If you want to throw an exception object, assign the object to
1226 C<$@> and then pass C<Nullch> to croak():
1228 errsv = get_sv("@", TRUE);
1229 sv_setsv(errsv, exception_object);
1236 Perl_croak(pTHX_ const char *pat, ...)
1239 va_start(args, pat);
1246 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1255 msv = vmess(pat, args);
1256 message = SvPV(msv, msglen);
1259 /* sv_2cv might call Perl_warn() */
1260 SV *oldwarnhook = PL_warnhook;
1262 SAVESPTR(PL_warnhook);
1263 PL_warnhook = Nullsv;
1264 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1266 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1272 msg = newSVpvn(message, msglen);
1276 PUSHSTACKi(PERLSI_WARNHOOK);
1280 call_sv((SV*)cv, G_DISCARD);
1287 PerlIO *serr = Perl_error_log;
1289 PerlIO_write(serr, message, msglen);
1291 DEBUG_L(*message == '!'
1292 ? (xstat(message[1]=='!'
1293 ? (message[2]=='!' ? 2 : 1)
1298 (void)PerlIO_flush(serr);
1302 #if defined(PERL_IMPLICIT_CONTEXT)
1304 Perl_warn_nocontext(const char *pat, ...)
1308 va_start(args, pat);
1312 #endif /* PERL_IMPLICIT_CONTEXT */
1317 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1318 function the same way you use the C C<printf> function. See
1325 Perl_warn(pTHX_ const char *pat, ...)
1328 va_start(args, pat);
1333 #if defined(PERL_IMPLICIT_CONTEXT)
1335 Perl_warner_nocontext(U32 err, const char *pat, ...)
1339 va_start(args, pat);
1340 vwarner(err, pat, &args);
1343 #endif /* PERL_IMPLICIT_CONTEXT */
1346 Perl_warner(pTHX_ U32 err, const char* pat,...)
1349 va_start(args, pat);
1350 vwarner(err, pat, &args);
1355 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1364 msv = vmess(pat, args);
1365 message = SvPV(msv, msglen);
1369 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1370 #endif /* USE_THREADS */
1372 /* sv_2cv might call Perl_croak() */
1373 SV *olddiehook = PL_diehook;
1375 SAVESPTR(PL_diehook);
1376 PL_diehook = Nullsv;
1377 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1379 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1385 msg = newSVpvn(message, msglen);
1389 PUSHSTACKi(PERLSI_DIEHOOK);
1393 call_sv((SV*)cv, G_DISCARD);
1399 PL_restartop = die_where(message, msglen);
1403 PerlIO *serr = Perl_error_log;
1404 PerlIO_write(serr, message, msglen);
1405 (void)PerlIO_flush(serr);
1412 /* sv_2cv might call Perl_warn() */
1413 SV *oldwarnhook = PL_warnhook;
1415 SAVESPTR(PL_warnhook);
1416 PL_warnhook = Nullsv;
1417 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1419 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1425 msg = newSVpvn(message, msglen);
1429 PUSHSTACKi(PERLSI_WARNHOOK);
1433 call_sv((SV*)cv, G_DISCARD);
1440 PerlIO *serr = Perl_error_log;
1441 PerlIO_write(serr, message, msglen);
1443 DEBUG_L(*message == '!'
1444 ? (xstat(message[1]=='!'
1445 ? (message[2]=='!' ? 2 : 1)
1450 (void)PerlIO_flush(serr);
1455 #ifdef USE_ENVIRON_ARRAY
1456 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1457 #if !defined(WIN32) && !defined(NETWARE)
1459 Perl_my_setenv(pTHX_ char *nam, char *val)
1461 #ifndef PERL_USE_SAFE_PUTENV
1462 /* most putenv()s leak, so we manipulate environ directly */
1463 register I32 i=setenv_getix(nam); /* where does it go? */
1465 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 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1475 strcpy(tmpenv[j], environ[j]);
1477 tmpenv[max] = Nullch;
1478 environ = tmpenv; /* tell exec where it is now */
1481 safesysfree(environ[i]);
1482 while (environ[i]) {
1483 environ[i] = environ[i+1];
1488 if (!environ[i]) { /* does not exist yet */
1489 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1490 environ[i+1] = Nullch; /* make sure it's null terminated */
1493 safesysfree(environ[i]);
1494 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1496 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1498 #else /* PERL_USE_SAFE_PUTENV */
1499 # if defined(__CYGWIN__)
1500 setenv(nam, val, 1);
1504 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1505 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1506 (void)putenv(new_env);
1507 # endif /* __CYGWIN__ */
1508 #endif /* PERL_USE_SAFE_PUTENV */
1511 #else /* WIN32 || NETWARE */
1514 Perl_my_setenv(pTHX_ char *nam,char *val)
1516 register char *envstr;
1517 STRLEN len = strlen(nam) + 3;
1522 New(904, envstr, len, char);
1523 (void)sprintf(envstr,"%s=%s",nam,val);
1524 (void)PerlEnv_putenv(envstr);
1528 #endif /* WIN32 || NETWARE */
1531 Perl_setenv_getix(pTHX_ char *nam)
1533 register I32 i, len = strlen(nam);
1535 for (i = 0; environ[i]; i++) {
1538 strnicmp(environ[i],nam,len) == 0
1540 strnEQ(environ[i],nam,len)
1542 && environ[i][len] == '=')
1543 break; /* strnEQ must come first to avoid */
1544 } /* potential SEGV's */
1548 #endif /* !VMS && !EPOC*/
1550 #ifdef UNLINK_ALL_VERSIONS
1552 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1556 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1561 /* this is a drop-in replacement for bcopy() */
1562 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1564 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1568 if (from - to >= 0) {
1576 *(--to) = *(--from);
1582 /* this is a drop-in replacement for memset() */
1585 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1595 /* this is a drop-in replacement for bzero() */
1596 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1598 Perl_my_bzero(register char *loc, register I32 len)
1608 /* this is a drop-in replacement for memcmp() */
1609 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1611 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1613 register U8 *a = (U8 *)s1;
1614 register U8 *b = (U8 *)s2;
1618 if (tmp = *a++ - *b++)
1623 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1627 #ifdef USE_CHAR_VSPRINTF
1632 vsprintf(char *dest, const char *pat, char *args)
1636 fakebuf._ptr = dest;
1637 fakebuf._cnt = 32767;
1641 fakebuf._flag = _IOWRT|_IOSTRG;
1642 _doprnt(pat, args, &fakebuf); /* what a kludge */
1643 (void)putc('\0', &fakebuf);
1644 #ifdef USE_CHAR_VSPRINTF
1647 return 0; /* perl doesn't use return value */
1651 #endif /* HAS_VPRINTF */
1654 #if BYTEORDER != 0x4321
1656 Perl_my_swap(pTHX_ short s)
1658 #if (BYTEORDER & 1) == 0
1661 result = ((s & 255) << 8) + ((s >> 8) & 255);
1669 Perl_my_htonl(pTHX_ long l)
1673 char c[sizeof(long)];
1676 #if BYTEORDER == 0x1234
1677 u.c[0] = (l >> 24) & 255;
1678 u.c[1] = (l >> 16) & 255;
1679 u.c[2] = (l >> 8) & 255;
1683 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1684 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1689 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1690 u.c[o & 0xf] = (l >> s) & 255;
1698 Perl_my_ntohl(pTHX_ long l)
1702 char c[sizeof(long)];
1705 #if BYTEORDER == 0x1234
1706 u.c[0] = (l >> 24) & 255;
1707 u.c[1] = (l >> 16) & 255;
1708 u.c[2] = (l >> 8) & 255;
1712 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1713 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1720 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1721 l |= (u.c[o & 0xf] & 255) << s;
1728 #endif /* BYTEORDER != 0x4321 */
1732 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1733 * If these functions are defined,
1734 * the BYTEORDER is neither 0x1234 nor 0x4321.
1735 * However, this is not assumed.
1739 #define HTOV(name,type) \
1741 name (register type n) \
1745 char c[sizeof(type)]; \
1749 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1750 u.c[i] = (n >> s) & 0xFF; \
1755 #define VTOH(name,type) \
1757 name (register type n) \
1761 char c[sizeof(type)]; \
1767 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1768 n += (u.c[i] & 0xFF) << s; \
1773 #if defined(HAS_HTOVS) && !defined(htovs)
1776 #if defined(HAS_HTOVL) && !defined(htovl)
1779 #if defined(HAS_VTOHS) && !defined(vtohs)
1782 #if defined(HAS_VTOHL) && !defined(vtohl)
1787 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1789 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1791 register I32 This, that;
1797 PERL_FLUSHALL_FOR_CHILD;
1798 This = (*mode == 'w');
1802 taint_proper("Insecure %s%s", "EXEC");
1804 if (PerlProc_pipe(p) < 0)
1806 /* Try for another pipe pair for error return */
1807 if (PerlProc_pipe(pp) >= 0)
1809 while ((pid = vfork()) < 0) {
1810 if (errno != EAGAIN) {
1811 PerlLIO_close(p[This]);
1813 PerlLIO_close(pp[0]);
1814 PerlLIO_close(pp[1]);
1826 /* Close parent's end of _the_ pipe */
1827 PerlLIO_close(p[THAT]);
1828 /* Close parent's end of error status pipe (if any) */
1830 PerlLIO_close(pp[0]);
1831 #if defined(HAS_FCNTL) && defined(F_SETFD)
1832 /* Close error pipe automatically if exec works */
1833 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1836 /* Now dup our end of _the_ pipe to right position */
1837 if (p[THIS] != (*mode == 'r')) {
1838 PerlLIO_dup2(p[THIS], *mode == 'r');
1839 PerlLIO_close(p[THIS]);
1841 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1842 /* No automatic close - do it by hand */
1849 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1855 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
1861 do_execfree(); /* free any memory malloced by child on vfork */
1862 /* Close child's end of pipe */
1863 PerlLIO_close(p[that]);
1865 PerlLIO_close(pp[1]);
1866 /* Keep the lower of the two fd numbers */
1867 if (p[that] < p[This]) {
1868 PerlLIO_dup2(p[This], p[that]);
1869 PerlLIO_close(p[This]);
1873 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1875 (void)SvUPGRADE(sv,SVt_IV);
1877 PL_forkprocess = pid;
1878 /* If we managed to get status pipe check for exec fail */
1879 if (did_pipes && pid > 0) {
1883 while (n < sizeof(int)) {
1884 n1 = PerlLIO_read(pp[0],
1885 (void*)(((char*)&errkid)+n),
1891 PerlLIO_close(pp[0]);
1893 if (n) { /* Error */
1895 if (n != sizeof(int))
1896 Perl_croak(aTHX_ "panic: kid popen errno read");
1898 pid2 = wait4pid(pid, &status, 0);
1899 } while (pid2 == -1 && errno == EINTR);
1900 errno = errkid; /* Propagate errno from kid */
1905 PerlLIO_close(pp[0]);
1906 return PerlIO_fdopen(p[This], mode);
1908 Perl_croak(aTHX_ "List form of piped open not implemented");
1909 return (PerlIO *) NULL;
1913 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1914 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
1916 Perl_my_popen(pTHX_ char *cmd, char *mode)
1919 register I32 This, that;
1922 I32 doexec = strNE(cmd,"-");
1926 PERL_FLUSHALL_FOR_CHILD;
1929 return my_syspopen(aTHX_ cmd,mode);
1932 This = (*mode == 'w');
1934 if (doexec && PL_tainting) {
1936 taint_proper("Insecure %s%s", "EXEC");
1938 if (PerlProc_pipe(p) < 0)
1940 if (doexec && PerlProc_pipe(pp) >= 0)
1942 while ((pid = (doexec?vfork():fork())) < 0) {
1943 if (errno != EAGAIN) {
1944 PerlLIO_close(p[This]);
1946 PerlLIO_close(pp[0]);
1947 PerlLIO_close(pp[1]);
1950 Perl_croak(aTHX_ "Can't fork");
1962 PerlLIO_close(p[THAT]);
1964 PerlLIO_close(pp[0]);
1965 #if defined(HAS_FCNTL) && defined(F_SETFD)
1966 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1969 if (p[THIS] != (*mode == 'r')) {
1970 PerlLIO_dup2(p[THIS], *mode == 'r');
1971 PerlLIO_close(p[THIS]);
1975 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1984 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
1989 /* may or may not use the shell */
1990 do_exec3(cmd, pp[1], did_pipes);
1993 #endif /* defined OS2 */
1995 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
1996 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
1998 hv_clear(PL_pidstatus); /* we have no children */
2003 do_execfree(); /* free any memory malloced by child on vfork */
2004 PerlLIO_close(p[that]);
2006 PerlLIO_close(pp[1]);
2007 if (p[that] < p[This]) {
2008 PerlLIO_dup2(p[This], p[that]);
2009 PerlLIO_close(p[This]);
2013 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2015 (void)SvUPGRADE(sv,SVt_IV);
2017 PL_forkprocess = pid;
2018 if (did_pipes && pid > 0) {
2022 while (n < sizeof(int)) {
2023 n1 = PerlLIO_read(pp[0],
2024 (void*)(((char*)&errkid)+n),
2030 PerlLIO_close(pp[0]);
2032 if (n) { /* Error */
2034 if (n != sizeof(int))
2035 Perl_croak(aTHX_ "panic: kid popen errno read");
2037 pid2 = wait4pid(pid, &status, 0);
2038 } while (pid2 == -1 && errno == EINTR);
2039 errno = errkid; /* Propagate errno from kid */
2044 PerlLIO_close(pp[0]);
2045 return PerlIO_fdopen(p[This], mode);
2048 #if defined(atarist) || defined(DJGPP)
2051 Perl_my_popen(pTHX_ char *cmd, char *mode)
2053 PERL_FLUSHALL_FOR_CHILD;
2054 /* Call system's popen() to get a FILE *, then import it.
2055 used 0 for 2nd parameter to PerlIO_importFILE;
2058 return PerlIO_importFILE(popen(cmd, mode), 0);
2062 #endif /* !DOSISH */
2066 Perl_dump_fds(pTHX_ char *s)
2069 struct stat tmpstatbuf;
2071 PerlIO_printf(Perl_debug_log,"%s", s);
2072 for (fd = 0; fd < 32; fd++) {
2073 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2074 PerlIO_printf(Perl_debug_log," %d",fd);
2076 PerlIO_printf(Perl_debug_log,"\n");
2078 #endif /* DUMP_FDS */
2082 dup2(int oldfd, int newfd)
2084 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2087 PerlLIO_close(newfd);
2088 return fcntl(oldfd, F_DUPFD, newfd);
2090 #define DUP2_MAX_FDS 256
2091 int fdtmp[DUP2_MAX_FDS];
2097 PerlLIO_close(newfd);
2098 /* good enough for low fd's... */
2099 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2100 if (fdx >= DUP2_MAX_FDS) {
2108 PerlLIO_close(fdtmp[--fdx]);
2115 #ifdef HAS_SIGACTION
2118 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2120 struct sigaction act, oact;
2122 act.sa_handler = handler;
2123 sigemptyset(&act.sa_mask);
2126 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2127 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2131 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2132 act.sa_flags |= SA_NOCLDWAIT;
2134 if (sigaction(signo, &act, &oact) == -1)
2137 return oact.sa_handler;
2141 Perl_rsignal_state(pTHX_ int signo)
2143 struct sigaction oact;
2145 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2148 return oact.sa_handler;
2152 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2154 struct sigaction act;
2156 act.sa_handler = handler;
2157 sigemptyset(&act.sa_mask);
2160 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2161 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2165 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2166 act.sa_flags |= SA_NOCLDWAIT;
2168 return sigaction(signo, &act, save);
2172 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2174 return sigaction(signo, save, (struct sigaction *)NULL);
2177 #else /* !HAS_SIGACTION */
2180 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2182 return PerlProc_signal(signo, handler);
2185 static int sig_trapped;
2195 Perl_rsignal_state(pTHX_ int signo)
2197 Sighandler_t oldsig;
2200 oldsig = PerlProc_signal(signo, sig_trap);
2201 PerlProc_signal(signo, oldsig);
2203 PerlProc_kill(PerlProc_getpid(), signo);
2208 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2210 *save = PerlProc_signal(signo, handler);
2211 return (*save == SIG_ERR) ? -1 : 0;
2215 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2217 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2220 #endif /* !HAS_SIGACTION */
2221 #endif /* !PERL_MICRO */
2223 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2224 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2226 Perl_my_pclose(pTHX_ PerlIO *ptr)
2228 Sigsave_t hstat, istat, qstat;
2234 int saved_errno = 0;
2236 int saved_vaxc_errno;
2239 int saved_win32_errno;
2243 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2245 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2247 *svp = &PL_sv_undef;
2249 if (pid == -1) { /* Opened by popen. */
2250 return my_syspclose(ptr);
2253 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2254 saved_errno = errno;
2256 saved_vaxc_errno = vaxc$errno;
2259 saved_win32_errno = GetLastError();
2263 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2266 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2267 rsignal_save(SIGINT, SIG_IGN, &istat);
2268 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2271 pid2 = wait4pid(pid, &status, 0);
2272 } while (pid2 == -1 && errno == EINTR);
2274 rsignal_restore(SIGHUP, &hstat);
2275 rsignal_restore(SIGINT, &istat);
2276 rsignal_restore(SIGQUIT, &qstat);
2279 SETERRNO(saved_errno, saved_vaxc_errno);
2282 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2284 #endif /* !DOSISH */
2286 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2288 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2292 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2296 char spid[TYPE_CHARS(int)];
2299 sprintf(spid, "%"IVdf, (IV)pid);
2300 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2301 if (svp && *svp != &PL_sv_undef) {
2302 *statusp = SvIVX(*svp);
2303 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2310 hv_iterinit(PL_pidstatus);
2311 if ((entry = hv_iternext(PL_pidstatus))) {
2312 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2313 sv = hv_iterval(PL_pidstatus,entry);
2314 *statusp = SvIVX(sv);
2315 sprintf(spid, "%"IVdf, (IV)pid);
2316 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2323 # ifdef HAS_WAITPID_RUNTIME
2324 if (!HAS_WAITPID_RUNTIME)
2327 return PerlProc_waitpid(pid,statusp,flags);
2329 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2330 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2332 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2337 Perl_croak(aTHX_ "Can't do waitpid with flags");
2339 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2340 pidgone(result,*statusp);
2348 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2352 Perl_pidgone(pTHX_ Pid_t pid, int status)
2355 char spid[TYPE_CHARS(int)];
2357 sprintf(spid, "%"IVdf, (IV)pid);
2358 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2359 (void)SvUPGRADE(sv,SVt_IV);
2364 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2367 int /* Cannot prototype with I32
2369 my_syspclose(PerlIO *ptr)
2372 Perl_my_pclose(pTHX_ PerlIO *ptr)
2375 /* Needs work for PerlIO ! */
2376 FILE *f = PerlIO_findFILE(ptr);
2377 I32 result = pclose(f);
2379 result = (result << 8) & 0xff00;
2381 PerlIO_releaseFILE(ptr,f);
2387 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2390 register const char *frombase = from;
2393 register const char c = *from;
2398 while (count-- > 0) {
2399 for (todo = len; todo > 0; todo--) {
2408 Perl_same_dirent(pTHX_ char *a, char *b)
2410 char *fa = strrchr(a,'/');
2411 char *fb = strrchr(b,'/');
2412 struct stat tmpstatbuf1;
2413 struct stat tmpstatbuf2;
2414 SV *tmpsv = sv_newmortal();
2427 sv_setpv(tmpsv, ".");
2429 sv_setpvn(tmpsv, a, fa - a);
2430 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2433 sv_setpv(tmpsv, ".");
2435 sv_setpvn(tmpsv, b, fb - b);
2436 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2438 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2439 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2441 #endif /* !HAS_RENAME */
2444 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2446 char *xfound = Nullch;
2447 char *xfailed = Nullch;
2448 char tmpbuf[MAXPATHLEN];
2452 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2453 # define SEARCH_EXTS ".bat", ".cmd", NULL
2454 # define MAX_EXT_LEN 4
2457 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2458 # define MAX_EXT_LEN 4
2461 # define SEARCH_EXTS ".pl", ".com", NULL
2462 # define MAX_EXT_LEN 4
2464 /* additional extensions to try in each dir if scriptname not found */
2466 char *exts[] = { SEARCH_EXTS };
2467 char **ext = search_ext ? search_ext : exts;
2468 int extidx = 0, i = 0;
2469 char *curext = Nullch;
2471 # define MAX_EXT_LEN 0
2475 * If dosearch is true and if scriptname does not contain path
2476 * delimiters, search the PATH for scriptname.
2478 * If SEARCH_EXTS is also defined, will look for each
2479 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2480 * while searching the PATH.
2482 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2483 * proceeds as follows:
2484 * If DOSISH or VMSISH:
2485 * + look for ./scriptname{,.foo,.bar}
2486 * + search the PATH for scriptname{,.foo,.bar}
2489 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2490 * this will not look in '.' if it's not in the PATH)
2495 # ifdef ALWAYS_DEFTYPES
2496 len = strlen(scriptname);
2497 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2498 int hasdir, idx = 0, deftypes = 1;
2501 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2504 int hasdir, idx = 0, deftypes = 1;
2507 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2509 /* The first time through, just add SEARCH_EXTS to whatever we
2510 * already have, so we can check for default file types. */
2512 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2518 if ((strlen(tmpbuf) + strlen(scriptname)
2519 + MAX_EXT_LEN) >= sizeof tmpbuf)
2520 continue; /* don't search dir with too-long name */
2521 strcat(tmpbuf, scriptname);
2525 if (strEQ(scriptname, "-"))
2527 if (dosearch) { /* Look in '.' first. */
2528 char *cur = scriptname;
2530 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2532 if (strEQ(ext[i++],curext)) {
2533 extidx = -1; /* already has an ext */
2538 DEBUG_p(PerlIO_printf(Perl_debug_log,
2539 "Looking for %s\n",cur));
2540 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2541 && !S_ISDIR(PL_statbuf.st_mode)) {
2549 if (cur == scriptname) {
2550 len = strlen(scriptname);
2551 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2553 cur = strcpy(tmpbuf, scriptname);
2555 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2556 && strcpy(tmpbuf+len, ext[extidx++]));
2561 #ifdef MACOS_TRADITIONAL
2562 if (dosearch && !strchr(scriptname, ':') &&
2563 (s = PerlEnv_getenv("Commands")))
2565 if (dosearch && !strchr(scriptname, '/')
2567 && !strchr(scriptname, '\\')
2569 && (s = PerlEnv_getenv("PATH")))
2574 PL_bufend = s + strlen(s);
2575 while (s < PL_bufend) {
2576 #ifdef MACOS_TRADITIONAL
2577 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2581 #if defined(atarist) || defined(DOSISH)
2586 && *s != ';'; len++, s++) {
2587 if (len < sizeof tmpbuf)
2590 if (len < sizeof tmpbuf)
2592 #else /* ! (atarist || DOSISH) */
2593 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2596 #endif /* ! (atarist || DOSISH) */
2597 #endif /* MACOS_TRADITIONAL */
2600 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2601 continue; /* don't search dir with too-long name */
2602 #ifdef MACOS_TRADITIONAL
2603 if (len && tmpbuf[len - 1] != ':')
2604 tmpbuf[len++] = ':';
2607 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2608 && tmpbuf[len - 1] != '/'
2609 && tmpbuf[len - 1] != '\\'
2612 tmpbuf[len++] = '/';
2613 if (len == 2 && tmpbuf[0] == '.')
2616 (void)strcpy(tmpbuf + len, scriptname);
2620 len = strlen(tmpbuf);
2621 if (extidx > 0) /* reset after previous loop */
2625 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2626 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2627 if (S_ISDIR(PL_statbuf.st_mode)) {
2631 } while ( retval < 0 /* not there */
2632 && extidx>=0 && ext[extidx] /* try an extension? */
2633 && strcpy(tmpbuf+len, ext[extidx++])
2638 if (S_ISREG(PL_statbuf.st_mode)
2639 && cando(S_IRUSR,TRUE,&PL_statbuf)
2640 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2641 && cando(S_IXUSR,TRUE,&PL_statbuf)
2645 xfound = tmpbuf; /* bingo! */
2649 xfailed = savepv(tmpbuf);
2652 if (!xfound && !seen_dot && !xfailed &&
2653 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2654 || S_ISDIR(PL_statbuf.st_mode)))
2656 seen_dot = 1; /* Disable message. */
2658 if (flags & 1) { /* do or die? */
2659 Perl_croak(aTHX_ "Can't %s %s%s%s",
2660 (xfailed ? "execute" : "find"),
2661 (xfailed ? xfailed : scriptname),
2662 (xfailed ? "" : " on PATH"),
2663 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2665 scriptname = Nullch;
2669 scriptname = xfound;
2671 return (scriptname ? savepv(scriptname) : Nullch);
2674 #ifndef PERL_GET_CONTEXT_DEFINED
2677 Perl_get_context(void)
2679 #if defined(USE_THREADS) || defined(USE_ITHREADS)
2680 # ifdef OLD_PTHREADS_API
2682 if (pthread_getspecific(PL_thr_key, &t))
2683 Perl_croak_nocontext("panic: pthread_getspecific");
2686 # ifdef I_MACH_CTHREADS
2687 return (void*)cthread_data(cthread_self());
2689 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2698 Perl_set_context(void *t)
2700 #if defined(USE_THREADS) || defined(USE_ITHREADS)
2701 # ifdef I_MACH_CTHREADS
2702 cthread_set_data(cthread_self(), t);
2704 if (pthread_setspecific(PL_thr_key, t))
2705 Perl_croak_nocontext("panic: pthread_setspecific");
2710 #endif /* !PERL_GET_CONTEXT_DEFINED */
2715 /* Very simplistic scheduler for now */
2719 thr = thr->i.next_run;
2723 Perl_cond_init(pTHX_ perl_cond *cp)
2729 Perl_cond_signal(pTHX_ perl_cond *cp)
2732 perl_cond cond = *cp;
2737 /* Insert t in the runnable queue just ahead of us */
2738 t->i.next_run = thr->i.next_run;
2739 thr->i.next_run->i.prev_run = t;
2740 t->i.prev_run = thr;
2741 thr->i.next_run = t;
2742 thr->i.wait_queue = 0;
2743 /* Remove from the wait queue */
2749 Perl_cond_broadcast(pTHX_ perl_cond *cp)
2752 perl_cond cond, cond_next;
2754 for (cond = *cp; cond; cond = cond_next) {
2756 /* Insert t in the runnable queue just ahead of us */
2757 t->i.next_run = thr->i.next_run;
2758 thr->i.next_run->i.prev_run = t;
2759 t->i.prev_run = thr;
2760 thr->i.next_run = t;
2761 thr->i.wait_queue = 0;
2762 /* Remove from the wait queue */
2763 cond_next = cond->next;
2770 Perl_cond_wait(pTHX_ perl_cond *cp)
2774 if (thr->i.next_run == thr)
2775 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
2777 New(666, cond, 1, struct perl_wait_queue);
2781 thr->i.wait_queue = cond;
2782 /* Remove ourselves from runnable queue */
2783 thr->i.next_run->i.prev_run = thr->i.prev_run;
2784 thr->i.prev_run->i.next_run = thr->i.next_run;
2786 #endif /* FAKE_THREADS */
2789 Perl_condpair_magic(pTHX_ SV *sv)
2793 SvUPGRADE(sv, SVt_PVMG);
2794 mg = mg_find(sv, PERL_MAGIC_mutex);
2798 New(53, cp, 1, condpair_t);
2799 MUTEX_INIT(&cp->mutex);
2800 COND_INIT(&cp->owner_cond);
2801 COND_INIT(&cp->cond);
2803 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
2804 mg = mg_find(sv, PERL_MAGIC_mutex);
2806 /* someone else beat us to initialising it */
2807 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2808 MUTEX_DESTROY(&cp->mutex);
2809 COND_DESTROY(&cp->owner_cond);
2810 COND_DESTROY(&cp->cond);
2814 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
2816 mg->mg_ptr = (char *)cp;
2817 mg->mg_len = sizeof(cp);
2818 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2819 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
2820 "%p: condpair_magic %p\n", thr, sv));)
2827 Perl_sv_lock(pTHX_ SV *osv)
2837 mg = condpair_magic(sv);
2838 MUTEX_LOCK(MgMUTEXP(mg));
2839 if (MgOWNER(mg) == thr)
2840 MUTEX_UNLOCK(MgMUTEXP(mg));
2843 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
2845 DEBUG_S(PerlIO_printf(Perl_debug_log,
2846 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
2847 PTR2UV(thr), PTR2UV(sv));)
2848 MUTEX_UNLOCK(MgMUTEXP(mg));
2849 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
2851 UNLOCK_SV_LOCK_MUTEX;
2856 * Make a new perl thread structure using t as a prototype. Some of the
2857 * fields for the new thread are copied from the prototype thread, t,
2858 * so t should not be running in perl at the time this function is
2859 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2860 * thread calling new_struct_thread) clearly satisfies this constraint.
2862 struct perl_thread *
2863 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
2865 #if !defined(PERL_IMPLICIT_CONTEXT)
2866 struct perl_thread *thr;
2872 sv = newSVpvn("", 0);
2873 SvGROW(sv, sizeof(struct perl_thread) + 1);
2874 SvCUR_set(sv, sizeof(struct perl_thread));
2875 thr = (Thread) SvPVX(sv);
2877 memset(thr, 0xab, sizeof(struct perl_thread));
2884 Zero(&PL_hv_fetch_ent_mh, 1, HE);
2885 PL_efloatbuf = (char*)NULL;
2888 Zero(thr, 1, struct perl_thread);
2894 PL_curcop = &PL_compiling;
2895 thr->interp = t->interp;
2896 thr->cvcache = newHV();
2897 thr->threadsv = newAV();
2898 thr->specific = newAV();
2899 thr->errsv = newSVpvn("", 0);
2900 thr->flags = THRf_R_JOINABLE;
2902 MUTEX_INIT(&thr->mutex);
2906 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
2909 PL_statname = NEWSV(66,0);
2910 PL_errors = newSVpvn("", 0);
2912 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
2913 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
2914 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
2915 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
2916 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
2918 PL_reginterp_cnt = 0;
2919 PL_lastscream = Nullsv;
2922 PL_reg_start_tmp = 0;
2923 PL_reg_start_tmpl = 0;
2924 PL_reg_poscache = Nullch;
2926 /* parent thread's data needs to be locked while we make copy */
2927 MUTEX_LOCK(&t->mutex);
2929 #ifdef PERL_FLEXIBLE_EXCEPTIONS
2930 PL_protect = t->Tprotect;
2933 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
2934 PL_defstash = t->Tdefstash; /* XXX maybe these should */
2935 PL_curstash = t->Tcurstash; /* always be set to main? */
2937 PL_tainted = t->Ttainted;
2938 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
2939 PL_nrs = newSVsv(t->Tnrs);
2940 PL_rs = t->Tnrs ? SvREFCNT_inc(PL_nrs) : Nullsv;
2941 PL_last_in_gv = Nullgv;
2942 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
2943 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2944 PL_chopset = t->Tchopset;
2945 PL_bodytarget = newSVsv(t->Tbodytarget);
2946 PL_toptarget = newSVsv(t->Ttoptarget);
2947 if (t->Tformtarget == t->Ttoptarget)
2948 PL_formtarget = PL_toptarget;
2950 PL_formtarget = PL_bodytarget;
2952 /* Initialise all per-thread SVs that the template thread used */
2953 svp = AvARRAY(t->threadsv);
2954 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
2955 if (*svp && *svp != &PL_sv_undef) {
2956 SV *sv = newSVsv(*svp);
2957 av_store(thr->threadsv, i, sv);
2958 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
2959 DEBUG_S(PerlIO_printf(Perl_debug_log,
2960 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
2964 thr->threadsvp = AvARRAY(thr->threadsv);
2966 MUTEX_LOCK(&PL_threads_mutex);
2968 thr->tid = ++PL_threadnum;
2969 thr->next = t->next;
2972 thr->next->prev = thr;
2973 MUTEX_UNLOCK(&PL_threads_mutex);
2975 /* done copying parent's state */
2976 MUTEX_UNLOCK(&t->mutex);
2978 #ifdef HAVE_THREAD_INTERN
2979 Perl_init_thread_intern(thr);
2980 #endif /* HAVE_THREAD_INTERN */
2983 #endif /* USE_THREADS */
2985 #ifdef PERL_GLOBAL_STRUCT
2994 Perl_get_op_names(pTHX)
3000 Perl_get_op_descs(pTHX)
3006 Perl_get_no_modify(pTHX)
3008 return (char*)PL_no_modify;
3012 Perl_get_opargs(pTHX)
3018 Perl_get_ppaddr(pTHX)
3020 return (PPADDR_t*)PL_ppaddr;
3023 #ifndef HAS_GETENV_LEN
3025 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3027 char *env_trans = PerlEnv_getenv(env_elem);
3029 *len = strlen(env_trans);
3036 Perl_get_vtbl(pTHX_ int vtbl_id)
3038 MGVTBL* result = Null(MGVTBL*);
3042 result = &PL_vtbl_sv;
3045 result = &PL_vtbl_env;
3047 case want_vtbl_envelem:
3048 result = &PL_vtbl_envelem;
3051 result = &PL_vtbl_sig;
3053 case want_vtbl_sigelem:
3054 result = &PL_vtbl_sigelem;
3056 case want_vtbl_pack:
3057 result = &PL_vtbl_pack;
3059 case want_vtbl_packelem:
3060 result = &PL_vtbl_packelem;
3062 case want_vtbl_dbline:
3063 result = &PL_vtbl_dbline;
3066 result = &PL_vtbl_isa;
3068 case want_vtbl_isaelem:
3069 result = &PL_vtbl_isaelem;
3071 case want_vtbl_arylen:
3072 result = &PL_vtbl_arylen;
3074 case want_vtbl_glob:
3075 result = &PL_vtbl_glob;
3077 case want_vtbl_mglob:
3078 result = &PL_vtbl_mglob;
3080 case want_vtbl_nkeys:
3081 result = &PL_vtbl_nkeys;
3083 case want_vtbl_taint:
3084 result = &PL_vtbl_taint;
3086 case want_vtbl_substr:
3087 result = &PL_vtbl_substr;
3090 result = &PL_vtbl_vec;
3093 result = &PL_vtbl_pos;
3096 result = &PL_vtbl_bm;
3099 result = &PL_vtbl_fm;
3101 case want_vtbl_uvar:
3102 result = &PL_vtbl_uvar;
3105 case want_vtbl_mutex:
3106 result = &PL_vtbl_mutex;
3109 case want_vtbl_defelem:
3110 result = &PL_vtbl_defelem;
3112 case want_vtbl_regexp:
3113 result = &PL_vtbl_regexp;
3115 case want_vtbl_regdata:
3116 result = &PL_vtbl_regdata;
3118 case want_vtbl_regdatum:
3119 result = &PL_vtbl_regdatum;
3121 #ifdef USE_LOCALE_COLLATE
3122 case want_vtbl_collxfrm:
3123 result = &PL_vtbl_collxfrm;
3126 case want_vtbl_amagic:
3127 result = &PL_vtbl_amagic;
3129 case want_vtbl_amagicelem:
3130 result = &PL_vtbl_amagicelem;
3132 case want_vtbl_backref:
3133 result = &PL_vtbl_backref;
3140 Perl_my_fflush_all(pTHX)
3142 #if defined(FFLUSH_NULL)
3143 return PerlIO_flush(NULL);
3145 # if defined(HAS__FWALK)
3146 /* undocumented, unprototyped, but very useful BSDism */
3147 extern void _fwalk(int (*)(FILE *));
3151 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3153 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3154 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3156 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3157 open_max = sysconf(_SC_OPEN_MAX);
3160 open_max = FOPEN_MAX;
3163 open_max = OPEN_MAX;
3174 for (i = 0; i < open_max; i++)
3175 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3176 STDIO_STREAM_ARRAY[i]._file < open_max &&
3177 STDIO_STREAM_ARRAY[i]._flag)
3178 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3182 SETERRNO(EBADF,RMS$_IFI);
3189 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3194 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3195 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3197 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3198 char *type = OP_IS_SOCKET(op) ||
3199 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3200 "socket" : "filehandle";
3203 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3205 warn_type = WARN_CLOSED;
3209 warn_type = WARN_UNOPENED;
3212 if (gv && isGV(gv)) {
3213 SV *sv = sv_newmortal();
3214 gv_efullname4(sv, gv, Nullch, FALSE);
3218 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3220 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
3222 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3224 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
3225 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3226 } else if (name && *name) {
3227 Perl_warner(aTHX_ warn_type,
3228 "%s%s on %s %s %s", func, pars, vile, type, name);
3229 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3230 Perl_warner(aTHX_ warn_type,
3231 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3235 Perl_warner(aTHX_ warn_type,
3236 "%s%s on %s %s", func, pars, vile, type);
3237 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3238 Perl_warner(aTHX_ warn_type,
3239 "\t(Are you trying to call %s%s on dirhandle?)\n",
3245 /* in ASCII order, not that it matters */
3246 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3249 Perl_ebcdic_control(pTHX_ int ch)
3257 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3258 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3261 if (ctlp == controllablechars)
3262 return('\177'); /* DEL */
3264 return((unsigned char)(ctlp - controllablechars - 1));
3265 } else { /* Want uncontrol */
3266 if (ch == '\177' || ch == -1)
3268 else if (ch == '\157')
3270 else if (ch == '\174')
3272 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3274 else if (ch == '\155')
3276 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3277 return(controllablechars[ch+1]);
3279 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3284 /* XXX struct tm on some systems (SunOS4/BSD) contains extra (non POSIX)
3285 * fields for which we don't have Configure support yet:
3286 * char *tm_zone; -- abbreviation of timezone name
3287 * long tm_gmtoff; -- offset from GMT in seconds
3288 * To workaround core dumps from the uninitialised tm_zone we get the
3289 * system to give us a reasonable struct to copy. This fix means that
3290 * strftime uses the tm_zone and tm_gmtoff values returned by
3291 * localtime(time()). That should give the desired result most of the
3292 * time. But probably not always!
3294 * This is a temporary workaround to be removed once Configure
3295 * support is added and NETaa14816 is considered in full.
3296 * It does not address tzname aspects of NETaa14816.
3299 # ifndef STRUCT_TM_HASZONE
3300 # define STRUCT_TM_HASZONE
3305 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3307 #ifdef STRUCT_TM_HASZONE
3310 Copy(localtime(&now), ptm, 1, struct tm);
3315 * mini_mktime - normalise struct tm values without the localtime()
3316 * semantics (and overhead) of mktime().
3319 Perl_mini_mktime(pTHX_ struct tm *ptm)
3323 int month, mday, year, jday;
3324 int odd_cent, odd_year;
3326 #define DAYS_PER_YEAR 365
3327 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3328 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3329 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3330 #define SECS_PER_HOUR (60*60)
3331 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3332 /* parentheses deliberately absent on these two, otherwise they don't work */
3333 #define MONTH_TO_DAYS 153/5
3334 #define DAYS_TO_MONTH 5/153
3335 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3336 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3337 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3338 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3341 * Year/day algorithm notes:
3343 * With a suitable offset for numeric value of the month, one can find
3344 * an offset into the year by considering months to have 30.6 (153/5) days,
3345 * using integer arithmetic (i.e., with truncation). To avoid too much
3346 * messing about with leap days, we consider January and February to be
3347 * the 13th and 14th month of the previous year. After that transformation,
3348 * we need the month index we use to be high by 1 from 'normal human' usage,
3349 * so the month index values we use run from 4 through 15.
3351 * Given that, and the rules for the Gregorian calendar (leap years are those
3352 * divisible by 4 unless also divisible by 100, when they must be divisible
3353 * by 400 instead), we can simply calculate the number of days since some
3354 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3355 * the days we derive from our month index, and adding in the day of the
3356 * month. The value used here is not adjusted for the actual origin which
3357 * it normally would use (1 January A.D. 1), since we're not exposing it.
3358 * We're only building the value so we can turn around and get the
3359 * normalised values for the year, month, day-of-month, and day-of-year.
3361 * For going backward, we need to bias the value we're using so that we find
3362 * the right year value. (Basically, we don't want the contribution of
3363 * March 1st to the number to apply while deriving the year). Having done
3364 * that, we 'count up' the contribution to the year number by accounting for
3365 * full quadracenturies (400-year periods) with their extra leap days, plus
3366 * the contribution from full centuries (to avoid counting in the lost leap
3367 * days), plus the contribution from full quad-years (to count in the normal
3368 * leap days), plus the leftover contribution from any non-leap years.
3369 * At this point, if we were working with an actual leap day, we'll have 0
3370 * days left over. This is also true for March 1st, however. So, we have
3371 * to special-case that result, and (earlier) keep track of the 'odd'
3372 * century and year contributions. If we got 4 extra centuries in a qcent,
3373 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3374 * Otherwise, we add back in the earlier bias we removed (the 123 from
3375 * figuring in March 1st), find the month index (integer division by 30.6),
3376 * and the remainder is the day-of-month. We then have to convert back to
3377 * 'real' months (including fixing January and February from being 14/15 in
3378 * the previous year to being in the proper year). After that, to get
3379 * tm_yday, we work with the normalised year and get a new yearday value for
3380 * January 1st, which we subtract from the yearday value we had earlier,
3381 * representing the date we've re-built. This is done from January 1
3382 * because tm_yday is 0-origin.
3384 * Since POSIX time routines are only guaranteed to work for times since the
3385 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3386 * applies Gregorian calendar rules even to dates before the 16th century
3387 * doesn't bother me. Besides, you'd need cultural context for a given
3388 * date to know whether it was Julian or Gregorian calendar, and that's
3389 * outside the scope for this routine. Since we convert back based on the
3390 * same rules we used to build the yearday, you'll only get strange results
3391 * for input which needed normalising, or for the 'odd' century years which
3392 * were leap years in the Julian calander but not in the Gregorian one.
3393 * I can live with that.
3395 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3396 * that's still outside the scope for POSIX time manipulation, so I don't
3400 year = 1900 + ptm->tm_year;
3401 month = ptm->tm_mon;
3402 mday = ptm->tm_mday;
3403 /* allow given yday with no month & mday to dominate the result */
3404 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3407 jday = 1 + ptm->tm_yday;
3416 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3417 yearday += month*MONTH_TO_DAYS + mday + jday;
3419 * Note that we don't know when leap-seconds were or will be,
3420 * so we have to trust the user if we get something which looks
3421 * like a sensible leap-second. Wild values for seconds will
3422 * be rationalised, however.
3424 if ((unsigned) ptm->tm_sec <= 60) {
3431 secs += 60 * ptm->tm_min;
3432 secs += SECS_PER_HOUR * ptm->tm_hour;
3434 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3435 /* got negative remainder, but need positive time */
3436 /* back off an extra day to compensate */
3437 yearday += (secs/SECS_PER_DAY)-1;
3438 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3441 yearday += (secs/SECS_PER_DAY);
3442 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3445 else if (secs >= SECS_PER_DAY) {
3446 yearday += (secs/SECS_PER_DAY);
3447 secs %= SECS_PER_DAY;
3449 ptm->tm_hour = secs/SECS_PER_HOUR;
3450 secs %= SECS_PER_HOUR;
3451 ptm->tm_min = secs/60;
3453 ptm->tm_sec += secs;
3454 /* done with time of day effects */
3456 * The algorithm for yearday has (so far) left it high by 428.
3457 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3458 * bias it by 123 while trying to figure out what year it
3459 * really represents. Even with this tweak, the reverse
3460 * translation fails for years before A.D. 0001.
3461 * It would still fail for Feb 29, but we catch that one below.
3463 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3464 yearday -= YEAR_ADJUST;
3465 year = (yearday / DAYS_PER_QCENT) * 400;
3466 yearday %= DAYS_PER_QCENT;
3467 odd_cent = yearday / DAYS_PER_CENT;
3468 year += odd_cent * 100;
3469 yearday %= DAYS_PER_CENT;
3470 year += (yearday / DAYS_PER_QYEAR) * 4;
3471 yearday %= DAYS_PER_QYEAR;
3472 odd_year = yearday / DAYS_PER_YEAR;
3474 yearday %= DAYS_PER_YEAR;
3475 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3480 yearday += YEAR_ADJUST; /* recover March 1st crock */
3481 month = yearday*DAYS_TO_MONTH;
3482 yearday -= month*MONTH_TO_DAYS;
3483 /* recover other leap-year adjustment */
3492 ptm->tm_year = year - 1900;
3494 ptm->tm_mday = yearday;
3495 ptm->tm_mon = month;
3499 ptm->tm_mon = month - 1;
3501 /* re-build yearday based on Jan 1 to get tm_yday */
3503 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3504 yearday += 14*MONTH_TO_DAYS + 1;
3505 ptm->tm_yday = jday - yearday;
3506 /* fix tm_wday if not overridden by caller */
3507 if ((unsigned)ptm->tm_wday > 6)
3508 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3512 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3520 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3523 mytm.tm_hour = hour;
3524 mytm.tm_mday = mday;
3526 mytm.tm_year = year;
3527 mytm.tm_wday = wday;
3528 mytm.tm_yday = yday;
3529 mytm.tm_isdst = isdst;
3532 New(0, buf, buflen, char);
3533 len = strftime(buf, buflen, fmt, &mytm);
3535 ** The following is needed to handle to the situation where
3536 ** tmpbuf overflows. Basically we want to allocate a buffer
3537 ** and try repeatedly. The reason why it is so complicated
3538 ** is that getting a return value of 0 from strftime can indicate
3539 ** one of the following:
3540 ** 1. buffer overflowed,
3541 ** 2. illegal conversion specifier, or
3542 ** 3. the format string specifies nothing to be returned(not
3543 ** an error). This could be because format is an empty string
3544 ** or it specifies %p that yields an empty string in some locale.
3545 ** If there is a better way to make it portable, go ahead by
3548 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3551 /* Possibly buf overflowed - try again with a bigger buf */
3552 int fmtlen = strlen(fmt);
3553 int bufsize = fmtlen + buflen;
3555 New(0, buf, bufsize, char);
3557 buflen = strftime(buf, bufsize, fmt, &mytm);
3558 if (buflen > 0 && buflen < bufsize)
3560 /* heuristic to prevent out-of-memory errors */
3561 if (bufsize > 100*fmtlen) {
3567 Renew(buf, bufsize, char);
3572 Perl_croak(aTHX_ "panic: no strftime");
3577 #define SV_CWD_RETURN_UNDEF \
3578 sv_setsv(sv, &PL_sv_undef); \
3581 #define SV_CWD_ISDOT(dp) \
3582 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3583 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3586 =for apidoc sv_getcwd
3588 Fill the sv with current working directory
3593 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3594 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3595 * getcwd(3) if available
3596 * Comments from the orignal:
3597 * This is a faster version of getcwd. It's also more dangerous
3598 * because you might chdir out of a directory that you can't chdir
3601 /* XXX: this needs more porting #ifndef HAS_GETCWD */
3603 Perl_sv_getcwd(pTHX_ register SV *sv)
3608 struct stat statbuf;
3609 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3610 int namelen, pathlen=0;
3615 (void)SvUPGRADE(sv, SVt_PV);
3620 while ((getcwd(SvPVX(sv), SvLEN(sv)-1) == NULL) && errno == ERANGE) {
3621 SvGROW(sv, SvLEN(sv) + 128);
3623 SvCUR_set(sv, strlen(SvPVX(sv)));
3628 if (PerlLIO_lstat(".", &statbuf) < 0) {
3629 SV_CWD_RETURN_UNDEF;
3632 orig_cdev = statbuf.st_dev;
3633 orig_cino = statbuf.st_ino;
3641 if (PerlDir_chdir("..") < 0) {
3642 SV_CWD_RETURN_UNDEF;
3644 if (PerlLIO_stat(".", &statbuf) < 0) {
3645 SV_CWD_RETURN_UNDEF;
3648 cdev = statbuf.st_dev;
3649 cino = statbuf.st_ino;
3651 if (odev == cdev && oino == cino) {
3654 if (!(dir = PerlDir_open("."))) {
3655 SV_CWD_RETURN_UNDEF;
3658 while ((dp = PerlDir_read(dir)) != NULL) {
3660 namelen = dp->d_namlen;
3662 namelen = strlen(dp->d_name);
3665 if (SV_CWD_ISDOT(dp)) {
3669 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3670 SV_CWD_RETURN_UNDEF;
3673 tdev = statbuf.st_dev;
3674 tino = statbuf.st_ino;
3675 if (tino == oino && tdev == odev) {
3681 SV_CWD_RETURN_UNDEF;
3684 SvGROW(sv, pathlen + namelen + 1);
3688 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3691 /* prepend current directory to the front */
3693 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3694 pathlen += (namelen + 1);
3696 #ifdef VOID_CLOSEDIR
3699 if (PerlDir_close(dir) < 0) {
3700 SV_CWD_RETURN_UNDEF;
3705 SvCUR_set(sv, pathlen);
3709 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3710 SV_CWD_RETURN_UNDEF;
3712 if (PerlLIO_stat(".", &statbuf) < 0) {
3713 SV_CWD_RETURN_UNDEF;
3716 cdev = statbuf.st_dev;
3717 cino = statbuf.st_ino;
3719 if (cdev != orig_cdev || cino != orig_cino) {
3720 Perl_croak(aTHX_ "Unstable directory path, "
3721 "current directory changed unexpectedly");
3732 =for apidoc sv_realpath
3734 Wrap or emulate realpath(3).
3739 Perl_sv_realpath(pTHX_ SV *sv, char *path, STRLEN len)
3742 char name[MAXPATHLEN] = { 0 }, *s;
3743 STRLEN pathlen, namelen;
3745 /* Don't use strlen() to avoid running off the end. */
3746 s = memchr(path, '\0', MAXPATHLEN);
3747 pathlen = s ? s - path : MAXPATHLEN;
3751 /* Be paranoid about the use of realpath(),
3752 * it is an infamous source of buffer overruns. */
3754 /* Is the source buffer too long? */
3755 if (pathlen == MAXPATHLEN) {
3756 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %c= (MAXPATHLEN = %d)",
3757 path, s ? '=' : '>', MAXPATHLEN);
3758 SV_CWD_RETURN_UNDEF;
3761 /* Here goes nothing. */
3762 if (realpath(path, name) == NULL) {
3763 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %s",
3764 path, Strerror(errno));
3765 SV_CWD_RETURN_UNDEF;
3768 /* Is the destination buffer too long?
3769 * Don't use strlen() to avoid running off the end. */
3770 s = memchr(name, '\0', MAXPATHLEN);
3771 namelen = s ? s - name : MAXPATHLEN;
3772 if (namelen == MAXPATHLEN) {
3773 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %c= (MAXPATHLEN = %d)",
3774 path, s ? '=' : '>', MAXPATHLEN);
3775 SV_CWD_RETURN_UNDEF;
3778 /* The coast is clear? */
3779 sv_setpvn(sv, name, namelen);
3787 char dotdots[MAXPATHLEN] = { 0 };
3788 struct stat cst, pst, tst;
3790 if (PerlLIO_stat(path, &cst) < 0) {
3791 Perl_warn(aTHX_ "sv_realpath: stat(\"%s\"): %s",
3792 path, Strerror(errno));
3793 SV_CWD_RETURN_UNDEF;
3796 (void)SvUPGRADE(sv, SVt_PV);
3801 Copy(path, dotdots, len, char);
3804 strcat(dotdots, "/..");
3805 StructCopy(&cst, &pst, struct stat);
3807 if (PerlLIO_stat(dotdots, &cst) < 0) {
3808 Perl_warn(aTHX_ "sv_realpath: stat(\"%s\"): %s",
3809 dotdots, Strerror(errno));
3810 SV_CWD_RETURN_UNDEF;
3813 if (pst.st_dev == cst.st_dev && pst.st_ino == cst.st_ino) {
3814 /* We've reached the root: previous is same as current */
3817 STRLEN dotdotslen = strlen(dotdots);
3819 /* Scan through the dir looking for name of previous */
3820 if (!(parent = PerlDir_open(dotdots))) {
3821 Perl_warn(aTHX_ "sv_realpath: opendir(\"%s\"): %s",
3822 dotdots, Strerror(errno));
3823 SV_CWD_RETURN_UNDEF;
3826 SETERRNO(0,SS$_NORMAL); /* for readdir() */
3827 while ((dp = PerlDir_read(parent)) != NULL) {
3828 if (SV_CWD_ISDOT(dp)) {
3832 Copy(dotdots, name, dotdotslen, char);
3833 name[dotdotslen] = '/';
3835 namelen = dp->d_namlen;
3837 namelen = strlen(dp->d_name);
3839 Copy(dp->d_name, name + dotdotslen + 1, namelen, char);
3840 name[dotdotslen + 1 + namelen] = 0;
3842 if (PerlLIO_lstat(name, &tst) < 0) {
3843 PerlDir_close(parent);
3844 Perl_warn(aTHX_ "sv_realpath: lstat(\"%s\"): %s",
3845 name, Strerror(errno));
3846 SV_CWD_RETURN_UNDEF;
3849 if (tst.st_dev == pst.st_dev && tst.st_ino == pst.st_ino)
3852 SETERRNO(0,SS$_NORMAL); /* for readdir() */
3856 Perl_warn(aTHX_ "sv_realpath: readdir(\"%s\"): %s",
3857 dotdots, Strerror(errno));
3858 SV_CWD_RETURN_UNDEF;
3861 SvGROW(sv, pathlen + namelen + 1);
3864 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3868 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3869 pathlen += (namelen + 1);
3871 #ifdef VOID_CLOSEDIR
3872 PerlDir_close(parent);
3874 if (PerlDir_close(parent) < 0) {
3875 Perl_warn(aTHX_ "sv_realpath: closedir(\"%s\"): %s",
3876 dotdots, Strerror(errno));
3877 SV_CWD_RETURN_UNDEF;
3883 SvCUR_set(sv, pathlen);