3 * Copyright (c) 1991-1997, 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
19 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
24 # define SIG_ERR ((Sighandler_t) -1)
27 /* XXX If this causes problems, set i_unistd=undef in the hint file. */
36 /* Put this after #includes because fork and vfork prototypes may
47 # include <sys/file.h>
51 # include <sys/wait.h>
58 static void xstat _((int));
59 long xcount[MAXXCOUNT];
60 long lastxcount[MAXXCOUNT];
61 long xycount[MAXXCOUNT][MAXYCOUNT];
62 long lastxycount[MAXXCOUNT][MAXYCOUNT];
68 /* paranoid version of malloc */
70 /* NOTE: Do not call the next three routines directly. Use the macros
71 * in handy.h, so that we can easily redefine everything to do tracking of
72 * allocated hunks back to the original New to track down any memory leaks.
73 * XXX This advice seems to be widely ignored :-( --AD August 1996.
77 safemalloc(MEM_SIZE size)
82 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
85 #endif /* HAS_64K_LIMIT */
88 croak("panic: malloc");
90 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
91 #if !(defined(I286) || defined(atarist))
92 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
101 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
108 /* paranoid version of realloc */
111 saferealloc(Malloc_t where,MEM_SIZE size)
114 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
115 Malloc_t PerlMem_realloc();
116 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
120 PerlIO_printf(PerlIO_stderr(),
121 "Reallocation too large: %lx\n", size) FLUSH;
124 #endif /* HAS_64K_LIMIT */
126 croak("Null realloc");
129 croak("panic: realloc");
131 ptr = PerlMem_realloc(where,size?size:1); /* realloc(0) is NASTY on our system */
133 #if !(defined(I286) || defined(atarist))
135 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,an++);
136 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
140 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,an++);
141 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
150 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
157 /* safe version of free */
160 safefree(Malloc_t where)
162 #if !(defined(I286) || defined(atarist))
163 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,an++));
165 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,an++));
173 /* safe version of calloc */
176 safecalloc(MEM_SIZE count, MEM_SIZE size)
181 if (size * count > 0xffff) {
182 PerlIO_printf(PerlIO_stderr(),
183 "Allocation too large: %lx\n", size * count) FLUSH;
186 #endif /* HAS_64K_LIMIT */
188 if ((long)size < 0 || (long)count < 0)
189 croak("panic: calloc");
192 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
193 #if !(defined(I286) || defined(atarist))
194 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
196 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
199 memset((void*)ptr, 0, size);
205 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
212 #endif /* !MYMALLOC */
216 struct mem_test_strut {
224 # define ALIGN sizeof(struct mem_test_strut)
226 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
227 # define typeof_chunk(ch) \
228 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
229 # define set_typeof_chunk(ch,t) \
230 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
231 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
234 ? ((size) - 1)/8 + 5 \
238 safexmalloc(I32 x, MEM_SIZE size)
240 register char* where = (char*)safemalloc(size + ALIGN);
243 xycount[x][SIZE_TO_Y(size)]++;
244 set_typeof_chunk(where, x);
245 sizeof_chunk(where) = size;
246 return (Malloc_t)(where + ALIGN);
250 safexrealloc(Malloc_t wh, MEM_SIZE size)
252 char *where = (char*)wh;
255 return safexmalloc(0,size);
258 MEM_SIZE old = sizeof_chunk(where - ALIGN);
259 int t = typeof_chunk(where - ALIGN);
260 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
262 xycount[t][SIZE_TO_Y(old)]--;
263 xycount[t][SIZE_TO_Y(size)]++;
264 xcount[t] += size - old;
265 sizeof_chunk(new) = size;
266 return (Malloc_t)(new + ALIGN);
271 safexfree(Malloc_t wh)
274 char *where = (char*)wh;
280 size = sizeof_chunk(where);
281 x = where[0] + 100 * where[1];
283 xycount[x][SIZE_TO_Y(size)]--;
288 safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
290 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
292 xycount[x][SIZE_TO_Y(size)]++;
293 memset((void*)(where + ALIGN), 0, size * count);
294 set_typeof_chunk(where, x);
295 sizeof_chunk(where) = size;
296 return (Malloc_t)(where + ALIGN);
302 register I32 i, j, total = 0;
303 I32 subtot[MAXYCOUNT];
305 for (j = 0; j < MAXYCOUNT; j++) {
309 PerlIO_printf(PerlIO_stderr(), " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
310 for (i = 0; i < MAXXCOUNT; i++) {
312 for (j = 0; j < MAXYCOUNT; j++) {
313 subtot[j] += xycount[i][j];
316 ? xcount[i] /* Have something */
318 ? xcount[i] != lastxcount[i] /* Changed */
319 : xcount[i] > lastxcount[i])) { /* Growed */
320 PerlIO_printf(PerlIO_stderr(),"%2d %02d %7ld ", i / 100, i % 100,
321 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
322 lastxcount[i] = xcount[i];
323 for (j = 0; j < MAXYCOUNT; j++) {
325 ? xycount[i][j] /* Have something */
327 ? xycount[i][j] != lastxycount[i][j] /* Changed */
328 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
329 PerlIO_printf(PerlIO_stderr(),"%3ld ",
331 ? xycount[i][j] - lastxycount[i][j]
333 lastxycount[i][j] = xycount[i][j];
335 PerlIO_printf(PerlIO_stderr(), " . ", xycount[i][j]);
338 PerlIO_printf(PerlIO_stderr(), "\n");
342 PerlIO_printf(PerlIO_stderr(), "Total %7ld ", total);
343 for (j = 0; j < MAXYCOUNT; j++) {
345 PerlIO_printf(PerlIO_stderr(), "%3ld ", subtot[j]);
347 PerlIO_printf(PerlIO_stderr(), " . ");
350 PerlIO_printf(PerlIO_stderr(), "\n");
354 #endif /* LEAKTEST */
356 /* copy a string up to some (non-backslashed) delimiter, if any */
359 delimcpy(register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
362 for (tolen = 0; from < fromend; from++, tolen++) {
364 if (from[1] == delim)
373 else if (*from == delim)
384 /* return ptr to little string in big string, NULL if not found */
385 /* This routine was donated by Corey Satten. */
388 instr(register char *big, register char *little)
390 register char *s, *x;
401 for (x=big,s=little; *s; /**/ ) {
415 /* same as instr but allow embedded nulls */
418 ninstr(register char *big, register char *bigend, char *little, char *lend)
420 register char *s, *x;
421 register I32 first = *little;
422 register char *littleend = lend;
424 if (!first && little >= littleend)
426 if (bigend - big < littleend - little)
428 bigend -= littleend - little++;
429 while (big <= bigend) {
432 for (x=big,s=little; s < littleend; /**/ ) {
444 /* reverse of the above--find last substring */
447 rninstr(register char *big, char *bigend, char *little, char *lend)
449 register char *bigbeg;
450 register char *s, *x;
451 register I32 first = *little;
452 register char *littleend = lend;
454 if (!first && little >= littleend)
457 big = bigend - (littleend - little++);
458 while (big >= bigbeg) {
461 for (x=big+2,s=little; s < littleend; /**/ ) {
474 * Set up for a new ctype locale.
477 perl_new_ctype(char *newctype)
479 #ifdef USE_LOCALE_CTYPE
483 for (i = 0; i < 256; i++) {
485 fold_locale[i] = toLOWER_LC(i);
486 else if (isLOWER_LC(i))
487 fold_locale[i] = toUPPER_LC(i);
492 #endif /* USE_LOCALE_CTYPE */
496 * Set up for a new collation locale.
499 perl_new_collate(char *newcoll)
501 #ifdef USE_LOCALE_COLLATE
504 if (collation_name) {
506 Safefree(collation_name);
507 collation_name = NULL;
508 collation_standard = TRUE;
515 if (! collation_name || strNE(collation_name, newcoll)) {
517 Safefree(collation_name);
518 collation_name = savepv(newcoll);
519 collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
522 /* 2: at most so many chars ('a', 'b'). */
523 /* 50: surely no system expands a char more. */
524 #define XFRMBUFSIZE (2 * 50)
525 char xbuf[XFRMBUFSIZE];
526 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
527 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
528 SSize_t mult = fb - fa;
530 croak("strxfrm() gets absurd");
531 collxfrm_base = (fa > mult) ? (fa - mult) : 0;
532 collxfrm_mult = mult;
536 #endif /* USE_LOCALE_COLLATE */
540 * Set up for a new numeric locale.
543 perl_new_numeric(char *newnum)
545 #ifdef USE_LOCALE_NUMERIC
549 Safefree(numeric_name);
551 numeric_standard = TRUE;
552 numeric_local = TRUE;
557 if (! numeric_name || strNE(numeric_name, newnum)) {
558 Safefree(numeric_name);
559 numeric_name = savepv(newnum);
560 numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
561 numeric_local = TRUE;
564 #endif /* USE_LOCALE_NUMERIC */
568 perl_set_numeric_standard(void)
570 #ifdef USE_LOCALE_NUMERIC
572 if (! numeric_standard) {
573 setlocale(LC_NUMERIC, "C");
574 numeric_standard = TRUE;
575 numeric_local = FALSE;
578 #endif /* USE_LOCALE_NUMERIC */
582 perl_set_numeric_local(void)
584 #ifdef USE_LOCALE_NUMERIC
586 if (! numeric_local) {
587 setlocale(LC_NUMERIC, numeric_name);
588 numeric_standard = FALSE;
589 numeric_local = TRUE;
592 #endif /* USE_LOCALE_NUMERIC */
597 * Initialize locale awareness.
600 perl_init_i18nl10n(int printwarn)
604 * 1 = set ok or not applicable,
605 * 0 = fallback to C locale,
606 * -1 = fallback to C locale failed
611 #ifdef USE_LOCALE_CTYPE
612 char *curctype = NULL;
613 #endif /* USE_LOCALE_CTYPE */
614 #ifdef USE_LOCALE_COLLATE
615 char *curcoll = NULL;
616 #endif /* USE_LOCALE_COLLATE */
617 #ifdef USE_LOCALE_NUMERIC
619 #endif /* USE_LOCALE_NUMERIC */
620 char *lc_all = PerlEnv_getenv("LC_ALL");
621 char *lang = PerlEnv_getenv("LANG");
622 bool setlocale_failure = FALSE;
624 #ifdef LOCALE_ENVIRON_REQUIRED
627 * Ultrix setlocale(..., "") fails if there are no environment
628 * variables from which to get a locale name.
635 if (setlocale(LC_ALL, ""))
638 setlocale_failure = TRUE;
640 if (!setlocale_failure)
643 #ifdef USE_LOCALE_CTYPE
644 if (! (curctype = setlocale(LC_CTYPE,
645 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
647 setlocale_failure = TRUE;
648 #endif /* USE_LOCALE_CTYPE */
649 #ifdef USE_LOCALE_COLLATE
650 if (! (curcoll = setlocale(LC_COLLATE,
651 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
653 setlocale_failure = TRUE;
654 #endif /* USE_LOCALE_COLLATE */
655 #ifdef USE_LOCALE_NUMERIC
656 if (! (curnum = setlocale(LC_NUMERIC,
657 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
659 setlocale_failure = TRUE;
660 #endif /* USE_LOCALE_NUMERIC */
663 #else /* !LOCALE_ENVIRON_REQUIRED */
667 if (! setlocale(LC_ALL, ""))
668 setlocale_failure = TRUE;
670 #ifdef USE_LOCALE_CTYPE
671 curctype = setlocale(LC_CTYPE, Nullch);
672 #endif /* USE_LOCALE_CTYPE */
673 #ifdef USE_LOCALE_COLLATE
674 curcoll = setlocale(LC_COLLATE, Nullch);
675 #endif /* USE_LOCALE_COLLATE */
676 #ifdef USE_LOCALE_NUMERIC
677 curnum = setlocale(LC_NUMERIC, Nullch);
678 #endif /* USE_LOCALE_NUMERIC */
683 #ifdef USE_LOCALE_CTYPE
684 if (! (curctype = setlocale(LC_CTYPE, "")))
685 setlocale_failure = TRUE;
686 #endif /* USE_LOCALE_CTYPE */
687 #ifdef USE_LOCALE_COLLATE
688 if (! (curcoll = setlocale(LC_COLLATE, "")))
689 setlocale_failure = TRUE;
690 #endif /* USE_LOCALE_COLLATE */
691 #ifdef USE_LOCALE_NUMERIC
692 if (! (curnum = setlocale(LC_NUMERIC, "")))
693 setlocale_failure = TRUE;
694 #endif /* USE_LOCALE_NUMERIC */
698 #endif /* !LOCALE_ENVIRON_REQUIRED */
700 if (setlocale_failure) {
702 bool locwarn = (printwarn > 1 ||
704 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
709 PerlIO_printf(PerlIO_stderr(),
710 "perl: warning: Setting locale failed.\n");
714 PerlIO_printf(PerlIO_stderr(),
715 "perl: warning: Setting locale failed for the categories:\n\t");
716 #ifdef USE_LOCALE_CTYPE
718 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
719 #endif /* USE_LOCALE_CTYPE */
720 #ifdef USE_LOCALE_COLLATE
722 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
723 #endif /* USE_LOCALE_COLLATE */
724 #ifdef USE_LOCALE_NUMERIC
726 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
727 #endif /* USE_LOCALE_NUMERIC */
728 PerlIO_printf(PerlIO_stderr(), "\n");
732 PerlIO_printf(PerlIO_stderr(),
733 "perl: warning: Please check that your locale settings:\n");
735 PerlIO_printf(PerlIO_stderr(),
736 "\tLC_ALL = %c%s%c,\n",
738 lc_all ? lc_all : "unset",
743 for (e = environ; *e; e++) {
744 if (strnEQ(*e, "LC_", 3)
745 && strnNE(*e, "LC_ALL=", 7)
746 && (p = strchr(*e, '=')))
747 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
748 (int)(p - *e), *e, p + 1);
752 PerlIO_printf(PerlIO_stderr(),
755 lang ? lang : "unset",
758 PerlIO_printf(PerlIO_stderr(),
759 " are supported and installed on your system.\n");
764 if (setlocale(LC_ALL, "C")) {
766 PerlIO_printf(PerlIO_stderr(),
767 "perl: warning: Falling back to the standard locale (\"C\").\n");
772 PerlIO_printf(PerlIO_stderr(),
773 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
780 #ifdef USE_LOCALE_CTYPE
781 || !(curctype || setlocale(LC_CTYPE, "C"))
782 #endif /* USE_LOCALE_CTYPE */
783 #ifdef USE_LOCALE_COLLATE
784 || !(curcoll || setlocale(LC_COLLATE, "C"))
785 #endif /* USE_LOCALE_COLLATE */
786 #ifdef USE_LOCALE_NUMERIC
787 || !(curnum || setlocale(LC_NUMERIC, "C"))
788 #endif /* USE_LOCALE_NUMERIC */
792 PerlIO_printf(PerlIO_stderr(),
793 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
797 #endif /* ! LC_ALL */
799 #ifdef USE_LOCALE_CTYPE
800 curctype = setlocale(LC_CTYPE, Nullch);
801 #endif /* USE_LOCALE_CTYPE */
802 #ifdef USE_LOCALE_COLLATE
803 curcoll = setlocale(LC_COLLATE, Nullch);
804 #endif /* USE_LOCALE_COLLATE */
805 #ifdef USE_LOCALE_NUMERIC
806 curnum = setlocale(LC_NUMERIC, Nullch);
807 #endif /* USE_LOCALE_NUMERIC */
810 #ifdef USE_LOCALE_CTYPE
811 perl_new_ctype(curctype);
812 #endif /* USE_LOCALE_CTYPE */
814 #ifdef USE_LOCALE_COLLATE
815 perl_new_collate(curcoll);
816 #endif /* USE_LOCALE_COLLATE */
818 #ifdef USE_LOCALE_NUMERIC
819 perl_new_numeric(curnum);
820 #endif /* USE_LOCALE_NUMERIC */
822 #endif /* USE_LOCALE */
827 /* Backwards compatibility. */
829 perl_init_i18nl14n(int printwarn)
831 return perl_init_i18nl10n(printwarn);
834 #ifdef USE_LOCALE_COLLATE
837 * mem_collxfrm() is a bit like strxfrm() but with two important
838 * differences. First, it handles embedded NULs. Second, it allocates
839 * a bit more memory than needed for the transformed data itself.
840 * The real transformed data begins at offset sizeof(collationix).
841 * Please see sv_collxfrm() to see how this is used.
844 mem_collxfrm(const char *s, STRLEN len, STRLEN *xlen)
847 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
849 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
850 /* the +1 is for the terminating NUL. */
852 xAlloc = sizeof(collation_ix) + collxfrm_base + (collxfrm_mult * len) + 1;
853 New(171, xbuf, xAlloc, char);
857 *(U32*)xbuf = collation_ix;
858 xout = sizeof(collation_ix);
859 for (xin = 0; xin < len; ) {
863 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
866 if (xused < xAlloc - xout)
868 xAlloc = (2 * xAlloc) + 1;
869 Renew(xbuf, xAlloc, char);
874 xin += strlen(s + xin) + 1;
877 /* Embedded NULs are understood but silently skipped
878 * because they make no sense in locale collation. */
882 *xlen = xout - sizeof(collation_ix);
891 #endif /* USE_LOCALE_COLLATE */
894 fbm_compile(SV *sv, U32 flags /* not used yet */)
896 register unsigned char *s;
897 register unsigned char *table;
899 register U32 len = SvCUR(sv);
903 sv_upgrade(sv, SVt_PVBM);
904 if (len > 255 || len == 0) /* TAIL might be on on a zero-length string. */
905 return; /* can't have offsets that big */
907 Sv_Grow(sv,len + 258);
908 table = (unsigned char*)(SvPVX(sv) + len + 1);
910 for (i = 0; i < 256; i++) {
914 while (s >= (unsigned char*)(SvPVX(sv)))
916 if (table[*s] == len)
921 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
924 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
925 for (i = 0; i < len; i++) {
926 if (freq[s[i]] < frequency) {
928 frequency = freq[s[i]];
931 BmRARE(sv) = s[rarest];
932 BmPREVIOUS(sv) = rarest;
933 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
937 fbm_instr(unsigned char *big, register unsigned char *bigend, SV *littlestr)
939 register unsigned char *s;
941 register I32 littlelen;
942 register unsigned char *little;
943 register unsigned char *table;
944 register unsigned char *olds;
945 register unsigned char *oldlittle;
947 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
949 char *l = SvPV(littlestr,len);
951 if (SvTAIL(littlestr)) { /* Can be only 0-len constant
952 substr => we can ignore SvVALID */
955 if ((s = (unsigned char*)ninstr((char*)big, (char*)bigend,
960 if (bigend > big && bigend[-1] == '\n')
961 return (char *)(bigend - 1);
963 return (char *) bigend;
967 return ninstr((char*)big,(char*)bigend, l, l + len);
970 littlelen = SvCUR(littlestr);
971 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
972 if (littlelen > bigend - big)
974 little = (unsigned char*)SvPVX(littlestr);
975 s = bigend - littlelen;
977 && bigend[-1] == '\n'
978 && s[-1] == *little && memEQ((char*)s - 1,(char*)little,littlelen))
979 return (char*)s - 1; /* how sweet it is */
980 else if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
981 return (char*)s; /* how sweet it is */
984 if (littlelen <= 2) {
985 unsigned char c1 = (unsigned char)SvPVX(littlestr)[0];
986 unsigned char c2 = (unsigned char)SvPVX(littlestr)[1];
987 /* This may do extra comparisons if littlelen == 2, but this
988 should be hidden in the noise since we do less indirection. */
992 while (s <= bigend) {
994 && (littlelen == 1 || s[1] == c2)
995 && (!SvTAIL(littlestr)
997 || s[littlelen] == '\n')) /* Automatically multiline */
1005 table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
1006 if (--littlelen >= bigend - big)
1008 s = big + littlelen;
1009 oldlittle = little = table - 2;
1013 if (tmp = table[*s]) {
1015 if (bigend - s > tmp) {
1020 if ((s += tmp) < bigend)
1026 tmp = littlelen; /* less expensive than calling strncmp() */
1029 if (*--s == *--little)
1032 s = olds + 1; /* here we pay the price for failure */
1034 if (s < bigend) /* fake up continue to outer loop */
1038 if (SvTAIL(littlestr) /* automatically multiline */
1039 && olds + 1 != bigend
1048 /* start_shift, end_shift are positive quantities which give offsets
1049 of ends of some substring of bigstr.
1050 If `last' we want the last occurence.
1051 old_posp is the way of communication between consequent calls if
1052 the next call needs to find the .
1053 The initial *old_posp should be -1.
1054 Note that we do not take into account SvTAIL, so it may give wrong
1055 positives if _ALL flag is set.
1059 screaminstr(SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1061 register unsigned char *s, *x;
1062 register unsigned char *big;
1064 register I32 previous;
1066 register unsigned char *little;
1067 register I32 stop_pos;
1068 register unsigned char *littleend;
1072 ? (pos = screamfirst[BmRARE(littlestr)]) < 0
1073 : (((pos = *old_posp), pos += screamnext[pos]) == 0))
1075 little = (unsigned char *)(SvPVX(littlestr));
1076 littleend = little + SvCUR(littlestr);
1078 /* The value of pos we can start at: */
1079 previous = BmPREVIOUS(littlestr);
1080 big = (unsigned char *)(SvPVX(bigstr));
1081 /* The value of pos we can stop at: */
1082 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1083 if (previous + start_shift > stop_pos) return Nullch;
1084 while (pos < previous + start_shift) {
1085 if (!(pos += screamnext[pos]))
1090 if (pos >= stop_pos) return Nullch;
1091 if (big[pos-previous] != first)
1093 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1099 if (s == littleend) {
1101 if (!last) return (char *)(big+pos-previous);
1104 } while ( pos += screamnext[pos] );
1105 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1106 #else /* !POINTERRIGOR */
1109 if (pos >= stop_pos) return Nullch;
1110 if (big[pos] != first)
1112 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1118 if (s == littleend) {
1120 if (!last) return (char *)(big+pos);
1123 } while ( pos += screamnext[pos] );
1124 return (last && found) ? (char *)(big+(*old_posp)) : Nullch;
1125 #endif /* POINTERRIGOR */
1129 ibcmp(char *s1, char *s2, register I32 len)
1131 register U8 *a = (U8 *)s1;
1132 register U8 *b = (U8 *)s2;
1134 if (*a != *b && *a != fold[*b])
1142 ibcmp_locale(char *s1, char *s2, register I32 len)
1144 register U8 *a = (U8 *)s1;
1145 register U8 *b = (U8 *)s2;
1147 if (*a != *b && *a != fold_locale[*b])
1154 /* copy a string to a safe spot */
1159 register char *newaddr;
1161 New(902,newaddr,strlen(sv)+1,char);
1162 (void)strcpy(newaddr,sv);
1166 /* same thing but with a known length */
1169 savepvn(char *sv, register I32 len)
1171 register char *newaddr;
1173 New(903,newaddr,len+1,char);
1174 Copy(sv,newaddr,len,char); /* might not be null terminated */
1175 newaddr[len] = '\0'; /* is now */
1179 /* the SV for form() and mess() is not kept in an arena */
1187 /* Create as PVMG now, to avoid any upgrading later */
1188 New(905, sv, 1, SV);
1189 Newz(905, any, 1, XPVMG);
1190 SvFLAGS(sv) = SVt_PVMG;
1191 SvANY(sv) = (void*)any;
1192 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1198 form(const char* pat, ...)
1209 va_start(args, pat);
1214 mess_sv = mess_alloc();
1215 sv_vsetpvfn(mess_sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1217 return SvPVX(mess_sv);
1221 mess(const char *pat, va_list *args)
1224 static char dgd[] = " during global destruction.\n";
1227 mess_sv = mess_alloc();
1229 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1230 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1235 if (curcop->cop_line)
1236 sv_catpvf(sv, " at %_ line %ld",
1237 GvSV(curcop->cop_filegv), (long)curcop->cop_line);
1238 if (GvIO(last_in_gv) && IoLINES(GvIOp(last_in_gv))) {
1239 bool line_mode = (RsSIMPLE(rs) &&
1240 SvLEN(rs) == 1 && *SvPVX(rs) == '\n');
1241 sv_catpvf(sv, ", <%s> %s %ld",
1242 last_in_gv == argvgv ? "" : GvNAME(last_in_gv),
1243 line_mode ? "line" : "chunk",
1244 (long)IoLINES(GvIOp(last_in_gv)));
1246 sv_catpv(sv, ".\n");
1254 die(const char* pat, ...)
1266 int was_in_eval = in_eval;
1272 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1273 "%p: die: curstack = %p, mainstack = %p\n",
1274 thr, curstack, mainstack));
1275 #endif /* USE_THREADS */
1278 va_start(args, pat);
1282 message = pat ? mess(pat, &args) : Nullch;
1286 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1287 "%p: die: message = %s\ndiehook = %p\n",
1288 thr, message, diehook));
1289 #endif /* USE_THREADS */
1291 /* sv_2cv might call croak() */
1292 SV *olddiehook = diehook;
1296 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1298 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1304 msg = newSVpv(message, 0);
1312 PUSHSTACK(SI_DIEHOOK);
1316 perl_call_sv((SV*)cv, G_DISCARD);
1322 restartop = die_where(message);
1324 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1325 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1326 thr, restartop, was_in_eval, top_env));
1327 #endif /* USE_THREADS */
1328 if ((!restartop && was_in_eval) || top_env->je_prev)
1335 croak(const char* pat, ...)
1339 croak(pat, va_alist)
1352 va_start(args, pat);
1356 message = mess(pat, &args);
1359 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1360 #endif /* USE_THREADS */
1362 /* sv_2cv might call croak() */
1363 SV *olddiehook = diehook;
1367 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1369 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1374 msg = newSVpv(message, 0);
1378 PUSHSTACK(SI_DIEHOOK);
1382 perl_call_sv((SV*)cv, G_DISCARD);
1388 restartop = die_where(message);
1391 PerlIO_puts(PerlIO_stderr(),message);
1392 (void)PerlIO_flush(PerlIO_stderr());
1398 warn(const char* pat,...)
1413 va_start(args, pat);
1417 message = mess(pat, &args);
1421 /* sv_2cv might call warn() */
1423 SV *oldwarnhook = warnhook;
1427 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1429 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1434 msg = newSVpv(message, 0);
1438 PUSHSTACK(SI_WARNHOOK);
1442 perl_call_sv((SV*)cv, G_DISCARD);
1448 PerlIO_puts(PerlIO_stderr(),message);
1450 DEBUG_L(*message == '!'
1451 ? (xstat(message[1]=='!'
1452 ? (message[2]=='!' ? 2 : 1)
1457 (void)PerlIO_flush(PerlIO_stderr());
1460 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1463 my_setenv(char *nam, char *val)
1465 register I32 i=setenv_getix(nam); /* where does it go? */
1467 if (environ == origenviron) { /* need we copy environment? */
1473 for (max = i; environ[max]; max++) ;
1474 New(901,tmpenv, max+2, char*);
1475 for (j=0; j<max; j++) /* copy environment */
1476 tmpenv[j] = savepv(environ[j]);
1477 tmpenv[max] = Nullch;
1478 environ = tmpenv; /* tell exec where it is now */
1481 Safefree(environ[i]);
1482 while (environ[i]) {
1483 environ[i] = environ[i+1];
1488 if (!environ[i]) { /* does not exist yet */
1489 Renew(environ, i+2, char*); /* just expand it a bit */
1490 environ[i+1] = Nullch; /* make sure it's null terminated */
1493 Safefree(environ[i]);
1494 New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1496 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1498 /* MS-DOS requires environment variable names to be in uppercase */
1499 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1500 * some utilities and applications may break because they only look
1501 * for upper case strings. (Fixed strupr() bug here.)]
1503 strcpy(environ[i],nam); strupr(environ[i]);
1504 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1508 #else /* if WIN32 */
1511 my_setenv(char *nam,char *val)
1514 #ifdef USE_WIN32_RTL_ENV
1516 register char *envstr;
1517 STRLEN namlen = strlen(nam);
1519 char *oldstr = environ[setenv_getix(nam)];
1521 /* putenv() has totally broken semantics in both the Borland
1522 * and Microsoft CRTLs. They either store the passed pointer in
1523 * the environment without making a copy, or make a copy and don't
1524 * free it. And on top of that, they dont free() old entries that
1525 * are being replaced/deleted. This means the caller must
1526 * free any old entries somehow, or we end up with a memory
1527 * leak every time my_setenv() is called. One might think
1528 * one could directly manipulate environ[], like the UNIX code
1529 * above, but direct changes to environ are not allowed when
1530 * calling putenv(), since the RTLs maintain an internal
1531 * *copy* of environ[]. Bad, bad, *bad* stink.
1542 vallen = strlen(val);
1543 New(904, envstr, namlen + vallen + 3, char);
1544 (void)sprintf(envstr,"%s=%s",nam,val);
1545 (void)PerlEnv_putenv(envstr);
1549 Safefree(envstr); /* MSVCRT leaks without this */
1552 #else /* !USE_WIN32_RTL_ENV */
1554 /* The sane way to deal with the environment.
1555 * Has these advantages over putenv() & co.:
1556 * * enables us to store a truly empty value in the
1557 * environment (like in UNIX).
1558 * * we don't have to deal with RTL globals, bugs and leaks.
1560 * Why you may want to enable USE_WIN32_RTL_ENV:
1561 * * environ[] and RTL functions will not reflect changes,
1562 * which might be an issue if extensions want to access
1563 * the env. via RTL. This cuts both ways, since RTL will
1564 * not see changes made by extensions that call the Win32
1565 * functions directly, either.
1568 SetEnvironmentVariable(nam,val);
1576 setenv_getix(char *nam)
1578 register I32 i, len = strlen(nam);
1580 for (i = 0; environ[i]; i++) {
1583 strnicmp(environ[i],nam,len) == 0
1585 strnEQ(environ[i],nam,len)
1587 && environ[i][len] == '=')
1588 break; /* strnEQ must come first to avoid */
1589 } /* potential SEGV's */
1595 #ifdef UNLINK_ALL_VERSIONS
1597 unlnk(f) /* unlink all versions of a file */
1602 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1607 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1609 my_bcopy(register char *from,register char *to,register I32 len)
1613 if (from - to >= 0) {
1621 *(--to) = *(--from);
1629 my_memset(loc,ch,len)
1642 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1656 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1658 my_memcmp(s1,s2,len)
1663 register U8 *a = (U8 *)s1;
1664 register U8 *b = (U8 *)s2;
1668 if (tmp = *a++ - *b++)
1673 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1675 #if defined(I_STDARG) || defined(I_VARARGS)
1678 #ifdef USE_CHAR_VSPRINTF
1683 vsprintf(dest, pat, args)
1690 fakebuf._ptr = dest;
1691 fakebuf._cnt = 32767;
1695 fakebuf._flag = _IOWRT|_IOSTRG;
1696 _doprnt(pat, args, &fakebuf); /* what a kludge */
1697 (void)putc('\0', &fakebuf);
1698 #ifdef USE_CHAR_VSPRINTF
1701 return 0; /* perl doesn't use return value */
1705 #endif /* HAS_VPRINTF */
1706 #endif /* I_VARARGS || I_STDARGS */
1709 #if BYTEORDER != 0x4321
1713 #if (BYTEORDER & 1) == 0
1716 result = ((s & 255) << 8) + ((s >> 8) & 255);
1728 char c[sizeof(long)];
1731 #if BYTEORDER == 0x1234
1732 u.c[0] = (l >> 24) & 255;
1733 u.c[1] = (l >> 16) & 255;
1734 u.c[2] = (l >> 8) & 255;
1738 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1739 croak("Unknown BYTEORDER\n");
1744 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1745 u.c[o & 0xf] = (l >> s) & 255;
1757 char c[sizeof(long)];
1760 #if BYTEORDER == 0x1234
1761 u.c[0] = (l >> 24) & 255;
1762 u.c[1] = (l >> 16) & 255;
1763 u.c[2] = (l >> 8) & 255;
1767 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1768 croak("Unknown BYTEORDER\n");
1775 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1776 l |= (u.c[o & 0xf] & 255) << s;
1783 #endif /* BYTEORDER != 0x4321 */
1787 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1788 * If these functions are defined,
1789 * the BYTEORDER is neither 0x1234 nor 0x4321.
1790 * However, this is not assumed.
1794 #define HTOV(name,type) \
1801 char c[sizeof(type)]; \
1805 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1806 u.c[i] = (n >> s) & 0xFF; \
1811 #define VTOH(name,type) \
1818 char c[sizeof(type)]; \
1824 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1825 n += (u.c[i] & 0xFF) << s; \
1830 #if defined(HAS_HTOVS) && !defined(htovs)
1833 #if defined(HAS_HTOVL) && !defined(htovl)
1836 #if defined(HAS_VTOHS) && !defined(vtohs)
1839 #if defined(HAS_VTOHL) && !defined(vtohl)
1843 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1844 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
1846 my_popen(char *cmd, char *mode)
1849 register I32 This, that;
1852 I32 doexec = strNE(cmd,"-");
1856 return my_syspopen(cmd,mode);
1859 This = (*mode == 'w');
1861 if (doexec && tainting) {
1863 taint_proper("Insecure %s%s", "EXEC");
1865 if (PerlProc_pipe(p) < 0)
1867 while ((pid = (doexec?vfork():fork())) < 0) {
1868 if (errno != EAGAIN) {
1869 PerlLIO_close(p[This]);
1871 croak("Can't fork");
1881 PerlLIO_close(p[THAT]);
1882 if (p[THIS] != (*mode == 'r')) {
1883 PerlLIO_dup2(p[THIS], *mode == 'r');
1884 PerlLIO_close(p[THIS]);
1887 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1893 for (fd = maxsysfd + 1; fd < NOFILE; fd++)
1896 do_exec(cmd); /* may or may not use the shell */
1900 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1901 sv_setiv(GvSV(tmpgv), (IV)getpid());
1903 hv_clear(pidstatus); /* we have no children */
1908 do_execfree(); /* free any memory malloced by child on vfork */
1909 PerlLIO_close(p[that]);
1910 if (p[that] < p[This]) {
1911 PerlLIO_dup2(p[This], p[that]);
1912 PerlLIO_close(p[This]);
1915 sv = *av_fetch(fdpid,p[This],TRUE);
1916 (void)SvUPGRADE(sv,SVt_IV);
1919 return PerlIO_fdopen(p[This], mode);
1922 #if defined(atarist) || defined(DJGPP)
1929 /* Needs work for PerlIO ! */
1930 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1931 return popen(PerlIO_exportFILE(cmd, 0), mode);
1935 #endif /* !DOSISH */
1942 struct stat tmpstatbuf;
1944 PerlIO_printf(PerlIO_stderr(),"%s", s);
1945 for (fd = 0; fd < 32; fd++) {
1946 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
1947 PerlIO_printf(PerlIO_stderr()," %d",fd);
1949 PerlIO_printf(PerlIO_stderr(),"\n");
1959 #if defined(HAS_FCNTL) && defined(F_DUPFD)
1962 PerlLIO_close(newfd);
1963 return fcntl(oldfd, F_DUPFD, newfd);
1965 #define DUP2_MAX_FDS 256
1966 int fdtmp[DUP2_MAX_FDS];
1972 PerlLIO_close(newfd);
1973 /* good enough for low fd's... */
1974 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
1975 if (fdx >= DUP2_MAX_FDS) {
1983 PerlLIO_close(fdtmp[--fdx]);
1990 #ifdef HAS_SIGACTION
1993 rsignal(int signo, Sighandler_t handler)
1995 struct sigaction act, oact;
1997 act.sa_handler = handler;
1998 sigemptyset(&act.sa_mask);
2001 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2003 if (sigaction(signo, &act, &oact) == -1)
2006 return oact.sa_handler;
2010 rsignal_state(int signo)
2012 struct sigaction oact;
2014 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2017 return oact.sa_handler;
2021 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2023 struct sigaction act;
2025 act.sa_handler = handler;
2026 sigemptyset(&act.sa_mask);
2029 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2031 return sigaction(signo, &act, save);
2035 rsignal_restore(int signo, Sigsave_t *save)
2037 return sigaction(signo, save, (struct sigaction *)NULL);
2040 #else /* !HAS_SIGACTION */
2043 rsignal(int signo, Sighandler_t handler)
2045 return PerlProc_signal(signo, handler);
2048 static int sig_trapped;
2058 rsignal_state(int signo)
2060 Sighandler_t oldsig;
2063 oldsig = PerlProc_signal(signo, sig_trap);
2064 PerlProc_signal(signo, oldsig);
2066 PerlProc_kill(getpid(), signo);
2071 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2073 *save = PerlProc_signal(signo, handler);
2074 return (*save == SIG_ERR) ? -1 : 0;
2078 rsignal_restore(int signo, Sigsave_t *save)
2080 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2083 #endif /* !HAS_SIGACTION */
2085 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2086 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
2088 my_pclose(PerlIO *ptr)
2090 Sigsave_t hstat, istat, qstat;
2098 int saved_vaxc_errno;
2101 int saved_win32_errno;
2104 svp = av_fetch(fdpid,PerlIO_fileno(ptr),TRUE);
2105 pid = (int)SvIVX(*svp);
2109 if (pid == -1) { /* Opened by popen. */
2110 return my_syspclose(ptr);
2113 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2114 saved_errno = errno;
2116 saved_vaxc_errno = vaxc$errno;
2119 saved_win32_errno = GetLastError();
2123 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2125 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2126 rsignal_save(SIGINT, SIG_IGN, &istat);
2127 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2129 pid2 = wait4pid(pid, &status, 0);
2130 } while (pid2 == -1 && errno == EINTR);
2131 rsignal_restore(SIGHUP, &hstat);
2132 rsignal_restore(SIGINT, &istat);
2133 rsignal_restore(SIGQUIT, &qstat);
2135 SETERRNO(saved_errno, saved_vaxc_errno);
2138 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2140 #endif /* !DOSISH */
2142 #if !defined(DOSISH) || defined(OS2) || defined(WIN32)
2144 wait4pid(int pid, int *statusp, int flags)
2148 char spid[TYPE_CHARS(int)];
2153 sprintf(spid, "%d", pid);
2154 svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
2155 if (svp && *svp != &sv_undef) {
2156 *statusp = SvIVX(*svp);
2157 (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2164 hv_iterinit(pidstatus);
2165 if (entry = hv_iternext(pidstatus)) {
2166 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2167 sv = hv_iterval(pidstatus,entry);
2168 *statusp = SvIVX(sv);
2169 sprintf(spid, "%d", pid);
2170 (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2175 # ifdef HAS_WAITPID_RUNTIME
2176 if (!HAS_WAITPID_RUNTIME)
2179 return waitpid(pid,statusp,flags);
2181 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2182 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2184 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2189 croak("Can't do waitpid with flags");
2191 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2192 pidgone(result,*statusp);
2200 #endif /* !DOSISH || OS2 || WIN32 */
2204 pidgone(int pid, int status)
2207 char spid[TYPE_CHARS(int)];
2209 sprintf(spid, "%d", pid);
2210 sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
2211 (void)SvUPGRADE(sv,SVt_IV);
2216 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2219 int /* Cannot prototype with I32
2228 /* Needs work for PerlIO ! */
2229 FILE *f = PerlIO_findFILE(ptr);
2230 I32 result = pclose(f);
2231 PerlIO_releaseFILE(ptr,f);
2237 repeatcpy(register char *to, register char *from, I32 len, register I32 count)
2240 register char *frombase = from;
2248 while (count-- > 0) {
2249 for (todo = len; todo > 0; todo--) {
2256 #ifndef CASTNEGFLOAT
2264 # define BIGDOUBLE 2147483648.0
2266 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2269 return (unsigned long)f;
2271 return (unsigned long)along;
2278 /* Unfortunately, on some systems the cast_uv() function doesn't
2279 work with the system-supplied definition of ULONG_MAX. The
2280 comparison (f >= ULONG_MAX) always comes out true. It must be a
2281 problem with the compiler constant folding.
2283 In any case, this workaround should be fine on any two's complement
2284 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2286 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2289 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2291 -- Kenneth Albanowski <kjahds@kjahds.com>
2295 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2303 return (I32) I32_MAX;
2305 return (I32) I32_MIN;
2325 return (UV) MY_UV_MAX;
2337 char *fa = strrchr(a,'/');
2338 char *fb = strrchr(b,'/');
2339 struct stat tmpstatbuf1;
2340 struct stat tmpstatbuf2;
2341 SV *tmpsv = sv_newmortal();
2354 sv_setpv(tmpsv, ".");
2356 sv_setpvn(tmpsv, a, fa - a);
2357 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2360 sv_setpv(tmpsv, ".");
2362 sv_setpvn(tmpsv, b, fb - b);
2363 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2365 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2366 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2368 #endif /* !HAS_RENAME */
2371 scan_oct(char *start, I32 len, I32 *retlen)
2373 register char *s = start;
2374 register UV retval = 0;
2375 bool overflowed = FALSE;
2377 while (len && *s >= '0' && *s <= '7') {
2378 register UV n = retval << 3;
2379 if (!overflowed && (n >> 3) != retval) {
2380 warn("Integer overflow in octal number");
2383 retval = n | (*s++ - '0');
2386 if (dowarn && len && (*s == '8' || *s == '9'))
2387 warn("Illegal octal digit ignored");
2388 *retlen = s - start;
2393 scan_hex(char *start, I32 len, I32 *retlen)
2395 register char *s = start;
2396 register UV retval = 0;
2397 bool overflowed = FALSE;
2400 while (len-- && *s && (tmp = strchr((char *) hexdigit, *s))) {
2401 register UV n = retval << 4;
2402 if (!overflowed && (n >> 4) != retval) {
2403 warn("Integer overflow in hex number");
2406 retval = n | ((tmp - hexdigit) & 15);
2409 if (dowarn && !tmp) {
2410 warn("Illegal hex digit ignored");
2412 *retlen = s - start;
2417 find_script(char *scriptname, bool dosearch, char **search_ext, I32 flags)
2420 char *xfound = Nullch;
2421 char *xfailed = Nullch;
2425 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2426 # define SEARCH_EXTS ".bat", ".cmd", NULL
2427 # define MAX_EXT_LEN 4
2430 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2431 # define MAX_EXT_LEN 4
2434 # define SEARCH_EXTS ".pl", ".com", NULL
2435 # define MAX_EXT_LEN 4
2437 /* additional extensions to try in each dir if scriptname not found */
2439 char *exts[] = { SEARCH_EXTS };
2440 char **ext = search_ext ? search_ext : exts;
2441 int extidx = 0, i = 0;
2442 char *curext = Nullch;
2444 # define MAX_EXT_LEN 0
2448 * If dosearch is true and if scriptname does not contain path
2449 * delimiters, search the PATH for scriptname.
2451 * If SEARCH_EXTS is also defined, will look for each
2452 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2453 * while searching the PATH.
2455 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2456 * proceeds as follows:
2457 * If DOSISH or VMSISH:
2458 * + look for ./scriptname{,.foo,.bar}
2459 * + search the PATH for scriptname{,.foo,.bar}
2462 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2463 * this will not look in '.' if it's not in the PATH)
2467 # ifdef ALWAYS_DEFTYPES
2468 len = strlen(scriptname);
2469 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2470 int hasdir, idx = 0, deftypes = 1;
2473 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2476 int hasdir, idx = 0, deftypes = 1;
2479 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2481 /* The first time through, just add SEARCH_EXTS to whatever we
2482 * already have, so we can check for default file types. */
2484 (!hasdir && my_trnlnm("DCL$PATH",tokenbuf,idx++)) )
2490 if ((strlen(tokenbuf) + strlen(scriptname)
2491 + MAX_EXT_LEN) >= sizeof tokenbuf)
2492 continue; /* don't search dir with too-long name */
2493 strcat(tokenbuf, scriptname);
2497 if (strEQ(scriptname, "-"))
2499 if (dosearch) { /* Look in '.' first. */
2500 char *cur = scriptname;
2502 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2504 if (strEQ(ext[i++],curext)) {
2505 extidx = -1; /* already has an ext */
2510 DEBUG_p(PerlIO_printf(Perl_debug_log,
2511 "Looking for %s\n",cur));
2512 if (PerlLIO_stat(cur,&statbuf) >= 0) {
2520 if (cur == scriptname) {
2521 len = strlen(scriptname);
2522 if (len+MAX_EXT_LEN+1 >= sizeof(tokenbuf))
2524 cur = strcpy(tokenbuf, scriptname);
2526 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2527 && strcpy(tokenbuf+len, ext[extidx++]));
2532 if (dosearch && !strchr(scriptname, '/')
2534 && !strchr(scriptname, '\\')
2536 && (s = PerlEnv_getenv("PATH"))) {
2539 bufend = s + strlen(s);
2540 while (s < bufend) {
2541 #if defined(atarist) || defined(DOSISH)
2546 && *s != ';'; len++, s++) {
2547 if (len < sizeof tokenbuf)
2550 if (len < sizeof tokenbuf)
2551 tokenbuf[len] = '\0';
2552 #else /* ! (atarist || DOSISH) */
2553 s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
2556 #endif /* ! (atarist || DOSISH) */
2559 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tokenbuf)
2560 continue; /* don't search dir with too-long name */
2562 #if defined(atarist) || defined(DOSISH)
2563 && tokenbuf[len - 1] != '/'
2564 && tokenbuf[len - 1] != '\\'
2567 tokenbuf[len++] = '/';
2568 if (len == 2 && tokenbuf[0] == '.')
2570 (void)strcpy(tokenbuf + len, scriptname);
2574 len = strlen(tokenbuf);
2575 if (extidx > 0) /* reset after previous loop */
2579 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tokenbuf));
2580 retval = PerlLIO_stat(tokenbuf,&statbuf);
2582 } while ( retval < 0 /* not there */
2583 && extidx>=0 && ext[extidx] /* try an extension? */
2584 && strcpy(tokenbuf+len, ext[extidx++])
2589 if (S_ISREG(statbuf.st_mode)
2590 && cando(S_IRUSR,TRUE,&statbuf)
2592 && cando(S_IXUSR,TRUE,&statbuf)
2596 xfound = tokenbuf; /* bingo! */
2600 xfailed = savepv(tokenbuf);
2603 if (!xfound && !seen_dot && !xfailed && (PerlLIO_stat(scriptname,&statbuf) < 0))
2605 seen_dot = 1; /* Disable message. */
2608 /* croak("Can't %s %s%s%s",
2609 (xfailed ? "execute" : "find"),
2610 (xfailed ? xfailed : scriptname),
2611 (xfailed ? "" : " on PATH"),
2612 (xfailed || seen_dot) ? "" : ", '.' not in PATH"); */
2615 scriptname = xfound;
2623 /* Very simplistic scheduler for now */
2627 thr = thr->i.next_run;
2638 perl_cond_signal(cp)
2642 perl_cond cond = *cp;
2647 /* Insert t in the runnable queue just ahead of us */
2648 t->i.next_run = thr->i.next_run;
2649 thr->i.next_run->i.prev_run = t;
2650 t->i.prev_run = thr;
2651 thr->i.next_run = t;
2652 thr->i.wait_queue = 0;
2653 /* Remove from the wait queue */
2659 perl_cond_broadcast(cp)
2663 perl_cond cond, cond_next;
2665 for (cond = *cp; cond; cond = cond_next) {
2667 /* Insert t in the runnable queue just ahead of us */
2668 t->i.next_run = thr->i.next_run;
2669 thr->i.next_run->i.prev_run = t;
2670 t->i.prev_run = thr;
2671 thr->i.next_run = t;
2672 thr->i.wait_queue = 0;
2673 /* Remove from the wait queue */
2674 cond_next = cond->next;
2686 if (thr->i.next_run == thr)
2687 croak("panic: perl_cond_wait called by last runnable thread");
2689 New(666, cond, 1, struct perl_wait_queue);
2693 thr->i.wait_queue = cond;
2694 /* Remove ourselves from runnable queue */
2695 thr->i.next_run->i.prev_run = thr->i.prev_run;
2696 thr->i.prev_run->i.next_run = thr->i.next_run;
2698 #endif /* FAKE_THREADS */
2700 #ifdef OLD_PTHREADS_API
2701 struct perl_thread *
2706 if (pthread_getspecific(thr_key, &t))
2707 croak("panic: pthread_getspecific");
2708 return (struct perl_thread *) t;
2710 #endif /* OLD_PTHREADS_API */
2713 condpair_magic(SV *sv)
2717 SvUPGRADE(sv, SVt_PVMG);
2718 mg = mg_find(sv, 'm');
2722 New(53, cp, 1, condpair_t);
2723 MUTEX_INIT(&cp->mutex);
2724 COND_INIT(&cp->owner_cond);
2725 COND_INIT(&cp->cond);
2728 mg = mg_find(sv, 'm');
2730 /* someone else beat us to initialising it */
2732 MUTEX_DESTROY(&cp->mutex);
2733 COND_DESTROY(&cp->owner_cond);
2734 COND_DESTROY(&cp->cond);
2738 sv_magic(sv, Nullsv, 'm', 0, 0);
2740 mg->mg_ptr = (char *)cp;
2741 mg->mg_len = sizeof(cp);
2743 DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
2744 "%p: condpair_magic %p\n", thr, sv));)
2751 * Make a new perl thread structure using t as a prototype. Some of the
2752 * fields for the new thread are copied from the prototype thread, t,
2753 * so t should not be running in perl at the time this function is
2754 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2755 * thread calling new_struct_thread) clearly satisfies this constraint.
2757 struct perl_thread *
2758 new_struct_thread(struct perl_thread *t)
2760 struct perl_thread *thr;
2765 sv = newSVpv("", 0);
2766 SvGROW(sv, sizeof(struct perl_thread) + 1);
2767 SvCUR_set(sv, sizeof(struct perl_thread));
2768 thr = (Thread) SvPVX(sv);
2770 memset(thr, 0xab, sizeof(struct perl_thread));
2782 curcop = &compiling;
2783 thr->cvcache = newHV();
2784 thr->threadsv = newAV();
2785 thr->specific = newAV();
2786 thr->errsv = newSVpv("", 0);
2787 thr->errhv = newHV();
2788 thr->flags = THRf_R_JOINABLE;
2789 MUTEX_INIT(&thr->mutex);
2791 curcop = t->Tcurcop; /* XXX As good a guess as any? */
2792 defstash = t->Tdefstash; /* XXX maybe these should */
2793 curstash = t->Tcurstash; /* always be set to main? */
2796 /* top_env needs to be non-zero. It points to an area
2797 in which longjmp() stuff is stored, as C callstack
2798 info there at least is thread specific this has to
2799 be per-thread. Otherwise a 'die' in a thread gives
2800 that thread the C stack of last thread to do an eval {}!
2801 See comments in scope.h
2802 Initialize top entry (as in perl.c for main thread)
2804 start_env.je_prev = NULL;
2805 start_env.je_ret = -1;
2806 start_env.je_mustcatch = TRUE;
2807 top_env = &start_env;
2812 tainted = t->Ttainted;
2813 curpm = t->Tcurpm; /* XXX No PMOP ref count */
2814 nrs = newSVsv(t->Tnrs);
2815 rs = newSVsv(t->Trs);
2816 last_in_gv = (GV*)SvREFCNT_inc(t->Tlast_in_gv);
2817 ofslen = t->Tofslen;
2818 ofs = savepvn(t->Tofs, ofslen);
2819 defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2820 chopset = t->Tchopset;
2821 formtarget = newSVsv(t->Tformtarget);
2822 bodytarget = newSVsv(t->Tbodytarget);
2823 toptarget = newSVsv(t->Ttoptarget);
2825 /* Initialise all per-thread SVs that the template thread used */
2826 svp = AvARRAY(t->threadsv);
2827 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
2828 if (*svp && *svp != &sv_undef) {
2829 SV *sv = newSVsv(*svp);
2830 av_store(thr->threadsv, i, sv);
2831 sv_magic(sv, 0, 0, &threadsv_names[i], 1);
2832 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
2833 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
2836 thr->threadsvp = AvARRAY(thr->threadsv);
2838 MUTEX_LOCK(&threads_mutex);
2840 thr->tid = ++threadnum;
2841 thr->next = t->next;
2844 thr->next->prev = thr;
2845 MUTEX_UNLOCK(&threads_mutex);
2847 #ifdef HAVE_THREAD_INTERN
2848 init_thread_intern(thr);
2849 #endif /* HAVE_THREAD_INTERN */
2852 #endif /* USE_THREADS */
2856 * This hack is to force load of "huge" support from libm.a
2857 * So it is in perl for (say) POSIX to use.
2858 * Needed for SunOS with Sun's 'acc' for example.
2867 #ifdef PERL_GLOBAL_STRUCT
2890 return (char*)no_modify;