3 * Copyright (c) 1991-2001, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12 * not content." --Gandalf
16 #define PERL_IN_UTIL_C
20 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
25 # define SIG_ERR ((Sighandler_t) -1)
33 /* Put this after #includes because fork and vfork prototypes may
41 # include <sys/wait.h>
52 long xcount[MAXXCOUNT];
53 long lastxcount[MAXXCOUNT];
54 long xycount[MAXXCOUNT][MAXYCOUNT];
55 long lastxycount[MAXXCOUNT][MAXYCOUNT];
59 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
60 # define FD_CLOEXEC 1 /* NeXT needs this */
63 /* paranoid version of system's malloc() */
65 /* NOTE: Do not call the next three routines directly. Use the macros
66 * in handy.h, so that we can easily redefine everything to do tracking of
67 * allocated hunks back to the original New to track down any memory leaks.
68 * XXX This advice seems to be widely ignored :-( --AD August 1996.
72 Perl_safesysmalloc(MEM_SIZE size)
78 PerlIO_printf(Perl_error_log,
79 "Allocation too large: %lx\n", size) FLUSH;
82 #endif /* HAS_64K_LIMIT */
85 Perl_croak_nocontext("panic: malloc");
87 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
88 PERL_ALLOC_CHECK(ptr);
89 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
95 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
102 /* paranoid version of system's realloc() */
105 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
109 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
110 Malloc_t PerlMem_realloc();
111 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
115 PerlIO_printf(Perl_error_log,
116 "Reallocation too large: %lx\n", size) FLUSH;
119 #endif /* HAS_64K_LIMIT */
126 return safesysmalloc(size);
129 Perl_croak_nocontext("panic: realloc");
131 ptr = (Malloc_t)PerlMem_realloc(where,size);
132 PERL_ALLOC_CHECK(ptr);
134 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
135 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
142 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
149 /* safe version of system's free() */
152 Perl_safesysfree(Malloc_t where)
154 #ifdef PERL_IMPLICIT_SYS
157 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
164 /* safe version of system's calloc() */
167 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
173 if (size * count > 0xffff) {
174 PerlIO_printf(Perl_error_log,
175 "Allocation too large: %lx\n", size * count) FLUSH;
178 #endif /* HAS_64K_LIMIT */
180 if ((long)size < 0 || (long)count < 0)
181 Perl_croak_nocontext("panic: calloc");
184 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
185 PERL_ALLOC_CHECK(ptr);
186 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
188 memset((void*)ptr, 0, size);
194 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
203 struct mem_test_strut {
211 # define ALIGN sizeof(struct mem_test_strut)
213 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
214 # define typeof_chunk(ch) \
215 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
216 # define set_typeof_chunk(ch,t) \
217 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
218 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
221 ? ((size) - 1)/8 + 5 \
225 Perl_safexmalloc(I32 x, MEM_SIZE size)
227 register char* where = (char*)safemalloc(size + ALIGN);
230 xycount[x][SIZE_TO_Y(size)]++;
231 set_typeof_chunk(where, x);
232 sizeof_chunk(where) = size;
233 return (Malloc_t)(where + ALIGN);
237 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
239 char *where = (char*)wh;
242 return safexmalloc(0,size);
245 MEM_SIZE old = sizeof_chunk(where - ALIGN);
246 int t = typeof_chunk(where - ALIGN);
247 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
249 xycount[t][SIZE_TO_Y(old)]--;
250 xycount[t][SIZE_TO_Y(size)]++;
251 xcount[t] += size - old;
252 sizeof_chunk(new) = size;
253 return (Malloc_t)(new + ALIGN);
258 Perl_safexfree(Malloc_t wh)
261 char *where = (char*)wh;
267 size = sizeof_chunk(where);
268 x = where[0] + 100 * where[1];
270 xycount[x][SIZE_TO_Y(size)]--;
275 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
277 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
279 xycount[x][SIZE_TO_Y(size)]++;
280 memset((void*)(where + ALIGN), 0, size * count);
281 set_typeof_chunk(where, x);
282 sizeof_chunk(where) = size;
283 return (Malloc_t)(where + ALIGN);
287 S_xstat(pTHX_ int flag)
289 register I32 i, j, total = 0;
290 I32 subtot[MAXYCOUNT];
292 for (j = 0; j < MAXYCOUNT; j++) {
296 PerlIO_printf(Perl_debug_log, " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
297 for (i = 0; i < MAXXCOUNT; i++) {
299 for (j = 0; j < MAXYCOUNT; j++) {
300 subtot[j] += xycount[i][j];
303 ? xcount[i] /* Have something */
305 ? xcount[i] != lastxcount[i] /* Changed */
306 : xcount[i] > lastxcount[i])) { /* Growed */
307 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
308 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
309 lastxcount[i] = xcount[i];
310 for (j = 0; j < MAXYCOUNT; j++) {
312 ? xycount[i][j] /* Have something */
314 ? xycount[i][j] != lastxycount[i][j] /* Changed */
315 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
316 PerlIO_printf(Perl_debug_log,"%3ld ",
318 ? xycount[i][j] - lastxycount[i][j]
320 lastxycount[i][j] = xycount[i][j];
322 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
325 PerlIO_printf(Perl_debug_log, "\n");
329 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
330 for (j = 0; j < MAXYCOUNT; j++) {
332 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
334 PerlIO_printf(Perl_debug_log, " . ");
337 PerlIO_printf(Perl_debug_log, "\n");
341 #endif /* LEAKTEST */
343 /* copy a string up to some (non-backslashed) delimiter, if any */
346 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
349 for (tolen = 0; from < fromend; from++, tolen++) {
351 if (from[1] == delim)
360 else if (*from == delim)
371 /* return ptr to little string in big string, NULL if not found */
372 /* This routine was donated by Corey Satten. */
375 Perl_instr(pTHX_ register const char *big, register const char *little)
377 register const char *s, *x;
388 for (x=big,s=little; *s; /**/ ) {
397 return (char*)(big-1);
402 /* same as instr but allow embedded nulls */
405 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
407 register const char *s, *x;
408 register I32 first = *little;
409 register const char *littleend = lend;
411 if (!first && little >= littleend)
413 if (bigend - big < littleend - little)
415 bigend -= littleend - little++;
416 while (big <= bigend) {
419 for (x=big,s=little; s < littleend; /**/ ) {
426 return (char*)(big-1);
431 /* reverse of the above--find last substring */
434 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
436 register const char *bigbeg;
437 register const char *s, *x;
438 register I32 first = *little;
439 register const char *littleend = lend;
441 if (!first && little >= littleend)
442 return (char*)bigend;
444 big = bigend - (littleend - little++);
445 while (big >= bigbeg) {
448 for (x=big+2,s=little; s < littleend; /**/ ) {
455 return (char*)(big+1);
461 * Set up for a new ctype locale.
464 Perl_new_ctype(pTHX_ char *newctype)
466 #ifdef USE_LOCALE_CTYPE
470 for (i = 0; i < 256; i++) {
472 PL_fold_locale[i] = toLOWER_LC(i);
473 else if (isLOWER_LC(i))
474 PL_fold_locale[i] = toUPPER_LC(i);
476 PL_fold_locale[i] = i;
479 #endif /* USE_LOCALE_CTYPE */
483 * Standardize the locale name from a string returned by 'setlocale'.
485 * The standard return value of setlocale() is either
486 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
487 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
488 * (the space-separated values represent the various sublocales,
489 * in some unspecificed order)
491 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
492 * which is harmful for further use of the string in setlocale().
496 S_stdize_locale(pTHX_ char *locs)
501 if ((s = strchr(locs, '='))) {
505 if ((t = strchr(s, '.'))) {
508 if ((u = strchr(t, '\n'))) {
512 Move(s + 1, locs, len, char);
521 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
527 * Set up for a new collation locale.
530 Perl_new_collate(pTHX_ char *newcoll)
532 #ifdef USE_LOCALE_COLLATE
535 if (PL_collation_name) {
537 Safefree(PL_collation_name);
538 PL_collation_name = NULL;
540 PL_collation_standard = TRUE;
541 PL_collxfrm_base = 0;
542 PL_collxfrm_mult = 2;
546 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
548 Safefree(PL_collation_name);
549 PL_collation_name = stdize_locale(savepv(newcoll));
550 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
553 /* 2: at most so many chars ('a', 'b'). */
554 /* 50: surely no system expands a char more. */
555 #define XFRMBUFSIZE (2 * 50)
556 char xbuf[XFRMBUFSIZE];
557 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
558 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
559 SSize_t mult = fb - fa;
561 Perl_croak(aTHX_ "strxfrm() gets absurd");
562 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
563 PL_collxfrm_mult = mult;
567 #endif /* USE_LOCALE_COLLATE */
571 Perl_set_numeric_radix(pTHX)
573 #ifdef USE_LOCALE_NUMERIC
574 # ifdef HAS_LOCALECONV
578 if (lc && lc->decimal_point) {
579 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
580 SvREFCNT_dec(PL_numeric_radix);
581 PL_numeric_radix = 0;
584 if (PL_numeric_radix)
585 sv_setpv(PL_numeric_radix, lc->decimal_point);
587 PL_numeric_radix = newSVpv(lc->decimal_point, 0);
591 PL_numeric_radix = 0;
592 # endif /* HAS_LOCALECONV */
593 #endif /* USE_LOCALE_NUMERIC */
597 * Set up for a new numeric locale.
600 Perl_new_numeric(pTHX_ char *newnum)
602 #ifdef USE_LOCALE_NUMERIC
605 if (PL_numeric_name) {
606 Safefree(PL_numeric_name);
607 PL_numeric_name = NULL;
609 PL_numeric_standard = TRUE;
610 PL_numeric_local = TRUE;
614 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
615 Safefree(PL_numeric_name);
616 PL_numeric_name = stdize_locale(savepv(newnum));
617 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
618 PL_numeric_local = TRUE;
622 #endif /* USE_LOCALE_NUMERIC */
626 Perl_set_numeric_standard(pTHX)
628 #ifdef USE_LOCALE_NUMERIC
630 if (! PL_numeric_standard) {
631 setlocale(LC_NUMERIC, "C");
632 PL_numeric_standard = TRUE;
633 PL_numeric_local = FALSE;
637 #endif /* USE_LOCALE_NUMERIC */
641 Perl_set_numeric_local(pTHX)
643 #ifdef USE_LOCALE_NUMERIC
645 if (! PL_numeric_local) {
646 setlocale(LC_NUMERIC, PL_numeric_name);
647 PL_numeric_standard = FALSE;
648 PL_numeric_local = TRUE;
652 #endif /* USE_LOCALE_NUMERIC */
656 * Initialize locale awareness.
659 Perl_init_i18nl10n(pTHX_ int printwarn)
663 * 1 = set ok or not applicable,
664 * 0 = fallback to C locale,
665 * -1 = fallback to C locale failed
670 #ifdef USE_LOCALE_CTYPE
671 char *curctype = NULL;
672 #endif /* USE_LOCALE_CTYPE */
673 #ifdef USE_LOCALE_COLLATE
674 char *curcoll = NULL;
675 #endif /* USE_LOCALE_COLLATE */
676 #ifdef USE_LOCALE_NUMERIC
678 #endif /* USE_LOCALE_NUMERIC */
680 char *language = PerlEnv_getenv("LANGUAGE");
682 char *lc_all = PerlEnv_getenv("LC_ALL");
683 char *lang = PerlEnv_getenv("LANG");
684 bool setlocale_failure = FALSE;
686 #ifdef LOCALE_ENVIRON_REQUIRED
689 * Ultrix setlocale(..., "") fails if there are no environment
690 * variables from which to get a locale name.
697 if (setlocale(LC_ALL, ""))
700 setlocale_failure = TRUE;
702 if (!setlocale_failure) {
703 #ifdef USE_LOCALE_CTYPE
706 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
708 setlocale_failure = TRUE;
710 curctype = savepv(curctype);
711 #endif /* USE_LOCALE_CTYPE */
712 #ifdef USE_LOCALE_COLLATE
714 setlocale(LC_COLLATE,
715 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
717 setlocale_failure = TRUE;
719 curcoll = savepv(curcoll);
720 #endif /* USE_LOCALE_COLLATE */
721 #ifdef USE_LOCALE_NUMERIC
723 setlocale(LC_NUMERIC,
724 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
726 setlocale_failure = TRUE;
728 curnum = savepv(curnum);
729 #endif /* USE_LOCALE_NUMERIC */
734 #endif /* !LOCALE_ENVIRON_REQUIRED */
737 if (! setlocale(LC_ALL, ""))
738 setlocale_failure = TRUE;
741 if (!setlocale_failure) {
742 #ifdef USE_LOCALE_CTYPE
743 if (! (curctype = setlocale(LC_CTYPE, "")))
744 setlocale_failure = TRUE;
746 curctype = savepv(curctype);
747 #endif /* USE_LOCALE_CTYPE */
748 #ifdef USE_LOCALE_COLLATE
749 if (! (curcoll = setlocale(LC_COLLATE, "")))
750 setlocale_failure = TRUE;
752 curcoll = savepv(curcoll);
753 #endif /* USE_LOCALE_COLLATE */
754 #ifdef USE_LOCALE_NUMERIC
755 if (! (curnum = setlocale(LC_NUMERIC, "")))
756 setlocale_failure = TRUE;
758 curnum = savepv(curnum);
759 #endif /* USE_LOCALE_NUMERIC */
762 if (setlocale_failure) {
764 bool locwarn = (printwarn > 1 ||
766 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
771 PerlIO_printf(Perl_error_log,
772 "perl: warning: Setting locale failed.\n");
776 PerlIO_printf(Perl_error_log,
777 "perl: warning: Setting locale failed for the categories:\n\t");
778 #ifdef USE_LOCALE_CTYPE
780 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
781 #endif /* USE_LOCALE_CTYPE */
782 #ifdef USE_LOCALE_COLLATE
784 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
785 #endif /* USE_LOCALE_COLLATE */
786 #ifdef USE_LOCALE_NUMERIC
788 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
789 #endif /* USE_LOCALE_NUMERIC */
790 PerlIO_printf(Perl_error_log, "\n");
794 PerlIO_printf(Perl_error_log,
795 "perl: warning: Please check that your locale settings:\n");
798 PerlIO_printf(Perl_error_log,
799 "\tLANGUAGE = %c%s%c,\n",
800 language ? '"' : '(',
801 language ? language : "unset",
802 language ? '"' : ')');
805 PerlIO_printf(Perl_error_log,
806 "\tLC_ALL = %c%s%c,\n",
808 lc_all ? lc_all : "unset",
813 for (e = environ; *e; e++) {
814 if (strnEQ(*e, "LC_", 3)
815 && strnNE(*e, "LC_ALL=", 7)
816 && (p = strchr(*e, '=')))
817 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
818 (int)(p - *e), *e, p + 1);
822 PerlIO_printf(Perl_error_log,
825 lang ? lang : "unset",
828 PerlIO_printf(Perl_error_log,
829 " are supported and installed on your system.\n");
834 if (setlocale(LC_ALL, "C")) {
836 PerlIO_printf(Perl_error_log,
837 "perl: warning: Falling back to the standard locale (\"C\").\n");
842 PerlIO_printf(Perl_error_log,
843 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
850 #ifdef USE_LOCALE_CTYPE
851 || !(curctype || setlocale(LC_CTYPE, "C"))
852 #endif /* USE_LOCALE_CTYPE */
853 #ifdef USE_LOCALE_COLLATE
854 || !(curcoll || setlocale(LC_COLLATE, "C"))
855 #endif /* USE_LOCALE_COLLATE */
856 #ifdef USE_LOCALE_NUMERIC
857 || !(curnum || setlocale(LC_NUMERIC, "C"))
858 #endif /* USE_LOCALE_NUMERIC */
862 PerlIO_printf(Perl_error_log,
863 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
867 #endif /* ! LC_ALL */
869 #ifdef USE_LOCALE_CTYPE
870 curctype = savepv(setlocale(LC_CTYPE, Nullch));
871 #endif /* USE_LOCALE_CTYPE */
872 #ifdef USE_LOCALE_COLLATE
873 curcoll = savepv(setlocale(LC_COLLATE, Nullch));
874 #endif /* USE_LOCALE_COLLATE */
875 #ifdef USE_LOCALE_NUMERIC
876 curnum = savepv(setlocale(LC_NUMERIC, Nullch));
877 #endif /* USE_LOCALE_NUMERIC */
881 #ifdef USE_LOCALE_CTYPE
883 #endif /* USE_LOCALE_CTYPE */
885 #ifdef USE_LOCALE_COLLATE
886 new_collate(curcoll);
887 #endif /* USE_LOCALE_COLLATE */
889 #ifdef USE_LOCALE_NUMERIC
891 #endif /* USE_LOCALE_NUMERIC */
894 #endif /* USE_LOCALE */
896 #ifdef USE_LOCALE_CTYPE
897 if (curctype != NULL)
899 #endif /* USE_LOCALE_CTYPE */
900 #ifdef USE_LOCALE_COLLATE
903 #endif /* USE_LOCALE_COLLATE */
904 #ifdef USE_LOCALE_NUMERIC
907 #endif /* USE_LOCALE_NUMERIC */
911 /* Backwards compatibility. */
913 Perl_init_i18nl14n(pTHX_ int printwarn)
915 return init_i18nl10n(printwarn);
918 #ifdef USE_LOCALE_COLLATE
921 * mem_collxfrm() is a bit like strxfrm() but with two important
922 * differences. First, it handles embedded NULs. Second, it allocates
923 * a bit more memory than needed for the transformed data itself.
924 * The real transformed data begins at offset sizeof(collationix).
925 * Please see sv_collxfrm() to see how this is used.
928 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
931 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
933 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
934 /* the +1 is for the terminating NUL. */
936 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
937 New(171, xbuf, xAlloc, char);
941 *(U32*)xbuf = PL_collation_ix;
942 xout = sizeof(PL_collation_ix);
943 for (xin = 0; xin < len; ) {
947 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
950 if (xused < xAlloc - xout)
952 xAlloc = (2 * xAlloc) + 1;
953 Renew(xbuf, xAlloc, char);
958 xin += strlen(s + xin) + 1;
961 /* Embedded NULs are understood but silently skipped
962 * because they make no sense in locale collation. */
966 *xlen = xout - sizeof(PL_collation_ix);
975 #endif /* USE_LOCALE_COLLATE */
977 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
979 /* As a space optimization, we do not compile tables for strings of length
980 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
981 special-cased in fbm_instr().
983 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
986 =for apidoc fbm_compile
988 Analyses the string in order to make fast searches on it using fbm_instr()
989 -- the Boyer-Moore algorithm.
995 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
1002 U32 frequency = 256;
1004 if (flags & FBMcf_TAIL)
1005 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
1006 s = (U8*)SvPV_force(sv, len);
1007 (void)SvUPGRADE(sv, SVt_PVBM);
1008 if (len == 0) /* TAIL might be on on a zero-length string. */
1018 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
1019 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
1020 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
1021 memset((void*)table, mlen, 256);
1022 table[-1] = (U8)flags;
1024 sb = s - mlen + 1; /* first char (maybe) */
1026 if (table[*s] == mlen)
1031 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
1034 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
1035 for (i = 0; i < len; i++) {
1036 if (PL_freq[s[i]] < frequency) {
1038 frequency = PL_freq[s[i]];
1041 BmRARE(sv) = s[rarest];
1042 BmPREVIOUS(sv) = rarest;
1043 BmUSEFUL(sv) = 100; /* Initial value */
1044 if (flags & FBMcf_TAIL)
1046 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
1047 BmRARE(sv),BmPREVIOUS(sv)));
1050 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
1051 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1055 =for apidoc fbm_instr
1057 Returns the location of the SV in the string delimited by C<str> and
1058 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
1059 does not have to be fbm_compiled, but the search will not be as fast
1066 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
1068 register unsigned char *s;
1070 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
1071 register STRLEN littlelen = l;
1072 register I32 multiline = flags & FBMrf_MULTILINE;
1074 if (bigend - big < littlelen) {
1075 if ( SvTAIL(littlestr)
1076 && (bigend - big == littlelen - 1)
1078 || (*big == *little &&
1079 memEQ((char *)big, (char *)little, littlelen - 1))))
1084 if (littlelen <= 2) { /* Special-cased */
1086 if (littlelen == 1) {
1087 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1088 /* Know that bigend != big. */
1089 if (bigend[-1] == '\n')
1090 return (char *)(bigend - 1);
1091 return (char *) bigend;
1094 while (s < bigend) {
1099 if (SvTAIL(littlestr))
1100 return (char *) bigend;
1104 return (char*)big; /* Cannot be SvTAIL! */
1106 /* littlelen is 2 */
1107 if (SvTAIL(littlestr) && !multiline) {
1108 if (bigend[-1] == '\n' && bigend[-2] == *little)
1109 return (char*)bigend - 2;
1110 if (bigend[-1] == *little)
1111 return (char*)bigend - 1;
1115 /* This should be better than FBM if c1 == c2, and almost
1116 as good otherwise: maybe better since we do less indirection.
1117 And we save a lot of memory by caching no table. */
1118 register unsigned char c1 = little[0];
1119 register unsigned char c2 = little[1];
1124 while (s <= bigend) {
1127 return (char*)s - 1;
1134 goto check_1char_anchor;
1145 goto check_1char_anchor;
1148 while (s <= bigend) {
1151 return (char*)s - 1;
1153 goto check_1char_anchor;
1162 check_1char_anchor: /* One char and anchor! */
1163 if (SvTAIL(littlestr) && (*bigend == *little))
1164 return (char *)bigend; /* bigend is already decremented. */
1167 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1168 s = bigend - littlelen;
1169 if (s >= big && bigend[-1] == '\n' && *s == *little
1170 /* Automatically of length > 2 */
1171 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1173 return (char*)s; /* how sweet it is */
1176 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1178 return (char*)s + 1; /* how sweet it is */
1182 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1183 char *b = ninstr((char*)big,(char*)bigend,
1184 (char*)little, (char*)little + littlelen);
1186 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1187 /* Chop \n from littlestr: */
1188 s = bigend - littlelen + 1;
1190 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1199 { /* Do actual FBM. */
1200 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1201 register unsigned char *oldlittle;
1203 if (littlelen > bigend - big)
1205 --littlelen; /* Last char found by table lookup */
1207 s = big + littlelen;
1208 little += littlelen; /* last char */
1215 if ((tmp = table[*s])) {
1217 if (bigend - s > tmp) {
1223 if ((s += tmp) < bigend)
1228 else { /* less expensive than calling strncmp() */
1229 register unsigned char *olds = s;
1234 if (*--s == *--little)
1236 s = olds + 1; /* here we pay the price for failure */
1238 if (s < bigend) /* fake up continue to outer loop */
1246 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1247 && memEQ((char *)(bigend - littlelen),
1248 (char *)(oldlittle - littlelen), littlelen) )
1249 return (char*)bigend - littlelen;
1254 /* start_shift, end_shift are positive quantities which give offsets
1255 of ends of some substring of bigstr.
1256 If `last' we want the last occurence.
1257 old_posp is the way of communication between consequent calls if
1258 the next call needs to find the .
1259 The initial *old_posp should be -1.
1261 Note that we take into account SvTAIL, so one can get extra
1262 optimizations if _ALL flag is set.
1265 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1266 if PL_multiline. In fact if !PL_multiline the autoritative answer
1267 is not supported yet. */
1270 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1272 register unsigned char *s, *x;
1273 register unsigned char *big;
1275 register I32 previous;
1277 register unsigned char *little;
1278 register I32 stop_pos;
1279 register unsigned char *littleend;
1283 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1284 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1286 if ( BmRARE(littlestr) == '\n'
1287 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1288 little = (unsigned char *)(SvPVX(littlestr));
1289 littleend = little + SvCUR(littlestr);
1296 little = (unsigned char *)(SvPVX(littlestr));
1297 littleend = little + SvCUR(littlestr);
1299 /* The value of pos we can start at: */
1300 previous = BmPREVIOUS(littlestr);
1301 big = (unsigned char *)(SvPVX(bigstr));
1302 /* The value of pos we can stop at: */
1303 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1304 if (previous + start_shift > stop_pos) {
1305 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1309 while (pos < previous + start_shift) {
1310 if (!(pos += PL_screamnext[pos]))
1315 if (pos >= stop_pos) break;
1316 if (big[pos-previous] != first)
1318 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1324 if (s == littleend) {
1326 if (!last) return (char *)(big+pos-previous);
1329 } while ( pos += PL_screamnext[pos] );
1330 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1331 #else /* !POINTERRIGOR */
1334 if (pos >= stop_pos) break;
1335 if (big[pos] != first)
1337 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1343 if (s == littleend) {
1345 if (!last) return (char *)(big+pos);
1348 } while ( pos += PL_screamnext[pos] );
1350 return (char *)(big+(*old_posp));
1351 #endif /* POINTERRIGOR */
1353 if (!SvTAIL(littlestr) || (end_shift > 0))
1355 /* Ignore the trailing "\n". This code is not microoptimized */
1356 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1357 stop_pos = littleend - little; /* Actual littlestr len */
1362 && ((stop_pos == 1) ||
1363 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1369 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1371 register U8 *a = (U8 *)s1;
1372 register U8 *b = (U8 *)s2;
1374 if (*a != *b && *a != PL_fold[*b])
1382 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1384 register U8 *a = (U8 *)s1;
1385 register U8 *b = (U8 *)s2;
1387 if (*a != *b && *a != PL_fold_locale[*b])
1394 /* copy a string to a safe spot */
1399 Copy a string to a safe spot. This does not use an SV.
1405 Perl_savepv(pTHX_ const char *sv)
1407 register char *newaddr;
1409 New(902,newaddr,strlen(sv)+1,char);
1410 (void)strcpy(newaddr,sv);
1414 /* same thing but with a known length */
1419 Copy a string to a safe spot. The C<len> indicates number of bytes to
1420 copy. This does not use an SV.
1426 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1428 register char *newaddr;
1430 New(903,newaddr,len+1,char);
1431 Copy(sv,newaddr,len,char); /* might not be null terminated */
1432 newaddr[len] = '\0'; /* is now */
1436 /* the SV for Perl_form() and mess() is not kept in an arena */
1445 return sv_2mortal(newSVpvn("",0));
1450 /* Create as PVMG now, to avoid any upgrading later */
1451 New(905, sv, 1, SV);
1452 Newz(905, any, 1, XPVMG);
1453 SvFLAGS(sv) = SVt_PVMG;
1454 SvANY(sv) = (void*)any;
1455 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1460 #if defined(PERL_IMPLICIT_CONTEXT)
1462 Perl_form_nocontext(const char* pat, ...)
1467 va_start(args, pat);
1468 retval = vform(pat, &args);
1472 #endif /* PERL_IMPLICIT_CONTEXT */
1475 Perl_form(pTHX_ const char* pat, ...)
1479 va_start(args, pat);
1480 retval = vform(pat, &args);
1486 Perl_vform(pTHX_ const char *pat, va_list *args)
1488 SV *sv = mess_alloc();
1489 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1493 #if defined(PERL_IMPLICIT_CONTEXT)
1495 Perl_mess_nocontext(const char *pat, ...)
1500 va_start(args, pat);
1501 retval = vmess(pat, &args);
1505 #endif /* PERL_IMPLICIT_CONTEXT */
1508 Perl_mess(pTHX_ const char *pat, ...)
1512 va_start(args, pat);
1513 retval = vmess(pat, &args);
1519 Perl_vmess(pTHX_ const char *pat, va_list *args)
1521 SV *sv = mess_alloc();
1522 static char dgd[] = " during global destruction.\n";
1524 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1525 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1526 if (CopLINE(PL_curcop))
1527 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1528 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1529 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1530 bool line_mode = (RsSIMPLE(PL_rs) &&
1531 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1532 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1533 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1534 line_mode ? "line" : "chunk",
1535 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1539 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1541 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1547 Perl_vdie(pTHX_ const char* pat, va_list *args)
1550 int was_in_eval = PL_in_eval;
1557 DEBUG_S(PerlIO_printf(Perl_debug_log,
1558 "%p: die: curstack = %p, mainstack = %p\n",
1559 thr, PL_curstack, PL_mainstack));
1562 msv = vmess(pat, args);
1563 if (PL_errors && SvCUR(PL_errors)) {
1564 sv_catsv(PL_errors, msv);
1565 message = SvPV(PL_errors, msglen);
1566 SvCUR_set(PL_errors, 0);
1569 message = SvPV(msv,msglen);
1576 DEBUG_S(PerlIO_printf(Perl_debug_log,
1577 "%p: die: message = %s\ndiehook = %p\n",
1578 thr, message, PL_diehook));
1580 /* sv_2cv might call Perl_croak() */
1581 SV *olddiehook = PL_diehook;
1583 SAVESPTR(PL_diehook);
1584 PL_diehook = Nullsv;
1585 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1587 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1594 msg = newSVpvn(message, msglen);
1602 PUSHSTACKi(PERLSI_DIEHOOK);
1606 call_sv((SV*)cv, G_DISCARD);
1612 PL_restartop = die_where(message, msglen);
1613 DEBUG_S(PerlIO_printf(Perl_debug_log,
1614 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1615 thr, PL_restartop, was_in_eval, PL_top_env));
1616 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1618 return PL_restartop;
1621 #if defined(PERL_IMPLICIT_CONTEXT)
1623 Perl_die_nocontext(const char* pat, ...)
1628 va_start(args, pat);
1629 o = vdie(pat, &args);
1633 #endif /* PERL_IMPLICIT_CONTEXT */
1636 Perl_die(pTHX_ const char* pat, ...)
1640 va_start(args, pat);
1641 o = vdie(pat, &args);
1647 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1657 msv = vmess(pat, args);
1658 if (PL_errors && SvCUR(PL_errors)) {
1659 sv_catsv(PL_errors, msv);
1660 message = SvPV(PL_errors, msglen);
1661 SvCUR_set(PL_errors, 0);
1664 message = SvPV(msv,msglen);
1671 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1672 PTR2UV(thr), message));
1675 /* sv_2cv might call Perl_croak() */
1676 SV *olddiehook = PL_diehook;
1678 SAVESPTR(PL_diehook);
1679 PL_diehook = Nullsv;
1680 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1682 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1689 msg = newSVpvn(message, msglen);
1697 PUSHSTACKi(PERLSI_DIEHOOK);
1701 call_sv((SV*)cv, G_DISCARD);
1707 PL_restartop = die_where(message, msglen);
1712 /* SFIO can really mess with your errno */
1715 PerlIO *serr = Perl_error_log;
1717 PerlIO_write(serr, message, msglen);
1718 (void)PerlIO_flush(serr);
1726 #if defined(PERL_IMPLICIT_CONTEXT)
1728 Perl_croak_nocontext(const char *pat, ...)
1732 va_start(args, pat);
1737 #endif /* PERL_IMPLICIT_CONTEXT */
1742 This is the XSUB-writer's interface to Perl's C<die> function.
1743 Normally use this function the same way you use the C C<printf>
1744 function. See C<warn>.
1746 If you want to throw an exception object, assign the object to
1747 C<$@> and then pass C<Nullch> to croak():
1749 errsv = get_sv("@", TRUE);
1750 sv_setsv(errsv, exception_object);
1757 Perl_croak(pTHX_ const char *pat, ...)
1760 va_start(args, pat);
1767 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1776 msv = vmess(pat, args);
1777 message = SvPV(msv, msglen);
1780 /* sv_2cv might call Perl_warn() */
1781 SV *oldwarnhook = PL_warnhook;
1783 SAVESPTR(PL_warnhook);
1784 PL_warnhook = Nullsv;
1785 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1787 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1793 msg = newSVpvn(message, msglen);
1797 PUSHSTACKi(PERLSI_WARNHOOK);
1801 call_sv((SV*)cv, G_DISCARD);
1808 PerlIO *serr = Perl_error_log;
1810 PerlIO_write(serr, message, msglen);
1812 DEBUG_L(*message == '!'
1813 ? (xstat(message[1]=='!'
1814 ? (message[2]=='!' ? 2 : 1)
1819 (void)PerlIO_flush(serr);
1823 #if defined(PERL_IMPLICIT_CONTEXT)
1825 Perl_warn_nocontext(const char *pat, ...)
1829 va_start(args, pat);
1833 #endif /* PERL_IMPLICIT_CONTEXT */
1838 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1839 function the same way you use the C C<printf> function. See
1846 Perl_warn(pTHX_ const char *pat, ...)
1849 va_start(args, pat);
1854 #if defined(PERL_IMPLICIT_CONTEXT)
1856 Perl_warner_nocontext(U32 err, const char *pat, ...)
1860 va_start(args, pat);
1861 vwarner(err, pat, &args);
1864 #endif /* PERL_IMPLICIT_CONTEXT */
1867 Perl_warner(pTHX_ U32 err, const char* pat,...)
1870 va_start(args, pat);
1871 vwarner(err, pat, &args);
1876 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1885 msv = vmess(pat, args);
1886 message = SvPV(msv, msglen);
1890 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1891 #endif /* USE_THREADS */
1893 /* sv_2cv might call Perl_croak() */
1894 SV *olddiehook = PL_diehook;
1896 SAVESPTR(PL_diehook);
1897 PL_diehook = Nullsv;
1898 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1900 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1906 msg = newSVpvn(message, msglen);
1910 PUSHSTACKi(PERLSI_DIEHOOK);
1914 call_sv((SV*)cv, G_DISCARD);
1920 PL_restartop = die_where(message, msglen);
1924 PerlIO *serr = Perl_error_log;
1925 PerlIO_write(serr, message, msglen);
1926 (void)PerlIO_flush(serr);
1933 /* sv_2cv might call Perl_warn() */
1934 SV *oldwarnhook = PL_warnhook;
1936 SAVESPTR(PL_warnhook);
1937 PL_warnhook = Nullsv;
1938 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1940 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1946 msg = newSVpvn(message, msglen);
1950 PUSHSTACKi(PERLSI_WARNHOOK);
1954 call_sv((SV*)cv, G_DISCARD);
1961 PerlIO *serr = Perl_error_log;
1962 PerlIO_write(serr, message, msglen);
1964 DEBUG_L(*message == '!'
1965 ? (xstat(message[1]=='!'
1966 ? (message[2]=='!' ? 2 : 1)
1971 (void)PerlIO_flush(serr);
1976 #ifdef USE_ENVIRON_ARRAY
1977 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1980 Perl_my_setenv(pTHX_ char *nam, char *val)
1982 #ifndef PERL_USE_SAFE_PUTENV
1983 /* most putenv()s leak, so we manipulate environ directly */
1984 register I32 i=setenv_getix(nam); /* where does it go? */
1986 if (environ == PL_origenviron) { /* need we copy environment? */
1992 for (max = i; environ[max]; max++) ;
1993 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1994 for (j=0; j<max; j++) { /* copy environment */
1995 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1996 strcpy(tmpenv[j], environ[j]);
1998 tmpenv[max] = Nullch;
1999 environ = tmpenv; /* tell exec where it is now */
2002 safesysfree(environ[i]);
2003 while (environ[i]) {
2004 environ[i] = environ[i+1];
2009 if (!environ[i]) { /* does not exist yet */
2010 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2011 environ[i+1] = Nullch; /* make sure it's null terminated */
2014 safesysfree(environ[i]);
2015 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
2017 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
2019 #else /* PERL_USE_SAFE_PUTENV */
2020 # if defined(__CYGWIN__)
2021 setenv(nam, val, 1);
2025 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
2026 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
2027 (void)putenv(new_env);
2028 # endif /* __CYGWIN__ */
2029 #endif /* PERL_USE_SAFE_PUTENV */
2035 Perl_my_setenv(pTHX_ char *nam,char *val)
2038 #ifdef USE_WIN32_RTL_ENV
2040 register char *envstr;
2041 STRLEN namlen = strlen(nam);
2043 char *oldstr = environ[setenv_getix(nam)];
2045 /* putenv() has totally broken semantics in both the Borland
2046 * and Microsoft CRTLs. They either store the passed pointer in
2047 * the environment without making a copy, or make a copy and don't
2048 * free it. And on top of that, they dont free() old entries that
2049 * are being replaced/deleted. This means the caller must
2050 * free any old entries somehow, or we end up with a memory
2051 * leak every time my_setenv() is called. One might think
2052 * one could directly manipulate environ[], like the UNIX code
2053 * above, but direct changes to environ are not allowed when
2054 * calling putenv(), since the RTLs maintain an internal
2055 * *copy* of environ[]. Bad, bad, *bad* stink.
2066 vallen = strlen(val);
2067 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
2068 (void)sprintf(envstr,"%s=%s",nam,val);
2069 (void)PerlEnv_putenv(envstr);
2071 safesysfree(oldstr);
2073 safesysfree(envstr); /* MSVCRT leaks without this */
2076 #else /* !USE_WIN32_RTL_ENV */
2078 register char *envstr;
2079 STRLEN len = strlen(nam) + 3;
2084 New(904, envstr, len, char);
2085 (void)sprintf(envstr,"%s=%s",nam,val);
2086 (void)PerlEnv_putenv(envstr);
2095 Perl_setenv_getix(pTHX_ char *nam)
2097 register I32 i, len = strlen(nam);
2099 for (i = 0; environ[i]; i++) {
2102 strnicmp(environ[i],nam,len) == 0
2104 strnEQ(environ[i],nam,len)
2106 && environ[i][len] == '=')
2107 break; /* strnEQ must come first to avoid */
2108 } /* potential SEGV's */
2112 #endif /* !VMS && !EPOC*/
2114 #ifdef UNLINK_ALL_VERSIONS
2116 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2120 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2125 /* this is a drop-in replacement for bcopy() */
2126 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2128 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2132 if (from - to >= 0) {
2140 *(--to) = *(--from);
2146 /* this is a drop-in replacement for memset() */
2149 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2159 /* this is a drop-in replacement for bzero() */
2160 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2162 Perl_my_bzero(register char *loc, register I32 len)
2172 /* this is a drop-in replacement for memcmp() */
2173 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2175 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2177 register U8 *a = (U8 *)s1;
2178 register U8 *b = (U8 *)s2;
2182 if (tmp = *a++ - *b++)
2187 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2191 #ifdef USE_CHAR_VSPRINTF
2196 vsprintf(char *dest, const char *pat, char *args)
2200 fakebuf._ptr = dest;
2201 fakebuf._cnt = 32767;
2205 fakebuf._flag = _IOWRT|_IOSTRG;
2206 _doprnt(pat, args, &fakebuf); /* what a kludge */
2207 (void)putc('\0', &fakebuf);
2208 #ifdef USE_CHAR_VSPRINTF
2211 return 0; /* perl doesn't use return value */
2215 #endif /* HAS_VPRINTF */
2218 #if BYTEORDER != 0x4321
2220 Perl_my_swap(pTHX_ short s)
2222 #if (BYTEORDER & 1) == 0
2225 result = ((s & 255) << 8) + ((s >> 8) & 255);
2233 Perl_my_htonl(pTHX_ long l)
2237 char c[sizeof(long)];
2240 #if BYTEORDER == 0x1234
2241 u.c[0] = (l >> 24) & 255;
2242 u.c[1] = (l >> 16) & 255;
2243 u.c[2] = (l >> 8) & 255;
2247 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2248 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2253 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2254 u.c[o & 0xf] = (l >> s) & 255;
2262 Perl_my_ntohl(pTHX_ long l)
2266 char c[sizeof(long)];
2269 #if BYTEORDER == 0x1234
2270 u.c[0] = (l >> 24) & 255;
2271 u.c[1] = (l >> 16) & 255;
2272 u.c[2] = (l >> 8) & 255;
2276 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2277 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2284 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2285 l |= (u.c[o & 0xf] & 255) << s;
2292 #endif /* BYTEORDER != 0x4321 */
2296 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2297 * If these functions are defined,
2298 * the BYTEORDER is neither 0x1234 nor 0x4321.
2299 * However, this is not assumed.
2303 #define HTOV(name,type) \
2305 name (register type n) \
2309 char c[sizeof(type)]; \
2313 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2314 u.c[i] = (n >> s) & 0xFF; \
2319 #define VTOH(name,type) \
2321 name (register type n) \
2325 char c[sizeof(type)]; \
2331 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2332 n += (u.c[i] & 0xFF) << s; \
2337 #if defined(HAS_HTOVS) && !defined(htovs)
2340 #if defined(HAS_HTOVL) && !defined(htovl)
2343 #if defined(HAS_VTOHS) && !defined(vtohs)
2346 #if defined(HAS_VTOHL) && !defined(vtohl)
2350 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2351 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2353 Perl_my_popen(pTHX_ char *cmd, char *mode)
2356 register I32 This, that;
2359 I32 doexec = strNE(cmd,"-");
2363 PERL_FLUSHALL_FOR_CHILD;
2366 return my_syspopen(aTHX_ cmd,mode);
2369 This = (*mode == 'w');
2371 if (doexec && PL_tainting) {
2373 taint_proper("Insecure %s%s", "EXEC");
2375 if (PerlProc_pipe(p) < 0)
2377 if (doexec && PerlProc_pipe(pp) >= 0)
2379 while ((pid = (doexec?vfork():fork())) < 0) {
2380 if (errno != EAGAIN) {
2381 PerlLIO_close(p[This]);
2383 PerlLIO_close(pp[0]);
2384 PerlLIO_close(pp[1]);
2387 Perl_croak(aTHX_ "Can't fork");
2399 PerlLIO_close(p[THAT]);
2401 PerlLIO_close(pp[0]);
2402 #if defined(HAS_FCNTL) && defined(F_SETFD)
2403 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2406 if (p[THIS] != (*mode == 'r')) {
2407 PerlLIO_dup2(p[THIS], *mode == 'r');
2408 PerlLIO_close(p[THIS]);
2412 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2418 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2422 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2425 #endif /* defined OS2 */
2427 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
2428 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2430 hv_clear(PL_pidstatus); /* we have no children */
2435 do_execfree(); /* free any memory malloced by child on vfork */
2436 PerlLIO_close(p[that]);
2438 PerlLIO_close(pp[1]);
2439 if (p[that] < p[This]) {
2440 PerlLIO_dup2(p[This], p[that]);
2441 PerlLIO_close(p[This]);
2445 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2447 (void)SvUPGRADE(sv,SVt_IV);
2449 PL_forkprocess = pid;
2450 if (did_pipes && pid > 0) {
2454 while (n < sizeof(int)) {
2455 n1 = PerlLIO_read(pp[0],
2456 (void*)(((char*)&errkid)+n),
2462 PerlLIO_close(pp[0]);
2464 if (n) { /* Error */
2466 if (n != sizeof(int))
2467 Perl_croak(aTHX_ "panic: kid popen errno read");
2469 pid2 = wait4pid(pid, &status, 0);
2470 } while (pid2 == -1 && errno == EINTR);
2471 errno = errkid; /* Propagate errno from kid */
2476 PerlLIO_close(pp[0]);
2477 return PerlIO_fdopen(p[This], mode);
2480 #if defined(atarist) || defined(DJGPP)
2483 Perl_my_popen(pTHX_ char *cmd, char *mode)
2485 PERL_FLUSHALL_FOR_CHILD;
2486 /* Call system's popen() to get a FILE *, then import it.
2487 used 0 for 2nd parameter to PerlIO_importFILE;
2490 return PerlIO_importFILE(popen(cmd, mode), 0);
2494 #endif /* !DOSISH */
2498 Perl_dump_fds(pTHX_ char *s)
2501 struct stat tmpstatbuf;
2503 PerlIO_printf(Perl_debug_log,"%s", s);
2504 for (fd = 0; fd < 32; fd++) {
2505 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2506 PerlIO_printf(Perl_debug_log," %d",fd);
2508 PerlIO_printf(Perl_debug_log,"\n");
2510 #endif /* DUMP_FDS */
2514 dup2(int oldfd, int newfd)
2516 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2519 PerlLIO_close(newfd);
2520 return fcntl(oldfd, F_DUPFD, newfd);
2522 #define DUP2_MAX_FDS 256
2523 int fdtmp[DUP2_MAX_FDS];
2529 PerlLIO_close(newfd);
2530 /* good enough for low fd's... */
2531 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2532 if (fdx >= DUP2_MAX_FDS) {
2540 PerlLIO_close(fdtmp[--fdx]);
2547 #ifdef HAS_SIGACTION
2550 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2552 struct sigaction act, oact;
2554 act.sa_handler = handler;
2555 sigemptyset(&act.sa_mask);
2558 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2559 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2563 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2564 act.sa_flags |= SA_NOCLDWAIT;
2566 if (sigaction(signo, &act, &oact) == -1)
2569 return oact.sa_handler;
2573 Perl_rsignal_state(pTHX_ int signo)
2575 struct sigaction oact;
2577 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2580 return oact.sa_handler;
2584 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2586 struct sigaction act;
2588 act.sa_handler = handler;
2589 sigemptyset(&act.sa_mask);
2592 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2593 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2597 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2598 act.sa_flags |= SA_NOCLDWAIT;
2600 return sigaction(signo, &act, save);
2604 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2606 return sigaction(signo, save, (struct sigaction *)NULL);
2609 #else /* !HAS_SIGACTION */
2612 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2614 return PerlProc_signal(signo, handler);
2617 static int sig_trapped;
2627 Perl_rsignal_state(pTHX_ int signo)
2629 Sighandler_t oldsig;
2632 oldsig = PerlProc_signal(signo, sig_trap);
2633 PerlProc_signal(signo, oldsig);
2635 PerlProc_kill(PerlProc_getpid(), signo);
2640 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2642 *save = PerlProc_signal(signo, handler);
2643 return (*save == SIG_ERR) ? -1 : 0;
2647 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2649 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2652 #endif /* !HAS_SIGACTION */
2653 #endif /* !PERL_MICRO */
2655 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2656 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2658 Perl_my_pclose(pTHX_ PerlIO *ptr)
2660 Sigsave_t hstat, istat, qstat;
2668 int saved_vaxc_errno;
2671 int saved_win32_errno;
2675 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2677 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2679 *svp = &PL_sv_undef;
2681 if (pid == -1) { /* Opened by popen. */
2682 return my_syspclose(ptr);
2685 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2686 saved_errno = errno;
2688 saved_vaxc_errno = vaxc$errno;
2691 saved_win32_errno = GetLastError();
2695 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2698 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2699 rsignal_save(SIGINT, SIG_IGN, &istat);
2700 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2703 pid2 = wait4pid(pid, &status, 0);
2704 } while (pid2 == -1 && errno == EINTR);
2706 rsignal_restore(SIGHUP, &hstat);
2707 rsignal_restore(SIGINT, &istat);
2708 rsignal_restore(SIGQUIT, &qstat);
2711 SETERRNO(saved_errno, saved_vaxc_errno);
2714 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2716 #endif /* !DOSISH */
2718 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2720 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2724 char spid[TYPE_CHARS(int)];
2728 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2730 sprintf(spid, "%"IVdf, (IV)pid);
2731 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2732 if (svp && *svp != &PL_sv_undef) {
2733 *statusp = SvIVX(*svp);
2734 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2741 hv_iterinit(PL_pidstatus);
2742 if ((entry = hv_iternext(PL_pidstatus))) {
2743 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2744 sv = hv_iterval(PL_pidstatus,entry);
2745 *statusp = SvIVX(sv);
2746 sprintf(spid, "%"IVdf, (IV)pid);
2747 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2753 # ifdef HAS_WAITPID_RUNTIME
2754 if (!HAS_WAITPID_RUNTIME)
2757 return PerlProc_waitpid(pid,statusp,flags);
2759 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2760 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2762 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2767 Perl_croak(aTHX_ "Can't do waitpid with flags");
2769 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2770 pidgone(result,*statusp);
2778 #endif /* !DOSISH || OS2 || WIN32 */
2782 Perl_pidgone(pTHX_ Pid_t pid, int status)
2785 char spid[TYPE_CHARS(int)];
2787 sprintf(spid, "%"IVdf, (IV)pid);
2788 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2789 (void)SvUPGRADE(sv,SVt_IV);
2794 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2797 int /* Cannot prototype with I32
2799 my_syspclose(PerlIO *ptr)
2802 Perl_my_pclose(pTHX_ PerlIO *ptr)
2805 /* Needs work for PerlIO ! */
2806 FILE *f = PerlIO_findFILE(ptr);
2807 I32 result = pclose(f);
2809 result = (result << 8) & 0xff00;
2811 PerlIO_releaseFILE(ptr,f);
2817 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2820 register const char *frombase = from;
2823 register const char c = *from;
2828 while (count-- > 0) {
2829 for (todo = len; todo > 0; todo--) {
2837 Perl_cast_ulong(pTHX_ NV f)
2842 # define BIGDOUBLE 2147483648.0
2844 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2847 return (unsigned long)f;
2849 return (unsigned long)along;
2853 /* Unfortunately, on some systems the cast_uv() function doesn't
2854 work with the system-supplied definition of ULONG_MAX. The
2855 comparison (f >= ULONG_MAX) always comes out true. It must be a
2856 problem with the compiler constant folding.
2858 In any case, this workaround should be fine on any two's complement
2859 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2861 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2864 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2866 -- Kenneth Albanowski <kjahds@kjahds.com>
2870 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2874 Perl_cast_i32(pTHX_ NV f)
2877 return (I32) I32_MAX;
2879 return (I32) I32_MIN;
2884 Perl_cast_iv(pTHX_ NV f)
2889 if (f >= (NV)UV_MAX)
2900 Perl_cast_uv(pTHX_ NV f)
2903 return (UV) MY_UV_MAX;
2917 Perl_same_dirent(pTHX_ char *a, char *b)
2919 char *fa = strrchr(a,'/');
2920 char *fb = strrchr(b,'/');
2921 struct stat tmpstatbuf1;
2922 struct stat tmpstatbuf2;
2923 SV *tmpsv = sv_newmortal();
2936 sv_setpv(tmpsv, ".");
2938 sv_setpvn(tmpsv, a, fa - a);
2939 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2942 sv_setpv(tmpsv, ".");
2944 sv_setpvn(tmpsv, b, fb - b);
2945 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2947 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2948 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2950 #endif /* !HAS_RENAME */
2953 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
2955 register char *s = start;
2956 register NV rnv = 0.0;
2957 register UV ruv = 0;
2958 register bool seenb = FALSE;
2959 register bool overflowed = FALSE;
2961 for (; len-- && *s; s++) {
2962 if (!(*s == '0' || *s == '1')) {
2963 if (*s == '_' && len && *retlen
2964 && (s[1] == '0' || s[1] == '1'))
2969 else if (seenb == FALSE && *s == 'b' && ruv == 0) {
2970 /* Disallow 0bbb0b0bbb... */
2975 if (ckWARN(WARN_DIGIT))
2976 Perl_warner(aTHX_ WARN_DIGIT,
2977 "Illegal binary digit '%c' ignored", *s);
2982 register UV xuv = ruv << 1;
2984 if ((xuv >> 1) != ruv) {
2987 if (ckWARN_d(WARN_OVERFLOW))
2988 Perl_warner(aTHX_ WARN_OVERFLOW,
2989 "Integer overflow in binary number");
2992 ruv = xuv | (*s - '0');
2996 /* If an NV has not enough bits in its mantissa to
2997 * represent an UV this summing of small low-order numbers
2998 * is a waste of time (because the NV cannot preserve
2999 * the low-order bits anyway): we could just remember when
3000 * did we overflow and in the end just multiply rnv by the
3007 if ( ( overflowed && rnv > 4294967295.0)
3009 || (!overflowed && ruv > 0xffffffff )
3012 if (ckWARN(WARN_PORTABLE))
3013 Perl_warner(aTHX_ WARN_PORTABLE,
3014 "Binary number > 0b11111111111111111111111111111111 non-portable");
3016 *retlen = s - start;
3021 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3023 register char *s = start;
3024 register NV rnv = 0.0;
3025 register UV ruv = 0;
3026 register bool overflowed = FALSE;
3028 for (; len-- && *s; s++) {
3029 if (!(*s >= '0' && *s <= '7')) {
3030 if (*s == '_' && len && *retlen
3031 && (s[1] >= '0' && s[1] <= '7'))
3037 /* Allow \octal to work the DWIM way (that is, stop scanning
3038 * as soon as non-octal characters are seen, complain only iff
3039 * someone seems to want to use the digits eight and nine). */
3040 if (*s == '8' || *s == '9') {
3041 if (ckWARN(WARN_DIGIT))
3042 Perl_warner(aTHX_ WARN_DIGIT,
3043 "Illegal octal digit '%c' ignored", *s);
3049 register UV xuv = ruv << 3;
3051 if ((xuv >> 3) != ruv) {
3054 if (ckWARN_d(WARN_OVERFLOW))
3055 Perl_warner(aTHX_ WARN_OVERFLOW,
3056 "Integer overflow in octal number");
3059 ruv = xuv | (*s - '0');
3063 /* If an NV has not enough bits in its mantissa to
3064 * represent an UV this summing of small low-order numbers
3065 * is a waste of time (because the NV cannot preserve
3066 * the low-order bits anyway): we could just remember when
3067 * did we overflow and in the end just multiply rnv by the
3068 * right amount of 8-tuples. */
3069 rnv += (NV)(*s - '0');
3074 if ( ( overflowed && rnv > 4294967295.0)
3076 || (!overflowed && ruv > 0xffffffff )
3079 if (ckWARN(WARN_PORTABLE))
3080 Perl_warner(aTHX_ WARN_PORTABLE,
3081 "Octal number > 037777777777 non-portable");
3083 *retlen = s - start;
3088 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3090 register char *s = start;
3091 register NV rnv = 0.0;
3092 register UV ruv = 0;
3093 register bool overflowed = FALSE;
3101 else if (len > 3 && s[0] == '0' && s[1] == 'x') {
3107 for (; len-- && *s; s++) {
3108 hexdigit = strchr((char *) PL_hexdigit, *s);
3110 if (*s == '_' && len && *retlen && s[1]
3111 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
3117 if (ckWARN(WARN_DIGIT))
3118 Perl_warner(aTHX_ WARN_DIGIT,
3119 "Illegal hexadecimal digit '%c' ignored", *s);
3124 register UV xuv = ruv << 4;
3126 if ((xuv >> 4) != ruv) {
3129 if (ckWARN_d(WARN_OVERFLOW))
3130 Perl_warner(aTHX_ WARN_OVERFLOW,
3131 "Integer overflow in hexadecimal number");
3134 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
3138 /* If an NV has not enough bits in its mantissa to
3139 * represent an UV this summing of small low-order numbers
3140 * is a waste of time (because the NV cannot preserve
3141 * the low-order bits anyway): we could just remember when
3142 * did we overflow and in the end just multiply rnv by the
3143 * right amount of 16-tuples. */
3144 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
3149 if ( ( overflowed && rnv > 4294967295.0)
3151 || (!overflowed && ruv > 0xffffffff )
3154 if (ckWARN(WARN_PORTABLE))
3155 Perl_warner(aTHX_ WARN_PORTABLE,
3156 "Hexadecimal number > 0xffffffff non-portable");
3158 *retlen = s - start;
3163 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
3165 char *xfound = Nullch;
3166 char *xfailed = Nullch;
3167 char tmpbuf[MAXPATHLEN];
3171 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3172 # define SEARCH_EXTS ".bat", ".cmd", NULL
3173 # define MAX_EXT_LEN 4
3176 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3177 # define MAX_EXT_LEN 4
3180 # define SEARCH_EXTS ".pl", ".com", NULL
3181 # define MAX_EXT_LEN 4
3183 /* additional extensions to try in each dir if scriptname not found */
3185 char *exts[] = { SEARCH_EXTS };
3186 char **ext = search_ext ? search_ext : exts;
3187 int extidx = 0, i = 0;
3188 char *curext = Nullch;
3190 # define MAX_EXT_LEN 0
3194 * If dosearch is true and if scriptname does not contain path
3195 * delimiters, search the PATH for scriptname.
3197 * If SEARCH_EXTS is also defined, will look for each
3198 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3199 * while searching the PATH.
3201 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3202 * proceeds as follows:
3203 * If DOSISH or VMSISH:
3204 * + look for ./scriptname{,.foo,.bar}
3205 * + search the PATH for scriptname{,.foo,.bar}
3208 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3209 * this will not look in '.' if it's not in the PATH)
3214 # ifdef ALWAYS_DEFTYPES
3215 len = strlen(scriptname);
3216 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3217 int hasdir, idx = 0, deftypes = 1;
3220 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3223 int hasdir, idx = 0, deftypes = 1;
3226 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3228 /* The first time through, just add SEARCH_EXTS to whatever we
3229 * already have, so we can check for default file types. */
3231 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3237 if ((strlen(tmpbuf) + strlen(scriptname)
3238 + MAX_EXT_LEN) >= sizeof tmpbuf)
3239 continue; /* don't search dir with too-long name */
3240 strcat(tmpbuf, scriptname);
3244 if (strEQ(scriptname, "-"))
3246 if (dosearch) { /* Look in '.' first. */
3247 char *cur = scriptname;
3249 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3251 if (strEQ(ext[i++],curext)) {
3252 extidx = -1; /* already has an ext */
3257 DEBUG_p(PerlIO_printf(Perl_debug_log,
3258 "Looking for %s\n",cur));
3259 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3260 && !S_ISDIR(PL_statbuf.st_mode)) {
3268 if (cur == scriptname) {
3269 len = strlen(scriptname);
3270 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3272 cur = strcpy(tmpbuf, scriptname);
3274 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3275 && strcpy(tmpbuf+len, ext[extidx++]));
3280 #ifdef MACOS_TRADITIONAL
3281 if (dosearch && !strchr(scriptname, ':') &&
3282 (s = PerlEnv_getenv("Commands")))
3284 if (dosearch && !strchr(scriptname, '/')
3286 && !strchr(scriptname, '\\')
3288 && (s = PerlEnv_getenv("PATH")))
3293 PL_bufend = s + strlen(s);
3294 while (s < PL_bufend) {
3295 #ifdef MACOS_TRADITIONAL
3296 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3300 #if defined(atarist) || defined(DOSISH)
3305 && *s != ';'; len++, s++) {
3306 if (len < sizeof tmpbuf)
3309 if (len < sizeof tmpbuf)
3311 #else /* ! (atarist || DOSISH) */
3312 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3315 #endif /* ! (atarist || DOSISH) */
3316 #endif /* MACOS_TRADITIONAL */
3319 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3320 continue; /* don't search dir with too-long name */
3321 #ifdef MACOS_TRADITIONAL
3322 if (len && tmpbuf[len - 1] != ':')
3323 tmpbuf[len++] = ':';
3326 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3327 && tmpbuf[len - 1] != '/'
3328 && tmpbuf[len - 1] != '\\'
3331 tmpbuf[len++] = '/';
3332 if (len == 2 && tmpbuf[0] == '.')
3335 (void)strcpy(tmpbuf + len, scriptname);
3339 len = strlen(tmpbuf);
3340 if (extidx > 0) /* reset after previous loop */
3344 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3345 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3346 if (S_ISDIR(PL_statbuf.st_mode)) {
3350 } while ( retval < 0 /* not there */
3351 && extidx>=0 && ext[extidx] /* try an extension? */
3352 && strcpy(tmpbuf+len, ext[extidx++])
3357 if (S_ISREG(PL_statbuf.st_mode)
3358 && cando(S_IRUSR,TRUE,&PL_statbuf)
3359 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3360 && cando(S_IXUSR,TRUE,&PL_statbuf)
3364 xfound = tmpbuf; /* bingo! */
3368 xfailed = savepv(tmpbuf);
3371 if (!xfound && !seen_dot && !xfailed &&
3372 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3373 || S_ISDIR(PL_statbuf.st_mode)))
3375 seen_dot = 1; /* Disable message. */
3377 if (flags & 1) { /* do or die? */
3378 Perl_croak(aTHX_ "Can't %s %s%s%s",
3379 (xfailed ? "execute" : "find"),
3380 (xfailed ? xfailed : scriptname),
3381 (xfailed ? "" : " on PATH"),
3382 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3384 scriptname = Nullch;
3388 scriptname = xfound;
3390 return (scriptname ? savepv(scriptname) : Nullch);
3393 #ifndef PERL_GET_CONTEXT_DEFINED
3396 Perl_get_context(void)
3398 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3399 # ifdef OLD_PTHREADS_API
3401 if (pthread_getspecific(PL_thr_key, &t))
3402 Perl_croak_nocontext("panic: pthread_getspecific");
3405 # ifdef I_MACH_CTHREADS
3406 return (void*)cthread_data(cthread_self());
3408 return (void*)pthread_getspecific(PL_thr_key);
3417 Perl_set_context(void *t)
3419 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3420 # ifdef I_MACH_CTHREADS
3421 cthread_set_data(cthread_self(), t);
3423 if (pthread_setspecific(PL_thr_key, t))
3424 Perl_croak_nocontext("panic: pthread_setspecific");
3429 #endif /* !PERL_GET_CONTEXT_DEFINED */
3434 /* Very simplistic scheduler for now */
3438 thr = thr->i.next_run;
3442 Perl_cond_init(pTHX_ perl_cond *cp)
3448 Perl_cond_signal(pTHX_ perl_cond *cp)
3451 perl_cond cond = *cp;
3456 /* Insert t in the runnable queue just ahead of us */
3457 t->i.next_run = thr->i.next_run;
3458 thr->i.next_run->i.prev_run = t;
3459 t->i.prev_run = thr;
3460 thr->i.next_run = t;
3461 thr->i.wait_queue = 0;
3462 /* Remove from the wait queue */
3468 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3471 perl_cond cond, cond_next;
3473 for (cond = *cp; cond; cond = cond_next) {
3475 /* Insert t in the runnable queue just ahead of us */
3476 t->i.next_run = thr->i.next_run;
3477 thr->i.next_run->i.prev_run = t;
3478 t->i.prev_run = thr;
3479 thr->i.next_run = t;
3480 thr->i.wait_queue = 0;
3481 /* Remove from the wait queue */
3482 cond_next = cond->next;
3489 Perl_cond_wait(pTHX_ perl_cond *cp)
3493 if (thr->i.next_run == thr)
3494 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3496 New(666, cond, 1, struct perl_wait_queue);
3500 thr->i.wait_queue = cond;
3501 /* Remove ourselves from runnable queue */
3502 thr->i.next_run->i.prev_run = thr->i.prev_run;
3503 thr->i.prev_run->i.next_run = thr->i.next_run;
3505 #endif /* FAKE_THREADS */
3508 Perl_condpair_magic(pTHX_ SV *sv)
3512 SvUPGRADE(sv, SVt_PVMG);
3513 mg = mg_find(sv, 'm');
3517 New(53, cp, 1, condpair_t);
3518 MUTEX_INIT(&cp->mutex);
3519 COND_INIT(&cp->owner_cond);
3520 COND_INIT(&cp->cond);
3522 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3523 mg = mg_find(sv, 'm');
3525 /* someone else beat us to initialising it */
3526 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3527 MUTEX_DESTROY(&cp->mutex);
3528 COND_DESTROY(&cp->owner_cond);
3529 COND_DESTROY(&cp->cond);
3533 sv_magic(sv, Nullsv, 'm', 0, 0);
3535 mg->mg_ptr = (char *)cp;
3536 mg->mg_len = sizeof(cp);
3537 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3538 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3539 "%p: condpair_magic %p\n", thr, sv));)
3546 Perl_sv_lock(pTHX_ SV *osv)
3556 mg = condpair_magic(sv);
3557 MUTEX_LOCK(MgMUTEXP(mg));
3558 if (MgOWNER(mg) == thr)
3559 MUTEX_UNLOCK(MgMUTEXP(mg));
3562 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3564 DEBUG_S(PerlIO_printf(Perl_debug_log,
3565 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3566 PTR2UV(thr), PTR2UV(sv));)
3567 MUTEX_UNLOCK(MgMUTEXP(mg));
3568 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3570 UNLOCK_SV_LOCK_MUTEX;
3575 * Make a new perl thread structure using t as a prototype. Some of the
3576 * fields for the new thread are copied from the prototype thread, t,
3577 * so t should not be running in perl at the time this function is
3578 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3579 * thread calling new_struct_thread) clearly satisfies this constraint.
3581 struct perl_thread *
3582 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3584 #if !defined(PERL_IMPLICIT_CONTEXT)
3585 struct perl_thread *thr;
3591 sv = newSVpvn("", 0);
3592 SvGROW(sv, sizeof(struct perl_thread) + 1);
3593 SvCUR_set(sv, sizeof(struct perl_thread));
3594 thr = (Thread) SvPVX(sv);
3596 memset(thr, 0xab, sizeof(struct perl_thread));
3603 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3604 PL_efloatbuf = (char*)NULL;
3607 Zero(thr, 1, struct perl_thread);
3613 PL_curcop = &PL_compiling;
3614 thr->interp = t->interp;
3615 thr->cvcache = newHV();
3616 thr->threadsv = newAV();
3617 thr->specific = newAV();
3618 thr->errsv = newSVpvn("", 0);
3619 thr->flags = THRf_R_JOINABLE;
3621 MUTEX_INIT(&thr->mutex);
3625 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3628 PL_statname = NEWSV(66,0);
3629 PL_errors = newSVpvn("", 0);
3631 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3632 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3633 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3634 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3635 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3637 PL_reginterp_cnt = 0;
3638 PL_lastscream = Nullsv;
3641 PL_reg_start_tmp = 0;
3642 PL_reg_start_tmpl = 0;
3643 PL_reg_poscache = Nullch;
3645 /* parent thread's data needs to be locked while we make copy */
3646 MUTEX_LOCK(&t->mutex);
3648 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3649 PL_protect = t->Tprotect;
3652 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3653 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3654 PL_curstash = t->Tcurstash; /* always be set to main? */
3656 PL_tainted = t->Ttainted;
3657 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3658 PL_nrs = newSVsv(t->Tnrs);
3659 PL_rs = t->Tnrs ? SvREFCNT_inc(PL_nrs) : Nullsv;
3660 PL_last_in_gv = Nullgv;
3661 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3662 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3663 PL_chopset = t->Tchopset;
3664 PL_bodytarget = newSVsv(t->Tbodytarget);
3665 PL_toptarget = newSVsv(t->Ttoptarget);
3666 if (t->Tformtarget == t->Ttoptarget)
3667 PL_formtarget = PL_toptarget;
3669 PL_formtarget = PL_bodytarget;
3671 /* Initialise all per-thread SVs that the template thread used */
3672 svp = AvARRAY(t->threadsv);
3673 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3674 if (*svp && *svp != &PL_sv_undef) {
3675 SV *sv = newSVsv(*svp);
3676 av_store(thr->threadsv, i, sv);
3677 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3678 DEBUG_S(PerlIO_printf(Perl_debug_log,
3679 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3683 thr->threadsvp = AvARRAY(thr->threadsv);
3685 MUTEX_LOCK(&PL_threads_mutex);
3687 thr->tid = ++PL_threadnum;
3688 thr->next = t->next;
3691 thr->next->prev = thr;
3692 MUTEX_UNLOCK(&PL_threads_mutex);
3694 /* done copying parent's state */
3695 MUTEX_UNLOCK(&t->mutex);
3697 #ifdef HAVE_THREAD_INTERN
3698 Perl_init_thread_intern(thr);
3699 #endif /* HAVE_THREAD_INTERN */
3702 #endif /* USE_THREADS */
3704 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
3706 * This hack is to force load of "huge" support from libm.a
3707 * So it is in perl for (say) POSIX to use.
3708 * Needed for SunOS with Sun's 'acc' for example.
3713 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
3720 #ifdef PERL_GLOBAL_STRUCT
3729 Perl_get_op_names(pTHX)
3735 Perl_get_op_descs(pTHX)
3741 Perl_get_no_modify(pTHX)
3743 return (char*)PL_no_modify;
3747 Perl_get_opargs(pTHX)
3753 Perl_get_ppaddr(pTHX)
3755 return (PPADDR_t*)PL_ppaddr;
3758 #ifndef HAS_GETENV_LEN
3760 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3762 char *env_trans = PerlEnv_getenv(env_elem);
3764 *len = strlen(env_trans);
3771 Perl_get_vtbl(pTHX_ int vtbl_id)
3773 MGVTBL* result = Null(MGVTBL*);
3777 result = &PL_vtbl_sv;
3780 result = &PL_vtbl_env;
3782 case want_vtbl_envelem:
3783 result = &PL_vtbl_envelem;
3786 result = &PL_vtbl_sig;
3788 case want_vtbl_sigelem:
3789 result = &PL_vtbl_sigelem;
3791 case want_vtbl_pack:
3792 result = &PL_vtbl_pack;
3794 case want_vtbl_packelem:
3795 result = &PL_vtbl_packelem;
3797 case want_vtbl_dbline:
3798 result = &PL_vtbl_dbline;
3801 result = &PL_vtbl_isa;
3803 case want_vtbl_isaelem:
3804 result = &PL_vtbl_isaelem;
3806 case want_vtbl_arylen:
3807 result = &PL_vtbl_arylen;
3809 case want_vtbl_glob:
3810 result = &PL_vtbl_glob;
3812 case want_vtbl_mglob:
3813 result = &PL_vtbl_mglob;
3815 case want_vtbl_nkeys:
3816 result = &PL_vtbl_nkeys;
3818 case want_vtbl_taint:
3819 result = &PL_vtbl_taint;
3821 case want_vtbl_substr:
3822 result = &PL_vtbl_substr;
3825 result = &PL_vtbl_vec;
3828 result = &PL_vtbl_pos;
3831 result = &PL_vtbl_bm;
3834 result = &PL_vtbl_fm;
3836 case want_vtbl_uvar:
3837 result = &PL_vtbl_uvar;
3840 case want_vtbl_mutex:
3841 result = &PL_vtbl_mutex;
3844 case want_vtbl_defelem:
3845 result = &PL_vtbl_defelem;
3847 case want_vtbl_regexp:
3848 result = &PL_vtbl_regexp;
3850 case want_vtbl_regdata:
3851 result = &PL_vtbl_regdata;
3853 case want_vtbl_regdatum:
3854 result = &PL_vtbl_regdatum;
3856 #ifdef USE_LOCALE_COLLATE
3857 case want_vtbl_collxfrm:
3858 result = &PL_vtbl_collxfrm;
3861 case want_vtbl_amagic:
3862 result = &PL_vtbl_amagic;
3864 case want_vtbl_amagicelem:
3865 result = &PL_vtbl_amagicelem;
3867 case want_vtbl_backref:
3868 result = &PL_vtbl_backref;
3875 Perl_my_fflush_all(pTHX)
3877 #if defined(FFLUSH_NULL)
3878 return PerlIO_flush(NULL);
3880 # if defined(HAS__FWALK)
3881 /* undocumented, unprototyped, but very useful BSDism */
3882 extern void _fwalk(int (*)(FILE *));
3887 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3888 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3889 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3891 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3892 open_max = sysconf(_SC_OPEN_MAX);
3895 open_max = FOPEN_MAX;
3898 open_max = OPEN_MAX;
3909 for (i = 0; i < open_max; i++)
3910 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3911 STDIO_STREAM_ARRAY[i]._file < open_max &&
3912 STDIO_STREAM_ARRAY[i]._flag)
3913 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3917 SETERRNO(EBADF,RMS$_IFI);
3924 Perl_my_atof(pTHX_ const char* s)
3927 #ifdef USE_LOCALE_NUMERIC
3928 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3932 SET_NUMERIC_STANDARD();
3934 SET_NUMERIC_LOCAL();
3935 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
3947 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3952 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3953 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3955 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3956 char *type = OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET) ?
3957 "socket" : "filehandle";
3960 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3962 warn_type = WARN_CLOSED;
3966 warn_type = WARN_UNOPENED;
3969 if (gv && isGV(gv)) {
3970 SV *sv = sv_newmortal();
3971 gv_efullname4(sv, gv, Nullch, FALSE);
3975 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3977 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
3979 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3981 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
3982 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3983 } else if (name && *name) {
3984 Perl_warner(aTHX_ warn_type,
3985 "%s%s on %s %s %s", func, pars, vile, type, name);
3986 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3987 Perl_warner(aTHX_ warn_type,
3988 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3992 Perl_warner(aTHX_ warn_type,
3993 "%s%s on %s %s", func, pars, vile, type);
3994 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3995 Perl_warner(aTHX_ warn_type,
3996 "\t(Are you trying to call %s%s on dirhandle?)\n",