3 * Copyright (c) 1991-2000, 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 /* We assume that decimal separator aka the radix
580 * character is always a single character. If it
581 * ever is a string, this needs to be rethunk. */
582 PL_numeric_radix = *lc->decimal_point;
584 PL_numeric_radix = 0;
585 # endif /* HAS_LOCALECONV */
586 #endif /* USE_LOCALE_NUMERIC */
590 * Set up for a new numeric locale.
593 Perl_new_numeric(pTHX_ char *newnum)
595 #ifdef USE_LOCALE_NUMERIC
598 if (PL_numeric_name) {
599 Safefree(PL_numeric_name);
600 PL_numeric_name = NULL;
602 PL_numeric_standard = TRUE;
603 PL_numeric_local = TRUE;
607 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
608 Safefree(PL_numeric_name);
609 PL_numeric_name = stdize_locale(savepv(newnum));
610 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
611 PL_numeric_local = TRUE;
615 #endif /* USE_LOCALE_NUMERIC */
619 Perl_set_numeric_standard(pTHX)
621 #ifdef USE_LOCALE_NUMERIC
623 if (! PL_numeric_standard) {
624 setlocale(LC_NUMERIC, "C");
625 PL_numeric_standard = TRUE;
626 PL_numeric_local = FALSE;
630 #endif /* USE_LOCALE_NUMERIC */
634 Perl_set_numeric_local(pTHX)
636 #ifdef USE_LOCALE_NUMERIC
638 if (! PL_numeric_local) {
639 setlocale(LC_NUMERIC, PL_numeric_name);
640 PL_numeric_standard = FALSE;
641 PL_numeric_local = TRUE;
645 #endif /* USE_LOCALE_NUMERIC */
649 * Initialize locale awareness.
652 Perl_init_i18nl10n(pTHX_ int printwarn)
656 * 1 = set ok or not applicable,
657 * 0 = fallback to C locale,
658 * -1 = fallback to C locale failed
663 #ifdef USE_LOCALE_CTYPE
664 char *curctype = NULL;
665 #endif /* USE_LOCALE_CTYPE */
666 #ifdef USE_LOCALE_COLLATE
667 char *curcoll = NULL;
668 #endif /* USE_LOCALE_COLLATE */
669 #ifdef USE_LOCALE_NUMERIC
671 #endif /* USE_LOCALE_NUMERIC */
673 char *language = PerlEnv_getenv("LANGUAGE");
675 char *lc_all = PerlEnv_getenv("LC_ALL");
676 char *lang = PerlEnv_getenv("LANG");
677 bool setlocale_failure = FALSE;
679 #ifdef LOCALE_ENVIRON_REQUIRED
682 * Ultrix setlocale(..., "") fails if there are no environment
683 * variables from which to get a locale name.
690 if (setlocale(LC_ALL, ""))
693 setlocale_failure = TRUE;
695 if (!setlocale_failure) {
696 #ifdef USE_LOCALE_CTYPE
699 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
701 setlocale_failure = TRUE;
703 curctype = savepv(curctype);
704 #endif /* USE_LOCALE_CTYPE */
705 #ifdef USE_LOCALE_COLLATE
707 setlocale(LC_COLLATE,
708 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
710 setlocale_failure = TRUE;
712 curcoll = savepv(curcoll);
713 #endif /* USE_LOCALE_COLLATE */
714 #ifdef USE_LOCALE_NUMERIC
716 setlocale(LC_NUMERIC,
717 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
719 setlocale_failure = TRUE;
721 curnum = savepv(curnum);
722 #endif /* USE_LOCALE_NUMERIC */
727 #endif /* !LOCALE_ENVIRON_REQUIRED */
730 if (! setlocale(LC_ALL, ""))
731 setlocale_failure = TRUE;
734 if (!setlocale_failure) {
735 #ifdef USE_LOCALE_CTYPE
736 if (! (curctype = setlocale(LC_CTYPE, "")))
737 setlocale_failure = TRUE;
739 curctype = savepv(curctype);
740 #endif /* USE_LOCALE_CTYPE */
741 #ifdef USE_LOCALE_COLLATE
742 if (! (curcoll = setlocale(LC_COLLATE, "")))
743 setlocale_failure = TRUE;
745 curcoll = savepv(curcoll);
746 #endif /* USE_LOCALE_COLLATE */
747 #ifdef USE_LOCALE_NUMERIC
748 if (! (curnum = setlocale(LC_NUMERIC, "")))
749 setlocale_failure = TRUE;
751 curnum = savepv(curnum);
752 #endif /* USE_LOCALE_NUMERIC */
755 if (setlocale_failure) {
757 bool locwarn = (printwarn > 1 ||
759 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
764 PerlIO_printf(Perl_error_log,
765 "perl: warning: Setting locale failed.\n");
769 PerlIO_printf(Perl_error_log,
770 "perl: warning: Setting locale failed for the categories:\n\t");
771 #ifdef USE_LOCALE_CTYPE
773 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
774 #endif /* USE_LOCALE_CTYPE */
775 #ifdef USE_LOCALE_COLLATE
777 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
778 #endif /* USE_LOCALE_COLLATE */
779 #ifdef USE_LOCALE_NUMERIC
781 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
782 #endif /* USE_LOCALE_NUMERIC */
783 PerlIO_printf(Perl_error_log, "\n");
787 PerlIO_printf(Perl_error_log,
788 "perl: warning: Please check that your locale settings:\n");
791 PerlIO_printf(Perl_error_log,
792 "\tLANGUAGE = %c%s%c,\n",
793 language ? '"' : '(',
794 language ? language : "unset",
795 language ? '"' : ')');
798 PerlIO_printf(Perl_error_log,
799 "\tLC_ALL = %c%s%c,\n",
801 lc_all ? lc_all : "unset",
806 for (e = environ; *e; e++) {
807 if (strnEQ(*e, "LC_", 3)
808 && strnNE(*e, "LC_ALL=", 7)
809 && (p = strchr(*e, '=')))
810 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
811 (int)(p - *e), *e, p + 1);
815 PerlIO_printf(Perl_error_log,
818 lang ? lang : "unset",
821 PerlIO_printf(Perl_error_log,
822 " are supported and installed on your system.\n");
827 if (setlocale(LC_ALL, "C")) {
829 PerlIO_printf(Perl_error_log,
830 "perl: warning: Falling back to the standard locale (\"C\").\n");
835 PerlIO_printf(Perl_error_log,
836 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
843 #ifdef USE_LOCALE_CTYPE
844 || !(curctype || setlocale(LC_CTYPE, "C"))
845 #endif /* USE_LOCALE_CTYPE */
846 #ifdef USE_LOCALE_COLLATE
847 || !(curcoll || setlocale(LC_COLLATE, "C"))
848 #endif /* USE_LOCALE_COLLATE */
849 #ifdef USE_LOCALE_NUMERIC
850 || !(curnum || setlocale(LC_NUMERIC, "C"))
851 #endif /* USE_LOCALE_NUMERIC */
855 PerlIO_printf(Perl_error_log,
856 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
860 #endif /* ! LC_ALL */
862 #ifdef USE_LOCALE_CTYPE
863 curctype = savepv(setlocale(LC_CTYPE, Nullch));
864 #endif /* USE_LOCALE_CTYPE */
865 #ifdef USE_LOCALE_COLLATE
866 curcoll = savepv(setlocale(LC_COLLATE, Nullch));
867 #endif /* USE_LOCALE_COLLATE */
868 #ifdef USE_LOCALE_NUMERIC
869 curnum = savepv(setlocale(LC_NUMERIC, Nullch));
870 #endif /* USE_LOCALE_NUMERIC */
874 #ifdef USE_LOCALE_CTYPE
876 #endif /* USE_LOCALE_CTYPE */
878 #ifdef USE_LOCALE_COLLATE
879 new_collate(curcoll);
880 #endif /* USE_LOCALE_COLLATE */
882 #ifdef USE_LOCALE_NUMERIC
884 #endif /* USE_LOCALE_NUMERIC */
887 #endif /* USE_LOCALE */
889 #ifdef USE_LOCALE_CTYPE
890 if (curctype != NULL)
892 #endif /* USE_LOCALE_CTYPE */
893 #ifdef USE_LOCALE_COLLATE
896 #endif /* USE_LOCALE_COLLATE */
897 #ifdef USE_LOCALE_NUMERIC
900 #endif /* USE_LOCALE_NUMERIC */
904 /* Backwards compatibility. */
906 Perl_init_i18nl14n(pTHX_ int printwarn)
908 return init_i18nl10n(printwarn);
911 #ifdef USE_LOCALE_COLLATE
914 * mem_collxfrm() is a bit like strxfrm() but with two important
915 * differences. First, it handles embedded NULs. Second, it allocates
916 * a bit more memory than needed for the transformed data itself.
917 * The real transformed data begins at offset sizeof(collationix).
918 * Please see sv_collxfrm() to see how this is used.
921 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
924 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
926 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
927 /* the +1 is for the terminating NUL. */
929 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
930 New(171, xbuf, xAlloc, char);
934 *(U32*)xbuf = PL_collation_ix;
935 xout = sizeof(PL_collation_ix);
936 for (xin = 0; xin < len; ) {
940 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
943 if (xused < xAlloc - xout)
945 xAlloc = (2 * xAlloc) + 1;
946 Renew(xbuf, xAlloc, char);
951 xin += strlen(s + xin) + 1;
954 /* Embedded NULs are understood but silently skipped
955 * because they make no sense in locale collation. */
959 *xlen = xout - sizeof(PL_collation_ix);
968 #endif /* USE_LOCALE_COLLATE */
970 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
972 /* As a space optimization, we do not compile tables for strings of length
973 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
974 special-cased in fbm_instr().
976 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
979 =for apidoc fbm_compile
981 Analyses the string in order to make fast searches on it using fbm_instr()
982 -- the Boyer-Moore algorithm.
988 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
997 if (flags & FBMcf_TAIL)
998 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
999 s = (U8*)SvPV_force(sv, len);
1000 (void)SvUPGRADE(sv, SVt_PVBM);
1001 if (len == 0) /* TAIL might be on on a zero-length string. */
1011 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
1012 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
1013 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
1014 memset((void*)table, mlen, 256);
1015 table[-1] = (U8)flags;
1017 sb = s - mlen + 1; /* first char (maybe) */
1019 if (table[*s] == mlen)
1024 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
1027 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
1028 for (i = 0; i < len; i++) {
1029 if (PL_freq[s[i]] < frequency) {
1031 frequency = PL_freq[s[i]];
1034 BmRARE(sv) = s[rarest];
1035 BmPREVIOUS(sv) = rarest;
1036 BmUSEFUL(sv) = 100; /* Initial value */
1037 if (flags & FBMcf_TAIL)
1039 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
1040 BmRARE(sv),BmPREVIOUS(sv)));
1043 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
1044 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1048 =for apidoc fbm_instr
1050 Returns the location of the SV in the string delimited by C<str> and
1051 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
1052 does not have to be fbm_compiled, but the search will not be as fast
1059 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
1061 register unsigned char *s;
1063 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
1064 register STRLEN littlelen = l;
1065 register I32 multiline = flags & FBMrf_MULTILINE;
1067 if (bigend - big < littlelen) {
1068 if ( SvTAIL(littlestr)
1069 && (bigend - big == littlelen - 1)
1071 || (*big == *little &&
1072 memEQ((char *)big, (char *)little, littlelen - 1))))
1077 if (littlelen <= 2) { /* Special-cased */
1079 if (littlelen == 1) {
1080 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1081 /* Know that bigend != big. */
1082 if (bigend[-1] == '\n')
1083 return (char *)(bigend - 1);
1084 return (char *) bigend;
1087 while (s < bigend) {
1092 if (SvTAIL(littlestr))
1093 return (char *) bigend;
1097 return (char*)big; /* Cannot be SvTAIL! */
1099 /* littlelen is 2 */
1100 if (SvTAIL(littlestr) && !multiline) {
1101 if (bigend[-1] == '\n' && bigend[-2] == *little)
1102 return (char*)bigend - 2;
1103 if (bigend[-1] == *little)
1104 return (char*)bigend - 1;
1108 /* This should be better than FBM if c1 == c2, and almost
1109 as good otherwise: maybe better since we do less indirection.
1110 And we save a lot of memory by caching no table. */
1111 register unsigned char c1 = little[0];
1112 register unsigned char c2 = little[1];
1117 while (s <= bigend) {
1120 return (char*)s - 1;
1127 goto check_1char_anchor;
1138 goto check_1char_anchor;
1141 while (s <= bigend) {
1144 return (char*)s - 1;
1146 goto check_1char_anchor;
1155 check_1char_anchor: /* One char and anchor! */
1156 if (SvTAIL(littlestr) && (*bigend == *little))
1157 return (char *)bigend; /* bigend is already decremented. */
1160 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1161 s = bigend - littlelen;
1162 if (s >= big && bigend[-1] == '\n' && *s == *little
1163 /* Automatically of length > 2 */
1164 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1166 return (char*)s; /* how sweet it is */
1169 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1171 return (char*)s + 1; /* how sweet it is */
1175 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1176 char *b = ninstr((char*)big,(char*)bigend,
1177 (char*)little, (char*)little + littlelen);
1179 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1180 /* Chop \n from littlestr: */
1181 s = bigend - littlelen + 1;
1183 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1192 { /* Do actual FBM. */
1193 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1194 register unsigned char *oldlittle;
1196 if (littlelen > bigend - big)
1198 --littlelen; /* Last char found by table lookup */
1200 s = big + littlelen;
1201 little += littlelen; /* last char */
1208 if ((tmp = table[*s])) {
1210 if (bigend - s > tmp) {
1216 if ((s += tmp) < bigend)
1221 else { /* less expensive than calling strncmp() */
1222 register unsigned char *olds = s;
1227 if (*--s == *--little)
1229 s = olds + 1; /* here we pay the price for failure */
1231 if (s < bigend) /* fake up continue to outer loop */
1239 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1240 && memEQ((char *)(bigend - littlelen),
1241 (char *)(oldlittle - littlelen), littlelen) )
1242 return (char*)bigend - littlelen;
1247 /* start_shift, end_shift are positive quantities which give offsets
1248 of ends of some substring of bigstr.
1249 If `last' we want the last occurence.
1250 old_posp is the way of communication between consequent calls if
1251 the next call needs to find the .
1252 The initial *old_posp should be -1.
1254 Note that we take into account SvTAIL, so one can get extra
1255 optimizations if _ALL flag is set.
1258 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1259 if PL_multiline. In fact if !PL_multiline the autoritative answer
1260 is not supported yet. */
1263 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1266 register unsigned char *s, *x;
1267 register unsigned char *big;
1269 register I32 previous;
1271 register unsigned char *little;
1272 register I32 stop_pos;
1273 register unsigned char *littleend;
1277 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1278 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1280 if ( BmRARE(littlestr) == '\n'
1281 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1282 little = (unsigned char *)(SvPVX(littlestr));
1283 littleend = little + SvCUR(littlestr);
1290 little = (unsigned char *)(SvPVX(littlestr));
1291 littleend = little + SvCUR(littlestr);
1293 /* The value of pos we can start at: */
1294 previous = BmPREVIOUS(littlestr);
1295 big = (unsigned char *)(SvPVX(bigstr));
1296 /* The value of pos we can stop at: */
1297 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1298 if (previous + start_shift > stop_pos) {
1299 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1303 while (pos < previous + start_shift) {
1304 if (!(pos += PL_screamnext[pos]))
1309 if (pos >= stop_pos) break;
1310 if (big[pos-previous] != first)
1312 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1318 if (s == littleend) {
1320 if (!last) return (char *)(big+pos-previous);
1323 } while ( pos += PL_screamnext[pos] );
1324 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1325 #else /* !POINTERRIGOR */
1328 if (pos >= stop_pos) break;
1329 if (big[pos] != first)
1331 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1337 if (s == littleend) {
1339 if (!last) return (char *)(big+pos);
1342 } while ( pos += PL_screamnext[pos] );
1344 return (char *)(big+(*old_posp));
1345 #endif /* POINTERRIGOR */
1347 if (!SvTAIL(littlestr) || (end_shift > 0))
1349 /* Ignore the trailing "\n". This code is not microoptimized */
1350 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1351 stop_pos = littleend - little; /* Actual littlestr len */
1356 && ((stop_pos == 1) ||
1357 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1363 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1365 register U8 *a = (U8 *)s1;
1366 register U8 *b = (U8 *)s2;
1368 if (*a != *b && *a != PL_fold[*b])
1376 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1378 register U8 *a = (U8 *)s1;
1379 register U8 *b = (U8 *)s2;
1381 if (*a != *b && *a != PL_fold_locale[*b])
1388 /* copy a string to a safe spot */
1393 Copy a string to a safe spot. This does not use an SV.
1399 Perl_savepv(pTHX_ const char *sv)
1401 register char *newaddr;
1403 New(902,newaddr,strlen(sv)+1,char);
1404 (void)strcpy(newaddr,sv);
1408 /* same thing but with a known length */
1413 Copy a string to a safe spot. The C<len> indicates number of bytes to
1414 copy. This does not use an SV.
1420 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1422 register char *newaddr;
1424 New(903,newaddr,len+1,char);
1425 Copy(sv,newaddr,len,char); /* might not be null terminated */
1426 newaddr[len] = '\0'; /* is now */
1430 /* the SV for Perl_form() and mess() is not kept in an arena */
1440 return sv_2mortal(newSVpvn("",0));
1445 /* Create as PVMG now, to avoid any upgrading later */
1446 New(905, sv, 1, SV);
1447 Newz(905, any, 1, XPVMG);
1448 SvFLAGS(sv) = SVt_PVMG;
1449 SvANY(sv) = (void*)any;
1450 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1455 #if defined(PERL_IMPLICIT_CONTEXT)
1457 Perl_form_nocontext(const char* pat, ...)
1462 va_start(args, pat);
1463 retval = vform(pat, &args);
1467 #endif /* PERL_IMPLICIT_CONTEXT */
1470 Perl_form(pTHX_ const char* pat, ...)
1474 va_start(args, pat);
1475 retval = vform(pat, &args);
1481 Perl_vform(pTHX_ const char *pat, va_list *args)
1483 SV *sv = mess_alloc();
1484 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1488 #if defined(PERL_IMPLICIT_CONTEXT)
1490 Perl_mess_nocontext(const char *pat, ...)
1495 va_start(args, pat);
1496 retval = vmess(pat, &args);
1500 #endif /* PERL_IMPLICIT_CONTEXT */
1503 Perl_mess(pTHX_ const char *pat, ...)
1507 va_start(args, pat);
1508 retval = vmess(pat, &args);
1514 Perl_vmess(pTHX_ const char *pat, va_list *args)
1516 SV *sv = mess_alloc();
1517 static char dgd[] = " during global destruction.\n";
1519 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1520 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1522 if (CopLINE(PL_curcop))
1523 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1524 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1525 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1526 bool line_mode = (RsSIMPLE(PL_rs) &&
1527 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1528 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1529 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1530 line_mode ? "line" : "chunk",
1531 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1535 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1537 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1543 Perl_vdie(pTHX_ const char* pat, va_list *args)
1547 int was_in_eval = PL_in_eval;
1554 DEBUG_S(PerlIO_printf(Perl_debug_log,
1555 "%p: die: curstack = %p, mainstack = %p\n",
1556 thr, PL_curstack, PL_mainstack));
1559 msv = vmess(pat, args);
1560 if (PL_errors && SvCUR(PL_errors)) {
1561 sv_catsv(PL_errors, msv);
1562 message = SvPV(PL_errors, msglen);
1563 SvCUR_set(PL_errors, 0);
1566 message = SvPV(msv,msglen);
1573 DEBUG_S(PerlIO_printf(Perl_debug_log,
1574 "%p: die: message = %s\ndiehook = %p\n",
1575 thr, message, PL_diehook));
1577 /* sv_2cv might call Perl_croak() */
1578 SV *olddiehook = PL_diehook;
1580 SAVESPTR(PL_diehook);
1581 PL_diehook = Nullsv;
1582 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1584 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1591 msg = newSVpvn(message, msglen);
1599 PUSHSTACKi(PERLSI_DIEHOOK);
1603 call_sv((SV*)cv, G_DISCARD);
1609 PL_restartop = die_where(message, msglen);
1610 DEBUG_S(PerlIO_printf(Perl_debug_log,
1611 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1612 thr, PL_restartop, was_in_eval, PL_top_env));
1613 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1615 return PL_restartop;
1618 #if defined(PERL_IMPLICIT_CONTEXT)
1620 Perl_die_nocontext(const char* pat, ...)
1625 va_start(args, pat);
1626 o = vdie(pat, &args);
1630 #endif /* PERL_IMPLICIT_CONTEXT */
1633 Perl_die(pTHX_ const char* pat, ...)
1637 va_start(args, pat);
1638 o = vdie(pat, &args);
1644 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1655 msv = vmess(pat, args);
1656 if (PL_errors && SvCUR(PL_errors)) {
1657 sv_catsv(PL_errors, msv);
1658 message = SvPV(PL_errors, msglen);
1659 SvCUR_set(PL_errors, 0);
1662 message = SvPV(msv,msglen);
1669 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1670 PTR2UV(thr), message));
1673 /* sv_2cv might call Perl_croak() */
1674 SV *olddiehook = PL_diehook;
1676 SAVESPTR(PL_diehook);
1677 PL_diehook = Nullsv;
1678 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1680 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1687 msg = newSVpvn(message, msglen);
1695 PUSHSTACKi(PERLSI_DIEHOOK);
1699 call_sv((SV*)cv, G_DISCARD);
1705 PL_restartop = die_where(message, msglen);
1710 /* SFIO can really mess with your errno */
1713 PerlIO *serr = Perl_error_log;
1715 PerlIO_write(serr, message, msglen);
1716 (void)PerlIO_flush(serr);
1724 #if defined(PERL_IMPLICIT_CONTEXT)
1726 Perl_croak_nocontext(const char *pat, ...)
1730 va_start(args, pat);
1735 #endif /* PERL_IMPLICIT_CONTEXT */
1740 This is the XSUB-writer's interface to Perl's C<die> function.
1741 Normally use this function the same way you use the C C<printf>
1742 function. See C<warn>.
1744 If you want to throw an exception object, assign the object to
1745 C<$@> and then pass C<Nullch> to croak():
1747 errsv = get_sv("@", TRUE);
1748 sv_setsv(errsv, exception_object);
1755 Perl_croak(pTHX_ const char *pat, ...)
1758 va_start(args, pat);
1765 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1774 msv = vmess(pat, args);
1775 message = SvPV(msv, msglen);
1778 /* sv_2cv might call Perl_warn() */
1780 SV *oldwarnhook = PL_warnhook;
1782 SAVESPTR(PL_warnhook);
1783 PL_warnhook = Nullsv;
1784 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1786 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1792 msg = newSVpvn(message, msglen);
1796 PUSHSTACKi(PERLSI_WARNHOOK);
1800 call_sv((SV*)cv, G_DISCARD);
1807 PerlIO *serr = Perl_error_log;
1809 PerlIO_write(serr, message, msglen);
1811 DEBUG_L(*message == '!'
1812 ? (xstat(message[1]=='!'
1813 ? (message[2]=='!' ? 2 : 1)
1818 (void)PerlIO_flush(serr);
1822 #if defined(PERL_IMPLICIT_CONTEXT)
1824 Perl_warn_nocontext(const char *pat, ...)
1828 va_start(args, pat);
1832 #endif /* PERL_IMPLICIT_CONTEXT */
1837 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1838 function the same way you use the C C<printf> function. See
1845 Perl_warn(pTHX_ const char *pat, ...)
1848 va_start(args, pat);
1853 #if defined(PERL_IMPLICIT_CONTEXT)
1855 Perl_warner_nocontext(U32 err, const char *pat, ...)
1859 va_start(args, pat);
1860 vwarner(err, pat, &args);
1863 #endif /* PERL_IMPLICIT_CONTEXT */
1866 Perl_warner(pTHX_ U32 err, const char* pat,...)
1869 va_start(args, pat);
1870 vwarner(err, pat, &args);
1875 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() */
1935 SV *oldwarnhook = PL_warnhook;
1937 SAVESPTR(PL_warnhook);
1938 PL_warnhook = Nullsv;
1939 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1941 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1947 msg = newSVpvn(message, msglen);
1951 PUSHSTACKi(PERLSI_WARNHOOK);
1955 call_sv((SV*)cv, G_DISCARD);
1962 PerlIO *serr = Perl_error_log;
1963 PerlIO_write(serr, message, msglen);
1965 DEBUG_L(*message == '!'
1966 ? (xstat(message[1]=='!'
1967 ? (message[2]=='!' ? 2 : 1)
1972 (void)PerlIO_flush(serr);
1977 #ifdef USE_ENVIRON_ARRAY
1978 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1981 Perl_my_setenv(pTHX_ char *nam, char *val)
1983 #ifndef PERL_USE_SAFE_PUTENV
1984 /* most putenv()s leak, so we manipulate environ directly */
1985 register I32 i=setenv_getix(nam); /* where does it go? */
1987 if (environ == PL_origenviron) { /* need we copy environment? */
1993 for (max = i; environ[max]; max++) ;
1994 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1995 for (j=0; j<max; j++) { /* copy environment */
1996 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1997 strcpy(tmpenv[j], environ[j]);
1999 tmpenv[max] = Nullch;
2000 environ = tmpenv; /* tell exec where it is now */
2003 safesysfree(environ[i]);
2004 while (environ[i]) {
2005 environ[i] = environ[i+1];
2010 if (!environ[i]) { /* does not exist yet */
2011 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2012 environ[i+1] = Nullch; /* make sure it's null terminated */
2015 safesysfree(environ[i]);
2016 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
2018 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
2020 #else /* PERL_USE_SAFE_PUTENV */
2021 # if defined(__CYGWIN__)
2022 setenv(nam, val, 1);
2026 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
2027 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
2028 (void)putenv(new_env);
2029 # endif /* __CYGWIN__ */
2030 #endif /* PERL_USE_SAFE_PUTENV */
2036 Perl_my_setenv(pTHX_ char *nam,char *val)
2039 #ifdef USE_WIN32_RTL_ENV
2041 register char *envstr;
2042 STRLEN namlen = strlen(nam);
2044 char *oldstr = environ[setenv_getix(nam)];
2046 /* putenv() has totally broken semantics in both the Borland
2047 * and Microsoft CRTLs. They either store the passed pointer in
2048 * the environment without making a copy, or make a copy and don't
2049 * free it. And on top of that, they dont free() old entries that
2050 * are being replaced/deleted. This means the caller must
2051 * free any old entries somehow, or we end up with a memory
2052 * leak every time my_setenv() is called. One might think
2053 * one could directly manipulate environ[], like the UNIX code
2054 * above, but direct changes to environ are not allowed when
2055 * calling putenv(), since the RTLs maintain an internal
2056 * *copy* of environ[]. Bad, bad, *bad* stink.
2067 vallen = strlen(val);
2068 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
2069 (void)sprintf(envstr,"%s=%s",nam,val);
2070 (void)PerlEnv_putenv(envstr);
2072 safesysfree(oldstr);
2074 safesysfree(envstr); /* MSVCRT leaks without this */
2077 #else /* !USE_WIN32_RTL_ENV */
2079 register char *envstr;
2080 STRLEN len = strlen(nam) + 3;
2085 New(904, envstr, len, char);
2086 (void)sprintf(envstr,"%s=%s",nam,val);
2087 (void)PerlEnv_putenv(envstr);
2096 Perl_setenv_getix(pTHX_ char *nam)
2098 register I32 i, len = strlen(nam);
2100 for (i = 0; environ[i]; i++) {
2103 strnicmp(environ[i],nam,len) == 0
2105 strnEQ(environ[i],nam,len)
2107 && environ[i][len] == '=')
2108 break; /* strnEQ must come first to avoid */
2109 } /* potential SEGV's */
2113 #endif /* !VMS && !EPOC*/
2115 #ifdef UNLINK_ALL_VERSIONS
2117 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2121 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2126 /* this is a drop-in replacement for bcopy() */
2127 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2129 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2133 if (from - to >= 0) {
2141 *(--to) = *(--from);
2147 /* this is a drop-in replacement for memset() */
2150 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2160 /* this is a drop-in replacement for bzero() */
2161 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2163 Perl_my_bzero(register char *loc, register I32 len)
2173 /* this is a drop-in replacement for memcmp() */
2174 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2176 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2178 register U8 *a = (U8 *)s1;
2179 register U8 *b = (U8 *)s2;
2183 if (tmp = *a++ - *b++)
2188 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2192 #ifdef USE_CHAR_VSPRINTF
2197 vsprintf(char *dest, const char *pat, char *args)
2201 fakebuf._ptr = dest;
2202 fakebuf._cnt = 32767;
2206 fakebuf._flag = _IOWRT|_IOSTRG;
2207 _doprnt(pat, args, &fakebuf); /* what a kludge */
2208 (void)putc('\0', &fakebuf);
2209 #ifdef USE_CHAR_VSPRINTF
2212 return 0; /* perl doesn't use return value */
2216 #endif /* HAS_VPRINTF */
2219 #if BYTEORDER != 0x4321
2221 Perl_my_swap(pTHX_ short s)
2223 #if (BYTEORDER & 1) == 0
2226 result = ((s & 255) << 8) + ((s >> 8) & 255);
2234 Perl_my_htonl(pTHX_ long l)
2238 char c[sizeof(long)];
2241 #if BYTEORDER == 0x1234
2242 u.c[0] = (l >> 24) & 255;
2243 u.c[1] = (l >> 16) & 255;
2244 u.c[2] = (l >> 8) & 255;
2248 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2249 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2254 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2255 u.c[o & 0xf] = (l >> s) & 255;
2263 Perl_my_ntohl(pTHX_ long l)
2267 char c[sizeof(long)];
2270 #if BYTEORDER == 0x1234
2271 u.c[0] = (l >> 24) & 255;
2272 u.c[1] = (l >> 16) & 255;
2273 u.c[2] = (l >> 8) & 255;
2277 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2278 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2285 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2286 l |= (u.c[o & 0xf] & 255) << s;
2293 #endif /* BYTEORDER != 0x4321 */
2297 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2298 * If these functions are defined,
2299 * the BYTEORDER is neither 0x1234 nor 0x4321.
2300 * However, this is not assumed.
2304 #define HTOV(name,type) \
2306 name (register type n) \
2310 char c[sizeof(type)]; \
2314 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2315 u.c[i] = (n >> s) & 0xFF; \
2320 #define VTOH(name,type) \
2322 name (register type n) \
2326 char c[sizeof(type)]; \
2332 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2333 n += (u.c[i] & 0xFF) << s; \
2338 #if defined(HAS_HTOVS) && !defined(htovs)
2341 #if defined(HAS_HTOVL) && !defined(htovl)
2344 #if defined(HAS_VTOHS) && !defined(vtohs)
2347 #if defined(HAS_VTOHL) && !defined(vtohl)
2351 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2352 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2354 Perl_my_popen(pTHX_ char *cmd, char *mode)
2357 register I32 This, that;
2360 I32 doexec = strNE(cmd,"-");
2364 PERL_FLUSHALL_FOR_CHILD;
2367 return my_syspopen(aTHX_ cmd,mode);
2370 This = (*mode == 'w');
2372 if (doexec && PL_tainting) {
2374 taint_proper("Insecure %s%s", "EXEC");
2376 if (PerlProc_pipe(p) < 0)
2378 if (doexec && PerlProc_pipe(pp) >= 0)
2380 while ((pid = (doexec?vfork():fork())) < 0) {
2381 if (errno != EAGAIN) {
2382 PerlLIO_close(p[This]);
2384 PerlLIO_close(pp[0]);
2385 PerlLIO_close(pp[1]);
2388 Perl_croak(aTHX_ "Can't fork");
2400 PerlLIO_close(p[THAT]);
2402 PerlLIO_close(pp[0]);
2403 #if defined(HAS_FCNTL) && defined(F_SETFD)
2404 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2407 if (p[THIS] != (*mode == 'r')) {
2408 PerlLIO_dup2(p[THIS], *mode == 'r');
2409 PerlLIO_close(p[THIS]);
2413 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2419 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2423 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2426 #endif /* defined OS2 */
2428 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
2429 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2431 hv_clear(PL_pidstatus); /* we have no children */
2436 do_execfree(); /* free any memory malloced by child on vfork */
2437 PerlLIO_close(p[that]);
2439 PerlLIO_close(pp[1]);
2440 if (p[that] < p[This]) {
2441 PerlLIO_dup2(p[This], p[that]);
2442 PerlLIO_close(p[This]);
2446 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2448 (void)SvUPGRADE(sv,SVt_IV);
2450 PL_forkprocess = pid;
2451 if (did_pipes && pid > 0) {
2455 while (n < sizeof(int)) {
2456 n1 = PerlLIO_read(pp[0],
2457 (void*)(((char*)&errkid)+n),
2463 PerlLIO_close(pp[0]);
2465 if (n) { /* Error */
2466 if (n != sizeof(int))
2467 Perl_croak(aTHX_ "panic: kid popen errno read");
2468 errno = errkid; /* Propagate errno from kid */
2473 PerlLIO_close(pp[0]);
2474 return PerlIO_fdopen(p[This], mode);
2477 #if defined(atarist) || defined(DJGPP)
2480 Perl_my_popen(pTHX_ char *cmd, char *mode)
2482 PERL_FLUSHALL_FOR_CHILD;
2483 /* Call system's popen() to get a FILE *, then import it.
2484 used 0 for 2nd parameter to PerlIO_importFILE;
2487 return PerlIO_importFILE(popen(cmd, mode), 0);
2491 #endif /* !DOSISH */
2495 Perl_dump_fds(pTHX_ char *s)
2498 struct stat tmpstatbuf;
2500 PerlIO_printf(Perl_debug_log,"%s", s);
2501 for (fd = 0; fd < 32; fd++) {
2502 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2503 PerlIO_printf(Perl_debug_log," %d",fd);
2505 PerlIO_printf(Perl_debug_log,"\n");
2507 #endif /* DUMP_FDS */
2511 dup2(int oldfd, int newfd)
2513 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2516 PerlLIO_close(newfd);
2517 return fcntl(oldfd, F_DUPFD, newfd);
2519 #define DUP2_MAX_FDS 256
2520 int fdtmp[DUP2_MAX_FDS];
2526 PerlLIO_close(newfd);
2527 /* good enough for low fd's... */
2528 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2529 if (fdx >= DUP2_MAX_FDS) {
2537 PerlLIO_close(fdtmp[--fdx]);
2544 #ifdef HAS_SIGACTION
2547 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2549 struct sigaction act, oact;
2551 act.sa_handler = handler;
2552 sigemptyset(&act.sa_mask);
2555 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2558 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2559 act.sa_flags |= SA_NOCLDWAIT;
2561 if (sigaction(signo, &act, &oact) == -1)
2564 return oact.sa_handler;
2568 Perl_rsignal_state(pTHX_ int signo)
2570 struct sigaction oact;
2572 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2575 return oact.sa_handler;
2579 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2581 struct sigaction act;
2583 act.sa_handler = handler;
2584 sigemptyset(&act.sa_mask);
2587 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2590 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2591 act.sa_flags |= SA_NOCLDWAIT;
2593 return sigaction(signo, &act, save);
2597 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2599 return sigaction(signo, save, (struct sigaction *)NULL);
2602 #else /* !HAS_SIGACTION */
2605 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2607 return PerlProc_signal(signo, handler);
2610 static int sig_trapped;
2620 Perl_rsignal_state(pTHX_ int signo)
2622 Sighandler_t oldsig;
2625 oldsig = PerlProc_signal(signo, sig_trap);
2626 PerlProc_signal(signo, oldsig);
2628 PerlProc_kill(PerlProc_getpid(), signo);
2633 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2635 *save = PerlProc_signal(signo, handler);
2636 return (*save == SIG_ERR) ? -1 : 0;
2640 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2642 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2645 #endif /* !HAS_SIGACTION */
2646 #endif /* !PERL_MICRO */
2648 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2649 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2651 Perl_my_pclose(pTHX_ PerlIO *ptr)
2653 Sigsave_t hstat, istat, qstat;
2661 int saved_vaxc_errno;
2664 int saved_win32_errno;
2668 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2672 *svp = &PL_sv_undef;
2674 if (pid == -1) { /* Opened by popen. */
2675 return my_syspclose(ptr);
2678 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2679 saved_errno = errno;
2681 saved_vaxc_errno = vaxc$errno;
2684 saved_win32_errno = GetLastError();
2688 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2691 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2692 rsignal_save(SIGINT, SIG_IGN, &istat);
2693 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2696 pid2 = wait4pid(pid, &status, 0);
2697 } while (pid2 == -1 && errno == EINTR);
2699 rsignal_restore(SIGHUP, &hstat);
2700 rsignal_restore(SIGINT, &istat);
2701 rsignal_restore(SIGQUIT, &qstat);
2704 SETERRNO(saved_errno, saved_vaxc_errno);
2707 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2709 #endif /* !DOSISH */
2711 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2713 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2717 char spid[TYPE_CHARS(int)];
2721 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2723 sprintf(spid, "%"IVdf, (IV)pid);
2724 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2725 if (svp && *svp != &PL_sv_undef) {
2726 *statusp = SvIVX(*svp);
2727 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2734 hv_iterinit(PL_pidstatus);
2735 if ((entry = hv_iternext(PL_pidstatus))) {
2736 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2737 sv = hv_iterval(PL_pidstatus,entry);
2738 *statusp = SvIVX(sv);
2739 sprintf(spid, "%"IVdf, (IV)pid);
2740 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2746 # ifdef HAS_WAITPID_RUNTIME
2747 if (!HAS_WAITPID_RUNTIME)
2750 return PerlProc_waitpid(pid,statusp,flags);
2752 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2753 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2755 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2760 Perl_croak(aTHX_ "Can't do waitpid with flags");
2762 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2763 pidgone(result,*statusp);
2771 #endif /* !DOSISH || OS2 || WIN32 */
2775 Perl_pidgone(pTHX_ Pid_t pid, int status)
2778 char spid[TYPE_CHARS(int)];
2780 sprintf(spid, "%"IVdf, (IV)pid);
2781 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2782 (void)SvUPGRADE(sv,SVt_IV);
2787 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2790 int /* Cannot prototype with I32
2792 my_syspclose(PerlIO *ptr)
2795 Perl_my_pclose(pTHX_ PerlIO *ptr)
2798 /* Needs work for PerlIO ! */
2799 FILE *f = PerlIO_findFILE(ptr);
2800 I32 result = pclose(f);
2802 result = (result << 8) & 0xff00;
2804 PerlIO_releaseFILE(ptr,f);
2810 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2813 register const char *frombase = from;
2816 register const char c = *from;
2821 while (count-- > 0) {
2822 for (todo = len; todo > 0; todo--) {
2830 Perl_cast_ulong(pTHX_ NV f)
2835 # define BIGDOUBLE 2147483648.0
2837 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2840 return (unsigned long)f;
2842 return (unsigned long)along;
2846 /* Unfortunately, on some systems the cast_uv() function doesn't
2847 work with the system-supplied definition of ULONG_MAX. The
2848 comparison (f >= ULONG_MAX) always comes out true. It must be a
2849 problem with the compiler constant folding.
2851 In any case, this workaround should be fine on any two's complement
2852 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2854 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2857 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2859 -- Kenneth Albanowski <kjahds@kjahds.com>
2863 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2867 Perl_cast_i32(pTHX_ NV f)
2870 return (I32) I32_MAX;
2872 return (I32) I32_MIN;
2877 Perl_cast_iv(pTHX_ NV f)
2882 if (f >= (NV)UV_MAX)
2893 Perl_cast_uv(pTHX_ NV f)
2896 return (UV) MY_UV_MAX;
2910 Perl_same_dirent(pTHX_ char *a, char *b)
2912 char *fa = strrchr(a,'/');
2913 char *fb = strrchr(b,'/');
2914 struct stat tmpstatbuf1;
2915 struct stat tmpstatbuf2;
2916 SV *tmpsv = sv_newmortal();
2929 sv_setpv(tmpsv, ".");
2931 sv_setpvn(tmpsv, a, fa - a);
2932 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2935 sv_setpv(tmpsv, ".");
2937 sv_setpvn(tmpsv, b, fb - b);
2938 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2940 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2941 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2943 #endif /* !HAS_RENAME */
2946 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
2948 register char *s = start;
2949 register NV rnv = 0.0;
2950 register UV ruv = 0;
2951 register bool seenb = FALSE;
2952 register bool overflowed = FALSE;
2954 for (; len-- && *s; s++) {
2955 if (!(*s == '0' || *s == '1')) {
2956 if (*s == '_' && len && *retlen
2957 && (s[1] == '0' || s[1] == '1'))
2962 else if (seenb == FALSE && *s == 'b' && ruv == 0) {
2963 /* Disallow 0bbb0b0bbb... */
2969 if (ckWARN(WARN_DIGIT))
2970 Perl_warner(aTHX_ WARN_DIGIT,
2971 "Illegal binary digit '%c' ignored", *s);
2976 register UV xuv = ruv << 1;
2978 if ((xuv >> 1) != ruv) {
2982 if (ckWARN_d(WARN_OVERFLOW))
2983 Perl_warner(aTHX_ WARN_OVERFLOW,
2984 "Integer overflow in binary number");
2987 ruv = xuv | (*s - '0');
2991 /* If an NV has not enough bits in its mantissa to
2992 * represent an UV this summing of small low-order numbers
2993 * is a waste of time (because the NV cannot preserve
2994 * the low-order bits anyway): we could just remember when
2995 * did we overflow and in the end just multiply rnv by the
3002 if ( ( overflowed && rnv > 4294967295.0)
3004 || (!overflowed && ruv > 0xffffffff )
3008 if (ckWARN(WARN_PORTABLE))
3009 Perl_warner(aTHX_ WARN_PORTABLE,
3010 "Binary number > 0b11111111111111111111111111111111 non-portable");
3012 *retlen = s - start;
3017 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3019 register char *s = start;
3020 register NV rnv = 0.0;
3021 register UV ruv = 0;
3022 register bool overflowed = FALSE;
3024 for (; len-- && *s; s++) {
3025 if (!(*s >= '0' && *s <= '7')) {
3026 if (*s == '_' && len && *retlen
3027 && (s[1] >= '0' && s[1] <= '7'))
3033 /* Allow \octal to work the DWIM way (that is, stop scanning
3034 * as soon as non-octal characters are seen, complain only iff
3035 * someone seems to want to use the digits eight and nine). */
3036 if (*s == '8' || *s == '9') {
3038 if (ckWARN(WARN_DIGIT))
3039 Perl_warner(aTHX_ WARN_DIGIT,
3040 "Illegal octal digit '%c' ignored", *s);
3046 register UV xuv = ruv << 3;
3048 if ((xuv >> 3) != ruv) {
3052 if (ckWARN_d(WARN_OVERFLOW))
3053 Perl_warner(aTHX_ WARN_OVERFLOW,
3054 "Integer overflow in octal number");
3057 ruv = xuv | (*s - '0');
3061 /* If an NV has not enough bits in its mantissa to
3062 * represent an UV this summing of small low-order numbers
3063 * is a waste of time (because the NV cannot preserve
3064 * the low-order bits anyway): we could just remember when
3065 * did we overflow and in the end just multiply rnv by the
3066 * right amount of 8-tuples. */
3067 rnv += (NV)(*s - '0');
3072 if ( ( overflowed && rnv > 4294967295.0)
3074 || (!overflowed && ruv > 0xffffffff )
3078 if (ckWARN(WARN_PORTABLE))
3079 Perl_warner(aTHX_ WARN_PORTABLE,
3080 "Octal number > 037777777777 non-portable");
3082 *retlen = s - start;
3087 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3089 register char *s = start;
3090 register NV rnv = 0.0;
3091 register UV ruv = 0;
3092 register bool overflowed = FALSE;
3100 else if (len > 3 && s[0] == '0' && s[1] == 'x') {
3106 for (; len-- && *s; s++) {
3107 hexdigit = strchr((char *) PL_hexdigit, *s);
3109 if (*s == '_' && len && *retlen && s[1]
3110 && (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) {
3130 if (ckWARN_d(WARN_OVERFLOW))
3131 Perl_warner(aTHX_ WARN_OVERFLOW,
3132 "Integer overflow in hexadecimal number");
3135 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
3139 /* If an NV has not enough bits in its mantissa to
3140 * represent an UV this summing of small low-order numbers
3141 * is a waste of time (because the NV cannot preserve
3142 * the low-order bits anyway): we could just remember when
3143 * did we overflow and in the end just multiply rnv by the
3144 * right amount of 16-tuples. */
3145 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
3150 if ( ( overflowed && rnv > 4294967295.0)
3152 || (!overflowed && ruv > 0xffffffff )
3156 if (ckWARN(WARN_PORTABLE))
3157 Perl_warner(aTHX_ WARN_PORTABLE,
3158 "Hexadecimal number > 0xffffffff non-portable");
3160 *retlen = s - start;
3165 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
3168 char *xfound = Nullch;
3169 char *xfailed = Nullch;
3170 char tmpbuf[MAXPATHLEN];
3174 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3175 # define SEARCH_EXTS ".bat", ".cmd", NULL
3176 # define MAX_EXT_LEN 4
3179 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3180 # define MAX_EXT_LEN 4
3183 # define SEARCH_EXTS ".pl", ".com", NULL
3184 # define MAX_EXT_LEN 4
3186 /* additional extensions to try in each dir if scriptname not found */
3188 char *exts[] = { SEARCH_EXTS };
3189 char **ext = search_ext ? search_ext : exts;
3190 int extidx = 0, i = 0;
3191 char *curext = Nullch;
3193 # define MAX_EXT_LEN 0
3197 * If dosearch is true and if scriptname does not contain path
3198 * delimiters, search the PATH for scriptname.
3200 * If SEARCH_EXTS is also defined, will look for each
3201 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3202 * while searching the PATH.
3204 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3205 * proceeds as follows:
3206 * If DOSISH or VMSISH:
3207 * + look for ./scriptname{,.foo,.bar}
3208 * + search the PATH for scriptname{,.foo,.bar}
3211 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3212 * this will not look in '.' if it's not in the PATH)
3217 # ifdef ALWAYS_DEFTYPES
3218 len = strlen(scriptname);
3219 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3220 int hasdir, idx = 0, deftypes = 1;
3223 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3226 int hasdir, idx = 0, deftypes = 1;
3229 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3231 /* The first time through, just add SEARCH_EXTS to whatever we
3232 * already have, so we can check for default file types. */
3234 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3240 if ((strlen(tmpbuf) + strlen(scriptname)
3241 + MAX_EXT_LEN) >= sizeof tmpbuf)
3242 continue; /* don't search dir with too-long name */
3243 strcat(tmpbuf, scriptname);
3247 if (strEQ(scriptname, "-"))
3249 if (dosearch) { /* Look in '.' first. */
3250 char *cur = scriptname;
3252 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3254 if (strEQ(ext[i++],curext)) {
3255 extidx = -1; /* already has an ext */
3260 DEBUG_p(PerlIO_printf(Perl_debug_log,
3261 "Looking for %s\n",cur));
3262 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3263 && !S_ISDIR(PL_statbuf.st_mode)) {
3271 if (cur == scriptname) {
3272 len = strlen(scriptname);
3273 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3275 cur = strcpy(tmpbuf, scriptname);
3277 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3278 && strcpy(tmpbuf+len, ext[extidx++]));
3283 #ifdef MACOS_TRADITIONAL
3284 if (dosearch && !strchr(scriptname, ':') &&
3285 (s = PerlEnv_getenv("Commands")))
3287 if (dosearch && !strchr(scriptname, '/')
3289 && !strchr(scriptname, '\\')
3291 && (s = PerlEnv_getenv("PATH")))
3296 PL_bufend = s + strlen(s);
3297 while (s < PL_bufend) {
3298 #ifdef MACOS_TRADITIONAL
3299 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3303 #if defined(atarist) || defined(DOSISH)
3308 && *s != ';'; len++, s++) {
3309 if (len < sizeof tmpbuf)
3312 if (len < sizeof tmpbuf)
3314 #else /* ! (atarist || DOSISH) */
3315 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3318 #endif /* ! (atarist || DOSISH) */
3319 #endif /* MACOS_TRADITIONAL */
3322 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3323 continue; /* don't search dir with too-long name */
3324 #ifdef MACOS_TRADITIONAL
3325 if (len && tmpbuf[len - 1] != ':')
3326 tmpbuf[len++] = ':';
3329 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3330 && tmpbuf[len - 1] != '/'
3331 && tmpbuf[len - 1] != '\\'
3334 tmpbuf[len++] = '/';
3335 if (len == 2 && tmpbuf[0] == '.')
3338 (void)strcpy(tmpbuf + len, scriptname);
3342 len = strlen(tmpbuf);
3343 if (extidx > 0) /* reset after previous loop */
3347 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3348 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3349 if (S_ISDIR(PL_statbuf.st_mode)) {
3353 } while ( retval < 0 /* not there */
3354 && extidx>=0 && ext[extidx] /* try an extension? */
3355 && strcpy(tmpbuf+len, ext[extidx++])
3360 if (S_ISREG(PL_statbuf.st_mode)
3361 && cando(S_IRUSR,TRUE,&PL_statbuf)
3362 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3363 && cando(S_IXUSR,TRUE,&PL_statbuf)
3367 xfound = tmpbuf; /* bingo! */
3371 xfailed = savepv(tmpbuf);
3374 if (!xfound && !seen_dot && !xfailed &&
3375 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3376 || S_ISDIR(PL_statbuf.st_mode)))
3378 seen_dot = 1; /* Disable message. */
3380 if (flags & 1) { /* do or die? */
3381 Perl_croak(aTHX_ "Can't %s %s%s%s",
3382 (xfailed ? "execute" : "find"),
3383 (xfailed ? xfailed : scriptname),
3384 (xfailed ? "" : " on PATH"),
3385 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3387 scriptname = Nullch;
3391 scriptname = xfound;
3393 return (scriptname ? savepv(scriptname) : Nullch);
3396 #ifndef PERL_GET_CONTEXT_DEFINED
3399 Perl_get_context(void)
3401 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3402 # ifdef OLD_PTHREADS_API
3404 if (pthread_getspecific(PL_thr_key, &t))
3405 Perl_croak_nocontext("panic: pthread_getspecific");
3408 # ifdef I_MACH_CTHREADS
3409 return (void*)cthread_data(cthread_self());
3411 return (void*)pthread_getspecific(PL_thr_key);
3420 Perl_set_context(void *t)
3422 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3423 # ifdef I_MACH_CTHREADS
3424 cthread_set_data(cthread_self(), t);
3426 if (pthread_setspecific(PL_thr_key, t))
3427 Perl_croak_nocontext("panic: pthread_setspecific");
3432 #endif /* !PERL_GET_CONTEXT_DEFINED */
3437 /* Very simplistic scheduler for now */
3441 thr = thr->i.next_run;
3445 Perl_cond_init(pTHX_ perl_cond *cp)
3451 Perl_cond_signal(pTHX_ perl_cond *cp)
3454 perl_cond cond = *cp;
3459 /* Insert t in the runnable queue just ahead of us */
3460 t->i.next_run = thr->i.next_run;
3461 thr->i.next_run->i.prev_run = t;
3462 t->i.prev_run = thr;
3463 thr->i.next_run = t;
3464 thr->i.wait_queue = 0;
3465 /* Remove from the wait queue */
3471 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3474 perl_cond cond, cond_next;
3476 for (cond = *cp; cond; cond = cond_next) {
3478 /* Insert t in the runnable queue just ahead of us */
3479 t->i.next_run = thr->i.next_run;
3480 thr->i.next_run->i.prev_run = t;
3481 t->i.prev_run = thr;
3482 thr->i.next_run = t;
3483 thr->i.wait_queue = 0;
3484 /* Remove from the wait queue */
3485 cond_next = cond->next;
3492 Perl_cond_wait(pTHX_ perl_cond *cp)
3496 if (thr->i.next_run == thr)
3497 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3499 New(666, cond, 1, struct perl_wait_queue);
3503 thr->i.wait_queue = cond;
3504 /* Remove ourselves from runnable queue */
3505 thr->i.next_run->i.prev_run = thr->i.prev_run;
3506 thr->i.prev_run->i.next_run = thr->i.next_run;
3508 #endif /* FAKE_THREADS */
3511 Perl_condpair_magic(pTHX_ SV *sv)
3515 SvUPGRADE(sv, SVt_PVMG);
3516 mg = mg_find(sv, 'm');
3520 New(53, cp, 1, condpair_t);
3521 MUTEX_INIT(&cp->mutex);
3522 COND_INIT(&cp->owner_cond);
3523 COND_INIT(&cp->cond);
3525 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3526 mg = mg_find(sv, 'm');
3528 /* someone else beat us to initialising it */
3529 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3530 MUTEX_DESTROY(&cp->mutex);
3531 COND_DESTROY(&cp->owner_cond);
3532 COND_DESTROY(&cp->cond);
3536 sv_magic(sv, Nullsv, 'm', 0, 0);
3538 mg->mg_ptr = (char *)cp;
3539 mg->mg_len = sizeof(cp);
3540 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3541 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3542 "%p: condpair_magic %p\n", thr, sv));)
3549 Perl_sv_lock(pTHX_ SV *osv)
3559 mg = condpair_magic(sv);
3560 MUTEX_LOCK(MgMUTEXP(mg));
3561 if (MgOWNER(mg) == thr)
3562 MUTEX_UNLOCK(MgMUTEXP(mg));
3565 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3567 DEBUG_S(PerlIO_printf(Perl_debug_log,
3568 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3569 PTR2UV(thr), PTR2UV(sv));)
3570 MUTEX_UNLOCK(MgMUTEXP(mg));
3571 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3573 UNLOCK_SV_LOCK_MUTEX;
3578 * Make a new perl thread structure using t as a prototype. Some of the
3579 * fields for the new thread are copied from the prototype thread, t,
3580 * so t should not be running in perl at the time this function is
3581 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3582 * thread calling new_struct_thread) clearly satisfies this constraint.
3584 struct perl_thread *
3585 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3587 #if !defined(PERL_IMPLICIT_CONTEXT)
3588 struct perl_thread *thr;
3594 sv = newSVpvn("", 0);
3595 SvGROW(sv, sizeof(struct perl_thread) + 1);
3596 SvCUR_set(sv, sizeof(struct perl_thread));
3597 thr = (Thread) SvPVX(sv);
3599 memset(thr, 0xab, sizeof(struct perl_thread));
3606 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3607 PL_efloatbuf = (char*)NULL;
3610 Zero(thr, 1, struct perl_thread);
3616 PL_curcop = &PL_compiling;
3617 thr->interp = t->interp;
3618 thr->cvcache = newHV();
3619 thr->threadsv = newAV();
3620 thr->specific = newAV();
3621 thr->errsv = newSVpvn("", 0);
3622 thr->flags = THRf_R_JOINABLE;
3624 MUTEX_INIT(&thr->mutex);
3628 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3631 PL_statname = NEWSV(66,0);
3632 PL_errors = newSVpvn("", 0);
3634 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3635 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3636 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3637 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3638 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3640 PL_reginterp_cnt = 0;
3641 PL_lastscream = Nullsv;
3644 PL_reg_start_tmp = 0;
3645 PL_reg_start_tmpl = 0;
3646 PL_reg_poscache = Nullch;
3648 /* parent thread's data needs to be locked while we make copy */
3649 MUTEX_LOCK(&t->mutex);
3651 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3652 PL_protect = t->Tprotect;
3655 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3656 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3657 PL_curstash = t->Tcurstash; /* always be set to main? */
3659 PL_tainted = t->Ttainted;
3660 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3661 PL_nrs = newSVsv(t->Tnrs);
3662 PL_rs = SvREFCNT_inc(PL_nrs);
3663 PL_last_in_gv = Nullgv;
3664 PL_ofslen = t->Tofslen;
3665 PL_ofs = savepvn(t->Tofs, PL_ofslen);
3666 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3667 PL_chopset = t->Tchopset;
3668 PL_bodytarget = newSVsv(t->Tbodytarget);
3669 PL_toptarget = newSVsv(t->Ttoptarget);
3670 if (t->Tformtarget == t->Ttoptarget)
3671 PL_formtarget = PL_toptarget;
3673 PL_formtarget = PL_bodytarget;
3675 /* Initialise all per-thread SVs that the template thread used */
3676 svp = AvARRAY(t->threadsv);
3677 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3678 if (*svp && *svp != &PL_sv_undef) {
3679 SV *sv = newSVsv(*svp);
3680 av_store(thr->threadsv, i, sv);
3681 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3682 DEBUG_S(PerlIO_printf(Perl_debug_log,
3683 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3687 thr->threadsvp = AvARRAY(thr->threadsv);
3689 MUTEX_LOCK(&PL_threads_mutex);
3691 thr->tid = ++PL_threadnum;
3692 thr->next = t->next;
3695 thr->next->prev = thr;
3696 MUTEX_UNLOCK(&PL_threads_mutex);
3698 /* done copying parent's state */
3699 MUTEX_UNLOCK(&t->mutex);
3701 #ifdef HAVE_THREAD_INTERN
3702 Perl_init_thread_intern(thr);
3703 #endif /* HAVE_THREAD_INTERN */
3706 #endif /* USE_THREADS */
3708 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
3710 * This hack is to force load of "huge" support from libm.a
3711 * So it is in perl for (say) POSIX to use.
3712 * Needed for SunOS with Sun's 'acc' for example.
3717 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
3724 #ifdef PERL_GLOBAL_STRUCT
3733 Perl_get_op_names(pTHX)
3739 Perl_get_op_descs(pTHX)
3745 Perl_get_no_modify(pTHX)
3747 return (char*)PL_no_modify;
3751 Perl_get_opargs(pTHX)
3757 Perl_get_ppaddr(pTHX)
3759 return (PPADDR_t*)PL_ppaddr;
3762 #ifndef HAS_GETENV_LEN
3764 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3766 char *env_trans = PerlEnv_getenv(env_elem);
3768 *len = strlen(env_trans);
3775 Perl_get_vtbl(pTHX_ int vtbl_id)
3777 MGVTBL* result = Null(MGVTBL*);
3781 result = &PL_vtbl_sv;
3784 result = &PL_vtbl_env;
3786 case want_vtbl_envelem:
3787 result = &PL_vtbl_envelem;
3790 result = &PL_vtbl_sig;
3792 case want_vtbl_sigelem:
3793 result = &PL_vtbl_sigelem;
3795 case want_vtbl_pack:
3796 result = &PL_vtbl_pack;
3798 case want_vtbl_packelem:
3799 result = &PL_vtbl_packelem;
3801 case want_vtbl_dbline:
3802 result = &PL_vtbl_dbline;
3805 result = &PL_vtbl_isa;
3807 case want_vtbl_isaelem:
3808 result = &PL_vtbl_isaelem;
3810 case want_vtbl_arylen:
3811 result = &PL_vtbl_arylen;
3813 case want_vtbl_glob:
3814 result = &PL_vtbl_glob;
3816 case want_vtbl_mglob:
3817 result = &PL_vtbl_mglob;
3819 case want_vtbl_nkeys:
3820 result = &PL_vtbl_nkeys;
3822 case want_vtbl_taint:
3823 result = &PL_vtbl_taint;
3825 case want_vtbl_substr:
3826 result = &PL_vtbl_substr;
3829 result = &PL_vtbl_vec;
3832 result = &PL_vtbl_pos;
3835 result = &PL_vtbl_bm;
3838 result = &PL_vtbl_fm;
3840 case want_vtbl_uvar:
3841 result = &PL_vtbl_uvar;
3844 case want_vtbl_mutex:
3845 result = &PL_vtbl_mutex;
3848 case want_vtbl_defelem:
3849 result = &PL_vtbl_defelem;
3851 case want_vtbl_regexp:
3852 result = &PL_vtbl_regexp;
3854 case want_vtbl_regdata:
3855 result = &PL_vtbl_regdata;
3857 case want_vtbl_regdatum:
3858 result = &PL_vtbl_regdatum;
3860 #ifdef USE_LOCALE_COLLATE
3861 case want_vtbl_collxfrm:
3862 result = &PL_vtbl_collxfrm;
3865 case want_vtbl_amagic:
3866 result = &PL_vtbl_amagic;
3868 case want_vtbl_amagicelem:
3869 result = &PL_vtbl_amagicelem;
3871 case want_vtbl_backref:
3872 result = &PL_vtbl_backref;
3879 Perl_my_fflush_all(pTHX)
3881 #if defined(FFLUSH_NULL)
3882 return PerlIO_flush(NULL);
3884 # if defined(HAS__FWALK)
3885 /* undocumented, unprototyped, but very useful BSDism */
3886 extern void _fwalk(int (*)(FILE *));
3891 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3892 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3893 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3895 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3896 open_max = sysconf(_SC_OPEN_MAX);
3899 open_max = FOPEN_MAX;
3902 open_max = OPEN_MAX;
3913 for (i = 0; i < open_max; i++)
3914 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3915 STDIO_STREAM_ARRAY[i]._file < open_max &&
3916 STDIO_STREAM_ARRAY[i]._flag)
3917 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3921 SETERRNO(EBADF,RMS$_IFI);
3928 Perl_my_atof(pTHX_ const char* s)
3931 #ifdef USE_LOCALE_NUMERIC
3932 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3936 SET_NUMERIC_STANDARD();
3938 SET_NUMERIC_LOCAL();
3939 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
3951 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3956 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3957 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3959 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3960 char *type = OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET) ?
3961 "socket" : "filehandle";
3964 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3966 warn_type = WARN_CLOSED;
3970 warn_type = WARN_UNOPENED;
3973 if (gv && isGV(gv)) {
3974 SV *sv = sv_newmortal();
3975 gv_efullname4(sv, gv, Nullch, FALSE);
3979 if (name && *name) {
3980 Perl_warner(aTHX_ warn_type,
3981 "%s%s on %s %s %s", func, pars, vile, type, name);
3982 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3983 Perl_warner(aTHX_ warn_type,
3984 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3988 Perl_warner(aTHX_ warn_type,
3989 "%s%s on %s %s", func, pars, vile, type);
3990 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3991 Perl_warner(aTHX_ warn_type,
3992 "\t(Are you trying to call %s%s on dirhandle?)\n",