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 =for apidoc fbm_compile
493 Analyses the string in order to make fast searches on it using fbm_instr()
494 -- the Boyer-Moore algorithm.
500 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
509 if (flags & FBMcf_TAIL)
510 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
511 s = (U8*)SvPV_force(sv, len);
512 (void)SvUPGRADE(sv, SVt_PVBM);
513 if (len == 0) /* TAIL might be on a zero-length string. */
523 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
524 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
525 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
526 memset((void*)table, mlen, 256);
527 table[-1] = (U8)flags;
529 sb = s - mlen + 1; /* first char (maybe) */
531 if (table[*s] == mlen)
536 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
539 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
540 for (i = 0; i < len; i++) {
541 if (PL_freq[s[i]] < frequency) {
543 frequency = PL_freq[s[i]];
546 BmRARE(sv) = s[rarest];
547 BmPREVIOUS(sv) = rarest;
548 BmUSEFUL(sv) = 100; /* Initial value */
549 if (flags & FBMcf_TAIL)
551 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
552 BmRARE(sv),BmPREVIOUS(sv)));
555 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
556 /* If SvTAIL is actually due to \Z or \z, this gives false positives
560 =for apidoc fbm_instr
562 Returns the location of the SV in the string delimited by C<str> and
563 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
564 does not have to be fbm_compiled, but the search will not be as fast
571 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
573 register unsigned char *s;
575 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
576 register STRLEN littlelen = l;
577 register I32 multiline = flags & FBMrf_MULTILINE;
579 if (bigend - big < littlelen) {
580 if ( SvTAIL(littlestr)
581 && (bigend - big == littlelen - 1)
583 || (*big == *little &&
584 memEQ((char *)big, (char *)little, littlelen - 1))))
589 if (littlelen <= 2) { /* Special-cased */
591 if (littlelen == 1) {
592 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
593 /* Know that bigend != big. */
594 if (bigend[-1] == '\n')
595 return (char *)(bigend - 1);
596 return (char *) bigend;
604 if (SvTAIL(littlestr))
605 return (char *) bigend;
609 return (char*)big; /* Cannot be SvTAIL! */
612 if (SvTAIL(littlestr) && !multiline) {
613 if (bigend[-1] == '\n' && bigend[-2] == *little)
614 return (char*)bigend - 2;
615 if (bigend[-1] == *little)
616 return (char*)bigend - 1;
620 /* This should be better than FBM if c1 == c2, and almost
621 as good otherwise: maybe better since we do less indirection.
622 And we save a lot of memory by caching no table. */
623 register unsigned char c1 = little[0];
624 register unsigned char c2 = little[1];
629 while (s <= bigend) {
639 goto check_1char_anchor;
650 goto check_1char_anchor;
653 while (s <= bigend) {
658 goto check_1char_anchor;
667 check_1char_anchor: /* One char and anchor! */
668 if (SvTAIL(littlestr) && (*bigend == *little))
669 return (char *)bigend; /* bigend is already decremented. */
672 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
673 s = bigend - littlelen;
674 if (s >= big && bigend[-1] == '\n' && *s == *little
675 /* Automatically of length > 2 */
676 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
678 return (char*)s; /* how sweet it is */
681 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
683 return (char*)s + 1; /* how sweet it is */
687 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
688 char *b = ninstr((char*)big,(char*)bigend,
689 (char*)little, (char*)little + littlelen);
691 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
692 /* Chop \n from littlestr: */
693 s = bigend - littlelen + 1;
695 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
704 { /* Do actual FBM. */
705 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
706 register unsigned char *oldlittle;
708 if (littlelen > bigend - big)
710 --littlelen; /* Last char found by table lookup */
713 little += littlelen; /* last char */
720 if ((tmp = table[*s])) {
721 if ((s += tmp) < bigend)
725 else { /* less expensive than calling strncmp() */
726 register unsigned char *olds = s;
731 if (*--s == *--little)
733 s = olds + 1; /* here we pay the price for failure */
735 if (s < bigend) /* fake up continue to outer loop */
743 if ( s == bigend && (table[-1] & FBMcf_TAIL)
744 && memEQ((char *)(bigend - littlelen),
745 (char *)(oldlittle - littlelen), littlelen) )
746 return (char*)bigend - littlelen;
751 /* start_shift, end_shift are positive quantities which give offsets
752 of ends of some substring of bigstr.
753 If `last' we want the last occurence.
754 old_posp is the way of communication between consequent calls if
755 the next call needs to find the .
756 The initial *old_posp should be -1.
758 Note that we take into account SvTAIL, so one can get extra
759 optimizations if _ALL flag is set.
762 /* If SvTAIL is actually due to \Z or \z, this gives false positives
763 if PL_multiline. In fact if !PL_multiline the authoritative answer
764 is not supported yet. */
767 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
769 register unsigned char *s, *x;
770 register unsigned char *big;
772 register I32 previous;
774 register unsigned char *little;
775 register I32 stop_pos;
776 register unsigned char *littleend;
780 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
781 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
783 if ( BmRARE(littlestr) == '\n'
784 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
785 little = (unsigned char *)(SvPVX(littlestr));
786 littleend = little + SvCUR(littlestr);
793 little = (unsigned char *)(SvPVX(littlestr));
794 littleend = little + SvCUR(littlestr);
796 /* The value of pos we can start at: */
797 previous = BmPREVIOUS(littlestr);
798 big = (unsigned char *)(SvPVX(bigstr));
799 /* The value of pos we can stop at: */
800 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
801 if (previous + start_shift > stop_pos) {
803 stop_pos does not include SvTAIL in the count, so this check is incorrect
804 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
807 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
812 while (pos < previous + start_shift) {
813 if (!(pos += PL_screamnext[pos]))
818 if (pos >= stop_pos) break;
819 if (big[pos] != first)
821 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
827 if (s == littleend) {
829 if (!last) return (char *)(big+pos);
832 } while ( pos += PL_screamnext[pos] );
834 return (char *)(big+(*old_posp));
836 if (!SvTAIL(littlestr) || (end_shift > 0))
838 /* Ignore the trailing "\n". This code is not microoptimized */
839 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
840 stop_pos = littleend - little; /* Actual littlestr len */
845 && ((stop_pos == 1) ||
846 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
852 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
854 register U8 *a = (U8 *)s1;
855 register U8 *b = (U8 *)s2;
857 if (*a != *b && *a != PL_fold[*b])
865 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
867 register U8 *a = (U8 *)s1;
868 register U8 *b = (U8 *)s2;
870 if (*a != *b && *a != PL_fold_locale[*b])
877 /* copy a string to a safe spot */
882 Copy a string to a safe spot. This does not use an SV.
888 Perl_savepv(pTHX_ const char *sv)
890 register char *newaddr;
892 New(902,newaddr,strlen(sv)+1,char);
893 (void)strcpy(newaddr,sv);
897 /* same thing but with a known length */
902 Copy a string to a safe spot. The C<len> indicates number of bytes to
903 copy. This does not use an SV.
909 Perl_savepvn(pTHX_ const char *sv, register I32 len)
911 register char *newaddr;
913 New(903,newaddr,len+1,char);
914 Copy(sv,newaddr,len,char); /* might not be null terminated */
915 newaddr[len] = '\0'; /* is now */
919 /* the SV for Perl_form() and mess() is not kept in an arena */
928 return sv_2mortal(newSVpvn("",0));
933 /* Create as PVMG now, to avoid any upgrading later */
935 Newz(905, any, 1, XPVMG);
936 SvFLAGS(sv) = SVt_PVMG;
937 SvANY(sv) = (void*)any;
938 SvREFCNT(sv) = 1 << 30; /* practically infinite */
943 #if defined(PERL_IMPLICIT_CONTEXT)
945 Perl_form_nocontext(const char* pat, ...)
951 retval = vform(pat, &args);
955 #endif /* PERL_IMPLICIT_CONTEXT */
960 Takes a sprintf-style format pattern and conventional
961 (non-SV) arguments and returns the formatted string.
963 (char *) Perl_form(pTHX_ const char* pat, ...)
965 can be used any place a string (char *) is required:
967 char * s = Perl_form("%d.%d",major,minor);
969 Uses a single private buffer so if you want to format several strings you
970 must explicitly copy the earlier strings away (and free the copies when you
977 Perl_form(pTHX_ const char* pat, ...)
982 retval = vform(pat, &args);
988 Perl_vform(pTHX_ const char *pat, va_list *args)
990 SV *sv = mess_alloc();
991 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
995 #if defined(PERL_IMPLICIT_CONTEXT)
997 Perl_mess_nocontext(const char *pat, ...)
1002 va_start(args, pat);
1003 retval = vmess(pat, &args);
1007 #endif /* PERL_IMPLICIT_CONTEXT */
1010 Perl_mess(pTHX_ const char *pat, ...)
1014 va_start(args, pat);
1015 retval = vmess(pat, &args);
1021 S_closest_cop(pTHX_ COP *cop, OP *o)
1023 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1025 if (!o || o == PL_op) return cop;
1027 if (o->op_flags & OPf_KIDS) {
1029 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1033 /* If the OP_NEXTSTATE has been optimised away we can still use it
1034 * the get the file and line number. */
1036 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1039 /* Keep searching, and return when we've found something. */
1041 new_cop = closest_cop(cop, kid);
1042 if (new_cop) return new_cop;
1046 /* Nothing found. */
1052 Perl_vmess(pTHX_ const char *pat, va_list *args)
1054 SV *sv = mess_alloc();
1055 static char dgd[] = " during global destruction.\n";
1058 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1059 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1062 * Try and find the file and line for PL_op. This will usually be
1063 * PL_curcop, but it might be a cop that has been optimised away. We
1064 * can try to find such a cop by searching through the optree starting
1065 * from the sibling of PL_curcop.
1068 cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1069 if (!cop) cop = PL_curcop;
1072 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1073 CopFILE(cop), (IV)CopLINE(cop));
1074 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1075 bool line_mode = (RsSIMPLE(PL_rs) &&
1076 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1077 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1078 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1079 line_mode ? "line" : "chunk",
1080 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1082 #ifdef USE_5005THREADS
1084 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1086 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1092 Perl_vdie(pTHX_ const char* pat, va_list *args)
1095 int was_in_eval = PL_in_eval;
1102 DEBUG_S(PerlIO_printf(Perl_debug_log,
1103 "%p: die: curstack = %p, mainstack = %p\n",
1104 thr, PL_curstack, PL_mainstack));
1107 msv = vmess(pat, args);
1108 if (PL_errors && SvCUR(PL_errors)) {
1109 sv_catsv(PL_errors, msv);
1110 message = SvPV(PL_errors, msglen);
1111 SvCUR_set(PL_errors, 0);
1114 message = SvPV(msv,msglen);
1121 DEBUG_S(PerlIO_printf(Perl_debug_log,
1122 "%p: die: message = %s\ndiehook = %p\n",
1123 thr, message, PL_diehook));
1125 /* sv_2cv might call Perl_croak() */
1126 SV *olddiehook = PL_diehook;
1128 SAVESPTR(PL_diehook);
1129 PL_diehook = Nullsv;
1130 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1132 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1139 msg = newSVpvn(message, msglen);
1147 PUSHSTACKi(PERLSI_DIEHOOK);
1151 call_sv((SV*)cv, G_DISCARD);
1157 PL_restartop = die_where(message, msglen);
1158 DEBUG_S(PerlIO_printf(Perl_debug_log,
1159 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1160 thr, PL_restartop, was_in_eval, PL_top_env));
1161 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1163 return PL_restartop;
1166 #if defined(PERL_IMPLICIT_CONTEXT)
1168 Perl_die_nocontext(const char* pat, ...)
1173 va_start(args, pat);
1174 o = vdie(pat, &args);
1178 #endif /* PERL_IMPLICIT_CONTEXT */
1181 Perl_die(pTHX_ const char* pat, ...)
1185 va_start(args, pat);
1186 o = vdie(pat, &args);
1192 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1202 msv = vmess(pat, args);
1203 if (PL_errors && SvCUR(PL_errors)) {
1204 sv_catsv(PL_errors, msv);
1205 message = SvPV(PL_errors, msglen);
1206 SvCUR_set(PL_errors, 0);
1209 message = SvPV(msv,msglen);
1216 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1217 PTR2UV(thr), message));
1220 /* sv_2cv might call Perl_croak() */
1221 SV *olddiehook = PL_diehook;
1223 SAVESPTR(PL_diehook);
1224 PL_diehook = Nullsv;
1225 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1227 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1234 msg = newSVpvn(message, msglen);
1242 PUSHSTACKi(PERLSI_DIEHOOK);
1246 call_sv((SV*)cv, G_DISCARD);
1252 PL_restartop = die_where(message, msglen);
1256 message = SvPVx(ERRSV, msglen);
1260 /* SFIO can really mess with your errno */
1263 PerlIO *serr = Perl_error_log;
1265 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1266 (void)PerlIO_flush(serr);
1274 #if defined(PERL_IMPLICIT_CONTEXT)
1276 Perl_croak_nocontext(const char *pat, ...)
1280 va_start(args, pat);
1285 #endif /* PERL_IMPLICIT_CONTEXT */
1290 This is the XSUB-writer's interface to Perl's C<die> function.
1291 Normally use this function the same way you use the C C<printf>
1292 function. See C<warn>.
1294 If you want to throw an exception object, assign the object to
1295 C<$@> and then pass C<Nullch> to croak():
1297 errsv = get_sv("@", TRUE);
1298 sv_setsv(errsv, exception_object);
1305 Perl_croak(pTHX_ const char *pat, ...)
1308 va_start(args, pat);
1315 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1324 msv = vmess(pat, args);
1325 message = SvPV(msv, msglen);
1328 /* sv_2cv might call Perl_warn() */
1329 SV *oldwarnhook = PL_warnhook;
1331 SAVESPTR(PL_warnhook);
1332 PL_warnhook = Nullsv;
1333 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1335 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1341 msg = newSVpvn(message, msglen);
1345 PUSHSTACKi(PERLSI_WARNHOOK);
1349 call_sv((SV*)cv, G_DISCARD);
1356 PerlIO *serr = Perl_error_log;
1358 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1360 DEBUG_L(*message == '!'
1361 ? (xstat(message[1]=='!'
1362 ? (message[2]=='!' ? 2 : 1)
1367 (void)PerlIO_flush(serr);
1371 #if defined(PERL_IMPLICIT_CONTEXT)
1373 Perl_warn_nocontext(const char *pat, ...)
1377 va_start(args, pat);
1381 #endif /* PERL_IMPLICIT_CONTEXT */
1386 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1387 function the same way you use the C C<printf> function. See
1394 Perl_warn(pTHX_ const char *pat, ...)
1397 va_start(args, pat);
1402 #if defined(PERL_IMPLICIT_CONTEXT)
1404 Perl_warner_nocontext(U32 err, const char *pat, ...)
1408 va_start(args, pat);
1409 vwarner(err, pat, &args);
1412 #endif /* PERL_IMPLICIT_CONTEXT */
1415 Perl_warner(pTHX_ U32 err, const char* pat,...)
1418 va_start(args, pat);
1419 vwarner(err, pat, &args);
1424 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1433 msv = vmess(pat, args);
1434 message = SvPV(msv, msglen);
1437 #ifdef USE_5005THREADS
1438 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1439 #endif /* USE_5005THREADS */
1441 /* sv_2cv might call Perl_croak() */
1442 SV *olddiehook = PL_diehook;
1444 SAVESPTR(PL_diehook);
1445 PL_diehook = Nullsv;
1446 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1448 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1454 msg = newSVpvn(message, msglen);
1458 PUSHSTACKi(PERLSI_DIEHOOK);
1462 call_sv((SV*)cv, G_DISCARD);
1468 PL_restartop = die_where(message, msglen);
1472 PerlIO *serr = Perl_error_log;
1473 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1474 (void)PerlIO_flush(serr);
1481 /* sv_2cv might call Perl_warn() */
1482 SV *oldwarnhook = PL_warnhook;
1484 SAVESPTR(PL_warnhook);
1485 PL_warnhook = Nullsv;
1486 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1488 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1494 msg = newSVpvn(message, msglen);
1498 PUSHSTACKi(PERLSI_WARNHOOK);
1502 call_sv((SV*)cv, G_DISCARD);
1509 PerlIO *serr = Perl_error_log;
1510 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1512 DEBUG_L(*message == '!'
1513 ? (xstat(message[1]=='!'
1514 ? (message[2]=='!' ? 2 : 1)
1519 (void)PerlIO_flush(serr);
1524 /* since we've already done strlen() for both nam and val
1525 * we can use that info to make things faster than
1526 * sprintf(s, "%s=%s", nam, val)
1528 #define my_setenv_format(s, nam, nlen, val, vlen) \
1529 Copy(nam, s, nlen, char); \
1531 Copy(val, s+(nlen+1), vlen, char); \
1532 *(s+(nlen+1+vlen)) = '\0'
1534 #ifdef USE_ENVIRON_ARRAY
1535 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1536 #if !defined(WIN32) && !defined(NETWARE)
1538 Perl_my_setenv(pTHX_ char *nam, char *val)
1540 #ifndef PERL_USE_SAFE_PUTENV
1541 /* most putenv()s leak, so we manipulate environ directly */
1542 register I32 i=setenv_getix(nam); /* where does it go? */
1545 if (environ == PL_origenviron) { /* need we copy environment? */
1551 for (max = i; environ[max]; max++) ;
1552 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1553 for (j=0; j<max; j++) { /* copy environment */
1554 int len = strlen(environ[j]);
1555 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1556 Copy(environ[j], tmpenv[j], len+1, char);
1558 tmpenv[max] = Nullch;
1559 environ = tmpenv; /* tell exec where it is now */
1562 safesysfree(environ[i]);
1563 while (environ[i]) {
1564 environ[i] = environ[i+1];
1569 if (!environ[i]) { /* does not exist yet */
1570 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1571 environ[i+1] = Nullch; /* make sure it's null terminated */
1574 safesysfree(environ[i]);
1578 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1579 /* all that work just for this */
1580 my_setenv_format(environ[i], nam, nlen, val, vlen);
1582 #else /* PERL_USE_SAFE_PUTENV */
1583 # if defined(__CYGWIN__)
1584 setenv(nam, val, 1);
1587 int nlen = strlen(nam), vlen;
1592 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1593 /* all that work just for this */
1594 my_setenv_format(new_env, nam, nlen, val, vlen);
1595 (void)putenv(new_env);
1596 # endif /* __CYGWIN__ */
1597 #endif /* PERL_USE_SAFE_PUTENV */
1600 #else /* WIN32 || NETWARE */
1603 Perl_my_setenv(pTHX_ char *nam,char *val)
1605 register char *envstr;
1606 int nlen = strlen(nam), vlen;
1612 New(904, envstr, nlen+vlen+2, char);
1613 my_setenv_format(envstr, nam, nlen, val, vlen);
1614 (void)PerlEnv_putenv(envstr);
1618 #endif /* WIN32 || NETWARE */
1621 Perl_setenv_getix(pTHX_ char *nam)
1623 register I32 i, len = strlen(nam);
1625 for (i = 0; environ[i]; i++) {
1628 strnicmp(environ[i],nam,len) == 0
1630 strnEQ(environ[i],nam,len)
1632 && environ[i][len] == '=')
1633 break; /* strnEQ must come first to avoid */
1634 } /* potential SEGV's */
1638 #endif /* !VMS && !EPOC*/
1640 #ifdef UNLINK_ALL_VERSIONS
1642 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1646 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1651 /* this is a drop-in replacement for bcopy() */
1652 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1654 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1658 if (from - to >= 0) {
1666 *(--to) = *(--from);
1672 /* this is a drop-in replacement for memset() */
1675 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1685 /* this is a drop-in replacement for bzero() */
1686 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1688 Perl_my_bzero(register char *loc, register I32 len)
1698 /* this is a drop-in replacement for memcmp() */
1699 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1701 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1703 register U8 *a = (U8 *)s1;
1704 register U8 *b = (U8 *)s2;
1708 if (tmp = *a++ - *b++)
1713 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1717 #ifdef USE_CHAR_VSPRINTF
1722 vsprintf(char *dest, const char *pat, char *args)
1726 fakebuf._ptr = dest;
1727 fakebuf._cnt = 32767;
1731 fakebuf._flag = _IOWRT|_IOSTRG;
1732 _doprnt(pat, args, &fakebuf); /* what a kludge */
1733 (void)putc('\0', &fakebuf);
1734 #ifdef USE_CHAR_VSPRINTF
1737 return 0; /* perl doesn't use return value */
1741 #endif /* HAS_VPRINTF */
1744 #if BYTEORDER != 0x4321
1746 Perl_my_swap(pTHX_ short s)
1748 #if (BYTEORDER & 1) == 0
1751 result = ((s & 255) << 8) + ((s >> 8) & 255);
1759 Perl_my_htonl(pTHX_ long l)
1763 char c[sizeof(long)];
1766 #if BYTEORDER == 0x1234
1767 u.c[0] = (l >> 24) & 255;
1768 u.c[1] = (l >> 16) & 255;
1769 u.c[2] = (l >> 8) & 255;
1773 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1774 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1779 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1780 u.c[o & 0xf] = (l >> s) & 255;
1788 Perl_my_ntohl(pTHX_ long l)
1792 char c[sizeof(long)];
1795 #if BYTEORDER == 0x1234
1796 u.c[0] = (l >> 24) & 255;
1797 u.c[1] = (l >> 16) & 255;
1798 u.c[2] = (l >> 8) & 255;
1802 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1803 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1810 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1811 l |= (u.c[o & 0xf] & 255) << s;
1818 #endif /* BYTEORDER != 0x4321 */
1822 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1823 * If these functions are defined,
1824 * the BYTEORDER is neither 0x1234 nor 0x4321.
1825 * However, this is not assumed.
1829 #define HTOV(name,type) \
1831 name (register type n) \
1835 char c[sizeof(type)]; \
1839 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1840 u.c[i] = (n >> s) & 0xFF; \
1845 #define VTOH(name,type) \
1847 name (register type n) \
1851 char c[sizeof(type)]; \
1857 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1858 n += (u.c[i] & 0xFF) << s; \
1863 #if defined(HAS_HTOVS) && !defined(htovs)
1866 #if defined(HAS_HTOVL) && !defined(htovl)
1869 #if defined(HAS_VTOHS) && !defined(vtohs)
1872 #if defined(HAS_VTOHL) && !defined(vtohl)
1877 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1879 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1881 register I32 This, that;
1887 PERL_FLUSHALL_FOR_CHILD;
1888 This = (*mode == 'w');
1892 taint_proper("Insecure %s%s", "EXEC");
1894 if (PerlProc_pipe(p) < 0)
1896 /* Try for another pipe pair for error return */
1897 if (PerlProc_pipe(pp) >= 0)
1899 while ((pid = PerlProc_fork()) < 0) {
1900 if (errno != EAGAIN) {
1901 PerlLIO_close(p[This]);
1903 PerlLIO_close(pp[0]);
1904 PerlLIO_close(pp[1]);
1916 /* Close parent's end of _the_ pipe */
1917 PerlLIO_close(p[THAT]);
1918 /* Close parent's end of error status pipe (if any) */
1920 PerlLIO_close(pp[0]);
1921 #if defined(HAS_FCNTL) && defined(F_SETFD)
1922 /* Close error pipe automatically if exec works */
1923 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1926 /* Now dup our end of _the_ pipe to right position */
1927 if (p[THIS] != (*mode == 'r')) {
1928 PerlLIO_dup2(p[THIS], *mode == 'r');
1929 PerlLIO_close(p[THIS]);
1931 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1932 /* No automatic close - do it by hand */
1939 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1945 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
1951 do_execfree(); /* free any memory malloced by child on fork */
1952 /* Close child's end of pipe */
1953 PerlLIO_close(p[that]);
1955 PerlLIO_close(pp[1]);
1956 /* Keep the lower of the two fd numbers */
1957 if (p[that] < p[This]) {
1958 PerlLIO_dup2(p[This], p[that]);
1959 PerlLIO_close(p[This]);
1963 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1965 (void)SvUPGRADE(sv,SVt_IV);
1967 PL_forkprocess = pid;
1968 /* If we managed to get status pipe check for exec fail */
1969 if (did_pipes && pid > 0) {
1973 while (n < sizeof(int)) {
1974 n1 = PerlLIO_read(pp[0],
1975 (void*)(((char*)&errkid)+n),
1981 PerlLIO_close(pp[0]);
1983 if (n) { /* Error */
1985 PerlLIO_close(p[This]);
1986 if (n != sizeof(int))
1987 Perl_croak(aTHX_ "panic: kid popen errno read");
1989 pid2 = wait4pid(pid, &status, 0);
1990 } while (pid2 == -1 && errno == EINTR);
1991 errno = errkid; /* Propagate errno from kid */
1996 PerlLIO_close(pp[0]);
1997 return PerlIO_fdopen(p[This], mode);
1999 Perl_croak(aTHX_ "List form of piped open not implemented");
2000 return (PerlIO *) NULL;
2004 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2005 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2007 Perl_my_popen(pTHX_ char *cmd, char *mode)
2010 register I32 This, that;
2013 I32 doexec = strNE(cmd,"-");
2017 PERL_FLUSHALL_FOR_CHILD;
2020 return my_syspopen(aTHX_ cmd,mode);
2023 This = (*mode == 'w');
2025 if (doexec && PL_tainting) {
2027 taint_proper("Insecure %s%s", "EXEC");
2029 if (PerlProc_pipe(p) < 0)
2031 if (doexec && PerlProc_pipe(pp) >= 0)
2033 while ((pid = PerlProc_fork()) < 0) {
2034 if (errno != EAGAIN) {
2035 PerlLIO_close(p[This]);
2037 PerlLIO_close(pp[0]);
2038 PerlLIO_close(pp[1]);
2041 Perl_croak(aTHX_ "Can't fork");
2053 PerlLIO_close(p[THAT]);
2055 PerlLIO_close(pp[0]);
2056 #if defined(HAS_FCNTL) && defined(F_SETFD)
2057 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2060 if (p[THIS] != (*mode == 'r')) {
2061 PerlLIO_dup2(p[THIS], *mode == 'r');
2062 PerlLIO_close(p[THIS]);
2066 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2075 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2080 /* may or may not use the shell */
2081 do_exec3(cmd, pp[1], did_pipes);
2084 #endif /* defined OS2 */
2086 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2087 SvREADONLY_off(GvSV(tmpgv));
2088 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2089 SvREADONLY_on(GvSV(tmpgv));
2092 hv_clear(PL_pidstatus); /* we have no children */
2097 do_execfree(); /* free any memory malloced by child on fork */
2098 PerlLIO_close(p[that]);
2100 PerlLIO_close(pp[1]);
2101 if (p[that] < p[This]) {
2102 PerlLIO_dup2(p[This], p[that]);
2103 PerlLIO_close(p[This]);
2107 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2109 (void)SvUPGRADE(sv,SVt_IV);
2111 PL_forkprocess = pid;
2112 if (did_pipes && pid > 0) {
2116 while (n < sizeof(int)) {
2117 n1 = PerlLIO_read(pp[0],
2118 (void*)(((char*)&errkid)+n),
2124 PerlLIO_close(pp[0]);
2126 if (n) { /* Error */
2128 PerlLIO_close(p[This]);
2129 if (n != sizeof(int))
2130 Perl_croak(aTHX_ "panic: kid popen errno read");
2132 pid2 = wait4pid(pid, &status, 0);
2133 } while (pid2 == -1 && errno == EINTR);
2134 errno = errkid; /* Propagate errno from kid */
2139 PerlLIO_close(pp[0]);
2140 return PerlIO_fdopen(p[This], mode);
2143 #if defined(atarist)
2146 Perl_my_popen(pTHX_ char *cmd, char *mode)
2148 PERL_FLUSHALL_FOR_CHILD;
2149 /* Call system's popen() to get a FILE *, then import it.
2150 used 0 for 2nd parameter to PerlIO_importFILE;
2153 return PerlIO_importFILE(popen(cmd, mode), 0);
2157 FILE *djgpp_popen();
2159 Perl_my_popen(pTHX_ char *cmd, char *mode)
2161 PERL_FLUSHALL_FOR_CHILD;
2162 /* Call system's popen() to get a FILE *, then import it.
2163 used 0 for 2nd parameter to PerlIO_importFILE;
2166 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2171 #endif /* !DOSISH */
2173 /* this is called in parent before the fork() */
2175 Perl_atfork_lock(void)
2177 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2178 /* locks must be held in locking order (if any) */
2180 MUTEX_LOCK(&PL_malloc_mutex);
2186 /* this is called in both parent and child after the fork() */
2188 Perl_atfork_unlock(void)
2190 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2191 /* locks must be released in same order as in atfork_lock() */
2193 MUTEX_UNLOCK(&PL_malloc_mutex);
2202 #if defined(HAS_FORK)
2204 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2209 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2210 * handlers elsewhere in the code */
2215 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2216 Perl_croak_nocontext("fork() not available");
2218 #endif /* HAS_FORK */
2223 Perl_dump_fds(pTHX_ char *s)
2226 struct stat tmpstatbuf;
2228 PerlIO_printf(Perl_debug_log,"%s", s);
2229 for (fd = 0; fd < 32; fd++) {
2230 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2231 PerlIO_printf(Perl_debug_log," %d",fd);
2233 PerlIO_printf(Perl_debug_log,"\n");
2235 #endif /* DUMP_FDS */
2239 dup2(int oldfd, int newfd)
2241 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2244 PerlLIO_close(newfd);
2245 return fcntl(oldfd, F_DUPFD, newfd);
2247 #define DUP2_MAX_FDS 256
2248 int fdtmp[DUP2_MAX_FDS];
2254 PerlLIO_close(newfd);
2255 /* good enough for low fd's... */
2256 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2257 if (fdx >= DUP2_MAX_FDS) {
2265 PerlLIO_close(fdtmp[--fdx]);
2272 #ifdef HAS_SIGACTION
2275 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2277 struct sigaction act, oact;
2279 act.sa_handler = handler;
2280 sigemptyset(&act.sa_mask);
2283 #if defined(PERL_OLD_SIGNALS)
2284 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2288 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2289 act.sa_flags |= SA_NOCLDWAIT;
2291 if (sigaction(signo, &act, &oact) == -1)
2294 return oact.sa_handler;
2298 Perl_rsignal_state(pTHX_ int signo)
2300 struct sigaction oact;
2302 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2305 return oact.sa_handler;
2309 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2311 struct sigaction act;
2313 act.sa_handler = handler;
2314 sigemptyset(&act.sa_mask);
2317 #if defined(PERL_OLD_SIGNALS)
2318 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2322 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2323 act.sa_flags |= SA_NOCLDWAIT;
2325 return sigaction(signo, &act, save);
2329 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2331 return sigaction(signo, save, (struct sigaction *)NULL);
2334 #else /* !HAS_SIGACTION */
2337 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2339 return PerlProc_signal(signo, handler);
2342 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2343 ignore the implications of this for threading */
2353 Perl_rsignal_state(pTHX_ int signo)
2355 Sighandler_t oldsig;
2358 oldsig = PerlProc_signal(signo, sig_trap);
2359 PerlProc_signal(signo, oldsig);
2361 PerlProc_kill(PerlProc_getpid(), signo);
2366 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2368 *save = PerlProc_signal(signo, handler);
2369 return (*save == SIG_ERR) ? -1 : 0;
2373 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2375 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2378 #endif /* !HAS_SIGACTION */
2379 #endif /* !PERL_MICRO */
2381 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2382 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2384 Perl_my_pclose(pTHX_ PerlIO *ptr)
2386 Sigsave_t hstat, istat, qstat;
2392 int saved_errno = 0;
2394 int saved_vaxc_errno;
2397 int saved_win32_errno;
2401 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2403 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2405 *svp = &PL_sv_undef;
2407 if (pid == -1) { /* Opened by popen. */
2408 return my_syspclose(ptr);
2411 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2412 saved_errno = errno;
2414 saved_vaxc_errno = vaxc$errno;
2417 saved_win32_errno = GetLastError();
2421 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2424 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2425 rsignal_save(SIGINT, SIG_IGN, &istat);
2426 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2429 pid2 = wait4pid(pid, &status, 0);
2430 } while (pid2 == -1 && errno == EINTR);
2432 rsignal_restore(SIGHUP, &hstat);
2433 rsignal_restore(SIGINT, &istat);
2434 rsignal_restore(SIGQUIT, &qstat);
2437 SETERRNO(saved_errno, saved_vaxc_errno);
2440 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2442 #endif /* !DOSISH */
2444 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2446 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2451 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2455 char spid[TYPE_CHARS(int)];
2458 sprintf(spid, "%"IVdf, (IV)pid);
2459 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2460 if (svp && *svp != &PL_sv_undef) {
2461 *statusp = SvIVX(*svp);
2462 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2469 hv_iterinit(PL_pidstatus);
2470 if ((entry = hv_iternext(PL_pidstatus))) {
2471 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2472 sv = hv_iterval(PL_pidstatus,entry);
2473 *statusp = SvIVX(sv);
2474 sprintf(spid, "%"IVdf, (IV)pid);
2475 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2482 # ifdef HAS_WAITPID_RUNTIME
2483 if (!HAS_WAITPID_RUNTIME)
2486 result = PerlProc_waitpid(pid,statusp,flags);
2489 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2490 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2493 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2497 Perl_croak(aTHX_ "Can't do waitpid with flags");
2499 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2500 pidgone(result,*statusp);
2507 if (result < 0 && errno == EINTR) {
2512 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2516 Perl_pidgone(pTHX_ Pid_t pid, int status)
2519 char spid[TYPE_CHARS(int)];
2521 sprintf(spid, "%"IVdf, (IV)pid);
2522 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2523 (void)SvUPGRADE(sv,SVt_IV);
2528 #if defined(atarist) || defined(OS2)
2531 int /* Cannot prototype with I32
2533 my_syspclose(PerlIO *ptr)
2536 Perl_my_pclose(pTHX_ PerlIO *ptr)
2539 /* Needs work for PerlIO ! */
2540 FILE *f = PerlIO_findFILE(ptr);
2541 I32 result = pclose(f);
2542 PerlIO_releaseFILE(ptr,f);
2550 Perl_my_pclose(pTHX_ PerlIO *ptr)
2552 /* Needs work for PerlIO ! */
2553 FILE *f = PerlIO_findFILE(ptr);
2554 I32 result = djgpp_pclose(f);
2555 result = (result << 8) & 0xff00;
2556 PerlIO_releaseFILE(ptr,f);
2562 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2565 register const char *frombase = from;
2568 register const char c = *from;
2573 while (count-- > 0) {
2574 for (todo = len; todo > 0; todo--) {
2583 Perl_same_dirent(pTHX_ char *a, char *b)
2585 char *fa = strrchr(a,'/');
2586 char *fb = strrchr(b,'/');
2587 struct stat tmpstatbuf1;
2588 struct stat tmpstatbuf2;
2589 SV *tmpsv = sv_newmortal();
2602 sv_setpv(tmpsv, ".");
2604 sv_setpvn(tmpsv, a, fa - a);
2605 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2608 sv_setpv(tmpsv, ".");
2610 sv_setpvn(tmpsv, b, fb - b);
2611 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2613 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2614 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2616 #endif /* !HAS_RENAME */
2619 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2621 char *xfound = Nullch;
2622 char *xfailed = Nullch;
2623 char tmpbuf[MAXPATHLEN];
2627 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2628 # define SEARCH_EXTS ".bat", ".cmd", NULL
2629 # define MAX_EXT_LEN 4
2632 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2633 # define MAX_EXT_LEN 4
2636 # define SEARCH_EXTS ".pl", ".com", NULL
2637 # define MAX_EXT_LEN 4
2639 /* additional extensions to try in each dir if scriptname not found */
2641 char *exts[] = { SEARCH_EXTS };
2642 char **ext = search_ext ? search_ext : exts;
2643 int extidx = 0, i = 0;
2644 char *curext = Nullch;
2646 # define MAX_EXT_LEN 0
2650 * If dosearch is true and if scriptname does not contain path
2651 * delimiters, search the PATH for scriptname.
2653 * If SEARCH_EXTS is also defined, will look for each
2654 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2655 * while searching the PATH.
2657 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2658 * proceeds as follows:
2659 * If DOSISH or VMSISH:
2660 * + look for ./scriptname{,.foo,.bar}
2661 * + search the PATH for scriptname{,.foo,.bar}
2664 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2665 * this will not look in '.' if it's not in the PATH)
2670 # ifdef ALWAYS_DEFTYPES
2671 len = strlen(scriptname);
2672 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2673 int hasdir, idx = 0, deftypes = 1;
2676 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2679 int hasdir, idx = 0, deftypes = 1;
2682 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2684 /* The first time through, just add SEARCH_EXTS to whatever we
2685 * already have, so we can check for default file types. */
2687 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2693 if ((strlen(tmpbuf) + strlen(scriptname)
2694 + MAX_EXT_LEN) >= sizeof tmpbuf)
2695 continue; /* don't search dir with too-long name */
2696 strcat(tmpbuf, scriptname);
2700 if (strEQ(scriptname, "-"))
2702 if (dosearch) { /* Look in '.' first. */
2703 char *cur = scriptname;
2705 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2707 if (strEQ(ext[i++],curext)) {
2708 extidx = -1; /* already has an ext */
2713 DEBUG_p(PerlIO_printf(Perl_debug_log,
2714 "Looking for %s\n",cur));
2715 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2716 && !S_ISDIR(PL_statbuf.st_mode)) {
2724 if (cur == scriptname) {
2725 len = strlen(scriptname);
2726 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2728 cur = strcpy(tmpbuf, scriptname);
2730 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2731 && strcpy(tmpbuf+len, ext[extidx++]));
2736 #ifdef MACOS_TRADITIONAL
2737 if (dosearch && !strchr(scriptname, ':') &&
2738 (s = PerlEnv_getenv("Commands")))
2740 if (dosearch && !strchr(scriptname, '/')
2742 && !strchr(scriptname, '\\')
2744 && (s = PerlEnv_getenv("PATH")))
2749 PL_bufend = s + strlen(s);
2750 while (s < PL_bufend) {
2751 #ifdef MACOS_TRADITIONAL
2752 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2756 #if defined(atarist) || defined(DOSISH)
2761 && *s != ';'; len++, s++) {
2762 if (len < sizeof tmpbuf)
2765 if (len < sizeof tmpbuf)
2767 #else /* ! (atarist || DOSISH) */
2768 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2771 #endif /* ! (atarist || DOSISH) */
2772 #endif /* MACOS_TRADITIONAL */
2775 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2776 continue; /* don't search dir with too-long name */
2777 #ifdef MACOS_TRADITIONAL
2778 if (len && tmpbuf[len - 1] != ':')
2779 tmpbuf[len++] = ':';
2782 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2783 && tmpbuf[len - 1] != '/'
2784 && tmpbuf[len - 1] != '\\'
2787 tmpbuf[len++] = '/';
2788 if (len == 2 && tmpbuf[0] == '.')
2791 (void)strcpy(tmpbuf + len, scriptname);
2795 len = strlen(tmpbuf);
2796 if (extidx > 0) /* reset after previous loop */
2800 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2801 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2802 if (S_ISDIR(PL_statbuf.st_mode)) {
2806 } while ( retval < 0 /* not there */
2807 && extidx>=0 && ext[extidx] /* try an extension? */
2808 && strcpy(tmpbuf+len, ext[extidx++])
2813 if (S_ISREG(PL_statbuf.st_mode)
2814 && cando(S_IRUSR,TRUE,&PL_statbuf)
2815 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2816 && cando(S_IXUSR,TRUE,&PL_statbuf)
2820 xfound = tmpbuf; /* bingo! */
2824 xfailed = savepv(tmpbuf);
2827 if (!xfound && !seen_dot && !xfailed &&
2828 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2829 || S_ISDIR(PL_statbuf.st_mode)))
2831 seen_dot = 1; /* Disable message. */
2833 if (flags & 1) { /* do or die? */
2834 Perl_croak(aTHX_ "Can't %s %s%s%s",
2835 (xfailed ? "execute" : "find"),
2836 (xfailed ? xfailed : scriptname),
2837 (xfailed ? "" : " on PATH"),
2838 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2840 scriptname = Nullch;
2844 scriptname = xfound;
2846 return (scriptname ? savepv(scriptname) : Nullch);
2849 #ifndef PERL_GET_CONTEXT_DEFINED
2852 Perl_get_context(void)
2854 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2855 # ifdef OLD_PTHREADS_API
2857 if (pthread_getspecific(PL_thr_key, &t))
2858 Perl_croak_nocontext("panic: pthread_getspecific");
2861 # ifdef I_MACH_CTHREADS
2862 return (void*)cthread_data(cthread_self());
2864 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2873 Perl_set_context(void *t)
2875 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2876 # ifdef I_MACH_CTHREADS
2877 cthread_set_data(cthread_self(), t);
2879 if (pthread_setspecific(PL_thr_key, t))
2880 Perl_croak_nocontext("panic: pthread_setspecific");
2885 #endif /* !PERL_GET_CONTEXT_DEFINED */
2887 #ifdef USE_5005THREADS
2890 /* Very simplistic scheduler for now */
2894 thr = thr->i.next_run;
2898 Perl_cond_init(pTHX_ perl_cond *cp)
2904 Perl_cond_signal(pTHX_ perl_cond *cp)
2907 perl_cond cond = *cp;
2912 /* Insert t in the runnable queue just ahead of us */
2913 t->i.next_run = thr->i.next_run;
2914 thr->i.next_run->i.prev_run = t;
2915 t->i.prev_run = thr;
2916 thr->i.next_run = t;
2917 thr->i.wait_queue = 0;
2918 /* Remove from the wait queue */
2924 Perl_cond_broadcast(pTHX_ perl_cond *cp)
2927 perl_cond cond, cond_next;
2929 for (cond = *cp; cond; cond = cond_next) {
2931 /* Insert t in the runnable queue just ahead of us */
2932 t->i.next_run = thr->i.next_run;
2933 thr->i.next_run->i.prev_run = t;
2934 t->i.prev_run = thr;
2935 thr->i.next_run = t;
2936 thr->i.wait_queue = 0;
2937 /* Remove from the wait queue */
2938 cond_next = cond->next;
2945 Perl_cond_wait(pTHX_ perl_cond *cp)
2949 if (thr->i.next_run == thr)
2950 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
2952 New(666, cond, 1, struct perl_wait_queue);
2956 thr->i.wait_queue = cond;
2957 /* Remove ourselves from runnable queue */
2958 thr->i.next_run->i.prev_run = thr->i.prev_run;
2959 thr->i.prev_run->i.next_run = thr->i.next_run;
2961 #endif /* FAKE_THREADS */
2964 Perl_condpair_magic(pTHX_ SV *sv)
2968 (void)SvUPGRADE(sv, SVt_PVMG);
2969 mg = mg_find(sv, PERL_MAGIC_mutex);
2973 New(53, cp, 1, condpair_t);
2974 MUTEX_INIT(&cp->mutex);
2975 COND_INIT(&cp->owner_cond);
2976 COND_INIT(&cp->cond);
2978 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
2979 mg = mg_find(sv, PERL_MAGIC_mutex);
2981 /* someone else beat us to initialising it */
2982 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2983 MUTEX_DESTROY(&cp->mutex);
2984 COND_DESTROY(&cp->owner_cond);
2985 COND_DESTROY(&cp->cond);
2989 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
2991 mg->mg_ptr = (char *)cp;
2992 mg->mg_len = sizeof(cp);
2993 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2994 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
2995 "%p: condpair_magic %p\n", thr, sv)));
3002 Perl_sv_lock(pTHX_ SV *osv)
3012 mg = condpair_magic(sv);
3013 MUTEX_LOCK(MgMUTEXP(mg));
3014 if (MgOWNER(mg) == thr)
3015 MUTEX_UNLOCK(MgMUTEXP(mg));
3018 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3020 DEBUG_S(PerlIO_printf(Perl_debug_log,
3021 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3022 PTR2UV(thr), PTR2UV(sv)));
3023 MUTEX_UNLOCK(MgMUTEXP(mg));
3024 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3026 UNLOCK_SV_LOCK_MUTEX;
3031 * Make a new perl thread structure using t as a prototype. Some of the
3032 * fields for the new thread are copied from the prototype thread, t,
3033 * so t should not be running in perl at the time this function is
3034 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3035 * thread calling new_struct_thread) clearly satisfies this constraint.
3037 struct perl_thread *
3038 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3040 #if !defined(PERL_IMPLICIT_CONTEXT)
3041 struct perl_thread *thr;
3047 sv = newSVpvn("", 0);
3048 SvGROW(sv, sizeof(struct perl_thread) + 1);
3049 SvCUR_set(sv, sizeof(struct perl_thread));
3050 thr = (Thread) SvPVX(sv);
3052 memset(thr, 0xab, sizeof(struct perl_thread));
3059 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3060 PL_efloatbuf = (char*)NULL;
3063 Zero(thr, 1, struct perl_thread);
3069 PL_curcop = &PL_compiling;
3070 thr->interp = t->interp;
3071 thr->cvcache = newHV();
3072 thr->threadsv = newAV();
3073 thr->specific = newAV();
3074 thr->errsv = newSVpvn("", 0);
3075 thr->flags = THRf_R_JOINABLE;
3077 MUTEX_INIT(&thr->mutex);
3081 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3084 PL_statname = NEWSV(66,0);
3085 PL_errors = newSVpvn("", 0);
3087 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3088 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3089 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3090 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3091 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3093 PL_reginterp_cnt = 0;
3094 PL_lastscream = Nullsv;
3097 PL_reg_start_tmp = 0;
3098 PL_reg_start_tmpl = 0;
3099 PL_reg_poscache = Nullch;
3101 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3103 /* parent thread's data needs to be locked while we make copy */
3104 MUTEX_LOCK(&t->mutex);
3106 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3107 PL_protect = t->Tprotect;
3110 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3111 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3112 PL_curstash = t->Tcurstash; /* always be set to main? */
3114 PL_tainted = t->Ttainted;
3115 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3116 PL_rs = newSVsv(t->Trs);
3117 PL_last_in_gv = Nullgv;
3118 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3119 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3120 PL_chopset = t->Tchopset;
3121 PL_bodytarget = newSVsv(t->Tbodytarget);
3122 PL_toptarget = newSVsv(t->Ttoptarget);
3123 if (t->Tformtarget == t->Ttoptarget)
3124 PL_formtarget = PL_toptarget;
3126 PL_formtarget = PL_bodytarget;
3128 /* Initialise all per-thread SVs that the template thread used */
3129 svp = AvARRAY(t->threadsv);
3130 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3131 if (*svp && *svp != &PL_sv_undef) {
3132 SV *sv = newSVsv(*svp);
3133 av_store(thr->threadsv, i, sv);
3134 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3135 DEBUG_S(PerlIO_printf(Perl_debug_log,
3136 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3140 thr->threadsvp = AvARRAY(thr->threadsv);
3142 MUTEX_LOCK(&PL_threads_mutex);
3144 thr->tid = ++PL_threadnum;
3145 thr->next = t->next;
3148 thr->next->prev = thr;
3149 MUTEX_UNLOCK(&PL_threads_mutex);
3151 /* done copying parent's state */
3152 MUTEX_UNLOCK(&t->mutex);
3154 #ifdef HAVE_THREAD_INTERN
3155 Perl_init_thread_intern(thr);
3156 #endif /* HAVE_THREAD_INTERN */
3159 #endif /* USE_5005THREADS */
3161 #ifdef PERL_GLOBAL_STRUCT
3170 Perl_get_op_names(pTHX)
3176 Perl_get_op_descs(pTHX)
3182 Perl_get_no_modify(pTHX)
3184 return (char*)PL_no_modify;
3188 Perl_get_opargs(pTHX)
3194 Perl_get_ppaddr(pTHX)
3196 return (PPADDR_t*)PL_ppaddr;
3199 #ifndef HAS_GETENV_LEN
3201 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3203 char *env_trans = PerlEnv_getenv(env_elem);
3205 *len = strlen(env_trans);
3212 Perl_get_vtbl(pTHX_ int vtbl_id)
3214 MGVTBL* result = Null(MGVTBL*);
3218 result = &PL_vtbl_sv;
3221 result = &PL_vtbl_env;
3223 case want_vtbl_envelem:
3224 result = &PL_vtbl_envelem;
3227 result = &PL_vtbl_sig;
3229 case want_vtbl_sigelem:
3230 result = &PL_vtbl_sigelem;
3232 case want_vtbl_pack:
3233 result = &PL_vtbl_pack;
3235 case want_vtbl_packelem:
3236 result = &PL_vtbl_packelem;
3238 case want_vtbl_dbline:
3239 result = &PL_vtbl_dbline;
3242 result = &PL_vtbl_isa;
3244 case want_vtbl_isaelem:
3245 result = &PL_vtbl_isaelem;
3247 case want_vtbl_arylen:
3248 result = &PL_vtbl_arylen;
3250 case want_vtbl_glob:
3251 result = &PL_vtbl_glob;
3253 case want_vtbl_mglob:
3254 result = &PL_vtbl_mglob;
3256 case want_vtbl_nkeys:
3257 result = &PL_vtbl_nkeys;
3259 case want_vtbl_taint:
3260 result = &PL_vtbl_taint;
3262 case want_vtbl_substr:
3263 result = &PL_vtbl_substr;
3266 result = &PL_vtbl_vec;
3269 result = &PL_vtbl_pos;
3272 result = &PL_vtbl_bm;
3275 result = &PL_vtbl_fm;
3277 case want_vtbl_uvar:
3278 result = &PL_vtbl_uvar;
3280 #ifdef USE_5005THREADS
3281 case want_vtbl_mutex:
3282 result = &PL_vtbl_mutex;
3285 case want_vtbl_defelem:
3286 result = &PL_vtbl_defelem;
3288 case want_vtbl_regexp:
3289 result = &PL_vtbl_regexp;
3291 case want_vtbl_regdata:
3292 result = &PL_vtbl_regdata;
3294 case want_vtbl_regdatum:
3295 result = &PL_vtbl_regdatum;
3297 #ifdef USE_LOCALE_COLLATE
3298 case want_vtbl_collxfrm:
3299 result = &PL_vtbl_collxfrm;
3302 case want_vtbl_amagic:
3303 result = &PL_vtbl_amagic;
3305 case want_vtbl_amagicelem:
3306 result = &PL_vtbl_amagicelem;
3308 case want_vtbl_backref:
3309 result = &PL_vtbl_backref;
3316 Perl_my_fflush_all(pTHX)
3318 #if defined(FFLUSH_NULL)
3319 return PerlIO_flush(NULL);
3321 # if defined(HAS__FWALK)
3322 /* undocumented, unprototyped, but very useful BSDism */
3323 extern void _fwalk(int (*)(FILE *));
3327 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3329 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3330 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3332 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3333 open_max = sysconf(_SC_OPEN_MAX);
3336 open_max = FOPEN_MAX;
3339 open_max = OPEN_MAX;
3350 for (i = 0; i < open_max; i++)
3351 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3352 STDIO_STREAM_ARRAY[i]._file < open_max &&
3353 STDIO_STREAM_ARRAY[i]._flag)
3354 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3358 SETERRNO(EBADF,RMS$_IFI);
3365 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3370 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3371 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3373 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3374 char *type = OP_IS_SOCKET(op) ||
3375 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3376 "socket" : "filehandle";
3379 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3381 warn_type = WARN_CLOSED;
3385 warn_type = WARN_UNOPENED;
3388 if (gv && isGV(gv)) {
3389 SV *sv = sv_newmortal();
3390 gv_efullname4(sv, gv, Nullch, FALSE);
3394 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3396 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
3398 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3400 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
3401 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3402 } else if (name && *name) {
3403 Perl_warner(aTHX_ warn_type,
3404 "%s%s on %s %s %s", func, pars, vile, type, name);
3405 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3406 Perl_warner(aTHX_ warn_type,
3407 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3411 Perl_warner(aTHX_ warn_type,
3412 "%s%s on %s %s", func, pars, vile, type);
3413 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3414 Perl_warner(aTHX_ warn_type,
3415 "\t(Are you trying to call %s%s on dirhandle?)\n",
3421 /* in ASCII order, not that it matters */
3422 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3425 Perl_ebcdic_control(pTHX_ int ch)
3433 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3434 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3437 if (ctlp == controllablechars)
3438 return('\177'); /* DEL */
3440 return((unsigned char)(ctlp - controllablechars - 1));
3441 } else { /* Want uncontrol */
3442 if (ch == '\177' || ch == -1)
3444 else if (ch == '\157')
3446 else if (ch == '\174')
3448 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3450 else if (ch == '\155')
3452 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3453 return(controllablechars[ch+1]);
3455 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3460 /* XXX struct tm on some systems (SunOS4/BSD) contains extra (non POSIX)
3461 * fields for which we don't have Configure support yet:
3462 * char *tm_zone; -- abbreviation of timezone name
3463 * long tm_gmtoff; -- offset from GMT in seconds
3464 * To workaround core dumps from the uninitialised tm_zone we get the
3465 * system to give us a reasonable struct to copy. This fix means that
3466 * strftime uses the tm_zone and tm_gmtoff values returned by
3467 * localtime(time()). That should give the desired result most of the
3468 * time. But probably not always!
3470 * This is a temporary workaround to be removed once Configure
3471 * support is added and NETaa14816 is considered in full.
3472 * It does not address tzname aspects of NETaa14816.
3475 # ifndef STRUCT_TM_HASZONE
3476 # define STRUCT_TM_HASZONE
3481 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3483 #ifdef STRUCT_TM_HASZONE
3486 Copy(localtime(&now), ptm, 1, struct tm);
3491 * mini_mktime - normalise struct tm values without the localtime()
3492 * semantics (and overhead) of mktime().
3495 Perl_mini_mktime(pTHX_ struct tm *ptm)
3499 int month, mday, year, jday;
3500 int odd_cent, odd_year;
3502 #define DAYS_PER_YEAR 365
3503 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3504 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3505 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3506 #define SECS_PER_HOUR (60*60)
3507 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3508 /* parentheses deliberately absent on these two, otherwise they don't work */
3509 #define MONTH_TO_DAYS 153/5
3510 #define DAYS_TO_MONTH 5/153
3511 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3512 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3513 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3514 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3517 * Year/day algorithm notes:
3519 * With a suitable offset for numeric value of the month, one can find
3520 * an offset into the year by considering months to have 30.6 (153/5) days,
3521 * using integer arithmetic (i.e., with truncation). To avoid too much
3522 * messing about with leap days, we consider January and February to be
3523 * the 13th and 14th month of the previous year. After that transformation,
3524 * we need the month index we use to be high by 1 from 'normal human' usage,
3525 * so the month index values we use run from 4 through 15.
3527 * Given that, and the rules for the Gregorian calendar (leap years are those
3528 * divisible by 4 unless also divisible by 100, when they must be divisible
3529 * by 400 instead), we can simply calculate the number of days since some
3530 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3531 * the days we derive from our month index, and adding in the day of the
3532 * month. The value used here is not adjusted for the actual origin which
3533 * it normally would use (1 January A.D. 1), since we're not exposing it.
3534 * We're only building the value so we can turn around and get the
3535 * normalised values for the year, month, day-of-month, and day-of-year.
3537 * For going backward, we need to bias the value we're using so that we find
3538 * the right year value. (Basically, we don't want the contribution of
3539 * March 1st to the number to apply while deriving the year). Having done
3540 * that, we 'count up' the contribution to the year number by accounting for
3541 * full quadracenturies (400-year periods) with their extra leap days, plus
3542 * the contribution from full centuries (to avoid counting in the lost leap
3543 * days), plus the contribution from full quad-years (to count in the normal
3544 * leap days), plus the leftover contribution from any non-leap years.
3545 * At this point, if we were working with an actual leap day, we'll have 0
3546 * days left over. This is also true for March 1st, however. So, we have
3547 * to special-case that result, and (earlier) keep track of the 'odd'
3548 * century and year contributions. If we got 4 extra centuries in a qcent,
3549 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3550 * Otherwise, we add back in the earlier bias we removed (the 123 from
3551 * figuring in March 1st), find the month index (integer division by 30.6),
3552 * and the remainder is the day-of-month. We then have to convert back to
3553 * 'real' months (including fixing January and February from being 14/15 in
3554 * the previous year to being in the proper year). After that, to get
3555 * tm_yday, we work with the normalised year and get a new yearday value for
3556 * January 1st, which we subtract from the yearday value we had earlier,
3557 * representing the date we've re-built. This is done from January 1
3558 * because tm_yday is 0-origin.
3560 * Since POSIX time routines are only guaranteed to work for times since the
3561 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3562 * applies Gregorian calendar rules even to dates before the 16th century
3563 * doesn't bother me. Besides, you'd need cultural context for a given
3564 * date to know whether it was Julian or Gregorian calendar, and that's
3565 * outside the scope for this routine. Since we convert back based on the
3566 * same rules we used to build the yearday, you'll only get strange results
3567 * for input which needed normalising, or for the 'odd' century years which
3568 * were leap years in the Julian calander but not in the Gregorian one.
3569 * I can live with that.
3571 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3572 * that's still outside the scope for POSIX time manipulation, so I don't
3576 year = 1900 + ptm->tm_year;
3577 month = ptm->tm_mon;
3578 mday = ptm->tm_mday;
3579 /* allow given yday with no month & mday to dominate the result */
3580 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3583 jday = 1 + ptm->tm_yday;
3592 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3593 yearday += month*MONTH_TO_DAYS + mday + jday;
3595 * Note that we don't know when leap-seconds were or will be,
3596 * so we have to trust the user if we get something which looks
3597 * like a sensible leap-second. Wild values for seconds will
3598 * be rationalised, however.
3600 if ((unsigned) ptm->tm_sec <= 60) {
3607 secs += 60 * ptm->tm_min;
3608 secs += SECS_PER_HOUR * ptm->tm_hour;
3610 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3611 /* got negative remainder, but need positive time */
3612 /* back off an extra day to compensate */
3613 yearday += (secs/SECS_PER_DAY)-1;
3614 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3617 yearday += (secs/SECS_PER_DAY);
3618 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3621 else if (secs >= SECS_PER_DAY) {
3622 yearday += (secs/SECS_PER_DAY);
3623 secs %= SECS_PER_DAY;
3625 ptm->tm_hour = secs/SECS_PER_HOUR;
3626 secs %= SECS_PER_HOUR;
3627 ptm->tm_min = secs/60;
3629 ptm->tm_sec += secs;
3630 /* done with time of day effects */
3632 * The algorithm for yearday has (so far) left it high by 428.
3633 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3634 * bias it by 123 while trying to figure out what year it
3635 * really represents. Even with this tweak, the reverse
3636 * translation fails for years before A.D. 0001.
3637 * It would still fail for Feb 29, but we catch that one below.
3639 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3640 yearday -= YEAR_ADJUST;
3641 year = (yearday / DAYS_PER_QCENT) * 400;
3642 yearday %= DAYS_PER_QCENT;
3643 odd_cent = yearday / DAYS_PER_CENT;
3644 year += odd_cent * 100;
3645 yearday %= DAYS_PER_CENT;
3646 year += (yearday / DAYS_PER_QYEAR) * 4;
3647 yearday %= DAYS_PER_QYEAR;
3648 odd_year = yearday / DAYS_PER_YEAR;
3650 yearday %= DAYS_PER_YEAR;
3651 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3656 yearday += YEAR_ADJUST; /* recover March 1st crock */
3657 month = yearday*DAYS_TO_MONTH;
3658 yearday -= month*MONTH_TO_DAYS;
3659 /* recover other leap-year adjustment */
3668 ptm->tm_year = year - 1900;
3670 ptm->tm_mday = yearday;
3671 ptm->tm_mon = month;
3675 ptm->tm_mon = month - 1;
3677 /* re-build yearday based on Jan 1 to get tm_yday */
3679 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3680 yearday += 14*MONTH_TO_DAYS + 1;
3681 ptm->tm_yday = jday - yearday;
3682 /* fix tm_wday if not overridden by caller */
3683 if ((unsigned)ptm->tm_wday > 6)
3684 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3688 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3696 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3699 mytm.tm_hour = hour;
3700 mytm.tm_mday = mday;
3702 mytm.tm_year = year;
3703 mytm.tm_wday = wday;
3704 mytm.tm_yday = yday;
3705 mytm.tm_isdst = isdst;
3708 New(0, buf, buflen, char);
3709 len = strftime(buf, buflen, fmt, &mytm);
3711 ** The following is needed to handle to the situation where
3712 ** tmpbuf overflows. Basically we want to allocate a buffer
3713 ** and try repeatedly. The reason why it is so complicated
3714 ** is that getting a return value of 0 from strftime can indicate
3715 ** one of the following:
3716 ** 1. buffer overflowed,
3717 ** 2. illegal conversion specifier, or
3718 ** 3. the format string specifies nothing to be returned(not
3719 ** an error). This could be because format is an empty string
3720 ** or it specifies %p that yields an empty string in some locale.
3721 ** If there is a better way to make it portable, go ahead by
3724 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3727 /* Possibly buf overflowed - try again with a bigger buf */
3728 int fmtlen = strlen(fmt);
3729 int bufsize = fmtlen + buflen;
3731 New(0, buf, bufsize, char);
3733 buflen = strftime(buf, bufsize, fmt, &mytm);
3734 if (buflen > 0 && buflen < bufsize)
3736 /* heuristic to prevent out-of-memory errors */
3737 if (bufsize > 100*fmtlen) {
3743 Renew(buf, bufsize, char);
3748 Perl_croak(aTHX_ "panic: no strftime");
3753 #define SV_CWD_RETURN_UNDEF \
3754 sv_setsv(sv, &PL_sv_undef); \
3757 #define SV_CWD_ISDOT(dp) \
3758 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3759 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3762 =for apidoc getcwd_sv
3764 Fill the sv with current working directory
3769 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3770 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3771 * getcwd(3) if available
3772 * Comments from the orignal:
3773 * This is a faster version of getcwd. It's also more dangerous
3774 * because you might chdir out of a directory that you can't chdir
3778 Perl_getcwd_sv(pTHX_ register SV *sv)
3782 #ifndef INCOMPLETE_TAINTS
3788 char buf[MAXPATHLEN];
3790 /* Some getcwd()s automatically allocate a buffer of the given
3791 * size from the heap if they are given a NULL buffer pointer.
3792 * The problem is that this behaviour is not portable. */
3793 if (getcwd(buf, sizeof(buf) - 1)) {
3794 STRLEN len = strlen(buf);
3795 sv_setpvn(sv, buf, len);
3799 sv_setsv(sv, &PL_sv_undef);
3806 struct stat statbuf;
3807 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3808 int namelen, pathlen=0;
3812 (void)SvUPGRADE(sv, SVt_PV);
3814 if (PerlLIO_lstat(".", &statbuf) < 0) {
3815 SV_CWD_RETURN_UNDEF;
3818 orig_cdev = statbuf.st_dev;
3819 orig_cino = statbuf.st_ino;
3827 if (PerlDir_chdir("..") < 0) {
3828 SV_CWD_RETURN_UNDEF;
3830 if (PerlLIO_stat(".", &statbuf) < 0) {
3831 SV_CWD_RETURN_UNDEF;
3834 cdev = statbuf.st_dev;
3835 cino = statbuf.st_ino;
3837 if (odev == cdev && oino == cino) {
3840 if (!(dir = PerlDir_open("."))) {
3841 SV_CWD_RETURN_UNDEF;
3844 while ((dp = PerlDir_read(dir)) != NULL) {
3846 namelen = dp->d_namlen;
3848 namelen = strlen(dp->d_name);
3851 if (SV_CWD_ISDOT(dp)) {
3855 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3856 SV_CWD_RETURN_UNDEF;
3859 tdev = statbuf.st_dev;
3860 tino = statbuf.st_ino;
3861 if (tino == oino && tdev == odev) {
3867 SV_CWD_RETURN_UNDEF;
3870 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3871 SV_CWD_RETURN_UNDEF;
3874 SvGROW(sv, pathlen + namelen + 1);
3878 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3881 /* prepend current directory to the front */
3883 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3884 pathlen += (namelen + 1);
3886 #ifdef VOID_CLOSEDIR
3889 if (PerlDir_close(dir) < 0) {
3890 SV_CWD_RETURN_UNDEF;
3896 SvCUR_set(sv, pathlen);
3900 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3901 SV_CWD_RETURN_UNDEF;
3904 if (PerlLIO_stat(".", &statbuf) < 0) {
3905 SV_CWD_RETURN_UNDEF;
3908 cdev = statbuf.st_dev;
3909 cino = statbuf.st_ino;
3911 if (cdev != orig_cdev || cino != orig_cino) {
3912 Perl_croak(aTHX_ "Unstable directory path, "
3913 "current directory changed unexpectedly");
3924 =for apidoc new_vstring
3926 Returns a pointer to the next character after the parsed
3927 vstring, as well as updating the passed in sv.
3929 Function must be called like
3932 s = new_vstring(s,sv);
3934 The sv must already be large enough to store the vstring
3941 Perl_new_vstring(pTHX_ char *s, SV *sv)
3944 if (*pos == 'v') pos++; /* get past 'v' */
3945 while (isDIGIT(*pos) || *pos == '_')
3947 if (!isALPHA(*pos)) {
3949 U8 tmpbuf[UTF8_MAXLEN+1];
3952 if (*s == 'v') s++; /* get past 'v' */
3954 sv_setpvn(sv, "", 0);
3959 /* this is atoi() that tolerates underscores */
3962 if ( *(s-1) == '_') {
3965 while (--end >= s) {
3968 rev += (*end - '0') * mult;
3970 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
3971 Perl_warner(aTHX_ WARN_OVERFLOW,
3972 "Integer overflow in decimal number");
3975 /* Append native character for the rev point */
3976 tmpend = uvchr_to_utf8(tmpbuf, rev);
3977 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
3978 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
3980 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
3986 while (isDIGIT(*pos) )
3995 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET)
3997 S_socketpair_udp (int fd[2]) {
3998 /* Fake a datagram socketpair using UDP to localhost. */
3999 int sockets[2] = {-1, -1};
4000 struct sockaddr_in addresses[2];
4002 Sock_size_t size = sizeof (struct sockaddr_in);
4003 unsigned short port;
4006 memset (&addresses, 0, sizeof (addresses));
4009 sockets[i] = socket (AF_INET, SOCK_DGRAM, 0);
4010 if (sockets[i] == -1)
4011 goto tidy_up_and_fail;
4013 addresses[i].sin_family = AF_INET;
4014 addresses[i].sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4015 addresses[i].sin_port = 0; /* kernel choses port. */
4016 if (bind (sockets[i], (struct sockaddr *) &addresses[i],
4017 sizeof (struct sockaddr_in))
4019 goto tidy_up_and_fail;
4022 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4023 for each connect the other socket to it. */
4026 if (getsockname (sockets[i], (struct sockaddr *) &addresses[i], &size)
4028 goto tidy_up_and_fail;
4029 if (size != sizeof (struct sockaddr_in))
4030 goto abort_tidy_up_and_fail;
4031 /* !1 is 0, !0 is 1 */
4032 if (connect(sockets[!i], (struct sockaddr *) &addresses[i],
4033 sizeof (struct sockaddr_in)) == -1)
4034 goto tidy_up_and_fail;
4037 /* Now we have 2 sockets connected to each other. I don't trust some other
4038 process not to have already sent a packet to us (by random) so send
4039 a packet from each to the other. */
4042 /* I'm going to send my own port number. As a short.
4043 (Who knows if someone somewhere has sin_port as a bitfield and needs
4044 this routine. (I'm assuming crays have socketpair)) */
4045 port = addresses[i].sin_port;
4046 got = write (sockets[i], &port, sizeof(port));
4047 if (got != sizeof(port)) {
4049 goto tidy_up_and_fail;
4050 goto abort_tidy_up_and_fail;
4054 /* Packets sent. I don't trust them to have arrived though.
4055 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4056 connect to localhost will use a second kernel thread. In 2.6 the
4057 first thread running the connect() returns before the second completes,
4058 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4059 returns 0. Poor programs have tripped up. One poor program's authors'
4060 had a 50-1 reverse stock split. Not sure how connected these were.)
4061 So I don't trust someone not to have an unpredictable UDP stack.
4065 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4066 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4070 FD_SET (sockets[0], &rset);
4071 FD_SET (sockets[1], &rset);
4073 got = select (max + 1, &rset, NULL, NULL, &waitfor);
4074 if (got != 2 || !FD_ISSET (sockets[0], &rset)
4075 || !FD_ISSET (sockets[1], &rset)) {
4076 /* I hope this is portable and appropriate. */
4078 goto tidy_up_and_fail;
4079 goto abort_tidy_up_and_fail;
4083 /* And the paranoia department even now doesn't trust it to have arrive
4084 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4086 struct sockaddr_in readfrom;
4087 unsigned short buffer[2];
4091 got = recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4097 (struct sockaddr *) &readfrom, &size);
4100 goto tidy_up_and_fail;
4101 if (got != sizeof(port)
4102 || size != sizeof (struct sockaddr_in)
4103 /* Check other socket sent us its port. */
4104 || buffer[0] != (unsigned short) addresses[!i].sin_port
4105 /* Check kernel says we got the datagram from that socket. */
4106 || readfrom.sin_family != addresses[!i].sin_family
4107 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4108 || readfrom.sin_port != addresses[!i].sin_port)
4109 goto abort_tidy_up_and_fail;
4112 /* My caller (my_socketpair) has validated that this is non-NULL */
4115 /* I hereby declare this connection open. May God bless all who cross
4119 abort_tidy_up_and_fail:
4120 errno = ECONNABORTED;
4123 int save_errno = errno;
4124 if (sockets[0] != -1)
4126 if (sockets[1] != -1)
4134 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4135 /* Stevens says that family must be AF_LOCAL, protocol 0.
4136 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4140 struct sockaddr_in listen_addr;
4141 struct sockaddr_in connect_addr;
4146 || family != AF_UNIX
4149 errno = EAFNOSUPPORT;
4157 if (type == SOCK_DGRAM)
4158 return S_socketpair_udp (fd);
4160 listener = socket (AF_INET, type, 0);
4163 memset (&listen_addr, 0, sizeof (listen_addr));
4164 listen_addr.sin_family = AF_INET;
4165 listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4166 listen_addr.sin_port = 0; /* kernel choses port. */
4167 if (bind (listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
4169 goto tidy_up_and_fail;
4170 if (listen(listener, 1) == -1)
4171 goto tidy_up_and_fail;
4173 connector = socket (AF_INET, type, 0);
4174 if (connector == -1)
4175 goto tidy_up_and_fail;
4176 /* We want to find out the port number to connect to. */
4177 size = sizeof (connect_addr);
4178 if (getsockname (listener, (struct sockaddr *) &connect_addr, &size) == -1)
4179 goto tidy_up_and_fail;
4180 if (size != sizeof (connect_addr))
4181 goto abort_tidy_up_and_fail;
4182 if (connect(connector, (struct sockaddr *) &connect_addr,
4183 sizeof (connect_addr)) == -1)
4184 goto tidy_up_and_fail;
4186 size = sizeof (listen_addr);
4187 acceptor = accept (listener, (struct sockaddr *) &listen_addr, &size);
4189 goto tidy_up_and_fail;
4190 if (size != sizeof (listen_addr))
4191 goto abort_tidy_up_and_fail;
4193 /* Now check we are talking to ourself by matching port and host on the
4195 if (getsockname (connector, (struct sockaddr *) &connect_addr, &size) == -1)
4196 goto tidy_up_and_fail;
4197 if (size != sizeof (connect_addr)
4198 || listen_addr.sin_family != connect_addr.sin_family
4199 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4200 || listen_addr.sin_port != connect_addr.sin_port) {
4201 goto abort_tidy_up_and_fail;
4207 abort_tidy_up_and_fail:
4208 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4211 int save_errno = errno;
4214 if (connector != -1)
4222 #endif /* !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) */