3 * Copyright (c) 1991-1999, 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];
65 /* paranoid version of system's malloc() */
67 /* NOTE: Do not call the next three routines directly. Use the macros
68 * in handy.h, so that we can easily redefine everything to do tracking of
69 * allocated hunks back to the original New to track down any memory leaks.
70 * XXX This advice seems to be widely ignored :-( --AD August 1996.
74 safesysmalloc(MEM_SIZE size)
79 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
82 #endif /* HAS_64K_LIMIT */
85 croak("panic: malloc");
87 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
88 #if !(defined(I286) || defined(atarist))
89 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
91 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
98 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
105 /* paranoid version of system's realloc() */
108 safesysrealloc(Malloc_t where,MEM_SIZE size)
111 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
112 Malloc_t PerlMem_realloc();
113 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
117 PerlIO_printf(PerlIO_stderr(),
118 "Reallocation too large: %lx\n", size) FLUSH;
121 #endif /* HAS_64K_LIMIT */
128 return safesysmalloc(size);
131 croak("panic: realloc");
133 ptr = PerlMem_realloc(where,size);
135 #if !(defined(I286) || defined(atarist))
137 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,PL_an++);
138 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
142 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,PL_an++);
143 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
152 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
159 /* safe version of system's free() */
162 safesysfree(Malloc_t where)
164 #if !(defined(I286) || defined(atarist))
165 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,PL_an++));
167 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,PL_an++));
175 /* safe version of system's calloc() */
178 safesyscalloc(MEM_SIZE count, MEM_SIZE size)
183 if (size * count > 0xffff) {
184 PerlIO_printf(PerlIO_stderr(),
185 "Allocation too large: %lx\n", size * count) FLUSH;
188 #endif /* HAS_64K_LIMIT */
190 if ((long)size < 0 || (long)count < 0)
191 croak("panic: calloc");
194 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
195 #if !(defined(I286) || defined(atarist))
196 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
198 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
201 memset((void*)ptr, 0, size);
207 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
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 const char *big, register const char *little)
390 register const char *s, *x;
401 for (x=big,s=little; *s; /**/ ) {
410 return (char*)(big-1);
415 /* same as instr but allow embedded nulls */
418 ninstr(register const char *big, register const char *bigend, const char *little, const char *lend)
420 register const char *s, *x;
421 register I32 first = *little;
422 register const 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; /**/ ) {
439 return (char*)(big-1);
444 /* reverse of the above--find last substring */
447 rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
449 register const char *bigbeg;
450 register const char *s, *x;
451 register I32 first = *little;
452 register const char *littleend = lend;
454 if (!first && little >= littleend)
455 return (char*)bigend;
457 big = bigend - (littleend - little++);
458 while (big >= bigbeg) {
461 for (x=big+2,s=little; s < littleend; /**/ ) {
468 return (char*)(big+1);
474 * Set up for a new ctype locale.
477 perl_new_ctype(const char *newctype)
479 #ifdef USE_LOCALE_CTYPE
483 for (i = 0; i < 256; i++) {
485 PL_fold_locale[i] = toLOWER_LC(i);
486 else if (isLOWER_LC(i))
487 PL_fold_locale[i] = toUPPER_LC(i);
489 PL_fold_locale[i] = i;
492 #endif /* USE_LOCALE_CTYPE */
496 * Set up for a new collation locale.
499 perl_new_collate(const char *newcoll)
501 #ifdef USE_LOCALE_COLLATE
504 if (PL_collation_name) {
506 Safefree(PL_collation_name);
507 PL_collation_name = NULL;
508 PL_collation_standard = TRUE;
509 PL_collxfrm_base = 0;
510 PL_collxfrm_mult = 2;
515 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
517 Safefree(PL_collation_name);
518 PL_collation_name = savepv(newcoll);
519 PL_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 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
532 PL_collxfrm_mult = mult;
536 #endif /* USE_LOCALE_COLLATE */
540 * Set up for a new numeric locale.
543 perl_new_numeric(const char *newnum)
545 #ifdef USE_LOCALE_NUMERIC
548 if (PL_numeric_name) {
549 Safefree(PL_numeric_name);
550 PL_numeric_name = NULL;
551 PL_numeric_standard = TRUE;
552 PL_numeric_local = TRUE;
557 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
558 Safefree(PL_numeric_name);
559 PL_numeric_name = savepv(newnum);
560 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
561 PL_numeric_local = TRUE;
564 #endif /* USE_LOCALE_NUMERIC */
568 perl_set_numeric_standard(void)
570 #ifdef USE_LOCALE_NUMERIC
572 if (! PL_numeric_standard) {
573 setlocale(LC_NUMERIC, "C");
574 PL_numeric_standard = TRUE;
575 PL_numeric_local = FALSE;
578 #endif /* USE_LOCALE_NUMERIC */
582 perl_set_numeric_local(void)
584 #ifdef USE_LOCALE_NUMERIC
586 if (! PL_numeric_local) {
587 setlocale(LC_NUMERIC, PL_numeric_name);
588 PL_numeric_standard = FALSE;
589 PL_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 */
621 char *language = PerlEnv_getenv("LANGUAGE");
623 char *lc_all = PerlEnv_getenv("LC_ALL");
624 char *lang = PerlEnv_getenv("LANG");
625 bool setlocale_failure = FALSE;
627 #ifdef LOCALE_ENVIRON_REQUIRED
630 * Ultrix setlocale(..., "") fails if there are no environment
631 * variables from which to get a locale name.
638 if (setlocale(LC_ALL, ""))
641 setlocale_failure = TRUE;
643 if (!setlocale_failure) {
644 #ifdef USE_LOCALE_CTYPE
647 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
649 setlocale_failure = TRUE;
650 #endif /* USE_LOCALE_CTYPE */
651 #ifdef USE_LOCALE_COLLATE
653 setlocale(LC_COLLATE,
654 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
656 setlocale_failure = TRUE;
657 #endif /* USE_LOCALE_COLLATE */
658 #ifdef USE_LOCALE_NUMERIC
660 setlocale(LC_NUMERIC,
661 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
663 setlocale_failure = TRUE;
664 #endif /* USE_LOCALE_NUMERIC */
669 #endif /* !LOCALE_ENVIRON_REQUIRED */
672 if (! setlocale(LC_ALL, ""))
673 setlocale_failure = TRUE;
676 if (!setlocale_failure) {
677 #ifdef USE_LOCALE_CTYPE
678 if (! (curctype = setlocale(LC_CTYPE, "")))
679 setlocale_failure = TRUE;
680 #endif /* USE_LOCALE_CTYPE */
681 #ifdef USE_LOCALE_COLLATE
682 if (! (curcoll = setlocale(LC_COLLATE, "")))
683 setlocale_failure = TRUE;
684 #endif /* USE_LOCALE_COLLATE */
685 #ifdef USE_LOCALE_NUMERIC
686 if (! (curnum = setlocale(LC_NUMERIC, "")))
687 setlocale_failure = TRUE;
688 #endif /* USE_LOCALE_NUMERIC */
691 if (setlocale_failure) {
693 bool locwarn = (printwarn > 1 ||
695 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
700 PerlIO_printf(PerlIO_stderr(),
701 "perl: warning: Setting locale failed.\n");
705 PerlIO_printf(PerlIO_stderr(),
706 "perl: warning: Setting locale failed for the categories:\n\t");
707 #ifdef USE_LOCALE_CTYPE
709 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
710 #endif /* USE_LOCALE_CTYPE */
711 #ifdef USE_LOCALE_COLLATE
713 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
714 #endif /* USE_LOCALE_COLLATE */
715 #ifdef USE_LOCALE_NUMERIC
717 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
718 #endif /* USE_LOCALE_NUMERIC */
719 PerlIO_printf(PerlIO_stderr(), "\n");
723 PerlIO_printf(PerlIO_stderr(),
724 "perl: warning: Please check that your locale settings:\n");
727 PerlIO_printf(PerlIO_stderr(),
728 "\tLANGUAGE = %c%s%c,\n",
729 language ? '"' : '(',
730 language ? language : "unset",
731 language ? '"' : ')');
734 PerlIO_printf(PerlIO_stderr(),
735 "\tLC_ALL = %c%s%c,\n",
737 lc_all ? lc_all : "unset",
742 for (e = environ; *e; e++) {
743 if (strnEQ(*e, "LC_", 3)
744 && strnNE(*e, "LC_ALL=", 7)
745 && (p = strchr(*e, '=')))
746 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
747 (int)(p - *e), *e, p + 1);
751 PerlIO_printf(PerlIO_stderr(),
754 lang ? lang : "unset",
757 PerlIO_printf(PerlIO_stderr(),
758 " are supported and installed on your system.\n");
763 if (setlocale(LC_ALL, "C")) {
765 PerlIO_printf(PerlIO_stderr(),
766 "perl: warning: Falling back to the standard locale (\"C\").\n");
771 PerlIO_printf(PerlIO_stderr(),
772 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
779 #ifdef USE_LOCALE_CTYPE
780 || !(curctype || setlocale(LC_CTYPE, "C"))
781 #endif /* USE_LOCALE_CTYPE */
782 #ifdef USE_LOCALE_COLLATE
783 || !(curcoll || setlocale(LC_COLLATE, "C"))
784 #endif /* USE_LOCALE_COLLATE */
785 #ifdef USE_LOCALE_NUMERIC
786 || !(curnum || setlocale(LC_NUMERIC, "C"))
787 #endif /* USE_LOCALE_NUMERIC */
791 PerlIO_printf(PerlIO_stderr(),
792 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
796 #endif /* ! LC_ALL */
798 #ifdef USE_LOCALE_CTYPE
799 curctype = setlocale(LC_CTYPE, Nullch);
800 #endif /* USE_LOCALE_CTYPE */
801 #ifdef USE_LOCALE_COLLATE
802 curcoll = setlocale(LC_COLLATE, Nullch);
803 #endif /* USE_LOCALE_COLLATE */
804 #ifdef USE_LOCALE_NUMERIC
805 curnum = setlocale(LC_NUMERIC, Nullch);
806 #endif /* USE_LOCALE_NUMERIC */
809 #ifdef USE_LOCALE_CTYPE
810 perl_new_ctype(curctype);
811 #endif /* USE_LOCALE_CTYPE */
813 #ifdef USE_LOCALE_COLLATE
814 perl_new_collate(curcoll);
815 #endif /* USE_LOCALE_COLLATE */
817 #ifdef USE_LOCALE_NUMERIC
818 perl_new_numeric(curnum);
819 #endif /* USE_LOCALE_NUMERIC */
821 #endif /* USE_LOCALE */
826 /* Backwards compatibility. */
828 perl_init_i18nl14n(int printwarn)
830 return perl_init_i18nl10n(printwarn);
833 #ifdef USE_LOCALE_COLLATE
836 * mem_collxfrm() is a bit like strxfrm() but with two important
837 * differences. First, it handles embedded NULs. Second, it allocates
838 * a bit more memory than needed for the transformed data itself.
839 * The real transformed data begins at offset sizeof(collationix).
840 * Please see sv_collxfrm() to see how this is used.
843 mem_collxfrm(const char *s, STRLEN len, STRLEN *xlen)
846 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
848 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
849 /* the +1 is for the terminating NUL. */
851 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
852 New(171, xbuf, xAlloc, char);
856 *(U32*)xbuf = PL_collation_ix;
857 xout = sizeof(PL_collation_ix);
858 for (xin = 0; xin < len; ) {
862 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
865 if (xused < xAlloc - xout)
867 xAlloc = (2 * xAlloc) + 1;
868 Renew(xbuf, xAlloc, char);
873 xin += strlen(s + xin) + 1;
876 /* Embedded NULs are understood but silently skipped
877 * because they make no sense in locale collation. */
881 *xlen = xout - sizeof(PL_collation_ix);
890 #endif /* USE_LOCALE_COLLATE */
893 fbm_compile(SV *sv, U32 flags /* not used yet */)
902 s = (U8*)SvPV_force(sv, len);
903 (void)SvUPGRADE(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 (PL_freq[s[i]] < frequency) {
928 frequency = PL_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, U32 flags)
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) && !PL_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)
1062 register unsigned char *s, *x;
1063 register unsigned char *big;
1065 register I32 previous;
1067 register unsigned char *little;
1068 register I32 stop_pos;
1069 register unsigned char *littleend;
1073 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1074 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0))
1076 little = (unsigned char *)(SvPVX(littlestr));
1077 littleend = little + SvCUR(littlestr);
1079 /* The value of pos we can start at: */
1080 previous = BmPREVIOUS(littlestr);
1081 big = (unsigned char *)(SvPVX(bigstr));
1082 /* The value of pos we can stop at: */
1083 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1084 if (previous + start_shift > stop_pos) return Nullch;
1085 while (pos < previous + start_shift) {
1086 if (!(pos += PL_screamnext[pos]))
1091 if (pos >= stop_pos) break;
1092 if (big[pos-previous] != first)
1094 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1100 if (s == littleend) {
1102 if (!last) return (char *)(big+pos-previous);
1105 } while ( pos += PL_screamnext[pos] );
1106 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1107 #else /* !POINTERRIGOR */
1110 if (pos >= stop_pos) break;
1111 if (big[pos] != first)
1113 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1119 if (s == littleend) {
1121 if (!last) return (char *)(big+pos);
1124 } while ( pos += PL_screamnext[pos] );
1125 return (last && found) ? (char *)(big+(*old_posp)) : Nullch;
1126 #endif /* POINTERRIGOR */
1130 ibcmp(const char *s1, const char *s2, register I32 len)
1132 register U8 *a = (U8 *)s1;
1133 register U8 *b = (U8 *)s2;
1135 if (*a != *b && *a != PL_fold[*b])
1143 ibcmp_locale(const char *s1, const char *s2, register I32 len)
1145 register U8 *a = (U8 *)s1;
1146 register U8 *b = (U8 *)s2;
1148 if (*a != *b && *a != PL_fold_locale[*b])
1155 /* copy a string to a safe spot */
1158 savepv(const char *sv)
1160 register char *newaddr;
1162 New(902,newaddr,strlen(sv)+1,char);
1163 (void)strcpy(newaddr,sv);
1167 /* same thing but with a known length */
1170 savepvn(const char *sv, register I32 len)
1172 register char *newaddr;
1174 New(903,newaddr,len+1,char);
1175 Copy(sv,newaddr,len,char); /* might not be null terminated */
1176 newaddr[len] = '\0'; /* is now */
1180 /* the SV for form() and mess() is not kept in an arena */
1190 return sv_2mortal(newSVpvn("",0));
1195 /* Create as PVMG now, to avoid any upgrading later */
1196 New(905, sv, 1, SV);
1197 Newz(905, any, 1, XPVMG);
1198 SvFLAGS(sv) = SVt_PVMG;
1199 SvANY(sv) = (void*)any;
1200 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1206 form(const char* pat, ...)
1208 SV *sv = mess_alloc();
1210 va_start(args, pat);
1211 sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1217 mess(const char *pat, va_list *args)
1219 SV *sv = mess_alloc();
1220 static char dgd[] = " during global destruction.\n";
1222 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1223 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1228 if (PL_curcop->cop_line)
1229 sv_catpvf(sv, " at %_ line %ld",
1230 GvSV(PL_curcop->cop_filegv), (long)PL_curcop->cop_line);
1231 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1232 bool line_mode = (RsSIMPLE(PL_rs) &&
1233 SvLEN(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1234 sv_catpvf(sv, ", <%s> %s %ld",
1235 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1236 line_mode ? "line" : "chunk",
1237 (long)IoLINES(GvIOp(PL_last_in_gv)));
1239 sv_catpv(sv, ".\n");
1246 die(const char* pat, ...)
1251 int was_in_eval = PL_in_eval;
1258 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1259 "%p: die: curstack = %p, mainstack = %p\n",
1260 thr, PL_curstack, PL_mainstack));
1262 va_start(args, pat);
1264 msv = mess(pat, &args);
1265 message = SvPV(msv,msglen);
1272 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1273 "%p: die: message = %s\ndiehook = %p\n",
1274 thr, message, PL_diehook));
1276 /* sv_2cv might call croak() */
1277 SV *olddiehook = PL_diehook;
1279 SAVESPTR(PL_diehook);
1280 PL_diehook = Nullsv;
1281 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1283 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1289 msg = newSVpvn(message, msglen);
1297 PUSHSTACKi(PERLSI_DIEHOOK);
1301 perl_call_sv((SV*)cv, G_DISCARD);
1307 PL_restartop = die_where(message, msglen);
1308 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1309 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1310 thr, PL_restartop, was_in_eval, PL_top_env));
1311 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1313 return PL_restartop;
1317 croak(const char* pat, ...)
1328 va_start(args, pat);
1329 msv = mess(pat, &args);
1330 message = SvPV(msv,msglen);
1332 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1334 /* sv_2cv might call croak() */
1335 SV *olddiehook = PL_diehook;
1337 SAVESPTR(PL_diehook);
1338 PL_diehook = Nullsv;
1339 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1341 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1346 msg = newSVpvn(message, msglen);
1350 PUSHSTACKi(PERLSI_DIEHOOK);
1354 perl_call_sv((SV*)cv, G_DISCARD);
1360 PL_restartop = die_where(message, msglen);
1365 /* SFIO can really mess with your errno */
1368 PerlIO_write(PerlIO_stderr(), message, msglen);
1369 (void)PerlIO_flush(PerlIO_stderr());
1378 warn(const char* pat,...)
1388 va_start(args, pat);
1389 msv = mess(pat, &args);
1390 message = SvPV(msv, msglen);
1394 /* sv_2cv might call warn() */
1396 SV *oldwarnhook = PL_warnhook;
1398 SAVESPTR(PL_warnhook);
1399 PL_warnhook = Nullsv;
1400 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1402 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1407 msg = newSVpvn(message, msglen);
1411 PUSHSTACKi(PERLSI_WARNHOOK);
1415 perl_call_sv((SV*)cv, G_DISCARD);
1421 PerlIO_write(PerlIO_stderr(), message, msglen);
1423 DEBUG_L(*message == '!'
1424 ? (xstat(message[1]=='!'
1425 ? (message[2]=='!' ? 2 : 1)
1430 (void)PerlIO_flush(PerlIO_stderr());
1434 warner(U32 err, const char* pat,...)
1445 va_start(args, pat);
1446 msv = mess(pat, &args);
1447 message = SvPV(msv, msglen);
1452 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1453 #endif /* USE_THREADS */
1455 /* sv_2cv might call croak() */
1456 SV *olddiehook = PL_diehook;
1458 SAVESPTR(PL_diehook);
1459 PL_diehook = Nullsv;
1460 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1462 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1467 msg = newSVpvn(message, msglen);
1474 perl_call_sv((SV*)cv, G_DISCARD);
1480 PL_restartop = die_where(message, msglen);
1483 PerlIO_write(PerlIO_stderr(), message, msglen);
1484 (void)PerlIO_flush(PerlIO_stderr());
1490 /* sv_2cv might call warn() */
1492 SV *oldwarnhook = PL_warnhook;
1494 SAVESPTR(PL_warnhook);
1495 PL_warnhook = Nullsv;
1496 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1498 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1503 msg = newSVpvn(message, msglen);
1510 perl_call_sv((SV*)cv, G_DISCARD);
1516 PerlIO_write(PerlIO_stderr(), message, msglen);
1520 (void)PerlIO_flush(PerlIO_stderr());
1524 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1527 my_setenv(char *nam, char *val)
1529 #ifndef PERL_USE_SAFE_PUTENV
1530 /* most putenv()s leak, so we manipulate environ directly */
1531 register I32 i=setenv_getix(nam); /* where does it go? */
1533 if (environ == PL_origenviron) { /* need we copy environment? */
1539 for (max = i; environ[max]; max++) ;
1540 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1541 for (j=0; j<max; j++) { /* copy environment */
1542 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1543 strcpy(tmpenv[j], environ[j]);
1545 tmpenv[max] = Nullch;
1546 environ = tmpenv; /* tell exec where it is now */
1549 safesysfree(environ[i]);
1550 while (environ[i]) {
1551 environ[i] = environ[i+1];
1556 if (!environ[i]) { /* does not exist yet */
1557 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1558 environ[i+1] = Nullch; /* make sure it's null terminated */
1561 safesysfree(environ[i]);
1562 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1565 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1567 /* MS-DOS requires environment variable names to be in uppercase */
1568 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1569 * some utilities and applications may break because they only look
1570 * for upper case strings. (Fixed strupr() bug here.)]
1572 strcpy(environ[i],nam); strupr(environ[i]);
1573 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1576 #else /* PERL_USE_SAFE_PUTENV */
1579 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1581 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1583 strcpy(new_env,nam); strupr(new_env);
1584 (void)sprintf(new_env + strlen(nam),"=%s",val);
1586 (void)putenv(new_env);
1587 #endif /* PERL_USE_SAFE_PUTENV */
1590 #else /* if WIN32 */
1593 my_setenv(char *nam,char *val)
1596 #ifdef USE_WIN32_RTL_ENV
1598 register char *envstr;
1599 STRLEN namlen = strlen(nam);
1601 char *oldstr = environ[setenv_getix(nam)];
1603 /* putenv() has totally broken semantics in both the Borland
1604 * and Microsoft CRTLs. They either store the passed pointer in
1605 * the environment without making a copy, or make a copy and don't
1606 * free it. And on top of that, they dont free() old entries that
1607 * are being replaced/deleted. This means the caller must
1608 * free any old entries somehow, or we end up with a memory
1609 * leak every time my_setenv() is called. One might think
1610 * one could directly manipulate environ[], like the UNIX code
1611 * above, but direct changes to environ are not allowed when
1612 * calling putenv(), since the RTLs maintain an internal
1613 * *copy* of environ[]. Bad, bad, *bad* stink.
1624 vallen = strlen(val);
1625 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
1626 (void)sprintf(envstr,"%s=%s",nam,val);
1627 (void)PerlEnv_putenv(envstr);
1629 safesysfree(oldstr);
1631 safesysfree(envstr); /* MSVCRT leaks without this */
1634 #else /* !USE_WIN32_RTL_ENV */
1636 register char *envstr;
1637 STRLEN len = strlen(nam) + 3;
1642 New(904, envstr, len, char);
1643 (void)sprintf(envstr,"%s=%s",nam,val);
1644 (void)PerlEnv_putenv(envstr);
1653 setenv_getix(char *nam)
1655 register I32 i, len = strlen(nam);
1657 for (i = 0; environ[i]; i++) {
1660 strnicmp(environ[i],nam,len) == 0
1662 strnEQ(environ[i],nam,len)
1664 && environ[i][len] == '=')
1665 break; /* strnEQ must come first to avoid */
1666 } /* potential SEGV's */
1672 #ifdef UNLINK_ALL_VERSIONS
1674 unlnk(f) /* unlink all versions of a file */
1679 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1684 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1686 my_bcopy(register const char *from,register char *to,register I32 len)
1690 if (from - to >= 0) {
1698 *(--to) = *(--from);
1706 my_memset(register char *loc, register I32 ch, register I32 len)
1716 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1718 my_bzero(register char *loc, register I32 len)
1728 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1730 my_memcmp(const char *s1, const char *s2, register I32 len)
1732 register U8 *a = (U8 *)s1;
1733 register U8 *b = (U8 *)s2;
1737 if (tmp = *a++ - *b++)
1742 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1746 #ifdef USE_CHAR_VSPRINTF
1751 vsprintf(char *dest, const char *pat, char *args)
1755 fakebuf._ptr = dest;
1756 fakebuf._cnt = 32767;
1760 fakebuf._flag = _IOWRT|_IOSTRG;
1761 _doprnt(pat, args, &fakebuf); /* what a kludge */
1762 (void)putc('\0', &fakebuf);
1763 #ifdef USE_CHAR_VSPRINTF
1766 return 0; /* perl doesn't use return value */
1770 #endif /* HAS_VPRINTF */
1773 #if BYTEORDER != 0x4321
1777 #if (BYTEORDER & 1) == 0
1780 result = ((s & 255) << 8) + ((s >> 8) & 255);
1792 char c[sizeof(long)];
1795 #if BYTEORDER == 0x1234
1796 u.c[0] = (l >> 24) & 255;
1797 u.c[1] = (l >> 16) & 255;
1798 u.c[2] = (l >> 8) & 255;
1802 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1803 croak("Unknown BYTEORDER\n");
1808 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1809 u.c[o & 0xf] = (l >> s) & 255;
1821 char c[sizeof(long)];
1824 #if BYTEORDER == 0x1234
1825 u.c[0] = (l >> 24) & 255;
1826 u.c[1] = (l >> 16) & 255;
1827 u.c[2] = (l >> 8) & 255;
1831 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1832 croak("Unknown BYTEORDER\n");
1839 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1840 l |= (u.c[o & 0xf] & 255) << s;
1847 #endif /* BYTEORDER != 0x4321 */
1851 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1852 * If these functions are defined,
1853 * the BYTEORDER is neither 0x1234 nor 0x4321.
1854 * However, this is not assumed.
1858 #define HTOV(name,type) \
1865 char c[sizeof(type)]; \
1869 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1870 u.c[i] = (n >> s) & 0xFF; \
1875 #define VTOH(name,type) \
1882 char c[sizeof(type)]; \
1888 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1889 n += (u.c[i] & 0xFF) << s; \
1894 #if defined(HAS_HTOVS) && !defined(htovs)
1897 #if defined(HAS_HTOVL) && !defined(htovl)
1900 #if defined(HAS_VTOHS) && !defined(vtohs)
1903 #if defined(HAS_VTOHL) && !defined(vtohl)
1907 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1908 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
1910 my_popen(char *cmd, char *mode)
1913 register I32 This, that;
1916 I32 doexec = strNE(cmd,"-");
1920 return my_syspopen(cmd,mode);
1923 This = (*mode == 'w');
1925 if (doexec && PL_tainting) {
1927 taint_proper("Insecure %s%s", "EXEC");
1929 if (PerlProc_pipe(p) < 0)
1931 while ((pid = (doexec?vfork():fork())) < 0) {
1932 if (errno != EAGAIN) {
1933 PerlLIO_close(p[This]);
1935 croak("Can't fork");
1947 PerlLIO_close(p[THAT]);
1948 if (p[THIS] != (*mode == 'r')) {
1949 PerlLIO_dup2(p[THIS], *mode == 'r');
1950 PerlLIO_close(p[THIS]);
1953 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1959 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
1962 do_exec(cmd); /* may or may not use the shell */
1966 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1967 sv_setiv(GvSV(tmpgv), (IV)getpid());
1969 hv_clear(PL_pidstatus); /* we have no children */
1974 do_execfree(); /* free any memory malloced by child on vfork */
1975 PerlLIO_close(p[that]);
1976 if (p[that] < p[This]) {
1977 PerlLIO_dup2(p[This], p[that]);
1978 PerlLIO_close(p[This]);
1981 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1982 (void)SvUPGRADE(sv,SVt_IV);
1984 PL_forkprocess = pid;
1985 return PerlIO_fdopen(p[This], mode);
1988 #if defined(atarist) || defined(DJGPP)
1995 /* Needs work for PerlIO ! */
1996 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1997 return popen(PerlIO_exportFILE(cmd, 0), mode);
2001 #endif /* !DOSISH */
2008 struct stat tmpstatbuf;
2010 PerlIO_printf(PerlIO_stderr(),"%s", s);
2011 for (fd = 0; fd < 32; fd++) {
2012 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2013 PerlIO_printf(PerlIO_stderr()," %d",fd);
2015 PerlIO_printf(PerlIO_stderr(),"\n");
2017 #endif /* DUMP_FDS */
2025 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2028 PerlLIO_close(newfd);
2029 return fcntl(oldfd, F_DUPFD, newfd);
2031 #define DUP2_MAX_FDS 256
2032 int fdtmp[DUP2_MAX_FDS];
2038 PerlLIO_close(newfd);
2039 /* good enough for low fd's... */
2040 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2041 if (fdx >= DUP2_MAX_FDS) {
2049 PerlLIO_close(fdtmp[--fdx]);
2056 #ifdef HAS_SIGACTION
2059 rsignal(int signo, Sighandler_t handler)
2061 struct sigaction act, oact;
2063 act.sa_handler = handler;
2064 sigemptyset(&act.sa_mask);
2067 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2070 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2071 act.sa_flags |= SA_NOCLDWAIT;
2073 if (sigaction(signo, &act, &oact) == -1)
2076 return oact.sa_handler;
2080 rsignal_state(int signo)
2082 struct sigaction oact;
2084 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2087 return oact.sa_handler;
2091 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2093 struct sigaction act;
2095 act.sa_handler = handler;
2096 sigemptyset(&act.sa_mask);
2099 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2102 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2103 act.sa_flags |= SA_NOCLDWAIT;
2105 return sigaction(signo, &act, save);
2109 rsignal_restore(int signo, Sigsave_t *save)
2111 return sigaction(signo, save, (struct sigaction *)NULL);
2114 #else /* !HAS_SIGACTION */
2117 rsignal(int signo, Sighandler_t handler)
2119 return PerlProc_signal(signo, handler);
2122 static int sig_trapped;
2132 rsignal_state(int signo)
2134 Sighandler_t oldsig;
2137 oldsig = PerlProc_signal(signo, sig_trap);
2138 PerlProc_signal(signo, oldsig);
2140 PerlProc_kill(getpid(), signo);
2145 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2147 *save = PerlProc_signal(signo, handler);
2148 return (*save == SIG_ERR) ? -1 : 0;
2152 rsignal_restore(int signo, Sigsave_t *save)
2154 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2157 #endif /* !HAS_SIGACTION */
2159 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2160 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
2162 my_pclose(PerlIO *ptr)
2164 Sigsave_t hstat, istat, qstat;
2172 int saved_vaxc_errno;
2175 int saved_win32_errno;
2178 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2179 pid = (int)SvIVX(*svp);
2181 *svp = &PL_sv_undef;
2183 if (pid == -1) { /* Opened by popen. */
2184 return my_syspclose(ptr);
2187 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2188 saved_errno = errno;
2190 saved_vaxc_errno = vaxc$errno;
2193 saved_win32_errno = GetLastError();
2197 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2199 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2200 rsignal_save(SIGINT, SIG_IGN, &istat);
2201 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2203 pid2 = wait4pid(pid, &status, 0);
2204 } while (pid2 == -1 && errno == EINTR);
2205 rsignal_restore(SIGHUP, &hstat);
2206 rsignal_restore(SIGINT, &istat);
2207 rsignal_restore(SIGQUIT, &qstat);
2209 SETERRNO(saved_errno, saved_vaxc_errno);
2212 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2214 #endif /* !DOSISH */
2216 #if !defined(DOSISH) || defined(OS2) || defined(WIN32)
2218 wait4pid(int pid, int *statusp, int flags)
2222 char spid[TYPE_CHARS(int)];
2227 sprintf(spid, "%d", pid);
2228 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2229 if (svp && *svp != &PL_sv_undef) {
2230 *statusp = SvIVX(*svp);
2231 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2238 hv_iterinit(PL_pidstatus);
2239 if (entry = hv_iternext(PL_pidstatus)) {
2240 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2241 sv = hv_iterval(PL_pidstatus,entry);
2242 *statusp = SvIVX(sv);
2243 sprintf(spid, "%d", pid);
2244 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2249 # ifdef HAS_WAITPID_RUNTIME
2250 if (!HAS_WAITPID_RUNTIME)
2253 return PerlProc_waitpid(pid,statusp,flags);
2255 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2256 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2258 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2263 croak("Can't do waitpid with flags");
2265 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2266 pidgone(result,*statusp);
2274 #endif /* !DOSISH || OS2 || WIN32 */
2278 pidgone(int pid, int status)
2281 char spid[TYPE_CHARS(int)];
2283 sprintf(spid, "%d", pid);
2284 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2285 (void)SvUPGRADE(sv,SVt_IV);
2290 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2293 int /* Cannot prototype with I32
2302 /* Needs work for PerlIO ! */
2303 FILE *f = PerlIO_findFILE(ptr);
2304 I32 result = pclose(f);
2305 PerlIO_releaseFILE(ptr,f);
2311 repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
2314 register const char *frombase = from;
2317 register const char c = *from;
2322 while (count-- > 0) {
2323 for (todo = len; todo > 0; todo--) {
2331 cast_ulong(double f)
2336 # define BIGDOUBLE 2147483648.0
2338 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2341 return (unsigned long)f;
2343 return (unsigned long)along;
2347 /* Unfortunately, on some systems the cast_uv() function doesn't
2348 work with the system-supplied definition of ULONG_MAX. The
2349 comparison (f >= ULONG_MAX) always comes out true. It must be a
2350 problem with the compiler constant folding.
2352 In any case, this workaround should be fine on any two's complement
2353 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2355 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2358 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2360 -- Kenneth Albanowski <kjahds@kjahds.com>
2364 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2371 return (I32) I32_MAX;
2373 return (I32) I32_MIN;
2391 return (UV) MY_UV_MAX;
2397 same_dirent(char *a, char *b)
2399 char *fa = strrchr(a,'/');
2400 char *fb = strrchr(b,'/');
2401 struct stat tmpstatbuf1;
2402 struct stat tmpstatbuf2;
2403 SV *tmpsv = sv_newmortal();
2416 sv_setpv(tmpsv, ".");
2418 sv_setpvn(tmpsv, a, fa - a);
2419 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2422 sv_setpv(tmpsv, ".");
2424 sv_setpvn(tmpsv, b, fb - b);
2425 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2427 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2428 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2430 #endif /* !HAS_RENAME */
2433 scan_bin(char *start, I32 len, I32 *retlen)
2435 register char *s = start;
2436 register UV retval = 0;
2437 bool overflowed = FALSE;
2438 while (len && *s >= '0' && *s <= '1') {
2439 register UV n = retval << 1;
2440 if (!overflowed && (n >> 1) != retval) {
2441 warn("Integer overflow in binary number");
2444 retval = n | (*s++ - '0');
2447 if (len && (*s >= '2' || *s <= '9')) {
2449 if (ckWARN(WARN_UNSAFE))
2450 warner(WARN_UNSAFE, "Illegal binary digit '%c' ignored", *s);
2452 *retlen = s - start;
2456 scan_oct(char *start, I32 len, I32 *retlen)
2458 register char *s = start;
2459 register UV retval = 0;
2460 bool overflowed = FALSE;
2462 while (len && *s >= '0' && *s <= '7') {
2463 register UV n = retval << 3;
2464 if (!overflowed && (n >> 3) != retval) {
2465 warn("Integer overflow in octal number");
2468 retval = n | (*s++ - '0');
2471 if (len && (*s == '8' || *s == '9')) {
2473 if (ckWARN(WARN_OCTAL))
2474 warner(WARN_OCTAL, "Illegal octal digit '%c' ignored", *s);
2476 *retlen = s - start;
2481 scan_hex(char *start, I32 len, I32 *retlen)
2483 register char *s = start;
2484 register UV retval = 0;
2485 bool overflowed = FALSE;
2489 while (len-- && *s) {
2490 tmp = strchr((char *) PL_hexdigit, *s++);
2492 if (*(s-1) == '_' || (*(s-1) == 'x' && retval == 0))
2497 if (ckWARN(WARN_UNSAFE))
2498 warner(WARN_UNSAFE,"Illegal hex digit '%c' ignored", *s);
2503 if (!overflowed && (n >> 4) != retval) {
2504 warn("Integer overflow in hex number");
2507 retval = n | ((tmp - PL_hexdigit) & 15);
2509 *retlen = s - start;
2514 find_script(char *scriptname, bool dosearch, char **search_ext, I32 flags)
2517 char *xfound = Nullch;
2518 char *xfailed = Nullch;
2519 char tmpbuf[MAXPATHLEN];
2523 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2524 # define SEARCH_EXTS ".bat", ".cmd", NULL
2525 # define MAX_EXT_LEN 4
2528 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2529 # define MAX_EXT_LEN 4
2532 # define SEARCH_EXTS ".pl", ".com", NULL
2533 # define MAX_EXT_LEN 4
2535 /* additional extensions to try in each dir if scriptname not found */
2537 char *exts[] = { SEARCH_EXTS };
2538 char **ext = search_ext ? search_ext : exts;
2539 int extidx = 0, i = 0;
2540 char *curext = Nullch;
2542 # define MAX_EXT_LEN 0
2546 * If dosearch is true and if scriptname does not contain path
2547 * delimiters, search the PATH for scriptname.
2549 * If SEARCH_EXTS is also defined, will look for each
2550 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2551 * while searching the PATH.
2553 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2554 * proceeds as follows:
2555 * If DOSISH or VMSISH:
2556 * + look for ./scriptname{,.foo,.bar}
2557 * + search the PATH for scriptname{,.foo,.bar}
2560 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2561 * this will not look in '.' if it's not in the PATH)
2566 # ifdef ALWAYS_DEFTYPES
2567 len = strlen(scriptname);
2568 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2569 int hasdir, idx = 0, deftypes = 1;
2572 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2575 int hasdir, idx = 0, deftypes = 1;
2578 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2580 /* The first time through, just add SEARCH_EXTS to whatever we
2581 * already have, so we can check for default file types. */
2583 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2589 if ((strlen(tmpbuf) + strlen(scriptname)
2590 + MAX_EXT_LEN) >= sizeof tmpbuf)
2591 continue; /* don't search dir with too-long name */
2592 strcat(tmpbuf, scriptname);
2596 if (strEQ(scriptname, "-"))
2598 if (dosearch) { /* Look in '.' first. */
2599 char *cur = scriptname;
2601 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2603 if (strEQ(ext[i++],curext)) {
2604 extidx = -1; /* already has an ext */
2609 DEBUG_p(PerlIO_printf(Perl_debug_log,
2610 "Looking for %s\n",cur));
2611 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2612 && !S_ISDIR(PL_statbuf.st_mode)) {
2620 if (cur == scriptname) {
2621 len = strlen(scriptname);
2622 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2624 cur = strcpy(tmpbuf, scriptname);
2626 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2627 && strcpy(tmpbuf+len, ext[extidx++]));
2632 if (dosearch && !strchr(scriptname, '/')
2634 && !strchr(scriptname, '\\')
2636 && (s = PerlEnv_getenv("PATH"))) {
2639 PL_bufend = s + strlen(s);
2640 while (s < PL_bufend) {
2641 #if defined(atarist) || defined(DOSISH)
2646 && *s != ';'; len++, s++) {
2647 if (len < sizeof tmpbuf)
2650 if (len < sizeof tmpbuf)
2652 #else /* ! (atarist || DOSISH) */
2653 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2656 #endif /* ! (atarist || DOSISH) */
2659 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2660 continue; /* don't search dir with too-long name */
2662 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2663 && tmpbuf[len - 1] != '/'
2664 && tmpbuf[len - 1] != '\\'
2667 tmpbuf[len++] = '/';
2668 if (len == 2 && tmpbuf[0] == '.')
2670 (void)strcpy(tmpbuf + len, scriptname);
2674 len = strlen(tmpbuf);
2675 if (extidx > 0) /* reset after previous loop */
2679 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2680 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2681 if (S_ISDIR(PL_statbuf.st_mode)) {
2685 } while ( retval < 0 /* not there */
2686 && extidx>=0 && ext[extidx] /* try an extension? */
2687 && strcpy(tmpbuf+len, ext[extidx++])
2692 if (S_ISREG(PL_statbuf.st_mode)
2693 && cando(S_IRUSR,TRUE,&PL_statbuf)
2695 && cando(S_IXUSR,TRUE,&PL_statbuf)
2699 xfound = tmpbuf; /* bingo! */
2703 xfailed = savepv(tmpbuf);
2706 if (!xfound && !seen_dot && !xfailed &&
2707 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2708 || S_ISDIR(PL_statbuf.st_mode)))
2710 seen_dot = 1; /* Disable message. */
2712 if (flags & 1) { /* do or die? */
2713 croak("Can't %s %s%s%s",
2714 (xfailed ? "execute" : "find"),
2715 (xfailed ? xfailed : scriptname),
2716 (xfailed ? "" : " on PATH"),
2717 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2719 scriptname = Nullch;
2723 scriptname = xfound;
2725 return (scriptname ? savepv(scriptname) : Nullch);
2731 /* Very simplistic scheduler for now */
2735 thr = thr->i.next_run;
2739 perl_cond_init(perl_cond *cp)
2745 perl_cond_signal(perl_cond *cp)
2748 perl_cond cond = *cp;
2753 /* Insert t in the runnable queue just ahead of us */
2754 t->i.next_run = thr->i.next_run;
2755 thr->i.next_run->i.prev_run = t;
2756 t->i.prev_run = thr;
2757 thr->i.next_run = t;
2758 thr->i.wait_queue = 0;
2759 /* Remove from the wait queue */
2765 perl_cond_broadcast(perl_cond *cp)
2768 perl_cond cond, cond_next;
2770 for (cond = *cp; cond; cond = cond_next) {
2772 /* Insert t in the runnable queue just ahead of us */
2773 t->i.next_run = thr->i.next_run;
2774 thr->i.next_run->i.prev_run = t;
2775 t->i.prev_run = thr;
2776 thr->i.next_run = t;
2777 thr->i.wait_queue = 0;
2778 /* Remove from the wait queue */
2779 cond_next = cond->next;
2786 perl_cond_wait(perl_cond *cp)
2790 if (thr->i.next_run == thr)
2791 croak("panic: perl_cond_wait called by last runnable thread");
2793 New(666, cond, 1, struct perl_wait_queue);
2797 thr->i.wait_queue = cond;
2798 /* Remove ourselves from runnable queue */
2799 thr->i.next_run->i.prev_run = thr->i.prev_run;
2800 thr->i.prev_run->i.next_run = thr->i.next_run;
2802 #endif /* FAKE_THREADS */
2804 #ifdef PTHREAD_GETSPECIFIC_INT
2805 struct perl_thread *
2810 if (pthread_getspecific(PL_thr_key, &t))
2811 croak("panic: pthread_getspecific");
2812 return (struct perl_thread *) t;
2817 condpair_magic(SV *sv)
2821 SvUPGRADE(sv, SVt_PVMG);
2822 mg = mg_find(sv, 'm');
2826 New(53, cp, 1, condpair_t);
2827 MUTEX_INIT(&cp->mutex);
2828 COND_INIT(&cp->owner_cond);
2829 COND_INIT(&cp->cond);
2832 mg = mg_find(sv, 'm');
2834 /* someone else beat us to initialising it */
2836 MUTEX_DESTROY(&cp->mutex);
2837 COND_DESTROY(&cp->owner_cond);
2838 COND_DESTROY(&cp->cond);
2842 sv_magic(sv, Nullsv, 'm', 0, 0);
2844 mg->mg_ptr = (char *)cp;
2845 mg->mg_len = sizeof(cp);
2847 DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
2848 "%p: condpair_magic %p\n", thr, sv));)
2855 * Make a new perl thread structure using t as a prototype. Some of the
2856 * fields for the new thread are copied from the prototype thread, t,
2857 * so t should not be running in perl at the time this function is
2858 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2859 * thread calling new_struct_thread) clearly satisfies this constraint.
2861 struct perl_thread *
2862 new_struct_thread(struct perl_thread *t)
2864 struct perl_thread *thr;
2869 sv = newSVpvn("", 0);
2870 SvGROW(sv, sizeof(struct perl_thread) + 1);
2871 SvCUR_set(sv, sizeof(struct perl_thread));
2872 thr = (Thread) SvPVX(sv);
2874 memset(thr, 0xab, sizeof(struct perl_thread));
2881 Zero(&PL_hv_fetch_ent_mh, 1, HE);
2883 Zero(thr, 1, struct perl_thread);
2889 PL_curcop = &PL_compiling;
2890 thr->cvcache = newHV();
2891 thr->threadsv = newAV();
2892 thr->specific = newAV();
2893 thr->errsv = newSVpvn("", 0);
2894 thr->errhv = newHV();
2895 thr->flags = THRf_R_JOINABLE;
2896 MUTEX_INIT(&thr->mutex);
2898 /* top_env needs to be non-zero. It points to an area
2899 in which longjmp() stuff is stored, as C callstack
2900 info there at least is thread specific this has to
2901 be per-thread. Otherwise a 'die' in a thread gives
2902 that thread the C stack of last thread to do an eval {}!
2903 See comments in scope.h
2904 Initialize top entry (as in perl.c for main thread)
2906 PL_start_env.je_prev = NULL;
2907 PL_start_env.je_ret = -1;
2908 PL_start_env.je_mustcatch = TRUE;
2909 PL_top_env = &PL_start_env;
2914 PL_statname = NEWSV(66,0);
2916 PL_regcompp = FUNC_NAME_TO_PTR(pregcomp);
2917 PL_regexecp = FUNC_NAME_TO_PTR(regexec_flags);
2919 PL_reginterp_cnt = 0;
2920 PL_lastscream = Nullsv;
2923 PL_reg_start_tmp = 0;
2924 PL_reg_start_tmpl = 0;
2926 /* parent thread's data needs to be locked while we make copy */
2927 MUTEX_LOCK(&t->mutex);
2929 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
2930 PL_defstash = t->Tdefstash; /* XXX maybe these should */
2931 PL_curstash = t->Tcurstash; /* always be set to main? */
2933 PL_tainted = t->Ttainted;
2934 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
2935 PL_nrs = newSVsv(t->Tnrs);
2936 PL_rs = SvREFCNT_inc(PL_nrs);
2937 PL_last_in_gv = Nullgv;
2938 PL_ofslen = t->Tofslen;
2939 PL_ofs = savepvn(t->Tofs, PL_ofslen);
2940 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2941 PL_chopset = t->Tchopset;
2942 PL_formtarget = newSVsv(t->Tformtarget);
2943 PL_bodytarget = newSVsv(t->Tbodytarget);
2944 PL_toptarget = newSVsv(t->Ttoptarget);
2946 /* Initialise all per-thread SVs that the template thread used */
2947 svp = AvARRAY(t->threadsv);
2948 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
2949 if (*svp && *svp != &PL_sv_undef) {
2950 SV *sv = newSVsv(*svp);
2951 av_store(thr->threadsv, i, sv);
2952 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
2953 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
2954 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
2957 thr->threadsvp = AvARRAY(thr->threadsv);
2959 MUTEX_LOCK(&PL_threads_mutex);
2961 thr->tid = ++PL_threadnum;
2962 thr->next = t->next;
2965 thr->next->prev = thr;
2966 MUTEX_UNLOCK(&PL_threads_mutex);
2968 /* done copying parent's state */
2969 MUTEX_UNLOCK(&t->mutex);
2971 #ifdef HAVE_THREAD_INTERN
2972 init_thread_intern(thr);
2973 #endif /* HAVE_THREAD_INTERN */
2976 #endif /* USE_THREADS */
2980 * This hack is to force load of "huge" support from libm.a
2981 * So it is in perl for (say) POSIX to use.
2982 * Needed for SunOS with Sun's 'acc' for example.
2991 #ifdef PERL_GLOBAL_STRUCT
3014 return (char*)PL_no_modify;
3024 get_specialsv_list(void)
3026 return PL_specialsv_list;
3031 get_vtbl(int vtbl_id)
3033 MGVTBL* result = Null(MGVTBL*);
3037 result = &PL_vtbl_sv;
3040 result = &PL_vtbl_env;
3042 case want_vtbl_envelem:
3043 result = &PL_vtbl_envelem;
3046 result = &PL_vtbl_sig;
3048 case want_vtbl_sigelem:
3049 result = &PL_vtbl_sigelem;
3051 case want_vtbl_pack:
3052 result = &PL_vtbl_pack;
3054 case want_vtbl_packelem:
3055 result = &PL_vtbl_packelem;
3057 case want_vtbl_dbline:
3058 result = &PL_vtbl_dbline;
3061 result = &PL_vtbl_isa;
3063 case want_vtbl_isaelem:
3064 result = &PL_vtbl_isaelem;
3066 case want_vtbl_arylen:
3067 result = &PL_vtbl_arylen;
3069 case want_vtbl_glob:
3070 result = &PL_vtbl_glob;
3072 case want_vtbl_mglob:
3073 result = &PL_vtbl_mglob;
3075 case want_vtbl_nkeys:
3076 result = &PL_vtbl_nkeys;
3078 case want_vtbl_taint:
3079 result = &PL_vtbl_taint;
3081 case want_vtbl_substr:
3082 result = &PL_vtbl_substr;
3085 result = &PL_vtbl_vec;
3088 result = &PL_vtbl_pos;
3091 result = &PL_vtbl_bm;
3094 result = &PL_vtbl_fm;
3096 case want_vtbl_uvar:
3097 result = &PL_vtbl_uvar;
3100 case want_vtbl_mutex:
3101 result = &PL_vtbl_mutex;
3104 case want_vtbl_defelem:
3105 result = &PL_vtbl_defelem;
3107 case want_vtbl_regexp:
3108 result = &PL_vtbl_regexp;
3110 case want_vtbl_regdata:
3111 result = &PL_vtbl_regdata;
3113 case want_vtbl_regdatum:
3114 result = &PL_vtbl_regdatum;
3116 #ifdef USE_LOCALE_COLLATE
3117 case want_vtbl_collxfrm:
3118 result = &PL_vtbl_collxfrm;
3121 case want_vtbl_amagic:
3122 result = &PL_vtbl_amagic;
3124 case want_vtbl_amagicelem:
3125 result = &PL_vtbl_amagicelem;