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
18 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
23 # define SIG_ERR ((Sighandler_t) -1)
26 /* XXX If this causes problems, set i_unistd=undef in the hint file. */
35 /* Put this after #includes because fork and vfork prototypes may
46 # include <sys/file.h>
50 # include <sys/wait.h>
57 static void xstat _((int));
58 long xcount[MAXXCOUNT];
59 long lastxcount[MAXXCOUNT];
60 long xycount[MAXXCOUNT][MAXYCOUNT];
61 long lastxycount[MAXXCOUNT][MAXYCOUNT];
67 /* paranoid version of malloc */
69 /* NOTE: Do not call the next three routines directly. Use the macros
70 * in handy.h, so that we can easily redefine everything to do tracking of
71 * allocated hunks back to the original New to track down any memory leaks.
72 * XXX This advice seems to be widely ignored :-( --AD August 1996.
76 safemalloc(MEM_SIZE size)
81 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
84 #endif /* HAS_64K_LIMIT */
87 croak("panic: malloc");
89 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
90 #if !(defined(I286) || defined(atarist))
91 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
93 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
100 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
107 /* paranoid version of realloc */
110 saferealloc(Malloc_t where,MEM_SIZE size)
113 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
114 Malloc_t PerlMem_realloc();
115 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
119 PerlIO_printf(PerlIO_stderr(),
120 "Reallocation too large: %lx\n", size) FLUSH;
123 #endif /* HAS_64K_LIMIT */
130 return safemalloc(size);
133 croak("panic: realloc");
135 ptr = PerlMem_realloc(where,size);
137 #if !(defined(I286) || defined(atarist))
139 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,PL_an++);
140 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
144 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,PL_an++);
145 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
154 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
161 /* safe version of free */
164 safefree(Malloc_t where)
166 #if !(defined(I286) || defined(atarist))
167 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,PL_an++));
169 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,PL_an++));
177 /* safe version of calloc */
180 safecalloc(MEM_SIZE count, MEM_SIZE size)
185 if (size * count > 0xffff) {
186 PerlIO_printf(PerlIO_stderr(),
187 "Allocation too large: %lx\n", size * count) FLUSH;
190 #endif /* HAS_64K_LIMIT */
192 if ((long)size < 0 || (long)count < 0)
193 croak("panic: calloc");
196 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
197 #if !(defined(I286) || defined(atarist))
198 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
200 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
203 memset((void*)ptr, 0, size);
209 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
216 #endif /* !MYMALLOC */
220 struct mem_test_strut {
228 # define ALIGN sizeof(struct mem_test_strut)
230 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
231 # define typeof_chunk(ch) \
232 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
233 # define set_typeof_chunk(ch,t) \
234 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
235 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
238 ? ((size) - 1)/8 + 5 \
242 safexmalloc(I32 x, MEM_SIZE size)
244 register char* where = (char*)safemalloc(size + ALIGN);
247 xycount[x][SIZE_TO_Y(size)]++;
248 set_typeof_chunk(where, x);
249 sizeof_chunk(where) = size;
250 return (Malloc_t)(where + ALIGN);
254 safexrealloc(Malloc_t wh, MEM_SIZE size)
256 char *where = (char*)wh;
259 return safexmalloc(0,size);
262 MEM_SIZE old = sizeof_chunk(where - ALIGN);
263 int t = typeof_chunk(where - ALIGN);
264 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
266 xycount[t][SIZE_TO_Y(old)]--;
267 xycount[t][SIZE_TO_Y(size)]++;
268 xcount[t] += size - old;
269 sizeof_chunk(new) = size;
270 return (Malloc_t)(new + ALIGN);
275 safexfree(Malloc_t wh)
278 char *where = (char*)wh;
284 size = sizeof_chunk(where);
285 x = where[0] + 100 * where[1];
287 xycount[x][SIZE_TO_Y(size)]--;
292 safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
294 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
296 xycount[x][SIZE_TO_Y(size)]++;
297 memset((void*)(where + ALIGN), 0, size * count);
298 set_typeof_chunk(where, x);
299 sizeof_chunk(where) = size;
300 return (Malloc_t)(where + ALIGN);
306 register I32 i, j, total = 0;
307 I32 subtot[MAXYCOUNT];
309 for (j = 0; j < MAXYCOUNT; j++) {
313 PerlIO_printf(PerlIO_stderr(), " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
314 for (i = 0; i < MAXXCOUNT; i++) {
316 for (j = 0; j < MAXYCOUNT; j++) {
317 subtot[j] += xycount[i][j];
320 ? xcount[i] /* Have something */
322 ? xcount[i] != lastxcount[i] /* Changed */
323 : xcount[i] > lastxcount[i])) { /* Growed */
324 PerlIO_printf(PerlIO_stderr(),"%2d %02d %7ld ", i / 100, i % 100,
325 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
326 lastxcount[i] = xcount[i];
327 for (j = 0; j < MAXYCOUNT; j++) {
329 ? xycount[i][j] /* Have something */
331 ? xycount[i][j] != lastxycount[i][j] /* Changed */
332 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
333 PerlIO_printf(PerlIO_stderr(),"%3ld ",
335 ? xycount[i][j] - lastxycount[i][j]
337 lastxycount[i][j] = xycount[i][j];
339 PerlIO_printf(PerlIO_stderr(), " . ", xycount[i][j]);
342 PerlIO_printf(PerlIO_stderr(), "\n");
346 PerlIO_printf(PerlIO_stderr(), "Total %7ld ", total);
347 for (j = 0; j < MAXYCOUNT; j++) {
349 PerlIO_printf(PerlIO_stderr(), "%3ld ", subtot[j]);
351 PerlIO_printf(PerlIO_stderr(), " . ");
354 PerlIO_printf(PerlIO_stderr(), "\n");
358 #endif /* LEAKTEST */
360 /* copy a string up to some (non-backslashed) delimiter, if any */
363 delimcpy(register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
366 for (tolen = 0; from < fromend; from++, tolen++) {
368 if (from[1] == delim)
377 else if (*from == delim)
388 /* return ptr to little string in big string, NULL if not found */
389 /* This routine was donated by Corey Satten. */
392 instr(register char *big, register char *little)
394 register char *s, *x;
405 for (x=big,s=little; *s; /**/ ) {
419 /* same as instr but allow embedded nulls */
422 ninstr(register char *big, register char *bigend, char *little, char *lend)
424 register char *s, *x;
425 register I32 first = *little;
426 register char *littleend = lend;
428 if (!first && little >= littleend)
430 if (bigend - big < littleend - little)
432 bigend -= littleend - little++;
433 while (big <= bigend) {
436 for (x=big,s=little; s < littleend; /**/ ) {
448 /* reverse of the above--find last substring */
451 rninstr(register char *big, char *bigend, char *little, char *lend)
453 register char *bigbeg;
454 register char *s, *x;
455 register I32 first = *little;
456 register char *littleend = lend;
458 if (!first && little >= littleend)
461 big = bigend - (littleend - little++);
462 while (big >= bigbeg) {
465 for (x=big+2,s=little; s < littleend; /**/ ) {
478 * Set up for a new ctype locale.
481 perl_new_ctype(char *newctype)
483 #ifdef USE_LOCALE_CTYPE
487 for (i = 0; i < 256; i++) {
489 PL_fold_locale[i] = toLOWER_LC(i);
490 else if (isLOWER_LC(i))
491 PL_fold_locale[i] = toUPPER_LC(i);
493 PL_fold_locale[i] = i;
496 #endif /* USE_LOCALE_CTYPE */
500 * Set up for a new collation locale.
503 perl_new_collate(char *newcoll)
505 #ifdef USE_LOCALE_COLLATE
508 if (PL_collation_name) {
510 Safefree(PL_collation_name);
511 PL_collation_name = NULL;
512 PL_collation_standard = TRUE;
513 PL_collxfrm_base = 0;
514 PL_collxfrm_mult = 2;
519 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
521 Safefree(PL_collation_name);
522 PL_collation_name = savepv(newcoll);
523 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
526 /* 2: at most so many chars ('a', 'b'). */
527 /* 50: surely no system expands a char more. */
528 #define XFRMBUFSIZE (2 * 50)
529 char xbuf[XFRMBUFSIZE];
530 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
531 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
532 SSize_t mult = fb - fa;
534 croak("strxfrm() gets absurd");
535 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
536 PL_collxfrm_mult = mult;
540 #endif /* USE_LOCALE_COLLATE */
544 * Set up for a new numeric locale.
547 perl_new_numeric(char *newnum)
549 #ifdef USE_LOCALE_NUMERIC
552 if (PL_numeric_name) {
553 Safefree(PL_numeric_name);
554 PL_numeric_name = NULL;
555 PL_numeric_standard = TRUE;
556 PL_numeric_local = TRUE;
561 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
562 Safefree(PL_numeric_name);
563 PL_numeric_name = savepv(newnum);
564 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
565 PL_numeric_local = TRUE;
568 #endif /* USE_LOCALE_NUMERIC */
572 perl_set_numeric_standard(void)
574 #ifdef USE_LOCALE_NUMERIC
576 if (! PL_numeric_standard) {
577 setlocale(LC_NUMERIC, "C");
578 PL_numeric_standard = TRUE;
579 PL_numeric_local = FALSE;
582 #endif /* USE_LOCALE_NUMERIC */
586 perl_set_numeric_local(void)
588 #ifdef USE_LOCALE_NUMERIC
590 if (! PL_numeric_local) {
591 setlocale(LC_NUMERIC, PL_numeric_name);
592 PL_numeric_standard = FALSE;
593 PL_numeric_local = TRUE;
596 #endif /* USE_LOCALE_NUMERIC */
601 * Initialize locale awareness.
604 perl_init_i18nl10n(int printwarn)
608 * 1 = set ok or not applicable,
609 * 0 = fallback to C locale,
610 * -1 = fallback to C locale failed
615 #ifdef USE_LOCALE_CTYPE
616 char *curctype = NULL;
617 #endif /* USE_LOCALE_CTYPE */
618 #ifdef USE_LOCALE_COLLATE
619 char *curcoll = NULL;
620 #endif /* USE_LOCALE_COLLATE */
621 #ifdef USE_LOCALE_NUMERIC
623 #endif /* USE_LOCALE_NUMERIC */
625 char *language = PerlEnv_getenv("LANGUAGE");
627 char *lc_all = PerlEnv_getenv("LC_ALL");
628 char *lang = PerlEnv_getenv("LANG");
629 bool setlocale_failure = FALSE;
631 #ifdef LOCALE_ENVIRON_REQUIRED
634 * Ultrix setlocale(..., "") fails if there are no environment
635 * variables from which to get a locale name.
642 if (setlocale(LC_ALL, ""))
645 setlocale_failure = TRUE;
647 if (!setlocale_failure) {
648 #ifdef USE_LOCALE_CTYPE
651 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
653 setlocale_failure = TRUE;
654 #endif /* USE_LOCALE_CTYPE */
655 #ifdef USE_LOCALE_COLLATE
657 setlocale(LC_COLLATE,
658 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
660 setlocale_failure = TRUE;
661 #endif /* USE_LOCALE_COLLATE */
662 #ifdef USE_LOCALE_NUMERIC
664 setlocale(LC_NUMERIC,
665 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
667 setlocale_failure = TRUE;
668 #endif /* USE_LOCALE_NUMERIC */
673 #endif /* !LOCALE_ENVIRON_REQUIRED */
676 if (! setlocale(LC_ALL, ""))
677 setlocale_failure = TRUE;
680 if (!setlocale_failure) {
681 #ifdef USE_LOCALE_CTYPE
682 if (! (curctype = setlocale(LC_CTYPE, "")))
683 setlocale_failure = TRUE;
684 #endif /* USE_LOCALE_CTYPE */
685 #ifdef USE_LOCALE_COLLATE
686 if (! (curcoll = setlocale(LC_COLLATE, "")))
687 setlocale_failure = TRUE;
688 #endif /* USE_LOCALE_COLLATE */
689 #ifdef USE_LOCALE_NUMERIC
690 if (! (curnum = setlocale(LC_NUMERIC, "")))
691 setlocale_failure = TRUE;
692 #endif /* USE_LOCALE_NUMERIC */
695 if (setlocale_failure) {
697 bool locwarn = (printwarn > 1 ||
699 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
704 PerlIO_printf(PerlIO_stderr(),
705 "perl: warning: Setting locale failed.\n");
709 PerlIO_printf(PerlIO_stderr(),
710 "perl: warning: Setting locale failed for the categories:\n\t");
711 #ifdef USE_LOCALE_CTYPE
713 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
714 #endif /* USE_LOCALE_CTYPE */
715 #ifdef USE_LOCALE_COLLATE
717 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
718 #endif /* USE_LOCALE_COLLATE */
719 #ifdef USE_LOCALE_NUMERIC
721 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
722 #endif /* USE_LOCALE_NUMERIC */
723 PerlIO_printf(PerlIO_stderr(), "\n");
727 PerlIO_printf(PerlIO_stderr(),
728 "perl: warning: Please check that your locale settings:\n");
731 PerlIO_printf(PerlIO_stderr(),
732 "\tLANGUAGE = %c%s%c,\n",
733 language ? '"' : '(',
734 language ? language : "unset",
735 language ? '"' : ')');
738 PerlIO_printf(PerlIO_stderr(),
739 "\tLC_ALL = %c%s%c,\n",
741 lc_all ? lc_all : "unset",
746 for (e = environ; *e; e++) {
747 if (strnEQ(*e, "LC_", 3)
748 && strnNE(*e, "LC_ALL=", 7)
749 && (p = strchr(*e, '=')))
750 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
751 (int)(p - *e), *e, p + 1);
755 PerlIO_printf(PerlIO_stderr(),
758 lang ? lang : "unset",
761 PerlIO_printf(PerlIO_stderr(),
762 " are supported and installed on your system.\n");
767 if (setlocale(LC_ALL, "C")) {
769 PerlIO_printf(PerlIO_stderr(),
770 "perl: warning: Falling back to the standard locale (\"C\").\n");
775 PerlIO_printf(PerlIO_stderr(),
776 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
783 #ifdef USE_LOCALE_CTYPE
784 || !(curctype || setlocale(LC_CTYPE, "C"))
785 #endif /* USE_LOCALE_CTYPE */
786 #ifdef USE_LOCALE_COLLATE
787 || !(curcoll || setlocale(LC_COLLATE, "C"))
788 #endif /* USE_LOCALE_COLLATE */
789 #ifdef USE_LOCALE_NUMERIC
790 || !(curnum || setlocale(LC_NUMERIC, "C"))
791 #endif /* USE_LOCALE_NUMERIC */
795 PerlIO_printf(PerlIO_stderr(),
796 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
800 #endif /* ! LC_ALL */
802 #ifdef USE_LOCALE_CTYPE
803 curctype = setlocale(LC_CTYPE, Nullch);
804 #endif /* USE_LOCALE_CTYPE */
805 #ifdef USE_LOCALE_COLLATE
806 curcoll = setlocale(LC_COLLATE, Nullch);
807 #endif /* USE_LOCALE_COLLATE */
808 #ifdef USE_LOCALE_NUMERIC
809 curnum = setlocale(LC_NUMERIC, Nullch);
810 #endif /* USE_LOCALE_NUMERIC */
813 #ifdef USE_LOCALE_CTYPE
814 perl_new_ctype(curctype);
815 #endif /* USE_LOCALE_CTYPE */
817 #ifdef USE_LOCALE_COLLATE
818 perl_new_collate(curcoll);
819 #endif /* USE_LOCALE_COLLATE */
821 #ifdef USE_LOCALE_NUMERIC
822 perl_new_numeric(curnum);
823 #endif /* USE_LOCALE_NUMERIC */
825 #endif /* USE_LOCALE */
830 /* Backwards compatibility. */
832 perl_init_i18nl14n(int printwarn)
834 return perl_init_i18nl10n(printwarn);
837 #ifdef USE_LOCALE_COLLATE
840 * mem_collxfrm() is a bit like strxfrm() but with two important
841 * differences. First, it handles embedded NULs. Second, it allocates
842 * a bit more memory than needed for the transformed data itself.
843 * The real transformed data begins at offset sizeof(collationix).
844 * Please see sv_collxfrm() to see how this is used.
847 mem_collxfrm(const char *s, STRLEN len, STRLEN *xlen)
850 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
852 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
853 /* the +1 is for the terminating NUL. */
855 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
856 New(171, xbuf, xAlloc, char);
860 *(U32*)xbuf = PL_collation_ix;
861 xout = sizeof(PL_collation_ix);
862 for (xin = 0; xin < len; ) {
866 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
869 if (xused < xAlloc - xout)
871 xAlloc = (2 * xAlloc) + 1;
872 Renew(xbuf, xAlloc, char);
877 xin += strlen(s + xin) + 1;
880 /* Embedded NULs are understood but silently skipped
881 * because they make no sense in locale collation. */
885 *xlen = xout - sizeof(PL_collation_ix);
894 #endif /* USE_LOCALE_COLLATE */
897 fbm_compile(SV *sv, U32 flags /* not used yet */)
906 s = (U8*)SvPV_force(sv, len);
907 (void)SvUPGRADE(sv, SVt_PVBM);
908 if (len > 255 || len == 0) /* TAIL might be on on a zero-length string. */
909 return; /* can't have offsets that big */
911 Sv_Grow(sv,len + 258);
912 table = (unsigned char*)(SvPVX(sv) + len + 1);
914 for (i = 0; i < 256; i++) {
918 while (s >= (unsigned char*)(SvPVX(sv)))
920 if (table[*s] == len)
925 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
928 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
929 for (i = 0; i < len; i++) {
930 if (PL_freq[s[i]] < frequency) {
932 frequency = PL_freq[s[i]];
935 BmRARE(sv) = s[rarest];
936 BmPREVIOUS(sv) = rarest;
937 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
941 fbm_instr(unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
943 register unsigned char *s;
945 register I32 littlelen;
946 register unsigned char *little;
947 register unsigned char *table;
948 register unsigned char *olds;
949 register unsigned char *oldlittle;
951 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
953 char *l = SvPV(littlestr,len);
955 if (SvTAIL(littlestr)) { /* Can be only 0-len constant
956 substr => we can ignore SvVALID */
959 if ((s = (unsigned char*)ninstr((char*)big, (char*)bigend,
964 if (bigend > big && bigend[-1] == '\n')
965 return (char *)(bigend - 1);
967 return (char *) bigend;
971 return ninstr((char*)big,(char*)bigend, l, l + len);
974 littlelen = SvCUR(littlestr);
975 if (SvTAIL(littlestr) && !PL_multiline) { /* tail anchored? */
976 if (littlelen > bigend - big)
978 little = (unsigned char*)SvPVX(littlestr);
979 s = bigend - littlelen;
981 && bigend[-1] == '\n'
982 && s[-1] == *little && memEQ((char*)s - 1,(char*)little,littlelen))
983 return (char*)s - 1; /* how sweet it is */
984 else if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
985 return (char*)s; /* how sweet it is */
988 if (littlelen <= 2) {
989 unsigned char c1 = (unsigned char)SvPVX(littlestr)[0];
990 unsigned char c2 = (unsigned char)SvPVX(littlestr)[1];
991 /* This may do extra comparisons if littlelen == 2, but this
992 should be hidden in the noise since we do less indirection. */
996 while (s <= bigend) {
998 && (littlelen == 1 || s[1] == c2)
999 && (!SvTAIL(littlestr)
1001 || s[littlelen] == '\n')) /* Automatically multiline */
1009 table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
1010 if (--littlelen >= bigend - big)
1012 s = big + littlelen;
1013 oldlittle = little = table - 2;
1017 if (tmp = table[*s]) {
1019 if (bigend - s > tmp) {
1024 if ((s += tmp) < bigend)
1030 tmp = littlelen; /* less expensive than calling strncmp() */
1033 if (*--s == *--little)
1036 s = olds + 1; /* here we pay the price for failure */
1038 if (s < bigend) /* fake up continue to outer loop */
1042 if (SvTAIL(littlestr) /* automatically multiline */
1043 && olds + 1 != bigend
1052 /* start_shift, end_shift are positive quantities which give offsets
1053 of ends of some substring of bigstr.
1054 If `last' we want the last occurence.
1055 old_posp is the way of communication between consequent calls if
1056 the next call needs to find the .
1057 The initial *old_posp should be -1.
1058 Note that we do not take into account SvTAIL, so it may give wrong
1059 positives if _ALL flag is set.
1063 screaminstr(SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1066 register unsigned char *s, *x;
1067 register unsigned char *big;
1069 register I32 previous;
1071 register unsigned char *little;
1072 register I32 stop_pos;
1073 register unsigned char *littleend;
1077 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1078 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0))
1080 little = (unsigned char *)(SvPVX(littlestr));
1081 littleend = little + SvCUR(littlestr);
1083 /* The value of pos we can start at: */
1084 previous = BmPREVIOUS(littlestr);
1085 big = (unsigned char *)(SvPVX(bigstr));
1086 /* The value of pos we can stop at: */
1087 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1088 if (previous + start_shift > stop_pos) return Nullch;
1089 while (pos < previous + start_shift) {
1090 if (!(pos += PL_screamnext[pos]))
1095 if (pos >= stop_pos) break;
1096 if (big[pos-previous] != first)
1098 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1104 if (s == littleend) {
1106 if (!last) return (char *)(big+pos-previous);
1109 } while ( pos += PL_screamnext[pos] );
1110 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1111 #else /* !POINTERRIGOR */
1114 if (pos >= stop_pos) break;
1115 if (big[pos] != first)
1117 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1123 if (s == littleend) {
1125 if (!last) return (char *)(big+pos);
1128 } while ( pos += PL_screamnext[pos] );
1129 return (last && found) ? (char *)(big+(*old_posp)) : Nullch;
1130 #endif /* POINTERRIGOR */
1134 ibcmp(char *s1, char *s2, register I32 len)
1136 register U8 *a = (U8 *)s1;
1137 register U8 *b = (U8 *)s2;
1139 if (*a != *b && *a != PL_fold[*b])
1147 ibcmp_locale(char *s1, char *s2, register I32 len)
1149 register U8 *a = (U8 *)s1;
1150 register U8 *b = (U8 *)s2;
1152 if (*a != *b && *a != PL_fold_locale[*b])
1159 /* copy a string to a safe spot */
1164 register char *newaddr;
1166 New(902,newaddr,strlen(sv)+1,char);
1167 (void)strcpy(newaddr,sv);
1171 /* same thing but with a known length */
1174 savepvn(char *sv, register I32 len)
1176 register char *newaddr;
1178 New(903,newaddr,len+1,char);
1179 Copy(sv,newaddr,len,char); /* might not be null terminated */
1180 newaddr[len] = '\0'; /* is now */
1184 /* the SV for form() and mess() is not kept in an arena */
1194 return sv_2mortal(newSVpvn("",0));
1199 /* Create as PVMG now, to avoid any upgrading later */
1200 New(905, sv, 1, SV);
1201 Newz(905, any, 1, XPVMG);
1202 SvFLAGS(sv) = SVt_PVMG;
1203 SvANY(sv) = (void*)any;
1204 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1210 form(const char* pat, ...)
1212 SV *sv = mess_alloc();
1214 va_start(args, pat);
1215 sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1221 mess(const char *pat, va_list *args)
1223 SV *sv = mess_alloc();
1224 static char dgd[] = " during global destruction.\n";
1226 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1227 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1232 if (PL_curcop->cop_line)
1233 sv_catpvf(sv, " at %_ line %ld",
1234 GvSV(PL_curcop->cop_filegv), (long)PL_curcop->cop_line);
1235 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1236 bool line_mode = (RsSIMPLE(PL_rs) &&
1237 SvLEN(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1238 sv_catpvf(sv, ", <%s> %s %ld",
1239 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1240 line_mode ? "line" : "chunk",
1241 (long)IoLINES(GvIOp(PL_last_in_gv)));
1243 sv_catpv(sv, ".\n");
1250 die(const char* pat, ...)
1255 int was_in_eval = PL_in_eval;
1260 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1261 "%p: die: curstack = %p, mainstack = %p\n",
1262 thr, PL_curstack, PL_mainstack));
1264 va_start(args, pat);
1265 message = pat ? mess(pat, &args) : Nullch;
1268 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1269 "%p: die: message = %s\ndiehook = %p\n",
1270 thr, message, PL_diehook));
1272 /* sv_2cv might call croak() */
1273 SV *olddiehook = PL_diehook;
1275 SAVESPTR(PL_diehook);
1276 PL_diehook = Nullsv;
1277 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1279 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1285 msg = newSVpv(message, 0);
1293 PUSHSTACKi(PERLSI_DIEHOOK);
1297 perl_call_sv((SV*)cv, G_DISCARD);
1303 PL_restartop = die_where(message);
1304 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1305 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1306 thr, PL_restartop, was_in_eval, PL_top_env));
1307 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1309 return PL_restartop;
1313 croak(const char* pat, ...)
1322 va_start(args, pat);
1323 message = mess(pat, &args);
1325 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1327 /* sv_2cv might call croak() */
1328 SV *olddiehook = PL_diehook;
1330 SAVESPTR(PL_diehook);
1331 PL_diehook = Nullsv;
1332 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1334 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1339 msg = newSVpv(message, 0);
1343 PUSHSTACKi(PERLSI_DIEHOOK);
1347 perl_call_sv((SV*)cv, G_DISCARD);
1353 PL_restartop = die_where(message);
1356 PerlIO_puts(PerlIO_stderr(),message);
1357 (void)PerlIO_flush(PerlIO_stderr());
1362 warn(const char* pat,...)
1370 va_start(args, pat);
1371 message = mess(pat, &args);
1375 /* sv_2cv might call warn() */
1377 SV *oldwarnhook = PL_warnhook;
1379 SAVESPTR(PL_warnhook);
1380 PL_warnhook = Nullsv;
1381 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1383 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1388 msg = newSVpv(message, 0);
1392 PUSHSTACKi(PERLSI_WARNHOOK);
1396 perl_call_sv((SV*)cv, G_DISCARD);
1402 PerlIO_puts(PerlIO_stderr(),message);
1404 DEBUG_L(*message == '!'
1405 ? (xstat(message[1]=='!'
1406 ? (message[2]=='!' ? 2 : 1)
1411 (void)PerlIO_flush(PerlIO_stderr());
1415 warner(U32 err, const char* pat,...)
1424 va_start(args, pat);
1425 message = mess(pat, &args);
1430 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1431 #endif /* USE_THREADS */
1433 /* sv_2cv might call croak() */
1434 SV *olddiehook = PL_diehook;
1436 SAVESPTR(PL_diehook);
1437 PL_diehook = Nullsv;
1438 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1440 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1445 msg = newSVpv(message, 0);
1452 perl_call_sv((SV*)cv, G_DISCARD);
1458 PL_restartop = die_where(message);
1461 PerlIO_puts(PerlIO_stderr(),message);
1462 (void)PerlIO_flush(PerlIO_stderr());
1468 /* sv_2cv might call warn() */
1470 SV *oldwarnhook = PL_warnhook;
1472 SAVESPTR(PL_warnhook);
1473 PL_warnhook = Nullsv;
1474 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1476 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1481 msg = newSVpv(message, 0);
1488 perl_call_sv((SV*)cv, G_DISCARD);
1494 PerlIO_puts(PerlIO_stderr(),message);
1498 (void)PerlIO_flush(PerlIO_stderr());
1502 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1505 my_setenv(char *nam, char *val)
1507 register I32 i=setenv_getix(nam); /* where does it go? */
1509 if (environ == PL_origenviron) { /* need we copy environment? */
1515 for (max = i; environ[max]; max++) ;
1516 New(901,tmpenv, max+2, char*);
1517 for (j=0; j<max; j++) /* copy environment */
1518 tmpenv[j] = savepv(environ[j]);
1519 tmpenv[max] = Nullch;
1520 environ = tmpenv; /* tell exec where it is now */
1523 Safefree(environ[i]);
1524 while (environ[i]) {
1525 environ[i] = environ[i+1];
1530 if (!environ[i]) { /* does not exist yet */
1531 Renew(environ, i+2, char*); /* just expand it a bit */
1532 environ[i+1] = Nullch; /* make sure it's null terminated */
1535 Safefree(environ[i]);
1536 New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1538 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1540 /* MS-DOS requires environment variable names to be in uppercase */
1541 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1542 * some utilities and applications may break because they only look
1543 * for upper case strings. (Fixed strupr() bug here.)]
1545 strcpy(environ[i],nam); strupr(environ[i]);
1546 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1550 #else /* if WIN32 */
1553 my_setenv(char *nam,char *val)
1556 #ifdef USE_WIN32_RTL_ENV
1558 register char *envstr;
1559 STRLEN namlen = strlen(nam);
1561 char *oldstr = environ[setenv_getix(nam)];
1563 /* putenv() has totally broken semantics in both the Borland
1564 * and Microsoft CRTLs. They either store the passed pointer in
1565 * the environment without making a copy, or make a copy and don't
1566 * free it. And on top of that, they dont free() old entries that
1567 * are being replaced/deleted. This means the caller must
1568 * free any old entries somehow, or we end up with a memory
1569 * leak every time my_setenv() is called. One might think
1570 * one could directly manipulate environ[], like the UNIX code
1571 * above, but direct changes to environ are not allowed when
1572 * calling putenv(), since the RTLs maintain an internal
1573 * *copy* of environ[]. Bad, bad, *bad* stink.
1584 vallen = strlen(val);
1585 New(904, envstr, namlen + vallen + 3, char);
1586 (void)sprintf(envstr,"%s=%s",nam,val);
1587 (void)PerlEnv_putenv(envstr);
1591 Safefree(envstr); /* MSVCRT leaks without this */
1594 #else /* !USE_WIN32_RTL_ENV */
1596 /* The sane way to deal with the environment.
1597 * Has these advantages over putenv() & co.:
1598 * * enables us to store a truly empty value in the
1599 * environment (like in UNIX).
1600 * * we don't have to deal with RTL globals, bugs and leaks.
1602 * Why you may want to enable USE_WIN32_RTL_ENV:
1603 * * environ[] and RTL functions will not reflect changes,
1604 * which might be an issue if extensions want to access
1605 * the env. via RTL. This cuts both ways, since RTL will
1606 * not see changes made by extensions that call the Win32
1607 * functions directly, either.
1610 SetEnvironmentVariable(nam,val);
1618 setenv_getix(char *nam)
1620 register I32 i, len = strlen(nam);
1622 for (i = 0; environ[i]; i++) {
1625 strnicmp(environ[i],nam,len) == 0
1627 strnEQ(environ[i],nam,len)
1629 && environ[i][len] == '=')
1630 break; /* strnEQ must come first to avoid */
1631 } /* potential SEGV's */
1637 #ifdef UNLINK_ALL_VERSIONS
1639 unlnk(f) /* unlink all versions of a file */
1644 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1649 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1651 my_bcopy(register char *from,register char *to,register I32 len)
1655 if (from - to >= 0) {
1663 *(--to) = *(--from);
1671 my_memset(loc,ch,len)
1684 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1698 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1700 my_memcmp(s1,s2,len)
1705 register U8 *a = (U8 *)s1;
1706 register U8 *b = (U8 *)s2;
1710 if (tmp = *a++ - *b++)
1715 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1719 #ifdef USE_CHAR_VSPRINTF
1724 vsprintf(dest, pat, args)
1731 fakebuf._ptr = dest;
1732 fakebuf._cnt = 32767;
1736 fakebuf._flag = _IOWRT|_IOSTRG;
1737 _doprnt(pat, args, &fakebuf); /* what a kludge */
1738 (void)putc('\0', &fakebuf);
1739 #ifdef USE_CHAR_VSPRINTF
1742 return 0; /* perl doesn't use return value */
1746 #endif /* HAS_VPRINTF */
1749 #if BYTEORDER != 0x4321
1753 #if (BYTEORDER & 1) == 0
1756 result = ((s & 255) << 8) + ((s >> 8) & 255);
1768 char c[sizeof(long)];
1771 #if BYTEORDER == 0x1234
1772 u.c[0] = (l >> 24) & 255;
1773 u.c[1] = (l >> 16) & 255;
1774 u.c[2] = (l >> 8) & 255;
1778 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1779 croak("Unknown BYTEORDER\n");
1784 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1785 u.c[o & 0xf] = (l >> s) & 255;
1797 char c[sizeof(long)];
1800 #if BYTEORDER == 0x1234
1801 u.c[0] = (l >> 24) & 255;
1802 u.c[1] = (l >> 16) & 255;
1803 u.c[2] = (l >> 8) & 255;
1807 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1808 croak("Unknown BYTEORDER\n");
1815 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1816 l |= (u.c[o & 0xf] & 255) << s;
1823 #endif /* BYTEORDER != 0x4321 */
1827 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1828 * If these functions are defined,
1829 * the BYTEORDER is neither 0x1234 nor 0x4321.
1830 * However, this is not assumed.
1834 #define HTOV(name,type) \
1841 char c[sizeof(type)]; \
1845 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1846 u.c[i] = (n >> s) & 0xFF; \
1851 #define VTOH(name,type) \
1858 char c[sizeof(type)]; \
1864 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1865 n += (u.c[i] & 0xFF) << s; \
1870 #if defined(HAS_HTOVS) && !defined(htovs)
1873 #if defined(HAS_HTOVL) && !defined(htovl)
1876 #if defined(HAS_VTOHS) && !defined(vtohs)
1879 #if defined(HAS_VTOHL) && !defined(vtohl)
1883 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1884 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
1886 my_popen(char *cmd, char *mode)
1889 register I32 This, that;
1892 I32 doexec = strNE(cmd,"-");
1896 return my_syspopen(cmd,mode);
1899 This = (*mode == 'w');
1901 if (doexec && PL_tainting) {
1903 taint_proper("Insecure %s%s", "EXEC");
1905 if (PerlProc_pipe(p) < 0)
1907 while ((pid = (doexec?vfork():fork())) < 0) {
1908 if (errno != EAGAIN) {
1909 PerlLIO_close(p[This]);
1911 croak("Can't fork");
1923 PerlLIO_close(p[THAT]);
1924 if (p[THIS] != (*mode == 'r')) {
1925 PerlLIO_dup2(p[THIS], *mode == 'r');
1926 PerlLIO_close(p[THIS]);
1929 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1935 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
1938 do_exec(cmd); /* may or may not use the shell */
1942 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1943 sv_setiv(GvSV(tmpgv), (IV)getpid());
1945 hv_clear(PL_pidstatus); /* we have no children */
1950 do_execfree(); /* free any memory malloced by child on vfork */
1951 PerlLIO_close(p[that]);
1952 if (p[that] < p[This]) {
1953 PerlLIO_dup2(p[This], p[that]);
1954 PerlLIO_close(p[This]);
1957 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1958 (void)SvUPGRADE(sv,SVt_IV);
1960 PL_forkprocess = pid;
1961 return PerlIO_fdopen(p[This], mode);
1964 #if defined(atarist) || defined(DJGPP)
1971 /* Needs work for PerlIO ! */
1972 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1973 return popen(PerlIO_exportFILE(cmd, 0), mode);
1977 #endif /* !DOSISH */
1984 struct stat tmpstatbuf;
1986 PerlIO_printf(PerlIO_stderr(),"%s", s);
1987 for (fd = 0; fd < 32; fd++) {
1988 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
1989 PerlIO_printf(PerlIO_stderr()," %d",fd);
1991 PerlIO_printf(PerlIO_stderr(),"\n");
1993 #endif /* DUMP_FDS */
2001 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2004 PerlLIO_close(newfd);
2005 return fcntl(oldfd, F_DUPFD, newfd);
2007 #define DUP2_MAX_FDS 256
2008 int fdtmp[DUP2_MAX_FDS];
2014 PerlLIO_close(newfd);
2015 /* good enough for low fd's... */
2016 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2017 if (fdx >= DUP2_MAX_FDS) {
2025 PerlLIO_close(fdtmp[--fdx]);
2032 #ifdef HAS_SIGACTION
2035 rsignal(int signo, Sighandler_t handler)
2037 struct sigaction act, oact;
2039 act.sa_handler = handler;
2040 sigemptyset(&act.sa_mask);
2043 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2046 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2047 act.sa_flags |= SA_NOCLDWAIT;
2049 if (sigaction(signo, &act, &oact) == -1)
2052 return oact.sa_handler;
2056 rsignal_state(int signo)
2058 struct sigaction oact;
2060 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2063 return oact.sa_handler;
2067 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2069 struct sigaction act;
2071 act.sa_handler = handler;
2072 sigemptyset(&act.sa_mask);
2075 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2078 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2079 act.sa_flags |= SA_NOCLDWAIT;
2081 return sigaction(signo, &act, save);
2085 rsignal_restore(int signo, Sigsave_t *save)
2087 return sigaction(signo, save, (struct sigaction *)NULL);
2090 #else /* !HAS_SIGACTION */
2093 rsignal(int signo, Sighandler_t handler)
2095 return PerlProc_signal(signo, handler);
2098 static int sig_trapped;
2108 rsignal_state(int signo)
2110 Sighandler_t oldsig;
2113 oldsig = PerlProc_signal(signo, sig_trap);
2114 PerlProc_signal(signo, oldsig);
2116 PerlProc_kill(getpid(), signo);
2121 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2123 *save = PerlProc_signal(signo, handler);
2124 return (*save == SIG_ERR) ? -1 : 0;
2128 rsignal_restore(int signo, Sigsave_t *save)
2130 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2133 #endif /* !HAS_SIGACTION */
2135 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2136 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
2138 my_pclose(PerlIO *ptr)
2140 Sigsave_t hstat, istat, qstat;
2148 int saved_vaxc_errno;
2151 int saved_win32_errno;
2154 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2155 pid = (int)SvIVX(*svp);
2157 *svp = &PL_sv_undef;
2159 if (pid == -1) { /* Opened by popen. */
2160 return my_syspclose(ptr);
2163 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2164 saved_errno = errno;
2166 saved_vaxc_errno = vaxc$errno;
2169 saved_win32_errno = GetLastError();
2173 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2175 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2176 rsignal_save(SIGINT, SIG_IGN, &istat);
2177 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2179 pid2 = wait4pid(pid, &status, 0);
2180 } while (pid2 == -1 && errno == EINTR);
2181 rsignal_restore(SIGHUP, &hstat);
2182 rsignal_restore(SIGINT, &istat);
2183 rsignal_restore(SIGQUIT, &qstat);
2185 SETERRNO(saved_errno, saved_vaxc_errno);
2188 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2190 #endif /* !DOSISH */
2192 #if !defined(DOSISH) || defined(OS2) || defined(WIN32)
2194 wait4pid(int pid, int *statusp, int flags)
2198 char spid[TYPE_CHARS(int)];
2203 sprintf(spid, "%d", pid);
2204 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2205 if (svp && *svp != &PL_sv_undef) {
2206 *statusp = SvIVX(*svp);
2207 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2214 hv_iterinit(PL_pidstatus);
2215 if (entry = hv_iternext(PL_pidstatus)) {
2216 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2217 sv = hv_iterval(PL_pidstatus,entry);
2218 *statusp = SvIVX(sv);
2219 sprintf(spid, "%d", pid);
2220 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2225 # ifdef HAS_WAITPID_RUNTIME
2226 if (!HAS_WAITPID_RUNTIME)
2229 return PerlProc_waitpid(pid,statusp,flags);
2231 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2232 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2234 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2239 croak("Can't do waitpid with flags");
2241 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2242 pidgone(result,*statusp);
2250 #endif /* !DOSISH || OS2 || WIN32 */
2254 pidgone(int pid, int status)
2257 char spid[TYPE_CHARS(int)];
2259 sprintf(spid, "%d", pid);
2260 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2261 (void)SvUPGRADE(sv,SVt_IV);
2266 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2269 int /* Cannot prototype with I32
2278 /* Needs work for PerlIO ! */
2279 FILE *f = PerlIO_findFILE(ptr);
2280 I32 result = pclose(f);
2281 PerlIO_releaseFILE(ptr,f);
2287 repeatcpy(register char *to, register char *from, I32 len, register I32 count)
2290 register char *frombase = from;
2293 register char c = *from;
2298 while (count-- > 0) {
2299 for (todo = len; todo > 0; todo--) {
2307 cast_ulong(double f)
2312 # define BIGDOUBLE 2147483648.0
2314 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2317 return (unsigned long)f;
2319 return (unsigned long)along;
2323 /* Unfortunately, on some systems the cast_uv() function doesn't
2324 work with the system-supplied definition of ULONG_MAX. The
2325 comparison (f >= ULONG_MAX) always comes out true. It must be a
2326 problem with the compiler constant folding.
2328 In any case, this workaround should be fine on any two's complement
2329 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2331 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2334 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2336 -- Kenneth Albanowski <kjahds@kjahds.com>
2340 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2347 return (I32) I32_MAX;
2349 return (I32) I32_MIN;
2367 return (UV) MY_UV_MAX;
2373 same_dirent(char *a, char *b)
2375 char *fa = strrchr(a,'/');
2376 char *fb = strrchr(b,'/');
2377 struct stat tmpstatbuf1;
2378 struct stat tmpstatbuf2;
2379 SV *tmpsv = sv_newmortal();
2392 sv_setpv(tmpsv, ".");
2394 sv_setpvn(tmpsv, a, fa - a);
2395 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2398 sv_setpv(tmpsv, ".");
2400 sv_setpvn(tmpsv, b, fb - b);
2401 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2403 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2404 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2406 #endif /* !HAS_RENAME */
2409 scan_bin(char *start, I32 len, I32 *retlen)
2411 register char *s = start;
2412 register UV retval = 0;
2413 bool overflowed = FALSE;
2414 while (len && *s >= '0' && *s <= '1') {
2415 register UV n = retval << 1;
2416 if (!overflowed && (n >> 1) != retval) {
2417 warn("Integer overflow in binary number");
2420 retval = n | (*s++ - '0');
2423 if (len && (*s >= '2' || *s <= '9')) {
2425 if (ckWARN(WARN_UNSAFE))
2426 warner(WARN_UNSAFE, "Illegal binary digit ignored");
2428 *retlen = s - start;
2432 scan_oct(char *start, I32 len, I32 *retlen)
2434 register char *s = start;
2435 register UV retval = 0;
2436 bool overflowed = FALSE;
2438 while (len && *s >= '0' && *s <= '7') {
2439 register UV n = retval << 3;
2440 if (!overflowed && (n >> 3) != retval) {
2441 warn("Integer overflow in octal number");
2444 retval = n | (*s++ - '0');
2447 if (len && (*s == '8' || *s == '9')) {
2449 if (ckWARN(WARN_OCTAL))
2450 warner(WARN_OCTAL, "Illegal octal digit ignored");
2452 *retlen = s - start;
2457 scan_hex(char *start, I32 len, I32 *retlen)
2459 register char *s = start;
2460 register UV retval = 0;
2461 bool overflowed = FALSE;
2465 while (len-- && *s) {
2466 tmp = strchr((char *) PL_hexdigit, *s++);
2468 if (*(s-1) == '_' || (*(s-1) == 'x' && retval == 0))
2473 if (ckWARN(WARN_UNSAFE))
2474 warner(WARN_UNSAFE,"Illegal hex digit ignored");
2479 if (!overflowed && (n >> 4) != retval) {
2480 warn("Integer overflow in hex number");
2483 retval = n | ((tmp - PL_hexdigit) & 15);
2485 *retlen = s - start;
2490 find_script(char *scriptname, bool dosearch, char **search_ext, I32 flags)
2493 char *xfound = Nullch;
2494 char *xfailed = Nullch;
2495 char tmpbuf[MAXPATHLEN];
2499 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2500 # define SEARCH_EXTS ".bat", ".cmd", NULL
2501 # define MAX_EXT_LEN 4
2504 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2505 # define MAX_EXT_LEN 4
2508 # define SEARCH_EXTS ".pl", ".com", NULL
2509 # define MAX_EXT_LEN 4
2511 /* additional extensions to try in each dir if scriptname not found */
2513 char *exts[] = { SEARCH_EXTS };
2514 char **ext = search_ext ? search_ext : exts;
2515 int extidx = 0, i = 0;
2516 char *curext = Nullch;
2518 # define MAX_EXT_LEN 0
2522 * If dosearch is true and if scriptname does not contain path
2523 * delimiters, search the PATH for scriptname.
2525 * If SEARCH_EXTS is also defined, will look for each
2526 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2527 * while searching the PATH.
2529 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2530 * proceeds as follows:
2531 * If DOSISH or VMSISH:
2532 * + look for ./scriptname{,.foo,.bar}
2533 * + search the PATH for scriptname{,.foo,.bar}
2536 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2537 * this will not look in '.' if it's not in the PATH)
2542 # ifdef ALWAYS_DEFTYPES
2543 len = strlen(scriptname);
2544 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2545 int hasdir, idx = 0, deftypes = 1;
2548 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2551 int hasdir, idx = 0, deftypes = 1;
2554 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2556 /* The first time through, just add SEARCH_EXTS to whatever we
2557 * already have, so we can check for default file types. */
2559 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2565 if ((strlen(tmpbuf) + strlen(scriptname)
2566 + MAX_EXT_LEN) >= sizeof tmpbuf)
2567 continue; /* don't search dir with too-long name */
2568 strcat(tmpbuf, scriptname);
2572 if (strEQ(scriptname, "-"))
2574 if (dosearch) { /* Look in '.' first. */
2575 char *cur = scriptname;
2577 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2579 if (strEQ(ext[i++],curext)) {
2580 extidx = -1; /* already has an ext */
2585 DEBUG_p(PerlIO_printf(Perl_debug_log,
2586 "Looking for %s\n",cur));
2587 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2588 && !S_ISDIR(PL_statbuf.st_mode)) {
2596 if (cur == scriptname) {
2597 len = strlen(scriptname);
2598 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2600 cur = strcpy(tmpbuf, scriptname);
2602 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2603 && strcpy(tmpbuf+len, ext[extidx++]));
2608 if (dosearch && !strchr(scriptname, '/')
2610 && !strchr(scriptname, '\\')
2612 && (s = PerlEnv_getenv("PATH"))) {
2615 PL_bufend = s + strlen(s);
2616 while (s < PL_bufend) {
2617 #if defined(atarist) || defined(DOSISH)
2622 && *s != ';'; len++, s++) {
2623 if (len < sizeof tmpbuf)
2626 if (len < sizeof tmpbuf)
2628 #else /* ! (atarist || DOSISH) */
2629 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2632 #endif /* ! (atarist || DOSISH) */
2635 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2636 continue; /* don't search dir with too-long name */
2638 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2639 && tmpbuf[len - 1] != '/'
2640 && tmpbuf[len - 1] != '\\'
2643 tmpbuf[len++] = '/';
2644 if (len == 2 && tmpbuf[0] == '.')
2646 (void)strcpy(tmpbuf + len, scriptname);
2650 len = strlen(tmpbuf);
2651 if (extidx > 0) /* reset after previous loop */
2655 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2656 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2657 if (S_ISDIR(PL_statbuf.st_mode)) {
2661 } while ( retval < 0 /* not there */
2662 && extidx>=0 && ext[extidx] /* try an extension? */
2663 && strcpy(tmpbuf+len, ext[extidx++])
2668 if (S_ISREG(PL_statbuf.st_mode)
2669 && cando(S_IRUSR,TRUE,&PL_statbuf)
2671 && cando(S_IXUSR,TRUE,&PL_statbuf)
2675 xfound = tmpbuf; /* bingo! */
2679 xfailed = savepv(tmpbuf);
2682 if (!xfound && !seen_dot && !xfailed &&
2683 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2684 || S_ISDIR(PL_statbuf.st_mode)))
2686 seen_dot = 1; /* Disable message. */
2688 if (flags & 1) { /* do or die? */
2689 croak("Can't %s %s%s%s",
2690 (xfailed ? "execute" : "find"),
2691 (xfailed ? xfailed : scriptname),
2692 (xfailed ? "" : " on PATH"),
2693 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2695 scriptname = Nullch;
2699 scriptname = xfound;
2701 return (scriptname ? savepv(scriptname) : Nullch);
2707 /* Very simplistic scheduler for now */
2711 thr = thr->i.next_run;
2715 perl_cond_init(perl_cond *cp)
2721 perl_cond_signal(perl_cond *cp)
2724 perl_cond cond = *cp;
2729 /* Insert t in the runnable queue just ahead of us */
2730 t->i.next_run = thr->i.next_run;
2731 thr->i.next_run->i.prev_run = t;
2732 t->i.prev_run = thr;
2733 thr->i.next_run = t;
2734 thr->i.wait_queue = 0;
2735 /* Remove from the wait queue */
2741 perl_cond_broadcast(perl_cond *cp)
2744 perl_cond cond, cond_next;
2746 for (cond = *cp; cond; cond = cond_next) {
2748 /* Insert t in the runnable queue just ahead of us */
2749 t->i.next_run = thr->i.next_run;
2750 thr->i.next_run->i.prev_run = t;
2751 t->i.prev_run = thr;
2752 thr->i.next_run = t;
2753 thr->i.wait_queue = 0;
2754 /* Remove from the wait queue */
2755 cond_next = cond->next;
2762 perl_cond_wait(perl_cond *cp)
2766 if (thr->i.next_run == thr)
2767 croak("panic: perl_cond_wait called by last runnable thread");
2769 New(666, cond, 1, struct perl_wait_queue);
2773 thr->i.wait_queue = cond;
2774 /* Remove ourselves from runnable queue */
2775 thr->i.next_run->i.prev_run = thr->i.prev_run;
2776 thr->i.prev_run->i.next_run = thr->i.next_run;
2778 #endif /* FAKE_THREADS */
2780 #ifdef PTHREAD_GETSPECIFIC_INT
2781 struct perl_thread *
2786 if (pthread_getspecific(PL_thr_key, &t))
2787 croak("panic: pthread_getspecific");
2788 return (struct perl_thread *) t;
2793 condpair_magic(SV *sv)
2797 SvUPGRADE(sv, SVt_PVMG);
2798 mg = mg_find(sv, 'm');
2802 New(53, cp, 1, condpair_t);
2803 MUTEX_INIT(&cp->mutex);
2804 COND_INIT(&cp->owner_cond);
2805 COND_INIT(&cp->cond);
2808 mg = mg_find(sv, 'm');
2810 /* someone else beat us to initialising it */
2812 MUTEX_DESTROY(&cp->mutex);
2813 COND_DESTROY(&cp->owner_cond);
2814 COND_DESTROY(&cp->cond);
2818 sv_magic(sv, Nullsv, 'm', 0, 0);
2820 mg->mg_ptr = (char *)cp;
2821 mg->mg_len = sizeof(cp);
2823 DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
2824 "%p: condpair_magic %p\n", thr, sv));)
2831 * Make a new perl thread structure using t as a prototype. Some of the
2832 * fields for the new thread are copied from the prototype thread, t,
2833 * so t should not be running in perl at the time this function is
2834 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2835 * thread calling new_struct_thread) clearly satisfies this constraint.
2837 struct perl_thread *
2838 new_struct_thread(struct perl_thread *t)
2840 struct perl_thread *thr;
2845 sv = newSVpv("", 0);
2846 SvGROW(sv, sizeof(struct perl_thread) + 1);
2847 SvCUR_set(sv, sizeof(struct perl_thread));
2848 thr = (Thread) SvPVX(sv);
2850 memset(thr, 0xab, sizeof(struct perl_thread));
2857 Zero(&PL_hv_fetch_ent_mh, 1, HE);
2859 Zero(thr, 1, struct perl_thread);
2865 PL_curcop = &PL_compiling;
2866 thr->cvcache = newHV();
2867 thr->threadsv = newAV();
2868 thr->specific = newAV();
2869 thr->errsv = newSVpv("", 0);
2870 thr->errhv = newHV();
2871 thr->flags = THRf_R_JOINABLE;
2872 MUTEX_INIT(&thr->mutex);
2874 /* top_env needs to be non-zero. It points to an area
2875 in which longjmp() stuff is stored, as C callstack
2876 info there at least is thread specific this has to
2877 be per-thread. Otherwise a 'die' in a thread gives
2878 that thread the C stack of last thread to do an eval {}!
2879 See comments in scope.h
2880 Initialize top entry (as in perl.c for main thread)
2882 PL_start_env.je_prev = NULL;
2883 PL_start_env.je_ret = -1;
2884 PL_start_env.je_mustcatch = TRUE;
2885 PL_top_env = &PL_start_env;
2890 PL_statname = NEWSV(66,0);
2892 PL_regcompp = FUNC_NAME_TO_PTR(pregcomp);
2893 PL_regexecp = FUNC_NAME_TO_PTR(regexec_flags);
2895 PL_reginterp_cnt = 0;
2896 PL_lastscream = Nullsv;
2899 PL_reg_start_tmp = 0;
2900 PL_reg_start_tmpl = 0;
2902 /* parent thread's data needs to be locked while we make copy */
2903 MUTEX_LOCK(&t->mutex);
2905 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
2906 PL_defstash = t->Tdefstash; /* XXX maybe these should */
2907 PL_curstash = t->Tcurstash; /* always be set to main? */
2909 PL_tainted = t->Ttainted;
2910 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
2911 PL_nrs = newSVsv(t->Tnrs);
2912 PL_rs = SvREFCNT_inc(PL_nrs);
2913 PL_last_in_gv = Nullgv;
2914 PL_ofslen = t->Tofslen;
2915 PL_ofs = savepvn(t->Tofs, PL_ofslen);
2916 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2917 PL_chopset = t->Tchopset;
2918 PL_formtarget = newSVsv(t->Tformtarget);
2919 PL_bodytarget = newSVsv(t->Tbodytarget);
2920 PL_toptarget = newSVsv(t->Ttoptarget);
2922 /* Initialise all per-thread SVs that the template thread used */
2923 svp = AvARRAY(t->threadsv);
2924 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
2925 if (*svp && *svp != &PL_sv_undef) {
2926 SV *sv = newSVsv(*svp);
2927 av_store(thr->threadsv, i, sv);
2928 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
2929 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
2930 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
2933 thr->threadsvp = AvARRAY(thr->threadsv);
2935 MUTEX_LOCK(&PL_threads_mutex);
2937 thr->tid = ++PL_threadnum;
2938 thr->next = t->next;
2941 thr->next->prev = thr;
2942 MUTEX_UNLOCK(&PL_threads_mutex);
2944 /* done copying parent's state */
2945 MUTEX_UNLOCK(&t->mutex);
2947 #ifdef HAVE_THREAD_INTERN
2948 init_thread_intern(thr);
2949 #endif /* HAVE_THREAD_INTERN */
2952 #endif /* USE_THREADS */
2956 * This hack is to force load of "huge" support from libm.a
2957 * So it is in perl for (say) POSIX to use.
2958 * Needed for SunOS with Sun's 'acc' for example.
2967 #ifdef PERL_GLOBAL_STRUCT
2990 return (char*)PL_no_modify;
3000 get_specialsv_list(void)
3002 return PL_specialsv_list;
3007 get_vtbl(int vtbl_id)
3009 MGVTBL* result = Null(MGVTBL*);
3013 result = &PL_vtbl_sv;
3016 result = &PL_vtbl_env;
3018 case want_vtbl_envelem:
3019 result = &PL_vtbl_envelem;
3022 result = &PL_vtbl_sig;
3024 case want_vtbl_sigelem:
3025 result = &PL_vtbl_sigelem;
3027 case want_vtbl_pack:
3028 result = &PL_vtbl_pack;
3030 case want_vtbl_packelem:
3031 result = &PL_vtbl_packelem;
3033 case want_vtbl_dbline:
3034 result = &PL_vtbl_dbline;
3037 result = &PL_vtbl_isa;
3039 case want_vtbl_isaelem:
3040 result = &PL_vtbl_isaelem;
3042 case want_vtbl_arylen:
3043 result = &PL_vtbl_arylen;
3045 case want_vtbl_glob:
3046 result = &PL_vtbl_glob;
3048 case want_vtbl_mglob:
3049 result = &PL_vtbl_mglob;
3051 case want_vtbl_nkeys:
3052 result = &PL_vtbl_nkeys;
3054 case want_vtbl_taint:
3055 result = &PL_vtbl_taint;
3057 case want_vtbl_substr:
3058 result = &PL_vtbl_substr;
3061 result = &PL_vtbl_vec;
3064 result = &PL_vtbl_pos;
3067 result = &PL_vtbl_bm;
3070 result = &PL_vtbl_fm;
3072 case want_vtbl_uvar:
3073 result = &PL_vtbl_uvar;
3076 case want_vtbl_mutex:
3077 result = &PL_vtbl_mutex;
3080 case want_vtbl_defelem:
3081 result = &PL_vtbl_defelem;
3083 case want_vtbl_regexp:
3084 result = &PL_vtbl_regexp;
3086 case want_vtbl_regdata:
3087 result = &PL_vtbl_regdata;
3089 case want_vtbl_regdatum:
3090 result = &PL_vtbl_regdatum;
3092 #ifdef USE_LOCALE_COLLATE
3093 case want_vtbl_collxfrm:
3094 result = &PL_vtbl_collxfrm;
3097 case want_vtbl_amagic:
3098 result = &PL_vtbl_amagic;
3100 case want_vtbl_amagicelem:
3101 result = &PL_vtbl_amagicelem;