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 if (PL_collation_name)
549 Safefree(PL_collation_name);
550 PL_collation_name = stdize_locale(newcoll);
551 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
554 /* 2: at most so many chars ('a', 'b'). */
555 /* 50: surely no system expands a char more. */
556 #define XFRMBUFSIZE (2 * 50)
557 char xbuf[XFRMBUFSIZE];
558 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
559 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
560 SSize_t mult = fb - fa;
562 Perl_croak(aTHX_ "strxfrm() gets absurd");
563 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
564 PL_collxfrm_mult = mult;
568 #endif /* USE_LOCALE_COLLATE */
572 Perl_set_numeric_radix(pTHX)
574 #ifdef USE_LOCALE_NUMERIC
575 # ifdef HAS_LOCALECONV
579 if (lc && lc->decimal_point)
580 /* We assume that decimal separator aka the radix
581 * character is always a single character. If it
582 * ever is a string, this needs to be rethunk. */
583 PL_numeric_radix = *lc->decimal_point;
585 PL_numeric_radix = 0;
586 # endif /* HAS_LOCALECONV */
587 #endif /* USE_LOCALE_NUMERIC */
591 * Set up for a new numeric locale.
594 Perl_new_numeric(pTHX_ char *newnum)
596 #ifdef USE_LOCALE_NUMERIC
599 if (PL_numeric_name) {
600 Safefree(PL_numeric_name);
601 PL_numeric_name = NULL;
603 PL_numeric_standard = TRUE;
604 PL_numeric_local = TRUE;
608 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
610 Safefree(PL_numeric_name);
611 PL_numeric_name = stdize_locale(newnum);
612 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
613 PL_numeric_local = TRUE;
617 #endif /* USE_LOCALE_NUMERIC */
621 Perl_set_numeric_standard(pTHX)
623 #ifdef USE_LOCALE_NUMERIC
625 if (! PL_numeric_standard) {
626 setlocale(LC_NUMERIC, "C");
627 PL_numeric_standard = TRUE;
628 PL_numeric_local = FALSE;
632 #endif /* USE_LOCALE_NUMERIC */
636 Perl_set_numeric_local(pTHX)
638 #ifdef USE_LOCALE_NUMERIC
640 if (! PL_numeric_local) {
641 setlocale(LC_NUMERIC, PL_numeric_name);
642 PL_numeric_standard = FALSE;
643 PL_numeric_local = TRUE;
647 #endif /* USE_LOCALE_NUMERIC */
651 * Initialize locale awareness.
654 Perl_init_i18nl10n(pTHX_ int printwarn)
658 * 1 = set ok or not applicable,
659 * 0 = fallback to C locale,
660 * -1 = fallback to C locale failed
665 #ifdef USE_LOCALE_CTYPE
666 char *curctype = NULL;
667 #endif /* USE_LOCALE_CTYPE */
668 #ifdef USE_LOCALE_COLLATE
669 char *curcoll = NULL;
670 #endif /* USE_LOCALE_COLLATE */
671 #ifdef USE_LOCALE_NUMERIC
673 #endif /* USE_LOCALE_NUMERIC */
675 char *language = PerlEnv_getenv("LANGUAGE");
677 char *lc_all = PerlEnv_getenv("LC_ALL");
678 char *lang = PerlEnv_getenv("LANG");
679 bool setlocale_failure = FALSE;
681 #ifdef LOCALE_ENVIRON_REQUIRED
684 * Ultrix setlocale(..., "") fails if there are no environment
685 * variables from which to get a locale name.
692 if (setlocale(LC_ALL, ""))
695 setlocale_failure = TRUE;
697 if (!setlocale_failure) {
698 #ifdef USE_LOCALE_CTYPE
701 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
703 setlocale_failure = TRUE;
705 curctype = savepv(curctype);
706 #endif /* USE_LOCALE_CTYPE */
707 #ifdef USE_LOCALE_COLLATE
709 setlocale(LC_COLLATE,
710 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
712 setlocale_failure = TRUE;
714 curcoll = savepv(curcoll);
715 #endif /* USE_LOCALE_COLLATE */
716 #ifdef USE_LOCALE_NUMERIC
718 setlocale(LC_NUMERIC,
719 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
721 setlocale_failure = TRUE;
723 curnum = savepv(curnum);
724 #endif /* USE_LOCALE_NUMERIC */
729 #endif /* !LOCALE_ENVIRON_REQUIRED */
732 if (! setlocale(LC_ALL, ""))
733 setlocale_failure = TRUE;
736 if (!setlocale_failure) {
737 #ifdef USE_LOCALE_CTYPE
738 if (! (curctype = setlocale(LC_CTYPE, "")))
739 setlocale_failure = TRUE;
741 curctype = savepv(curctype);
742 #endif /* USE_LOCALE_CTYPE */
743 #ifdef USE_LOCALE_COLLATE
744 if (! (curcoll = setlocale(LC_COLLATE, "")))
745 setlocale_failure = TRUE;
747 curcoll = savepv(curcoll);
748 #endif /* USE_LOCALE_COLLATE */
749 #ifdef USE_LOCALE_NUMERIC
750 if (! (curnum = setlocale(LC_NUMERIC, "")))
751 setlocale_failure = TRUE;
753 curnum = savepv(curnum);
754 #endif /* USE_LOCALE_NUMERIC */
757 if (setlocale_failure) {
759 bool locwarn = (printwarn > 1 ||
761 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
766 PerlIO_printf(Perl_error_log,
767 "perl: warning: Setting locale failed.\n");
771 PerlIO_printf(Perl_error_log,
772 "perl: warning: Setting locale failed for the categories:\n\t");
773 #ifdef USE_LOCALE_CTYPE
775 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
776 #endif /* USE_LOCALE_CTYPE */
777 #ifdef USE_LOCALE_COLLATE
779 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
780 #endif /* USE_LOCALE_COLLATE */
781 #ifdef USE_LOCALE_NUMERIC
783 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
784 #endif /* USE_LOCALE_NUMERIC */
785 PerlIO_printf(Perl_error_log, "\n");
789 PerlIO_printf(Perl_error_log,
790 "perl: warning: Please check that your locale settings:\n");
793 PerlIO_printf(Perl_error_log,
794 "\tLANGUAGE = %c%s%c,\n",
795 language ? '"' : '(',
796 language ? language : "unset",
797 language ? '"' : ')');
800 PerlIO_printf(Perl_error_log,
801 "\tLC_ALL = %c%s%c,\n",
803 lc_all ? lc_all : "unset",
808 for (e = environ; *e; e++) {
809 if (strnEQ(*e, "LC_", 3)
810 && strnNE(*e, "LC_ALL=", 7)
811 && (p = strchr(*e, '=')))
812 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
813 (int)(p - *e), *e, p + 1);
817 PerlIO_printf(Perl_error_log,
820 lang ? lang : "unset",
823 PerlIO_printf(Perl_error_log,
824 " are supported and installed on your system.\n");
829 if (setlocale(LC_ALL, "C")) {
831 PerlIO_printf(Perl_error_log,
832 "perl: warning: Falling back to the standard locale (\"C\").\n");
837 PerlIO_printf(Perl_error_log,
838 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
845 #ifdef USE_LOCALE_CTYPE
846 || !(curctype || setlocale(LC_CTYPE, "C"))
847 #endif /* USE_LOCALE_CTYPE */
848 #ifdef USE_LOCALE_COLLATE
849 || !(curcoll || setlocale(LC_COLLATE, "C"))
850 #endif /* USE_LOCALE_COLLATE */
851 #ifdef USE_LOCALE_NUMERIC
852 || !(curnum || setlocale(LC_NUMERIC, "C"))
853 #endif /* USE_LOCALE_NUMERIC */
857 PerlIO_printf(Perl_error_log,
858 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
862 #endif /* ! LC_ALL */
864 #ifdef USE_LOCALE_CTYPE
865 curctype = savepv(setlocale(LC_CTYPE, Nullch));
866 #endif /* USE_LOCALE_CTYPE */
867 #ifdef USE_LOCALE_COLLATE
868 curcoll = savepv(setlocale(LC_COLLATE, Nullch));
869 #endif /* USE_LOCALE_COLLATE */
870 #ifdef USE_LOCALE_NUMERIC
871 curnum = savepv(setlocale(LC_NUMERIC, Nullch));
872 #endif /* USE_LOCALE_NUMERIC */
876 #ifdef USE_LOCALE_CTYPE
878 #endif /* USE_LOCALE_CTYPE */
880 #ifdef USE_LOCALE_COLLATE
881 new_collate(curcoll);
882 #endif /* USE_LOCALE_COLLATE */
884 #ifdef USE_LOCALE_NUMERIC
886 #endif /* USE_LOCALE_NUMERIC */
889 #endif /* USE_LOCALE */
891 #ifdef USE_LOCALE_CTYPE
892 if (curctype != NULL)
894 #endif /* USE_LOCALE_CTYPE */
895 #ifdef USE_LOCALE_COLLATE
898 #endif /* USE_LOCALE_COLLATE */
899 #ifdef USE_LOCALE_NUMERIC
902 #endif /* USE_LOCALE_NUMERIC */
906 /* Backwards compatibility. */
908 Perl_init_i18nl14n(pTHX_ int printwarn)
910 return init_i18nl10n(printwarn);
913 #ifdef USE_LOCALE_COLLATE
916 * mem_collxfrm() is a bit like strxfrm() but with two important
917 * differences. First, it handles embedded NULs. Second, it allocates
918 * a bit more memory than needed for the transformed data itself.
919 * The real transformed data begins at offset sizeof(collationix).
920 * Please see sv_collxfrm() to see how this is used.
923 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
926 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
928 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
929 /* the +1 is for the terminating NUL. */
931 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
932 New(171, xbuf, xAlloc, char);
936 *(U32*)xbuf = PL_collation_ix;
937 xout = sizeof(PL_collation_ix);
938 for (xin = 0; xin < len; ) {
942 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
945 if (xused < xAlloc - xout)
947 xAlloc = (2 * xAlloc) + 1;
948 Renew(xbuf, xAlloc, char);
953 xin += strlen(s + xin) + 1;
956 /* Embedded NULs are understood but silently skipped
957 * because they make no sense in locale collation. */
961 *xlen = xout - sizeof(PL_collation_ix);
970 #endif /* USE_LOCALE_COLLATE */
972 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
974 /* As a space optimization, we do not compile tables for strings of length
975 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
976 special-cased in fbm_instr().
978 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
981 =for apidoc fbm_compile
983 Analyses the string in order to make fast searches on it using fbm_instr()
984 -- the Boyer-Moore algorithm.
990 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
999 if (flags & FBMcf_TAIL)
1000 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
1001 s = (U8*)SvPV_force(sv, len);
1002 (void)SvUPGRADE(sv, SVt_PVBM);
1003 if (len == 0) /* TAIL might be on on a zero-length string. */
1013 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
1014 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
1015 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
1016 memset((void*)table, mlen, 256);
1017 table[-1] = (U8)flags;
1019 sb = s - mlen + 1; /* first char (maybe) */
1021 if (table[*s] == mlen)
1026 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
1029 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
1030 for (i = 0; i < len; i++) {
1031 if (PL_freq[s[i]] < frequency) {
1033 frequency = PL_freq[s[i]];
1036 BmRARE(sv) = s[rarest];
1037 BmPREVIOUS(sv) = rarest;
1038 BmUSEFUL(sv) = 100; /* Initial value */
1039 if (flags & FBMcf_TAIL)
1041 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
1042 BmRARE(sv),BmPREVIOUS(sv)));
1045 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
1046 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1050 =for apidoc fbm_instr
1052 Returns the location of the SV in the string delimited by C<str> and
1053 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
1054 does not have to be fbm_compiled, but the search will not be as fast
1061 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
1063 register unsigned char *s;
1065 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
1066 register STRLEN littlelen = l;
1067 register I32 multiline = flags & FBMrf_MULTILINE;
1069 if (bigend - big < littlelen) {
1070 if ( SvTAIL(littlestr)
1071 && (bigend - big == littlelen - 1)
1073 || (*big == *little &&
1074 memEQ((char *)big, (char *)little, littlelen - 1))))
1079 if (littlelen <= 2) { /* Special-cased */
1081 if (littlelen == 1) {
1082 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1083 /* Know that bigend != big. */
1084 if (bigend[-1] == '\n')
1085 return (char *)(bigend - 1);
1086 return (char *) bigend;
1089 while (s < bigend) {
1094 if (SvTAIL(littlestr))
1095 return (char *) bigend;
1099 return (char*)big; /* Cannot be SvTAIL! */
1101 /* littlelen is 2 */
1102 if (SvTAIL(littlestr) && !multiline) {
1103 if (bigend[-1] == '\n' && bigend[-2] == *little)
1104 return (char*)bigend - 2;
1105 if (bigend[-1] == *little)
1106 return (char*)bigend - 1;
1110 /* This should be better than FBM if c1 == c2, and almost
1111 as good otherwise: maybe better since we do less indirection.
1112 And we save a lot of memory by caching no table. */
1113 register unsigned char c1 = little[0];
1114 register unsigned char c2 = little[1];
1119 while (s <= bigend) {
1122 return (char*)s - 1;
1129 goto check_1char_anchor;
1140 goto check_1char_anchor;
1143 while (s <= bigend) {
1146 return (char*)s - 1;
1148 goto check_1char_anchor;
1157 check_1char_anchor: /* One char and anchor! */
1158 if (SvTAIL(littlestr) && (*bigend == *little))
1159 return (char *)bigend; /* bigend is already decremented. */
1162 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1163 s = bigend - littlelen;
1164 if (s >= big && bigend[-1] == '\n' && *s == *little
1165 /* Automatically of length > 2 */
1166 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1168 return (char*)s; /* how sweet it is */
1171 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1173 return (char*)s + 1; /* how sweet it is */
1177 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1178 char *b = ninstr((char*)big,(char*)bigend,
1179 (char*)little, (char*)little + littlelen);
1181 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1182 /* Chop \n from littlestr: */
1183 s = bigend - littlelen + 1;
1185 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1194 { /* Do actual FBM. */
1195 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1196 register unsigned char *oldlittle;
1198 if (littlelen > bigend - big)
1200 --littlelen; /* Last char found by table lookup */
1202 s = big + littlelen;
1203 little += littlelen; /* last char */
1210 if ((tmp = table[*s])) {
1212 if (bigend - s > tmp) {
1218 if ((s += tmp) < bigend)
1223 else { /* less expensive than calling strncmp() */
1224 register unsigned char *olds = s;
1229 if (*--s == *--little)
1231 s = olds + 1; /* here we pay the price for failure */
1233 if (s < bigend) /* fake up continue to outer loop */
1241 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1242 && memEQ((char *)(bigend - littlelen),
1243 (char *)(oldlittle - littlelen), littlelen) )
1244 return (char*)bigend - littlelen;
1249 /* start_shift, end_shift are positive quantities which give offsets
1250 of ends of some substring of bigstr.
1251 If `last' we want the last occurence.
1252 old_posp is the way of communication between consequent calls if
1253 the next call needs to find the .
1254 The initial *old_posp should be -1.
1256 Note that we take into account SvTAIL, so one can get extra
1257 optimizations if _ALL flag is set.
1260 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1261 if PL_multiline. In fact if !PL_multiline the autoritative answer
1262 is not supported yet. */
1265 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1267 register unsigned char *s, *x;
1268 register unsigned char *big;
1270 register I32 previous;
1272 register unsigned char *little;
1273 register I32 stop_pos;
1274 register unsigned char *littleend;
1278 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1279 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1281 if ( BmRARE(littlestr) == '\n'
1282 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1283 little = (unsigned char *)(SvPVX(littlestr));
1284 littleend = little + SvCUR(littlestr);
1291 little = (unsigned char *)(SvPVX(littlestr));
1292 littleend = little + SvCUR(littlestr);
1294 /* The value of pos we can start at: */
1295 previous = BmPREVIOUS(littlestr);
1296 big = (unsigned char *)(SvPVX(bigstr));
1297 /* The value of pos we can stop at: */
1298 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1299 if (previous + start_shift > stop_pos) {
1300 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1304 while (pos < previous + start_shift) {
1305 if (!(pos += PL_screamnext[pos]))
1310 if (pos >= stop_pos) break;
1311 if (big[pos-previous] != first)
1313 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1319 if (s == littleend) {
1321 if (!last) return (char *)(big+pos-previous);
1324 } while ( pos += PL_screamnext[pos] );
1325 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1326 #else /* !POINTERRIGOR */
1329 if (pos >= stop_pos) break;
1330 if (big[pos] != first)
1332 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1338 if (s == littleend) {
1340 if (!last) return (char *)(big+pos);
1343 } while ( pos += PL_screamnext[pos] );
1345 return (char *)(big+(*old_posp));
1346 #endif /* POINTERRIGOR */
1348 if (!SvTAIL(littlestr) || (end_shift > 0))
1350 /* Ignore the trailing "\n". This code is not microoptimized */
1351 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1352 stop_pos = littleend - little; /* Actual littlestr len */
1357 && ((stop_pos == 1) ||
1358 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1364 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1366 register U8 *a = (U8 *)s1;
1367 register U8 *b = (U8 *)s2;
1369 if (*a != *b && *a != PL_fold[*b])
1377 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1379 register U8 *a = (U8 *)s1;
1380 register U8 *b = (U8 *)s2;
1382 if (*a != *b && *a != PL_fold_locale[*b])
1389 /* copy a string to a safe spot */
1394 Copy a string to a safe spot. This does not use an SV.
1400 Perl_savepv(pTHX_ const char *sv)
1402 register char *newaddr;
1404 New(902,newaddr,strlen(sv)+1,char);
1405 (void)strcpy(newaddr,sv);
1409 /* same thing but with a known length */
1414 Copy a string to a safe spot. The C<len> indicates number of bytes to
1415 copy. This does not use an SV.
1421 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1423 register char *newaddr;
1425 New(903,newaddr,len+1,char);
1426 Copy(sv,newaddr,len,char); /* might not be null terminated */
1427 newaddr[len] = '\0'; /* is now */
1431 /* 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') {
1521 if (CopLINE(PL_curcop))
1522 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1523 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1524 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1525 bool line_mode = (RsSIMPLE(PL_rs) &&
1526 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1527 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1528 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1529 line_mode ? "line" : "chunk",
1530 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1534 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1536 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1542 Perl_vdie(pTHX_ const char* pat, va_list *args)
1545 int was_in_eval = PL_in_eval;
1552 DEBUG_S(PerlIO_printf(Perl_debug_log,
1553 "%p: die: curstack = %p, mainstack = %p\n",
1554 thr, PL_curstack, PL_mainstack));
1557 msv = vmess(pat, args);
1558 if (PL_errors && SvCUR(PL_errors)) {
1559 sv_catsv(PL_errors, msv);
1560 message = SvPV(PL_errors, msglen);
1561 SvCUR_set(PL_errors, 0);
1564 message = SvPV(msv,msglen);
1571 DEBUG_S(PerlIO_printf(Perl_debug_log,
1572 "%p: die: message = %s\ndiehook = %p\n",
1573 thr, message, PL_diehook));
1575 /* sv_2cv might call Perl_croak() */
1576 SV *olddiehook = PL_diehook;
1578 SAVESPTR(PL_diehook);
1579 PL_diehook = Nullsv;
1580 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1582 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1589 msg = newSVpvn(message, msglen);
1597 PUSHSTACKi(PERLSI_DIEHOOK);
1601 call_sv((SV*)cv, G_DISCARD);
1607 PL_restartop = die_where(message, msglen);
1608 DEBUG_S(PerlIO_printf(Perl_debug_log,
1609 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1610 thr, PL_restartop, was_in_eval, PL_top_env));
1611 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1613 return PL_restartop;
1616 #if defined(PERL_IMPLICIT_CONTEXT)
1618 Perl_die_nocontext(const char* pat, ...)
1623 va_start(args, pat);
1624 o = vdie(pat, &args);
1628 #endif /* PERL_IMPLICIT_CONTEXT */
1631 Perl_die(pTHX_ const char* pat, ...)
1635 va_start(args, pat);
1636 o = vdie(pat, &args);
1642 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1652 msv = vmess(pat, args);
1653 if (PL_errors && SvCUR(PL_errors)) {
1654 sv_catsv(PL_errors, msv);
1655 message = SvPV(PL_errors, msglen);
1656 SvCUR_set(PL_errors, 0);
1659 message = SvPV(msv,msglen);
1666 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1667 PTR2UV(thr), message));
1670 /* sv_2cv might call Perl_croak() */
1671 SV *olddiehook = PL_diehook;
1673 SAVESPTR(PL_diehook);
1674 PL_diehook = Nullsv;
1675 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1677 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1684 msg = newSVpvn(message, msglen);
1692 PUSHSTACKi(PERLSI_DIEHOOK);
1696 call_sv((SV*)cv, G_DISCARD);
1702 PL_restartop = die_where(message, msglen);
1707 /* SFIO can really mess with your errno */
1710 PerlIO *serr = Perl_error_log;
1712 PerlIO_write(serr, message, msglen);
1713 (void)PerlIO_flush(serr);
1721 #if defined(PERL_IMPLICIT_CONTEXT)
1723 Perl_croak_nocontext(const char *pat, ...)
1727 va_start(args, pat);
1732 #endif /* PERL_IMPLICIT_CONTEXT */
1737 This is the XSUB-writer's interface to Perl's C<die> function.
1738 Normally use this function the same way you use the C C<printf>
1739 function. See C<warn>.
1741 If you want to throw an exception object, assign the object to
1742 C<$@> and then pass C<Nullch> to croak():
1744 errsv = get_sv("@", TRUE);
1745 sv_setsv(errsv, exception_object);
1752 Perl_croak(pTHX_ const char *pat, ...)
1755 va_start(args, pat);
1762 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1771 msv = vmess(pat, args);
1772 message = SvPV(msv, msglen);
1775 /* sv_2cv might call Perl_warn() */
1776 SV *oldwarnhook = PL_warnhook;
1778 SAVESPTR(PL_warnhook);
1779 PL_warnhook = Nullsv;
1780 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1782 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1788 msg = newSVpvn(message, msglen);
1792 PUSHSTACKi(PERLSI_WARNHOOK);
1796 call_sv((SV*)cv, G_DISCARD);
1803 PerlIO *serr = Perl_error_log;
1805 PerlIO_write(serr, message, msglen);
1807 DEBUG_L(*message == '!'
1808 ? (xstat(message[1]=='!'
1809 ? (message[2]=='!' ? 2 : 1)
1814 (void)PerlIO_flush(serr);
1818 #if defined(PERL_IMPLICIT_CONTEXT)
1820 Perl_warn_nocontext(const char *pat, ...)
1824 va_start(args, pat);
1828 #endif /* PERL_IMPLICIT_CONTEXT */
1833 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1834 function the same way you use the C C<printf> function. See
1841 Perl_warn(pTHX_ const char *pat, ...)
1844 va_start(args, pat);
1849 #if defined(PERL_IMPLICIT_CONTEXT)
1851 Perl_warner_nocontext(U32 err, const char *pat, ...)
1855 va_start(args, pat);
1856 vwarner(err, pat, &args);
1859 #endif /* PERL_IMPLICIT_CONTEXT */
1862 Perl_warner(pTHX_ U32 err, const char* pat,...)
1865 va_start(args, pat);
1866 vwarner(err, pat, &args);
1871 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1880 msv = vmess(pat, args);
1881 message = SvPV(msv, msglen);
1885 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1886 #endif /* USE_THREADS */
1888 /* sv_2cv might call Perl_croak() */
1889 SV *olddiehook = PL_diehook;
1891 SAVESPTR(PL_diehook);
1892 PL_diehook = Nullsv;
1893 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1895 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1901 msg = newSVpvn(message, msglen);
1905 PUSHSTACKi(PERLSI_DIEHOOK);
1909 call_sv((SV*)cv, G_DISCARD);
1915 PL_restartop = die_where(message, msglen);
1919 PerlIO *serr = Perl_error_log;
1920 PerlIO_write(serr, message, msglen);
1921 (void)PerlIO_flush(serr);
1928 /* sv_2cv might call Perl_warn() */
1929 SV *oldwarnhook = PL_warnhook;
1931 SAVESPTR(PL_warnhook);
1932 PL_warnhook = Nullsv;
1933 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1935 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1941 msg = newSVpvn(message, msglen);
1945 PUSHSTACKi(PERLSI_WARNHOOK);
1949 call_sv((SV*)cv, G_DISCARD);
1956 PerlIO *serr = Perl_error_log;
1957 PerlIO_write(serr, message, msglen);
1959 DEBUG_L(*message == '!'
1960 ? (xstat(message[1]=='!'
1961 ? (message[2]=='!' ? 2 : 1)
1966 (void)PerlIO_flush(serr);
1971 #ifdef USE_ENVIRON_ARRAY
1972 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1975 Perl_my_setenv(pTHX_ char *nam, char *val)
1977 #ifndef PERL_USE_SAFE_PUTENV
1978 /* most putenv()s leak, so we manipulate environ directly */
1979 register I32 i=setenv_getix(nam); /* where does it go? */
1981 if (environ == PL_origenviron) { /* need we copy environment? */
1987 for (max = i; environ[max]; max++) ;
1988 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1989 for (j=0; j<max; j++) { /* copy environment */
1990 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1991 strcpy(tmpenv[j], environ[j]);
1993 tmpenv[max] = Nullch;
1994 environ = tmpenv; /* tell exec where it is now */
1997 safesysfree(environ[i]);
1998 while (environ[i]) {
1999 environ[i] = environ[i+1];
2004 if (!environ[i]) { /* does not exist yet */
2005 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2006 environ[i+1] = Nullch; /* make sure it's null terminated */
2009 safesysfree(environ[i]);
2010 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
2012 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
2014 #else /* PERL_USE_SAFE_PUTENV */
2015 # if defined(__CYGWIN__)
2016 setenv(nam, val, 1);
2020 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
2021 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
2022 (void)putenv(new_env);
2023 # endif /* __CYGWIN__ */
2024 #endif /* PERL_USE_SAFE_PUTENV */
2030 Perl_my_setenv(pTHX_ char *nam,char *val)
2033 #ifdef USE_WIN32_RTL_ENV
2035 register char *envstr;
2036 STRLEN namlen = strlen(nam);
2038 char *oldstr = environ[setenv_getix(nam)];
2040 /* putenv() has totally broken semantics in both the Borland
2041 * and Microsoft CRTLs. They either store the passed pointer in
2042 * the environment without making a copy, or make a copy and don't
2043 * free it. And on top of that, they dont free() old entries that
2044 * are being replaced/deleted. This means the caller must
2045 * free any old entries somehow, or we end up with a memory
2046 * leak every time my_setenv() is called. One might think
2047 * one could directly manipulate environ[], like the UNIX code
2048 * above, but direct changes to environ are not allowed when
2049 * calling putenv(), since the RTLs maintain an internal
2050 * *copy* of environ[]. Bad, bad, *bad* stink.
2061 vallen = strlen(val);
2062 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
2063 (void)sprintf(envstr,"%s=%s",nam,val);
2064 (void)PerlEnv_putenv(envstr);
2066 safesysfree(oldstr);
2068 safesysfree(envstr); /* MSVCRT leaks without this */
2071 #else /* !USE_WIN32_RTL_ENV */
2073 register char *envstr;
2074 STRLEN len = strlen(nam) + 3;
2079 New(904, envstr, len, char);
2080 (void)sprintf(envstr,"%s=%s",nam,val);
2081 (void)PerlEnv_putenv(envstr);
2090 Perl_setenv_getix(pTHX_ char *nam)
2092 register I32 i, len = strlen(nam);
2094 for (i = 0; environ[i]; i++) {
2097 strnicmp(environ[i],nam,len) == 0
2099 strnEQ(environ[i],nam,len)
2101 && environ[i][len] == '=')
2102 break; /* strnEQ must come first to avoid */
2103 } /* potential SEGV's */
2107 #endif /* !VMS && !EPOC*/
2109 #ifdef UNLINK_ALL_VERSIONS
2111 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2115 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2120 /* this is a drop-in replacement for bcopy() */
2121 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2123 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2127 if (from - to >= 0) {
2135 *(--to) = *(--from);
2141 /* this is a drop-in replacement for memset() */
2144 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2154 /* this is a drop-in replacement for bzero() */
2155 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2157 Perl_my_bzero(register char *loc, register I32 len)
2167 /* this is a drop-in replacement for memcmp() */
2168 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2170 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2172 register U8 *a = (U8 *)s1;
2173 register U8 *b = (U8 *)s2;
2177 if (tmp = *a++ - *b++)
2182 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2186 #ifdef USE_CHAR_VSPRINTF
2191 vsprintf(char *dest, const char *pat, char *args)
2195 fakebuf._ptr = dest;
2196 fakebuf._cnt = 32767;
2200 fakebuf._flag = _IOWRT|_IOSTRG;
2201 _doprnt(pat, args, &fakebuf); /* what a kludge */
2202 (void)putc('\0', &fakebuf);
2203 #ifdef USE_CHAR_VSPRINTF
2206 return 0; /* perl doesn't use return value */
2210 #endif /* HAS_VPRINTF */
2213 #if BYTEORDER != 0x4321
2215 Perl_my_swap(pTHX_ short s)
2217 #if (BYTEORDER & 1) == 0
2220 result = ((s & 255) << 8) + ((s >> 8) & 255);
2228 Perl_my_htonl(pTHX_ long l)
2232 char c[sizeof(long)];
2235 #if BYTEORDER == 0x1234
2236 u.c[0] = (l >> 24) & 255;
2237 u.c[1] = (l >> 16) & 255;
2238 u.c[2] = (l >> 8) & 255;
2242 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2243 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2248 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2249 u.c[o & 0xf] = (l >> s) & 255;
2257 Perl_my_ntohl(pTHX_ long l)
2261 char c[sizeof(long)];
2264 #if BYTEORDER == 0x1234
2265 u.c[0] = (l >> 24) & 255;
2266 u.c[1] = (l >> 16) & 255;
2267 u.c[2] = (l >> 8) & 255;
2271 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2272 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2279 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2280 l |= (u.c[o & 0xf] & 255) << s;
2287 #endif /* BYTEORDER != 0x4321 */
2291 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2292 * If these functions are defined,
2293 * the BYTEORDER is neither 0x1234 nor 0x4321.
2294 * However, this is not assumed.
2298 #define HTOV(name,type) \
2300 name (register type n) \
2304 char c[sizeof(type)]; \
2308 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2309 u.c[i] = (n >> s) & 0xFF; \
2314 #define VTOH(name,type) \
2316 name (register type n) \
2320 char c[sizeof(type)]; \
2326 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2327 n += (u.c[i] & 0xFF) << s; \
2332 #if defined(HAS_HTOVS) && !defined(htovs)
2335 #if defined(HAS_HTOVL) && !defined(htovl)
2338 #if defined(HAS_VTOHS) && !defined(vtohs)
2341 #if defined(HAS_VTOHL) && !defined(vtohl)
2345 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2346 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2348 Perl_my_popen(pTHX_ char *cmd, char *mode)
2351 register I32 This, that;
2354 I32 doexec = strNE(cmd,"-");
2358 PERL_FLUSHALL_FOR_CHILD;
2361 return my_syspopen(aTHX_ cmd,mode);
2364 This = (*mode == 'w');
2366 if (doexec && PL_tainting) {
2368 taint_proper("Insecure %s%s", "EXEC");
2370 if (PerlProc_pipe(p) < 0)
2372 if (doexec && PerlProc_pipe(pp) >= 0)
2374 while ((pid = (doexec?vfork():fork())) < 0) {
2375 if (errno != EAGAIN) {
2376 PerlLIO_close(p[This]);
2378 PerlLIO_close(pp[0]);
2379 PerlLIO_close(pp[1]);
2382 Perl_croak(aTHX_ "Can't fork");
2394 PerlLIO_close(p[THAT]);
2396 PerlLIO_close(pp[0]);
2397 #if defined(HAS_FCNTL) && defined(F_SETFD)
2398 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2401 if (p[THIS] != (*mode == 'r')) {
2402 PerlLIO_dup2(p[THIS], *mode == 'r');
2403 PerlLIO_close(p[THIS]);
2407 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2413 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2417 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2420 #endif /* defined OS2 */
2422 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
2423 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2425 hv_clear(PL_pidstatus); /* we have no children */
2430 do_execfree(); /* free any memory malloced by child on vfork */
2431 PerlLIO_close(p[that]);
2433 PerlLIO_close(pp[1]);
2434 if (p[that] < p[This]) {
2435 PerlLIO_dup2(p[This], p[that]);
2436 PerlLIO_close(p[This]);
2440 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2442 (void)SvUPGRADE(sv,SVt_IV);
2444 PL_forkprocess = pid;
2445 if (did_pipes && pid > 0) {
2449 while (n < sizeof(int)) {
2450 n1 = PerlLIO_read(pp[0],
2451 (void*)(((char*)&errkid)+n),
2457 PerlLIO_close(pp[0]);
2459 if (n) { /* Error */
2460 if (n != sizeof(int))
2461 Perl_croak(aTHX_ "panic: kid popen errno read");
2462 errno = errkid; /* Propagate errno from kid */
2467 PerlLIO_close(pp[0]);
2468 return PerlIO_fdopen(p[This], mode);
2471 #if defined(atarist) || defined(DJGPP)
2474 Perl_my_popen(pTHX_ char *cmd, char *mode)
2476 PERL_FLUSHALL_FOR_CHILD;
2477 /* Call system's popen() to get a FILE *, then import it.
2478 used 0 for 2nd parameter to PerlIO_importFILE;
2481 return PerlIO_importFILE(popen(cmd, mode), 0);
2485 #endif /* !DOSISH */
2489 Perl_dump_fds(pTHX_ char *s)
2492 struct stat tmpstatbuf;
2494 PerlIO_printf(Perl_debug_log,"%s", s);
2495 for (fd = 0; fd < 32; fd++) {
2496 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2497 PerlIO_printf(Perl_debug_log," %d",fd);
2499 PerlIO_printf(Perl_debug_log,"\n");
2501 #endif /* DUMP_FDS */
2505 dup2(int oldfd, int newfd)
2507 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2510 PerlLIO_close(newfd);
2511 return fcntl(oldfd, F_DUPFD, newfd);
2513 #define DUP2_MAX_FDS 256
2514 int fdtmp[DUP2_MAX_FDS];
2520 PerlLIO_close(newfd);
2521 /* good enough for low fd's... */
2522 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2523 if (fdx >= DUP2_MAX_FDS) {
2531 PerlLIO_close(fdtmp[--fdx]);
2538 #ifdef HAS_SIGACTION
2541 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2543 struct sigaction act, oact;
2545 act.sa_handler = handler;
2546 sigemptyset(&act.sa_mask);
2549 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2552 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2553 act.sa_flags |= SA_NOCLDWAIT;
2555 if (sigaction(signo, &act, &oact) == -1)
2558 return oact.sa_handler;
2562 Perl_rsignal_state(pTHX_ int signo)
2564 struct sigaction oact;
2566 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2569 return oact.sa_handler;
2573 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2575 struct sigaction act;
2577 act.sa_handler = handler;
2578 sigemptyset(&act.sa_mask);
2581 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2584 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2585 act.sa_flags |= SA_NOCLDWAIT;
2587 return sigaction(signo, &act, save);
2591 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2593 return sigaction(signo, save, (struct sigaction *)NULL);
2596 #else /* !HAS_SIGACTION */
2599 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2601 return PerlProc_signal(signo, handler);
2604 static int sig_trapped;
2614 Perl_rsignal_state(pTHX_ int signo)
2616 Sighandler_t oldsig;
2619 oldsig = PerlProc_signal(signo, sig_trap);
2620 PerlProc_signal(signo, oldsig);
2622 PerlProc_kill(PerlProc_getpid(), signo);
2627 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2629 *save = PerlProc_signal(signo, handler);
2630 return (*save == SIG_ERR) ? -1 : 0;
2634 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2636 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2639 #endif /* !HAS_SIGACTION */
2640 #endif /* !PERL_MICRO */
2642 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2643 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2645 Perl_my_pclose(pTHX_ PerlIO *ptr)
2647 Sigsave_t hstat, istat, qstat;
2655 int saved_vaxc_errno;
2658 int saved_win32_errno;
2662 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2666 *svp = &PL_sv_undef;
2668 if (pid == -1) { /* Opened by popen. */
2669 return my_syspclose(ptr);
2672 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2673 saved_errno = errno;
2675 saved_vaxc_errno = vaxc$errno;
2678 saved_win32_errno = GetLastError();
2682 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2685 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2686 rsignal_save(SIGINT, SIG_IGN, &istat);
2687 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2690 pid2 = wait4pid(pid, &status, 0);
2691 } while (pid2 == -1 && errno == EINTR);
2693 rsignal_restore(SIGHUP, &hstat);
2694 rsignal_restore(SIGINT, &istat);
2695 rsignal_restore(SIGQUIT, &qstat);
2698 SETERRNO(saved_errno, saved_vaxc_errno);
2701 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2703 #endif /* !DOSISH */
2705 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2707 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2711 char spid[TYPE_CHARS(int)];
2715 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2717 sprintf(spid, "%"IVdf, (IV)pid);
2718 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2719 if (svp && *svp != &PL_sv_undef) {
2720 *statusp = SvIVX(*svp);
2721 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2728 hv_iterinit(PL_pidstatus);
2729 if ((entry = hv_iternext(PL_pidstatus))) {
2730 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2731 sv = hv_iterval(PL_pidstatus,entry);
2732 *statusp = SvIVX(sv);
2733 sprintf(spid, "%"IVdf, (IV)pid);
2734 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2740 # ifdef HAS_WAITPID_RUNTIME
2741 if (!HAS_WAITPID_RUNTIME)
2744 return PerlProc_waitpid(pid,statusp,flags);
2746 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2747 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2749 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2754 Perl_croak(aTHX_ "Can't do waitpid with flags");
2756 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2757 pidgone(result,*statusp);
2765 #endif /* !DOSISH || OS2 || WIN32 */
2769 Perl_pidgone(pTHX_ Pid_t pid, int status)
2772 char spid[TYPE_CHARS(int)];
2774 sprintf(spid, "%"IVdf, (IV)pid);
2775 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2776 (void)SvUPGRADE(sv,SVt_IV);
2781 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2784 int /* Cannot prototype with I32
2786 my_syspclose(PerlIO *ptr)
2789 Perl_my_pclose(pTHX_ PerlIO *ptr)
2792 /* Needs work for PerlIO ! */
2793 FILE *f = PerlIO_findFILE(ptr);
2794 I32 result = pclose(f);
2796 result = (result << 8) & 0xff00;
2798 PerlIO_releaseFILE(ptr,f);
2804 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2807 register const char *frombase = from;
2810 register const char c = *from;
2815 while (count-- > 0) {
2816 for (todo = len; todo > 0; todo--) {
2824 Perl_cast_ulong(pTHX_ NV f)
2829 # define BIGDOUBLE 2147483648.0
2831 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2834 return (unsigned long)f;
2836 return (unsigned long)along;
2840 /* Unfortunately, on some systems the cast_uv() function doesn't
2841 work with the system-supplied definition of ULONG_MAX. The
2842 comparison (f >= ULONG_MAX) always comes out true. It must be a
2843 problem with the compiler constant folding.
2845 In any case, this workaround should be fine on any two's complement
2846 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2848 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2851 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2853 -- Kenneth Albanowski <kjahds@kjahds.com>
2857 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2861 Perl_cast_i32(pTHX_ NV f)
2864 return (I32) I32_MAX;
2866 return (I32) I32_MIN;
2871 Perl_cast_iv(pTHX_ NV f)
2876 if (f >= (NV)UV_MAX)
2887 Perl_cast_uv(pTHX_ NV f)
2890 return (UV) MY_UV_MAX;
2904 Perl_same_dirent(pTHX_ char *a, char *b)
2906 char *fa = strrchr(a,'/');
2907 char *fb = strrchr(b,'/');
2908 struct stat tmpstatbuf1;
2909 struct stat tmpstatbuf2;
2910 SV *tmpsv = sv_newmortal();
2923 sv_setpv(tmpsv, ".");
2925 sv_setpvn(tmpsv, a, fa - a);
2926 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2929 sv_setpv(tmpsv, ".");
2931 sv_setpvn(tmpsv, b, fb - b);
2932 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2934 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2935 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2937 #endif /* !HAS_RENAME */
2940 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
2942 register char *s = start;
2943 register NV rnv = 0.0;
2944 register UV ruv = 0;
2945 register bool seenb = FALSE;
2946 register bool overflowed = FALSE;
2948 for (; len-- && *s; s++) {
2949 if (!(*s == '0' || *s == '1')) {
2950 if (*s == '_' && len && *retlen
2951 && (s[1] == '0' || s[1] == '1'))
2956 else if (seenb == FALSE && *s == 'b' && ruv == 0) {
2957 /* Disallow 0bbb0b0bbb... */
2962 if (ckWARN(WARN_DIGIT))
2963 Perl_warner(aTHX_ WARN_DIGIT,
2964 "Illegal binary digit '%c' ignored", *s);
2969 register UV xuv = ruv << 1;
2971 if ((xuv >> 1) != ruv) {
2974 if (ckWARN_d(WARN_OVERFLOW))
2975 Perl_warner(aTHX_ WARN_OVERFLOW,
2976 "Integer overflow in binary number");
2979 ruv = xuv | (*s - '0');
2983 /* If an NV has not enough bits in its mantissa to
2984 * represent an UV this summing of small low-order numbers
2985 * is a waste of time (because the NV cannot preserve
2986 * the low-order bits anyway): we could just remember when
2987 * did we overflow and in the end just multiply rnv by the
2994 if ( ( overflowed && rnv > 4294967295.0)
2996 || (!overflowed && ruv > 0xffffffff )
2999 if (ckWARN(WARN_PORTABLE))
3000 Perl_warner(aTHX_ WARN_PORTABLE,
3001 "Binary number > 0b11111111111111111111111111111111 non-portable");
3003 *retlen = s - start;
3008 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3010 register char *s = start;
3011 register NV rnv = 0.0;
3012 register UV ruv = 0;
3013 register bool overflowed = FALSE;
3015 for (; len-- && *s; s++) {
3016 if (!(*s >= '0' && *s <= '7')) {
3017 if (*s == '_' && len && *retlen
3018 && (s[1] >= '0' && s[1] <= '7'))
3024 /* Allow \octal to work the DWIM way (that is, stop scanning
3025 * as soon as non-octal characters are seen, complain only iff
3026 * someone seems to want to use the digits eight and nine). */
3027 if (*s == '8' || *s == '9') {
3028 if (ckWARN(WARN_DIGIT))
3029 Perl_warner(aTHX_ WARN_DIGIT,
3030 "Illegal octal digit '%c' ignored", *s);
3036 register UV xuv = ruv << 3;
3038 if ((xuv >> 3) != ruv) {
3041 if (ckWARN_d(WARN_OVERFLOW))
3042 Perl_warner(aTHX_ WARN_OVERFLOW,
3043 "Integer overflow in octal number");
3046 ruv = xuv | (*s - '0');
3050 /* If an NV has not enough bits in its mantissa to
3051 * represent an UV this summing of small low-order numbers
3052 * is a waste of time (because the NV cannot preserve
3053 * the low-order bits anyway): we could just remember when
3054 * did we overflow and in the end just multiply rnv by the
3055 * right amount of 8-tuples. */
3056 rnv += (NV)(*s - '0');
3061 if ( ( overflowed && rnv > 4294967295.0)
3063 || (!overflowed && ruv > 0xffffffff )
3066 if (ckWARN(WARN_PORTABLE))
3067 Perl_warner(aTHX_ WARN_PORTABLE,
3068 "Octal number > 037777777777 non-portable");
3070 *retlen = s - start;
3075 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3077 register char *s = start;
3078 register NV rnv = 0.0;
3079 register UV ruv = 0;
3080 register bool overflowed = FALSE;
3088 else if (len > 3 && s[0] == '0' && s[1] == 'x') {
3094 for (; len-- && *s; s++) {
3095 hexdigit = strchr((char *) PL_hexdigit, *s);
3097 if (*s == '_' && len && *retlen && s[1]
3098 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
3104 if (ckWARN(WARN_DIGIT))
3105 Perl_warner(aTHX_ WARN_DIGIT,
3106 "Illegal hexadecimal digit '%c' ignored", *s);
3111 register UV xuv = ruv << 4;
3113 if ((xuv >> 4) != ruv) {
3116 if (ckWARN_d(WARN_OVERFLOW))
3117 Perl_warner(aTHX_ WARN_OVERFLOW,
3118 "Integer overflow in hexadecimal number");
3121 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
3125 /* If an NV has not enough bits in its mantissa to
3126 * represent an UV this summing of small low-order numbers
3127 * is a waste of time (because the NV cannot preserve
3128 * the low-order bits anyway): we could just remember when
3129 * did we overflow and in the end just multiply rnv by the
3130 * right amount of 16-tuples. */
3131 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
3136 if ( ( overflowed && rnv > 4294967295.0)
3138 || (!overflowed && ruv > 0xffffffff )
3141 if (ckWARN(WARN_PORTABLE))
3142 Perl_warner(aTHX_ WARN_PORTABLE,
3143 "Hexadecimal number > 0xffffffff non-portable");
3145 *retlen = s - start;
3150 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
3152 char *xfound = Nullch;
3153 char *xfailed = Nullch;
3154 char tmpbuf[MAXPATHLEN];
3158 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3159 # define SEARCH_EXTS ".bat", ".cmd", NULL
3160 # define MAX_EXT_LEN 4
3163 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3164 # define MAX_EXT_LEN 4
3167 # define SEARCH_EXTS ".pl", ".com", NULL
3168 # define MAX_EXT_LEN 4
3170 /* additional extensions to try in each dir if scriptname not found */
3172 char *exts[] = { SEARCH_EXTS };
3173 char **ext = search_ext ? search_ext : exts;
3174 int extidx = 0, i = 0;
3175 char *curext = Nullch;
3177 # define MAX_EXT_LEN 0
3181 * If dosearch is true and if scriptname does not contain path
3182 * delimiters, search the PATH for scriptname.
3184 * If SEARCH_EXTS is also defined, will look for each
3185 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3186 * while searching the PATH.
3188 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3189 * proceeds as follows:
3190 * If DOSISH or VMSISH:
3191 * + look for ./scriptname{,.foo,.bar}
3192 * + search the PATH for scriptname{,.foo,.bar}
3195 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3196 * this will not look in '.' if it's not in the PATH)
3201 # ifdef ALWAYS_DEFTYPES
3202 len = strlen(scriptname);
3203 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3204 int hasdir, idx = 0, deftypes = 1;
3207 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3210 int hasdir, idx = 0, deftypes = 1;
3213 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3215 /* The first time through, just add SEARCH_EXTS to whatever we
3216 * already have, so we can check for default file types. */
3218 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3224 if ((strlen(tmpbuf) + strlen(scriptname)
3225 + MAX_EXT_LEN) >= sizeof tmpbuf)
3226 continue; /* don't search dir with too-long name */
3227 strcat(tmpbuf, scriptname);
3231 if (strEQ(scriptname, "-"))
3233 if (dosearch) { /* Look in '.' first. */
3234 char *cur = scriptname;
3236 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3238 if (strEQ(ext[i++],curext)) {
3239 extidx = -1; /* already has an ext */
3244 DEBUG_p(PerlIO_printf(Perl_debug_log,
3245 "Looking for %s\n",cur));
3246 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3247 && !S_ISDIR(PL_statbuf.st_mode)) {
3255 if (cur == scriptname) {
3256 len = strlen(scriptname);
3257 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3259 cur = strcpy(tmpbuf, scriptname);
3261 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3262 && strcpy(tmpbuf+len, ext[extidx++]));
3267 #ifdef MACOS_TRADITIONAL
3268 if (dosearch && !strchr(scriptname, ':') &&
3269 (s = PerlEnv_getenv("Commands")))
3271 if (dosearch && !strchr(scriptname, '/')
3273 && !strchr(scriptname, '\\')
3275 && (s = PerlEnv_getenv("PATH")))
3280 PL_bufend = s + strlen(s);
3281 while (s < PL_bufend) {
3282 #ifdef MACOS_TRADITIONAL
3283 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3287 #if defined(atarist) || defined(DOSISH)
3292 && *s != ';'; len++, s++) {
3293 if (len < sizeof tmpbuf)
3296 if (len < sizeof tmpbuf)
3298 #else /* ! (atarist || DOSISH) */
3299 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3302 #endif /* ! (atarist || DOSISH) */
3303 #endif /* MACOS_TRADITIONAL */
3306 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3307 continue; /* don't search dir with too-long name */
3308 #ifdef MACOS_TRADITIONAL
3309 if (len && tmpbuf[len - 1] != ':')
3310 tmpbuf[len++] = ':';
3313 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3314 && tmpbuf[len - 1] != '/'
3315 && tmpbuf[len - 1] != '\\'
3318 tmpbuf[len++] = '/';
3319 if (len == 2 && tmpbuf[0] == '.')
3322 (void)strcpy(tmpbuf + len, scriptname);
3326 len = strlen(tmpbuf);
3327 if (extidx > 0) /* reset after previous loop */
3331 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3332 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3333 if (S_ISDIR(PL_statbuf.st_mode)) {
3337 } while ( retval < 0 /* not there */
3338 && extidx>=0 && ext[extidx] /* try an extension? */
3339 && strcpy(tmpbuf+len, ext[extidx++])
3344 if (S_ISREG(PL_statbuf.st_mode)
3345 && cando(S_IRUSR,TRUE,&PL_statbuf)
3346 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3347 && cando(S_IXUSR,TRUE,&PL_statbuf)
3351 xfound = tmpbuf; /* bingo! */
3355 xfailed = savepv(tmpbuf);
3358 if (!xfound && !seen_dot && !xfailed &&
3359 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3360 || S_ISDIR(PL_statbuf.st_mode)))
3362 seen_dot = 1; /* Disable message. */
3364 if (flags & 1) { /* do or die? */
3365 Perl_croak(aTHX_ "Can't %s %s%s%s",
3366 (xfailed ? "execute" : "find"),
3367 (xfailed ? xfailed : scriptname),
3368 (xfailed ? "" : " on PATH"),
3369 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3371 scriptname = Nullch;
3375 scriptname = xfound;
3377 return (scriptname ? savepv(scriptname) : Nullch);
3380 #ifndef PERL_GET_CONTEXT_DEFINED
3383 Perl_get_context(void)
3385 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3386 # ifdef OLD_PTHREADS_API
3388 if (pthread_getspecific(PL_thr_key, &t))
3389 Perl_croak_nocontext("panic: pthread_getspecific");
3392 # ifdef I_MACH_CTHREADS
3393 return (void*)cthread_data(cthread_self());
3395 return (void*)pthread_getspecific(PL_thr_key);
3404 Perl_set_context(void *t)
3406 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3407 # ifdef I_MACH_CTHREADS
3408 cthread_set_data(cthread_self(), t);
3410 if (pthread_setspecific(PL_thr_key, t))
3411 Perl_croak_nocontext("panic: pthread_setspecific");
3416 #endif /* !PERL_GET_CONTEXT_DEFINED */
3421 /* Very simplistic scheduler for now */
3425 thr = thr->i.next_run;
3429 Perl_cond_init(pTHX_ perl_cond *cp)
3435 Perl_cond_signal(pTHX_ perl_cond *cp)
3438 perl_cond cond = *cp;
3443 /* Insert t in the runnable queue just ahead of us */
3444 t->i.next_run = thr->i.next_run;
3445 thr->i.next_run->i.prev_run = t;
3446 t->i.prev_run = thr;
3447 thr->i.next_run = t;
3448 thr->i.wait_queue = 0;
3449 /* Remove from the wait queue */
3455 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3458 perl_cond cond, cond_next;
3460 for (cond = *cp; cond; cond = cond_next) {
3462 /* Insert t in the runnable queue just ahead of us */
3463 t->i.next_run = thr->i.next_run;
3464 thr->i.next_run->i.prev_run = t;
3465 t->i.prev_run = thr;
3466 thr->i.next_run = t;
3467 thr->i.wait_queue = 0;
3468 /* Remove from the wait queue */
3469 cond_next = cond->next;
3476 Perl_cond_wait(pTHX_ perl_cond *cp)
3480 if (thr->i.next_run == thr)
3481 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3483 New(666, cond, 1, struct perl_wait_queue);
3487 thr->i.wait_queue = cond;
3488 /* Remove ourselves from runnable queue */
3489 thr->i.next_run->i.prev_run = thr->i.prev_run;
3490 thr->i.prev_run->i.next_run = thr->i.next_run;
3492 #endif /* FAKE_THREADS */
3495 Perl_condpair_magic(pTHX_ SV *sv)
3499 SvUPGRADE(sv, SVt_PVMG);
3500 mg = mg_find(sv, 'm');
3504 New(53, cp, 1, condpair_t);
3505 MUTEX_INIT(&cp->mutex);
3506 COND_INIT(&cp->owner_cond);
3507 COND_INIT(&cp->cond);
3509 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3510 mg = mg_find(sv, 'm');
3512 /* someone else beat us to initialising it */
3513 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3514 MUTEX_DESTROY(&cp->mutex);
3515 COND_DESTROY(&cp->owner_cond);
3516 COND_DESTROY(&cp->cond);
3520 sv_magic(sv, Nullsv, 'm', 0, 0);
3522 mg->mg_ptr = (char *)cp;
3523 mg->mg_len = sizeof(cp);
3524 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3525 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3526 "%p: condpair_magic %p\n", thr, sv));)
3533 Perl_sv_lock(pTHX_ SV *osv)
3543 mg = condpair_magic(sv);
3544 MUTEX_LOCK(MgMUTEXP(mg));
3545 if (MgOWNER(mg) == thr)
3546 MUTEX_UNLOCK(MgMUTEXP(mg));
3549 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3551 DEBUG_S(PerlIO_printf(Perl_debug_log,
3552 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3553 PTR2UV(thr), PTR2UV(sv));)
3554 MUTEX_UNLOCK(MgMUTEXP(mg));
3555 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3557 UNLOCK_SV_LOCK_MUTEX;
3562 * Make a new perl thread structure using t as a prototype. Some of the
3563 * fields for the new thread are copied from the prototype thread, t,
3564 * so t should not be running in perl at the time this function is
3565 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3566 * thread calling new_struct_thread) clearly satisfies this constraint.
3568 struct perl_thread *
3569 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3571 #if !defined(PERL_IMPLICIT_CONTEXT)
3572 struct perl_thread *thr;
3578 sv = newSVpvn("", 0);
3579 SvGROW(sv, sizeof(struct perl_thread) + 1);
3580 SvCUR_set(sv, sizeof(struct perl_thread));
3581 thr = (Thread) SvPVX(sv);
3583 memset(thr, 0xab, sizeof(struct perl_thread));
3590 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3591 PL_efloatbuf = (char*)NULL;
3594 Zero(thr, 1, struct perl_thread);
3600 PL_curcop = &PL_compiling;
3601 thr->interp = t->interp;
3602 thr->cvcache = newHV();
3603 thr->threadsv = newAV();
3604 thr->specific = newAV();
3605 thr->errsv = newSVpvn("", 0);
3606 thr->flags = THRf_R_JOINABLE;
3608 MUTEX_INIT(&thr->mutex);
3612 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3615 PL_statname = NEWSV(66,0);
3616 PL_errors = newSVpvn("", 0);
3618 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3619 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3620 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3621 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3622 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3624 PL_reginterp_cnt = 0;
3625 PL_lastscream = Nullsv;
3628 PL_reg_start_tmp = 0;
3629 PL_reg_start_tmpl = 0;
3630 PL_reg_poscache = Nullch;
3632 /* parent thread's data needs to be locked while we make copy */
3633 MUTEX_LOCK(&t->mutex);
3635 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3636 PL_protect = t->Tprotect;
3639 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3640 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3641 PL_curstash = t->Tcurstash; /* always be set to main? */
3643 PL_tainted = t->Ttainted;
3644 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3645 PL_nrs = newSVsv(t->Tnrs);
3646 PL_rs = SvREFCNT_inc(PL_nrs);
3647 PL_last_in_gv = Nullgv;
3648 PL_ofs_sv = SvREFCNT_inc(PL_ofs_sv);
3649 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3650 PL_chopset = t->Tchopset;
3651 PL_bodytarget = newSVsv(t->Tbodytarget);
3652 PL_toptarget = newSVsv(t->Ttoptarget);
3653 if (t->Tformtarget == t->Ttoptarget)
3654 PL_formtarget = PL_toptarget;
3656 PL_formtarget = PL_bodytarget;
3658 /* Initialise all per-thread SVs that the template thread used */
3659 svp = AvARRAY(t->threadsv);
3660 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3661 if (*svp && *svp != &PL_sv_undef) {
3662 SV *sv = newSVsv(*svp);
3663 av_store(thr->threadsv, i, sv);
3664 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3665 DEBUG_S(PerlIO_printf(Perl_debug_log,
3666 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3670 thr->threadsvp = AvARRAY(thr->threadsv);
3672 MUTEX_LOCK(&PL_threads_mutex);
3674 thr->tid = ++PL_threadnum;
3675 thr->next = t->next;
3678 thr->next->prev = thr;
3679 MUTEX_UNLOCK(&PL_threads_mutex);
3681 /* done copying parent's state */
3682 MUTEX_UNLOCK(&t->mutex);
3684 #ifdef HAVE_THREAD_INTERN
3685 Perl_init_thread_intern(thr);
3686 #endif /* HAVE_THREAD_INTERN */
3689 #endif /* USE_THREADS */
3691 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
3693 * This hack is to force load of "huge" support from libm.a
3694 * So it is in perl for (say) POSIX to use.
3695 * Needed for SunOS with Sun's 'acc' for example.
3700 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
3707 #ifdef PERL_GLOBAL_STRUCT
3716 Perl_get_op_names(pTHX)
3722 Perl_get_op_descs(pTHX)
3728 Perl_get_no_modify(pTHX)
3730 return (char*)PL_no_modify;
3734 Perl_get_opargs(pTHX)
3740 Perl_get_ppaddr(pTHX)
3742 return (PPADDR_t*)PL_ppaddr;
3745 #ifndef HAS_GETENV_LEN
3747 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3749 char *env_trans = PerlEnv_getenv(env_elem);
3751 *len = strlen(env_trans);
3758 Perl_get_vtbl(pTHX_ int vtbl_id)
3760 MGVTBL* result = Null(MGVTBL*);
3764 result = &PL_vtbl_sv;
3767 result = &PL_vtbl_env;
3769 case want_vtbl_envelem:
3770 result = &PL_vtbl_envelem;
3773 result = &PL_vtbl_sig;
3775 case want_vtbl_sigelem:
3776 result = &PL_vtbl_sigelem;
3778 case want_vtbl_pack:
3779 result = &PL_vtbl_pack;
3781 case want_vtbl_packelem:
3782 result = &PL_vtbl_packelem;
3784 case want_vtbl_dbline:
3785 result = &PL_vtbl_dbline;
3788 result = &PL_vtbl_isa;
3790 case want_vtbl_isaelem:
3791 result = &PL_vtbl_isaelem;
3793 case want_vtbl_arylen:
3794 result = &PL_vtbl_arylen;
3796 case want_vtbl_glob:
3797 result = &PL_vtbl_glob;
3799 case want_vtbl_mglob:
3800 result = &PL_vtbl_mglob;
3802 case want_vtbl_nkeys:
3803 result = &PL_vtbl_nkeys;
3805 case want_vtbl_taint:
3806 result = &PL_vtbl_taint;
3808 case want_vtbl_substr:
3809 result = &PL_vtbl_substr;
3812 result = &PL_vtbl_vec;
3815 result = &PL_vtbl_pos;
3818 result = &PL_vtbl_bm;
3821 result = &PL_vtbl_fm;
3823 case want_vtbl_uvar:
3824 result = &PL_vtbl_uvar;
3827 case want_vtbl_mutex:
3828 result = &PL_vtbl_mutex;
3831 case want_vtbl_defelem:
3832 result = &PL_vtbl_defelem;
3834 case want_vtbl_regexp:
3835 result = &PL_vtbl_regexp;
3837 case want_vtbl_regdata:
3838 result = &PL_vtbl_regdata;
3840 case want_vtbl_regdatum:
3841 result = &PL_vtbl_regdatum;
3843 #ifdef USE_LOCALE_COLLATE
3844 case want_vtbl_collxfrm:
3845 result = &PL_vtbl_collxfrm;
3848 case want_vtbl_amagic:
3849 result = &PL_vtbl_amagic;
3851 case want_vtbl_amagicelem:
3852 result = &PL_vtbl_amagicelem;
3854 case want_vtbl_backref:
3855 result = &PL_vtbl_backref;
3862 Perl_my_fflush_all(pTHX)
3864 #if defined(FFLUSH_NULL)
3865 return PerlIO_flush(NULL);
3867 # if defined(HAS__FWALK)
3868 /* undocumented, unprototyped, but very useful BSDism */
3869 extern void _fwalk(int (*)(FILE *));
3874 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3875 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3876 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3878 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3879 open_max = sysconf(_SC_OPEN_MAX);
3882 open_max = FOPEN_MAX;
3885 open_max = OPEN_MAX;
3896 for (i = 0; i < open_max; i++)
3897 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3898 STDIO_STREAM_ARRAY[i]._file < open_max &&
3899 STDIO_STREAM_ARRAY[i]._flag)
3900 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3904 SETERRNO(EBADF,RMS$_IFI);
3911 Perl_my_atof(pTHX_ const char* s)
3914 #ifdef USE_LOCALE_NUMERIC
3915 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3919 SET_NUMERIC_STANDARD();
3921 SET_NUMERIC_LOCAL();
3922 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
3934 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3939 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3940 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3942 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3943 char *type = OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET) ?
3944 "socket" : "filehandle";
3947 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3949 warn_type = WARN_CLOSED;
3953 warn_type = WARN_UNOPENED;
3956 if (gv && isGV(gv)) {
3957 SV *sv = sv_newmortal();
3958 gv_efullname4(sv, gv, Nullch, FALSE);
3962 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3964 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
3966 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3968 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
3969 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3970 } else if (name && *name) {
3971 Perl_warner(aTHX_ warn_type,
3972 "%s%s on %s %s %s", func, pars, vile, type, name);
3973 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3974 Perl_warner(aTHX_ warn_type,
3975 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3979 Perl_warner(aTHX_ warn_type,
3980 "%s%s on %s %s", func, pars, vile, type);
3981 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3982 Perl_warner(aTHX_ warn_type,
3983 "\t(Are you trying to call %s%s on dirhandle?)\n",