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)
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 PerlMem_malloc(nbytes);
345 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
348 return PerlMem_calloc(elements, size);
351 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
354 return 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;
896 New(902,newaddr,strlen(sv)+1,char);
897 (void)strcpy(newaddr,sv);
901 /* same thing but with a known length */
906 Copy a string to a safe spot. The C<len> indicates number of bytes to
907 copy. This does not use an SV.
913 Perl_savepvn(pTHX_ const char *sv, register I32 len)
915 register char *newaddr;
917 New(903,newaddr,len+1,char);
918 Copy(sv,newaddr,len,char); /* might not be null terminated */
919 newaddr[len] = '\0'; /* is now */
923 /* the SV for Perl_form() and mess() is not kept in an arena */
932 return sv_2mortal(newSVpvn("",0));
937 /* Create as PVMG now, to avoid any upgrading later */
939 Newz(905, any, 1, XPVMG);
940 SvFLAGS(sv) = SVt_PVMG;
941 SvANY(sv) = (void*)any;
942 SvREFCNT(sv) = 1 << 30; /* practically infinite */
947 #if defined(PERL_IMPLICIT_CONTEXT)
949 Perl_form_nocontext(const char* pat, ...)
955 retval = vform(pat, &args);
959 #endif /* PERL_IMPLICIT_CONTEXT */
962 =head1 Miscellaneous Functions
965 Takes a sprintf-style format pattern and conventional
966 (non-SV) arguments and returns the formatted string.
968 (char *) Perl_form(pTHX_ const char* pat, ...)
970 can be used any place a string (char *) is required:
972 char * s = Perl_form("%d.%d",major,minor);
974 Uses a single private buffer so if you want to format several strings you
975 must explicitly copy the earlier strings away (and free the copies when you
982 Perl_form(pTHX_ const char* pat, ...)
987 retval = vform(pat, &args);
993 Perl_vform(pTHX_ const char *pat, va_list *args)
995 SV *sv = mess_alloc();
996 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1000 #if defined(PERL_IMPLICIT_CONTEXT)
1002 Perl_mess_nocontext(const char *pat, ...)
1007 va_start(args, pat);
1008 retval = vmess(pat, &args);
1012 #endif /* PERL_IMPLICIT_CONTEXT */
1015 Perl_mess(pTHX_ const char *pat, ...)
1019 va_start(args, pat);
1020 retval = vmess(pat, &args);
1026 S_closest_cop(pTHX_ COP *cop, OP *o)
1028 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1030 if (!o || o == PL_op) return cop;
1032 if (o->op_flags & OPf_KIDS) {
1034 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1038 /* If the OP_NEXTSTATE has been optimised away we can still use it
1039 * the get the file and line number. */
1041 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1044 /* Keep searching, and return when we've found something. */
1046 new_cop = closest_cop(cop, kid);
1047 if (new_cop) return new_cop;
1051 /* Nothing found. */
1057 Perl_vmess(pTHX_ const char *pat, va_list *args)
1059 SV *sv = mess_alloc();
1060 static char dgd[] = " during global destruction.\n";
1063 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1064 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1067 * Try and find the file and line for PL_op. This will usually be
1068 * PL_curcop, but it might be a cop that has been optimised away. We
1069 * can try to find such a cop by searching through the optree starting
1070 * from the sibling of PL_curcop.
1073 cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1074 if (!cop) cop = PL_curcop;
1077 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1078 CopFILE(cop), (IV)CopLINE(cop));
1079 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1080 bool line_mode = (RsSIMPLE(PL_rs) &&
1081 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1082 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1083 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1084 line_mode ? "line" : "chunk",
1085 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1087 #ifdef USE_5005THREADS
1089 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1091 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1097 Perl_vdie(pTHX_ const char* pat, va_list *args)
1100 int was_in_eval = PL_in_eval;
1107 DEBUG_S(PerlIO_printf(Perl_debug_log,
1108 "%p: die: curstack = %p, mainstack = %p\n",
1109 thr, PL_curstack, PL_mainstack));
1112 msv = vmess(pat, args);
1113 if (PL_errors && SvCUR(PL_errors)) {
1114 sv_catsv(PL_errors, msv);
1115 message = SvPV(PL_errors, msglen);
1116 SvCUR_set(PL_errors, 0);
1119 message = SvPV(msv,msglen);
1126 DEBUG_S(PerlIO_printf(Perl_debug_log,
1127 "%p: die: message = %s\ndiehook = %p\n",
1128 thr, message, PL_diehook));
1130 /* sv_2cv might call Perl_croak() */
1131 SV *olddiehook = PL_diehook;
1133 SAVESPTR(PL_diehook);
1134 PL_diehook = Nullsv;
1135 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1137 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1144 msg = newSVpvn(message, msglen);
1152 PUSHSTACKi(PERLSI_DIEHOOK);
1156 call_sv((SV*)cv, G_DISCARD);
1162 PL_restartop = die_where(message, msglen);
1163 DEBUG_S(PerlIO_printf(Perl_debug_log,
1164 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1165 thr, PL_restartop, was_in_eval, PL_top_env));
1166 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1168 return PL_restartop;
1171 #if defined(PERL_IMPLICIT_CONTEXT)
1173 Perl_die_nocontext(const char* pat, ...)
1178 va_start(args, pat);
1179 o = vdie(pat, &args);
1183 #endif /* PERL_IMPLICIT_CONTEXT */
1186 Perl_die(pTHX_ const char* pat, ...)
1190 va_start(args, pat);
1191 o = vdie(pat, &args);
1197 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1207 msv = vmess(pat, args);
1208 if (PL_errors && SvCUR(PL_errors)) {
1209 sv_catsv(PL_errors, msv);
1210 message = SvPV(PL_errors, msglen);
1211 SvCUR_set(PL_errors, 0);
1214 message = SvPV(msv,msglen);
1221 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1222 PTR2UV(thr), message));
1225 /* sv_2cv might call Perl_croak() */
1226 SV *olddiehook = PL_diehook;
1228 SAVESPTR(PL_diehook);
1229 PL_diehook = Nullsv;
1230 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1232 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1239 msg = newSVpvn(message, msglen);
1247 PUSHSTACKi(PERLSI_DIEHOOK);
1251 call_sv((SV*)cv, G_DISCARD);
1257 PL_restartop = die_where(message, msglen);
1261 message = SvPVx(ERRSV, msglen);
1265 /* SFIO can really mess with your errno */
1268 PerlIO *serr = Perl_error_log;
1270 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1271 (void)PerlIO_flush(serr);
1279 #if defined(PERL_IMPLICIT_CONTEXT)
1281 Perl_croak_nocontext(const char *pat, ...)
1285 va_start(args, pat);
1290 #endif /* PERL_IMPLICIT_CONTEXT */
1293 =head1 Warning and Dieing
1297 This is the XSUB-writer's interface to Perl's C<die> function.
1298 Normally use this function the same way you use the C C<printf>
1299 function. See C<warn>.
1301 If you want to throw an exception object, assign the object to
1302 C<$@> and then pass C<Nullch> to croak():
1304 errsv = get_sv("@", TRUE);
1305 sv_setsv(errsv, exception_object);
1312 Perl_croak(pTHX_ const char *pat, ...)
1315 va_start(args, pat);
1322 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1331 msv = vmess(pat, args);
1332 message = SvPV(msv, msglen);
1335 /* sv_2cv might call Perl_warn() */
1336 SV *oldwarnhook = PL_warnhook;
1338 SAVESPTR(PL_warnhook);
1339 PL_warnhook = Nullsv;
1340 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1342 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1348 msg = newSVpvn(message, msglen);
1352 PUSHSTACKi(PERLSI_WARNHOOK);
1356 call_sv((SV*)cv, G_DISCARD);
1363 PerlIO *serr = Perl_error_log;
1365 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1367 DEBUG_L(*message == '!'
1368 ? (xstat(message[1]=='!'
1369 ? (message[2]=='!' ? 2 : 1)
1374 (void)PerlIO_flush(serr);
1378 #if defined(PERL_IMPLICIT_CONTEXT)
1380 Perl_warn_nocontext(const char *pat, ...)
1384 va_start(args, pat);
1388 #endif /* PERL_IMPLICIT_CONTEXT */
1393 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1394 function the same way you use the C C<printf> function. See
1401 Perl_warn(pTHX_ const char *pat, ...)
1404 va_start(args, pat);
1409 #if defined(PERL_IMPLICIT_CONTEXT)
1411 Perl_warner_nocontext(U32 err, const char *pat, ...)
1415 va_start(args, pat);
1416 vwarner(err, pat, &args);
1419 #endif /* PERL_IMPLICIT_CONTEXT */
1422 Perl_warner(pTHX_ U32 err, const char* pat,...)
1425 va_start(args, pat);
1426 vwarner(err, pat, &args);
1431 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1440 msv = vmess(pat, args);
1441 message = SvPV(msv, msglen);
1444 #ifdef USE_5005THREADS
1445 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1446 #endif /* USE_5005THREADS */
1448 /* sv_2cv might call Perl_croak() */
1449 SV *olddiehook = PL_diehook;
1451 SAVESPTR(PL_diehook);
1452 PL_diehook = Nullsv;
1453 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1455 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1461 msg = newSVpvn(message, msglen);
1465 PUSHSTACKi(PERLSI_DIEHOOK);
1469 call_sv((SV*)cv, G_DISCARD);
1475 PL_restartop = die_where(message, msglen);
1479 PerlIO *serr = Perl_error_log;
1480 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1481 (void)PerlIO_flush(serr);
1488 /* sv_2cv might call Perl_warn() */
1489 SV *oldwarnhook = PL_warnhook;
1491 SAVESPTR(PL_warnhook);
1492 PL_warnhook = Nullsv;
1493 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1495 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1501 msg = newSVpvn(message, msglen);
1505 PUSHSTACKi(PERLSI_WARNHOOK);
1509 call_sv((SV*)cv, G_DISCARD);
1516 PerlIO *serr = Perl_error_log;
1517 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1519 DEBUG_L(*message == '!'
1520 ? (xstat(message[1]=='!'
1521 ? (message[2]=='!' ? 2 : 1)
1526 (void)PerlIO_flush(serr);
1531 /* since we've already done strlen() for both nam and val
1532 * we can use that info to make things faster than
1533 * sprintf(s, "%s=%s", nam, val)
1535 #define my_setenv_format(s, nam, nlen, val, vlen) \
1536 Copy(nam, s, nlen, char); \
1538 Copy(val, s+(nlen+1), vlen, char); \
1539 *(s+(nlen+1+vlen)) = '\0'
1541 #ifdef USE_ENVIRON_ARRAY
1542 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1543 #if !defined(WIN32) && !defined(NETWARE)
1545 Perl_my_setenv(pTHX_ char *nam, char *val)
1547 #ifndef PERL_USE_SAFE_PUTENV
1548 /* most putenv()s leak, so we manipulate environ directly */
1549 register I32 i=setenv_getix(nam); /* where does it go? */
1552 if (environ == PL_origenviron) { /* need we copy environment? */
1558 for (max = i; environ[max]; max++) ;
1559 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1560 for (j=0; j<max; j++) { /* copy environment */
1561 int len = strlen(environ[j]);
1562 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1563 Copy(environ[j], tmpenv[j], len+1, char);
1565 tmpenv[max] = Nullch;
1566 environ = tmpenv; /* tell exec where it is now */
1569 safesysfree(environ[i]);
1570 while (environ[i]) {
1571 environ[i] = environ[i+1];
1576 if (!environ[i]) { /* does not exist yet */
1577 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1578 environ[i+1] = Nullch; /* make sure it's null terminated */
1581 safesysfree(environ[i]);
1585 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1586 /* all that work just for this */
1587 my_setenv_format(environ[i], nam, nlen, val, vlen);
1589 #else /* PERL_USE_SAFE_PUTENV */
1590 # if defined(__CYGWIN__)
1591 setenv(nam, val, 1);
1594 int nlen = strlen(nam), vlen;
1599 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1600 /* all that work just for this */
1601 my_setenv_format(new_env, nam, nlen, val, vlen);
1602 (void)putenv(new_env);
1603 # endif /* __CYGWIN__ */
1604 #endif /* PERL_USE_SAFE_PUTENV */
1607 #else /* WIN32 || NETWARE */
1610 Perl_my_setenv(pTHX_ char *nam,char *val)
1612 register char *envstr;
1613 int nlen = strlen(nam), vlen;
1619 New(904, envstr, nlen+vlen+2, char);
1620 my_setenv_format(envstr, nam, nlen, val, vlen);
1621 (void)PerlEnv_putenv(envstr);
1625 #endif /* WIN32 || NETWARE */
1628 Perl_setenv_getix(pTHX_ char *nam)
1630 register I32 i, len = strlen(nam);
1632 for (i = 0; environ[i]; i++) {
1635 strnicmp(environ[i],nam,len) == 0
1637 strnEQ(environ[i],nam,len)
1639 && environ[i][len] == '=')
1640 break; /* strnEQ must come first to avoid */
1641 } /* potential SEGV's */
1645 #endif /* !VMS && !EPOC*/
1647 #ifdef UNLINK_ALL_VERSIONS
1649 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1653 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1658 /* this is a drop-in replacement for bcopy() */
1659 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1661 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1665 if (from - to >= 0) {
1673 *(--to) = *(--from);
1679 /* this is a drop-in replacement for memset() */
1682 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1692 /* this is a drop-in replacement for bzero() */
1693 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1695 Perl_my_bzero(register char *loc, register I32 len)
1705 /* this is a drop-in replacement for memcmp() */
1706 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1708 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1710 register U8 *a = (U8 *)s1;
1711 register U8 *b = (U8 *)s2;
1715 if (tmp = *a++ - *b++)
1720 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1724 #ifdef USE_CHAR_VSPRINTF
1729 vsprintf(char *dest, const char *pat, char *args)
1733 fakebuf._ptr = dest;
1734 fakebuf._cnt = 32767;
1738 fakebuf._flag = _IOWRT|_IOSTRG;
1739 _doprnt(pat, args, &fakebuf); /* what a kludge */
1740 (void)putc('\0', &fakebuf);
1741 #ifdef USE_CHAR_VSPRINTF
1744 return 0; /* perl doesn't use return value */
1748 #endif /* HAS_VPRINTF */
1751 #if BYTEORDER != 0x4321
1753 Perl_my_swap(pTHX_ short s)
1755 #if (BYTEORDER & 1) == 0
1758 result = ((s & 255) << 8) + ((s >> 8) & 255);
1766 Perl_my_htonl(pTHX_ long l)
1770 char c[sizeof(long)];
1773 #if BYTEORDER == 0x1234
1774 u.c[0] = (l >> 24) & 255;
1775 u.c[1] = (l >> 16) & 255;
1776 u.c[2] = (l >> 8) & 255;
1780 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1781 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1786 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1787 u.c[o & 0xf] = (l >> s) & 255;
1795 Perl_my_ntohl(pTHX_ long l)
1799 char c[sizeof(long)];
1802 #if BYTEORDER == 0x1234
1803 u.c[0] = (l >> 24) & 255;
1804 u.c[1] = (l >> 16) & 255;
1805 u.c[2] = (l >> 8) & 255;
1809 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1810 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1817 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1818 l |= (u.c[o & 0xf] & 255) << s;
1825 #endif /* BYTEORDER != 0x4321 */
1829 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1830 * If these functions are defined,
1831 * the BYTEORDER is neither 0x1234 nor 0x4321.
1832 * However, this is not assumed.
1836 #define HTOV(name,type) \
1838 name (register type n) \
1842 char c[sizeof(type)]; \
1846 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1847 u.c[i] = (n >> s) & 0xFF; \
1852 #define VTOH(name,type) \
1854 name (register type n) \
1858 char c[sizeof(type)]; \
1864 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1865 n += (u.c[i] & 0xFF) << s; \
1870 #if defined(HAS_HTOVS) && !defined(htovs)
1873 #if defined(HAS_HTOVL) && !defined(htovl)
1876 #if defined(HAS_VTOHS) && !defined(vtohs)
1879 #if defined(HAS_VTOHL) && !defined(vtohl)
1884 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1886 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1888 register I32 This, that;
1894 PERL_FLUSHALL_FOR_CHILD;
1895 This = (*mode == 'w');
1899 taint_proper("Insecure %s%s", "EXEC");
1901 if (PerlProc_pipe(p) < 0)
1903 /* Try for another pipe pair for error return */
1904 if (PerlProc_pipe(pp) >= 0)
1906 while ((pid = PerlProc_fork()) < 0) {
1907 if (errno != EAGAIN) {
1908 PerlLIO_close(p[This]);
1910 PerlLIO_close(pp[0]);
1911 PerlLIO_close(pp[1]);
1923 /* Close parent's end of _the_ pipe */
1924 PerlLIO_close(p[THAT]);
1925 /* Close parent's end of error status pipe (if any) */
1927 PerlLIO_close(pp[0]);
1928 #if defined(HAS_FCNTL) && defined(F_SETFD)
1929 /* Close error pipe automatically if exec works */
1930 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1933 /* Now dup our end of _the_ pipe to right position */
1934 if (p[THIS] != (*mode == 'r')) {
1935 PerlLIO_dup2(p[THIS], *mode == 'r');
1936 PerlLIO_close(p[THIS]);
1938 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1939 /* No automatic close - do it by hand */
1946 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1952 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
1958 do_execfree(); /* free any memory malloced by child on fork */
1959 /* Close child's end of pipe */
1960 PerlLIO_close(p[that]);
1962 PerlLIO_close(pp[1]);
1963 /* Keep the lower of the two fd numbers */
1964 if (p[that] < p[This]) {
1965 PerlLIO_dup2(p[This], p[that]);
1966 PerlLIO_close(p[This]);
1970 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1972 (void)SvUPGRADE(sv,SVt_IV);
1974 PL_forkprocess = pid;
1975 /* If we managed to get status pipe check for exec fail */
1976 if (did_pipes && pid > 0) {
1980 while (n < sizeof(int)) {
1981 n1 = PerlLIO_read(pp[0],
1982 (void*)(((char*)&errkid)+n),
1988 PerlLIO_close(pp[0]);
1990 if (n) { /* Error */
1992 PerlLIO_close(p[This]);
1993 if (n != sizeof(int))
1994 Perl_croak(aTHX_ "panic: kid popen errno read");
1996 pid2 = wait4pid(pid, &status, 0);
1997 } while (pid2 == -1 && errno == EINTR);
1998 errno = errkid; /* Propagate errno from kid */
2003 PerlLIO_close(pp[0]);
2004 return PerlIO_fdopen(p[This], mode);
2006 Perl_croak(aTHX_ "List form of piped open not implemented");
2007 return (PerlIO *) NULL;
2011 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2012 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2014 Perl_my_popen(pTHX_ char *cmd, char *mode)
2017 register I32 This, that;
2020 I32 doexec = strNE(cmd,"-");
2024 PERL_FLUSHALL_FOR_CHILD;
2027 return my_syspopen(aTHX_ cmd,mode);
2030 This = (*mode == 'w');
2032 if (doexec && PL_tainting) {
2034 taint_proper("Insecure %s%s", "EXEC");
2036 if (PerlProc_pipe(p) < 0)
2038 if (doexec && PerlProc_pipe(pp) >= 0)
2040 while ((pid = PerlProc_fork()) < 0) {
2041 if (errno != EAGAIN) {
2042 PerlLIO_close(p[This]);
2044 PerlLIO_close(pp[0]);
2045 PerlLIO_close(pp[1]);
2048 Perl_croak(aTHX_ "Can't fork");
2060 PerlLIO_close(p[THAT]);
2062 PerlLIO_close(pp[0]);
2063 #if defined(HAS_FCNTL) && defined(F_SETFD)
2064 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2067 if (p[THIS] != (*mode == 'r')) {
2068 PerlLIO_dup2(p[THIS], *mode == 'r');
2069 PerlLIO_close(p[THIS]);
2073 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2082 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2087 /* may or may not use the shell */
2088 do_exec3(cmd, pp[1], did_pipes);
2091 #endif /* defined OS2 */
2093 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2094 SvREADONLY_off(GvSV(tmpgv));
2095 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2096 SvREADONLY_on(GvSV(tmpgv));
2099 hv_clear(PL_pidstatus); /* we have no children */
2104 do_execfree(); /* free any memory malloced by child on fork */
2105 PerlLIO_close(p[that]);
2107 PerlLIO_close(pp[1]);
2108 if (p[that] < p[This]) {
2109 PerlLIO_dup2(p[This], p[that]);
2110 PerlLIO_close(p[This]);
2114 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2116 (void)SvUPGRADE(sv,SVt_IV);
2118 PL_forkprocess = pid;
2119 if (did_pipes && pid > 0) {
2123 while (n < sizeof(int)) {
2124 n1 = PerlLIO_read(pp[0],
2125 (void*)(((char*)&errkid)+n),
2131 PerlLIO_close(pp[0]);
2133 if (n) { /* Error */
2135 PerlLIO_close(p[This]);
2136 if (n != sizeof(int))
2137 Perl_croak(aTHX_ "panic: kid popen errno read");
2139 pid2 = wait4pid(pid, &status, 0);
2140 } while (pid2 == -1 && errno == EINTR);
2141 errno = errkid; /* Propagate errno from kid */
2146 PerlLIO_close(pp[0]);
2147 return PerlIO_fdopen(p[This], mode);
2150 #if defined(atarist)
2153 Perl_my_popen(pTHX_ char *cmd, char *mode)
2155 PERL_FLUSHALL_FOR_CHILD;
2156 /* Call system's popen() to get a FILE *, then import it.
2157 used 0 for 2nd parameter to PerlIO_importFILE;
2160 return PerlIO_importFILE(popen(cmd, mode), 0);
2164 FILE *djgpp_popen();
2166 Perl_my_popen(pTHX_ char *cmd, char *mode)
2168 PERL_FLUSHALL_FOR_CHILD;
2169 /* Call system's popen() to get a FILE *, then import it.
2170 used 0 for 2nd parameter to PerlIO_importFILE;
2173 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2178 #endif /* !DOSISH */
2180 /* this is called in parent before the fork() */
2182 Perl_atfork_lock(void)
2184 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2185 /* locks must be held in locking order (if any) */
2187 MUTEX_LOCK(&PL_malloc_mutex);
2193 /* this is called in both parent and child after the fork() */
2195 Perl_atfork_unlock(void)
2197 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2198 /* locks must be released in same order as in atfork_lock() */
2200 MUTEX_UNLOCK(&PL_malloc_mutex);
2209 #if defined(HAS_FORK)
2211 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2216 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2217 * handlers elsewhere in the code */
2222 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2223 Perl_croak_nocontext("fork() not available");
2225 #endif /* HAS_FORK */
2230 Perl_dump_fds(pTHX_ char *s)
2233 struct stat tmpstatbuf;
2235 PerlIO_printf(Perl_debug_log,"%s", s);
2236 for (fd = 0; fd < 32; fd++) {
2237 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2238 PerlIO_printf(Perl_debug_log," %d",fd);
2240 PerlIO_printf(Perl_debug_log,"\n");
2242 #endif /* DUMP_FDS */
2246 dup2(int oldfd, int newfd)
2248 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2251 PerlLIO_close(newfd);
2252 return fcntl(oldfd, F_DUPFD, newfd);
2254 #define DUP2_MAX_FDS 256
2255 int fdtmp[DUP2_MAX_FDS];
2261 PerlLIO_close(newfd);
2262 /* good enough for low fd's... */
2263 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2264 if (fdx >= DUP2_MAX_FDS) {
2272 PerlLIO_close(fdtmp[--fdx]);
2279 #ifdef HAS_SIGACTION
2282 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2284 struct sigaction act, oact;
2286 act.sa_handler = handler;
2287 sigemptyset(&act.sa_mask);
2290 #if defined(PERL_OLD_SIGNALS)
2291 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2295 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2296 act.sa_flags |= SA_NOCLDWAIT;
2298 if (sigaction(signo, &act, &oact) == -1)
2301 return oact.sa_handler;
2305 Perl_rsignal_state(pTHX_ int signo)
2307 struct sigaction oact;
2309 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2312 return oact.sa_handler;
2316 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2318 struct sigaction act;
2320 act.sa_handler = handler;
2321 sigemptyset(&act.sa_mask);
2324 #if defined(PERL_OLD_SIGNALS)
2325 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2329 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2330 act.sa_flags |= SA_NOCLDWAIT;
2332 return sigaction(signo, &act, save);
2336 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2338 return sigaction(signo, save, (struct sigaction *)NULL);
2341 #else /* !HAS_SIGACTION */
2344 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2346 return PerlProc_signal(signo, handler);
2349 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2350 ignore the implications of this for threading */
2360 Perl_rsignal_state(pTHX_ int signo)
2362 Sighandler_t oldsig;
2365 oldsig = PerlProc_signal(signo, sig_trap);
2366 PerlProc_signal(signo, oldsig);
2368 PerlProc_kill(PerlProc_getpid(), signo);
2373 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2375 *save = PerlProc_signal(signo, handler);
2376 return (*save == SIG_ERR) ? -1 : 0;
2380 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2382 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2385 #endif /* !HAS_SIGACTION */
2386 #endif /* !PERL_MICRO */
2388 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2389 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2391 Perl_my_pclose(pTHX_ PerlIO *ptr)
2393 Sigsave_t hstat, istat, qstat;
2399 int saved_errno = 0;
2401 int saved_vaxc_errno;
2404 int saved_win32_errno;
2408 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2410 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2412 *svp = &PL_sv_undef;
2414 if (pid == -1) { /* Opened by popen. */
2415 return my_syspclose(ptr);
2418 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2419 saved_errno = errno;
2421 saved_vaxc_errno = vaxc$errno;
2424 saved_win32_errno = GetLastError();
2428 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2431 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2432 rsignal_save(SIGINT, SIG_IGN, &istat);
2433 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2436 pid2 = wait4pid(pid, &status, 0);
2437 } while (pid2 == -1 && errno == EINTR);
2439 rsignal_restore(SIGHUP, &hstat);
2440 rsignal_restore(SIGINT, &istat);
2441 rsignal_restore(SIGQUIT, &qstat);
2444 SETERRNO(saved_errno, saved_vaxc_errno);
2447 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2449 #endif /* !DOSISH */
2451 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2453 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2458 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2462 char spid[TYPE_CHARS(int)];
2465 sprintf(spid, "%"IVdf, (IV)pid);
2466 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2467 if (svp && *svp != &PL_sv_undef) {
2468 *statusp = SvIVX(*svp);
2469 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2476 hv_iterinit(PL_pidstatus);
2477 if ((entry = hv_iternext(PL_pidstatus))) {
2478 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2479 sv = hv_iterval(PL_pidstatus,entry);
2480 *statusp = SvIVX(sv);
2481 sprintf(spid, "%"IVdf, (IV)pid);
2482 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2489 # ifdef HAS_WAITPID_RUNTIME
2490 if (!HAS_WAITPID_RUNTIME)
2493 result = PerlProc_waitpid(pid,statusp,flags);
2496 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2497 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2500 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2504 Perl_croak(aTHX_ "Can't do waitpid with flags");
2506 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2507 pidgone(result,*statusp);
2514 if (result < 0 && errno == EINTR) {
2519 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2523 Perl_pidgone(pTHX_ Pid_t pid, int status)
2526 char spid[TYPE_CHARS(int)];
2528 sprintf(spid, "%"IVdf, (IV)pid);
2529 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2530 (void)SvUPGRADE(sv,SVt_IV);
2535 #if defined(atarist) || defined(OS2)
2538 int /* Cannot prototype with I32
2540 my_syspclose(PerlIO *ptr)
2543 Perl_my_pclose(pTHX_ PerlIO *ptr)
2546 /* Needs work for PerlIO ! */
2547 FILE *f = PerlIO_findFILE(ptr);
2548 I32 result = pclose(f);
2549 PerlIO_releaseFILE(ptr,f);
2557 Perl_my_pclose(pTHX_ PerlIO *ptr)
2559 /* Needs work for PerlIO ! */
2560 FILE *f = PerlIO_findFILE(ptr);
2561 I32 result = djgpp_pclose(f);
2562 result = (result << 8) & 0xff00;
2563 PerlIO_releaseFILE(ptr,f);
2569 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2572 register const char *frombase = from;
2575 register const char c = *from;
2580 while (count-- > 0) {
2581 for (todo = len; todo > 0; todo--) {
2590 Perl_same_dirent(pTHX_ char *a, char *b)
2592 char *fa = strrchr(a,'/');
2593 char *fb = strrchr(b,'/');
2594 struct stat tmpstatbuf1;
2595 struct stat tmpstatbuf2;
2596 SV *tmpsv = sv_newmortal();
2609 sv_setpv(tmpsv, ".");
2611 sv_setpvn(tmpsv, a, fa - a);
2612 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2615 sv_setpv(tmpsv, ".");
2617 sv_setpvn(tmpsv, b, fb - b);
2618 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2620 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2621 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2623 #endif /* !HAS_RENAME */
2626 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2628 char *xfound = Nullch;
2629 char *xfailed = Nullch;
2630 char tmpbuf[MAXPATHLEN];
2634 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2635 # define SEARCH_EXTS ".bat", ".cmd", NULL
2636 # define MAX_EXT_LEN 4
2639 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2640 # define MAX_EXT_LEN 4
2643 # define SEARCH_EXTS ".pl", ".com", NULL
2644 # define MAX_EXT_LEN 4
2646 /* additional extensions to try in each dir if scriptname not found */
2648 char *exts[] = { SEARCH_EXTS };
2649 char **ext = search_ext ? search_ext : exts;
2650 int extidx = 0, i = 0;
2651 char *curext = Nullch;
2653 # define MAX_EXT_LEN 0
2657 * If dosearch is true and if scriptname does not contain path
2658 * delimiters, search the PATH for scriptname.
2660 * If SEARCH_EXTS is also defined, will look for each
2661 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2662 * while searching the PATH.
2664 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2665 * proceeds as follows:
2666 * If DOSISH or VMSISH:
2667 * + look for ./scriptname{,.foo,.bar}
2668 * + search the PATH for scriptname{,.foo,.bar}
2671 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2672 * this will not look in '.' if it's not in the PATH)
2677 # ifdef ALWAYS_DEFTYPES
2678 len = strlen(scriptname);
2679 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2680 int hasdir, idx = 0, deftypes = 1;
2683 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2686 int hasdir, idx = 0, deftypes = 1;
2689 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2691 /* The first time through, just add SEARCH_EXTS to whatever we
2692 * already have, so we can check for default file types. */
2694 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2700 if ((strlen(tmpbuf) + strlen(scriptname)
2701 + MAX_EXT_LEN) >= sizeof tmpbuf)
2702 continue; /* don't search dir with too-long name */
2703 strcat(tmpbuf, scriptname);
2707 if (strEQ(scriptname, "-"))
2709 if (dosearch) { /* Look in '.' first. */
2710 char *cur = scriptname;
2712 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2714 if (strEQ(ext[i++],curext)) {
2715 extidx = -1; /* already has an ext */
2720 DEBUG_p(PerlIO_printf(Perl_debug_log,
2721 "Looking for %s\n",cur));
2722 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2723 && !S_ISDIR(PL_statbuf.st_mode)) {
2731 if (cur == scriptname) {
2732 len = strlen(scriptname);
2733 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2735 cur = strcpy(tmpbuf, scriptname);
2737 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2738 && strcpy(tmpbuf+len, ext[extidx++]));
2743 #ifdef MACOS_TRADITIONAL
2744 if (dosearch && !strchr(scriptname, ':') &&
2745 (s = PerlEnv_getenv("Commands")))
2747 if (dosearch && !strchr(scriptname, '/')
2749 && !strchr(scriptname, '\\')
2751 && (s = PerlEnv_getenv("PATH")))
2756 PL_bufend = s + strlen(s);
2757 while (s < PL_bufend) {
2758 #ifdef MACOS_TRADITIONAL
2759 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2763 #if defined(atarist) || defined(DOSISH)
2768 && *s != ';'; len++, s++) {
2769 if (len < sizeof tmpbuf)
2772 if (len < sizeof tmpbuf)
2774 #else /* ! (atarist || DOSISH) */
2775 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2778 #endif /* ! (atarist || DOSISH) */
2779 #endif /* MACOS_TRADITIONAL */
2782 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2783 continue; /* don't search dir with too-long name */
2784 #ifdef MACOS_TRADITIONAL
2785 if (len && tmpbuf[len - 1] != ':')
2786 tmpbuf[len++] = ':';
2789 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2790 && tmpbuf[len - 1] != '/'
2791 && tmpbuf[len - 1] != '\\'
2794 tmpbuf[len++] = '/';
2795 if (len == 2 && tmpbuf[0] == '.')
2798 (void)strcpy(tmpbuf + len, scriptname);
2802 len = strlen(tmpbuf);
2803 if (extidx > 0) /* reset after previous loop */
2807 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2808 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2809 if (S_ISDIR(PL_statbuf.st_mode)) {
2813 } while ( retval < 0 /* not there */
2814 && extidx>=0 && ext[extidx] /* try an extension? */
2815 && strcpy(tmpbuf+len, ext[extidx++])
2820 if (S_ISREG(PL_statbuf.st_mode)
2821 && cando(S_IRUSR,TRUE,&PL_statbuf)
2822 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2823 && cando(S_IXUSR,TRUE,&PL_statbuf)
2827 xfound = tmpbuf; /* bingo! */
2831 xfailed = savepv(tmpbuf);
2834 if (!xfound && !seen_dot && !xfailed &&
2835 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2836 || S_ISDIR(PL_statbuf.st_mode)))
2838 seen_dot = 1; /* Disable message. */
2840 if (flags & 1) { /* do or die? */
2841 Perl_croak(aTHX_ "Can't %s %s%s%s",
2842 (xfailed ? "execute" : "find"),
2843 (xfailed ? xfailed : scriptname),
2844 (xfailed ? "" : " on PATH"),
2845 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2847 scriptname = Nullch;
2851 scriptname = xfound;
2853 return (scriptname ? savepv(scriptname) : Nullch);
2856 #ifndef PERL_GET_CONTEXT_DEFINED
2859 Perl_get_context(void)
2861 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2862 # ifdef OLD_PTHREADS_API
2864 if (pthread_getspecific(PL_thr_key, &t))
2865 Perl_croak_nocontext("panic: pthread_getspecific");
2868 # ifdef I_MACH_CTHREADS
2869 return (void*)cthread_data(cthread_self());
2871 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2880 Perl_set_context(void *t)
2882 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2883 # ifdef I_MACH_CTHREADS
2884 cthread_set_data(cthread_self(), t);
2886 if (pthread_setspecific(PL_thr_key, t))
2887 Perl_croak_nocontext("panic: pthread_setspecific");
2892 #endif /* !PERL_GET_CONTEXT_DEFINED */
2894 #ifdef USE_5005THREADS
2897 /* Very simplistic scheduler for now */
2901 thr = thr->i.next_run;
2905 Perl_cond_init(pTHX_ perl_cond *cp)
2911 Perl_cond_signal(pTHX_ perl_cond *cp)
2914 perl_cond cond = *cp;
2919 /* Insert t in the runnable queue just ahead of us */
2920 t->i.next_run = thr->i.next_run;
2921 thr->i.next_run->i.prev_run = t;
2922 t->i.prev_run = thr;
2923 thr->i.next_run = t;
2924 thr->i.wait_queue = 0;
2925 /* Remove from the wait queue */
2931 Perl_cond_broadcast(pTHX_ perl_cond *cp)
2934 perl_cond cond, cond_next;
2936 for (cond = *cp; cond; cond = cond_next) {
2938 /* Insert t in the runnable queue just ahead of us */
2939 t->i.next_run = thr->i.next_run;
2940 thr->i.next_run->i.prev_run = t;
2941 t->i.prev_run = thr;
2942 thr->i.next_run = t;
2943 thr->i.wait_queue = 0;
2944 /* Remove from the wait queue */
2945 cond_next = cond->next;
2952 Perl_cond_wait(pTHX_ perl_cond *cp)
2956 if (thr->i.next_run == thr)
2957 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
2959 New(666, cond, 1, struct perl_wait_queue);
2963 thr->i.wait_queue = cond;
2964 /* Remove ourselves from runnable queue */
2965 thr->i.next_run->i.prev_run = thr->i.prev_run;
2966 thr->i.prev_run->i.next_run = thr->i.next_run;
2968 #endif /* FAKE_THREADS */
2971 Perl_condpair_magic(pTHX_ SV *sv)
2975 (void)SvUPGRADE(sv, SVt_PVMG);
2976 mg = mg_find(sv, PERL_MAGIC_mutex);
2980 New(53, cp, 1, condpair_t);
2981 MUTEX_INIT(&cp->mutex);
2982 COND_INIT(&cp->owner_cond);
2983 COND_INIT(&cp->cond);
2985 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
2986 mg = mg_find(sv, PERL_MAGIC_mutex);
2988 /* someone else beat us to initialising it */
2989 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2990 MUTEX_DESTROY(&cp->mutex);
2991 COND_DESTROY(&cp->owner_cond);
2992 COND_DESTROY(&cp->cond);
2996 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
2998 mg->mg_ptr = (char *)cp;
2999 mg->mg_len = sizeof(cp);
3000 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3001 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3002 "%p: condpair_magic %p\n", thr, sv)));
3009 Perl_sv_lock(pTHX_ SV *osv)
3019 mg = condpair_magic(sv);
3020 MUTEX_LOCK(MgMUTEXP(mg));
3021 if (MgOWNER(mg) == thr)
3022 MUTEX_UNLOCK(MgMUTEXP(mg));
3025 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3027 DEBUG_S(PerlIO_printf(Perl_debug_log,
3028 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3029 PTR2UV(thr), PTR2UV(sv)));
3030 MUTEX_UNLOCK(MgMUTEXP(mg));
3031 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3033 UNLOCK_SV_LOCK_MUTEX;
3038 * Make a new perl thread structure using t as a prototype. Some of the
3039 * fields for the new thread are copied from the prototype thread, t,
3040 * so t should not be running in perl at the time this function is
3041 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3042 * thread calling new_struct_thread) clearly satisfies this constraint.
3044 struct perl_thread *
3045 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3047 #if !defined(PERL_IMPLICIT_CONTEXT)
3048 struct perl_thread *thr;
3054 sv = newSVpvn("", 0);
3055 SvGROW(sv, sizeof(struct perl_thread) + 1);
3056 SvCUR_set(sv, sizeof(struct perl_thread));
3057 thr = (Thread) SvPVX(sv);
3059 memset(thr, 0xab, sizeof(struct perl_thread));
3066 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3067 PL_efloatbuf = (char*)NULL;
3070 Zero(thr, 1, struct perl_thread);
3076 PL_curcop = &PL_compiling;
3077 thr->interp = t->interp;
3078 thr->cvcache = newHV();
3079 thr->threadsv = newAV();
3080 thr->specific = newAV();
3081 thr->errsv = newSVpvn("", 0);
3082 thr->flags = THRf_R_JOINABLE;
3084 MUTEX_INIT(&thr->mutex);
3088 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3091 PL_statname = NEWSV(66,0);
3092 PL_errors = newSVpvn("", 0);
3094 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3095 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3096 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3097 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3098 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3100 PL_reginterp_cnt = 0;
3101 PL_lastscream = Nullsv;
3104 PL_reg_start_tmp = 0;
3105 PL_reg_start_tmpl = 0;
3106 PL_reg_poscache = Nullch;
3108 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3110 /* parent thread's data needs to be locked while we make copy */
3111 MUTEX_LOCK(&t->mutex);
3113 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3114 PL_protect = t->Tprotect;
3117 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3118 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3119 PL_curstash = t->Tcurstash; /* always be set to main? */
3121 PL_tainted = t->Ttainted;
3122 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3123 PL_rs = newSVsv(t->Trs);
3124 PL_last_in_gv = Nullgv;
3125 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3126 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3127 PL_chopset = t->Tchopset;
3128 PL_bodytarget = newSVsv(t->Tbodytarget);
3129 PL_toptarget = newSVsv(t->Ttoptarget);
3130 if (t->Tformtarget == t->Ttoptarget)
3131 PL_formtarget = PL_toptarget;
3133 PL_formtarget = PL_bodytarget;
3135 /* Initialise all per-thread SVs that the template thread used */
3136 svp = AvARRAY(t->threadsv);
3137 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3138 if (*svp && *svp != &PL_sv_undef) {
3139 SV *sv = newSVsv(*svp);
3140 av_store(thr->threadsv, i, sv);
3141 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3142 DEBUG_S(PerlIO_printf(Perl_debug_log,
3143 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3147 thr->threadsvp = AvARRAY(thr->threadsv);
3149 MUTEX_LOCK(&PL_threads_mutex);
3151 thr->tid = ++PL_threadnum;
3152 thr->next = t->next;
3155 thr->next->prev = thr;
3156 MUTEX_UNLOCK(&PL_threads_mutex);
3158 /* done copying parent's state */
3159 MUTEX_UNLOCK(&t->mutex);
3161 #ifdef HAVE_THREAD_INTERN
3162 Perl_init_thread_intern(thr);
3163 #endif /* HAVE_THREAD_INTERN */
3166 #endif /* USE_5005THREADS */
3168 #ifdef PERL_GLOBAL_STRUCT
3177 Perl_get_op_names(pTHX)
3183 Perl_get_op_descs(pTHX)
3189 Perl_get_no_modify(pTHX)
3191 return (char*)PL_no_modify;
3195 Perl_get_opargs(pTHX)
3201 Perl_get_ppaddr(pTHX)
3203 return (PPADDR_t*)PL_ppaddr;
3206 #ifndef HAS_GETENV_LEN
3208 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3210 char *env_trans = PerlEnv_getenv(env_elem);
3212 *len = strlen(env_trans);
3219 Perl_get_vtbl(pTHX_ int vtbl_id)
3221 MGVTBL* result = Null(MGVTBL*);
3225 result = &PL_vtbl_sv;
3228 result = &PL_vtbl_env;
3230 case want_vtbl_envelem:
3231 result = &PL_vtbl_envelem;
3234 result = &PL_vtbl_sig;
3236 case want_vtbl_sigelem:
3237 result = &PL_vtbl_sigelem;
3239 case want_vtbl_pack:
3240 result = &PL_vtbl_pack;
3242 case want_vtbl_packelem:
3243 result = &PL_vtbl_packelem;
3245 case want_vtbl_dbline:
3246 result = &PL_vtbl_dbline;
3249 result = &PL_vtbl_isa;
3251 case want_vtbl_isaelem:
3252 result = &PL_vtbl_isaelem;
3254 case want_vtbl_arylen:
3255 result = &PL_vtbl_arylen;
3257 case want_vtbl_glob:
3258 result = &PL_vtbl_glob;
3260 case want_vtbl_mglob:
3261 result = &PL_vtbl_mglob;
3263 case want_vtbl_nkeys:
3264 result = &PL_vtbl_nkeys;
3266 case want_vtbl_taint:
3267 result = &PL_vtbl_taint;
3269 case want_vtbl_substr:
3270 result = &PL_vtbl_substr;
3273 result = &PL_vtbl_vec;
3276 result = &PL_vtbl_pos;
3279 result = &PL_vtbl_bm;
3282 result = &PL_vtbl_fm;
3284 case want_vtbl_uvar:
3285 result = &PL_vtbl_uvar;
3287 #ifdef USE_5005THREADS
3288 case want_vtbl_mutex:
3289 result = &PL_vtbl_mutex;
3292 case want_vtbl_defelem:
3293 result = &PL_vtbl_defelem;
3295 case want_vtbl_regexp:
3296 result = &PL_vtbl_regexp;
3298 case want_vtbl_regdata:
3299 result = &PL_vtbl_regdata;
3301 case want_vtbl_regdatum:
3302 result = &PL_vtbl_regdatum;
3304 #ifdef USE_LOCALE_COLLATE
3305 case want_vtbl_collxfrm:
3306 result = &PL_vtbl_collxfrm;
3309 case want_vtbl_amagic:
3310 result = &PL_vtbl_amagic;
3312 case want_vtbl_amagicelem:
3313 result = &PL_vtbl_amagicelem;
3315 case want_vtbl_backref:
3316 result = &PL_vtbl_backref;
3323 Perl_my_fflush_all(pTHX)
3325 #if defined(FFLUSH_NULL)
3326 return PerlIO_flush(NULL);
3328 # if defined(HAS__FWALK)
3329 /* undocumented, unprototyped, but very useful BSDism */
3330 extern void _fwalk(int (*)(FILE *));
3334 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3336 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3337 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3339 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3340 open_max = sysconf(_SC_OPEN_MAX);
3343 open_max = FOPEN_MAX;
3346 open_max = OPEN_MAX;
3357 for (i = 0; i < open_max; i++)
3358 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3359 STDIO_STREAM_ARRAY[i]._file < open_max &&
3360 STDIO_STREAM_ARRAY[i]._flag)
3361 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3365 SETERRNO(EBADF,RMS$_IFI);
3372 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3377 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3378 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3380 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3381 char *type = OP_IS_SOCKET(op) ||
3382 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3383 "socket" : "filehandle";
3386 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3388 warn_type = WARN_CLOSED;
3392 warn_type = WARN_UNOPENED;
3395 if (gv && isGV(gv)) {
3396 SV *sv = sv_newmortal();
3397 gv_efullname4(sv, gv, Nullch, FALSE);
3401 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3403 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
3405 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3407 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
3408 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3409 } else if (name && *name) {
3410 Perl_warner(aTHX_ warn_type,
3411 "%s%s on %s %s %s", func, pars, vile, type, name);
3412 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3413 Perl_warner(aTHX_ warn_type,
3414 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3418 Perl_warner(aTHX_ warn_type,
3419 "%s%s on %s %s", func, pars, vile, type);
3420 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3421 Perl_warner(aTHX_ warn_type,
3422 "\t(Are you trying to call %s%s on dirhandle?)\n",
3428 /* in ASCII order, not that it matters */
3429 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3432 Perl_ebcdic_control(pTHX_ int ch)
3440 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3441 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3444 if (ctlp == controllablechars)
3445 return('\177'); /* DEL */
3447 return((unsigned char)(ctlp - controllablechars - 1));
3448 } else { /* Want uncontrol */
3449 if (ch == '\177' || ch == -1)
3451 else if (ch == '\157')
3453 else if (ch == '\174')
3455 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3457 else if (ch == '\155')
3459 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3460 return(controllablechars[ch+1]);
3462 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3467 /* XXX struct tm on some systems (SunOS4/BSD) contains extra (non POSIX)
3468 * fields for which we don't have Configure support yet:
3469 * char *tm_zone; -- abbreviation of timezone name
3470 * long tm_gmtoff; -- offset from GMT in seconds
3471 * To workaround core dumps from the uninitialised tm_zone we get the
3472 * system to give us a reasonable struct to copy. This fix means that
3473 * strftime uses the tm_zone and tm_gmtoff values returned by
3474 * localtime(time()). That should give the desired result most of the
3475 * time. But probably not always!
3477 * This is a temporary workaround to be removed once Configure
3478 * support is added and NETaa14816 is considered in full.
3479 * It does not address tzname aspects of NETaa14816.
3482 # ifndef STRUCT_TM_HASZONE
3483 # define STRUCT_TM_HASZONE
3488 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3490 #ifdef STRUCT_TM_HASZONE
3493 Copy(localtime(&now), ptm, 1, struct tm);
3498 * mini_mktime - normalise struct tm values without the localtime()
3499 * semantics (and overhead) of mktime().
3502 Perl_mini_mktime(pTHX_ struct tm *ptm)
3506 int month, mday, year, jday;
3507 int odd_cent, odd_year;
3509 #define DAYS_PER_YEAR 365
3510 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3511 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3512 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3513 #define SECS_PER_HOUR (60*60)
3514 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3515 /* parentheses deliberately absent on these two, otherwise they don't work */
3516 #define MONTH_TO_DAYS 153/5
3517 #define DAYS_TO_MONTH 5/153
3518 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3519 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3520 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3521 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3524 * Year/day algorithm notes:
3526 * With a suitable offset for numeric value of the month, one can find
3527 * an offset into the year by considering months to have 30.6 (153/5) days,
3528 * using integer arithmetic (i.e., with truncation). To avoid too much
3529 * messing about with leap days, we consider January and February to be
3530 * the 13th and 14th month of the previous year. After that transformation,
3531 * we need the month index we use to be high by 1 from 'normal human' usage,
3532 * so the month index values we use run from 4 through 15.
3534 * Given that, and the rules for the Gregorian calendar (leap years are those
3535 * divisible by 4 unless also divisible by 100, when they must be divisible
3536 * by 400 instead), we can simply calculate the number of days since some
3537 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3538 * the days we derive from our month index, and adding in the day of the
3539 * month. The value used here is not adjusted for the actual origin which
3540 * it normally would use (1 January A.D. 1), since we're not exposing it.
3541 * We're only building the value so we can turn around and get the
3542 * normalised values for the year, month, day-of-month, and day-of-year.
3544 * For going backward, we need to bias the value we're using so that we find
3545 * the right year value. (Basically, we don't want the contribution of
3546 * March 1st to the number to apply while deriving the year). Having done
3547 * that, we 'count up' the contribution to the year number by accounting for
3548 * full quadracenturies (400-year periods) with their extra leap days, plus
3549 * the contribution from full centuries (to avoid counting in the lost leap
3550 * days), plus the contribution from full quad-years (to count in the normal
3551 * leap days), plus the leftover contribution from any non-leap years.
3552 * At this point, if we were working with an actual leap day, we'll have 0
3553 * days left over. This is also true for March 1st, however. So, we have
3554 * to special-case that result, and (earlier) keep track of the 'odd'
3555 * century and year contributions. If we got 4 extra centuries in a qcent,
3556 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3557 * Otherwise, we add back in the earlier bias we removed (the 123 from
3558 * figuring in March 1st), find the month index (integer division by 30.6),
3559 * and the remainder is the day-of-month. We then have to convert back to
3560 * 'real' months (including fixing January and February from being 14/15 in
3561 * the previous year to being in the proper year). After that, to get
3562 * tm_yday, we work with the normalised year and get a new yearday value for
3563 * January 1st, which we subtract from the yearday value we had earlier,
3564 * representing the date we've re-built. This is done from January 1
3565 * because tm_yday is 0-origin.
3567 * Since POSIX time routines are only guaranteed to work for times since the
3568 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3569 * applies Gregorian calendar rules even to dates before the 16th century
3570 * doesn't bother me. Besides, you'd need cultural context for a given
3571 * date to know whether it was Julian or Gregorian calendar, and that's
3572 * outside the scope for this routine. Since we convert back based on the
3573 * same rules we used to build the yearday, you'll only get strange results
3574 * for input which needed normalising, or for the 'odd' century years which
3575 * were leap years in the Julian calander but not in the Gregorian one.
3576 * I can live with that.
3578 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3579 * that's still outside the scope for POSIX time manipulation, so I don't
3583 year = 1900 + ptm->tm_year;
3584 month = ptm->tm_mon;
3585 mday = ptm->tm_mday;
3586 /* allow given yday with no month & mday to dominate the result */
3587 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3590 jday = 1 + ptm->tm_yday;
3599 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3600 yearday += month*MONTH_TO_DAYS + mday + jday;
3602 * Note that we don't know when leap-seconds were or will be,
3603 * so we have to trust the user if we get something which looks
3604 * like a sensible leap-second. Wild values for seconds will
3605 * be rationalised, however.
3607 if ((unsigned) ptm->tm_sec <= 60) {
3614 secs += 60 * ptm->tm_min;
3615 secs += SECS_PER_HOUR * ptm->tm_hour;
3617 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3618 /* got negative remainder, but need positive time */
3619 /* back off an extra day to compensate */
3620 yearday += (secs/SECS_PER_DAY)-1;
3621 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3624 yearday += (secs/SECS_PER_DAY);
3625 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3628 else if (secs >= SECS_PER_DAY) {
3629 yearday += (secs/SECS_PER_DAY);
3630 secs %= SECS_PER_DAY;
3632 ptm->tm_hour = secs/SECS_PER_HOUR;
3633 secs %= SECS_PER_HOUR;
3634 ptm->tm_min = secs/60;
3636 ptm->tm_sec += secs;
3637 /* done with time of day effects */
3639 * The algorithm for yearday has (so far) left it high by 428.
3640 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3641 * bias it by 123 while trying to figure out what year it
3642 * really represents. Even with this tweak, the reverse
3643 * translation fails for years before A.D. 0001.
3644 * It would still fail for Feb 29, but we catch that one below.
3646 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3647 yearday -= YEAR_ADJUST;
3648 year = (yearday / DAYS_PER_QCENT) * 400;
3649 yearday %= DAYS_PER_QCENT;
3650 odd_cent = yearday / DAYS_PER_CENT;
3651 year += odd_cent * 100;
3652 yearday %= DAYS_PER_CENT;
3653 year += (yearday / DAYS_PER_QYEAR) * 4;
3654 yearday %= DAYS_PER_QYEAR;
3655 odd_year = yearday / DAYS_PER_YEAR;
3657 yearday %= DAYS_PER_YEAR;
3658 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3663 yearday += YEAR_ADJUST; /* recover March 1st crock */
3664 month = yearday*DAYS_TO_MONTH;
3665 yearday -= month*MONTH_TO_DAYS;
3666 /* recover other leap-year adjustment */
3675 ptm->tm_year = year - 1900;
3677 ptm->tm_mday = yearday;
3678 ptm->tm_mon = month;
3682 ptm->tm_mon = month - 1;
3684 /* re-build yearday based on Jan 1 to get tm_yday */
3686 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3687 yearday += 14*MONTH_TO_DAYS + 1;
3688 ptm->tm_yday = jday - yearday;
3689 /* fix tm_wday if not overridden by caller */
3690 if ((unsigned)ptm->tm_wday > 6)
3691 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3695 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3703 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3706 mytm.tm_hour = hour;
3707 mytm.tm_mday = mday;
3709 mytm.tm_year = year;
3710 mytm.tm_wday = wday;
3711 mytm.tm_yday = yday;
3712 mytm.tm_isdst = isdst;
3715 New(0, buf, buflen, char);
3716 len = strftime(buf, buflen, fmt, &mytm);
3718 ** The following is needed to handle to the situation where
3719 ** tmpbuf overflows. Basically we want to allocate a buffer
3720 ** and try repeatedly. The reason why it is so complicated
3721 ** is that getting a return value of 0 from strftime can indicate
3722 ** one of the following:
3723 ** 1. buffer overflowed,
3724 ** 2. illegal conversion specifier, or
3725 ** 3. the format string specifies nothing to be returned(not
3726 ** an error). This could be because format is an empty string
3727 ** or it specifies %p that yields an empty string in some locale.
3728 ** If there is a better way to make it portable, go ahead by
3731 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3734 /* Possibly buf overflowed - try again with a bigger buf */
3735 int fmtlen = strlen(fmt);
3736 int bufsize = fmtlen + buflen;
3738 New(0, buf, bufsize, char);
3740 buflen = strftime(buf, bufsize, fmt, &mytm);
3741 if (buflen > 0 && buflen < bufsize)
3743 /* heuristic to prevent out-of-memory errors */
3744 if (bufsize > 100*fmtlen) {
3750 Renew(buf, bufsize, char);
3755 Perl_croak(aTHX_ "panic: no strftime");
3760 #define SV_CWD_RETURN_UNDEF \
3761 sv_setsv(sv, &PL_sv_undef); \
3764 #define SV_CWD_ISDOT(dp) \
3765 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3766 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3769 =head1 Miscellaneous Functions
3771 =for apidoc getcwd_sv
3773 Fill the sv with current working directory
3778 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3779 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3780 * getcwd(3) if available
3781 * Comments from the orignal:
3782 * This is a faster version of getcwd. It's also more dangerous
3783 * because you might chdir out of a directory that you can't chdir
3787 Perl_getcwd_sv(pTHX_ register SV *sv)
3791 #ifndef INCOMPLETE_TAINTS
3797 char buf[MAXPATHLEN];
3799 /* Some getcwd()s automatically allocate a buffer of the given
3800 * size from the heap if they are given a NULL buffer pointer.
3801 * The problem is that this behaviour is not portable. */
3802 if (getcwd(buf, sizeof(buf) - 1)) {
3803 STRLEN len = strlen(buf);
3804 sv_setpvn(sv, buf, len);
3808 sv_setsv(sv, &PL_sv_undef);
3815 struct stat statbuf;
3816 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3817 int namelen, pathlen=0;
3821 (void)SvUPGRADE(sv, SVt_PV);
3823 if (PerlLIO_lstat(".", &statbuf) < 0) {
3824 SV_CWD_RETURN_UNDEF;
3827 orig_cdev = statbuf.st_dev;
3828 orig_cino = statbuf.st_ino;
3836 if (PerlDir_chdir("..") < 0) {
3837 SV_CWD_RETURN_UNDEF;
3839 if (PerlLIO_stat(".", &statbuf) < 0) {
3840 SV_CWD_RETURN_UNDEF;
3843 cdev = statbuf.st_dev;
3844 cino = statbuf.st_ino;
3846 if (odev == cdev && oino == cino) {
3849 if (!(dir = PerlDir_open("."))) {
3850 SV_CWD_RETURN_UNDEF;
3853 while ((dp = PerlDir_read(dir)) != NULL) {
3855 namelen = dp->d_namlen;
3857 namelen = strlen(dp->d_name);
3860 if (SV_CWD_ISDOT(dp)) {
3864 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3865 SV_CWD_RETURN_UNDEF;
3868 tdev = statbuf.st_dev;
3869 tino = statbuf.st_ino;
3870 if (tino == oino && tdev == odev) {
3876 SV_CWD_RETURN_UNDEF;
3879 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3880 SV_CWD_RETURN_UNDEF;
3883 SvGROW(sv, pathlen + namelen + 1);
3887 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3890 /* prepend current directory to the front */
3892 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3893 pathlen += (namelen + 1);
3895 #ifdef VOID_CLOSEDIR
3898 if (PerlDir_close(dir) < 0) {
3899 SV_CWD_RETURN_UNDEF;
3905 SvCUR_set(sv, pathlen);
3909 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3910 SV_CWD_RETURN_UNDEF;
3913 if (PerlLIO_stat(".", &statbuf) < 0) {
3914 SV_CWD_RETURN_UNDEF;
3917 cdev = statbuf.st_dev;
3918 cino = statbuf.st_ino;
3920 if (cdev != orig_cdev || cino != orig_cino) {
3921 Perl_croak(aTHX_ "Unstable directory path, "
3922 "current directory changed unexpectedly");
3933 =head1 SV Manipulation Functions
3935 =for apidoc new_vstring
3937 Returns a pointer to the next character after the parsed
3938 vstring, as well as updating the passed in sv.
3940 Function must be called like
3943 s = new_vstring(s,sv);
3945 The sv must already be large enough to store the vstring
3952 Perl_new_vstring(pTHX_ char *s, SV *sv)
3955 if (*pos == 'v') pos++; /* get past 'v' */
3956 while (isDIGIT(*pos) || *pos == '_')
3958 if (!isALPHA(*pos)) {
3960 U8 tmpbuf[UTF8_MAXLEN+1];
3963 if (*s == 'v') s++; /* get past 'v' */
3965 sv_setpvn(sv, "", 0);
3970 /* this is atoi() that tolerates underscores */
3973 if ( *(s-1) == '_') {
3976 while (--end >= s) {
3979 rev += (*end - '0') * mult;
3981 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
3982 Perl_warner(aTHX_ WARN_OVERFLOW,
3983 "Integer overflow in decimal number");
3986 /* Append native character for the rev point */
3987 tmpend = uvchr_to_utf8(tmpbuf, rev);
3988 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
3989 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
3991 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
3997 while (isDIGIT(*pos) )
4006 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET)
4008 S_socketpair_udp (int fd[2]) {
4010 /* Fake a datagram socketpair using UDP to localhost. */
4011 int sockets[2] = {-1, -1};
4012 struct sockaddr_in addresses[2];
4014 Sock_size_t size = sizeof (struct sockaddr_in);
4015 unsigned short port;
4018 memset (&addresses, 0, sizeof (addresses));
4021 sockets[i] = PerlSock_socket (AF_INET, SOCK_DGRAM, PF_INET);
4022 if (sockets[i] == -1)
4023 goto tidy_up_and_fail;
4025 addresses[i].sin_family = AF_INET;
4026 addresses[i].sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4027 addresses[i].sin_port = 0; /* kernel choses port. */
4028 if (PerlSock_bind (sockets[i], (struct sockaddr *) &addresses[i],
4029 sizeof (struct sockaddr_in))
4031 goto tidy_up_and_fail;
4034 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4035 for each connect the other socket to it. */
4038 if (PerlSock_getsockname (sockets[i], (struct sockaddr *) &addresses[i], &size)
4040 goto tidy_up_and_fail;
4041 if (size != sizeof (struct sockaddr_in))
4042 goto abort_tidy_up_and_fail;
4043 /* !1 is 0, !0 is 1 */
4044 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4045 sizeof (struct sockaddr_in)) == -1)
4046 goto tidy_up_and_fail;
4049 /* Now we have 2 sockets connected to each other. I don't trust some other
4050 process not to have already sent a packet to us (by random) so send
4051 a packet from each to the other. */
4054 /* I'm going to send my own port number. As a short.
4055 (Who knows if someone somewhere has sin_port as a bitfield and needs
4056 this routine. (I'm assuming crays have socketpair)) */
4057 port = addresses[i].sin_port;
4058 got = PerlLIO_write (sockets[i], &port, sizeof(port));
4059 if (got != sizeof(port)) {
4061 goto tidy_up_and_fail;
4062 goto abort_tidy_up_and_fail;
4066 /* Packets sent. I don't trust them to have arrived though.
4067 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4068 connect to localhost will use a second kernel thread. In 2.6 the
4069 first thread running the connect() returns before the second completes,
4070 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4071 returns 0. Poor programs have tripped up. One poor program's authors'
4072 had a 50-1 reverse stock split. Not sure how connected these were.)
4073 So I don't trust someone not to have an unpredictable UDP stack.
4077 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4078 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4082 FD_SET (sockets[0], &rset);
4083 FD_SET (sockets[1], &rset);
4085 got = PerlSock_select (max + 1, &rset, NULL, NULL, &waitfor);
4086 if (got != 2 || !FD_ISSET (sockets[0], &rset)
4087 || !FD_ISSET (sockets[1], &rset)) {
4088 /* I hope this is portable and appropriate. */
4090 goto tidy_up_and_fail;
4091 goto abort_tidy_up_and_fail;
4095 /* And the paranoia department even now doesn't trust it to have arrive
4096 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4098 struct sockaddr_in readfrom;
4099 unsigned short buffer[2];
4104 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4106 (struct sockaddr *) &readfrom, &size);
4108 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4110 (struct sockaddr *) &readfrom, &size);
4114 goto tidy_up_and_fail;
4115 if (got != sizeof(port)
4116 || size != sizeof (struct sockaddr_in)
4117 /* Check other socket sent us its port. */
4118 || buffer[0] != (unsigned short) addresses[!i].sin_port
4119 /* Check kernel says we got the datagram from that socket. */
4120 || readfrom.sin_family != addresses[!i].sin_family
4121 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4122 || readfrom.sin_port != addresses[!i].sin_port)
4123 goto abort_tidy_up_and_fail;
4126 /* My caller (my_socketpair) has validated that this is non-NULL */
4129 /* I hereby declare this connection open. May God bless all who cross
4133 abort_tidy_up_and_fail:
4134 errno = ECONNABORTED;
4137 int save_errno = errno;
4138 if (sockets[0] != -1)
4139 PerlLIO_close (sockets[0]);
4140 if (sockets[1] != -1)
4141 PerlLIO_close (sockets[1]);
4148 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4149 /* Stevens says that family must be AF_LOCAL, protocol 0.
4150 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4155 struct sockaddr_in listen_addr;
4156 struct sockaddr_in connect_addr;
4161 || family != AF_UNIX
4164 errno = EAFNOSUPPORT;
4172 if (type == SOCK_DGRAM)
4173 return S_socketpair_udp (fd);
4175 listener = PerlSock_socket (AF_INET, type, 0);
4178 memset (&listen_addr, 0, sizeof (listen_addr));
4179 listen_addr.sin_family = AF_INET;
4180 listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4181 listen_addr.sin_port = 0; /* kernel choses port. */
4182 if (PerlSock_bind (listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
4184 goto tidy_up_and_fail;
4185 if (PerlSock_listen(listener, 1) == -1)
4186 goto tidy_up_and_fail;
4188 connector = PerlSock_socket (AF_INET, type, 0);
4189 if (connector == -1)
4190 goto tidy_up_and_fail;
4191 /* We want to find out the port number to connect to. */
4192 size = sizeof (connect_addr);
4193 if (PerlSock_getsockname (listener, (struct sockaddr *) &connect_addr, &size) == -1)
4194 goto tidy_up_and_fail;
4195 if (size != sizeof (connect_addr))
4196 goto abort_tidy_up_and_fail;
4197 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4198 sizeof (connect_addr)) == -1)
4199 goto tidy_up_and_fail;
4201 size = sizeof (listen_addr);
4202 acceptor = PerlSock_accept (listener, (struct sockaddr *) &listen_addr, &size);
4204 goto tidy_up_and_fail;
4205 if (size != sizeof (listen_addr))
4206 goto abort_tidy_up_and_fail;
4207 PerlLIO_close (listener);
4208 /* Now check we are talking to ourself by matching port and host on the
4210 if (PerlSock_getsockname (connector, (struct sockaddr *) &connect_addr, &size) == -1)
4211 goto tidy_up_and_fail;
4212 if (size != sizeof (connect_addr)
4213 || listen_addr.sin_family != connect_addr.sin_family
4214 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4215 || listen_addr.sin_port != connect_addr.sin_port) {
4216 goto abort_tidy_up_and_fail;
4222 abort_tidy_up_and_fail:
4223 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4226 int save_errno = errno;
4228 PerlLIO_close (listener);
4229 if (connector != -1)
4230 PerlLIO_close (connector);
4232 PerlLIO_close (acceptor);
4237 #endif /* !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) */
4238 #ifdef HAS_SOCKETPAIR
4239 /* In any case have a stub so that there's code corresponding
4240 * to the my_socketpair in global.sym. */
4242 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4243 return socketpair(family, type, protocol, fd);