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)
29 /* XXX If this causes problems, set i_unistd=undef in the hint file. */
38 /* Put this after #includes because fork and vfork prototypes may
46 # include <sys/wait.h>
57 long xcount[MAXXCOUNT];
58 long lastxcount[MAXXCOUNT];
59 long xycount[MAXXCOUNT][MAXYCOUNT];
60 long lastxycount[MAXXCOUNT][MAXYCOUNT];
64 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
65 # define FD_CLOEXEC 1 /* NeXT needs this */
68 /* paranoid version of system's malloc() */
70 /* NOTE: Do not call the next three routines directly. Use the macros
71 * in handy.h, so that we can easily redefine everything to do tracking of
72 * allocated hunks back to the original New to track down any memory leaks.
73 * XXX This advice seems to be widely ignored :-( --AD August 1996.
77 Perl_safesysmalloc(MEM_SIZE size)
83 PerlIO_printf(Perl_error_log,
84 "Allocation too large: %lx\n", size) FLUSH;
87 #endif /* HAS_64K_LIMIT */
90 Perl_croak_nocontext("panic: malloc");
92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
93 PERL_ALLOC_CHECK(ptr);
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
100 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
107 /* paranoid version of system's realloc() */
110 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
114 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
115 Malloc_t PerlMem_realloc();
116 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
120 PerlIO_printf(Perl_error_log,
121 "Reallocation too large: %lx\n", size) FLUSH;
124 #endif /* HAS_64K_LIMIT */
131 return safesysmalloc(size);
134 Perl_croak_nocontext("panic: realloc");
136 ptr = (Malloc_t)PerlMem_realloc(where,size);
137 PERL_ALLOC_CHECK(ptr);
139 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
140 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
147 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
154 /* safe version of system's free() */
157 Perl_safesysfree(Malloc_t where)
159 #ifdef PERL_IMPLICIT_SYS
162 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
169 /* safe version of system's calloc() */
172 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
178 if (size * count > 0xffff) {
179 PerlIO_printf(Perl_error_log,
180 "Allocation too large: %lx\n", size * count) FLUSH;
183 #endif /* HAS_64K_LIMIT */
185 if ((long)size < 0 || (long)count < 0)
186 Perl_croak_nocontext("panic: calloc");
189 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
190 PERL_ALLOC_CHECK(ptr);
191 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));
193 memset((void*)ptr, 0, size);
199 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
208 struct mem_test_strut {
216 # define ALIGN sizeof(struct mem_test_strut)
218 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
219 # define typeof_chunk(ch) \
220 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
221 # define set_typeof_chunk(ch,t) \
222 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
223 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
226 ? ((size) - 1)/8 + 5 \
230 Perl_safexmalloc(I32 x, MEM_SIZE size)
232 register char* where = (char*)safemalloc(size + ALIGN);
235 xycount[x][SIZE_TO_Y(size)]++;
236 set_typeof_chunk(where, x);
237 sizeof_chunk(where) = size;
238 return (Malloc_t)(where + ALIGN);
242 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
244 char *where = (char*)wh;
247 return safexmalloc(0,size);
250 MEM_SIZE old = sizeof_chunk(where - ALIGN);
251 int t = typeof_chunk(where - ALIGN);
252 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
254 xycount[t][SIZE_TO_Y(old)]--;
255 xycount[t][SIZE_TO_Y(size)]++;
256 xcount[t] += size - old;
257 sizeof_chunk(new) = size;
258 return (Malloc_t)(new + ALIGN);
263 Perl_safexfree(Malloc_t wh)
266 char *where = (char*)wh;
272 size = sizeof_chunk(where);
273 x = where[0] + 100 * where[1];
275 xycount[x][SIZE_TO_Y(size)]--;
280 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
282 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
284 xycount[x][SIZE_TO_Y(size)]++;
285 memset((void*)(where + ALIGN), 0, size * count);
286 set_typeof_chunk(where, x);
287 sizeof_chunk(where) = size;
288 return (Malloc_t)(where + ALIGN);
292 S_xstat(pTHX_ int flag)
294 register I32 i, j, total = 0;
295 I32 subtot[MAXYCOUNT];
297 for (j = 0; j < MAXYCOUNT; j++) {
301 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);
302 for (i = 0; i < MAXXCOUNT; i++) {
304 for (j = 0; j < MAXYCOUNT; j++) {
305 subtot[j] += xycount[i][j];
308 ? xcount[i] /* Have something */
310 ? xcount[i] != lastxcount[i] /* Changed */
311 : xcount[i] > lastxcount[i])) { /* Growed */
312 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
313 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
314 lastxcount[i] = xcount[i];
315 for (j = 0; j < MAXYCOUNT; j++) {
317 ? xycount[i][j] /* Have something */
319 ? xycount[i][j] != lastxycount[i][j] /* Changed */
320 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
321 PerlIO_printf(Perl_debug_log,"%3ld ",
323 ? xycount[i][j] - lastxycount[i][j]
325 lastxycount[i][j] = xycount[i][j];
327 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
330 PerlIO_printf(Perl_debug_log, "\n");
334 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
335 for (j = 0; j < MAXYCOUNT; j++) {
337 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
339 PerlIO_printf(Perl_debug_log, " . ");
342 PerlIO_printf(Perl_debug_log, "\n");
346 #endif /* LEAKTEST */
348 /* copy a string up to some (non-backslashed) delimiter, if any */
351 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
354 for (tolen = 0; from < fromend; from++, tolen++) {
356 if (from[1] == delim)
365 else if (*from == delim)
376 /* return ptr to little string in big string, NULL if not found */
377 /* This routine was donated by Corey Satten. */
380 Perl_instr(pTHX_ register const char *big, register const char *little)
382 register const char *s, *x;
393 for (x=big,s=little; *s; /**/ ) {
402 return (char*)(big-1);
407 /* same as instr but allow embedded nulls */
410 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
412 register const char *s, *x;
413 register I32 first = *little;
414 register const char *littleend = lend;
416 if (!first && little >= littleend)
418 if (bigend - big < littleend - little)
420 bigend -= littleend - little++;
421 while (big <= bigend) {
424 for (x=big,s=little; s < littleend; /**/ ) {
431 return (char*)(big-1);
436 /* reverse of the above--find last substring */
439 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
441 register const char *bigbeg;
442 register const char *s, *x;
443 register I32 first = *little;
444 register const char *littleend = lend;
446 if (!first && little >= littleend)
447 return (char*)bigend;
449 big = bigend - (littleend - little++);
450 while (big >= bigbeg) {
453 for (x=big+2,s=little; s < littleend; /**/ ) {
460 return (char*)(big+1);
466 * Set up for a new ctype locale.
469 Perl_new_ctype(pTHX_ char *newctype)
471 #ifdef USE_LOCALE_CTYPE
475 for (i = 0; i < 256; i++) {
477 PL_fold_locale[i] = toLOWER_LC(i);
478 else if (isLOWER_LC(i))
479 PL_fold_locale[i] = toUPPER_LC(i);
481 PL_fold_locale[i] = i;
484 #endif /* USE_LOCALE_CTYPE */
488 * Standardize the locale name from a string returned by 'setlocale'.
490 * The standard return value of setlocale() is either
491 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
492 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
493 * (the space-separated values represent the various sublocales,
494 * in some unspecificed order)
496 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
497 * which is harmful for further use of the string in setlocale().
501 S_stdize_locale(pTHX_ char *locs)
506 if ((s = strchr(locs, '='))) {
510 if ((t = strchr(s, '.'))) {
513 if ((u = strchr(t, '\n'))) {
517 Move(s + 1, locs, len, char);
526 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
532 * Set up for a new collation locale.
535 Perl_new_collate(pTHX_ char *newcoll)
537 #ifdef USE_LOCALE_COLLATE
540 if (PL_collation_name) {
542 Safefree(PL_collation_name);
543 PL_collation_name = NULL;
545 PL_collation_standard = TRUE;
546 PL_collxfrm_base = 0;
547 PL_collxfrm_mult = 2;
551 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
553 Safefree(PL_collation_name);
554 PL_collation_name = stdize_locale(savepv(newcoll));
555 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
558 /* 2: at most so many chars ('a', 'b'). */
559 /* 50: surely no system expands a char more. */
560 #define XFRMBUFSIZE (2 * 50)
561 char xbuf[XFRMBUFSIZE];
562 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
563 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
564 SSize_t mult = fb - fa;
566 Perl_croak(aTHX_ "strxfrm() gets absurd");
567 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
568 PL_collxfrm_mult = mult;
572 #endif /* USE_LOCALE_COLLATE */
576 Perl_set_numeric_radix(pTHX)
578 #ifdef USE_LOCALE_NUMERIC
579 # ifdef HAS_LOCALECONV
583 if (lc && lc->decimal_point)
584 /* We assume that decimal separator aka the radix
585 * character is always a single character. If it
586 * ever is a string, this needs to be rethunk. */
587 PL_numeric_radix = *lc->decimal_point;
589 PL_numeric_radix = 0;
590 # endif /* HAS_LOCALECONV */
591 #endif /* USE_LOCALE_NUMERIC */
595 * Set up for a new numeric locale.
598 Perl_new_numeric(pTHX_ char *newnum)
600 #ifdef USE_LOCALE_NUMERIC
603 if (PL_numeric_name) {
604 Safefree(PL_numeric_name);
605 PL_numeric_name = NULL;
607 PL_numeric_standard = TRUE;
608 PL_numeric_local = TRUE;
612 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
613 Safefree(PL_numeric_name);
614 PL_numeric_name = stdize_locale(savepv(newnum));
615 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
616 PL_numeric_local = TRUE;
620 #endif /* USE_LOCALE_NUMERIC */
624 Perl_set_numeric_standard(pTHX)
626 #ifdef USE_LOCALE_NUMERIC
628 if (! PL_numeric_standard) {
629 setlocale(LC_NUMERIC, "C");
630 PL_numeric_standard = TRUE;
631 PL_numeric_local = FALSE;
635 #endif /* USE_LOCALE_NUMERIC */
639 Perl_set_numeric_local(pTHX)
641 #ifdef USE_LOCALE_NUMERIC
643 if (! PL_numeric_local) {
644 setlocale(LC_NUMERIC, PL_numeric_name);
645 PL_numeric_standard = FALSE;
646 PL_numeric_local = TRUE;
650 #endif /* USE_LOCALE_NUMERIC */
654 * Initialize locale awareness.
657 Perl_init_i18nl10n(pTHX_ int printwarn)
661 * 1 = set ok or not applicable,
662 * 0 = fallback to C locale,
663 * -1 = fallback to C locale failed
668 #ifdef USE_LOCALE_CTYPE
669 char *curctype = NULL;
670 #endif /* USE_LOCALE_CTYPE */
671 #ifdef USE_LOCALE_COLLATE
672 char *curcoll = NULL;
673 #endif /* USE_LOCALE_COLLATE */
674 #ifdef USE_LOCALE_NUMERIC
676 #endif /* USE_LOCALE_NUMERIC */
678 char *language = PerlEnv_getenv("LANGUAGE");
680 char *lc_all = PerlEnv_getenv("LC_ALL");
681 char *lang = PerlEnv_getenv("LANG");
682 bool setlocale_failure = FALSE;
684 #ifdef LOCALE_ENVIRON_REQUIRED
687 * Ultrix setlocale(..., "") fails if there are no environment
688 * variables from which to get a locale name.
695 if (setlocale(LC_ALL, ""))
698 setlocale_failure = TRUE;
700 if (!setlocale_failure) {
701 #ifdef USE_LOCALE_CTYPE
704 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
706 setlocale_failure = TRUE;
708 curctype = savepv(curctype);
709 #endif /* USE_LOCALE_CTYPE */
710 #ifdef USE_LOCALE_COLLATE
712 setlocale(LC_COLLATE,
713 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
715 setlocale_failure = TRUE;
717 curcoll = savepv(curcoll);
718 #endif /* USE_LOCALE_COLLATE */
719 #ifdef USE_LOCALE_NUMERIC
721 setlocale(LC_NUMERIC,
722 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
724 setlocale_failure = TRUE;
726 curnum = savepv(curnum);
727 #endif /* USE_LOCALE_NUMERIC */
732 #endif /* !LOCALE_ENVIRON_REQUIRED */
735 if (! setlocale(LC_ALL, ""))
736 setlocale_failure = TRUE;
739 if (!setlocale_failure) {
740 #ifdef USE_LOCALE_CTYPE
741 if (! (curctype = setlocale(LC_CTYPE, "")))
742 setlocale_failure = TRUE;
744 curctype = savepv(curctype);
745 #endif /* USE_LOCALE_CTYPE */
746 #ifdef USE_LOCALE_COLLATE
747 if (! (curcoll = setlocale(LC_COLLATE, "")))
748 setlocale_failure = TRUE;
750 curcoll = savepv(curcoll);
751 #endif /* USE_LOCALE_COLLATE */
752 #ifdef USE_LOCALE_NUMERIC
753 if (! (curnum = setlocale(LC_NUMERIC, "")))
754 setlocale_failure = TRUE;
756 curnum = savepv(curnum);
757 #endif /* USE_LOCALE_NUMERIC */
760 if (setlocale_failure) {
762 bool locwarn = (printwarn > 1 ||
764 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
769 PerlIO_printf(Perl_error_log,
770 "perl: warning: Setting locale failed.\n");
774 PerlIO_printf(Perl_error_log,
775 "perl: warning: Setting locale failed for the categories:\n\t");
776 #ifdef USE_LOCALE_CTYPE
778 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
779 #endif /* USE_LOCALE_CTYPE */
780 #ifdef USE_LOCALE_COLLATE
782 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
783 #endif /* USE_LOCALE_COLLATE */
784 #ifdef USE_LOCALE_NUMERIC
786 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
787 #endif /* USE_LOCALE_NUMERIC */
788 PerlIO_printf(Perl_error_log, "\n");
792 PerlIO_printf(Perl_error_log,
793 "perl: warning: Please check that your locale settings:\n");
796 PerlIO_printf(Perl_error_log,
797 "\tLANGUAGE = %c%s%c,\n",
798 language ? '"' : '(',
799 language ? language : "unset",
800 language ? '"' : ')');
803 PerlIO_printf(Perl_error_log,
804 "\tLC_ALL = %c%s%c,\n",
806 lc_all ? lc_all : "unset",
811 for (e = environ; *e; e++) {
812 if (strnEQ(*e, "LC_", 3)
813 && strnNE(*e, "LC_ALL=", 7)
814 && (p = strchr(*e, '=')))
815 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
816 (int)(p - *e), *e, p + 1);
820 PerlIO_printf(Perl_error_log,
823 lang ? lang : "unset",
826 PerlIO_printf(Perl_error_log,
827 " are supported and installed on your system.\n");
832 if (setlocale(LC_ALL, "C")) {
834 PerlIO_printf(Perl_error_log,
835 "perl: warning: Falling back to the standard locale (\"C\").\n");
840 PerlIO_printf(Perl_error_log,
841 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
848 #ifdef USE_LOCALE_CTYPE
849 || !(curctype || setlocale(LC_CTYPE, "C"))
850 #endif /* USE_LOCALE_CTYPE */
851 #ifdef USE_LOCALE_COLLATE
852 || !(curcoll || setlocale(LC_COLLATE, "C"))
853 #endif /* USE_LOCALE_COLLATE */
854 #ifdef USE_LOCALE_NUMERIC
855 || !(curnum || setlocale(LC_NUMERIC, "C"))
856 #endif /* USE_LOCALE_NUMERIC */
860 PerlIO_printf(Perl_error_log,
861 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
865 #endif /* ! LC_ALL */
867 #ifdef USE_LOCALE_CTYPE
868 curctype = savepv(setlocale(LC_CTYPE, Nullch));
869 #endif /* USE_LOCALE_CTYPE */
870 #ifdef USE_LOCALE_COLLATE
871 curcoll = savepv(setlocale(LC_COLLATE, Nullch));
872 #endif /* USE_LOCALE_COLLATE */
873 #ifdef USE_LOCALE_NUMERIC
874 curnum = savepv(setlocale(LC_NUMERIC, Nullch));
875 #endif /* USE_LOCALE_NUMERIC */
879 #ifdef USE_LOCALE_CTYPE
881 #endif /* USE_LOCALE_CTYPE */
883 #ifdef USE_LOCALE_COLLATE
884 new_collate(curcoll);
885 #endif /* USE_LOCALE_COLLATE */
887 #ifdef USE_LOCALE_NUMERIC
889 #endif /* USE_LOCALE_NUMERIC */
892 #endif /* USE_LOCALE */
894 #ifdef USE_LOCALE_CTYPE
895 if (curctype != NULL)
897 #endif /* USE_LOCALE_CTYPE */
898 #ifdef USE_LOCALE_COLLATE
901 #endif /* USE_LOCALE_COLLATE */
902 #ifdef USE_LOCALE_NUMERIC
905 #endif /* USE_LOCALE_NUMERIC */
909 /* Backwards compatibility. */
911 Perl_init_i18nl14n(pTHX_ int printwarn)
913 return init_i18nl10n(printwarn);
916 #ifdef USE_LOCALE_COLLATE
919 * mem_collxfrm() is a bit like strxfrm() but with two important
920 * differences. First, it handles embedded NULs. Second, it allocates
921 * a bit more memory than needed for the transformed data itself.
922 * The real transformed data begins at offset sizeof(collationix).
923 * Please see sv_collxfrm() to see how this is used.
926 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
929 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
931 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
932 /* the +1 is for the terminating NUL. */
934 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
935 New(171, xbuf, xAlloc, char);
939 *(U32*)xbuf = PL_collation_ix;
940 xout = sizeof(PL_collation_ix);
941 for (xin = 0; xin < len; ) {
945 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
948 if (xused < xAlloc - xout)
950 xAlloc = (2 * xAlloc) + 1;
951 Renew(xbuf, xAlloc, char);
956 xin += strlen(s + xin) + 1;
959 /* Embedded NULs are understood but silently skipped
960 * because they make no sense in locale collation. */
964 *xlen = xout - sizeof(PL_collation_ix);
973 #endif /* USE_LOCALE_COLLATE */
975 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
977 /* As a space optimization, we do not compile tables for strings of length
978 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
979 special-cased in fbm_instr().
981 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
984 =for apidoc fbm_compile
986 Analyses the string in order to make fast searches on it using fbm_instr()
987 -- the Boyer-Moore algorithm.
993 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
1000 U32 frequency = 256;
1002 if (flags & FBMcf_TAIL)
1003 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
1004 s = (U8*)SvPV_force(sv, len);
1005 (void)SvUPGRADE(sv, SVt_PVBM);
1006 if (len == 0) /* TAIL might be on on a zero-length string. */
1016 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
1017 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
1018 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
1019 memset((void*)table, mlen, 256);
1020 table[-1] = (U8)flags;
1022 sb = s - mlen + 1; /* first char (maybe) */
1024 if (table[*s] == mlen)
1029 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
1032 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
1033 for (i = 0; i < len; i++) {
1034 if (PL_freq[s[i]] < frequency) {
1036 frequency = PL_freq[s[i]];
1039 BmRARE(sv) = s[rarest];
1040 BmPREVIOUS(sv) = rarest;
1041 BmUSEFUL(sv) = 100; /* Initial value */
1042 if (flags & FBMcf_TAIL)
1044 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
1045 BmRARE(sv),BmPREVIOUS(sv)));
1048 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
1049 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1053 =for apidoc fbm_instr
1055 Returns the location of the SV in the string delimited by C<str> and
1056 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
1057 does not have to be fbm_compiled, but the search will not be as fast
1064 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
1066 register unsigned char *s;
1068 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
1069 register STRLEN littlelen = l;
1070 register I32 multiline = flags & FBMrf_MULTILINE;
1072 if (bigend - big < littlelen) {
1073 if ( SvTAIL(littlestr)
1074 && (bigend - big == littlelen - 1)
1076 || (*big == *little &&
1077 memEQ((char *)big, (char *)little, littlelen - 1))))
1082 if (littlelen <= 2) { /* Special-cased */
1084 if (littlelen == 1) {
1085 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1086 /* Know that bigend != big. */
1087 if (bigend[-1] == '\n')
1088 return (char *)(bigend - 1);
1089 return (char *) bigend;
1092 while (s < bigend) {
1097 if (SvTAIL(littlestr))
1098 return (char *) bigend;
1102 return (char*)big; /* Cannot be SvTAIL! */
1104 /* littlelen is 2 */
1105 if (SvTAIL(littlestr) && !multiline) {
1106 if (bigend[-1] == '\n' && bigend[-2] == *little)
1107 return (char*)bigend - 2;
1108 if (bigend[-1] == *little)
1109 return (char*)bigend - 1;
1113 /* This should be better than FBM if c1 == c2, and almost
1114 as good otherwise: maybe better since we do less indirection.
1115 And we save a lot of memory by caching no table. */
1116 register unsigned char c1 = little[0];
1117 register unsigned char c2 = little[1];
1122 while (s <= bigend) {
1125 return (char*)s - 1;
1132 goto check_1char_anchor;
1143 goto check_1char_anchor;
1146 while (s <= bigend) {
1149 return (char*)s - 1;
1151 goto check_1char_anchor;
1160 check_1char_anchor: /* One char and anchor! */
1161 if (SvTAIL(littlestr) && (*bigend == *little))
1162 return (char *)bigend; /* bigend is already decremented. */
1165 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1166 s = bigend - littlelen;
1167 if (s >= big && bigend[-1] == '\n' && *s == *little
1168 /* Automatically of length > 2 */
1169 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1171 return (char*)s; /* how sweet it is */
1174 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1176 return (char*)s + 1; /* how sweet it is */
1180 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1181 char *b = ninstr((char*)big,(char*)bigend,
1182 (char*)little, (char*)little + littlelen);
1184 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1185 /* Chop \n from littlestr: */
1186 s = bigend - littlelen + 1;
1188 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1197 { /* Do actual FBM. */
1198 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1199 register unsigned char *oldlittle;
1201 if (littlelen > bigend - big)
1203 --littlelen; /* Last char found by table lookup */
1205 s = big + littlelen;
1206 little += littlelen; /* last char */
1213 if ((tmp = table[*s])) {
1215 if (bigend - s > tmp) {
1221 if ((s += tmp) < bigend)
1226 else { /* less expensive than calling strncmp() */
1227 register unsigned char *olds = s;
1232 if (*--s == *--little)
1234 s = olds + 1; /* here we pay the price for failure */
1236 if (s < bigend) /* fake up continue to outer loop */
1244 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1245 && memEQ((char *)(bigend - littlelen),
1246 (char *)(oldlittle - littlelen), littlelen) )
1247 return (char*)bigend - littlelen;
1252 /* start_shift, end_shift are positive quantities which give offsets
1253 of ends of some substring of bigstr.
1254 If `last' we want the last occurence.
1255 old_posp is the way of communication between consequent calls if
1256 the next call needs to find the .
1257 The initial *old_posp should be -1.
1259 Note that we take into account SvTAIL, so one can get extra
1260 optimizations if _ALL flag is set.
1263 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1264 if PL_multiline. In fact if !PL_multiline the autoritative answer
1265 is not supported yet. */
1268 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1271 register unsigned char *s, *x;
1272 register unsigned char *big;
1274 register I32 previous;
1276 register unsigned char *little;
1277 register I32 stop_pos;
1278 register unsigned char *littleend;
1282 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1283 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1285 if ( BmRARE(littlestr) == '\n'
1286 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1287 little = (unsigned char *)(SvPVX(littlestr));
1288 littleend = little + SvCUR(littlestr);
1295 little = (unsigned char *)(SvPVX(littlestr));
1296 littleend = little + SvCUR(littlestr);
1298 /* The value of pos we can start at: */
1299 previous = BmPREVIOUS(littlestr);
1300 big = (unsigned char *)(SvPVX(bigstr));
1301 /* The value of pos we can stop at: */
1302 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1303 if (previous + start_shift > stop_pos) {
1304 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1308 while (pos < previous + start_shift) {
1309 if (!(pos += PL_screamnext[pos]))
1314 if (pos >= stop_pos) break;
1315 if (big[pos-previous] != first)
1317 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1323 if (s == littleend) {
1325 if (!last) return (char *)(big+pos-previous);
1328 } while ( pos += PL_screamnext[pos] );
1329 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1330 #else /* !POINTERRIGOR */
1333 if (pos >= stop_pos) break;
1334 if (big[pos] != first)
1336 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1342 if (s == littleend) {
1344 if (!last) return (char *)(big+pos);
1347 } while ( pos += PL_screamnext[pos] );
1349 return (char *)(big+(*old_posp));
1350 #endif /* POINTERRIGOR */
1352 if (!SvTAIL(littlestr) || (end_shift > 0))
1354 /* Ignore the trailing "\n". This code is not microoptimized */
1355 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1356 stop_pos = littleend - little; /* Actual littlestr len */
1361 && ((stop_pos == 1) ||
1362 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1368 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1370 register U8 *a = (U8 *)s1;
1371 register U8 *b = (U8 *)s2;
1373 if (*a != *b && *a != PL_fold[*b])
1381 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1383 register U8 *a = (U8 *)s1;
1384 register U8 *b = (U8 *)s2;
1386 if (*a != *b && *a != PL_fold_locale[*b])
1393 /* copy a string to a safe spot */
1398 Copy a string to a safe spot. This does not use an SV.
1404 Perl_savepv(pTHX_ const char *sv)
1406 register char *newaddr;
1408 New(902,newaddr,strlen(sv)+1,char);
1409 (void)strcpy(newaddr,sv);
1413 /* same thing but with a known length */
1418 Copy a string to a safe spot. The C<len> indicates number of bytes to
1419 copy. This does not use an SV.
1425 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1427 register char *newaddr;
1429 New(903,newaddr,len+1,char);
1430 Copy(sv,newaddr,len,char); /* might not be null terminated */
1431 newaddr[len] = '\0'; /* is now */
1435 /* the SV for Perl_form() and mess() is not kept in an arena */
1445 return sv_2mortal(newSVpvn("",0));
1450 /* Create as PVMG now, to avoid any upgrading later */
1451 New(905, sv, 1, SV);
1452 Newz(905, any, 1, XPVMG);
1453 SvFLAGS(sv) = SVt_PVMG;
1454 SvANY(sv) = (void*)any;
1455 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1460 #if defined(PERL_IMPLICIT_CONTEXT)
1462 Perl_form_nocontext(const char* pat, ...)
1467 va_start(args, pat);
1468 retval = vform(pat, &args);
1472 #endif /* PERL_IMPLICIT_CONTEXT */
1475 Perl_form(pTHX_ const char* pat, ...)
1479 va_start(args, pat);
1480 retval = vform(pat, &args);
1486 Perl_vform(pTHX_ const char *pat, va_list *args)
1488 SV *sv = mess_alloc();
1489 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1493 #if defined(PERL_IMPLICIT_CONTEXT)
1495 Perl_mess_nocontext(const char *pat, ...)
1500 va_start(args, pat);
1501 retval = vmess(pat, &args);
1505 #endif /* PERL_IMPLICIT_CONTEXT */
1508 Perl_mess(pTHX_ const char *pat, ...)
1512 va_start(args, pat);
1513 retval = vmess(pat, &args);
1519 Perl_vmess(pTHX_ const char *pat, va_list *args)
1521 SV *sv = mess_alloc();
1522 static char dgd[] = " during global destruction.\n";
1524 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1525 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1527 if (CopLINE(PL_curcop))
1528 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1529 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1530 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1531 bool line_mode = (RsSIMPLE(PL_rs) &&
1532 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1533 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1534 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1535 line_mode ? "line" : "chunk",
1536 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1540 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1542 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1548 Perl_vdie(pTHX_ const char* pat, va_list *args)
1552 int was_in_eval = PL_in_eval;
1559 DEBUG_S(PerlIO_printf(Perl_debug_log,
1560 "%p: die: curstack = %p, mainstack = %p\n",
1561 thr, PL_curstack, PL_mainstack));
1564 msv = vmess(pat, args);
1565 if (PL_errors && SvCUR(PL_errors)) {
1566 sv_catsv(PL_errors, msv);
1567 message = SvPV(PL_errors, msglen);
1568 SvCUR_set(PL_errors, 0);
1571 message = SvPV(msv,msglen);
1578 DEBUG_S(PerlIO_printf(Perl_debug_log,
1579 "%p: die: message = %s\ndiehook = %p\n",
1580 thr, message, PL_diehook));
1582 /* sv_2cv might call Perl_croak() */
1583 SV *olddiehook = PL_diehook;
1585 SAVESPTR(PL_diehook);
1586 PL_diehook = Nullsv;
1587 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1589 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1596 msg = newSVpvn(message, msglen);
1604 PUSHSTACKi(PERLSI_DIEHOOK);
1608 call_sv((SV*)cv, G_DISCARD);
1614 PL_restartop = die_where(message, msglen);
1615 DEBUG_S(PerlIO_printf(Perl_debug_log,
1616 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1617 thr, PL_restartop, was_in_eval, PL_top_env));
1618 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1620 return PL_restartop;
1623 #if defined(PERL_IMPLICIT_CONTEXT)
1625 Perl_die_nocontext(const char* pat, ...)
1630 va_start(args, pat);
1631 o = vdie(pat, &args);
1635 #endif /* PERL_IMPLICIT_CONTEXT */
1638 Perl_die(pTHX_ const char* pat, ...)
1642 va_start(args, pat);
1643 o = vdie(pat, &args);
1649 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1660 msv = vmess(pat, args);
1661 if (PL_errors && SvCUR(PL_errors)) {
1662 sv_catsv(PL_errors, msv);
1663 message = SvPV(PL_errors, msglen);
1664 SvCUR_set(PL_errors, 0);
1667 message = SvPV(msv,msglen);
1674 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1675 PTR2UV(thr), message));
1678 /* sv_2cv might call Perl_croak() */
1679 SV *olddiehook = PL_diehook;
1681 SAVESPTR(PL_diehook);
1682 PL_diehook = Nullsv;
1683 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1685 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1692 msg = newSVpvn(message, msglen);
1700 PUSHSTACKi(PERLSI_DIEHOOK);
1704 call_sv((SV*)cv, G_DISCARD);
1710 PL_restartop = die_where(message, msglen);
1715 /* SFIO can really mess with your errno */
1718 PerlIO *serr = Perl_error_log;
1720 PerlIO_write(serr, message, msglen);
1721 (void)PerlIO_flush(serr);
1729 #if defined(PERL_IMPLICIT_CONTEXT)
1731 Perl_croak_nocontext(const char *pat, ...)
1735 va_start(args, pat);
1740 #endif /* PERL_IMPLICIT_CONTEXT */
1745 This is the XSUB-writer's interface to Perl's C<die> function.
1746 Normally use this function the same way you use the C C<printf>
1747 function. See C<warn>.
1749 If you want to throw an exception object, assign the object to
1750 C<$@> and then pass C<Nullch> to croak():
1752 errsv = get_sv("@", TRUE);
1753 sv_setsv(errsv, exception_object);
1760 Perl_croak(pTHX_ const char *pat, ...)
1763 va_start(args, pat);
1770 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1779 msv = vmess(pat, args);
1780 message = SvPV(msv, msglen);
1783 /* sv_2cv might call Perl_warn() */
1785 SV *oldwarnhook = PL_warnhook;
1787 SAVESPTR(PL_warnhook);
1788 PL_warnhook = Nullsv;
1789 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1791 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1797 msg = newSVpvn(message, msglen);
1801 PUSHSTACKi(PERLSI_WARNHOOK);
1805 call_sv((SV*)cv, G_DISCARD);
1812 PerlIO *serr = Perl_error_log;
1814 PerlIO_write(serr, message, msglen);
1816 DEBUG_L(*message == '!'
1817 ? (xstat(message[1]=='!'
1818 ? (message[2]=='!' ? 2 : 1)
1823 (void)PerlIO_flush(serr);
1827 #if defined(PERL_IMPLICIT_CONTEXT)
1829 Perl_warn_nocontext(const char *pat, ...)
1833 va_start(args, pat);
1837 #endif /* PERL_IMPLICIT_CONTEXT */
1842 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1843 function the same way you use the C C<printf> function. See
1850 Perl_warn(pTHX_ const char *pat, ...)
1853 va_start(args, pat);
1858 #if defined(PERL_IMPLICIT_CONTEXT)
1860 Perl_warner_nocontext(U32 err, const char *pat, ...)
1864 va_start(args, pat);
1865 vwarner(err, pat, &args);
1868 #endif /* PERL_IMPLICIT_CONTEXT */
1871 Perl_warner(pTHX_ U32 err, const char* pat,...)
1874 va_start(args, pat);
1875 vwarner(err, pat, &args);
1880 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1890 msv = vmess(pat, args);
1891 message = SvPV(msv, msglen);
1895 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1896 #endif /* USE_THREADS */
1898 /* sv_2cv might call Perl_croak() */
1899 SV *olddiehook = PL_diehook;
1901 SAVESPTR(PL_diehook);
1902 PL_diehook = Nullsv;
1903 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1905 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1911 msg = newSVpvn(message, msglen);
1915 PUSHSTACKi(PERLSI_DIEHOOK);
1919 call_sv((SV*)cv, G_DISCARD);
1925 PL_restartop = die_where(message, msglen);
1929 PerlIO *serr = Perl_error_log;
1930 PerlIO_write(serr, message, msglen);
1931 (void)PerlIO_flush(serr);
1938 /* sv_2cv might call Perl_warn() */
1940 SV *oldwarnhook = PL_warnhook;
1942 SAVESPTR(PL_warnhook);
1943 PL_warnhook = Nullsv;
1944 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1946 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1952 msg = newSVpvn(message, msglen);
1956 PUSHSTACKi(PERLSI_WARNHOOK);
1960 call_sv((SV*)cv, G_DISCARD);
1967 PerlIO *serr = Perl_error_log;
1968 PerlIO_write(serr, message, msglen);
1970 DEBUG_L(*message == '!'
1971 ? (xstat(message[1]=='!'
1972 ? (message[2]=='!' ? 2 : 1)
1977 (void)PerlIO_flush(serr);
1982 #ifdef USE_ENVIRON_ARRAY
1983 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1986 Perl_my_setenv(pTHX_ char *nam, char *val)
1988 #ifndef PERL_USE_SAFE_PUTENV
1989 /* most putenv()s leak, so we manipulate environ directly */
1990 register I32 i=setenv_getix(nam); /* where does it go? */
1992 if (environ == PL_origenviron) { /* need we copy environment? */
1998 for (max = i; environ[max]; max++) ;
1999 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2000 for (j=0; j<max; j++) { /* copy environment */
2001 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
2002 strcpy(tmpenv[j], environ[j]);
2004 tmpenv[max] = Nullch;
2005 environ = tmpenv; /* tell exec where it is now */
2008 safesysfree(environ[i]);
2009 while (environ[i]) {
2010 environ[i] = environ[i+1];
2015 if (!environ[i]) { /* does not exist yet */
2016 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2017 environ[i+1] = Nullch; /* make sure it's null terminated */
2020 safesysfree(environ[i]);
2021 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
2023 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
2025 #else /* PERL_USE_SAFE_PUTENV */
2026 # if defined(__CYGWIN__)
2027 setenv(nam, val, 1);
2031 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
2032 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
2033 (void)putenv(new_env);
2034 # endif /* __CYGWIN__ */
2035 #endif /* PERL_USE_SAFE_PUTENV */
2041 Perl_my_setenv(pTHX_ char *nam,char *val)
2044 #ifdef USE_WIN32_RTL_ENV
2046 register char *envstr;
2047 STRLEN namlen = strlen(nam);
2049 char *oldstr = environ[setenv_getix(nam)];
2051 /* putenv() has totally broken semantics in both the Borland
2052 * and Microsoft CRTLs. They either store the passed pointer in
2053 * the environment without making a copy, or make a copy and don't
2054 * free it. And on top of that, they dont free() old entries that
2055 * are being replaced/deleted. This means the caller must
2056 * free any old entries somehow, or we end up with a memory
2057 * leak every time my_setenv() is called. One might think
2058 * one could directly manipulate environ[], like the UNIX code
2059 * above, but direct changes to environ are not allowed when
2060 * calling putenv(), since the RTLs maintain an internal
2061 * *copy* of environ[]. Bad, bad, *bad* stink.
2072 vallen = strlen(val);
2073 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
2074 (void)sprintf(envstr,"%s=%s",nam,val);
2075 (void)PerlEnv_putenv(envstr);
2077 safesysfree(oldstr);
2079 safesysfree(envstr); /* MSVCRT leaks without this */
2082 #else /* !USE_WIN32_RTL_ENV */
2084 register char *envstr;
2085 STRLEN len = strlen(nam) + 3;
2090 New(904, envstr, len, char);
2091 (void)sprintf(envstr,"%s=%s",nam,val);
2092 (void)PerlEnv_putenv(envstr);
2101 Perl_setenv_getix(pTHX_ char *nam)
2103 register I32 i, len = strlen(nam);
2105 for (i = 0; environ[i]; i++) {
2108 strnicmp(environ[i],nam,len) == 0
2110 strnEQ(environ[i],nam,len)
2112 && environ[i][len] == '=')
2113 break; /* strnEQ must come first to avoid */
2114 } /* potential SEGV's */
2118 #endif /* !VMS && !EPOC*/
2120 #ifdef UNLINK_ALL_VERSIONS
2122 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2126 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2131 /* this is a drop-in replacement for bcopy() */
2132 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2134 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2138 if (from - to >= 0) {
2146 *(--to) = *(--from);
2152 /* this is a drop-in replacement for memset() */
2155 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2165 /* this is a drop-in replacement for bzero() */
2166 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2168 Perl_my_bzero(register char *loc, register I32 len)
2178 /* this is a drop-in replacement for memcmp() */
2179 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2181 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2183 register U8 *a = (U8 *)s1;
2184 register U8 *b = (U8 *)s2;
2188 if (tmp = *a++ - *b++)
2193 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2197 #ifdef USE_CHAR_VSPRINTF
2202 vsprintf(char *dest, const char *pat, char *args)
2206 fakebuf._ptr = dest;
2207 fakebuf._cnt = 32767;
2211 fakebuf._flag = _IOWRT|_IOSTRG;
2212 _doprnt(pat, args, &fakebuf); /* what a kludge */
2213 (void)putc('\0', &fakebuf);
2214 #ifdef USE_CHAR_VSPRINTF
2217 return 0; /* perl doesn't use return value */
2221 #endif /* HAS_VPRINTF */
2224 #if BYTEORDER != 0x4321
2226 Perl_my_swap(pTHX_ short s)
2228 #if (BYTEORDER & 1) == 0
2231 result = ((s & 255) << 8) + ((s >> 8) & 255);
2239 Perl_my_htonl(pTHX_ long l)
2243 char c[sizeof(long)];
2246 #if BYTEORDER == 0x1234
2247 u.c[0] = (l >> 24) & 255;
2248 u.c[1] = (l >> 16) & 255;
2249 u.c[2] = (l >> 8) & 255;
2253 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2254 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2259 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2260 u.c[o & 0xf] = (l >> s) & 255;
2268 Perl_my_ntohl(pTHX_ long l)
2272 char c[sizeof(long)];
2275 #if BYTEORDER == 0x1234
2276 u.c[0] = (l >> 24) & 255;
2277 u.c[1] = (l >> 16) & 255;
2278 u.c[2] = (l >> 8) & 255;
2282 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2283 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2290 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2291 l |= (u.c[o & 0xf] & 255) << s;
2298 #endif /* BYTEORDER != 0x4321 */
2302 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2303 * If these functions are defined,
2304 * the BYTEORDER is neither 0x1234 nor 0x4321.
2305 * However, this is not assumed.
2309 #define HTOV(name,type) \
2311 name (register type n) \
2315 char c[sizeof(type)]; \
2319 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2320 u.c[i] = (n >> s) & 0xFF; \
2325 #define VTOH(name,type) \
2327 name (register type n) \
2331 char c[sizeof(type)]; \
2337 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2338 n += (u.c[i] & 0xFF) << s; \
2343 #if defined(HAS_HTOVS) && !defined(htovs)
2346 #if defined(HAS_HTOVL) && !defined(htovl)
2349 #if defined(HAS_VTOHS) && !defined(vtohs)
2352 #if defined(HAS_VTOHL) && !defined(vtohl)
2356 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2357 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2359 Perl_my_popen(pTHX_ char *cmd, char *mode)
2362 register I32 This, that;
2365 I32 doexec = strNE(cmd,"-");
2369 PERL_FLUSHALL_FOR_CHILD;
2372 return my_syspopen(aTHX_ cmd,mode);
2375 This = (*mode == 'w');
2377 if (doexec && PL_tainting) {
2379 taint_proper("Insecure %s%s", "EXEC");
2381 if (PerlProc_pipe(p) < 0)
2383 if (doexec && PerlProc_pipe(pp) >= 0)
2385 while ((pid = (doexec?vfork():fork())) < 0) {
2386 if (errno != EAGAIN) {
2387 PerlLIO_close(p[This]);
2389 PerlLIO_close(pp[0]);
2390 PerlLIO_close(pp[1]);
2393 Perl_croak(aTHX_ "Can't fork");
2405 PerlLIO_close(p[THAT]);
2407 PerlLIO_close(pp[0]);
2408 #if defined(HAS_FCNTL) && defined(F_SETFD)
2409 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2412 if (p[THIS] != (*mode == 'r')) {
2413 PerlLIO_dup2(p[THIS], *mode == 'r');
2414 PerlLIO_close(p[THIS]);
2418 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2424 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2428 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2431 #endif /* defined OS2 */
2433 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
2434 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2436 hv_clear(PL_pidstatus); /* we have no children */
2441 do_execfree(); /* free any memory malloced by child on vfork */
2442 PerlLIO_close(p[that]);
2444 PerlLIO_close(pp[1]);
2445 if (p[that] < p[This]) {
2446 PerlLIO_dup2(p[This], p[that]);
2447 PerlLIO_close(p[This]);
2451 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2453 (void)SvUPGRADE(sv,SVt_IV);
2455 PL_forkprocess = pid;
2456 if (did_pipes && pid > 0) {
2460 while (n < sizeof(int)) {
2461 n1 = PerlLIO_read(pp[0],
2462 (void*)(((char*)&errkid)+n),
2468 PerlLIO_close(pp[0]);
2470 if (n) { /* Error */
2471 if (n != sizeof(int))
2472 Perl_croak(aTHX_ "panic: kid popen errno read");
2473 errno = errkid; /* Propagate errno from kid */
2478 PerlLIO_close(pp[0]);
2479 return PerlIO_fdopen(p[This], mode);
2482 #if defined(atarist) || defined(DJGPP)
2485 Perl_my_popen(pTHX_ char *cmd, char *mode)
2487 PERL_FLUSHALL_FOR_CHILD;
2488 /* Call system's popen() to get a FILE *, then import it.
2489 used 0 for 2nd parameter to PerlIO_importFILE;
2492 return PerlIO_importFILE(popen(cmd, mode), 0);
2496 #endif /* !DOSISH */
2500 Perl_dump_fds(pTHX_ char *s)
2503 struct stat tmpstatbuf;
2505 PerlIO_printf(Perl_debug_log,"%s", s);
2506 for (fd = 0; fd < 32; fd++) {
2507 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2508 PerlIO_printf(Perl_debug_log," %d",fd);
2510 PerlIO_printf(Perl_debug_log,"\n");
2512 #endif /* DUMP_FDS */
2516 dup2(int oldfd, int newfd)
2518 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2521 PerlLIO_close(newfd);
2522 return fcntl(oldfd, F_DUPFD, newfd);
2524 #define DUP2_MAX_FDS 256
2525 int fdtmp[DUP2_MAX_FDS];
2531 PerlLIO_close(newfd);
2532 /* good enough for low fd's... */
2533 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2534 if (fdx >= DUP2_MAX_FDS) {
2542 PerlLIO_close(fdtmp[--fdx]);
2549 #ifdef HAS_SIGACTION
2552 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2554 struct sigaction act, oact;
2556 act.sa_handler = handler;
2557 sigemptyset(&act.sa_mask);
2560 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2563 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2564 act.sa_flags |= SA_NOCLDWAIT;
2566 if (sigaction(signo, &act, &oact) == -1)
2569 return oact.sa_handler;
2573 Perl_rsignal_state(pTHX_ int signo)
2575 struct sigaction oact;
2577 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2580 return oact.sa_handler;
2584 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2586 struct sigaction act;
2588 act.sa_handler = handler;
2589 sigemptyset(&act.sa_mask);
2592 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2595 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2596 act.sa_flags |= SA_NOCLDWAIT;
2598 return sigaction(signo, &act, save);
2602 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2604 return sigaction(signo, save, (struct sigaction *)NULL);
2607 #else /* !HAS_SIGACTION */
2610 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2612 return PerlProc_signal(signo, handler);
2615 static int sig_trapped;
2625 Perl_rsignal_state(pTHX_ int signo)
2627 Sighandler_t oldsig;
2630 oldsig = PerlProc_signal(signo, sig_trap);
2631 PerlProc_signal(signo, oldsig);
2633 PerlProc_kill(PerlProc_getpid(), signo);
2638 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2640 *save = PerlProc_signal(signo, handler);
2641 return (*save == SIG_ERR) ? -1 : 0;
2645 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2647 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2650 #endif /* !HAS_SIGACTION */
2651 #endif /* !PERL_MICRO */
2653 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2654 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2656 Perl_my_pclose(pTHX_ PerlIO *ptr)
2658 Sigsave_t hstat, istat, qstat;
2666 int saved_vaxc_errno;
2669 int saved_win32_errno;
2673 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2677 *svp = &PL_sv_undef;
2679 if (pid == -1) { /* Opened by popen. */
2680 return my_syspclose(ptr);
2683 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2684 saved_errno = errno;
2686 saved_vaxc_errno = vaxc$errno;
2689 saved_win32_errno = GetLastError();
2693 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2696 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2697 rsignal_save(SIGINT, SIG_IGN, &istat);
2698 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2701 pid2 = wait4pid(pid, &status, 0);
2702 } while (pid2 == -1 && errno == EINTR);
2704 rsignal_restore(SIGHUP, &hstat);
2705 rsignal_restore(SIGINT, &istat);
2706 rsignal_restore(SIGQUIT, &qstat);
2709 SETERRNO(saved_errno, saved_vaxc_errno);
2712 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2714 #endif /* !DOSISH */
2716 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2718 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2722 char spid[TYPE_CHARS(int)];
2726 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2728 sprintf(spid, "%"IVdf, (IV)pid);
2729 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2730 if (svp && *svp != &PL_sv_undef) {
2731 *statusp = SvIVX(*svp);
2732 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2739 hv_iterinit(PL_pidstatus);
2740 if ((entry = hv_iternext(PL_pidstatus))) {
2741 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2742 sv = hv_iterval(PL_pidstatus,entry);
2743 *statusp = SvIVX(sv);
2744 sprintf(spid, "%"IVdf, (IV)pid);
2745 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2751 # ifdef HAS_WAITPID_RUNTIME
2752 if (!HAS_WAITPID_RUNTIME)
2755 return PerlProc_waitpid(pid,statusp,flags);
2757 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2758 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2760 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2765 Perl_croak(aTHX_ "Can't do waitpid with flags");
2767 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2768 pidgone(result,*statusp);
2776 #endif /* !DOSISH || OS2 || WIN32 */
2780 Perl_pidgone(pTHX_ Pid_t pid, int status)
2783 char spid[TYPE_CHARS(int)];
2785 sprintf(spid, "%"IVdf, (IV)pid);
2786 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2787 (void)SvUPGRADE(sv,SVt_IV);
2792 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2795 int /* Cannot prototype with I32
2797 my_syspclose(PerlIO *ptr)
2800 Perl_my_pclose(pTHX_ PerlIO *ptr)
2803 /* Needs work for PerlIO ! */
2804 FILE *f = PerlIO_findFILE(ptr);
2805 I32 result = pclose(f);
2807 result = (result << 8) & 0xff00;
2809 PerlIO_releaseFILE(ptr,f);
2815 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2818 register const char *frombase = from;
2821 register const char c = *from;
2826 while (count-- > 0) {
2827 for (todo = len; todo > 0; todo--) {
2835 Perl_cast_ulong(pTHX_ NV f)
2840 # define BIGDOUBLE 2147483648.0
2842 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2845 return (unsigned long)f;
2847 return (unsigned long)along;
2851 /* Unfortunately, on some systems the cast_uv() function doesn't
2852 work with the system-supplied definition of ULONG_MAX. The
2853 comparison (f >= ULONG_MAX) always comes out true. It must be a
2854 problem with the compiler constant folding.
2856 In any case, this workaround should be fine on any two's complement
2857 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2859 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2862 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2864 -- Kenneth Albanowski <kjahds@kjahds.com>
2868 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2872 Perl_cast_i32(pTHX_ NV f)
2875 return (I32) I32_MAX;
2877 return (I32) I32_MIN;
2882 Perl_cast_iv(pTHX_ NV f)
2887 if (f >= (NV)UV_MAX)
2898 Perl_cast_uv(pTHX_ NV f)
2901 return (UV) MY_UV_MAX;
2915 Perl_same_dirent(pTHX_ char *a, char *b)
2917 char *fa = strrchr(a,'/');
2918 char *fb = strrchr(b,'/');
2919 struct stat tmpstatbuf1;
2920 struct stat tmpstatbuf2;
2921 SV *tmpsv = sv_newmortal();
2934 sv_setpv(tmpsv, ".");
2936 sv_setpvn(tmpsv, a, fa - a);
2937 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2940 sv_setpv(tmpsv, ".");
2942 sv_setpvn(tmpsv, b, fb - b);
2943 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2945 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2946 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2948 #endif /* !HAS_RENAME */
2951 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
2953 register char *s = start;
2954 register NV rnv = 0.0;
2955 register UV ruv = 0;
2956 register bool seenb = FALSE;
2957 register bool overflowed = FALSE;
2959 for (; len-- && *s; s++) {
2960 if (!(*s == '0' || *s == '1')) {
2961 if (*s == '_' && len && *retlen
2962 && (s[1] == '0' || s[1] == '1'))
2967 else if (seenb == FALSE && *s == 'b' && ruv == 0) {
2968 /* Disallow 0bbb0b0bbb... */
2974 if (ckWARN(WARN_DIGIT))
2975 Perl_warner(aTHX_ WARN_DIGIT,
2976 "Illegal binary digit '%c' ignored", *s);
2981 register UV xuv = ruv << 1;
2983 if ((xuv >> 1) != ruv) {
2987 if (ckWARN_d(WARN_OVERFLOW))
2988 Perl_warner(aTHX_ WARN_OVERFLOW,
2989 "Integer overflow in binary number");
2992 ruv = xuv | (*s - '0');
2996 /* If an NV has not enough bits in its mantissa to
2997 * represent an UV this summing of small low-order numbers
2998 * is a waste of time (because the NV cannot preserve
2999 * the low-order bits anyway): we could just remember when
3000 * did we overflow and in the end just multiply rnv by the
3007 if ( ( overflowed && rnv > 4294967295.0)
3009 || (!overflowed && ruv > 0xffffffff )
3013 if (ckWARN(WARN_PORTABLE))
3014 Perl_warner(aTHX_ WARN_PORTABLE,
3015 "Binary number > 0b11111111111111111111111111111111 non-portable");
3017 *retlen = s - start;
3022 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3024 register char *s = start;
3025 register NV rnv = 0.0;
3026 register UV ruv = 0;
3027 register bool overflowed = FALSE;
3029 for (; len-- && *s; s++) {
3030 if (!(*s >= '0' && *s <= '7')) {
3031 if (*s == '_' && len && *retlen
3032 && (s[1] >= '0' && s[1] <= '7'))
3038 /* Allow \octal to work the DWIM way (that is, stop scanning
3039 * as soon as non-octal characters are seen, complain only iff
3040 * someone seems to want to use the digits eight and nine). */
3041 if (*s == '8' || *s == '9') {
3043 if (ckWARN(WARN_DIGIT))
3044 Perl_warner(aTHX_ WARN_DIGIT,
3045 "Illegal octal digit '%c' ignored", *s);
3051 register UV xuv = ruv << 3;
3053 if ((xuv >> 3) != ruv) {
3057 if (ckWARN_d(WARN_OVERFLOW))
3058 Perl_warner(aTHX_ WARN_OVERFLOW,
3059 "Integer overflow in octal number");
3062 ruv = xuv | (*s - '0');
3066 /* If an NV has not enough bits in its mantissa to
3067 * represent an UV this summing of small low-order numbers
3068 * is a waste of time (because the NV cannot preserve
3069 * the low-order bits anyway): we could just remember when
3070 * did we overflow and in the end just multiply rnv by the
3071 * right amount of 8-tuples. */
3072 rnv += (NV)(*s - '0');
3077 if ( ( overflowed && rnv > 4294967295.0)
3079 || (!overflowed && ruv > 0xffffffff )
3083 if (ckWARN(WARN_PORTABLE))
3084 Perl_warner(aTHX_ WARN_PORTABLE,
3085 "Octal number > 037777777777 non-portable");
3087 *retlen = s - start;
3092 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3094 register char *s = start;
3095 register NV rnv = 0.0;
3096 register UV ruv = 0;
3097 register bool seenx = FALSE;
3098 register bool overflowed = FALSE;
3101 for (; len-- && *s; s++) {
3102 hexdigit = strchr((char *) PL_hexdigit, *s);
3104 if (*s == '_' && len && *retlen && s[1]
3105 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
3110 else if (seenx == FALSE && *s == 'x' && ruv == 0) {
3111 /* Disallow 0xxx0x0xxx... */
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",