3 * Copyright (c) 1991-2001, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12 * not content." --Gandalf
16 #define PERL_IN_UTIL_C
20 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
25 # define SIG_ERR ((Sighandler_t) -1)
33 /* Put this after #includes because fork and vfork prototypes may
41 # include <sys/wait.h>
52 long xcount[MAXXCOUNT];
53 long lastxcount[MAXXCOUNT];
54 long xycount[MAXXCOUNT][MAXYCOUNT];
55 long lastxycount[MAXXCOUNT][MAXYCOUNT];
59 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
60 # define FD_CLOEXEC 1 /* NeXT needs this */
63 /* paranoid version of system's malloc() */
65 /* NOTE: Do not call the next three routines directly. Use the macros
66 * in handy.h, so that we can easily redefine everything to do tracking of
67 * allocated hunks back to the original New to track down any memory leaks.
68 * XXX This advice seems to be widely ignored :-( --AD August 1996.
72 Perl_safesysmalloc(MEM_SIZE size)
78 PerlIO_printf(Perl_error_log,
79 "Allocation too large: %lx\n", size) FLUSH;
82 #endif /* HAS_64K_LIMIT */
85 Perl_croak_nocontext("panic: malloc");
87 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
88 PERL_ALLOC_CHECK(ptr);
89 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
95 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
102 /* paranoid version of system's realloc() */
105 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
109 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
110 Malloc_t PerlMem_realloc();
111 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
115 PerlIO_printf(Perl_error_log,
116 "Reallocation too large: %lx\n", size) FLUSH;
119 #endif /* HAS_64K_LIMIT */
126 return safesysmalloc(size);
129 Perl_croak_nocontext("panic: realloc");
131 ptr = (Malloc_t)PerlMem_realloc(where,size);
132 PERL_ALLOC_CHECK(ptr);
134 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
135 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
142 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
149 /* safe version of system's free() */
152 Perl_safesysfree(Malloc_t where)
154 #ifdef PERL_IMPLICIT_SYS
157 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
164 /* safe version of system's calloc() */
167 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
173 if (size * count > 0xffff) {
174 PerlIO_printf(Perl_error_log,
175 "Allocation too large: %lx\n", size * count) FLUSH;
178 #endif /* HAS_64K_LIMIT */
180 if ((long)size < 0 || (long)count < 0)
181 Perl_croak_nocontext("panic: calloc");
184 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
185 PERL_ALLOC_CHECK(ptr);
186 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
188 memset((void*)ptr, 0, size);
194 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
203 struct mem_test_strut {
211 # define ALIGN sizeof(struct mem_test_strut)
213 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
214 # define typeof_chunk(ch) \
215 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
216 # define set_typeof_chunk(ch,t) \
217 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
218 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
221 ? ((size) - 1)/8 + 5 \
225 Perl_safexmalloc(I32 x, MEM_SIZE size)
227 register char* where = (char*)safemalloc(size + ALIGN);
230 xycount[x][SIZE_TO_Y(size)]++;
231 set_typeof_chunk(where, x);
232 sizeof_chunk(where) = size;
233 return (Malloc_t)(where + ALIGN);
237 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
239 char *where = (char*)wh;
242 return safexmalloc(0,size);
245 MEM_SIZE old = sizeof_chunk(where - ALIGN);
246 int t = typeof_chunk(where - ALIGN);
247 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
249 xycount[t][SIZE_TO_Y(old)]--;
250 xycount[t][SIZE_TO_Y(size)]++;
251 xcount[t] += size - old;
252 sizeof_chunk(new) = size;
253 return (Malloc_t)(new + ALIGN);
258 Perl_safexfree(Malloc_t wh)
261 char *where = (char*)wh;
267 size = sizeof_chunk(where);
268 x = where[0] + 100 * where[1];
270 xycount[x][SIZE_TO_Y(size)]--;
275 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
277 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
279 xycount[x][SIZE_TO_Y(size)]++;
280 memset((void*)(where + ALIGN), 0, size * count);
281 set_typeof_chunk(where, x);
282 sizeof_chunk(where) = size;
283 return (Malloc_t)(where + ALIGN);
287 S_xstat(pTHX_ int flag)
289 register I32 i, j, total = 0;
290 I32 subtot[MAXYCOUNT];
292 for (j = 0; j < MAXYCOUNT; j++) {
296 PerlIO_printf(Perl_debug_log, " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
297 for (i = 0; i < MAXXCOUNT; i++) {
299 for (j = 0; j < MAXYCOUNT; j++) {
300 subtot[j] += xycount[i][j];
303 ? xcount[i] /* Have something */
305 ? xcount[i] != lastxcount[i] /* Changed */
306 : xcount[i] > lastxcount[i])) { /* Growed */
307 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
308 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
309 lastxcount[i] = xcount[i];
310 for (j = 0; j < MAXYCOUNT; j++) {
312 ? xycount[i][j] /* Have something */
314 ? xycount[i][j] != lastxycount[i][j] /* Changed */
315 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
316 PerlIO_printf(Perl_debug_log,"%3ld ",
318 ? xycount[i][j] - lastxycount[i][j]
320 lastxycount[i][j] = xycount[i][j];
322 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
325 PerlIO_printf(Perl_debug_log, "\n");
329 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
330 for (j = 0; j < MAXYCOUNT; j++) {
332 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
334 PerlIO_printf(Perl_debug_log, " . ");
337 PerlIO_printf(Perl_debug_log, "\n");
341 #endif /* LEAKTEST */
343 /* copy a string up to some (non-backslashed) delimiter, if any */
346 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
349 for (tolen = 0; from < fromend; from++, tolen++) {
351 if (from[1] == delim)
360 else if (*from == delim)
371 /* return ptr to little string in big string, NULL if not found */
372 /* This routine was donated by Corey Satten. */
375 Perl_instr(pTHX_ register const char *big, register const char *little)
377 register const char *s, *x;
388 for (x=big,s=little; *s; /**/ ) {
397 return (char*)(big-1);
402 /* same as instr but allow embedded nulls */
405 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
407 register const char *s, *x;
408 register I32 first = *little;
409 register const char *littleend = lend;
411 if (!first && little >= littleend)
413 if (bigend - big < littleend - little)
415 bigend -= littleend - little++;
416 while (big <= bigend) {
419 for (x=big,s=little; s < littleend; /**/ ) {
426 return (char*)(big-1);
431 /* reverse of the above--find last substring */
434 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
436 register const char *bigbeg;
437 register const char *s, *x;
438 register I32 first = *little;
439 register const char *littleend = lend;
441 if (!first && little >= littleend)
442 return (char*)bigend;
444 big = bigend - (littleend - little++);
445 while (big >= bigbeg) {
448 for (x=big+2,s=little; s < littleend; /**/ ) {
455 return (char*)(big+1);
461 * Set up for a new ctype locale.
464 Perl_new_ctype(pTHX_ char *newctype)
466 #ifdef USE_LOCALE_CTYPE
470 for (i = 0; i < 256; i++) {
472 PL_fold_locale[i] = toLOWER_LC(i);
473 else if (isLOWER_LC(i))
474 PL_fold_locale[i] = toUPPER_LC(i);
476 PL_fold_locale[i] = i;
479 #endif /* USE_LOCALE_CTYPE */
483 * Standardize the locale name from a string returned by 'setlocale'.
485 * The standard return value of setlocale() is either
486 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
487 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
488 * (the space-separated values represent the various sublocales,
489 * in some unspecificed order)
491 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
492 * which is harmful for further use of the string in setlocale().
496 S_stdize_locale(pTHX_ char *locs)
501 if ((s = strchr(locs, '='))) {
505 if ((t = strchr(s, '.'))) {
508 if ((u = strchr(t, '\n'))) {
512 Move(s + 1, locs, len, char);
521 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
527 * Set up for a new collation locale.
530 Perl_new_collate(pTHX_ char *newcoll)
532 #ifdef USE_LOCALE_COLLATE
535 if (PL_collation_name) {
537 Safefree(PL_collation_name);
538 PL_collation_name = NULL;
540 PL_collation_standard = TRUE;
541 PL_collxfrm_base = 0;
542 PL_collxfrm_mult = 2;
546 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
548 Safefree(PL_collation_name);
549 PL_collation_name = stdize_locale(savepv(newcoll));
550 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
553 /* 2: at most so many chars ('a', 'b'). */
554 /* 50: surely no system expands a char more. */
555 #define XFRMBUFSIZE (2 * 50)
556 char xbuf[XFRMBUFSIZE];
557 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
558 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
559 SSize_t mult = fb - fa;
561 Perl_croak(aTHX_ "strxfrm() gets absurd");
562 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
563 PL_collxfrm_mult = mult;
567 #endif /* USE_LOCALE_COLLATE */
571 Perl_set_numeric_radix(pTHX)
573 #ifdef USE_LOCALE_NUMERIC
574 # ifdef HAS_LOCALECONV
578 if (lc && lc->decimal_point) {
579 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
580 SvREFCNT_dec(PL_numeric_radix_sv);
581 PL_numeric_radix_sv = Nullsv;
584 if (PL_numeric_radix_sv)
585 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
587 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
591 PL_numeric_radix_sv = Nullsv;
592 # endif /* HAS_LOCALECONV */
593 #endif /* USE_LOCALE_NUMERIC */
597 * Set up for a new numeric locale.
600 Perl_new_numeric(pTHX_ char *newnum)
602 #ifdef USE_LOCALE_NUMERIC
605 if (PL_numeric_name) {
606 Safefree(PL_numeric_name);
607 PL_numeric_name = NULL;
609 PL_numeric_standard = TRUE;
610 PL_numeric_local = TRUE;
614 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
615 Safefree(PL_numeric_name);
616 PL_numeric_name = stdize_locale(savepv(newnum));
617 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
618 PL_numeric_local = TRUE;
622 #endif /* USE_LOCALE_NUMERIC */
626 Perl_set_numeric_standard(pTHX)
628 #ifdef USE_LOCALE_NUMERIC
630 if (! PL_numeric_standard) {
631 setlocale(LC_NUMERIC, "C");
632 PL_numeric_standard = TRUE;
633 PL_numeric_local = FALSE;
637 #endif /* USE_LOCALE_NUMERIC */
641 Perl_set_numeric_local(pTHX)
643 #ifdef USE_LOCALE_NUMERIC
645 if (! PL_numeric_local) {
646 setlocale(LC_NUMERIC, PL_numeric_name);
647 PL_numeric_standard = FALSE;
648 PL_numeric_local = TRUE;
652 #endif /* USE_LOCALE_NUMERIC */
656 * Initialize locale awareness.
659 Perl_init_i18nl10n(pTHX_ int printwarn)
663 * 1 = set ok or not applicable,
664 * 0 = fallback to C locale,
665 * -1 = fallback to C locale failed
668 #if defined(USE_LOCALE)
670 #ifdef USE_LOCALE_CTYPE
671 char *curctype = NULL;
672 #endif /* USE_LOCALE_CTYPE */
673 #ifdef USE_LOCALE_COLLATE
674 char *curcoll = NULL;
675 #endif /* USE_LOCALE_COLLATE */
676 #ifdef USE_LOCALE_NUMERIC
678 #endif /* USE_LOCALE_NUMERIC */
680 char *language = PerlEnv_getenv("LANGUAGE");
682 char *lc_all = PerlEnv_getenv("LC_ALL");
683 char *lang = PerlEnv_getenv("LANG");
684 bool setlocale_failure = FALSE;
686 #ifdef LOCALE_ENVIRON_REQUIRED
689 * Ultrix setlocale(..., "") fails if there are no environment
690 * variables from which to get a locale name.
697 if (setlocale(LC_ALL, ""))
700 setlocale_failure = TRUE;
702 if (!setlocale_failure) {
703 #ifdef USE_LOCALE_CTYPE
706 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
708 setlocale_failure = TRUE;
710 curctype = savepv(curctype);
711 #endif /* USE_LOCALE_CTYPE */
712 #ifdef USE_LOCALE_COLLATE
714 setlocale(LC_COLLATE,
715 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
717 setlocale_failure = TRUE;
719 curcoll = savepv(curcoll);
720 #endif /* USE_LOCALE_COLLATE */
721 #ifdef USE_LOCALE_NUMERIC
723 setlocale(LC_NUMERIC,
724 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
726 setlocale_failure = TRUE;
728 curnum = savepv(curnum);
729 #endif /* USE_LOCALE_NUMERIC */
734 #endif /* !LOCALE_ENVIRON_REQUIRED */
737 if (! setlocale(LC_ALL, ""))
738 setlocale_failure = TRUE;
741 if (!setlocale_failure) {
742 #ifdef USE_LOCALE_CTYPE
743 if (! (curctype = setlocale(LC_CTYPE, "")))
744 setlocale_failure = TRUE;
746 curctype = savepv(curctype);
747 #endif /* USE_LOCALE_CTYPE */
748 #ifdef USE_LOCALE_COLLATE
749 if (! (curcoll = setlocale(LC_COLLATE, "")))
750 setlocale_failure = TRUE;
752 curcoll = savepv(curcoll);
753 #endif /* USE_LOCALE_COLLATE */
754 #ifdef USE_LOCALE_NUMERIC
755 if (! (curnum = setlocale(LC_NUMERIC, "")))
756 setlocale_failure = TRUE;
758 curnum = savepv(curnum);
759 #endif /* USE_LOCALE_NUMERIC */
762 if (setlocale_failure) {
764 bool locwarn = (printwarn > 1 ||
766 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
771 PerlIO_printf(Perl_error_log,
772 "perl: warning: Setting locale failed.\n");
776 PerlIO_printf(Perl_error_log,
777 "perl: warning: Setting locale failed for the categories:\n\t");
778 #ifdef USE_LOCALE_CTYPE
780 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
781 #endif /* USE_LOCALE_CTYPE */
782 #ifdef USE_LOCALE_COLLATE
784 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
785 #endif /* USE_LOCALE_COLLATE */
786 #ifdef USE_LOCALE_NUMERIC
788 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
789 #endif /* USE_LOCALE_NUMERIC */
790 PerlIO_printf(Perl_error_log, "\n");
794 PerlIO_printf(Perl_error_log,
795 "perl: warning: Please check that your locale settings:\n");
798 PerlIO_printf(Perl_error_log,
799 "\tLANGUAGE = %c%s%c,\n",
800 language ? '"' : '(',
801 language ? language : "unset",
802 language ? '"' : ')');
805 PerlIO_printf(Perl_error_log,
806 "\tLC_ALL = %c%s%c,\n",
808 lc_all ? lc_all : "unset",
811 #if defined(USE_ENVIRON_ARRAY)
814 for (e = environ; *e; e++) {
815 if (strnEQ(*e, "LC_", 3)
816 && strnNE(*e, "LC_ALL=", 7)
817 && (p = strchr(*e, '=')))
818 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
819 (int)(p - *e), *e, p + 1);
823 PerlIO_printf(Perl_error_log,
824 "\t(possibly more locale environment variables)\n");
827 PerlIO_printf(Perl_error_log,
830 lang ? lang : "unset",
833 PerlIO_printf(Perl_error_log,
834 " are supported and installed on your system.\n");
839 if (setlocale(LC_ALL, "C")) {
841 PerlIO_printf(Perl_error_log,
842 "perl: warning: Falling back to the standard locale (\"C\").\n");
847 PerlIO_printf(Perl_error_log,
848 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
855 #ifdef USE_LOCALE_CTYPE
856 || !(curctype || setlocale(LC_CTYPE, "C"))
857 #endif /* USE_LOCALE_CTYPE */
858 #ifdef USE_LOCALE_COLLATE
859 || !(curcoll || setlocale(LC_COLLATE, "C"))
860 #endif /* USE_LOCALE_COLLATE */
861 #ifdef USE_LOCALE_NUMERIC
862 || !(curnum || setlocale(LC_NUMERIC, "C"))
863 #endif /* USE_LOCALE_NUMERIC */
867 PerlIO_printf(Perl_error_log,
868 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
872 #endif /* ! LC_ALL */
874 #ifdef USE_LOCALE_CTYPE
875 curctype = savepv(setlocale(LC_CTYPE, Nullch));
876 #endif /* USE_LOCALE_CTYPE */
877 #ifdef USE_LOCALE_COLLATE
878 curcoll = savepv(setlocale(LC_COLLATE, Nullch));
879 #endif /* USE_LOCALE_COLLATE */
880 #ifdef USE_LOCALE_NUMERIC
881 curnum = savepv(setlocale(LC_NUMERIC, Nullch));
882 #endif /* USE_LOCALE_NUMERIC */
886 #ifdef USE_LOCALE_CTYPE
888 #endif /* USE_LOCALE_CTYPE */
890 #ifdef USE_LOCALE_COLLATE
891 new_collate(curcoll);
892 #endif /* USE_LOCALE_COLLATE */
894 #ifdef USE_LOCALE_NUMERIC
896 #endif /* USE_LOCALE_NUMERIC */
899 #endif /* USE_LOCALE */
901 #ifdef USE_LOCALE_CTYPE
902 if (curctype != NULL)
904 #endif /* USE_LOCALE_CTYPE */
905 #ifdef USE_LOCALE_COLLATE
908 #endif /* USE_LOCALE_COLLATE */
909 #ifdef USE_LOCALE_NUMERIC
912 #endif /* USE_LOCALE_NUMERIC */
916 /* Backwards compatibility. */
918 Perl_init_i18nl14n(pTHX_ int printwarn)
920 return init_i18nl10n(printwarn);
923 #ifdef USE_LOCALE_COLLATE
926 * mem_collxfrm() is a bit like strxfrm() but with two important
927 * differences. First, it handles embedded NULs. Second, it allocates
928 * a bit more memory than needed for the transformed data itself.
929 * The real transformed data begins at offset sizeof(collationix).
930 * Please see sv_collxfrm() to see how this is used.
933 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
936 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
938 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
939 /* the +1 is for the terminating NUL. */
941 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
942 New(171, xbuf, xAlloc, char);
946 *(U32*)xbuf = PL_collation_ix;
947 xout = sizeof(PL_collation_ix);
948 for (xin = 0; xin < len; ) {
952 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
955 if (xused < xAlloc - xout)
957 xAlloc = (2 * xAlloc) + 1;
958 Renew(xbuf, xAlloc, char);
963 xin += strlen(s + xin) + 1;
966 /* Embedded NULs are understood but silently skipped
967 * because they make no sense in locale collation. */
971 *xlen = xout - sizeof(PL_collation_ix);
980 #endif /* USE_LOCALE_COLLATE */
982 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
984 /* As a space optimization, we do not compile tables for strings of length
985 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
986 special-cased in fbm_instr().
988 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
991 =for apidoc fbm_compile
993 Analyses the string in order to make fast searches on it using fbm_instr()
994 -- the Boyer-Moore algorithm.
1000 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
1007 U32 frequency = 256;
1009 if (flags & FBMcf_TAIL)
1010 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
1011 s = (U8*)SvPV_force(sv, len);
1012 (void)SvUPGRADE(sv, SVt_PVBM);
1013 if (len == 0) /* TAIL might be on on a zero-length string. */
1023 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
1024 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
1025 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
1026 memset((void*)table, mlen, 256);
1027 table[-1] = (U8)flags;
1029 sb = s - mlen + 1; /* first char (maybe) */
1031 if (table[*s] == mlen)
1036 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
1039 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
1040 for (i = 0; i < len; i++) {
1041 if (PL_freq[s[i]] < frequency) {
1043 frequency = PL_freq[s[i]];
1046 BmRARE(sv) = s[rarest];
1047 BmPREVIOUS(sv) = rarest;
1048 BmUSEFUL(sv) = 100; /* Initial value */
1049 if (flags & FBMcf_TAIL)
1051 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
1052 BmRARE(sv),BmPREVIOUS(sv)));
1055 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
1056 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1060 =for apidoc fbm_instr
1062 Returns the location of the SV in the string delimited by C<str> and
1063 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
1064 does not have to be fbm_compiled, but the search will not be as fast
1071 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
1073 register unsigned char *s;
1075 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
1076 register STRLEN littlelen = l;
1077 register I32 multiline = flags & FBMrf_MULTILINE;
1079 if (bigend - big < littlelen) {
1080 if ( SvTAIL(littlestr)
1081 && (bigend - big == littlelen - 1)
1083 || (*big == *little &&
1084 memEQ((char *)big, (char *)little, littlelen - 1))))
1089 if (littlelen <= 2) { /* Special-cased */
1091 if (littlelen == 1) {
1092 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1093 /* Know that bigend != big. */
1094 if (bigend[-1] == '\n')
1095 return (char *)(bigend - 1);
1096 return (char *) bigend;
1099 while (s < bigend) {
1104 if (SvTAIL(littlestr))
1105 return (char *) bigend;
1109 return (char*)big; /* Cannot be SvTAIL! */
1111 /* littlelen is 2 */
1112 if (SvTAIL(littlestr) && !multiline) {
1113 if (bigend[-1] == '\n' && bigend[-2] == *little)
1114 return (char*)bigend - 2;
1115 if (bigend[-1] == *little)
1116 return (char*)bigend - 1;
1120 /* This should be better than FBM if c1 == c2, and almost
1121 as good otherwise: maybe better since we do less indirection.
1122 And we save a lot of memory by caching no table. */
1123 register unsigned char c1 = little[0];
1124 register unsigned char c2 = little[1];
1129 while (s <= bigend) {
1132 return (char*)s - 1;
1139 goto check_1char_anchor;
1150 goto check_1char_anchor;
1153 while (s <= bigend) {
1156 return (char*)s - 1;
1158 goto check_1char_anchor;
1167 check_1char_anchor: /* One char and anchor! */
1168 if (SvTAIL(littlestr) && (*bigend == *little))
1169 return (char *)bigend; /* bigend is already decremented. */
1172 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1173 s = bigend - littlelen;
1174 if (s >= big && bigend[-1] == '\n' && *s == *little
1175 /* Automatically of length > 2 */
1176 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1178 return (char*)s; /* how sweet it is */
1181 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1183 return (char*)s + 1; /* how sweet it is */
1187 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1188 char *b = ninstr((char*)big,(char*)bigend,
1189 (char*)little, (char*)little + littlelen);
1191 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1192 /* Chop \n from littlestr: */
1193 s = bigend - littlelen + 1;
1195 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1204 { /* Do actual FBM. */
1205 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1206 register unsigned char *oldlittle;
1208 if (littlelen > bigend - big)
1210 --littlelen; /* Last char found by table lookup */
1212 s = big + littlelen;
1213 little += littlelen; /* last char */
1220 if ((tmp = table[*s])) {
1222 if (bigend - s > tmp) {
1228 if ((s += tmp) < bigend)
1233 else { /* less expensive than calling strncmp() */
1234 register unsigned char *olds = s;
1239 if (*--s == *--little)
1241 s = olds + 1; /* here we pay the price for failure */
1243 if (s < bigend) /* fake up continue to outer loop */
1251 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1252 && memEQ((char *)(bigend - littlelen),
1253 (char *)(oldlittle - littlelen), littlelen) )
1254 return (char*)bigend - littlelen;
1259 /* start_shift, end_shift are positive quantities which give offsets
1260 of ends of some substring of bigstr.
1261 If `last' we want the last occurence.
1262 old_posp is the way of communication between consequent calls if
1263 the next call needs to find the .
1264 The initial *old_posp should be -1.
1266 Note that we take into account SvTAIL, so one can get extra
1267 optimizations if _ALL flag is set.
1270 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1271 if PL_multiline. In fact if !PL_multiline the autoritative answer
1272 is not supported yet. */
1275 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1277 register unsigned char *s, *x;
1278 register unsigned char *big;
1280 register I32 previous;
1282 register unsigned char *little;
1283 register I32 stop_pos;
1284 register unsigned char *littleend;
1288 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1289 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1291 if ( BmRARE(littlestr) == '\n'
1292 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1293 little = (unsigned char *)(SvPVX(littlestr));
1294 littleend = little + SvCUR(littlestr);
1301 little = (unsigned char *)(SvPVX(littlestr));
1302 littleend = little + SvCUR(littlestr);
1304 /* The value of pos we can start at: */
1305 previous = BmPREVIOUS(littlestr);
1306 big = (unsigned char *)(SvPVX(bigstr));
1307 /* The value of pos we can stop at: */
1308 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1309 if (previous + start_shift > stop_pos) {
1310 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1314 while (pos < previous + start_shift) {
1315 if (!(pos += PL_screamnext[pos]))
1320 if (pos >= stop_pos) break;
1321 if (big[pos-previous] != first)
1323 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1329 if (s == littleend) {
1331 if (!last) return (char *)(big+pos-previous);
1334 } while ( pos += PL_screamnext[pos] );
1335 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1336 #else /* !POINTERRIGOR */
1339 if (pos >= stop_pos) break;
1340 if (big[pos] != first)
1342 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1348 if (s == littleend) {
1350 if (!last) return (char *)(big+pos);
1353 } while ( pos += PL_screamnext[pos] );
1355 return (char *)(big+(*old_posp));
1356 #endif /* POINTERRIGOR */
1358 if (!SvTAIL(littlestr) || (end_shift > 0))
1360 /* Ignore the trailing "\n". This code is not microoptimized */
1361 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1362 stop_pos = littleend - little; /* Actual littlestr len */
1367 && ((stop_pos == 1) ||
1368 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1374 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1376 register U8 *a = (U8 *)s1;
1377 register U8 *b = (U8 *)s2;
1379 if (*a != *b && *a != PL_fold[*b])
1387 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1389 register U8 *a = (U8 *)s1;
1390 register U8 *b = (U8 *)s2;
1392 if (*a != *b && *a != PL_fold_locale[*b])
1399 /* copy a string to a safe spot */
1404 Copy a string to a safe spot. This does not use an SV.
1410 Perl_savepv(pTHX_ const char *sv)
1412 register char *newaddr;
1414 New(902,newaddr,strlen(sv)+1,char);
1415 (void)strcpy(newaddr,sv);
1419 /* same thing but with a known length */
1424 Copy a string to a safe spot. The C<len> indicates number of bytes to
1425 copy. This does not use an SV.
1431 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1433 register char *newaddr;
1435 New(903,newaddr,len+1,char);
1436 Copy(sv,newaddr,len,char); /* might not be null terminated */
1437 newaddr[len] = '\0'; /* is now */
1441 /* the SV for Perl_form() and mess() is not kept in an arena */
1450 return sv_2mortal(newSVpvn("",0));
1455 /* Create as PVMG now, to avoid any upgrading later */
1456 New(905, sv, 1, SV);
1457 Newz(905, any, 1, XPVMG);
1458 SvFLAGS(sv) = SVt_PVMG;
1459 SvANY(sv) = (void*)any;
1460 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1465 #if defined(PERL_IMPLICIT_CONTEXT)
1467 Perl_form_nocontext(const char* pat, ...)
1472 va_start(args, pat);
1473 retval = vform(pat, &args);
1477 #endif /* PERL_IMPLICIT_CONTEXT */
1480 Perl_form(pTHX_ const char* pat, ...)
1484 va_start(args, pat);
1485 retval = vform(pat, &args);
1491 Perl_vform(pTHX_ const char *pat, va_list *args)
1493 SV *sv = mess_alloc();
1494 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1498 #if defined(PERL_IMPLICIT_CONTEXT)
1500 Perl_mess_nocontext(const char *pat, ...)
1505 va_start(args, pat);
1506 retval = vmess(pat, &args);
1510 #endif /* PERL_IMPLICIT_CONTEXT */
1513 Perl_mess(pTHX_ const char *pat, ...)
1517 va_start(args, pat);
1518 retval = vmess(pat, &args);
1524 Perl_vmess(pTHX_ const char *pat, va_list *args)
1526 SV *sv = mess_alloc();
1527 static char dgd[] = " during global destruction.\n";
1529 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1530 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1531 if (CopLINE(PL_curcop))
1532 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1533 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
1534 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1535 bool line_mode = (RsSIMPLE(PL_rs) &&
1536 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1537 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1538 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1539 line_mode ? "line" : "chunk",
1540 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1544 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1546 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1552 Perl_vdie(pTHX_ const char* pat, va_list *args)
1555 int was_in_eval = PL_in_eval;
1562 DEBUG_S(PerlIO_printf(Perl_debug_log,
1563 "%p: die: curstack = %p, mainstack = %p\n",
1564 thr, PL_curstack, PL_mainstack));
1567 msv = vmess(pat, args);
1568 if (PL_errors && SvCUR(PL_errors)) {
1569 sv_catsv(PL_errors, msv);
1570 message = SvPV(PL_errors, msglen);
1571 SvCUR_set(PL_errors, 0);
1574 message = SvPV(msv,msglen);
1581 DEBUG_S(PerlIO_printf(Perl_debug_log,
1582 "%p: die: message = %s\ndiehook = %p\n",
1583 thr, message, PL_diehook));
1585 /* sv_2cv might call Perl_croak() */
1586 SV *olddiehook = PL_diehook;
1588 SAVESPTR(PL_diehook);
1589 PL_diehook = Nullsv;
1590 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1592 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1599 msg = newSVpvn(message, msglen);
1607 PUSHSTACKi(PERLSI_DIEHOOK);
1611 call_sv((SV*)cv, G_DISCARD);
1617 PL_restartop = die_where(message, msglen);
1618 DEBUG_S(PerlIO_printf(Perl_debug_log,
1619 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1620 thr, PL_restartop, was_in_eval, PL_top_env));
1621 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1623 return PL_restartop;
1626 #if defined(PERL_IMPLICIT_CONTEXT)
1628 Perl_die_nocontext(const char* pat, ...)
1633 va_start(args, pat);
1634 o = vdie(pat, &args);
1638 #endif /* PERL_IMPLICIT_CONTEXT */
1641 Perl_die(pTHX_ const char* pat, ...)
1645 va_start(args, pat);
1646 o = vdie(pat, &args);
1652 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1662 msv = vmess(pat, args);
1663 if (PL_errors && SvCUR(PL_errors)) {
1664 sv_catsv(PL_errors, msv);
1665 message = SvPV(PL_errors, msglen);
1666 SvCUR_set(PL_errors, 0);
1669 message = SvPV(msv,msglen);
1676 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1677 PTR2UV(thr), message));
1680 /* sv_2cv might call Perl_croak() */
1681 SV *olddiehook = PL_diehook;
1683 SAVESPTR(PL_diehook);
1684 PL_diehook = Nullsv;
1685 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1687 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1694 msg = newSVpvn(message, msglen);
1702 PUSHSTACKi(PERLSI_DIEHOOK);
1706 call_sv((SV*)cv, G_DISCARD);
1712 PL_restartop = die_where(message, msglen);
1717 /* SFIO can really mess with your errno */
1720 PerlIO *serr = Perl_error_log;
1722 PerlIO_write(serr, message, msglen);
1723 (void)PerlIO_flush(serr);
1731 #if defined(PERL_IMPLICIT_CONTEXT)
1733 Perl_croak_nocontext(const char *pat, ...)
1737 va_start(args, pat);
1742 #endif /* PERL_IMPLICIT_CONTEXT */
1747 This is the XSUB-writer's interface to Perl's C<die> function.
1748 Normally use this function the same way you use the C C<printf>
1749 function. See C<warn>.
1751 If you want to throw an exception object, assign the object to
1752 C<$@> and then pass C<Nullch> to croak():
1754 errsv = get_sv("@", TRUE);
1755 sv_setsv(errsv, exception_object);
1762 Perl_croak(pTHX_ const char *pat, ...)
1765 va_start(args, pat);
1772 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1781 msv = vmess(pat, args);
1782 message = SvPV(msv, msglen);
1785 /* sv_2cv might call Perl_warn() */
1786 SV *oldwarnhook = PL_warnhook;
1788 SAVESPTR(PL_warnhook);
1789 PL_warnhook = Nullsv;
1790 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1792 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1798 msg = newSVpvn(message, msglen);
1802 PUSHSTACKi(PERLSI_WARNHOOK);
1806 call_sv((SV*)cv, G_DISCARD);
1813 PerlIO *serr = Perl_error_log;
1815 PerlIO_write(serr, message, msglen);
1817 DEBUG_L(*message == '!'
1818 ? (xstat(message[1]=='!'
1819 ? (message[2]=='!' ? 2 : 1)
1824 (void)PerlIO_flush(serr);
1828 #if defined(PERL_IMPLICIT_CONTEXT)
1830 Perl_warn_nocontext(const char *pat, ...)
1834 va_start(args, pat);
1838 #endif /* PERL_IMPLICIT_CONTEXT */
1843 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1844 function the same way you use the C C<printf> function. See
1851 Perl_warn(pTHX_ const char *pat, ...)
1854 va_start(args, pat);
1859 #if defined(PERL_IMPLICIT_CONTEXT)
1861 Perl_warner_nocontext(U32 err, const char *pat, ...)
1865 va_start(args, pat);
1866 vwarner(err, pat, &args);
1869 #endif /* PERL_IMPLICIT_CONTEXT */
1872 Perl_warner(pTHX_ U32 err, const char* pat,...)
1875 va_start(args, pat);
1876 vwarner(err, pat, &args);
1881 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() */
1939 SV *oldwarnhook = PL_warnhook;
1941 SAVESPTR(PL_warnhook);
1942 PL_warnhook = Nullsv;
1943 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1945 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1951 msg = newSVpvn(message, msglen);
1955 PUSHSTACKi(PERLSI_WARNHOOK);
1959 call_sv((SV*)cv, G_DISCARD);
1966 PerlIO *serr = Perl_error_log;
1967 PerlIO_write(serr, message, msglen);
1969 DEBUG_L(*message == '!'
1970 ? (xstat(message[1]=='!'
1971 ? (message[2]=='!' ? 2 : 1)
1976 (void)PerlIO_flush(serr);
1981 #ifdef USE_ENVIRON_ARRAY
1982 /* VMS' and EPOC's my_setenv() is in vms.c and epoc.c */
1985 Perl_my_setenv(pTHX_ char *nam, char *val)
1987 #ifndef PERL_USE_SAFE_PUTENV
1988 /* most putenv()s leak, so we manipulate environ directly */
1989 register I32 i=setenv_getix(nam); /* where does it go? */
1991 if (environ == PL_origenviron) { /* need we copy environment? */
1997 for (max = i; environ[max]; max++) ;
1998 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1999 for (j=0; j<max; j++) { /* copy environment */
2000 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
2001 strcpy(tmpenv[j], environ[j]);
2003 tmpenv[max] = Nullch;
2004 environ = tmpenv; /* tell exec where it is now */
2007 safesysfree(environ[i]);
2008 while (environ[i]) {
2009 environ[i] = environ[i+1];
2014 if (!environ[i]) { /* does not exist yet */
2015 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2016 environ[i+1] = Nullch; /* make sure it's null terminated */
2019 safesysfree(environ[i]);
2020 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
2022 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
2024 #else /* PERL_USE_SAFE_PUTENV */
2025 # if defined(__CYGWIN__)
2026 setenv(nam, val, 1);
2030 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
2031 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
2032 (void)putenv(new_env);
2033 # endif /* __CYGWIN__ */
2034 #endif /* PERL_USE_SAFE_PUTENV */
2040 Perl_my_setenv(pTHX_ char *nam,char *val)
2042 register char *envstr;
2043 STRLEN len = strlen(nam) + 3;
2048 New(904, envstr, len, char);
2049 (void)sprintf(envstr,"%s=%s",nam,val);
2050 (void)PerlEnv_putenv(envstr);
2057 Perl_setenv_getix(pTHX_ char *nam)
2059 register I32 i, len = strlen(nam);
2061 for (i = 0; environ[i]; i++) {
2064 strnicmp(environ[i],nam,len) == 0
2066 strnEQ(environ[i],nam,len)
2068 && environ[i][len] == '=')
2069 break; /* strnEQ must come first to avoid */
2070 } /* potential SEGV's */
2074 #endif /* !VMS && !EPOC*/
2076 #ifdef UNLINK_ALL_VERSIONS
2078 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2082 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2087 /* this is a drop-in replacement for bcopy() */
2088 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2090 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2094 if (from - to >= 0) {
2102 *(--to) = *(--from);
2108 /* this is a drop-in replacement for memset() */
2111 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2121 /* this is a drop-in replacement for bzero() */
2122 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2124 Perl_my_bzero(register char *loc, register I32 len)
2134 /* this is a drop-in replacement for memcmp() */
2135 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2137 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2139 register U8 *a = (U8 *)s1;
2140 register U8 *b = (U8 *)s2;
2144 if (tmp = *a++ - *b++)
2149 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2153 #ifdef USE_CHAR_VSPRINTF
2158 vsprintf(char *dest, const char *pat, char *args)
2162 fakebuf._ptr = dest;
2163 fakebuf._cnt = 32767;
2167 fakebuf._flag = _IOWRT|_IOSTRG;
2168 _doprnt(pat, args, &fakebuf); /* what a kludge */
2169 (void)putc('\0', &fakebuf);
2170 #ifdef USE_CHAR_VSPRINTF
2173 return 0; /* perl doesn't use return value */
2177 #endif /* HAS_VPRINTF */
2180 #if BYTEORDER != 0x4321
2182 Perl_my_swap(pTHX_ short s)
2184 #if (BYTEORDER & 1) == 0
2187 result = ((s & 255) << 8) + ((s >> 8) & 255);
2195 Perl_my_htonl(pTHX_ long l)
2199 char c[sizeof(long)];
2202 #if BYTEORDER == 0x1234
2203 u.c[0] = (l >> 24) & 255;
2204 u.c[1] = (l >> 16) & 255;
2205 u.c[2] = (l >> 8) & 255;
2209 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2210 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2215 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2216 u.c[o & 0xf] = (l >> s) & 255;
2224 Perl_my_ntohl(pTHX_ long l)
2228 char c[sizeof(long)];
2231 #if BYTEORDER == 0x1234
2232 u.c[0] = (l >> 24) & 255;
2233 u.c[1] = (l >> 16) & 255;
2234 u.c[2] = (l >> 8) & 255;
2238 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2239 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2246 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2247 l |= (u.c[o & 0xf] & 255) << s;
2254 #endif /* BYTEORDER != 0x4321 */
2258 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2259 * If these functions are defined,
2260 * the BYTEORDER is neither 0x1234 nor 0x4321.
2261 * However, this is not assumed.
2265 #define HTOV(name,type) \
2267 name (register type n) \
2271 char c[sizeof(type)]; \
2275 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2276 u.c[i] = (n >> s) & 0xFF; \
2281 #define VTOH(name,type) \
2283 name (register type n) \
2287 char c[sizeof(type)]; \
2293 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2294 n += (u.c[i] & 0xFF) << s; \
2299 #if defined(HAS_HTOVS) && !defined(htovs)
2302 #if defined(HAS_HTOVL) && !defined(htovl)
2305 #if defined(HAS_VTOHS) && !defined(vtohs)
2308 #if defined(HAS_VTOHL) && !defined(vtohl)
2313 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2315 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2317 register I32 This, that;
2323 PERL_FLUSHALL_FOR_CHILD;
2324 This = (*mode == 'w');
2328 taint_proper("Insecure %s%s", "EXEC");
2330 if (PerlProc_pipe(p) < 0)
2332 /* Try for another pipe pair for error return */
2333 if (PerlProc_pipe(pp) >= 0)
2335 while ((pid = vfork()) < 0) {
2336 if (errno != EAGAIN) {
2337 PerlLIO_close(p[This]);
2339 PerlLIO_close(pp[0]);
2340 PerlLIO_close(pp[1]);
2352 /* Close parent's end of _the_ pipe */
2353 PerlLIO_close(p[THAT]);
2354 /* Close parent's end of error status pipe (if any) */
2356 PerlLIO_close(pp[0]);
2357 #if defined(HAS_FCNTL) && defined(F_SETFD)
2358 /* Close error pipe automatically if exec works */
2359 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2362 /* Now dup our end of _the_ pipe to right position */
2363 if (p[THIS] != (*mode == 'r')) {
2364 PerlLIO_dup2(p[THIS], *mode == 'r');
2365 PerlLIO_close(p[THIS]);
2367 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2368 /* No automatic close - do it by hand */
2375 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2381 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2387 do_execfree(); /* free any memory malloced by child on vfork */
2388 /* Close child's end of pipe */
2389 PerlLIO_close(p[that]);
2391 PerlLIO_close(pp[1]);
2392 /* Keep the lower of the two fd numbers */
2393 if (p[that] < p[This]) {
2394 PerlLIO_dup2(p[This], p[that]);
2395 PerlLIO_close(p[This]);
2399 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2401 (void)SvUPGRADE(sv,SVt_IV);
2403 PL_forkprocess = pid;
2404 /* If we managed to get status pipe check for exec fail */
2405 if (did_pipes && pid > 0) {
2409 while (n < sizeof(int)) {
2410 n1 = PerlLIO_read(pp[0],
2411 (void*)(((char*)&errkid)+n),
2417 PerlLIO_close(pp[0]);
2419 if (n) { /* Error */
2421 if (n != sizeof(int))
2422 Perl_croak(aTHX_ "panic: kid popen errno read");
2424 pid2 = wait4pid(pid, &status, 0);
2425 } while (pid2 == -1 && errno == EINTR);
2426 errno = errkid; /* Propagate errno from kid */
2431 PerlLIO_close(pp[0]);
2432 return PerlIO_fdopen(p[This], mode);
2434 Perl_croak(aTHX_ "List form of piped open not implemented");
2435 return (PerlIO *) NULL;
2439 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2440 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2442 Perl_my_popen(pTHX_ char *cmd, char *mode)
2445 register I32 This, that;
2448 I32 doexec = strNE(cmd,"-");
2452 PERL_FLUSHALL_FOR_CHILD;
2455 return my_syspopen(aTHX_ cmd,mode);
2458 This = (*mode == 'w');
2460 if (doexec && PL_tainting) {
2462 taint_proper("Insecure %s%s", "EXEC");
2464 if (PerlProc_pipe(p) < 0)
2466 if (doexec && PerlProc_pipe(pp) >= 0)
2468 while ((pid = (doexec?vfork():fork())) < 0) {
2469 if (errno != EAGAIN) {
2470 PerlLIO_close(p[This]);
2472 PerlLIO_close(pp[0]);
2473 PerlLIO_close(pp[1]);
2476 Perl_croak(aTHX_ "Can't fork");
2488 PerlLIO_close(p[THAT]);
2490 PerlLIO_close(pp[0]);
2491 #if defined(HAS_FCNTL) && defined(F_SETFD)
2492 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2495 if (p[THIS] != (*mode == 'r')) {
2496 PerlLIO_dup2(p[THIS], *mode == 'r');
2497 PerlLIO_close(p[THIS]);
2501 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2510 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2515 /* may or may not use the shell */
2516 do_exec3(cmd, pp[1], did_pipes);
2519 #endif /* defined OS2 */
2521 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV)))
2522 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2524 hv_clear(PL_pidstatus); /* we have no children */
2529 do_execfree(); /* free any memory malloced by child on vfork */
2530 PerlLIO_close(p[that]);
2532 PerlLIO_close(pp[1]);
2533 if (p[that] < p[This]) {
2534 PerlLIO_dup2(p[This], p[that]);
2535 PerlLIO_close(p[This]);
2539 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2541 (void)SvUPGRADE(sv,SVt_IV);
2543 PL_forkprocess = pid;
2544 if (did_pipes && pid > 0) {
2548 while (n < sizeof(int)) {
2549 n1 = PerlLIO_read(pp[0],
2550 (void*)(((char*)&errkid)+n),
2556 PerlLIO_close(pp[0]);
2558 if (n) { /* Error */
2560 if (n != sizeof(int))
2561 Perl_croak(aTHX_ "panic: kid popen errno read");
2563 pid2 = wait4pid(pid, &status, 0);
2564 } while (pid2 == -1 && errno == EINTR);
2565 errno = errkid; /* Propagate errno from kid */
2570 PerlLIO_close(pp[0]);
2571 return PerlIO_fdopen(p[This], mode);
2574 #if defined(atarist) || defined(DJGPP)
2577 Perl_my_popen(pTHX_ char *cmd, char *mode)
2579 PERL_FLUSHALL_FOR_CHILD;
2580 /* Call system's popen() to get a FILE *, then import it.
2581 used 0 for 2nd parameter to PerlIO_importFILE;
2584 return PerlIO_importFILE(popen(cmd, mode), 0);
2588 #endif /* !DOSISH */
2592 Perl_dump_fds(pTHX_ char *s)
2595 struct stat tmpstatbuf;
2597 PerlIO_printf(Perl_debug_log,"%s", s);
2598 for (fd = 0; fd < 32; fd++) {
2599 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2600 PerlIO_printf(Perl_debug_log," %d",fd);
2602 PerlIO_printf(Perl_debug_log,"\n");
2604 #endif /* DUMP_FDS */
2608 dup2(int oldfd, int newfd)
2610 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2613 PerlLIO_close(newfd);
2614 return fcntl(oldfd, F_DUPFD, newfd);
2616 #define DUP2_MAX_FDS 256
2617 int fdtmp[DUP2_MAX_FDS];
2623 PerlLIO_close(newfd);
2624 /* good enough for low fd's... */
2625 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2626 if (fdx >= DUP2_MAX_FDS) {
2634 PerlLIO_close(fdtmp[--fdx]);
2641 #ifdef HAS_SIGACTION
2644 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2646 struct sigaction act, oact;
2648 act.sa_handler = handler;
2649 sigemptyset(&act.sa_mask);
2652 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2653 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2657 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2658 act.sa_flags |= SA_NOCLDWAIT;
2660 if (sigaction(signo, &act, &oact) == -1)
2663 return oact.sa_handler;
2667 Perl_rsignal_state(pTHX_ int signo)
2669 struct sigaction oact;
2671 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2674 return oact.sa_handler;
2678 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2680 struct sigaction act;
2682 act.sa_handler = handler;
2683 sigemptyset(&act.sa_mask);
2686 #if !defined(USE_PERLIO) || defined(PERL_OLD_SIGNALS)
2687 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2691 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2692 act.sa_flags |= SA_NOCLDWAIT;
2694 return sigaction(signo, &act, save);
2698 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2700 return sigaction(signo, save, (struct sigaction *)NULL);
2703 #else /* !HAS_SIGACTION */
2706 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2708 return PerlProc_signal(signo, handler);
2711 static int sig_trapped;
2721 Perl_rsignal_state(pTHX_ int signo)
2723 Sighandler_t oldsig;
2726 oldsig = PerlProc_signal(signo, sig_trap);
2727 PerlProc_signal(signo, oldsig);
2729 PerlProc_kill(PerlProc_getpid(), signo);
2734 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2736 *save = PerlProc_signal(signo, handler);
2737 return (*save == SIG_ERR) ? -1 : 0;
2741 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2743 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2746 #endif /* !HAS_SIGACTION */
2747 #endif /* !PERL_MICRO */
2749 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2750 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2752 Perl_my_pclose(pTHX_ PerlIO *ptr)
2754 Sigsave_t hstat, istat, qstat;
2760 int saved_errno = 0;
2762 int saved_vaxc_errno;
2765 int saved_win32_errno;
2769 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2771 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2773 *svp = &PL_sv_undef;
2775 if (pid == -1) { /* Opened by popen. */
2776 return my_syspclose(ptr);
2779 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2780 saved_errno = errno;
2782 saved_vaxc_errno = vaxc$errno;
2785 saved_win32_errno = GetLastError();
2789 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2792 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2793 rsignal_save(SIGINT, SIG_IGN, &istat);
2794 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2797 pid2 = wait4pid(pid, &status, 0);
2798 } while (pid2 == -1 && errno == EINTR);
2800 rsignal_restore(SIGHUP, &hstat);
2801 rsignal_restore(SIGINT, &istat);
2802 rsignal_restore(SIGQUIT, &qstat);
2805 SETERRNO(saved_errno, saved_vaxc_errno);
2808 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2810 #endif /* !DOSISH */
2812 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2814 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2818 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2822 char spid[TYPE_CHARS(int)];
2825 sprintf(spid, "%"IVdf, (IV)pid);
2826 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2827 if (svp && *svp != &PL_sv_undef) {
2828 *statusp = SvIVX(*svp);
2829 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2836 hv_iterinit(PL_pidstatus);
2837 if ((entry = hv_iternext(PL_pidstatus))) {
2838 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2839 sv = hv_iterval(PL_pidstatus,entry);
2840 *statusp = SvIVX(sv);
2841 sprintf(spid, "%"IVdf, (IV)pid);
2842 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2849 # ifdef HAS_WAITPID_RUNTIME
2850 if (!HAS_WAITPID_RUNTIME)
2853 return PerlProc_waitpid(pid,statusp,flags);
2855 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2856 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2858 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2863 Perl_croak(aTHX_ "Can't do waitpid with flags");
2865 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2866 pidgone(result,*statusp);
2874 #endif /* !DOSISH || OS2 || WIN32 */
2878 Perl_pidgone(pTHX_ Pid_t pid, int status)
2881 char spid[TYPE_CHARS(int)];
2883 sprintf(spid, "%"IVdf, (IV)pid);
2884 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2885 (void)SvUPGRADE(sv,SVt_IV);
2890 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2893 int /* Cannot prototype with I32
2895 my_syspclose(PerlIO *ptr)
2898 Perl_my_pclose(pTHX_ PerlIO *ptr)
2901 /* Needs work for PerlIO ! */
2902 FILE *f = PerlIO_findFILE(ptr);
2903 I32 result = pclose(f);
2905 result = (result << 8) & 0xff00;
2907 PerlIO_releaseFILE(ptr,f);
2913 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2916 register const char *frombase = from;
2919 register const char c = *from;
2924 while (count-- > 0) {
2925 for (todo = len; todo > 0; todo--) {
2933 Perl_cast_ulong(pTHX_ NV f)
2936 return f < I32_MIN ? (U32) I32_MIN : (U32)(I32) f;
2937 if (f < U32_MAX_P1) {
2939 if (f < U32_MAX_P1_HALF)
2941 f -= U32_MAX_P1_HALF;
2942 return ((U32) f) | (1 + U32_MAX >> 1);
2947 return f > 0 ? U32_MAX : 0 /* NaN */;
2951 Perl_cast_i32(pTHX_ NV f)
2954 return f < I32_MIN ? I32_MIN : (I32) f;
2955 if (f < U32_MAX_P1) {
2957 if (f < U32_MAX_P1_HALF)
2958 return (I32)(U32) f;
2959 f -= U32_MAX_P1_HALF;
2960 return (I32)(((U32) f) | (1 + U32_MAX >> 1));
2962 return (I32)(U32) f;
2965 return f > 0 ? (I32)U32_MAX : 0 /* NaN */;
2969 Perl_cast_iv(pTHX_ NV f)
2972 return f < IV_MIN ? IV_MIN : (IV) f;
2973 if (f < UV_MAX_P1) {
2975 /* For future flexibility allowing for sizeof(UV) >= sizeof(IV) */
2976 if (f < UV_MAX_P1_HALF)
2978 f -= UV_MAX_P1_HALF;
2979 return (IV)(((UV) f) | (1 + UV_MAX >> 1));
2984 return f > 0 ? (IV)UV_MAX : 0 /* NaN */;
2988 Perl_cast_uv(pTHX_ NV f)
2991 return f < IV_MIN ? (UV) IV_MIN : (UV)(IV) f;
2992 if (f < UV_MAX_P1) {
2994 if (f < UV_MAX_P1_HALF)
2996 f -= UV_MAX_P1_HALF;
2997 return ((UV) f) | (1 + UV_MAX >> 1);
3002 return f > 0 ? UV_MAX : 0 /* NaN */;
3007 Perl_same_dirent(pTHX_ char *a, char *b)
3009 char *fa = strrchr(a,'/');
3010 char *fb = strrchr(b,'/');
3011 struct stat tmpstatbuf1;
3012 struct stat tmpstatbuf2;
3013 SV *tmpsv = sv_newmortal();
3026 sv_setpv(tmpsv, ".");
3028 sv_setpvn(tmpsv, a, fa - a);
3029 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
3032 sv_setpv(tmpsv, ".");
3034 sv_setpvn(tmpsv, b, fb - b);
3035 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
3037 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3038 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3040 #endif /* !HAS_RENAME */
3043 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3045 register char *s = start;
3046 register NV rnv = 0.0;
3047 register UV ruv = 0;
3048 register bool seenb = FALSE;
3049 register bool overflowed = FALSE;
3051 for (; len-- && *s; s++) {
3052 if (!(*s == '0' || *s == '1')) {
3053 if (*s == '_' && len && *retlen
3054 && (s[1] == '0' || s[1] == '1'))
3059 else if (seenb == FALSE && *s == 'b' && ruv == 0) {
3060 /* Disallow 0bbb0b0bbb... */
3065 if (ckWARN(WARN_DIGIT))
3066 Perl_warner(aTHX_ WARN_DIGIT,
3067 "Illegal binary digit '%c' ignored", *s);
3072 register UV xuv = ruv << 1;
3074 if ((xuv >> 1) != ruv) {
3077 if (ckWARN_d(WARN_OVERFLOW))
3078 Perl_warner(aTHX_ WARN_OVERFLOW,
3079 "Integer overflow in binary number");
3082 ruv = xuv | (*s - '0');
3086 /* If an NV has not enough bits in its mantissa to
3087 * represent an UV this summing of small low-order numbers
3088 * is a waste of time (because the NV cannot preserve
3089 * the low-order bits anyway): we could just remember when
3090 * did we overflow and in the end just multiply rnv by the
3097 if ( ( overflowed && rnv > 4294967295.0)
3099 || (!overflowed && ruv > 0xffffffff )
3102 if (ckWARN(WARN_PORTABLE))
3103 Perl_warner(aTHX_ WARN_PORTABLE,
3104 "Binary number > 0b11111111111111111111111111111111 non-portable");
3106 *retlen = s - start;
3111 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3113 register char *s = start;
3114 register NV rnv = 0.0;
3115 register UV ruv = 0;
3116 register bool overflowed = FALSE;
3118 for (; len-- && *s; s++) {
3119 if (!(*s >= '0' && *s <= '7')) {
3120 if (*s == '_' && len && *retlen
3121 && (s[1] >= '0' && s[1] <= '7'))
3127 /* Allow \octal to work the DWIM way (that is, stop scanning
3128 * as soon as non-octal characters are seen, complain only iff
3129 * someone seems to want to use the digits eight and nine). */
3130 if (*s == '8' || *s == '9') {
3131 if (ckWARN(WARN_DIGIT))
3132 Perl_warner(aTHX_ WARN_DIGIT,
3133 "Illegal octal digit '%c' ignored", *s);
3139 register UV xuv = ruv << 3;
3141 if ((xuv >> 3) != ruv) {
3144 if (ckWARN_d(WARN_OVERFLOW))
3145 Perl_warner(aTHX_ WARN_OVERFLOW,
3146 "Integer overflow in octal number");
3149 ruv = xuv | (*s - '0');
3153 /* If an NV has not enough bits in its mantissa to
3154 * represent an UV this summing of small low-order numbers
3155 * is a waste of time (because the NV cannot preserve
3156 * the low-order bits anyway): we could just remember when
3157 * did we overflow and in the end just multiply rnv by the
3158 * right amount of 8-tuples. */
3159 rnv += (NV)(*s - '0');
3164 if ( ( overflowed && rnv > 4294967295.0)
3166 || (!overflowed && ruv > 0xffffffff )
3169 if (ckWARN(WARN_PORTABLE))
3170 Perl_warner(aTHX_ WARN_PORTABLE,
3171 "Octal number > 037777777777 non-portable");
3173 *retlen = s - start;
3178 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
3180 register char *s = start;
3181 register NV rnv = 0.0;
3182 register UV ruv = 0;
3183 register bool overflowed = FALSE;
3191 else if (len > 3 && s[0] == '0' && s[1] == 'x') {
3197 for (; len-- && *s; s++) {
3198 hexdigit = strchr((char *) PL_hexdigit, *s);
3200 if (*s == '_' && len && *retlen && s[1]
3201 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
3207 if (ckWARN(WARN_DIGIT))
3208 Perl_warner(aTHX_ WARN_DIGIT,
3209 "Illegal hexadecimal digit '%c' ignored", *s);
3214 register UV xuv = ruv << 4;
3216 if ((xuv >> 4) != ruv) {
3219 if (ckWARN_d(WARN_OVERFLOW))
3220 Perl_warner(aTHX_ WARN_OVERFLOW,
3221 "Integer overflow in hexadecimal number");
3224 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
3228 /* If an NV has not enough bits in its mantissa to
3229 * represent an UV this summing of small low-order numbers
3230 * is a waste of time (because the NV cannot preserve
3231 * the low-order bits anyway): we could just remember when
3232 * did we overflow and in the end just multiply rnv by the
3233 * right amount of 16-tuples. */
3234 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
3239 if ( ( overflowed && rnv > 4294967295.0)
3241 || (!overflowed && ruv > 0xffffffff )
3244 if (ckWARN(WARN_PORTABLE))
3245 Perl_warner(aTHX_ WARN_PORTABLE,
3246 "Hexadecimal number > 0xffffffff non-portable");
3248 *retlen = s - start;
3253 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
3255 char *xfound = Nullch;
3256 char *xfailed = Nullch;
3257 char tmpbuf[MAXPATHLEN];
3261 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3262 # define SEARCH_EXTS ".bat", ".cmd", NULL
3263 # define MAX_EXT_LEN 4
3266 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3267 # define MAX_EXT_LEN 4
3270 # define SEARCH_EXTS ".pl", ".com", NULL
3271 # define MAX_EXT_LEN 4
3273 /* additional extensions to try in each dir if scriptname not found */
3275 char *exts[] = { SEARCH_EXTS };
3276 char **ext = search_ext ? search_ext : exts;
3277 int extidx = 0, i = 0;
3278 char *curext = Nullch;
3280 # define MAX_EXT_LEN 0
3284 * If dosearch is true and if scriptname does not contain path
3285 * delimiters, search the PATH for scriptname.
3287 * If SEARCH_EXTS is also defined, will look for each
3288 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3289 * while searching the PATH.
3291 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3292 * proceeds as follows:
3293 * If DOSISH or VMSISH:
3294 * + look for ./scriptname{,.foo,.bar}
3295 * + search the PATH for scriptname{,.foo,.bar}
3298 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3299 * this will not look in '.' if it's not in the PATH)
3304 # ifdef ALWAYS_DEFTYPES
3305 len = strlen(scriptname);
3306 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3307 int hasdir, idx = 0, deftypes = 1;
3310 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3313 int hasdir, idx = 0, deftypes = 1;
3316 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3318 /* The first time through, just add SEARCH_EXTS to whatever we
3319 * already have, so we can check for default file types. */
3321 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3327 if ((strlen(tmpbuf) + strlen(scriptname)
3328 + MAX_EXT_LEN) >= sizeof tmpbuf)
3329 continue; /* don't search dir with too-long name */
3330 strcat(tmpbuf, scriptname);
3334 if (strEQ(scriptname, "-"))
3336 if (dosearch) { /* Look in '.' first. */
3337 char *cur = scriptname;
3339 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3341 if (strEQ(ext[i++],curext)) {
3342 extidx = -1; /* already has an ext */
3347 DEBUG_p(PerlIO_printf(Perl_debug_log,
3348 "Looking for %s\n",cur));
3349 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3350 && !S_ISDIR(PL_statbuf.st_mode)) {
3358 if (cur == scriptname) {
3359 len = strlen(scriptname);
3360 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3362 cur = strcpy(tmpbuf, scriptname);
3364 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3365 && strcpy(tmpbuf+len, ext[extidx++]));
3370 #ifdef MACOS_TRADITIONAL
3371 if (dosearch && !strchr(scriptname, ':') &&
3372 (s = PerlEnv_getenv("Commands")))
3374 if (dosearch && !strchr(scriptname, '/')
3376 && !strchr(scriptname, '\\')
3378 && (s = PerlEnv_getenv("PATH")))
3383 PL_bufend = s + strlen(s);
3384 while (s < PL_bufend) {
3385 #ifdef MACOS_TRADITIONAL
3386 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3390 #if defined(atarist) || defined(DOSISH)
3395 && *s != ';'; len++, s++) {
3396 if (len < sizeof tmpbuf)
3399 if (len < sizeof tmpbuf)
3401 #else /* ! (atarist || DOSISH) */
3402 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3405 #endif /* ! (atarist || DOSISH) */
3406 #endif /* MACOS_TRADITIONAL */
3409 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3410 continue; /* don't search dir with too-long name */
3411 #ifdef MACOS_TRADITIONAL
3412 if (len && tmpbuf[len - 1] != ':')
3413 tmpbuf[len++] = ':';
3416 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3417 && tmpbuf[len - 1] != '/'
3418 && tmpbuf[len - 1] != '\\'
3421 tmpbuf[len++] = '/';
3422 if (len == 2 && tmpbuf[0] == '.')
3425 (void)strcpy(tmpbuf + len, scriptname);
3429 len = strlen(tmpbuf);
3430 if (extidx > 0) /* reset after previous loop */
3434 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3435 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3436 if (S_ISDIR(PL_statbuf.st_mode)) {
3440 } while ( retval < 0 /* not there */
3441 && extidx>=0 && ext[extidx] /* try an extension? */
3442 && strcpy(tmpbuf+len, ext[extidx++])
3447 if (S_ISREG(PL_statbuf.st_mode)
3448 && cando(S_IRUSR,TRUE,&PL_statbuf)
3449 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3450 && cando(S_IXUSR,TRUE,&PL_statbuf)
3454 xfound = tmpbuf; /* bingo! */
3458 xfailed = savepv(tmpbuf);
3461 if (!xfound && !seen_dot && !xfailed &&
3462 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3463 || S_ISDIR(PL_statbuf.st_mode)))
3465 seen_dot = 1; /* Disable message. */
3467 if (flags & 1) { /* do or die? */
3468 Perl_croak(aTHX_ "Can't %s %s%s%s",
3469 (xfailed ? "execute" : "find"),
3470 (xfailed ? xfailed : scriptname),
3471 (xfailed ? "" : " on PATH"),
3472 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3474 scriptname = Nullch;
3478 scriptname = xfound;
3480 return (scriptname ? savepv(scriptname) : Nullch);
3483 #ifndef PERL_GET_CONTEXT_DEFINED
3486 Perl_get_context(void)
3488 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3489 # ifdef OLD_PTHREADS_API
3491 if (pthread_getspecific(PL_thr_key, &t))
3492 Perl_croak_nocontext("panic: pthread_getspecific");
3495 # ifdef I_MACH_CTHREADS
3496 return (void*)cthread_data(cthread_self());
3498 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3507 Perl_set_context(void *t)
3509 #if defined(USE_THREADS) || defined(USE_ITHREADS)
3510 # ifdef I_MACH_CTHREADS
3511 cthread_set_data(cthread_self(), t);
3513 if (pthread_setspecific(PL_thr_key, t))
3514 Perl_croak_nocontext("panic: pthread_setspecific");
3519 #endif /* !PERL_GET_CONTEXT_DEFINED */
3524 /* Very simplistic scheduler for now */
3528 thr = thr->i.next_run;
3532 Perl_cond_init(pTHX_ perl_cond *cp)
3538 Perl_cond_signal(pTHX_ perl_cond *cp)
3541 perl_cond cond = *cp;
3546 /* Insert t in the runnable queue just ahead of us */
3547 t->i.next_run = thr->i.next_run;
3548 thr->i.next_run->i.prev_run = t;
3549 t->i.prev_run = thr;
3550 thr->i.next_run = t;
3551 thr->i.wait_queue = 0;
3552 /* Remove from the wait queue */
3558 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3561 perl_cond cond, cond_next;
3563 for (cond = *cp; cond; cond = cond_next) {
3565 /* Insert t in the runnable queue just ahead of us */
3566 t->i.next_run = thr->i.next_run;
3567 thr->i.next_run->i.prev_run = t;
3568 t->i.prev_run = thr;
3569 thr->i.next_run = t;
3570 thr->i.wait_queue = 0;
3571 /* Remove from the wait queue */
3572 cond_next = cond->next;
3579 Perl_cond_wait(pTHX_ perl_cond *cp)
3583 if (thr->i.next_run == thr)
3584 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3586 New(666, cond, 1, struct perl_wait_queue);
3590 thr->i.wait_queue = cond;
3591 /* Remove ourselves from runnable queue */
3592 thr->i.next_run->i.prev_run = thr->i.prev_run;
3593 thr->i.prev_run->i.next_run = thr->i.next_run;
3595 #endif /* FAKE_THREADS */
3598 Perl_condpair_magic(pTHX_ SV *sv)
3602 SvUPGRADE(sv, SVt_PVMG);
3603 mg = mg_find(sv, PERL_MAGIC_mutex);
3607 New(53, cp, 1, condpair_t);
3608 MUTEX_INIT(&cp->mutex);
3609 COND_INIT(&cp->owner_cond);
3610 COND_INIT(&cp->cond);
3612 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3613 mg = mg_find(sv, PERL_MAGIC_mutex);
3615 /* someone else beat us to initialising it */
3616 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3617 MUTEX_DESTROY(&cp->mutex);
3618 COND_DESTROY(&cp->owner_cond);
3619 COND_DESTROY(&cp->cond);
3623 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3625 mg->mg_ptr = (char *)cp;
3626 mg->mg_len = sizeof(cp);
3627 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3628 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3629 "%p: condpair_magic %p\n", thr, sv));)
3636 Perl_sv_lock(pTHX_ SV *osv)
3646 mg = condpair_magic(sv);
3647 MUTEX_LOCK(MgMUTEXP(mg));
3648 if (MgOWNER(mg) == thr)
3649 MUTEX_UNLOCK(MgMUTEXP(mg));
3652 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3654 DEBUG_S(PerlIO_printf(Perl_debug_log,
3655 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3656 PTR2UV(thr), PTR2UV(sv));)
3657 MUTEX_UNLOCK(MgMUTEXP(mg));
3658 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3660 UNLOCK_SV_LOCK_MUTEX;
3665 * Make a new perl thread structure using t as a prototype. Some of the
3666 * fields for the new thread are copied from the prototype thread, t,
3667 * so t should not be running in perl at the time this function is
3668 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3669 * thread calling new_struct_thread) clearly satisfies this constraint.
3671 struct perl_thread *
3672 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3674 #if !defined(PERL_IMPLICIT_CONTEXT)
3675 struct perl_thread *thr;
3681 sv = newSVpvn("", 0);
3682 SvGROW(sv, sizeof(struct perl_thread) + 1);
3683 SvCUR_set(sv, sizeof(struct perl_thread));
3684 thr = (Thread) SvPVX(sv);
3686 memset(thr, 0xab, sizeof(struct perl_thread));
3693 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3694 PL_efloatbuf = (char*)NULL;
3697 Zero(thr, 1, struct perl_thread);
3703 PL_curcop = &PL_compiling;
3704 thr->interp = t->interp;
3705 thr->cvcache = newHV();
3706 thr->threadsv = newAV();
3707 thr->specific = newAV();
3708 thr->errsv = newSVpvn("", 0);
3709 thr->flags = THRf_R_JOINABLE;
3711 MUTEX_INIT(&thr->mutex);
3715 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3718 PL_statname = NEWSV(66,0);
3719 PL_errors = newSVpvn("", 0);
3721 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3722 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3723 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3724 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3725 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3727 PL_reginterp_cnt = 0;
3728 PL_lastscream = Nullsv;
3731 PL_reg_start_tmp = 0;
3732 PL_reg_start_tmpl = 0;
3733 PL_reg_poscache = Nullch;
3735 /* parent thread's data needs to be locked while we make copy */
3736 MUTEX_LOCK(&t->mutex);
3738 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3739 PL_protect = t->Tprotect;
3742 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3743 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3744 PL_curstash = t->Tcurstash; /* always be set to main? */
3746 PL_tainted = t->Ttainted;
3747 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3748 PL_nrs = newSVsv(t->Tnrs);
3749 PL_rs = t->Tnrs ? SvREFCNT_inc(PL_nrs) : Nullsv;
3750 PL_last_in_gv = Nullgv;
3751 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3752 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3753 PL_chopset = t->Tchopset;
3754 PL_bodytarget = newSVsv(t->Tbodytarget);
3755 PL_toptarget = newSVsv(t->Ttoptarget);
3756 if (t->Tformtarget == t->Ttoptarget)
3757 PL_formtarget = PL_toptarget;
3759 PL_formtarget = PL_bodytarget;
3761 /* Initialise all per-thread SVs that the template thread used */
3762 svp = AvARRAY(t->threadsv);
3763 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3764 if (*svp && *svp != &PL_sv_undef) {
3765 SV *sv = newSVsv(*svp);
3766 av_store(thr->threadsv, i, sv);
3767 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3768 DEBUG_S(PerlIO_printf(Perl_debug_log,
3769 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3773 thr->threadsvp = AvARRAY(thr->threadsv);
3775 MUTEX_LOCK(&PL_threads_mutex);
3777 thr->tid = ++PL_threadnum;
3778 thr->next = t->next;
3781 thr->next->prev = thr;
3782 MUTEX_UNLOCK(&PL_threads_mutex);
3784 /* done copying parent's state */
3785 MUTEX_UNLOCK(&t->mutex);
3787 #ifdef HAVE_THREAD_INTERN
3788 Perl_init_thread_intern(thr);
3789 #endif /* HAVE_THREAD_INTERN */
3792 #endif /* USE_THREADS */
3794 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
3796 * This hack is to force load of "huge" support from libm.a
3797 * So it is in perl for (say) POSIX to use.
3798 * Needed for SunOS with Sun's 'acc' for example.
3803 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
3810 #ifdef PERL_GLOBAL_STRUCT
3819 Perl_get_op_names(pTHX)
3825 Perl_get_op_descs(pTHX)
3831 Perl_get_no_modify(pTHX)
3833 return (char*)PL_no_modify;
3837 Perl_get_opargs(pTHX)
3843 Perl_get_ppaddr(pTHX)
3845 return (PPADDR_t*)PL_ppaddr;
3848 #ifndef HAS_GETENV_LEN
3850 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3852 char *env_trans = PerlEnv_getenv(env_elem);
3854 *len = strlen(env_trans);
3861 Perl_get_vtbl(pTHX_ int vtbl_id)
3863 MGVTBL* result = Null(MGVTBL*);
3867 result = &PL_vtbl_sv;
3870 result = &PL_vtbl_env;
3872 case want_vtbl_envelem:
3873 result = &PL_vtbl_envelem;
3876 result = &PL_vtbl_sig;
3878 case want_vtbl_sigelem:
3879 result = &PL_vtbl_sigelem;
3881 case want_vtbl_pack:
3882 result = &PL_vtbl_pack;
3884 case want_vtbl_packelem:
3885 result = &PL_vtbl_packelem;
3887 case want_vtbl_dbline:
3888 result = &PL_vtbl_dbline;
3891 result = &PL_vtbl_isa;
3893 case want_vtbl_isaelem:
3894 result = &PL_vtbl_isaelem;
3896 case want_vtbl_arylen:
3897 result = &PL_vtbl_arylen;
3899 case want_vtbl_glob:
3900 result = &PL_vtbl_glob;
3902 case want_vtbl_mglob:
3903 result = &PL_vtbl_mglob;
3905 case want_vtbl_nkeys:
3906 result = &PL_vtbl_nkeys;
3908 case want_vtbl_taint:
3909 result = &PL_vtbl_taint;
3911 case want_vtbl_substr:
3912 result = &PL_vtbl_substr;
3915 result = &PL_vtbl_vec;
3918 result = &PL_vtbl_pos;
3921 result = &PL_vtbl_bm;
3924 result = &PL_vtbl_fm;
3926 case want_vtbl_uvar:
3927 result = &PL_vtbl_uvar;
3930 case want_vtbl_mutex:
3931 result = &PL_vtbl_mutex;
3934 case want_vtbl_defelem:
3935 result = &PL_vtbl_defelem;
3937 case want_vtbl_regexp:
3938 result = &PL_vtbl_regexp;
3940 case want_vtbl_regdata:
3941 result = &PL_vtbl_regdata;
3943 case want_vtbl_regdatum:
3944 result = &PL_vtbl_regdatum;
3946 #ifdef USE_LOCALE_COLLATE
3947 case want_vtbl_collxfrm:
3948 result = &PL_vtbl_collxfrm;
3951 case want_vtbl_amagic:
3952 result = &PL_vtbl_amagic;
3954 case want_vtbl_amagicelem:
3955 result = &PL_vtbl_amagicelem;
3957 case want_vtbl_backref:
3958 result = &PL_vtbl_backref;
3965 Perl_my_fflush_all(pTHX)
3967 #if defined(FFLUSH_NULL)
3968 return PerlIO_flush(NULL);
3970 # if defined(HAS__FWALK)
3971 /* undocumented, unprototyped, but very useful BSDism */
3972 extern void _fwalk(int (*)(FILE *));
3976 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3978 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3979 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3981 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3982 open_max = sysconf(_SC_OPEN_MAX);
3985 open_max = FOPEN_MAX;
3988 open_max = OPEN_MAX;
3999 for (i = 0; i < open_max; i++)
4000 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
4001 STDIO_STREAM_ARRAY[i]._file < open_max &&
4002 STDIO_STREAM_ARRAY[i]._flag)
4003 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
4007 SETERRNO(EBADF,RMS$_IFI);
4014 Perl_my_atof(pTHX_ const char* s)
4017 #ifdef USE_LOCALE_NUMERIC
4018 if (PL_numeric_local && IN_LOCALE) {
4021 Perl_atof2(aTHX_ s, &x);
4022 SET_NUMERIC_STANDARD();
4023 Perl_atof2(aTHX_ s, &y);
4024 SET_NUMERIC_LOCAL();
4025 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
4029 Perl_atof2(aTHX_ s, &x);
4031 Perl_atof2(aTHX_ s, &x);
4037 S_mulexp10(NV value, I32 exponent)
4044 for (bit = 1; exponent; bit <<= 1) {
4045 if (exponent & bit) {
4052 else if (exponent < 0) {
4053 exponent = -exponent;
4054 for (bit = 1; exponent; bit <<= 1) {
4055 if (exponent & bit) {
4066 Perl_my_atof2(pTHX_ const char* orig, NV* value)
4070 char* s = (char*)orig;
4071 char* point = "."; /* locale-dependent decimal point equivalent */
4072 STRLEN pointlen = 1;
4077 /* this is arbitrary */
4079 /* we want the largest integers we can usefully use */
4080 #if defined(HAS_QUAD) && defined(USE_64_BIT_INT)
4081 # define PARTSIZE ((int)TYPE_DIGITS(U64)-1)
4084 # define PARTSIZE ((int)TYPE_DIGITS(U32)-1)
4087 I32 ipart = 0; /* index into part[] */
4088 I32 offcount; /* number of digits in least significant part */
4090 if (PL_numeric_radix_sv)
4091 point = SvPV(PL_numeric_radix_sv, pointlen);
4102 part[0] = offcount = 0;
4104 seendigit = 1; /* get this over with */
4106 /* skip leading zeros */
4111 /* integer digits */
4112 while (isDIGIT(*s)) {
4113 if (++offcount > PARTSIZE) {
4114 if (++ipart < PARTLIM) {
4116 offcount = 1; /* ++0 */
4119 /* limits of precision reached */
4124 while (isDIGIT(*s)) {
4128 /* warn of loss of precision? */
4132 part[ipart] = part[ipart] * 10 + (*s++ - '0');
4136 if (memEQ(s, point, pointlen)) {
4139 seendigit = 1; /* get this over with */
4141 /* decimal digits */
4142 while (isDIGIT(*s)) {
4143 if (++offcount > PARTSIZE) {
4144 if (++ipart < PARTLIM) {
4146 offcount = 1; /* ++0 */
4149 /* limits of precision reached */
4156 /* warn of loss of precision? */
4161 part[ipart] = part[ipart] * 10 + (*s++ - '0');
4165 /* combine components of mantissa */
4166 for (i = 0; i <= ipart; ++i)
4167 result += S_mulexp10((NV)part[ipart - i],
4168 i ? offcount + (i - 1) * PARTSIZE : 0);
4170 if (seendigit && (*s == 'e' || *s == 'E')) {
4171 bool expnegative = 0;
4182 exponent = exponent * 10 + (*s++ - '0');
4184 exponent = -exponent;
4187 /* now apply the exponent */
4188 exponent += expextra;
4189 result = S_mulexp10(result, exponent);
4191 /* now apply the sign */
4199 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
4204 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
4205 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
4207 char *pars = OP_IS_FILETEST(op) ? "" : "()";
4208 char *type = OP_IS_SOCKET(op) ||
4209 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
4210 "socket" : "filehandle";
4213 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
4215 warn_type = WARN_CLOSED;
4219 warn_type = WARN_UNOPENED;
4222 if (gv && isGV(gv)) {
4223 SV *sv = sv_newmortal();
4224 gv_efullname4(sv, gv, Nullch, FALSE);
4228 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
4230 Perl_warner(aTHX_ WARN_IO, "Filehandle %s opened only for %sput",
4232 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
4234 Perl_warner(aTHX_ WARN_IO, "Filehandle opened only for %sput",
4235 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
4236 } else if (name && *name) {
4237 Perl_warner(aTHX_ warn_type,
4238 "%s%s on %s %s %s", func, pars, vile, type, name);
4239 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
4240 Perl_warner(aTHX_ warn_type,
4241 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
4245 Perl_warner(aTHX_ warn_type,
4246 "%s%s on %s %s", func, pars, vile, type);
4247 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
4248 Perl_warner(aTHX_ warn_type,
4249 "\t(Are you trying to call %s%s on dirhandle?)\n",
4255 /* in ASCII order, not that it matters */
4256 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
4259 Perl_ebcdic_control(pTHX_ int ch)
4267 if ((ctlp = strchr(controllablechars, ch)) == 0) {
4268 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
4271 if (ctlp == controllablechars)
4272 return('\177'); /* DEL */
4274 return((unsigned char)(ctlp - controllablechars - 1));
4275 } else { /* Want uncontrol */
4276 if (ch == '\177' || ch == -1)
4278 else if (ch == '\157')
4280 else if (ch == '\174')
4282 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
4284 else if (ch == '\155')
4286 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
4287 return(controllablechars[ch+1]);
4289 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
4294 /* XXX struct tm on some systems (SunOS4/BSD) contains extra (non POSIX)
4295 * fields for which we don't have Configure support yet:
4296 * char *tm_zone; -- abbreviation of timezone name
4297 * long tm_gmtoff; -- offset from GMT in seconds
4298 * To workaround core dumps from the uninitialised tm_zone we get the
4299 * system to give us a reasonable struct to copy. This fix means that
4300 * strftime uses the tm_zone and tm_gmtoff values returned by
4301 * localtime(time()). That should give the desired result most of the
4302 * time. But probably not always!
4304 * This is a temporary workaround to be removed once Configure
4305 * support is added and NETaa14816 is considered in full.
4306 * It does not address tzname aspects of NETaa14816.
4309 # ifndef STRUCT_TM_HASZONE
4310 # define STRUCT_TM_HASZONE
4315 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
4317 #ifdef STRUCT_TM_HASZONE
4320 Copy(localtime(&now), ptm, 1, struct tm);
4325 * mini_mktime - normalise struct tm values without the localtime()
4326 * semantics (and overhead) of mktime().
4329 Perl_mini_mktime(pTHX_ struct tm *ptm)
4333 int month, mday, year, jday;
4334 int odd_cent, odd_year;
4336 #define DAYS_PER_YEAR 365
4337 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
4338 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
4339 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
4340 #define SECS_PER_HOUR (60*60)
4341 #define SECS_PER_DAY (24*SECS_PER_HOUR)
4342 /* parentheses deliberately absent on these two, otherwise they don't work */
4343 #define MONTH_TO_DAYS 153/5
4344 #define DAYS_TO_MONTH 5/153
4345 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4346 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4347 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4348 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4351 * Year/day algorithm notes:
4353 * With a suitable offset for numeric value of the month, one can find
4354 * an offset into the year by considering months to have 30.6 (153/5) days,
4355 * using integer arithmetic (i.e., with truncation). To avoid too much
4356 * messing about with leap days, we consider January and February to be
4357 * the 13th and 14th month of the previous year. After that transformation,
4358 * we need the month index we use to be high by 1 from 'normal human' usage,
4359 * so the month index values we use run from 4 through 15.
4361 * Given that, and the rules for the Gregorian calendar (leap years are those
4362 * divisible by 4 unless also divisible by 100, when they must be divisible
4363 * by 400 instead), we can simply calculate the number of days since some
4364 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4365 * the days we derive from our month index, and adding in the day of the
4366 * month. The value used here is not adjusted for the actual origin which
4367 * it normally would use (1 January A.D. 1), since we're not exposing it.
4368 * We're only building the value so we can turn around and get the
4369 * normalised values for the year, month, day-of-month, and day-of-year.
4371 * For going backward, we need to bias the value we're using so that we find
4372 * the right year value. (Basically, we don't want the contribution of
4373 * March 1st to the number to apply while deriving the year). Having done
4374 * that, we 'count up' the contribution to the year number by accounting for
4375 * full quadracenturies (400-year periods) with their extra leap days, plus
4376 * the contribution from full centuries (to avoid counting in the lost leap
4377 * days), plus the contribution from full quad-years (to count in the normal
4378 * leap days), plus the leftover contribution from any non-leap years.
4379 * At this point, if we were working with an actual leap day, we'll have 0
4380 * days left over. This is also true for March 1st, however. So, we have
4381 * to special-case that result, and (earlier) keep track of the 'odd'
4382 * century and year contributions. If we got 4 extra centuries in a qcent,
4383 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4384 * Otherwise, we add back in the earlier bias we removed (the 123 from
4385 * figuring in March 1st), find the month index (integer division by 30.6),
4386 * and the remainder is the day-of-month. We then have to convert back to
4387 * 'real' months (including fixing January and February from being 14/15 in
4388 * the previous year to being in the proper year). After that, to get
4389 * tm_yday, we work with the normalised year and get a new yearday value for
4390 * January 1st, which we subtract from the yearday value we had earlier,
4391 * representing the date we've re-built. This is done from January 1
4392 * because tm_yday is 0-origin.
4394 * Since POSIX time routines are only guaranteed to work for times since the
4395 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4396 * applies Gregorian calendar rules even to dates before the 16th century
4397 * doesn't bother me. Besides, you'd need cultural context for a given
4398 * date to know whether it was Julian or Gregorian calendar, and that's
4399 * outside the scope for this routine. Since we convert back based on the
4400 * same rules we used to build the yearday, you'll only get strange results
4401 * for input which needed normalising, or for the 'odd' century years which
4402 * were leap years in the Julian calander but not in the Gregorian one.
4403 * I can live with that.
4405 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4406 * that's still outside the scope for POSIX time manipulation, so I don't
4410 year = 1900 + ptm->tm_year;
4411 month = ptm->tm_mon;
4412 mday = ptm->tm_mday;
4413 /* allow given yday with no month & mday to dominate the result */
4414 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4417 jday = 1 + ptm->tm_yday;
4426 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4427 yearday += month*MONTH_TO_DAYS + mday + jday;
4429 * Note that we don't know when leap-seconds were or will be,
4430 * so we have to trust the user if we get something which looks
4431 * like a sensible leap-second. Wild values for seconds will
4432 * be rationalised, however.
4434 if ((unsigned) ptm->tm_sec <= 60) {
4441 secs += 60 * ptm->tm_min;
4442 secs += SECS_PER_HOUR * ptm->tm_hour;
4444 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4445 /* got negative remainder, but need positive time */
4446 /* back off an extra day to compensate */
4447 yearday += (secs/SECS_PER_DAY)-1;
4448 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4451 yearday += (secs/SECS_PER_DAY);
4452 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4455 else if (secs >= SECS_PER_DAY) {
4456 yearday += (secs/SECS_PER_DAY);
4457 secs %= SECS_PER_DAY;
4459 ptm->tm_hour = secs/SECS_PER_HOUR;
4460 secs %= SECS_PER_HOUR;
4461 ptm->tm_min = secs/60;
4463 ptm->tm_sec += secs;
4464 /* done with time of day effects */
4466 * The algorithm for yearday has (so far) left it high by 428.
4467 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4468 * bias it by 123 while trying to figure out what year it
4469 * really represents. Even with this tweak, the reverse
4470 * translation fails for years before A.D. 0001.
4471 * It would still fail for Feb 29, but we catch that one below.
4473 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4474 yearday -= YEAR_ADJUST;
4475 year = (yearday / DAYS_PER_QCENT) * 400;
4476 yearday %= DAYS_PER_QCENT;
4477 odd_cent = yearday / DAYS_PER_CENT;
4478 year += odd_cent * 100;
4479 yearday %= DAYS_PER_CENT;
4480 year += (yearday / DAYS_PER_QYEAR) * 4;
4481 yearday %= DAYS_PER_QYEAR;
4482 odd_year = yearday / DAYS_PER_YEAR;
4484 yearday %= DAYS_PER_YEAR;
4485 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4490 yearday += YEAR_ADJUST; /* recover March 1st crock */
4491 month = yearday*DAYS_TO_MONTH;
4492 yearday -= month*MONTH_TO_DAYS;
4493 /* recover other leap-year adjustment */
4502 ptm->tm_year = year - 1900;
4504 ptm->tm_mday = yearday;
4505 ptm->tm_mon = month;
4509 ptm->tm_mon = month - 1;
4511 /* re-build yearday based on Jan 1 to get tm_yday */
4513 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4514 yearday += 14*MONTH_TO_DAYS + 1;
4515 ptm->tm_yday = jday - yearday;
4516 /* fix tm_wday if not overridden by caller */
4517 if ((unsigned)ptm->tm_wday > 6)
4518 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4522 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
4530 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4533 mytm.tm_hour = hour;
4534 mytm.tm_mday = mday;
4536 mytm.tm_year = year;
4537 mytm.tm_wday = wday;
4538 mytm.tm_yday = yday;
4539 mytm.tm_isdst = isdst;
4542 New(0, buf, buflen, char);
4543 len = strftime(buf, buflen, fmt, &mytm);
4545 ** The following is needed to handle to the situation where
4546 ** tmpbuf overflows. Basically we want to allocate a buffer
4547 ** and try repeatedly. The reason why it is so complicated
4548 ** is that getting a return value of 0 from strftime can indicate
4549 ** one of the following:
4550 ** 1. buffer overflowed,
4551 ** 2. illegal conversion specifier, or
4552 ** 3. the format string specifies nothing to be returned(not
4553 ** an error). This could be because format is an empty string
4554 ** or it specifies %p that yields an empty string in some locale.
4555 ** If there is a better way to make it portable, go ahead by
4558 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4561 /* Possibly buf overflowed - try again with a bigger buf */
4562 int fmtlen = strlen(fmt);
4563 int bufsize = fmtlen + buflen;
4565 New(0, buf, bufsize, char);
4567 buflen = strftime(buf, bufsize, fmt, &mytm);
4568 if (buflen > 0 && buflen < bufsize)
4570 /* heuristic to prevent out-of-memory errors */
4571 if (bufsize > 100*fmtlen) {
4577 Renew(buf, bufsize, char);
4582 Perl_croak(aTHX_ "panic: no strftime");
4587 #define SV_CWD_RETURN_UNDEF \
4588 sv_setsv(sv, &PL_sv_undef); \
4591 #define SV_CWD_ISDOT(dp) \
4592 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4593 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4596 =for apidoc sv_getcwd
4598 Fill the sv with current working directory
4603 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4604 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4605 * getcwd(3) if available
4606 * Comments from the orignal:
4607 * This is a faster version of getcwd. It's also more dangerous
4608 * because you might chdir out of a directory that you can't chdir
4611 /* XXX: this needs more porting #ifndef HAS_GETCWD */
4613 Perl_sv_getcwd(pTHX_ register SV *sv)
4618 struct stat statbuf;
4619 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4620 int namelen, pathlen=0;
4625 (void)SvUPGRADE(sv, SVt_PV);
4630 while ((getcwd(SvPVX(sv), SvLEN(sv)-1) == NULL) && errno == ERANGE) {
4631 SvGROW(sv, SvLEN(sv) + 128);
4633 SvCUR_set(sv, strlen(SvPVX(sv)));
4638 if (PerlLIO_lstat(".", &statbuf) < 0) {
4639 CWDXS_RETURN_SVUNDEF(sv);
4642 orig_cdev = statbuf.st_dev;
4643 orig_cino = statbuf.st_ino;
4651 if (PerlDir_chdir("..") < 0) {
4652 SV_CWD_RETURN_UNDEF;
4654 if (PerlLIO_stat(".", &statbuf) < 0) {
4655 SV_CWD_RETURN_UNDEF;
4658 cdev = statbuf.st_dev;
4659 cino = statbuf.st_ino;
4661 if (odev == cdev && oino == cino) {
4664 if (!(dir = PerlDir_open("."))) {
4665 SV_CWD_RETURN_UNDEF;
4668 while ((dp = PerlDir_read(dir)) != NULL) {
4670 namelen = dp->d_namlen;
4672 namelen = strlen(dp->d_name);
4675 if (SV_CWD_ISDOT(dp)) {dp->d_name[0] == '.'
4679 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4680 SV_CWD_RETURN_UNDEF;
4683 tdev = statbuf.st_dev;
4684 tino = statbuf.st_ino;
4685 if (tino == oino && tdev == odev) {
4691 SV_CWD_RETURN_UNDEF;
4694 SvGROW(sv, pathlen + namelen + 1);
4698 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4701 /* prepend current directory to the front */
4703 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4704 pathlen += (namelen + 1);
4706 #ifdef VOID_CLOSEDIR
4709 if (PerlDir_close(dir) < 0) {
4710 SV_CWD_RETURN_UNDEF;
4715 SvCUR_set(sv, pathlen);
4719 if (PerlDir_chdir(SvPVX(sv)) < 0) {
4720 SV_CWD_RETURN_UNDEF;
4722 if (PerlLIO_stat(".", &statbuf) < 0) {
4723 SV_CWD_RETURN_UNDEF;
4726 cdev = statbuf.st_dev;
4727 cino = statbuf.st_ino;
4729 if (cdev != orig_cdev || cino != orig_cino) {
4730 Perl_croak(aTHX_ "Unstable directory path, "
4731 "current directory changed unexpectedly");
4742 =for apidoc sv_realpath
4744 Wrap or emulate realpath(3).
4749 Perl_sv_realpath(pTHX_ SV *sv, char *path, STRLEN len)
4752 char name[MAXPATHLEN] = { 0 }, *s;
4753 STRLEN pathlen, namelen;
4756 /* Be paranoid about the use of realpath(),
4757 * it is an infamous source of buffer overruns. */
4759 /* Is the source buffer too long?
4760 * Don't use strlen() to avoid running off the end. */
4761 s = memchr(path, '\0', MAXPATHLEN);
4762 pathlen = s ? s - path : MAXPATHLEN;
4763 if (pathlen == MAXPATHLEN) {
4764 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %c= (MAXPATHLEN = %d)",
4765 path, s ? '=' : '>', MAXPATHLEN);
4766 SV_CWD_RETURN_UNDEF;
4769 /* Here goes nothing. */
4770 if (realpath(path, name) == NULL) {
4771 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %s",
4772 path, Strerror(errno));
4773 SV_CWD_RETURN_UNDEF;
4776 /* Is the destination buffer too long?
4777 * Don't use strlen() to avoid running off the end. */
4778 s = memchr(name, '\0', MAXPATHLEN);
4779 namelen = s ? s - name : MAXPATHLEN;
4780 if (namelen == MAXPATHLEN) {
4781 Perl_warn(aTHX_ "sv_realpath: realpath(\"%s\"): %c= (MAXPATHLEN = %d)",
4782 path, s ? '=' : '>', MAXPATHLEN);
4783 SV_CWD_RETURN_UNDEF;
4786 /* The coast is clear? */
4787 sv_setpvn(sv, name, namelen);
4794 char dotdots[MAXPATHLEN] = { 0 };
4795 struct stat cst, pst, tst;
4797 if (PerlLIO_stat(path, &cst) < 0) {
4798 Perl_warn(aTHX_ "sv_realpath: stat(\"%s\"): %s",
4799 path, Strerror(errno));
4800 SV_CWD_RETURN_UNDEF;
4803 (void)SvUPGRADE(sv, SVt_PV);
4808 Copy(path, dotdots, len, char);
4811 strcat(dotdots, "/..");
4812 StructCopy(&cst, &pst, struct stat);
4814 if (PerlLIO_stat(dotdots, &cst) < 0) {
4815 Perl_warn(aTHX_ "sv_realpath: stat(\"%s\"): %s",
4816 dotdots, Strerror(errno));
4817 SV_CWD_RETURN_UNDEF;
4820 if (pst.st_dev == cst.st_dev && pst.st_ino == cst.st_ino) {
4821 /* We've reached the root: previous is same as current */
4824 STRLEN dotdotslen = strlen(dotdots);
4826 /* Scan through the dir looking for name of previous */
4827 if (!(parent = PerlDir_open(dotdots))) {
4828 Perl_warn(aTHX_ "sv_realpath: opendir(\"%s\"): %s",
4829 dotdots, Strerror(errno));
4830 SV_CWD_RETURN_UNDEF;
4833 SETERRNO(0,SS$_NORMAL); /* for readdir() */
4834 while ((dp = PerlDir_read(parent)) != NULL) {
4835 if (SV_CWD_ISDOT(dp)) {
4839 Copy(dotdots, name, dotdotslen, char);
4840 name[dotdotslen] = '/';
4842 namelen = dp->d_namlen;
4844 namelen = strlen(dp->d_name);
4846 Copy(dp->d_name, name + dotdotslen + 1, namelen, char);
4847 name[dotdotslen + 1 + namelen] = 0;
4849 if (PerlLIO_lstat(name, &tst) < 0) {
4850 PerlDir_close(parent);
4851 Perl_warn(aTHX_ "sv_realpath: lstat(\"%s\"): %s",
4852 name, Strerror(errno));
4853 SV_CWD_RETURN_UNDEF;
4856 if (tst.st_dev == pst.st_dev && tst.st_ino == pst.st_ino)
4859 SETERRNO(0,SS$_NORMAL); /* for readdir() */
4863 Perl_warn(aTHX_ "sv_realpath: readdir(\"%s\"): %s",
4864 dotdots, Strerror(errno));
4865 SV_CWD_RETURN_UNDEF;
4868 SvGROW(sv, pathlen + namelen + 1);
4871 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4875 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4876 pathlen += (namelen + 1);
4878 #ifdef VOID_CLOSEDIR
4879 PerlDir_close(parent);
4881 if (PerlDir_close(parent) < 0) {
4882 Perl_warn(aTHX_ "sv_realpath: closedir(\"%s\"): %s",
4883 dotdots, Strerror(errno));
4884 SV_CWD_RETURN_UNDEF;
4890 SvCUR_set(sv, pathlen);