3 * Copyright (c) 1991-2002, 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)
30 # include <sys/wait.h>
35 # include <sys/select.h>
43 long xcount[MAXXCOUNT];
44 long lastxcount[MAXXCOUNT];
45 long xycount[MAXXCOUNT][MAXYCOUNT];
46 long lastxycount[MAXXCOUNT][MAXYCOUNT];
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 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
93 /* paranoid version of system's realloc() */
96 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
100 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
101 Malloc_t PerlMem_realloc();
102 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
106 PerlIO_printf(Perl_error_log,
107 "Reallocation too large: %lx\n", size) FLUSH;
110 #endif /* HAS_64K_LIMIT */
117 return safesysmalloc(size);
120 Perl_croak_nocontext("panic: realloc");
122 ptr = (Malloc_t)PerlMem_realloc(where,size);
123 PERL_ALLOC_CHECK(ptr);
125 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
126 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
133 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
140 /* safe version of system's free() */
143 Perl_safesysfree(Malloc_t where)
145 #ifdef PERL_IMPLICIT_SYS
148 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
155 /* safe version of system's calloc() */
158 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
164 if (size * count > 0xffff) {
165 PerlIO_printf(Perl_error_log,
166 "Allocation too large: %lx\n", size * count) FLUSH;
169 #endif /* HAS_64K_LIMIT */
171 if ((long)size < 0 || (long)count < 0)
172 Perl_croak_nocontext("panic: calloc");
175 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
176 PERL_ALLOC_CHECK(ptr);
177 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));
179 memset((void*)ptr, 0, size);
185 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
194 struct mem_test_strut {
202 # define ALIGN sizeof(struct mem_test_strut)
204 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
205 # define typeof_chunk(ch) \
206 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
207 # define set_typeof_chunk(ch,t) \
208 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
209 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
212 ? ((size) - 1)/8 + 5 \
216 Perl_safexmalloc(I32 x, MEM_SIZE size)
218 register char* where = (char*)safemalloc(size + ALIGN);
221 xycount[x][SIZE_TO_Y(size)]++;
222 set_typeof_chunk(where, x);
223 sizeof_chunk(where) = size;
224 return (Malloc_t)(where + ALIGN);
228 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
230 char *where = (char*)wh;
233 return safexmalloc(0,size);
236 MEM_SIZE old = sizeof_chunk(where - ALIGN);
237 int t = typeof_chunk(where - ALIGN);
238 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
240 xycount[t][SIZE_TO_Y(old)]--;
241 xycount[t][SIZE_TO_Y(size)]++;
242 xcount[t] += size - old;
243 sizeof_chunk(new) = size;
244 return (Malloc_t)(new + ALIGN);
249 Perl_safexfree(Malloc_t wh)
252 char *where = (char*)wh;
258 size = sizeof_chunk(where);
259 x = where[0] + 100 * where[1];
261 xycount[x][SIZE_TO_Y(size)]--;
266 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
268 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
270 xycount[x][SIZE_TO_Y(size)]++;
271 memset((void*)(where + ALIGN), 0, size * count);
272 set_typeof_chunk(where, x);
273 sizeof_chunk(where) = size;
274 return (Malloc_t)(where + ALIGN);
278 S_xstat(pTHX_ int flag)
280 register I32 i, j, total = 0;
281 I32 subtot[MAXYCOUNT];
283 for (j = 0; j < MAXYCOUNT; j++) {
287 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);
288 for (i = 0; i < MAXXCOUNT; i++) {
290 for (j = 0; j < MAXYCOUNT; j++) {
291 subtot[j] += xycount[i][j];
294 ? xcount[i] /* Have something */
296 ? xcount[i] != lastxcount[i] /* Changed */
297 : xcount[i] > lastxcount[i])) { /* Growed */
298 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
299 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
300 lastxcount[i] = xcount[i];
301 for (j = 0; j < MAXYCOUNT; j++) {
303 ? xycount[i][j] /* Have something */
305 ? xycount[i][j] != lastxycount[i][j] /* Changed */
306 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
307 PerlIO_printf(Perl_debug_log,"%3ld ",
309 ? xycount[i][j] - lastxycount[i][j]
311 lastxycount[i][j] = xycount[i][j];
313 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
316 PerlIO_printf(Perl_debug_log, "\n");
320 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
321 for (j = 0; j < MAXYCOUNT; j++) {
323 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
325 PerlIO_printf(Perl_debug_log, " . ");
328 PerlIO_printf(Perl_debug_log, "\n");
332 #endif /* LEAKTEST */
334 /* These must be defined when not using Perl's malloc for binary
339 Malloc_t Perl_malloc (MEM_SIZE nbytes)
342 return (Malloc_t)PerlMem_malloc(nbytes);
345 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
348 return (Malloc_t)PerlMem_calloc(elements, size);
351 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
354 return (Malloc_t)PerlMem_realloc(where, nbytes);
357 Free_t Perl_mfree (Malloc_t where)
365 /* copy a string up to some (non-backslashed) delimiter, if any */
368 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
371 for (tolen = 0; from < fromend; from++, tolen++) {
373 if (from[1] == delim)
382 else if (*from == delim)
393 /* return ptr to little string in big string, NULL if not found */
394 /* This routine was donated by Corey Satten. */
397 Perl_instr(pTHX_ register const char *big, register const char *little)
399 register const char *s, *x;
410 for (x=big,s=little; *s; /**/ ) {
419 return (char*)(big-1);
424 /* same as instr but allow embedded nulls */
427 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
429 register const char *s, *x;
430 register I32 first = *little;
431 register const char *littleend = lend;
433 if (!first && little >= littleend)
435 if (bigend - big < littleend - little)
437 bigend -= littleend - little++;
438 while (big <= bigend) {
441 for (x=big,s=little; s < littleend; /**/ ) {
448 return (char*)(big-1);
453 /* reverse of the above--find last substring */
456 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
458 register const char *bigbeg;
459 register const char *s, *x;
460 register I32 first = *little;
461 register const char *littleend = lend;
463 if (!first && little >= littleend)
464 return (char*)bigend;
466 big = bigend - (littleend - little++);
467 while (big >= bigbeg) {
470 for (x=big+2,s=little; s < littleend; /**/ ) {
477 return (char*)(big+1);
482 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
484 /* As a space optimization, we do not compile tables for strings of length
485 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
486 special-cased in fbm_instr().
488 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
491 =head1 Miscellaneous Functions
493 =for apidoc fbm_compile
495 Analyses the string in order to make fast searches on it using fbm_instr()
496 -- the Boyer-Moore algorithm.
502 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
511 if (flags & FBMcf_TAIL)
512 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
513 s = (U8*)SvPV_force(sv, len);
514 (void)SvUPGRADE(sv, SVt_PVBM);
515 if (len == 0) /* TAIL might be on a zero-length string. */
525 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
526 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
527 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
528 memset((void*)table, mlen, 256);
529 table[-1] = (U8)flags;
531 sb = s - mlen + 1; /* first char (maybe) */
533 if (table[*s] == mlen)
538 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
541 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
542 for (i = 0; i < len; i++) {
543 if (PL_freq[s[i]] < frequency) {
545 frequency = PL_freq[s[i]];
548 BmRARE(sv) = s[rarest];
549 BmPREVIOUS(sv) = rarest;
550 BmUSEFUL(sv) = 100; /* Initial value */
551 if (flags & FBMcf_TAIL)
553 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
554 BmRARE(sv),BmPREVIOUS(sv)));
557 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
558 /* If SvTAIL is actually due to \Z or \z, this gives false positives
562 =for apidoc fbm_instr
564 Returns the location of the SV in the string delimited by C<str> and
565 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
566 does not have to be fbm_compiled, but the search will not be as fast
573 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
575 register unsigned char *s;
577 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
578 register STRLEN littlelen = l;
579 register I32 multiline = flags & FBMrf_MULTILINE;
581 if (bigend - big < littlelen) {
582 if ( SvTAIL(littlestr)
583 && (bigend - big == littlelen - 1)
585 || (*big == *little &&
586 memEQ((char *)big, (char *)little, littlelen - 1))))
591 if (littlelen <= 2) { /* Special-cased */
593 if (littlelen == 1) {
594 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
595 /* Know that bigend != big. */
596 if (bigend[-1] == '\n')
597 return (char *)(bigend - 1);
598 return (char *) bigend;
606 if (SvTAIL(littlestr))
607 return (char *) bigend;
611 return (char*)big; /* Cannot be SvTAIL! */
614 if (SvTAIL(littlestr) && !multiline) {
615 if (bigend[-1] == '\n' && bigend[-2] == *little)
616 return (char*)bigend - 2;
617 if (bigend[-1] == *little)
618 return (char*)bigend - 1;
622 /* This should be better than FBM if c1 == c2, and almost
623 as good otherwise: maybe better since we do less indirection.
624 And we save a lot of memory by caching no table. */
625 register unsigned char c1 = little[0];
626 register unsigned char c2 = little[1];
631 while (s <= bigend) {
641 goto check_1char_anchor;
652 goto check_1char_anchor;
655 while (s <= bigend) {
660 goto check_1char_anchor;
669 check_1char_anchor: /* One char and anchor! */
670 if (SvTAIL(littlestr) && (*bigend == *little))
671 return (char *)bigend; /* bigend is already decremented. */
674 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
675 s = bigend - littlelen;
676 if (s >= big && bigend[-1] == '\n' && *s == *little
677 /* Automatically of length > 2 */
678 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
680 return (char*)s; /* how sweet it is */
683 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
685 return (char*)s + 1; /* how sweet it is */
689 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
690 char *b = ninstr((char*)big,(char*)bigend,
691 (char*)little, (char*)little + littlelen);
693 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
694 /* Chop \n from littlestr: */
695 s = bigend - littlelen + 1;
697 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
706 { /* Do actual FBM. */
707 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
708 register unsigned char *oldlittle;
710 if (littlelen > bigend - big)
712 --littlelen; /* Last char found by table lookup */
715 little += littlelen; /* last char */
722 if ((tmp = table[*s])) {
723 if ((s += tmp) < bigend)
727 else { /* less expensive than calling strncmp() */
728 register unsigned char *olds = s;
733 if (*--s == *--little)
735 s = olds + 1; /* here we pay the price for failure */
737 if (s < bigend) /* fake up continue to outer loop */
745 if ( s == bigend && (table[-1] & FBMcf_TAIL)
746 && memEQ((char *)(bigend - littlelen),
747 (char *)(oldlittle - littlelen), littlelen) )
748 return (char*)bigend - littlelen;
753 /* start_shift, end_shift are positive quantities which give offsets
754 of ends of some substring of bigstr.
755 If `last' we want the last occurence.
756 old_posp is the way of communication between consequent calls if
757 the next call needs to find the .
758 The initial *old_posp should be -1.
760 Note that we take into account SvTAIL, so one can get extra
761 optimizations if _ALL flag is set.
764 /* If SvTAIL is actually due to \Z or \z, this gives false positives
765 if PL_multiline. In fact if !PL_multiline the authoritative answer
766 is not supported yet. */
769 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
771 register unsigned char *s, *x;
772 register unsigned char *big;
774 register I32 previous;
776 register unsigned char *little;
777 register I32 stop_pos;
778 register unsigned char *littleend;
782 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
783 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
785 if ( BmRARE(littlestr) == '\n'
786 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
787 little = (unsigned char *)(SvPVX(littlestr));
788 littleend = little + SvCUR(littlestr);
795 little = (unsigned char *)(SvPVX(littlestr));
796 littleend = little + SvCUR(littlestr);
798 /* The value of pos we can start at: */
799 previous = BmPREVIOUS(littlestr);
800 big = (unsigned char *)(SvPVX(bigstr));
801 /* The value of pos we can stop at: */
802 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
803 if (previous + start_shift > stop_pos) {
805 stop_pos does not include SvTAIL in the count, so this check is incorrect
806 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
809 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
814 while (pos < previous + start_shift) {
815 if (!(pos += PL_screamnext[pos]))
820 if (pos >= stop_pos) break;
821 if (big[pos] != first)
823 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
829 if (s == littleend) {
831 if (!last) return (char *)(big+pos);
834 } while ( pos += PL_screamnext[pos] );
836 return (char *)(big+(*old_posp));
838 if (!SvTAIL(littlestr) || (end_shift > 0))
840 /* Ignore the trailing "\n". This code is not microoptimized */
841 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
842 stop_pos = littleend - little; /* Actual littlestr len */
847 && ((stop_pos == 1) ||
848 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
854 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
856 register U8 *a = (U8 *)s1;
857 register U8 *b = (U8 *)s2;
859 if (*a != *b && *a != PL_fold[*b])
867 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
869 register U8 *a = (U8 *)s1;
870 register U8 *b = (U8 *)s2;
872 if (*a != *b && *a != PL_fold_locale[*b])
879 /* copy a string to a safe spot */
882 =head1 Memory Management
886 Copy a string to a safe spot. This does not use an SV.
892 Perl_savepv(pTHX_ const char *sv)
894 register char *newaddr = Nullch;
896 New(902,newaddr,strlen(sv)+1,char);
897 (void)strcpy(newaddr,sv);
902 /* same thing but with a known length */
907 Copy a string to a safe spot. The C<len> indicates number of bytes to
908 copy. If pointer is NULL allocate space for a string of size specified.
909 This does not use an SV.
915 Perl_savepvn(pTHX_ const char *sv, register I32 len)
917 register char *newaddr;
919 New(903,newaddr,len+1,char);
920 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
922 Copy(sv,newaddr,len,char); /* might not be null terminated */
923 newaddr[len] = '\0'; /* is now */
926 Zero(newaddr,len+1,char);
932 =for apidoc savesharedpv
934 Copy a string to a safe spot in memory shared between threads.
935 This does not use an SV.
940 Perl_savesharedpv(pTHX_ const char *sv)
942 register char *newaddr = Nullch;
944 newaddr = (char*)PerlMemShared_malloc(strlen(sv)+1);
945 (void)strcpy(newaddr,sv);
952 /* the SV for Perl_form() and mess() is not kept in an arena */
961 return sv_2mortal(newSVpvn("",0));
966 /* Create as PVMG now, to avoid any upgrading later */
968 Newz(905, any, 1, XPVMG);
969 SvFLAGS(sv) = SVt_PVMG;
970 SvANY(sv) = (void*)any;
971 SvREFCNT(sv) = 1 << 30; /* practically infinite */
976 #if defined(PERL_IMPLICIT_CONTEXT)
978 Perl_form_nocontext(const char* pat, ...)
984 retval = vform(pat, &args);
988 #endif /* PERL_IMPLICIT_CONTEXT */
991 =head1 Miscellaneous Functions
994 Takes a sprintf-style format pattern and conventional
995 (non-SV) arguments and returns the formatted string.
997 (char *) Perl_form(pTHX_ const char* pat, ...)
999 can be used any place a string (char *) is required:
1001 char * s = Perl_form("%d.%d",major,minor);
1003 Uses a single private buffer so if you want to format several strings you
1004 must explicitly copy the earlier strings away (and free the copies when you
1011 Perl_form(pTHX_ const char* pat, ...)
1015 va_start(args, pat);
1016 retval = vform(pat, &args);
1022 Perl_vform(pTHX_ const char *pat, va_list *args)
1024 SV *sv = mess_alloc();
1025 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1029 #if defined(PERL_IMPLICIT_CONTEXT)
1031 Perl_mess_nocontext(const char *pat, ...)
1036 va_start(args, pat);
1037 retval = vmess(pat, &args);
1041 #endif /* PERL_IMPLICIT_CONTEXT */
1044 Perl_mess(pTHX_ const char *pat, ...)
1048 va_start(args, pat);
1049 retval = vmess(pat, &args);
1055 S_closest_cop(pTHX_ COP *cop, OP *o)
1057 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1059 if (!o || o == PL_op) return cop;
1061 if (o->op_flags & OPf_KIDS) {
1063 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1067 /* If the OP_NEXTSTATE has been optimised away we can still use it
1068 * the get the file and line number. */
1070 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1073 /* Keep searching, and return when we've found something. */
1075 new_cop = closest_cop(cop, kid);
1076 if (new_cop) return new_cop;
1080 /* Nothing found. */
1086 Perl_vmess(pTHX_ const char *pat, va_list *args)
1088 SV *sv = mess_alloc();
1089 static char dgd[] = " during global destruction.\n";
1092 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1093 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1096 * Try and find the file and line for PL_op. This will usually be
1097 * PL_curcop, but it might be a cop that has been optimised away. We
1098 * can try to find such a cop by searching through the optree starting
1099 * from the sibling of PL_curcop.
1102 cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1103 if (!cop) cop = PL_curcop;
1106 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1107 OutCopFILE(cop), (IV)CopLINE(cop));
1108 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1109 bool line_mode = (RsSIMPLE(PL_rs) &&
1110 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1111 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1112 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1113 line_mode ? "line" : "chunk",
1114 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1116 #ifdef USE_5005THREADS
1118 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1120 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1126 Perl_vdie(pTHX_ const char* pat, va_list *args)
1129 int was_in_eval = PL_in_eval;
1136 DEBUG_S(PerlIO_printf(Perl_debug_log,
1137 "%p: die: curstack = %p, mainstack = %p\n",
1138 thr, PL_curstack, PL_mainstack));
1141 msv = vmess(pat, args);
1142 if (PL_errors && SvCUR(PL_errors)) {
1143 sv_catsv(PL_errors, msv);
1144 message = SvPV(PL_errors, msglen);
1145 SvCUR_set(PL_errors, 0);
1148 message = SvPV(msv,msglen);
1155 DEBUG_S(PerlIO_printf(Perl_debug_log,
1156 "%p: die: message = %s\ndiehook = %p\n",
1157 thr, message, PL_diehook));
1159 /* sv_2cv might call Perl_croak() */
1160 SV *olddiehook = PL_diehook;
1162 SAVESPTR(PL_diehook);
1163 PL_diehook = Nullsv;
1164 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1166 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1173 msg = newSVpvn(message, msglen);
1181 PUSHSTACKi(PERLSI_DIEHOOK);
1185 call_sv((SV*)cv, G_DISCARD);
1191 PL_restartop = die_where(message, msglen);
1192 DEBUG_S(PerlIO_printf(Perl_debug_log,
1193 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1194 thr, PL_restartop, was_in_eval, PL_top_env));
1195 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1197 return PL_restartop;
1200 #if defined(PERL_IMPLICIT_CONTEXT)
1202 Perl_die_nocontext(const char* pat, ...)
1207 va_start(args, pat);
1208 o = vdie(pat, &args);
1212 #endif /* PERL_IMPLICIT_CONTEXT */
1215 Perl_die(pTHX_ const char* pat, ...)
1219 va_start(args, pat);
1220 o = vdie(pat, &args);
1226 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1236 msv = vmess(pat, args);
1237 if (PL_errors && SvCUR(PL_errors)) {
1238 sv_catsv(PL_errors, msv);
1239 message = SvPV(PL_errors, msglen);
1240 SvCUR_set(PL_errors, 0);
1243 message = SvPV(msv,msglen);
1250 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1251 PTR2UV(thr), message));
1254 /* sv_2cv might call Perl_croak() */
1255 SV *olddiehook = PL_diehook;
1257 SAVESPTR(PL_diehook);
1258 PL_diehook = Nullsv;
1259 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1261 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1268 msg = newSVpvn(message, msglen);
1276 PUSHSTACKi(PERLSI_DIEHOOK);
1280 call_sv((SV*)cv, G_DISCARD);
1286 PL_restartop = die_where(message, msglen);
1290 message = SvPVx(ERRSV, msglen);
1294 /* SFIO can really mess with your errno */
1297 PerlIO *serr = Perl_error_log;
1299 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1300 (void)PerlIO_flush(serr);
1308 #if defined(PERL_IMPLICIT_CONTEXT)
1310 Perl_croak_nocontext(const char *pat, ...)
1314 va_start(args, pat);
1319 #endif /* PERL_IMPLICIT_CONTEXT */
1322 =head1 Warning and Dieing
1326 This is the XSUB-writer's interface to Perl's C<die> function.
1327 Normally use this function the same way you use the C C<printf>
1328 function. See C<warn>.
1330 If you want to throw an exception object, assign the object to
1331 C<$@> and then pass C<Nullch> to croak():
1333 errsv = get_sv("@", TRUE);
1334 sv_setsv(errsv, exception_object);
1341 Perl_croak(pTHX_ const char *pat, ...)
1344 va_start(args, pat);
1351 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1362 msv = vmess(pat, args);
1363 message = SvPV(msv, msglen);
1366 /* sv_2cv might call Perl_warn() */
1367 SV *oldwarnhook = PL_warnhook;
1369 SAVESPTR(PL_warnhook);
1370 PL_warnhook = Nullsv;
1371 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1373 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1379 msg = newSVpvn(message, msglen);
1383 PUSHSTACKi(PERLSI_WARNHOOK);
1387 call_sv((SV*)cv, G_DISCARD);
1394 /* if STDERR is tied, use it instead */
1395 if (PL_stderrgv && (io = GvIOp(PL_stderrgv))
1396 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar))) {
1399 XPUSHs(SvTIED_obj((SV*)io, mg));
1400 XPUSHs(sv_2mortal(newSVpvn(message, msglen)));
1402 call_method("PRINT", G_SCALAR);
1408 PerlIO *serr = Perl_error_log;
1410 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1412 DEBUG_L(*message == '!'
1413 ? (xstat(message[1]=='!'
1414 ? (message[2]=='!' ? 2 : 1)
1419 (void)PerlIO_flush(serr);
1423 #if defined(PERL_IMPLICIT_CONTEXT)
1425 Perl_warn_nocontext(const char *pat, ...)
1429 va_start(args, pat);
1433 #endif /* PERL_IMPLICIT_CONTEXT */
1438 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1439 function the same way you use the C C<printf> function. See
1446 Perl_warn(pTHX_ const char *pat, ...)
1449 va_start(args, pat);
1454 #if defined(PERL_IMPLICIT_CONTEXT)
1456 Perl_warner_nocontext(U32 err, const char *pat, ...)
1460 va_start(args, pat);
1461 vwarner(err, pat, &args);
1464 #endif /* PERL_IMPLICIT_CONTEXT */
1467 Perl_warner(pTHX_ U32 err, const char* pat,...)
1470 va_start(args, pat);
1471 vwarner(err, pat, &args);
1476 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1485 msv = vmess(pat, args);
1486 message = SvPV(msv, msglen);
1489 #ifdef USE_5005THREADS
1490 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1491 #endif /* USE_5005THREADS */
1493 /* sv_2cv might call Perl_croak() */
1494 SV *olddiehook = PL_diehook;
1496 SAVESPTR(PL_diehook);
1497 PL_diehook = Nullsv;
1498 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1500 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1506 msg = newSVpvn(message, msglen);
1510 PUSHSTACKi(PERLSI_DIEHOOK);
1514 call_sv((SV*)cv, G_DISCARD);
1520 PL_restartop = die_where(message, msglen);
1524 PerlIO *serr = Perl_error_log;
1525 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1526 (void)PerlIO_flush(serr);
1533 /* sv_2cv might call Perl_warn() */
1534 SV *oldwarnhook = PL_warnhook;
1536 SAVESPTR(PL_warnhook);
1537 PL_warnhook = Nullsv;
1538 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1540 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1546 msg = newSVpvn(message, msglen);
1550 PUSHSTACKi(PERLSI_WARNHOOK);
1554 call_sv((SV*)cv, G_DISCARD);
1561 PerlIO *serr = Perl_error_log;
1562 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1564 DEBUG_L(*message == '!'
1565 ? (xstat(message[1]=='!'
1566 ? (message[2]=='!' ? 2 : 1)
1571 (void)PerlIO_flush(serr);
1576 /* since we've already done strlen() for both nam and val
1577 * we can use that info to make things faster than
1578 * sprintf(s, "%s=%s", nam, val)
1580 #define my_setenv_format(s, nam, nlen, val, vlen) \
1581 Copy(nam, s, nlen, char); \
1583 Copy(val, s+(nlen+1), vlen, char); \
1584 *(s+(nlen+1+vlen)) = '\0'
1586 #ifdef USE_ENVIRON_ARRAY
1587 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1588 #if !defined(WIN32) && !defined(NETWARE)
1590 Perl_my_setenv(pTHX_ char *nam, char *val)
1592 #ifndef PERL_USE_SAFE_PUTENV
1593 /* most putenv()s leak, so we manipulate environ directly */
1594 register I32 i=setenv_getix(nam); /* where does it go? */
1597 if (environ == PL_origenviron) { /* need we copy environment? */
1603 for (max = i; environ[max]; max++) ;
1604 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1605 for (j=0; j<max; j++) { /* copy environment */
1606 int len = strlen(environ[j]);
1607 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1608 Copy(environ[j], tmpenv[j], len+1, char);
1610 tmpenv[max] = Nullch;
1611 environ = tmpenv; /* tell exec where it is now */
1614 safesysfree(environ[i]);
1615 while (environ[i]) {
1616 environ[i] = environ[i+1];
1621 if (!environ[i]) { /* does not exist yet */
1622 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1623 environ[i+1] = Nullch; /* make sure it's null terminated */
1626 safesysfree(environ[i]);
1630 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1631 /* all that work just for this */
1632 my_setenv_format(environ[i], nam, nlen, val, vlen);
1634 #else /* PERL_USE_SAFE_PUTENV */
1635 # if defined(__CYGWIN__)
1636 setenv(nam, val, 1);
1639 int nlen = strlen(nam), vlen;
1644 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1645 /* all that work just for this */
1646 my_setenv_format(new_env, nam, nlen, val, vlen);
1647 (void)putenv(new_env);
1648 # endif /* __CYGWIN__ */
1649 #endif /* PERL_USE_SAFE_PUTENV */
1652 #else /* WIN32 || NETWARE */
1655 Perl_my_setenv(pTHX_ char *nam,char *val)
1657 register char *envstr;
1658 int nlen = strlen(nam), vlen;
1664 New(904, envstr, nlen+vlen+2, char);
1665 my_setenv_format(envstr, nam, nlen, val, vlen);
1666 (void)PerlEnv_putenv(envstr);
1670 #endif /* WIN32 || NETWARE */
1673 Perl_setenv_getix(pTHX_ char *nam)
1675 register I32 i, len = strlen(nam);
1677 for (i = 0; environ[i]; i++) {
1680 strnicmp(environ[i],nam,len) == 0
1682 strnEQ(environ[i],nam,len)
1684 && environ[i][len] == '=')
1685 break; /* strnEQ must come first to avoid */
1686 } /* potential SEGV's */
1690 #endif /* !VMS && !EPOC*/
1692 #ifdef UNLINK_ALL_VERSIONS
1694 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1698 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1703 /* this is a drop-in replacement for bcopy() */
1704 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1706 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1710 if (from - to >= 0) {
1718 *(--to) = *(--from);
1724 /* this is a drop-in replacement for memset() */
1727 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1737 /* this is a drop-in replacement for bzero() */
1738 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1740 Perl_my_bzero(register char *loc, register I32 len)
1750 /* this is a drop-in replacement for memcmp() */
1751 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1753 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1755 register U8 *a = (U8 *)s1;
1756 register U8 *b = (U8 *)s2;
1760 if (tmp = *a++ - *b++)
1765 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1769 #ifdef USE_CHAR_VSPRINTF
1774 vsprintf(char *dest, const char *pat, char *args)
1778 fakebuf._ptr = dest;
1779 fakebuf._cnt = 32767;
1783 fakebuf._flag = _IOWRT|_IOSTRG;
1784 _doprnt(pat, args, &fakebuf); /* what a kludge */
1785 (void)putc('\0', &fakebuf);
1786 #ifdef USE_CHAR_VSPRINTF
1789 return 0; /* perl doesn't use return value */
1793 #endif /* HAS_VPRINTF */
1796 #if BYTEORDER != 0x4321
1798 Perl_my_swap(pTHX_ short s)
1800 #if (BYTEORDER & 1) == 0
1803 result = ((s & 255) << 8) + ((s >> 8) & 255);
1811 Perl_my_htonl(pTHX_ long l)
1815 char c[sizeof(long)];
1818 #if BYTEORDER == 0x1234
1819 u.c[0] = (l >> 24) & 255;
1820 u.c[1] = (l >> 16) & 255;
1821 u.c[2] = (l >> 8) & 255;
1825 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1826 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1831 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1832 u.c[o & 0xf] = (l >> s) & 255;
1840 Perl_my_ntohl(pTHX_ long l)
1844 char c[sizeof(long)];
1847 #if BYTEORDER == 0x1234
1848 u.c[0] = (l >> 24) & 255;
1849 u.c[1] = (l >> 16) & 255;
1850 u.c[2] = (l >> 8) & 255;
1854 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1855 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1862 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1863 l |= (u.c[o & 0xf] & 255) << s;
1870 #endif /* BYTEORDER != 0x4321 */
1874 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1875 * If these functions are defined,
1876 * the BYTEORDER is neither 0x1234 nor 0x4321.
1877 * However, this is not assumed.
1881 #define HTOV(name,type) \
1883 name (register type n) \
1887 char c[sizeof(type)]; \
1891 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1892 u.c[i] = (n >> s) & 0xFF; \
1897 #define VTOH(name,type) \
1899 name (register type n) \
1903 char c[sizeof(type)]; \
1909 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1910 n += (u.c[i] & 0xFF) << s; \
1915 #if defined(HAS_HTOVS) && !defined(htovs)
1918 #if defined(HAS_HTOVL) && !defined(htovl)
1921 #if defined(HAS_VTOHS) && !defined(vtohs)
1924 #if defined(HAS_VTOHL) && !defined(vtohl)
1929 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1931 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1933 register I32 This, that;
1939 PERL_FLUSHALL_FOR_CHILD;
1940 This = (*mode == 'w');
1944 taint_proper("Insecure %s%s", "EXEC");
1946 if (PerlProc_pipe(p) < 0)
1948 /* Try for another pipe pair for error return */
1949 if (PerlProc_pipe(pp) >= 0)
1951 while ((pid = PerlProc_fork()) < 0) {
1952 if (errno != EAGAIN) {
1953 PerlLIO_close(p[This]);
1955 PerlLIO_close(pp[0]);
1956 PerlLIO_close(pp[1]);
1968 /* Close parent's end of _the_ pipe */
1969 PerlLIO_close(p[THAT]);
1970 /* Close parent's end of error status pipe (if any) */
1972 PerlLIO_close(pp[0]);
1973 #if defined(HAS_FCNTL) && defined(F_SETFD)
1974 /* Close error pipe automatically if exec works */
1975 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1978 /* Now dup our end of _the_ pipe to right position */
1979 if (p[THIS] != (*mode == 'r')) {
1980 PerlLIO_dup2(p[THIS], *mode == 'r');
1981 PerlLIO_close(p[THIS]);
1983 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1984 /* No automatic close - do it by hand */
1991 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1997 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2003 do_execfree(); /* free any memory malloced by child on fork */
2004 /* Close child's end of pipe */
2005 PerlLIO_close(p[that]);
2007 PerlLIO_close(pp[1]);
2008 /* Keep the lower of the two fd numbers */
2009 if (p[that] < p[This]) {
2010 PerlLIO_dup2(p[This], p[that]);
2011 PerlLIO_close(p[This]);
2015 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2017 (void)SvUPGRADE(sv,SVt_IV);
2019 PL_forkprocess = pid;
2020 /* If we managed to get status pipe check for exec fail */
2021 if (did_pipes && pid > 0) {
2025 while (n < sizeof(int)) {
2026 n1 = PerlLIO_read(pp[0],
2027 (void*)(((char*)&errkid)+n),
2033 PerlLIO_close(pp[0]);
2035 if (n) { /* Error */
2037 PerlLIO_close(p[This]);
2038 if (n != sizeof(int))
2039 Perl_croak(aTHX_ "panic: kid popen errno read");
2041 pid2 = wait4pid(pid, &status, 0);
2042 } while (pid2 == -1 && errno == EINTR);
2043 errno = errkid; /* Propagate errno from kid */
2048 PerlLIO_close(pp[0]);
2049 return PerlIO_fdopen(p[This], mode);
2051 Perl_croak(aTHX_ "List form of piped open not implemented");
2052 return (PerlIO *) NULL;
2056 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2057 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2059 Perl_my_popen(pTHX_ char *cmd, char *mode)
2062 register I32 This, that;
2065 I32 doexec = strNE(cmd,"-");
2069 PERL_FLUSHALL_FOR_CHILD;
2072 return my_syspopen(aTHX_ cmd,mode);
2075 This = (*mode == 'w');
2077 if (doexec && PL_tainting) {
2079 taint_proper("Insecure %s%s", "EXEC");
2081 if (PerlProc_pipe(p) < 0)
2083 if (doexec && PerlProc_pipe(pp) >= 0)
2085 while ((pid = PerlProc_fork()) < 0) {
2086 if (errno != EAGAIN) {
2087 PerlLIO_close(p[This]);
2089 PerlLIO_close(pp[0]);
2090 PerlLIO_close(pp[1]);
2093 Perl_croak(aTHX_ "Can't fork");
2105 PerlLIO_close(p[THAT]);
2107 PerlLIO_close(pp[0]);
2108 #if defined(HAS_FCNTL) && defined(F_SETFD)
2109 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2112 if (p[THIS] != (*mode == 'r')) {
2113 PerlLIO_dup2(p[THIS], *mode == 'r');
2114 PerlLIO_close(p[THIS]);
2118 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2127 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2132 /* may or may not use the shell */
2133 do_exec3(cmd, pp[1], did_pipes);
2136 #endif /* defined OS2 */
2138 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2139 SvREADONLY_off(GvSV(tmpgv));
2140 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2141 SvREADONLY_on(GvSV(tmpgv));
2144 hv_clear(PL_pidstatus); /* we have no children */
2149 do_execfree(); /* free any memory malloced by child on fork */
2150 PerlLIO_close(p[that]);
2152 PerlLIO_close(pp[1]);
2153 if (p[that] < p[This]) {
2154 PerlLIO_dup2(p[This], p[that]);
2155 PerlLIO_close(p[This]);
2159 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2161 (void)SvUPGRADE(sv,SVt_IV);
2163 PL_forkprocess = pid;
2164 if (did_pipes && pid > 0) {
2168 while (n < sizeof(int)) {
2169 n1 = PerlLIO_read(pp[0],
2170 (void*)(((char*)&errkid)+n),
2176 PerlLIO_close(pp[0]);
2178 if (n) { /* Error */
2180 PerlLIO_close(p[This]);
2181 if (n != sizeof(int))
2182 Perl_croak(aTHX_ "panic: kid popen errno read");
2184 pid2 = wait4pid(pid, &status, 0);
2185 } while (pid2 == -1 && errno == EINTR);
2186 errno = errkid; /* Propagate errno from kid */
2191 PerlLIO_close(pp[0]);
2192 return PerlIO_fdopen(p[This], mode);
2195 #if defined(atarist) || defined(EPOC)
2198 Perl_my_popen(pTHX_ char *cmd, char *mode)
2200 PERL_FLUSHALL_FOR_CHILD;
2201 /* Call system's popen() to get a FILE *, then import it.
2202 used 0 for 2nd parameter to PerlIO_importFILE;
2205 return PerlIO_importFILE(popen(cmd, mode), 0);
2209 FILE *djgpp_popen();
2211 Perl_my_popen(pTHX_ char *cmd, char *mode)
2213 PERL_FLUSHALL_FOR_CHILD;
2214 /* Call system's popen() to get a FILE *, then import it.
2215 used 0 for 2nd parameter to PerlIO_importFILE;
2218 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2223 #endif /* !DOSISH */
2225 /* this is called in parent before the fork() */
2227 Perl_atfork_lock(void)
2229 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2230 /* locks must be held in locking order (if any) */
2232 MUTEX_LOCK(&PL_malloc_mutex);
2238 /* this is called in both parent and child after the fork() */
2240 Perl_atfork_unlock(void)
2242 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2243 /* locks must be released in same order as in atfork_lock() */
2245 MUTEX_UNLOCK(&PL_malloc_mutex);
2254 #if defined(HAS_FORK)
2256 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2261 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2262 * handlers elsewhere in the code */
2267 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2268 Perl_croak_nocontext("fork() not available");
2270 #endif /* HAS_FORK */
2275 Perl_dump_fds(pTHX_ char *s)
2278 struct stat tmpstatbuf;
2280 PerlIO_printf(Perl_debug_log,"%s", s);
2281 for (fd = 0; fd < 32; fd++) {
2282 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2283 PerlIO_printf(Perl_debug_log," %d",fd);
2285 PerlIO_printf(Perl_debug_log,"\n");
2287 #endif /* DUMP_FDS */
2291 dup2(int oldfd, int newfd)
2293 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2296 PerlLIO_close(newfd);
2297 return fcntl(oldfd, F_DUPFD, newfd);
2299 #define DUP2_MAX_FDS 256
2300 int fdtmp[DUP2_MAX_FDS];
2306 PerlLIO_close(newfd);
2307 /* good enough for low fd's... */
2308 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2309 if (fdx >= DUP2_MAX_FDS) {
2317 PerlLIO_close(fdtmp[--fdx]);
2324 #ifdef HAS_SIGACTION
2327 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2329 struct sigaction act, oact;
2331 act.sa_handler = handler;
2332 sigemptyset(&act.sa_mask);
2335 #if defined(PERL_OLD_SIGNALS)
2336 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2340 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2341 act.sa_flags |= SA_NOCLDWAIT;
2343 if (sigaction(signo, &act, &oact) == -1)
2346 return oact.sa_handler;
2350 Perl_rsignal_state(pTHX_ int signo)
2352 struct sigaction oact;
2354 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2357 return oact.sa_handler;
2361 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2363 struct sigaction act;
2365 act.sa_handler = handler;
2366 sigemptyset(&act.sa_mask);
2369 #if defined(PERL_OLD_SIGNALS)
2370 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2374 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2375 act.sa_flags |= SA_NOCLDWAIT;
2377 return sigaction(signo, &act, save);
2381 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2383 return sigaction(signo, save, (struct sigaction *)NULL);
2386 #else /* !HAS_SIGACTION */
2389 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2391 return PerlProc_signal(signo, handler);
2394 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2395 ignore the implications of this for threading */
2405 Perl_rsignal_state(pTHX_ int signo)
2407 Sighandler_t oldsig;
2410 oldsig = PerlProc_signal(signo, sig_trap);
2411 PerlProc_signal(signo, oldsig);
2413 PerlProc_kill(PerlProc_getpid(), signo);
2418 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2420 *save = PerlProc_signal(signo, handler);
2421 return (*save == SIG_ERR) ? -1 : 0;
2425 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2427 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2430 #endif /* !HAS_SIGACTION */
2431 #endif /* !PERL_MICRO */
2433 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2434 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2436 Perl_my_pclose(pTHX_ PerlIO *ptr)
2438 Sigsave_t hstat, istat, qstat;
2444 int saved_errno = 0;
2446 int saved_vaxc_errno;
2449 int saved_win32_errno;
2453 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2455 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2457 *svp = &PL_sv_undef;
2459 if (pid == -1) { /* Opened by popen. */
2460 return my_syspclose(ptr);
2463 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2464 saved_errno = errno;
2466 saved_vaxc_errno = vaxc$errno;
2469 saved_win32_errno = GetLastError();
2473 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2476 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2477 rsignal_save(SIGINT, SIG_IGN, &istat);
2478 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2481 pid2 = wait4pid(pid, &status, 0);
2482 } while (pid2 == -1 && errno == EINTR);
2484 rsignal_restore(SIGHUP, &hstat);
2485 rsignal_restore(SIGINT, &istat);
2486 rsignal_restore(SIGQUIT, &qstat);
2489 SETERRNO(saved_errno, saved_vaxc_errno);
2492 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2494 #endif /* !DOSISH */
2496 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2498 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2503 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2507 char spid[TYPE_CHARS(int)];
2510 sprintf(spid, "%"IVdf, (IV)pid);
2511 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2512 if (svp && *svp != &PL_sv_undef) {
2513 *statusp = SvIVX(*svp);
2514 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2521 hv_iterinit(PL_pidstatus);
2522 if ((entry = hv_iternext(PL_pidstatus))) {
2523 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2524 sv = hv_iterval(PL_pidstatus,entry);
2525 *statusp = SvIVX(sv);
2526 sprintf(spid, "%"IVdf, (IV)pid);
2527 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2534 # ifdef HAS_WAITPID_RUNTIME
2535 if (!HAS_WAITPID_RUNTIME)
2538 result = PerlProc_waitpid(pid,statusp,flags);
2541 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2542 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2545 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2549 Perl_croak(aTHX_ "Can't do waitpid with flags");
2551 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2552 pidgone(result,*statusp);
2559 if (result < 0 && errno == EINTR) {
2564 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2568 Perl_pidgone(pTHX_ Pid_t pid, int status)
2571 char spid[TYPE_CHARS(int)];
2573 sprintf(spid, "%"IVdf, (IV)pid);
2574 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2575 (void)SvUPGRADE(sv,SVt_IV);
2580 #if defined(atarist) || defined(OS2) || defined(EPOC)
2583 int /* Cannot prototype with I32
2585 my_syspclose(PerlIO *ptr)
2588 Perl_my_pclose(pTHX_ PerlIO *ptr)
2591 /* Needs work for PerlIO ! */
2592 FILE *f = PerlIO_findFILE(ptr);
2593 I32 result = pclose(f);
2594 PerlIO_releaseFILE(ptr,f);
2602 Perl_my_pclose(pTHX_ PerlIO *ptr)
2604 /* Needs work for PerlIO ! */
2605 FILE *f = PerlIO_findFILE(ptr);
2606 I32 result = djgpp_pclose(f);
2607 result = (result << 8) & 0xff00;
2608 PerlIO_releaseFILE(ptr,f);
2614 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2617 register const char *frombase = from;
2620 register const char c = *from;
2625 while (count-- > 0) {
2626 for (todo = len; todo > 0; todo--) {
2635 Perl_same_dirent(pTHX_ char *a, char *b)
2637 char *fa = strrchr(a,'/');
2638 char *fb = strrchr(b,'/');
2639 struct stat tmpstatbuf1;
2640 struct stat tmpstatbuf2;
2641 SV *tmpsv = sv_newmortal();
2654 sv_setpv(tmpsv, ".");
2656 sv_setpvn(tmpsv, a, fa - a);
2657 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2660 sv_setpv(tmpsv, ".");
2662 sv_setpvn(tmpsv, b, fb - b);
2663 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2665 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2666 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2668 #endif /* !HAS_RENAME */
2671 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2673 char *xfound = Nullch;
2674 char *xfailed = Nullch;
2675 char tmpbuf[MAXPATHLEN];
2679 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2680 # define SEARCH_EXTS ".bat", ".cmd", NULL
2681 # define MAX_EXT_LEN 4
2684 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2685 # define MAX_EXT_LEN 4
2688 # define SEARCH_EXTS ".pl", ".com", NULL
2689 # define MAX_EXT_LEN 4
2691 /* additional extensions to try in each dir if scriptname not found */
2693 char *exts[] = { SEARCH_EXTS };
2694 char **ext = search_ext ? search_ext : exts;
2695 int extidx = 0, i = 0;
2696 char *curext = Nullch;
2698 # define MAX_EXT_LEN 0
2702 * If dosearch is true and if scriptname does not contain path
2703 * delimiters, search the PATH for scriptname.
2705 * If SEARCH_EXTS is also defined, will look for each
2706 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2707 * while searching the PATH.
2709 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2710 * proceeds as follows:
2711 * If DOSISH or VMSISH:
2712 * + look for ./scriptname{,.foo,.bar}
2713 * + search the PATH for scriptname{,.foo,.bar}
2716 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2717 * this will not look in '.' if it's not in the PATH)
2722 # ifdef ALWAYS_DEFTYPES
2723 len = strlen(scriptname);
2724 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2725 int hasdir, idx = 0, deftypes = 1;
2728 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2731 int hasdir, idx = 0, deftypes = 1;
2734 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2736 /* The first time through, just add SEARCH_EXTS to whatever we
2737 * already have, so we can check for default file types. */
2739 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2745 if ((strlen(tmpbuf) + strlen(scriptname)
2746 + MAX_EXT_LEN) >= sizeof tmpbuf)
2747 continue; /* don't search dir with too-long name */
2748 strcat(tmpbuf, scriptname);
2752 if (strEQ(scriptname, "-"))
2754 if (dosearch) { /* Look in '.' first. */
2755 char *cur = scriptname;
2757 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2759 if (strEQ(ext[i++],curext)) {
2760 extidx = -1; /* already has an ext */
2765 DEBUG_p(PerlIO_printf(Perl_debug_log,
2766 "Looking for %s\n",cur));
2767 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2768 && !S_ISDIR(PL_statbuf.st_mode)) {
2776 if (cur == scriptname) {
2777 len = strlen(scriptname);
2778 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2780 cur = strcpy(tmpbuf, scriptname);
2782 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2783 && strcpy(tmpbuf+len, ext[extidx++]));
2788 #ifdef MACOS_TRADITIONAL
2789 if (dosearch && !strchr(scriptname, ':') &&
2790 (s = PerlEnv_getenv("Commands")))
2792 if (dosearch && !strchr(scriptname, '/')
2794 && !strchr(scriptname, '\\')
2796 && (s = PerlEnv_getenv("PATH")))
2801 PL_bufend = s + strlen(s);
2802 while (s < PL_bufend) {
2803 #ifdef MACOS_TRADITIONAL
2804 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2808 #if defined(atarist) || defined(DOSISH)
2813 && *s != ';'; len++, s++) {
2814 if (len < sizeof tmpbuf)
2817 if (len < sizeof tmpbuf)
2819 #else /* ! (atarist || DOSISH) */
2820 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2823 #endif /* ! (atarist || DOSISH) */
2824 #endif /* MACOS_TRADITIONAL */
2827 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2828 continue; /* don't search dir with too-long name */
2829 #ifdef MACOS_TRADITIONAL
2830 if (len && tmpbuf[len - 1] != ':')
2831 tmpbuf[len++] = ':';
2834 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2835 && tmpbuf[len - 1] != '/'
2836 && tmpbuf[len - 1] != '\\'
2839 tmpbuf[len++] = '/';
2840 if (len == 2 && tmpbuf[0] == '.')
2843 (void)strcpy(tmpbuf + len, scriptname);
2847 len = strlen(tmpbuf);
2848 if (extidx > 0) /* reset after previous loop */
2852 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2853 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2854 if (S_ISDIR(PL_statbuf.st_mode)) {
2858 } while ( retval < 0 /* not there */
2859 && extidx>=0 && ext[extidx] /* try an extension? */
2860 && strcpy(tmpbuf+len, ext[extidx++])
2865 if (S_ISREG(PL_statbuf.st_mode)
2866 && cando(S_IRUSR,TRUE,&PL_statbuf)
2867 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2868 && cando(S_IXUSR,TRUE,&PL_statbuf)
2872 xfound = tmpbuf; /* bingo! */
2876 xfailed = savepv(tmpbuf);
2879 if (!xfound && !seen_dot && !xfailed &&
2880 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2881 || S_ISDIR(PL_statbuf.st_mode)))
2883 seen_dot = 1; /* Disable message. */
2885 if (flags & 1) { /* do or die? */
2886 Perl_croak(aTHX_ "Can't %s %s%s%s",
2887 (xfailed ? "execute" : "find"),
2888 (xfailed ? xfailed : scriptname),
2889 (xfailed ? "" : " on PATH"),
2890 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2892 scriptname = Nullch;
2896 scriptname = xfound;
2898 return (scriptname ? savepv(scriptname) : Nullch);
2901 #ifndef PERL_GET_CONTEXT_DEFINED
2904 Perl_get_context(void)
2906 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2907 # ifdef OLD_PTHREADS_API
2909 if (pthread_getspecific(PL_thr_key, &t))
2910 Perl_croak_nocontext("panic: pthread_getspecific");
2913 # ifdef I_MACH_CTHREADS
2914 return (void*)cthread_data(cthread_self());
2916 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2925 Perl_set_context(void *t)
2927 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2928 # ifdef I_MACH_CTHREADS
2929 cthread_set_data(cthread_self(), t);
2931 if (pthread_setspecific(PL_thr_key, t))
2932 Perl_croak_nocontext("panic: pthread_setspecific");
2937 #endif /* !PERL_GET_CONTEXT_DEFINED */
2939 #ifdef USE_5005THREADS
2942 /* Very simplistic scheduler for now */
2946 thr = thr->i.next_run;
2950 Perl_cond_init(pTHX_ perl_cond *cp)
2956 Perl_cond_signal(pTHX_ perl_cond *cp)
2959 perl_cond cond = *cp;
2964 /* Insert t in the runnable queue just ahead of us */
2965 t->i.next_run = thr->i.next_run;
2966 thr->i.next_run->i.prev_run = t;
2967 t->i.prev_run = thr;
2968 thr->i.next_run = t;
2969 thr->i.wait_queue = 0;
2970 /* Remove from the wait queue */
2976 Perl_cond_broadcast(pTHX_ perl_cond *cp)
2979 perl_cond cond, cond_next;
2981 for (cond = *cp; cond; cond = cond_next) {
2983 /* Insert t in the runnable queue just ahead of us */
2984 t->i.next_run = thr->i.next_run;
2985 thr->i.next_run->i.prev_run = t;
2986 t->i.prev_run = thr;
2987 thr->i.next_run = t;
2988 thr->i.wait_queue = 0;
2989 /* Remove from the wait queue */
2990 cond_next = cond->next;
2997 Perl_cond_wait(pTHX_ perl_cond *cp)
3001 if (thr->i.next_run == thr)
3002 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3004 New(666, cond, 1, struct perl_wait_queue);
3008 thr->i.wait_queue = cond;
3009 /* Remove ourselves from runnable queue */
3010 thr->i.next_run->i.prev_run = thr->i.prev_run;
3011 thr->i.prev_run->i.next_run = thr->i.next_run;
3013 #endif /* FAKE_THREADS */
3016 Perl_condpair_magic(pTHX_ SV *sv)
3020 (void)SvUPGRADE(sv, SVt_PVMG);
3021 mg = mg_find(sv, PERL_MAGIC_mutex);
3025 New(53, cp, 1, condpair_t);
3026 MUTEX_INIT(&cp->mutex);
3027 COND_INIT(&cp->owner_cond);
3028 COND_INIT(&cp->cond);
3030 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3031 mg = mg_find(sv, PERL_MAGIC_mutex);
3033 /* someone else beat us to initialising it */
3034 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3035 MUTEX_DESTROY(&cp->mutex);
3036 COND_DESTROY(&cp->owner_cond);
3037 COND_DESTROY(&cp->cond);
3041 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3043 mg->mg_ptr = (char *)cp;
3044 mg->mg_len = sizeof(cp);
3045 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3046 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3047 "%p: condpair_magic %p\n", thr, sv)));
3054 Perl_sv_lock(pTHX_ SV *osv)
3064 mg = condpair_magic(sv);
3065 MUTEX_LOCK(MgMUTEXP(mg));
3066 if (MgOWNER(mg) == thr)
3067 MUTEX_UNLOCK(MgMUTEXP(mg));
3070 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3072 DEBUG_S(PerlIO_printf(Perl_debug_log,
3073 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3074 PTR2UV(thr), PTR2UV(sv)));
3075 MUTEX_UNLOCK(MgMUTEXP(mg));
3076 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3078 UNLOCK_SV_LOCK_MUTEX;
3083 * Make a new perl thread structure using t as a prototype. Some of the
3084 * fields for the new thread are copied from the prototype thread, t,
3085 * so t should not be running in perl at the time this function is
3086 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3087 * thread calling new_struct_thread) clearly satisfies this constraint.
3089 struct perl_thread *
3090 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3092 #if !defined(PERL_IMPLICIT_CONTEXT)
3093 struct perl_thread *thr;
3099 sv = newSVpvn("", 0);
3100 SvGROW(sv, sizeof(struct perl_thread) + 1);
3101 SvCUR_set(sv, sizeof(struct perl_thread));
3102 thr = (Thread) SvPVX(sv);
3104 memset(thr, 0xab, sizeof(struct perl_thread));
3111 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3112 PL_efloatbuf = (char*)NULL;
3115 Zero(thr, 1, struct perl_thread);
3121 PL_curcop = &PL_compiling;
3122 thr->interp = t->interp;
3123 thr->cvcache = newHV();
3124 thr->threadsv = newAV();
3125 thr->specific = newAV();
3126 thr->errsv = newSVpvn("", 0);
3127 thr->flags = THRf_R_JOINABLE;
3129 MUTEX_INIT(&thr->mutex);
3133 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3136 PL_statname = NEWSV(66,0);
3137 PL_errors = newSVpvn("", 0);
3139 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3140 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3141 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3142 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3143 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3145 PL_reginterp_cnt = 0;
3146 PL_lastscream = Nullsv;
3149 PL_reg_start_tmp = 0;
3150 PL_reg_start_tmpl = 0;
3151 PL_reg_poscache = Nullch;
3153 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3155 /* parent thread's data needs to be locked while we make copy */
3156 MUTEX_LOCK(&t->mutex);
3158 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3159 PL_protect = t->Tprotect;
3162 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3163 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3164 PL_curstash = t->Tcurstash; /* always be set to main? */
3166 PL_tainted = t->Ttainted;
3167 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3168 PL_rs = newSVsv(t->Trs);
3169 PL_last_in_gv = Nullgv;
3170 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3171 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3172 PL_chopset = t->Tchopset;
3173 PL_bodytarget = newSVsv(t->Tbodytarget);
3174 PL_toptarget = newSVsv(t->Ttoptarget);
3175 if (t->Tformtarget == t->Ttoptarget)
3176 PL_formtarget = PL_toptarget;
3178 PL_formtarget = PL_bodytarget;
3180 /* Initialise all per-thread SVs that the template thread used */
3181 svp = AvARRAY(t->threadsv);
3182 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3183 if (*svp && *svp != &PL_sv_undef) {
3184 SV *sv = newSVsv(*svp);
3185 av_store(thr->threadsv, i, sv);
3186 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3187 DEBUG_S(PerlIO_printf(Perl_debug_log,
3188 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3192 thr->threadsvp = AvARRAY(thr->threadsv);
3194 MUTEX_LOCK(&PL_threads_mutex);
3196 thr->tid = ++PL_threadnum;
3197 thr->next = t->next;
3200 thr->next->prev = thr;
3201 MUTEX_UNLOCK(&PL_threads_mutex);
3203 /* done copying parent's state */
3204 MUTEX_UNLOCK(&t->mutex);
3206 #ifdef HAVE_THREAD_INTERN
3207 Perl_init_thread_intern(thr);
3208 #endif /* HAVE_THREAD_INTERN */
3211 #endif /* USE_5005THREADS */
3213 #ifdef PERL_GLOBAL_STRUCT
3222 Perl_get_op_names(pTHX)
3228 Perl_get_op_descs(pTHX)
3234 Perl_get_no_modify(pTHX)
3236 return (char*)PL_no_modify;
3240 Perl_get_opargs(pTHX)
3246 Perl_get_ppaddr(pTHX)
3248 return (PPADDR_t*)PL_ppaddr;
3251 #ifndef HAS_GETENV_LEN
3253 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3255 char *env_trans = PerlEnv_getenv(env_elem);
3257 *len = strlen(env_trans);
3264 Perl_get_vtbl(pTHX_ int vtbl_id)
3266 MGVTBL* result = Null(MGVTBL*);
3270 result = &PL_vtbl_sv;
3273 result = &PL_vtbl_env;
3275 case want_vtbl_envelem:
3276 result = &PL_vtbl_envelem;
3279 result = &PL_vtbl_sig;
3281 case want_vtbl_sigelem:
3282 result = &PL_vtbl_sigelem;
3284 case want_vtbl_pack:
3285 result = &PL_vtbl_pack;
3287 case want_vtbl_packelem:
3288 result = &PL_vtbl_packelem;
3290 case want_vtbl_dbline:
3291 result = &PL_vtbl_dbline;
3294 result = &PL_vtbl_isa;
3296 case want_vtbl_isaelem:
3297 result = &PL_vtbl_isaelem;
3299 case want_vtbl_arylen:
3300 result = &PL_vtbl_arylen;
3302 case want_vtbl_glob:
3303 result = &PL_vtbl_glob;
3305 case want_vtbl_mglob:
3306 result = &PL_vtbl_mglob;
3308 case want_vtbl_nkeys:
3309 result = &PL_vtbl_nkeys;
3311 case want_vtbl_taint:
3312 result = &PL_vtbl_taint;
3314 case want_vtbl_substr:
3315 result = &PL_vtbl_substr;
3318 result = &PL_vtbl_vec;
3321 result = &PL_vtbl_pos;
3324 result = &PL_vtbl_bm;
3327 result = &PL_vtbl_fm;
3329 case want_vtbl_uvar:
3330 result = &PL_vtbl_uvar;
3332 #ifdef USE_5005THREADS
3333 case want_vtbl_mutex:
3334 result = &PL_vtbl_mutex;
3337 case want_vtbl_defelem:
3338 result = &PL_vtbl_defelem;
3340 case want_vtbl_regexp:
3341 result = &PL_vtbl_regexp;
3343 case want_vtbl_regdata:
3344 result = &PL_vtbl_regdata;
3346 case want_vtbl_regdatum:
3347 result = &PL_vtbl_regdatum;
3349 #ifdef USE_LOCALE_COLLATE
3350 case want_vtbl_collxfrm:
3351 result = &PL_vtbl_collxfrm;
3354 case want_vtbl_amagic:
3355 result = &PL_vtbl_amagic;
3357 case want_vtbl_amagicelem:
3358 result = &PL_vtbl_amagicelem;
3360 case want_vtbl_backref:
3361 result = &PL_vtbl_backref;
3368 Perl_my_fflush_all(pTHX)
3370 #if defined(FFLUSH_NULL)
3371 return PerlIO_flush(NULL);
3373 # if defined(HAS__FWALK)
3374 /* undocumented, unprototyped, but very useful BSDism */
3375 extern void _fwalk(int (*)(FILE *));
3379 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3381 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3382 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3384 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3385 open_max = sysconf(_SC_OPEN_MAX);
3388 open_max = FOPEN_MAX;
3391 open_max = OPEN_MAX;
3402 for (i = 0; i < open_max; i++)
3403 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3404 STDIO_STREAM_ARRAY[i]._file < open_max &&
3405 STDIO_STREAM_ARRAY[i]._flag)
3406 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3410 SETERRNO(EBADF,RMS$_IFI);
3417 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3422 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3423 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3425 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3426 char *type = OP_IS_SOCKET(op) ||
3427 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3428 "socket" : "filehandle";
3431 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3433 warn_type = WARN_CLOSED;
3437 warn_type = WARN_UNOPENED;
3440 if (gv && isGV(gv)) {
3441 SV *sv = sv_newmortal();
3442 gv_efullname4(sv, gv, Nullch, FALSE);
3446 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3448 Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle %s opened only for %sput",
3450 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3452 Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle opened only for %sput",
3453 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3454 } else if (name && *name) {
3455 Perl_warner(aTHX_ packWARN(warn_type),
3456 "%s%s on %s %s %s", func, pars, vile, type, name);
3457 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3458 Perl_warner(aTHX_ packWARN(warn_type),
3459 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3463 Perl_warner(aTHX_ packWARN(warn_type),
3464 "%s%s on %s %s", func, pars, vile, type);
3465 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3466 Perl_warner(aTHX_ packWARN(warn_type),
3467 "\t(Are you trying to call %s%s on dirhandle?)\n",
3473 /* in ASCII order, not that it matters */
3474 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3477 Perl_ebcdic_control(pTHX_ int ch)
3485 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3486 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3489 if (ctlp == controllablechars)
3490 return('\177'); /* DEL */
3492 return((unsigned char)(ctlp - controllablechars - 1));
3493 } else { /* Want uncontrol */
3494 if (ch == '\177' || ch == -1)
3496 else if (ch == '\157')
3498 else if (ch == '\174')
3500 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3502 else if (ch == '\155')
3504 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3505 return(controllablechars[ch+1]);
3507 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3512 /* To workaround core dumps from the uninitialised tm_zone we get the
3513 * system to give us a reasonable struct to copy. This fix means that
3514 * strftime uses the tm_zone and tm_gmtoff values returned by
3515 * localtime(time()). That should give the desired result most of the
3516 * time. But probably not always!
3518 * This does not address tzname aspects of NETaa14816.
3523 # ifndef STRUCT_TM_HASZONE
3524 # define STRUCT_TM_HASZONE
3528 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3529 # ifndef HAS_TM_TM_ZONE
3530 # define HAS_TM_TM_ZONE
3535 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3537 #ifdef HAS_TM_TM_ZONE
3540 Copy(localtime(&now), ptm, 1, struct tm);
3545 * mini_mktime - normalise struct tm values without the localtime()
3546 * semantics (and overhead) of mktime().
3549 Perl_mini_mktime(pTHX_ struct tm *ptm)
3553 int month, mday, year, jday;
3554 int odd_cent, odd_year;
3556 #define DAYS_PER_YEAR 365
3557 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3558 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3559 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3560 #define SECS_PER_HOUR (60*60)
3561 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3562 /* parentheses deliberately absent on these two, otherwise they don't work */
3563 #define MONTH_TO_DAYS 153/5
3564 #define DAYS_TO_MONTH 5/153
3565 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3566 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3567 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3568 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3571 * Year/day algorithm notes:
3573 * With a suitable offset for numeric value of the month, one can find
3574 * an offset into the year by considering months to have 30.6 (153/5) days,
3575 * using integer arithmetic (i.e., with truncation). To avoid too much
3576 * messing about with leap days, we consider January and February to be
3577 * the 13th and 14th month of the previous year. After that transformation,
3578 * we need the month index we use to be high by 1 from 'normal human' usage,
3579 * so the month index values we use run from 4 through 15.
3581 * Given that, and the rules for the Gregorian calendar (leap years are those
3582 * divisible by 4 unless also divisible by 100, when they must be divisible
3583 * by 400 instead), we can simply calculate the number of days since some
3584 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3585 * the days we derive from our month index, and adding in the day of the
3586 * month. The value used here is not adjusted for the actual origin which
3587 * it normally would use (1 January A.D. 1), since we're not exposing it.
3588 * We're only building the value so we can turn around and get the
3589 * normalised values for the year, month, day-of-month, and day-of-year.
3591 * For going backward, we need to bias the value we're using so that we find
3592 * the right year value. (Basically, we don't want the contribution of
3593 * March 1st to the number to apply while deriving the year). Having done
3594 * that, we 'count up' the contribution to the year number by accounting for
3595 * full quadracenturies (400-year periods) with their extra leap days, plus
3596 * the contribution from full centuries (to avoid counting in the lost leap
3597 * days), plus the contribution from full quad-years (to count in the normal
3598 * leap days), plus the leftover contribution from any non-leap years.
3599 * At this point, if we were working with an actual leap day, we'll have 0
3600 * days left over. This is also true for March 1st, however. So, we have
3601 * to special-case that result, and (earlier) keep track of the 'odd'
3602 * century and year contributions. If we got 4 extra centuries in a qcent,
3603 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3604 * Otherwise, we add back in the earlier bias we removed (the 123 from
3605 * figuring in March 1st), find the month index (integer division by 30.6),
3606 * and the remainder is the day-of-month. We then have to convert back to
3607 * 'real' months (including fixing January and February from being 14/15 in
3608 * the previous year to being in the proper year). After that, to get
3609 * tm_yday, we work with the normalised year and get a new yearday value for
3610 * January 1st, which we subtract from the yearday value we had earlier,
3611 * representing the date we've re-built. This is done from January 1
3612 * because tm_yday is 0-origin.
3614 * Since POSIX time routines are only guaranteed to work for times since the
3615 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3616 * applies Gregorian calendar rules even to dates before the 16th century
3617 * doesn't bother me. Besides, you'd need cultural context for a given
3618 * date to know whether it was Julian or Gregorian calendar, and that's
3619 * outside the scope for this routine. Since we convert back based on the
3620 * same rules we used to build the yearday, you'll only get strange results
3621 * for input which needed normalising, or for the 'odd' century years which
3622 * were leap years in the Julian calander but not in the Gregorian one.
3623 * I can live with that.
3625 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3626 * that's still outside the scope for POSIX time manipulation, so I don't
3630 year = 1900 + ptm->tm_year;
3631 month = ptm->tm_mon;
3632 mday = ptm->tm_mday;
3633 /* allow given yday with no month & mday to dominate the result */
3634 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3637 jday = 1 + ptm->tm_yday;
3646 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3647 yearday += month*MONTH_TO_DAYS + mday + jday;
3649 * Note that we don't know when leap-seconds were or will be,
3650 * so we have to trust the user if we get something which looks
3651 * like a sensible leap-second. Wild values for seconds will
3652 * be rationalised, however.
3654 if ((unsigned) ptm->tm_sec <= 60) {
3661 secs += 60 * ptm->tm_min;
3662 secs += SECS_PER_HOUR * ptm->tm_hour;
3664 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3665 /* got negative remainder, but need positive time */
3666 /* back off an extra day to compensate */
3667 yearday += (secs/SECS_PER_DAY)-1;
3668 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3671 yearday += (secs/SECS_PER_DAY);
3672 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3675 else if (secs >= SECS_PER_DAY) {
3676 yearday += (secs/SECS_PER_DAY);
3677 secs %= SECS_PER_DAY;
3679 ptm->tm_hour = secs/SECS_PER_HOUR;
3680 secs %= SECS_PER_HOUR;
3681 ptm->tm_min = secs/60;
3683 ptm->tm_sec += secs;
3684 /* done with time of day effects */
3686 * The algorithm for yearday has (so far) left it high by 428.
3687 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3688 * bias it by 123 while trying to figure out what year it
3689 * really represents. Even with this tweak, the reverse
3690 * translation fails for years before A.D. 0001.
3691 * It would still fail for Feb 29, but we catch that one below.
3693 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3694 yearday -= YEAR_ADJUST;
3695 year = (yearday / DAYS_PER_QCENT) * 400;
3696 yearday %= DAYS_PER_QCENT;
3697 odd_cent = yearday / DAYS_PER_CENT;
3698 year += odd_cent * 100;
3699 yearday %= DAYS_PER_CENT;
3700 year += (yearday / DAYS_PER_QYEAR) * 4;
3701 yearday %= DAYS_PER_QYEAR;
3702 odd_year = yearday / DAYS_PER_YEAR;
3704 yearday %= DAYS_PER_YEAR;
3705 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3710 yearday += YEAR_ADJUST; /* recover March 1st crock */
3711 month = yearday*DAYS_TO_MONTH;
3712 yearday -= month*MONTH_TO_DAYS;
3713 /* recover other leap-year adjustment */
3722 ptm->tm_year = year - 1900;
3724 ptm->tm_mday = yearday;
3725 ptm->tm_mon = month;
3729 ptm->tm_mon = month - 1;
3731 /* re-build yearday based on Jan 1 to get tm_yday */
3733 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3734 yearday += 14*MONTH_TO_DAYS + 1;
3735 ptm->tm_yday = jday - yearday;
3736 /* fix tm_wday if not overridden by caller */
3737 if ((unsigned)ptm->tm_wday > 6)
3738 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3742 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3750 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3753 mytm.tm_hour = hour;
3754 mytm.tm_mday = mday;
3756 mytm.tm_year = year;
3757 mytm.tm_wday = wday;
3758 mytm.tm_yday = yday;
3759 mytm.tm_isdst = isdst;
3762 New(0, buf, buflen, char);
3763 len = strftime(buf, buflen, fmt, &mytm);
3765 ** The following is needed to handle to the situation where
3766 ** tmpbuf overflows. Basically we want to allocate a buffer
3767 ** and try repeatedly. The reason why it is so complicated
3768 ** is that getting a return value of 0 from strftime can indicate
3769 ** one of the following:
3770 ** 1. buffer overflowed,
3771 ** 2. illegal conversion specifier, or
3772 ** 3. the format string specifies nothing to be returned(not
3773 ** an error). This could be because format is an empty string
3774 ** or it specifies %p that yields an empty string in some locale.
3775 ** If there is a better way to make it portable, go ahead by
3778 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3781 /* Possibly buf overflowed - try again with a bigger buf */
3782 int fmtlen = strlen(fmt);
3783 int bufsize = fmtlen + buflen;
3785 New(0, buf, bufsize, char);
3787 buflen = strftime(buf, bufsize, fmt, &mytm);
3788 if (buflen > 0 && buflen < bufsize)
3790 /* heuristic to prevent out-of-memory errors */
3791 if (bufsize > 100*fmtlen) {
3797 Renew(buf, bufsize, char);
3802 Perl_croak(aTHX_ "panic: no strftime");
3807 #define SV_CWD_RETURN_UNDEF \
3808 sv_setsv(sv, &PL_sv_undef); \
3811 #define SV_CWD_ISDOT(dp) \
3812 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3813 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3816 =head1 Miscellaneous Functions
3818 =for apidoc getcwd_sv
3820 Fill the sv with current working directory
3825 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3826 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3827 * getcwd(3) if available
3828 * Comments from the orignal:
3829 * This is a faster version of getcwd. It's also more dangerous
3830 * because you might chdir out of a directory that you can't chdir
3834 Perl_getcwd_sv(pTHX_ register SV *sv)
3838 #ifndef INCOMPLETE_TAINTS
3844 char buf[MAXPATHLEN];
3846 /* Some getcwd()s automatically allocate a buffer of the given
3847 * size from the heap if they are given a NULL buffer pointer.
3848 * The problem is that this behaviour is not portable. */
3849 if (getcwd(buf, sizeof(buf) - 1)) {
3850 STRLEN len = strlen(buf);
3851 sv_setpvn(sv, buf, len);
3855 sv_setsv(sv, &PL_sv_undef);
3862 struct stat statbuf;
3863 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3864 int namelen, pathlen=0;
3868 (void)SvUPGRADE(sv, SVt_PV);
3870 if (PerlLIO_lstat(".", &statbuf) < 0) {
3871 SV_CWD_RETURN_UNDEF;
3874 orig_cdev = statbuf.st_dev;
3875 orig_cino = statbuf.st_ino;
3883 if (PerlDir_chdir("..") < 0) {
3884 SV_CWD_RETURN_UNDEF;
3886 if (PerlLIO_stat(".", &statbuf) < 0) {
3887 SV_CWD_RETURN_UNDEF;
3890 cdev = statbuf.st_dev;
3891 cino = statbuf.st_ino;
3893 if (odev == cdev && oino == cino) {
3896 if (!(dir = PerlDir_open("."))) {
3897 SV_CWD_RETURN_UNDEF;
3900 while ((dp = PerlDir_read(dir)) != NULL) {
3902 namelen = dp->d_namlen;
3904 namelen = strlen(dp->d_name);
3907 if (SV_CWD_ISDOT(dp)) {
3911 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3912 SV_CWD_RETURN_UNDEF;
3915 tdev = statbuf.st_dev;
3916 tino = statbuf.st_ino;
3917 if (tino == oino && tdev == odev) {
3923 SV_CWD_RETURN_UNDEF;
3926 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3927 SV_CWD_RETURN_UNDEF;
3930 SvGROW(sv, pathlen + namelen + 1);
3934 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3937 /* prepend current directory to the front */
3939 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3940 pathlen += (namelen + 1);
3942 #ifdef VOID_CLOSEDIR
3945 if (PerlDir_close(dir) < 0) {
3946 SV_CWD_RETURN_UNDEF;
3952 SvCUR_set(sv, pathlen);
3956 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3957 SV_CWD_RETURN_UNDEF;
3960 if (PerlLIO_stat(".", &statbuf) < 0) {
3961 SV_CWD_RETURN_UNDEF;
3964 cdev = statbuf.st_dev;
3965 cino = statbuf.st_ino;
3967 if (cdev != orig_cdev || cino != orig_cino) {
3968 Perl_croak(aTHX_ "Unstable directory path, "
3969 "current directory changed unexpectedly");
3981 =head1 SV Manipulation Functions
3983 =for apidoc new_vstring
3985 Returns a pointer to the next character after the parsed
3986 vstring, as well as updating the passed in sv.
3988 Function must be called like
3991 s = new_vstring(s,sv);
3993 The sv must already be large enough to store the vstring
4000 Perl_new_vstring(pTHX_ char *s, SV *sv)
4003 if (*pos == 'v') pos++; /* get past 'v' */
4004 while (isDIGIT(*pos) || *pos == '_')
4006 if (!isALPHA(*pos)) {
4008 U8 tmpbuf[UTF8_MAXLEN+1];
4011 if (*s == 'v') s++; /* get past 'v' */
4013 sv_setpvn(sv, "", 0);
4018 /* this is atoi() that tolerates underscores */
4021 if ( s > pos && *(s-1) == '_') {
4024 while (--end >= s) {
4027 rev += (*end - '0') * mult;
4029 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
4030 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4031 "Integer overflow in decimal number");
4035 if (rev > 0x7FFFFFFF)
4036 Perl_croak(aTHX "In EBCDIC the v-string components cannot exceed 2147483647");
4038 /* Append native character for the rev point */
4039 tmpend = uvchr_to_utf8(tmpbuf, rev);
4040 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
4041 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
4043 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
4049 while (isDIGIT(*pos) )
4058 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4059 # define EMULATE_SOCKETPAIR_UDP
4062 #ifdef EMULATE_SOCKETPAIR_UDP
4064 S_socketpair_udp (int fd[2]) {
4066 /* Fake a datagram socketpair using UDP to localhost. */
4067 int sockets[2] = {-1, -1};
4068 struct sockaddr_in addresses[2];
4070 Sock_size_t size = sizeof (struct sockaddr_in);
4071 unsigned short port;
4074 memset (&addresses, 0, sizeof (addresses));
4077 sockets[i] = PerlSock_socket (AF_INET, SOCK_DGRAM, PF_INET);
4078 if (sockets[i] == -1)
4079 goto tidy_up_and_fail;
4081 addresses[i].sin_family = AF_INET;
4082 addresses[i].sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4083 addresses[i].sin_port = 0; /* kernel choses port. */
4084 if (PerlSock_bind (sockets[i], (struct sockaddr *) &addresses[i],
4085 sizeof (struct sockaddr_in))
4087 goto tidy_up_and_fail;
4090 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4091 for each connect the other socket to it. */
4094 if (PerlSock_getsockname (sockets[i], (struct sockaddr *) &addresses[i], &size)
4096 goto tidy_up_and_fail;
4097 if (size != sizeof (struct sockaddr_in))
4098 goto abort_tidy_up_and_fail;
4099 /* !1 is 0, !0 is 1 */
4100 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4101 sizeof (struct sockaddr_in)) == -1)
4102 goto tidy_up_and_fail;
4105 /* Now we have 2 sockets connected to each other. I don't trust some other
4106 process not to have already sent a packet to us (by random) so send
4107 a packet from each to the other. */
4110 /* I'm going to send my own port number. As a short.
4111 (Who knows if someone somewhere has sin_port as a bitfield and needs
4112 this routine. (I'm assuming crays have socketpair)) */
4113 port = addresses[i].sin_port;
4114 got = PerlLIO_write (sockets[i], &port, sizeof(port));
4115 if (got != sizeof(port)) {
4117 goto tidy_up_and_fail;
4118 goto abort_tidy_up_and_fail;
4122 /* Packets sent. I don't trust them to have arrived though.
4123 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4124 connect to localhost will use a second kernel thread. In 2.6 the
4125 first thread running the connect() returns before the second completes,
4126 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4127 returns 0. Poor programs have tripped up. One poor program's authors'
4128 had a 50-1 reverse stock split. Not sure how connected these were.)
4129 So I don't trust someone not to have an unpredictable UDP stack.
4133 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4134 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4138 FD_SET (sockets[0], &rset);
4139 FD_SET (sockets[1], &rset);
4141 got = PerlSock_select (max + 1, &rset, NULL, NULL, &waitfor);
4142 if (got != 2 || !FD_ISSET (sockets[0], &rset)
4143 || !FD_ISSET (sockets[1], &rset)) {
4144 /* I hope this is portable and appropriate. */
4146 goto tidy_up_and_fail;
4147 goto abort_tidy_up_and_fail;
4151 /* And the paranoia department even now doesn't trust it to have arrive
4152 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4154 struct sockaddr_in readfrom;
4155 unsigned short buffer[2];
4160 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4162 (struct sockaddr *) &readfrom, &size);
4164 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4166 (struct sockaddr *) &readfrom, &size);
4170 goto tidy_up_and_fail;
4171 if (got != sizeof(port)
4172 || size != sizeof (struct sockaddr_in)
4173 /* Check other socket sent us its port. */
4174 || buffer[0] != (unsigned short) addresses[!i].sin_port
4175 /* Check kernel says we got the datagram from that socket. */
4176 || readfrom.sin_family != addresses[!i].sin_family
4177 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4178 || readfrom.sin_port != addresses[!i].sin_port)
4179 goto abort_tidy_up_and_fail;
4182 /* My caller (my_socketpair) has validated that this is non-NULL */
4185 /* I hereby declare this connection open. May God bless all who cross
4189 abort_tidy_up_and_fail:
4190 errno = ECONNABORTED;
4193 int save_errno = errno;
4194 if (sockets[0] != -1)
4195 PerlLIO_close (sockets[0]);
4196 if (sockets[1] != -1)
4197 PerlLIO_close (sockets[1]);
4202 #endif /* EMULATE_SOCKETPAIR_UDP */
4204 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4206 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4207 /* Stevens says that family must be AF_LOCAL, protocol 0.
4208 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4213 struct sockaddr_in listen_addr;
4214 struct sockaddr_in connect_addr;
4219 || family != AF_UNIX
4222 errno = EAFNOSUPPORT;
4230 #ifdef EMULATE_SOCKETPAIR_UDP
4231 if (type == SOCK_DGRAM)
4232 return S_socketpair_udp (fd);
4235 listener = PerlSock_socket (AF_INET, type, 0);
4238 memset (&listen_addr, 0, sizeof (listen_addr));
4239 listen_addr.sin_family = AF_INET;
4240 listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4241 listen_addr.sin_port = 0; /* kernel choses port. */
4242 if (PerlSock_bind (listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
4244 goto tidy_up_and_fail;
4245 if (PerlSock_listen(listener, 1) == -1)
4246 goto tidy_up_and_fail;
4248 connector = PerlSock_socket (AF_INET, type, 0);
4249 if (connector == -1)
4250 goto tidy_up_and_fail;
4251 /* We want to find out the port number to connect to. */
4252 size = sizeof (connect_addr);
4253 if (PerlSock_getsockname (listener, (struct sockaddr *) &connect_addr, &size) == -1)
4254 goto tidy_up_and_fail;
4255 if (size != sizeof (connect_addr))
4256 goto abort_tidy_up_and_fail;
4257 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4258 sizeof (connect_addr)) == -1)
4259 goto tidy_up_and_fail;
4261 size = sizeof (listen_addr);
4262 acceptor = PerlSock_accept (listener, (struct sockaddr *) &listen_addr, &size);
4264 goto tidy_up_and_fail;
4265 if (size != sizeof (listen_addr))
4266 goto abort_tidy_up_and_fail;
4267 PerlLIO_close (listener);
4268 /* Now check we are talking to ourself by matching port and host on the
4270 if (PerlSock_getsockname (connector, (struct sockaddr *) &connect_addr, &size) == -1)
4271 goto tidy_up_and_fail;
4272 if (size != sizeof (connect_addr)
4273 || listen_addr.sin_family != connect_addr.sin_family
4274 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4275 || listen_addr.sin_port != connect_addr.sin_port) {
4276 goto abort_tidy_up_and_fail;
4282 abort_tidy_up_and_fail:
4283 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4286 int save_errno = errno;
4288 PerlLIO_close (listener);
4289 if (connector != -1)
4290 PerlLIO_close (connector);
4292 PerlLIO_close (acceptor);
4298 /* In any case have a stub so that there's code corresponding
4299 * to the my_socketpair in global.sym. */
4301 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4302 return socketpair(family, type, protocol, fd);
4308 =for apidoc sv_nosharing
4310 Dummy routine which "shares" an SV when there is no sharing module present.
4311 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4312 some level of strict-ness.
4318 Perl_sv_nosharing(pTHX_ SV *sv)
4323 =for apidoc sv_nolocking
4325 Dummy routine which "locks" an SV when there is no locking module present.
4326 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4327 some level of strict-ness.
4333 Perl_sv_nolocking(pTHX_ SV *sv)
4339 =for apidoc sv_nounlocking
4341 Dummy routine which "unlocks" an SV when there is no locking module present.
4342 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4343 some level of strict-ness.
4349 Perl_sv_nounlocking(pTHX_ SV *sv)