3 * Copyright (c) 1991-1999, 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
19 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
24 # define SIG_ERR ((Sighandler_t) -1)
27 /* XXX If this causes problems, set i_unistd=undef in the hint file. */
36 /* Put this after #includes because fork and vfork prototypes may
47 # include <sys/file.h>
51 # include <sys/wait.h>
62 long xcount[MAXXCOUNT];
63 long lastxcount[MAXXCOUNT];
64 long xycount[MAXXCOUNT][MAXYCOUNT];
65 long lastxycount[MAXXCOUNT][MAXYCOUNT];
69 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
70 # define FD_CLOEXEC 1 /* NeXT needs this */
73 /* paranoid version of system's malloc() */
75 /* NOTE: Do not call the next three routines directly. Use the macros
76 * in handy.h, so that we can easily redefine everything to do tracking of
77 * allocated hunks back to the original New to track down any memory leaks.
78 * XXX This advice seems to be widely ignored :-( --AD August 1996.
82 Perl_safesysmalloc(MEM_SIZE size)
88 PerlIO_printf(PerlIO_stderr(),
89 "Allocation too large: %lx\n", size) FLUSH;
92 #endif /* HAS_64K_LIMIT */
95 Perl_croak_nocontext("panic: malloc");
97 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
98 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
104 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
111 /* paranoid version of system's realloc() */
114 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
118 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
119 Malloc_t PerlMem_realloc();
120 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
124 PerlIO_printf(PerlIO_stderr(),
125 "Reallocation too large: %lx\n", size) FLUSH;
128 #endif /* HAS_64K_LIMIT */
135 return safesysmalloc(size);
138 Perl_croak_nocontext("panic: realloc");
140 ptr = PerlMem_realloc(where,size);
143 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,PL_an++);
144 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
152 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
159 /* safe version of system's free() */
162 Perl_safesysfree(Malloc_t where)
165 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,PL_an++));
172 /* safe version of system's calloc() */
175 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
181 if (size * count > 0xffff) {
182 PerlIO_printf(PerlIO_stderr(),
183 "Allocation too large: %lx\n", size * count) FLUSH;
186 #endif /* HAS_64K_LIMIT */
188 if ((long)size < 0 || (long)count < 0)
189 Perl_croak_nocontext("panic: calloc");
192 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
193 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
195 memset((void*)ptr, 0, size);
201 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
210 struct mem_test_strut {
218 # define ALIGN sizeof(struct mem_test_strut)
220 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
221 # define typeof_chunk(ch) \
222 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
223 # define set_typeof_chunk(ch,t) \
224 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
225 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
228 ? ((size) - 1)/8 + 5 \
232 Perl_safexmalloc(I32 x, MEM_SIZE size)
234 register char* where = (char*)safemalloc(size + ALIGN);
237 xycount[x][SIZE_TO_Y(size)]++;
238 set_typeof_chunk(where, x);
239 sizeof_chunk(where) = size;
240 return (Malloc_t)(where + ALIGN);
244 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
246 char *where = (char*)wh;
249 return safexmalloc(0,size);
252 MEM_SIZE old = sizeof_chunk(where - ALIGN);
253 int t = typeof_chunk(where - ALIGN);
254 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
256 xycount[t][SIZE_TO_Y(old)]--;
257 xycount[t][SIZE_TO_Y(size)]++;
258 xcount[t] += size - old;
259 sizeof_chunk(new) = size;
260 return (Malloc_t)(new + ALIGN);
265 Perl_safexfree(Malloc_t wh)
268 char *where = (char*)wh;
274 size = sizeof_chunk(where);
275 x = where[0] + 100 * where[1];
277 xycount[x][SIZE_TO_Y(size)]--;
282 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
284 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
286 xycount[x][SIZE_TO_Y(size)]++;
287 memset((void*)(where + ALIGN), 0, size * count);
288 set_typeof_chunk(where, x);
289 sizeof_chunk(where) = size;
290 return (Malloc_t)(where + ALIGN);
294 S_xstat(pTHX_ int flag)
296 register I32 i, j, total = 0;
297 I32 subtot[MAXYCOUNT];
299 for (j = 0; j < MAXYCOUNT; j++) {
303 PerlIO_printf(PerlIO_stderr(), " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
304 for (i = 0; i < MAXXCOUNT; i++) {
306 for (j = 0; j < MAXYCOUNT; j++) {
307 subtot[j] += xycount[i][j];
310 ? xcount[i] /* Have something */
312 ? xcount[i] != lastxcount[i] /* Changed */
313 : xcount[i] > lastxcount[i])) { /* Growed */
314 PerlIO_printf(PerlIO_stderr(),"%2d %02d %7ld ", i / 100, i % 100,
315 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
316 lastxcount[i] = xcount[i];
317 for (j = 0; j < MAXYCOUNT; j++) {
319 ? xycount[i][j] /* Have something */
321 ? xycount[i][j] != lastxycount[i][j] /* Changed */
322 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
323 PerlIO_printf(PerlIO_stderr(),"%3ld ",
325 ? xycount[i][j] - lastxycount[i][j]
327 lastxycount[i][j] = xycount[i][j];
329 PerlIO_printf(PerlIO_stderr(), " . ", xycount[i][j]);
332 PerlIO_printf(PerlIO_stderr(), "\n");
336 PerlIO_printf(PerlIO_stderr(), "Total %7ld ", total);
337 for (j = 0; j < MAXYCOUNT; j++) {
339 PerlIO_printf(PerlIO_stderr(), "%3ld ", subtot[j]);
341 PerlIO_printf(PerlIO_stderr(), " . ");
344 PerlIO_printf(PerlIO_stderr(), "\n");
348 #endif /* LEAKTEST */
350 /* copy a string up to some (non-backslashed) delimiter, if any */
353 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
356 for (tolen = 0; from < fromend; from++, tolen++) {
358 if (from[1] == delim)
367 else if (*from == delim)
378 /* return ptr to little string in big string, NULL if not found */
379 /* This routine was donated by Corey Satten. */
382 Perl_instr(pTHX_ register const char *big, register const char *little)
384 register const char *s, *x;
395 for (x=big,s=little; *s; /**/ ) {
404 return (char*)(big-1);
409 /* same as instr but allow embedded nulls */
412 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
414 register const char *s, *x;
415 register I32 first = *little;
416 register const char *littleend = lend;
418 if (!first && little >= littleend)
420 if (bigend - big < littleend - little)
422 bigend -= littleend - little++;
423 while (big <= bigend) {
426 for (x=big,s=little; s < littleend; /**/ ) {
433 return (char*)(big-1);
438 /* reverse of the above--find last substring */
441 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
443 register const char *bigbeg;
444 register const char *s, *x;
445 register I32 first = *little;
446 register const char *littleend = lend;
448 if (!first && little >= littleend)
449 return (char*)bigend;
451 big = bigend - (littleend - little++);
452 while (big >= bigbeg) {
455 for (x=big+2,s=little; s < littleend; /**/ ) {
462 return (char*)(big+1);
468 * Set up for a new ctype locale.
471 Perl_new_ctype(pTHX_ const char *newctype)
473 #ifdef USE_LOCALE_CTYPE
477 for (i = 0; i < 256; i++) {
479 PL_fold_locale[i] = toLOWER_LC(i);
480 else if (isLOWER_LC(i))
481 PL_fold_locale[i] = toUPPER_LC(i);
483 PL_fold_locale[i] = i;
486 #endif /* USE_LOCALE_CTYPE */
490 * Set up for a new collation locale.
493 Perl_new_collate(pTHX_ const char *newcoll)
495 #ifdef USE_LOCALE_COLLATE
498 if (PL_collation_name) {
500 Safefree(PL_collation_name);
501 PL_collation_name = NULL;
502 PL_collation_standard = TRUE;
503 PL_collxfrm_base = 0;
504 PL_collxfrm_mult = 2;
509 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
511 Safefree(PL_collation_name);
512 PL_collation_name = savepv(newcoll);
513 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
516 /* 2: at most so many chars ('a', 'b'). */
517 /* 50: surely no system expands a char more. */
518 #define XFRMBUFSIZE (2 * 50)
519 char xbuf[XFRMBUFSIZE];
520 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
521 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
522 SSize_t mult = fb - fa;
524 Perl_croak(aTHX_ "strxfrm() gets absurd");
525 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
526 PL_collxfrm_mult = mult;
530 #endif /* USE_LOCALE_COLLATE */
534 Perl_set_numeric_radix(pTHX)
536 #ifdef USE_LOCALE_NUMERIC
537 # ifdef HAS_LOCALECONV
541 if (lc && lc->decimal_point)
542 /* We assume that decimal separator aka the radix
543 * character is always a single character. If it
544 * ever is a string, this needs to be rethunk. */
545 PL_numeric_radix = *lc->decimal_point;
547 PL_numeric_radix = 0;
548 # endif /* HAS_LOCALECONV */
550 PL_numeric_radix = 0;
551 #endif /* USE_LOCALE_NUMERIC */
555 * Set up for a new numeric locale.
558 Perl_new_numeric(pTHX_ const char *newnum)
560 #ifdef USE_LOCALE_NUMERIC
563 if (PL_numeric_name) {
564 Safefree(PL_numeric_name);
565 PL_numeric_name = NULL;
566 PL_numeric_standard = TRUE;
567 PL_numeric_local = TRUE;
572 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
573 Safefree(PL_numeric_name);
574 PL_numeric_name = savepv(newnum);
575 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
576 PL_numeric_local = TRUE;
580 #endif /* USE_LOCALE_NUMERIC */
584 Perl_set_numeric_standard(pTHX)
586 #ifdef USE_LOCALE_NUMERIC
588 if (! PL_numeric_standard) {
589 setlocale(LC_NUMERIC, "C");
590 PL_numeric_standard = TRUE;
591 PL_numeric_local = FALSE;
594 #endif /* USE_LOCALE_NUMERIC */
598 Perl_set_numeric_local(pTHX)
600 #ifdef USE_LOCALE_NUMERIC
602 if (! PL_numeric_local) {
603 setlocale(LC_NUMERIC, PL_numeric_name);
604 PL_numeric_standard = FALSE;
605 PL_numeric_local = TRUE;
609 #endif /* USE_LOCALE_NUMERIC */
613 * Initialize locale awareness.
616 Perl_init_i18nl10n(pTHX_ int printwarn)
620 * 1 = set ok or not applicable,
621 * 0 = fallback to C locale,
622 * -1 = fallback to C locale failed
627 #ifdef USE_LOCALE_CTYPE
628 char *curctype = NULL;
629 #endif /* USE_LOCALE_CTYPE */
630 #ifdef USE_LOCALE_COLLATE
631 char *curcoll = NULL;
632 #endif /* USE_LOCALE_COLLATE */
633 #ifdef USE_LOCALE_NUMERIC
635 #endif /* USE_LOCALE_NUMERIC */
637 char *language = PerlEnv_getenv("LANGUAGE");
639 char *lc_all = PerlEnv_getenv("LC_ALL");
640 char *lang = PerlEnv_getenv("LANG");
641 bool setlocale_failure = FALSE;
643 #ifdef LOCALE_ENVIRON_REQUIRED
646 * Ultrix setlocale(..., "") fails if there are no environment
647 * variables from which to get a locale name.
654 if (setlocale(LC_ALL, ""))
657 setlocale_failure = TRUE;
659 if (!setlocale_failure) {
660 #ifdef USE_LOCALE_CTYPE
663 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
665 setlocale_failure = TRUE;
666 #endif /* USE_LOCALE_CTYPE */
667 #ifdef USE_LOCALE_COLLATE
669 setlocale(LC_COLLATE,
670 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
672 setlocale_failure = TRUE;
673 #endif /* USE_LOCALE_COLLATE */
674 #ifdef USE_LOCALE_NUMERIC
676 setlocale(LC_NUMERIC,
677 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
679 setlocale_failure = TRUE;
680 #endif /* USE_LOCALE_NUMERIC */
685 #endif /* !LOCALE_ENVIRON_REQUIRED */
688 if (! setlocale(LC_ALL, ""))
689 setlocale_failure = TRUE;
692 if (!setlocale_failure) {
693 #ifdef USE_LOCALE_CTYPE
694 if (! (curctype = setlocale(LC_CTYPE, "")))
695 setlocale_failure = TRUE;
696 #endif /* USE_LOCALE_CTYPE */
697 #ifdef USE_LOCALE_COLLATE
698 if (! (curcoll = setlocale(LC_COLLATE, "")))
699 setlocale_failure = TRUE;
700 #endif /* USE_LOCALE_COLLATE */
701 #ifdef USE_LOCALE_NUMERIC
702 if (! (curnum = setlocale(LC_NUMERIC, "")))
703 setlocale_failure = TRUE;
704 #endif /* USE_LOCALE_NUMERIC */
707 if (setlocale_failure) {
709 bool locwarn = (printwarn > 1 ||
711 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
716 PerlIO_printf(PerlIO_stderr(),
717 "perl: warning: Setting locale failed.\n");
721 PerlIO_printf(PerlIO_stderr(),
722 "perl: warning: Setting locale failed for the categories:\n\t");
723 #ifdef USE_LOCALE_CTYPE
725 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
726 #endif /* USE_LOCALE_CTYPE */
727 #ifdef USE_LOCALE_COLLATE
729 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
730 #endif /* USE_LOCALE_COLLATE */
731 #ifdef USE_LOCALE_NUMERIC
733 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
734 #endif /* USE_LOCALE_NUMERIC */
735 PerlIO_printf(PerlIO_stderr(), "\n");
739 PerlIO_printf(PerlIO_stderr(),
740 "perl: warning: Please check that your locale settings:\n");
743 PerlIO_printf(PerlIO_stderr(),
744 "\tLANGUAGE = %c%s%c,\n",
745 language ? '"' : '(',
746 language ? language : "unset",
747 language ? '"' : ')');
750 PerlIO_printf(PerlIO_stderr(),
751 "\tLC_ALL = %c%s%c,\n",
753 lc_all ? lc_all : "unset",
758 for (e = environ; *e; e++) {
759 if (strnEQ(*e, "LC_", 3)
760 && strnNE(*e, "LC_ALL=", 7)
761 && (p = strchr(*e, '=')))
762 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
763 (int)(p - *e), *e, p + 1);
767 PerlIO_printf(PerlIO_stderr(),
770 lang ? lang : "unset",
773 PerlIO_printf(PerlIO_stderr(),
774 " are supported and installed on your system.\n");
779 if (setlocale(LC_ALL, "C")) {
781 PerlIO_printf(PerlIO_stderr(),
782 "perl: warning: Falling back to the standard locale (\"C\").\n");
787 PerlIO_printf(PerlIO_stderr(),
788 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
795 #ifdef USE_LOCALE_CTYPE
796 || !(curctype || setlocale(LC_CTYPE, "C"))
797 #endif /* USE_LOCALE_CTYPE */
798 #ifdef USE_LOCALE_COLLATE
799 || !(curcoll || setlocale(LC_COLLATE, "C"))
800 #endif /* USE_LOCALE_COLLATE */
801 #ifdef USE_LOCALE_NUMERIC
802 || !(curnum || setlocale(LC_NUMERIC, "C"))
803 #endif /* USE_LOCALE_NUMERIC */
807 PerlIO_printf(PerlIO_stderr(),
808 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
812 #endif /* ! LC_ALL */
814 #ifdef USE_LOCALE_CTYPE
815 curctype = setlocale(LC_CTYPE, Nullch);
816 #endif /* USE_LOCALE_CTYPE */
817 #ifdef USE_LOCALE_COLLATE
818 curcoll = setlocale(LC_COLLATE, Nullch);
819 #endif /* USE_LOCALE_COLLATE */
820 #ifdef USE_LOCALE_NUMERIC
821 curnum = setlocale(LC_NUMERIC, Nullch);
822 #endif /* USE_LOCALE_NUMERIC */
825 #ifdef USE_LOCALE_CTYPE
827 #endif /* USE_LOCALE_CTYPE */
829 #ifdef USE_LOCALE_COLLATE
830 new_collate(curcoll);
831 #endif /* USE_LOCALE_COLLATE */
833 #ifdef USE_LOCALE_NUMERIC
835 #endif /* USE_LOCALE_NUMERIC */
837 #endif /* USE_LOCALE */
842 /* Backwards compatibility. */
844 Perl_init_i18nl14n(pTHX_ int printwarn)
846 return init_i18nl10n(printwarn);
849 #ifdef USE_LOCALE_COLLATE
852 * mem_collxfrm() is a bit like strxfrm() but with two important
853 * differences. First, it handles embedded NULs. Second, it allocates
854 * a bit more memory than needed for the transformed data itself.
855 * The real transformed data begins at offset sizeof(collationix).
856 * Please see sv_collxfrm() to see how this is used.
859 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
862 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
864 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
865 /* the +1 is for the terminating NUL. */
867 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
868 New(171, xbuf, xAlloc, char);
872 *(U32*)xbuf = PL_collation_ix;
873 xout = sizeof(PL_collation_ix);
874 for (xin = 0; xin < len; ) {
878 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
881 if (xused < xAlloc - xout)
883 xAlloc = (2 * xAlloc) + 1;
884 Renew(xbuf, xAlloc, char);
889 xin += strlen(s + xin) + 1;
892 /* Embedded NULs are understood but silently skipped
893 * because they make no sense in locale collation. */
897 *xlen = xout - sizeof(PL_collation_ix);
906 #endif /* USE_LOCALE_COLLATE */
908 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
910 /* As a space optimization, we do not compile tables for strings of length
911 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
912 special-cased in fbm_instr().
914 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
917 Perl_fbm_compile(pTHX_ SV *sv, U32 flags /* not used yet */)
926 if (flags & FBMcf_TAIL)
927 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
928 s = (U8*)SvPV_force(sv, len);
929 (void)SvUPGRADE(sv, SVt_PVBM);
930 if (len == 0) /* TAIL might be on on a zero-length string. */
938 Sv_Grow(sv,len + 256 + FBM_TABLE_OFFSET);
939 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
940 s = table - 1 - FBM_TABLE_OFFSET; /* Last char */
941 for (i = 0; i < 256; i++) {
944 table[-1] = flags; /* Not used yet */
948 if (table[*s] == mlen)
953 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
956 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
957 for (i = 0; i < len; i++) {
958 if (PL_freq[s[i]] < frequency) {
960 frequency = PL_freq[s[i]];
963 BmRARE(sv) = s[rarest];
964 BmPREVIOUS(sv) = rarest;
965 BmUSEFUL(sv) = 100; /* Initial value */
966 if (flags & FBMcf_TAIL)
968 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
971 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
972 /* If SvTAIL is actually due to \Z or \z, this gives false positives
976 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
978 register unsigned char *s;
980 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
981 register STRLEN littlelen = l;
982 register I32 multiline = flags & FBMrf_MULTILINE;
984 if (bigend - big < littlelen) {
986 if ( SvTAIL(littlestr)
987 && (bigend - big == littlelen - 1)
989 || *big == *little && memEQ(big, little, littlelen - 1)))
994 if (littlelen <= 2) { /* Special-cased */
997 if (littlelen == 1) {
998 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
999 /* Know that bigend != big. */
1000 if (bigend[-1] == '\n')
1001 return (char *)(bigend - 1);
1002 return (char *) bigend;
1005 while (s < bigend) {
1010 if (SvTAIL(littlestr))
1011 return (char *) bigend;
1015 return (char*)big; /* Cannot be SvTAIL! */
1017 /* littlelen is 2 */
1018 if (SvTAIL(littlestr) && !multiline) {
1019 if (bigend[-1] == '\n' && bigend[-2] == *little)
1020 return (char*)bigend - 2;
1021 if (bigend[-1] == *little)
1022 return (char*)bigend - 1;
1026 /* This should be better than FBM if c1 == c2, and almost
1027 as good otherwise: maybe better since we do less indirection.
1028 And we save a lot of memory by caching no table. */
1029 register unsigned char c1 = little[0];
1030 register unsigned char c2 = little[1];
1035 while (s <= bigend) {
1038 return (char*)s - 1;
1045 goto check_1char_anchor;
1056 goto check_1char_anchor;
1059 while (s <= bigend) {
1062 return (char*)s - 1;
1064 goto check_1char_anchor;
1073 check_1char_anchor: /* One char and anchor! */
1074 if (SvTAIL(littlestr) && (*bigend == *little))
1075 return (char *)bigend; /* bigend is already decremented. */
1078 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1079 s = bigend - littlelen;
1081 && bigend[-1] == '\n'
1083 /* Automatically of length > 2 */
1084 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1085 return (char*)s; /* how sweet it is */
1086 if (s[1] == *little && memEQ((char*)s + 2,(char*)little + 1,
1088 return (char*)s + 1; /* how sweet it is */
1091 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1092 char *b = ninstr((char*)big,(char*)bigend,
1093 (char*)little, (char*)little + littlelen);
1095 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1096 /* Chop \n from littlestr: */
1097 s = bigend - littlelen + 1;
1098 if (*s == *little && memEQ((char*)s + 1, (char*)little + 1,
1106 { /* Do actual FBM. */
1107 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1108 register unsigned char *oldlittle;
1110 if (littlelen > bigend - big)
1112 --littlelen; /* Last char found by table lookup */
1114 s = big + littlelen;
1115 little += littlelen; /* last char */
1122 if (tmp = table[*s]) {
1124 if (bigend - s > tmp) {
1130 if ((s += tmp) < bigend)
1135 else { /* less expensive than calling strncmp() */
1136 register unsigned char *olds = s;
1141 if (*--s == *--little)
1144 s = olds + 1; /* here we pay the price for failure */
1146 if (s < bigend) /* fake up continue to outer loop */
1154 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1155 && memEQ(bigend - littlelen, oldlittle - littlelen, littlelen) )
1156 return (char*)bigend - littlelen;
1161 /* start_shift, end_shift are positive quantities which give offsets
1162 of ends of some substring of bigstr.
1163 If `last' we want the last occurence.
1164 old_posp is the way of communication between consequent calls if
1165 the next call needs to find the .
1166 The initial *old_posp should be -1.
1168 Note that we take into account SvTAIL, so one can get extra
1169 optimizations if _ALL flag is set.
1172 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1173 if PL_multiline. In fact if !PL_multiline the autoritative answer
1174 is not supported yet. */
1177 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1180 register unsigned char *s, *x;
1181 register unsigned char *big;
1183 register I32 previous;
1185 register unsigned char *little;
1186 register I32 stop_pos;
1187 register unsigned char *littleend;
1191 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1192 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1194 if ( BmRARE(littlestr) == '\n'
1195 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1196 little = (unsigned char *)(SvPVX(littlestr));
1197 littleend = little + SvCUR(littlestr);
1204 little = (unsigned char *)(SvPVX(littlestr));
1205 littleend = little + SvCUR(littlestr);
1207 /* The value of pos we can start at: */
1208 previous = BmPREVIOUS(littlestr);
1209 big = (unsigned char *)(SvPVX(bigstr));
1210 /* The value of pos we can stop at: */
1211 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1212 if (previous + start_shift > stop_pos) {
1213 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1217 while (pos < previous + start_shift) {
1218 if (!(pos += PL_screamnext[pos]))
1223 if (pos >= stop_pos) break;
1224 if (big[pos-previous] != first)
1226 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1232 if (s == littleend) {
1234 if (!last) return (char *)(big+pos-previous);
1237 } while ( pos += PL_screamnext[pos] );
1238 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1239 #else /* !POINTERRIGOR */
1242 if (pos >= stop_pos) break;
1243 if (big[pos] != first)
1245 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1251 if (s == littleend) {
1253 if (!last) return (char *)(big+pos);
1256 } while ( pos += PL_screamnext[pos] );
1258 return (char *)(big+(*old_posp));
1259 #endif /* POINTERRIGOR */
1261 if (!SvTAIL(littlestr) || (end_shift > 0))
1263 /* Ignore the trailing "\n". This code is not microoptimized */
1264 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1265 stop_pos = littleend - little; /* Actual littlestr len */
1270 && ((stop_pos == 1) || memEQ(big + 1, little, stop_pos - 1)))
1276 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1278 register U8 *a = (U8 *)s1;
1279 register U8 *b = (U8 *)s2;
1281 if (*a != *b && *a != PL_fold[*b])
1289 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1291 register U8 *a = (U8 *)s1;
1292 register U8 *b = (U8 *)s2;
1294 if (*a != *b && *a != PL_fold_locale[*b])
1301 /* copy a string to a safe spot */
1304 Perl_savepv(pTHX_ const char *sv)
1306 register char *newaddr;
1308 New(902,newaddr,strlen(sv)+1,char);
1309 (void)strcpy(newaddr,sv);
1313 /* same thing but with a known length */
1316 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1318 register char *newaddr;
1320 New(903,newaddr,len+1,char);
1321 Copy(sv,newaddr,len,char); /* might not be null terminated */
1322 newaddr[len] = '\0'; /* is now */
1326 /* the SV for Perl_form() and mess() is not kept in an arena */
1336 return sv_2mortal(newSVpvn("",0));
1341 /* Create as PVMG now, to avoid any upgrading later */
1342 New(905, sv, 1, SV);
1343 Newz(905, any, 1, XPVMG);
1344 SvFLAGS(sv) = SVt_PVMG;
1345 SvANY(sv) = (void*)any;
1346 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1351 #if defined(PERL_IMPLICIT_CONTEXT)
1353 Perl_form_nocontext(const char* pat, ...)
1358 va_start(args, pat);
1359 retval = vform(pat, &args);
1363 #endif /* PERL_IMPLICIT_CONTEXT */
1366 Perl_form(pTHX_ const char* pat, ...)
1370 va_start(args, pat);
1371 retval = vform(pat, &args);
1377 Perl_vform(pTHX_ const char *pat, va_list *args)
1379 SV *sv = mess_alloc();
1380 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1385 Perl_mess(pTHX_ const char *pat, va_list *args)
1387 SV *sv = mess_alloc();
1388 static char dgd[] = " during global destruction.\n";
1390 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1391 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1394 if (PL_curcop->cop_line)
1395 Perl_sv_catpvf(aTHX_ sv, " at %_ line %" PERL_PRId64,
1396 GvSV(PL_curcop->cop_filegv), (IV)PL_curcop->cop_line);
1398 if (PL_curcop->cop_line)
1399 Perl_sv_catpvf(aTHX_ sv, " at %_ line %ld",
1400 GvSV(PL_curcop->cop_filegv), (long)PL_curcop->cop_line);
1402 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1403 bool line_mode = (RsSIMPLE(PL_rs) &&
1404 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1406 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %" PERL_PRId64,
1407 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1408 line_mode ? "line" : "chunk",
1409 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1411 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %ld",
1412 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1413 line_mode ? "line" : "chunk",
1414 (long)IoLINES(GvIOp(PL_last_in_gv)));
1419 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1421 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1427 Perl_vdie(pTHX_ const char* pat, va_list *args)
1431 int was_in_eval = PL_in_eval;
1438 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1439 "%p: die: curstack = %p, mainstack = %p\n",
1440 thr, PL_curstack, PL_mainstack));
1443 msv = mess(pat, args);
1444 message = SvPV(msv,msglen);
1450 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1451 "%p: die: message = %s\ndiehook = %p\n",
1452 thr, message, PL_diehook));
1454 /* sv_2cv might call Perl_croak() */
1455 SV *olddiehook = PL_diehook;
1457 SAVESPTR(PL_diehook);
1458 PL_diehook = Nullsv;
1459 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1461 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1467 msg = newSVpvn(message, msglen);
1475 PUSHSTACKi(PERLSI_DIEHOOK);
1479 /* HACK - REVISIT - avoid CATCH_SET(TRUE) in call_sv()
1480 or we come back here due to a JMPENV_JMP() and do
1481 a POPSTACK - but die_where() will have already done
1482 one as it unwound - NI-S 1999/08/14 */
1483 call_sv((SV*)cv, G_DISCARD|G_NOCATCH);
1489 PL_restartop = die_where(message, msglen);
1490 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1491 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1492 thr, PL_restartop, was_in_eval, PL_top_env));
1493 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1495 return PL_restartop;
1498 #if defined(PERL_IMPLICIT_CONTEXT)
1500 Perl_die_nocontext(const char* pat, ...)
1505 va_start(args, pat);
1506 o = vdie(pat, &args);
1510 #endif /* PERL_IMPLICIT_CONTEXT */
1513 Perl_die(pTHX_ const char* pat, ...)
1517 va_start(args, pat);
1518 o = vdie(pat, &args);
1524 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1534 msv = mess(pat, args);
1535 message = SvPV(msv,msglen);
1536 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1538 /* sv_2cv might call Perl_croak() */
1539 SV *olddiehook = PL_diehook;
1541 SAVESPTR(PL_diehook);
1542 PL_diehook = Nullsv;
1543 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1545 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1550 msg = newSVpvn(message, msglen);
1554 PUSHSTACKi(PERLSI_DIEHOOK);
1558 call_sv((SV*)cv, G_DISCARD);
1564 PL_restartop = die_where(message, msglen);
1569 /* SFIO can really mess with your errno */
1572 PerlIO_write(PerlIO_stderr(), message, msglen);
1573 (void)PerlIO_flush(PerlIO_stderr());
1581 #if defined(PERL_IMPLICIT_CONTEXT)
1583 Perl_croak_nocontext(const char *pat, ...)
1587 va_start(args, pat);
1592 #endif /* PERL_IMPLICIT_CONTEXT */
1595 Perl_croak(pTHX_ const char *pat, ...)
1598 va_start(args, pat);
1605 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1614 msv = mess(pat, args);
1615 message = SvPV(msv, msglen);
1618 /* sv_2cv might call Perl_warn() */
1620 SV *oldwarnhook = PL_warnhook;
1622 SAVESPTR(PL_warnhook);
1623 PL_warnhook = Nullsv;
1624 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1626 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1631 msg = newSVpvn(message, msglen);
1635 PUSHSTACKi(PERLSI_WARNHOOK);
1639 call_sv((SV*)cv, G_DISCARD);
1645 PerlIO_write(PerlIO_stderr(), message, msglen);
1647 DEBUG_L(*message == '!'
1648 ? (xstat(message[1]=='!'
1649 ? (message[2]=='!' ? 2 : 1)
1654 (void)PerlIO_flush(PerlIO_stderr());
1657 #if defined(PERL_IMPLICIT_CONTEXT)
1659 Perl_warn_nocontext(const char *pat, ...)
1663 va_start(args, pat);
1667 #endif /* PERL_IMPLICIT_CONTEXT */
1670 Perl_warn(pTHX_ const char *pat, ...)
1673 va_start(args, pat);
1678 #if defined(PERL_IMPLICIT_CONTEXT)
1680 Perl_warner_nocontext(U32 err, const char *pat, ...)
1684 va_start(args, pat);
1685 vwarner(err, pat, &args);
1688 #endif /* PERL_IMPLICIT_CONTEXT */
1691 Perl_warner(pTHX_ U32 err, const char* pat,...)
1694 va_start(args, pat);
1695 vwarner(err, pat, &args);
1700 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1710 msv = mess(pat, args);
1711 message = SvPV(msv, msglen);
1715 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1716 #endif /* USE_THREADS */
1718 /* sv_2cv might call Perl_croak() */
1719 SV *olddiehook = PL_diehook;
1721 SAVESPTR(PL_diehook);
1722 PL_diehook = Nullsv;
1723 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1725 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1730 msg = newSVpvn(message, msglen);
1737 call_sv((SV*)cv, G_DISCARD);
1743 PL_restartop = die_where(message, msglen);
1746 PerlIO_write(PerlIO_stderr(), message, msglen);
1747 (void)PerlIO_flush(PerlIO_stderr());
1753 /* sv_2cv might call Perl_warn() */
1755 SV *oldwarnhook = PL_warnhook;
1757 SAVESPTR(PL_warnhook);
1758 PL_warnhook = Nullsv;
1759 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1761 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1766 msg = newSVpvn(message, msglen);
1773 call_sv((SV*)cv, G_DISCARD);
1779 PerlIO_write(PerlIO_stderr(), message, msglen);
1783 (void)PerlIO_flush(PerlIO_stderr());
1787 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1788 #if !defined(WIN32) && !defined(CYGWIN)
1790 Perl_my_setenv(pTHX_ char *nam, char *val)
1792 #ifndef PERL_USE_SAFE_PUTENV
1793 /* most putenv()s leak, so we manipulate environ directly */
1794 register I32 i=setenv_getix(nam); /* where does it go? */
1796 if (environ == PL_origenviron) { /* need we copy environment? */
1802 for (max = i; environ[max]; max++) ;
1803 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1804 for (j=0; j<max; j++) { /* copy environment */
1805 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1806 strcpy(tmpenv[j], environ[j]);
1808 tmpenv[max] = Nullch;
1809 environ = tmpenv; /* tell exec where it is now */
1812 safesysfree(environ[i]);
1813 while (environ[i]) {
1814 environ[i] = environ[i+1];
1819 if (!environ[i]) { /* does not exist yet */
1820 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1821 environ[i+1] = Nullch; /* make sure it's null terminated */
1824 safesysfree(environ[i]);
1825 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1828 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1830 /* MS-DOS requires environment variable names to be in uppercase */
1831 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1832 * some utilities and applications may break because they only look
1833 * for upper case strings. (Fixed strupr() bug here.)]
1835 strcpy(environ[i],nam); strupr(environ[i]);
1836 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1839 #else /* PERL_USE_SAFE_PUTENV */
1842 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1844 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1846 strcpy(new_env,nam); strupr(new_env);
1847 (void)sprintf(new_env + strlen(nam),"=%s",val);
1849 (void)putenv(new_env);
1850 #endif /* PERL_USE_SAFE_PUTENV */
1853 #else /* WIN32 || CYGWIN */
1856 * Save environ of perl.exe, currently Cygwin links in separate environ's
1857 * for each exe/dll. Probably should be a member of impure_ptr.
1859 static char ***Perl_main_environ;
1862 Perl_my_setenv_init(char ***penviron)
1864 Perl_main_environ = penviron;
1868 my_setenv(char *nam, char *val)
1870 /* You can not directly manipulate the environ[] array because
1871 * the routines do some additional work that syncs the Cygwin
1872 * environment with the Windows environment.
1874 char *oldstr = environ[setenv_getix(nam)];
1883 setenv(nam, val, 1);
1884 environ = *Perl_main_environ; /* environ realloc can occur in setenv */
1885 if(oldstr && environ[setenv_getix(nam)] != oldstr)
1888 #else /* if WIN32 */
1891 Perl_my_setenv(pTHX_ char *nam,char *val)
1894 #ifdef USE_WIN32_RTL_ENV
1896 register char *envstr;
1897 STRLEN namlen = strlen(nam);
1899 char *oldstr = environ[setenv_getix(nam)];
1901 /* putenv() has totally broken semantics in both the Borland
1902 * and Microsoft CRTLs. They either store the passed pointer in
1903 * the environment without making a copy, or make a copy and don't
1904 * free it. And on top of that, they dont free() old entries that
1905 * are being replaced/deleted. This means the caller must
1906 * free any old entries somehow, or we end up with a memory
1907 * leak every time my_setenv() is called. One might think
1908 * one could directly manipulate environ[], like the UNIX code
1909 * above, but direct changes to environ are not allowed when
1910 * calling putenv(), since the RTLs maintain an internal
1911 * *copy* of environ[]. Bad, bad, *bad* stink.
1922 vallen = strlen(val);
1923 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
1924 (void)sprintf(envstr,"%s=%s",nam,val);
1925 (void)PerlEnv_putenv(envstr);
1927 safesysfree(oldstr);
1929 safesysfree(envstr); /* MSVCRT leaks without this */
1932 #else /* !USE_WIN32_RTL_ENV */
1934 register char *envstr;
1935 STRLEN len = strlen(nam) + 3;
1940 New(904, envstr, len, char);
1941 (void)sprintf(envstr,"%s=%s",nam,val);
1942 (void)PerlEnv_putenv(envstr);
1952 Perl_setenv_getix(pTHX_ char *nam)
1954 register I32 i, len = strlen(nam);
1956 for (i = 0; environ[i]; i++) {
1959 strnicmp(environ[i],nam,len) == 0
1961 strnEQ(environ[i],nam,len)
1963 && environ[i][len] == '=')
1964 break; /* strnEQ must come first to avoid */
1965 } /* potential SEGV's */
1971 #ifdef UNLINK_ALL_VERSIONS
1973 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1977 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1982 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1984 Perl_my_bcopy(pTHX_ register const char *from,register char *to,register I32 len)
1988 if (from - to >= 0) {
1996 *(--to) = *(--from);
2004 Perl_my_memset(pTHX_ register char *loc, register I32 ch, register I32 len)
2014 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2016 Perl_my_bzero(pTHX_ register char *loc, register I32 len)
2026 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2028 Perl_my_memcmp(pTHX_ const char *s1, const char *s2, register I32 len)
2030 register U8 *a = (U8 *)s1;
2031 register U8 *b = (U8 *)s2;
2035 if (tmp = *a++ - *b++)
2040 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2044 #ifdef USE_CHAR_VSPRINTF
2049 vsprintf(char *dest, const char *pat, char *args)
2053 fakebuf._ptr = dest;
2054 fakebuf._cnt = 32767;
2058 fakebuf._flag = _IOWRT|_IOSTRG;
2059 _doprnt(pat, args, &fakebuf); /* what a kludge */
2060 (void)putc('\0', &fakebuf);
2061 #ifdef USE_CHAR_VSPRINTF
2064 return 0; /* perl doesn't use return value */
2068 #endif /* HAS_VPRINTF */
2071 #if BYTEORDER != 0x4321
2073 Perl_my_swap(pTHX_ short s)
2075 #if (BYTEORDER & 1) == 0
2078 result = ((s & 255) << 8) + ((s >> 8) & 255);
2086 Perl_my_htonl(pTHX_ long l)
2090 char c[sizeof(long)];
2093 #if BYTEORDER == 0x1234
2094 u.c[0] = (l >> 24) & 255;
2095 u.c[1] = (l >> 16) & 255;
2096 u.c[2] = (l >> 8) & 255;
2100 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2101 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2106 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2107 u.c[o & 0xf] = (l >> s) & 255;
2115 Perl_my_ntohl(pTHX_ long l)
2119 char c[sizeof(long)];
2122 #if BYTEORDER == 0x1234
2123 u.c[0] = (l >> 24) & 255;
2124 u.c[1] = (l >> 16) & 255;
2125 u.c[2] = (l >> 8) & 255;
2129 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2130 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2137 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2138 l |= (u.c[o & 0xf] & 255) << s;
2145 #endif /* BYTEORDER != 0x4321 */
2149 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2150 * If these functions are defined,
2151 * the BYTEORDER is neither 0x1234 nor 0x4321.
2152 * However, this is not assumed.
2156 #define HTOV(name,type) \
2158 name (register type n) \
2162 char c[sizeof(type)]; \
2166 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2167 u.c[i] = (n >> s) & 0xFF; \
2172 #define VTOH(name,type) \
2174 name (register type n) \
2178 char c[sizeof(type)]; \
2184 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2185 n += (u.c[i] & 0xFF) << s; \
2190 #if defined(HAS_HTOVS) && !defined(htovs)
2193 #if defined(HAS_HTOVL) && !defined(htovl)
2196 #if defined(HAS_VTOHS) && !defined(vtohs)
2199 #if defined(HAS_VTOHL) && !defined(vtohl)
2203 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2204 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC)
2206 Perl_my_popen(pTHX_ char *cmd, char *mode)
2209 register I32 This, that;
2212 I32 doexec = strNE(cmd,"-");
2216 PERL_FLUSHALL_FOR_CHILD;
2219 return my_syspopen(cmd,mode);
2222 This = (*mode == 'w');
2224 if (doexec && PL_tainting) {
2226 taint_proper("Insecure %s%s", "EXEC");
2228 if (PerlProc_pipe(p) < 0)
2230 if (doexec && PerlProc_pipe(pp) >= 0)
2232 while ((pid = (doexec?vfork():fork())) < 0) {
2233 if (errno != EAGAIN) {
2234 PerlLIO_close(p[This]);
2236 PerlLIO_close(pp[0]);
2237 PerlLIO_close(pp[1]);
2240 Perl_croak(aTHX_ "Can't fork");
2252 PerlLIO_close(p[THAT]);
2254 PerlLIO_close(pp[0]);
2255 #if defined(HAS_FCNTL) && defined(F_SETFD)
2256 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2259 if (p[THIS] != (*mode == 'r')) {
2260 PerlLIO_dup2(p[THIS], *mode == 'r');
2261 PerlLIO_close(p[THIS]);
2265 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2271 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2275 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2278 #endif /* defined OS2 */
2280 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2281 sv_setiv(GvSV(tmpgv), (IV)getpid());
2283 hv_clear(PL_pidstatus); /* we have no children */
2288 do_execfree(); /* free any memory malloced by child on vfork */
2289 PerlLIO_close(p[that]);
2291 PerlLIO_close(pp[1]);
2292 if (p[that] < p[This]) {
2293 PerlLIO_dup2(p[This], p[that]);
2294 PerlLIO_close(p[This]);
2297 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2298 (void)SvUPGRADE(sv,SVt_IV);
2300 PL_forkprocess = pid;
2301 if (did_pipes && pid > 0) {
2305 while (n < sizeof(int)) {
2306 n1 = PerlLIO_read(pp[0],
2307 (void*)(((char*)&errkid)+n),
2313 PerlLIO_close(pp[0]);
2315 if (n) { /* Error */
2316 if (n != sizeof(int))
2317 Perl_croak(aTHX_ "panic: kid popen errno read");
2318 errno = errkid; /* Propagate errno from kid */
2323 PerlLIO_close(pp[0]);
2324 return PerlIO_fdopen(p[This], mode);
2327 #if defined(atarist) || defined(DJGPP)
2330 Perl_my_popen(pTHX_ char *cmd, char *mode)
2332 /* Needs work for PerlIO ! */
2333 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
2334 PERL_FLUSHALL_FOR_CHILD;
2335 return popen(PerlIO_exportFILE(cmd, 0), mode);
2339 #endif /* !DOSISH */
2343 Perl_dump_fds(pTHX_ char *s)
2346 struct stat tmpstatbuf;
2348 PerlIO_printf(PerlIO_stderr(),"%s", s);
2349 for (fd = 0; fd < 32; fd++) {
2350 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2351 PerlIO_printf(PerlIO_stderr()," %d",fd);
2353 PerlIO_printf(PerlIO_stderr(),"\n");
2355 #endif /* DUMP_FDS */
2359 dup2(int oldfd, int newfd)
2361 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2364 PerlLIO_close(newfd);
2365 return fcntl(oldfd, F_DUPFD, newfd);
2367 #define DUP2_MAX_FDS 256
2368 int fdtmp[DUP2_MAX_FDS];
2374 PerlLIO_close(newfd);
2375 /* good enough for low fd's... */
2376 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2377 if (fdx >= DUP2_MAX_FDS) {
2385 PerlLIO_close(fdtmp[--fdx]);
2392 #ifdef HAS_SIGACTION
2395 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2397 struct sigaction act, oact;
2399 act.sa_handler = handler;
2400 sigemptyset(&act.sa_mask);
2403 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2406 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2407 act.sa_flags |= SA_NOCLDWAIT;
2409 if (sigaction(signo, &act, &oact) == -1)
2412 return oact.sa_handler;
2416 Perl_rsignal_state(pTHX_ int signo)
2418 struct sigaction oact;
2420 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2423 return oact.sa_handler;
2427 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2429 struct sigaction act;
2431 act.sa_handler = handler;
2432 sigemptyset(&act.sa_mask);
2435 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2438 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2439 act.sa_flags |= SA_NOCLDWAIT;
2441 return sigaction(signo, &act, save);
2445 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2447 return sigaction(signo, save, (struct sigaction *)NULL);
2450 #else /* !HAS_SIGACTION */
2453 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2455 return PerlProc_signal(signo, handler);
2458 static int sig_trapped;
2468 Perl_rsignal_state(pTHX_ int signo)
2470 Sighandler_t oldsig;
2473 oldsig = PerlProc_signal(signo, sig_trap);
2474 PerlProc_signal(signo, oldsig);
2476 PerlProc_kill(getpid(), signo);
2481 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2483 *save = PerlProc_signal(signo, handler);
2484 return (*save == SIG_ERR) ? -1 : 0;
2488 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2490 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2493 #endif /* !HAS_SIGACTION */
2495 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2496 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC)
2498 Perl_my_pclose(pTHX_ PerlIO *ptr)
2500 Sigsave_t hstat, istat, qstat;
2508 int saved_vaxc_errno;
2511 int saved_win32_errno;
2514 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2515 pid = (int)SvIVX(*svp);
2517 *svp = &PL_sv_undef;
2519 if (pid == -1) { /* Opened by popen. */
2520 return my_syspclose(ptr);
2523 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2524 saved_errno = errno;
2526 saved_vaxc_errno = vaxc$errno;
2529 saved_win32_errno = GetLastError();
2533 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2535 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2536 rsignal_save(SIGINT, SIG_IGN, &istat);
2537 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2539 pid2 = wait4pid(pid, &status, 0);
2540 } while (pid2 == -1 && errno == EINTR);
2541 rsignal_restore(SIGHUP, &hstat);
2542 rsignal_restore(SIGINT, &istat);
2543 rsignal_restore(SIGQUIT, &qstat);
2545 SETERRNO(saved_errno, saved_vaxc_errno);
2548 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2550 #endif /* !DOSISH */
2552 #if !defined(DOSISH) || defined(OS2) || defined(WIN32)
2554 Perl_wait4pid(pTHX_ int pid, int *statusp, int flags)
2558 char spid[TYPE_CHARS(int)];
2563 sprintf(spid, "%d", pid);
2564 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2565 if (svp && *svp != &PL_sv_undef) {
2566 *statusp = SvIVX(*svp);
2567 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2574 hv_iterinit(PL_pidstatus);
2575 if (entry = hv_iternext(PL_pidstatus)) {
2576 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2577 sv = hv_iterval(PL_pidstatus,entry);
2578 *statusp = SvIVX(sv);
2579 sprintf(spid, "%d", pid);
2580 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2585 # ifdef HAS_WAITPID_RUNTIME
2586 if (!HAS_WAITPID_RUNTIME)
2589 return PerlProc_waitpid(pid,statusp,flags);
2591 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2592 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2594 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2599 Perl_croak(aTHX_ "Can't do waitpid with flags");
2601 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2602 pidgone(result,*statusp);
2610 #endif /* !DOSISH || OS2 || WIN32 */
2614 Perl_pidgone(pTHX_ int pid, int status)
2617 char spid[TYPE_CHARS(int)];
2619 sprintf(spid, "%d", pid);
2620 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2621 (void)SvUPGRADE(sv,SVt_IV);
2626 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2629 int /* Cannot prototype with I32
2631 my_syspclose(PerlIO *ptr)
2634 Perl_my_pclose(pTHX_ PerlIO *ptr)
2637 /* Needs work for PerlIO ! */
2638 FILE *f = PerlIO_findFILE(ptr);
2639 I32 result = pclose(f);
2640 PerlIO_releaseFILE(ptr,f);
2646 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2649 register const char *frombase = from;
2652 register const char c = *from;
2657 while (count-- > 0) {
2658 for (todo = len; todo > 0; todo--) {
2666 Perl_cast_ulong(pTHX_ NV f)
2671 # define BIGDOUBLE 2147483648.0
2673 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2676 return (unsigned long)f;
2678 return (unsigned long)along;
2682 /* Unfortunately, on some systems the cast_uv() function doesn't
2683 work with the system-supplied definition of ULONG_MAX. The
2684 comparison (f >= ULONG_MAX) always comes out true. It must be a
2685 problem with the compiler constant folding.
2687 In any case, this workaround should be fine on any two's complement
2688 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2690 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2693 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2695 -- Kenneth Albanowski <kjahds@kjahds.com>
2699 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2703 Perl_cast_i32(pTHX_ NV f)
2706 return (I32) I32_MAX;
2708 return (I32) I32_MIN;
2713 Perl_cast_iv(pTHX_ NV f)
2718 if (f >= (NV)UV_MAX)
2729 Perl_cast_uv(pTHX_ NV f)
2732 return (UV) MY_UV_MAX;
2746 Perl_same_dirent(pTHX_ char *a, char *b)
2748 char *fa = strrchr(a,'/');
2749 char *fb = strrchr(b,'/');
2750 struct stat tmpstatbuf1;
2751 struct stat tmpstatbuf2;
2752 SV *tmpsv = sv_newmortal();
2765 sv_setpv(tmpsv, ".");
2767 sv_setpvn(tmpsv, a, fa - a);
2768 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2771 sv_setpv(tmpsv, ".");
2773 sv_setpvn(tmpsv, b, fb - b);
2774 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2776 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2777 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2779 #endif /* !HAS_RENAME */
2782 Perl_scan_bin(pTHX_ char *start, I32 len, I32 *retlen)
2784 register char *s = start;
2785 register NV rnv = 0.0;
2786 register UV ruv = 0;
2787 register bool seenb = FALSE;
2788 register bool overflowed = FALSE;
2790 for (; len-- && *s; s++) {
2791 if (!(*s == '0' || *s == '1')) {
2793 continue; /* Note: does not check for __ and the like. */
2794 if (seenb == FALSE && *s == 'b' && ruv == 0) {
2795 /* Disallow 0bbb0b0bbb... */
2801 if (ckWARN(WARN_UNSAFE))
2802 Perl_warner(aTHX_ WARN_UNSAFE,
2803 "Illegal binary digit '%c' ignored", *s);
2808 register UV xuv = ruv << 1;
2810 if ((xuv >> 1) != ruv) {
2814 if (ckWARN_d(WARN_UNSAFE))
2815 Perl_warner(aTHX_ WARN_UNSAFE,
2816 "Integer overflow in binary number");
2818 ruv = xuv | (*s - '0');
2822 /* If an NV has not enough bits in its mantissa to
2823 * represent an UV this summing of small low-order numbers
2824 * is a waste of time (because the NV cannot preserve
2825 * the low-order bits anyway): we could just remember when
2826 * did we overflow and in the end just multiply rnv by the
2833 if ( ( overflowed && rnv > 4294967295.0)
2835 || (!overflowed && ruv > 0xffffffff )
2839 if (ckWARN(WARN_UNSAFE))
2840 Perl_warner(aTHX_ WARN_UNSAFE,
2841 "Binary number > 0b11111111111111111111111111111111 non-portable");
2843 *retlen = s - start;
2848 Perl_scan_oct(pTHX_ char *start, I32 len, I32 *retlen)
2850 register char *s = start;
2851 register NV rnv = 0.0;
2852 register UV ruv = 0;
2853 register bool overflowed = FALSE;
2855 for (; len-- && *s; s++) {
2856 if (!(*s >= '0' && *s <= '7')) {
2858 continue; /* Note: does not check for __ and the like. */
2860 /* Allow \octal to work the DWIM way (that is, stop scanning
2861 * as soon as non-octal characters are seen, complain only iff
2862 * someone seems to want to use the digits eight and nine). */
2863 if (*s == '8' || *s == '9') {
2865 if (ckWARN(WARN_OCTAL))
2866 Perl_warner(aTHX_ WARN_OCTAL,
2867 "Illegal octal digit '%c' ignored", *s);
2873 register UV xuv = ruv << 3;
2875 if ((xuv >> 3) != ruv) {
2879 if (ckWARN_d(WARN_UNSAFE))
2880 Perl_warner(aTHX_ WARN_UNSAFE,
2881 "Integer overflow in octal number");
2883 ruv = xuv | (*s - '0');
2887 /* If an NV has not enough bits in its mantissa to
2888 * represent an UV this summing of small low-order numbers
2889 * is a waste of time (because the NV cannot preserve
2890 * the low-order bits anyway): we could just remember when
2891 * did we overflow and in the end just multiply rnv by the
2892 * right amount of 8-tuples. */
2893 rnv += (NV)(*s - '0');
2898 if ( ( overflowed && rnv > 4294967295.0)
2900 || (!overflowed && ruv > 0xffffffff )
2904 if (ckWARN(WARN_UNSAFE))
2905 Perl_warner(aTHX_ WARN_UNSAFE,
2906 "Octal number > 037777777777 non-portable");
2908 *retlen = s - start;
2913 Perl_scan_hex(pTHX_ char *start, I32 len, I32 *retlen)
2915 register char *s = start;
2916 register NV rnv = 0.0;
2917 register UV ruv = 0;
2918 register bool seenx = FALSE;
2919 register bool overflowed = FALSE;
2922 for (; len-- && *s; s++) {
2923 hexdigit = strchr((char *) PL_hexdigit, *s);
2926 continue; /* Note: does not check for __ and the like. */
2927 if (seenx == FALSE && *s == 'x' && ruv == 0) {
2928 /* Disallow 0xxx0x0xxx... */
2934 if (ckWARN(WARN_UNSAFE))
2935 Perl_warner(aTHX_ WARN_UNSAFE,
2936 "Illegal hexadecimal digit '%c' ignored", *s);
2941 register UV xuv = ruv << 4;
2943 if ((xuv >> 4) != ruv) {
2947 if (ckWARN_d(WARN_UNSAFE))
2948 Perl_warner(aTHX_ WARN_UNSAFE,
2949 "Integer overflow in hexadecimal number");
2951 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
2955 /* If an NV has not enough bits in its mantissa to
2956 * represent an UV this summing of small low-order numbers
2957 * is a waste of time (because the NV cannot preserve
2958 * the low-order bits anyway): we could just remember when
2959 * did we overflow and in the end just multiply rnv by the
2960 * right amount of 16-tuples. */
2961 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
2966 if ( ( overflowed && rnv > 4294967295.0)
2968 || (!overflowed && ruv > 0xffffffff )
2972 if (ckWARN(WARN_UNSAFE))
2973 Perl_warner(aTHX_ WARN_UNSAFE,
2974 "Hexadecimal number > 0xffffffff non-portable");
2976 *retlen = s - start;
2981 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2984 char *xfound = Nullch;
2985 char *xfailed = Nullch;
2986 char tmpbuf[MAXPATHLEN];
2990 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2991 # define SEARCH_EXTS ".bat", ".cmd", NULL
2992 # define MAX_EXT_LEN 4
2995 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2996 # define MAX_EXT_LEN 4
2999 # define SEARCH_EXTS ".pl", ".com", NULL
3000 # define MAX_EXT_LEN 4
3002 /* additional extensions to try in each dir if scriptname not found */
3004 char *exts[] = { SEARCH_EXTS };
3005 char **ext = search_ext ? search_ext : exts;
3006 int extidx = 0, i = 0;
3007 char *curext = Nullch;
3009 # define MAX_EXT_LEN 0
3013 * If dosearch is true and if scriptname does not contain path
3014 * delimiters, search the PATH for scriptname.
3016 * If SEARCH_EXTS is also defined, will look for each
3017 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3018 * while searching the PATH.
3020 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3021 * proceeds as follows:
3022 * If DOSISH or VMSISH:
3023 * + look for ./scriptname{,.foo,.bar}
3024 * + search the PATH for scriptname{,.foo,.bar}
3027 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3028 * this will not look in '.' if it's not in the PATH)
3033 # ifdef ALWAYS_DEFTYPES
3034 len = strlen(scriptname);
3035 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3036 int hasdir, idx = 0, deftypes = 1;
3039 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3042 int hasdir, idx = 0, deftypes = 1;
3045 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3047 /* The first time through, just add SEARCH_EXTS to whatever we
3048 * already have, so we can check for default file types. */
3050 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3056 if ((strlen(tmpbuf) + strlen(scriptname)
3057 + MAX_EXT_LEN) >= sizeof tmpbuf)
3058 continue; /* don't search dir with too-long name */
3059 strcat(tmpbuf, scriptname);
3063 if (strEQ(scriptname, "-"))
3065 if (dosearch) { /* Look in '.' first. */
3066 char *cur = scriptname;
3068 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3070 if (strEQ(ext[i++],curext)) {
3071 extidx = -1; /* already has an ext */
3076 DEBUG_p(PerlIO_printf(Perl_debug_log,
3077 "Looking for %s\n",cur));
3078 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3079 && !S_ISDIR(PL_statbuf.st_mode)) {
3087 if (cur == scriptname) {
3088 len = strlen(scriptname);
3089 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3091 cur = strcpy(tmpbuf, scriptname);
3093 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3094 && strcpy(tmpbuf+len, ext[extidx++]));
3099 if (dosearch && !strchr(scriptname, '/')
3101 && !strchr(scriptname, '\\')
3103 && (s = PerlEnv_getenv("PATH"))) {
3106 PL_bufend = s + strlen(s);
3107 while (s < PL_bufend) {
3108 #if defined(atarist) || defined(DOSISH)
3113 && *s != ';'; len++, s++) {
3114 if (len < sizeof tmpbuf)
3117 if (len < sizeof tmpbuf)
3119 #else /* ! (atarist || DOSISH) */
3120 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3123 #endif /* ! (atarist || DOSISH) */
3126 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3127 continue; /* don't search dir with too-long name */
3129 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3130 && tmpbuf[len - 1] != '/'
3131 && tmpbuf[len - 1] != '\\'
3134 tmpbuf[len++] = '/';
3135 if (len == 2 && tmpbuf[0] == '.')
3137 (void)strcpy(tmpbuf + len, scriptname);
3141 len = strlen(tmpbuf);
3142 if (extidx > 0) /* reset after previous loop */
3146 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3147 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3148 if (S_ISDIR(PL_statbuf.st_mode)) {
3152 } while ( retval < 0 /* not there */
3153 && extidx>=0 && ext[extidx] /* try an extension? */
3154 && strcpy(tmpbuf+len, ext[extidx++])
3159 if (S_ISREG(PL_statbuf.st_mode)
3160 && cando(S_IRUSR,TRUE,&PL_statbuf)
3162 && cando(S_IXUSR,TRUE,&PL_statbuf)
3166 xfound = tmpbuf; /* bingo! */
3170 xfailed = savepv(tmpbuf);
3173 if (!xfound && !seen_dot && !xfailed &&
3174 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3175 || S_ISDIR(PL_statbuf.st_mode)))
3177 seen_dot = 1; /* Disable message. */
3179 if (flags & 1) { /* do or die? */
3180 Perl_croak(aTHX_ "Can't %s %s%s%s",
3181 (xfailed ? "execute" : "find"),
3182 (xfailed ? xfailed : scriptname),
3183 (xfailed ? "" : " on PATH"),
3184 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3186 scriptname = Nullch;
3190 scriptname = xfound;
3192 return (scriptname ? savepv(scriptname) : Nullch);
3198 /* Very simplistic scheduler for now */
3202 thr = thr->i.next_run;
3206 Perl_cond_init(pTHX_ perl_cond *cp)
3212 Perl_cond_signal(pTHX_ perl_cond *cp)
3215 perl_cond cond = *cp;
3220 /* Insert t in the runnable queue just ahead of us */
3221 t->i.next_run = thr->i.next_run;
3222 thr->i.next_run->i.prev_run = t;
3223 t->i.prev_run = thr;
3224 thr->i.next_run = t;
3225 thr->i.wait_queue = 0;
3226 /* Remove from the wait queue */
3232 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3235 perl_cond cond, cond_next;
3237 for (cond = *cp; cond; cond = cond_next) {
3239 /* Insert t in the runnable queue just ahead of us */
3240 t->i.next_run = thr->i.next_run;
3241 thr->i.next_run->i.prev_run = t;
3242 t->i.prev_run = thr;
3243 thr->i.next_run = t;
3244 thr->i.wait_queue = 0;
3245 /* Remove from the wait queue */
3246 cond_next = cond->next;
3253 Perl_cond_wait(pTHX_ perl_cond *cp)
3257 if (thr->i.next_run == thr)
3258 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3260 New(666, cond, 1, struct perl_wait_queue);
3264 thr->i.wait_queue = cond;
3265 /* Remove ourselves from runnable queue */
3266 thr->i.next_run->i.prev_run = thr->i.prev_run;
3267 thr->i.prev_run->i.next_run = thr->i.next_run;
3269 #endif /* FAKE_THREADS */
3271 #ifdef PTHREAD_GETSPECIFIC_INT
3272 struct perl_thread *
3277 if (pthread_getspecific(PL_thr_key, &t))
3278 Perl_croak(aTHX_ "panic: pthread_getspecific");
3279 return (struct perl_thread *) t;
3284 Perl_condpair_magic(pTHX_ SV *sv)
3288 SvUPGRADE(sv, SVt_PVMG);
3289 mg = mg_find(sv, 'm');
3293 New(53, cp, 1, condpair_t);
3294 MUTEX_INIT(&cp->mutex);
3295 COND_INIT(&cp->owner_cond);
3296 COND_INIT(&cp->cond);
3298 MUTEX_LOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3299 mg = mg_find(sv, 'm');
3301 /* someone else beat us to initialising it */
3302 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3303 MUTEX_DESTROY(&cp->mutex);
3304 COND_DESTROY(&cp->owner_cond);
3305 COND_DESTROY(&cp->cond);
3309 sv_magic(sv, Nullsv, 'm', 0, 0);
3311 mg->mg_ptr = (char *)cp;
3312 mg->mg_len = sizeof(cp);
3313 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3314 DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
3315 "%p: condpair_magic %p\n", thr, sv));)
3322 * Make a new perl thread structure using t as a prototype. Some of the
3323 * fields for the new thread are copied from the prototype thread, t,
3324 * so t should not be running in perl at the time this function is
3325 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3326 * thread calling new_struct_thread) clearly satisfies this constraint.
3328 struct perl_thread *
3329 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3331 #if !defined(PERL_IMPLICIT_CONTEXT)
3332 struct perl_thread *thr;
3338 sv = newSVpvn("", 0);
3339 SvGROW(sv, sizeof(struct perl_thread) + 1);
3340 SvCUR_set(sv, sizeof(struct perl_thread));
3341 thr = (Thread) SvPVX(sv);
3343 memset(thr, 0xab, sizeof(struct perl_thread));
3350 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3352 Zero(thr, 1, struct perl_thread);
3355 PL_protect = MEMBER_TO_FPTR(Perl_default_protect);
3360 PL_curcop = &PL_compiling;
3361 thr->interp = t->interp;
3362 thr->cvcache = newHV();
3363 thr->threadsv = newAV();
3364 thr->specific = newAV();
3365 thr->errsv = newSVpvn("", 0);
3366 thr->errhv = newHV();
3367 thr->flags = THRf_R_JOINABLE;
3368 MUTEX_INIT(&thr->mutex);
3370 /* top_env needs to be non-zero. It points to an area
3371 in which longjmp() stuff is stored, as C callstack
3372 info there at least is thread specific this has to
3373 be per-thread. Otherwise a 'die' in a thread gives
3374 that thread the C stack of last thread to do an eval {}!
3375 See comments in scope.h
3376 Initialize top entry (as in perl.c for main thread)
3378 PL_start_env.je_prev = NULL;
3379 PL_start_env.je_ret = -1;
3380 PL_start_env.je_mustcatch = TRUE;
3381 PL_top_env = &PL_start_env;
3383 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR) */
3386 PL_statname = NEWSV(66,0);
3388 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3389 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3390 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3391 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3392 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3394 PL_reginterp_cnt = 0;
3395 PL_lastscream = Nullsv;
3398 PL_reg_start_tmp = 0;
3399 PL_reg_start_tmpl = 0;
3400 PL_reg_poscache = Nullch;
3402 /* parent thread's data needs to be locked while we make copy */
3403 MUTEX_LOCK(&t->mutex);
3405 PL_protect = t->Tprotect;
3407 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3408 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3409 PL_curstash = t->Tcurstash; /* always be set to main? */
3411 PL_tainted = t->Ttainted;
3412 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3413 PL_nrs = newSVsv(t->Tnrs);
3414 PL_rs = SvREFCNT_inc(PL_nrs);
3415 PL_last_in_gv = Nullgv;
3416 PL_ofslen = t->Tofslen;
3417 PL_ofs = savepvn(t->Tofs, PL_ofslen);
3418 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3419 PL_chopset = t->Tchopset;
3420 PL_formtarget = newSVsv(t->Tformtarget);
3421 PL_bodytarget = newSVsv(t->Tbodytarget);
3422 PL_toptarget = newSVsv(t->Ttoptarget);
3424 /* Initialise all per-thread SVs that the template thread used */
3425 svp = AvARRAY(t->threadsv);
3426 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3427 if (*svp && *svp != &PL_sv_undef) {
3428 SV *sv = newSVsv(*svp);
3429 av_store(thr->threadsv, i, sv);
3430 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3431 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
3432 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
3435 thr->threadsvp = AvARRAY(thr->threadsv);
3437 MUTEX_LOCK(&PL_threads_mutex);
3439 thr->tid = ++PL_threadnum;
3440 thr->next = t->next;
3443 thr->next->prev = thr;
3444 MUTEX_UNLOCK(&PL_threads_mutex);
3446 /* done copying parent's state */
3447 MUTEX_UNLOCK(&t->mutex);
3449 #ifdef HAVE_THREAD_INTERN
3450 Perl_init_thread_intern(thr);
3451 #endif /* HAVE_THREAD_INTERN */
3454 #endif /* USE_THREADS */
3458 * This hack is to force load of "huge" support from libm.a
3459 * So it is in perl for (say) POSIX to use.
3460 * Needed for SunOS with Sun's 'acc' for example.
3469 #ifdef PERL_GLOBAL_STRUCT
3478 Perl_get_op_names(pTHX)
3484 Perl_get_op_descs(pTHX)
3490 Perl_get_no_modify(pTHX)
3492 return (char*)PL_no_modify;
3496 Perl_get_opargs(pTHX)
3502 Perl_get_ppaddr(pTHX)
3507 #ifndef HAS_GETENV_LEN
3509 Perl_getenv_len(pTHX_ char *env_elem, unsigned long *len)
3511 char *env_trans = PerlEnv_getenv(env_elem);
3513 *len = strlen(env_trans);
3520 Perl_get_vtbl(pTHX_ int vtbl_id)
3522 MGVTBL* result = Null(MGVTBL*);
3526 result = &PL_vtbl_sv;
3529 result = &PL_vtbl_env;
3531 case want_vtbl_envelem:
3532 result = &PL_vtbl_envelem;
3535 result = &PL_vtbl_sig;
3537 case want_vtbl_sigelem:
3538 result = &PL_vtbl_sigelem;
3540 case want_vtbl_pack:
3541 result = &PL_vtbl_pack;
3543 case want_vtbl_packelem:
3544 result = &PL_vtbl_packelem;
3546 case want_vtbl_dbline:
3547 result = &PL_vtbl_dbline;
3550 result = &PL_vtbl_isa;
3552 case want_vtbl_isaelem:
3553 result = &PL_vtbl_isaelem;
3555 case want_vtbl_arylen:
3556 result = &PL_vtbl_arylen;
3558 case want_vtbl_glob:
3559 result = &PL_vtbl_glob;
3561 case want_vtbl_mglob:
3562 result = &PL_vtbl_mglob;
3564 case want_vtbl_nkeys:
3565 result = &PL_vtbl_nkeys;
3567 case want_vtbl_taint:
3568 result = &PL_vtbl_taint;
3570 case want_vtbl_substr:
3571 result = &PL_vtbl_substr;
3574 result = &PL_vtbl_vec;
3577 result = &PL_vtbl_pos;
3580 result = &PL_vtbl_bm;
3583 result = &PL_vtbl_fm;
3585 case want_vtbl_uvar:
3586 result = &PL_vtbl_uvar;
3589 case want_vtbl_mutex:
3590 result = &PL_vtbl_mutex;
3593 case want_vtbl_defelem:
3594 result = &PL_vtbl_defelem;
3596 case want_vtbl_regexp:
3597 result = &PL_vtbl_regexp;
3599 case want_vtbl_regdata:
3600 result = &PL_vtbl_regdata;
3602 case want_vtbl_regdatum:
3603 result = &PL_vtbl_regdatum;
3605 #ifdef USE_LOCALE_COLLATE
3606 case want_vtbl_collxfrm:
3607 result = &PL_vtbl_collxfrm;
3610 case want_vtbl_amagic:
3611 result = &PL_vtbl_amagic;
3613 case want_vtbl_amagicelem:
3614 result = &PL_vtbl_amagicelem;
3616 case want_vtbl_backref:
3617 result = &PL_vtbl_backref;
3624 Perl_my_fflush_all(pTHX)
3627 return PerlIO_flush(NULL);
3630 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3631 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3632 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3634 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3635 open_max = sysconf(_SC_OPEN_MAX);
3638 open_max = FOPEN_MAX;
3641 open_max = OPEN_MAX;
3652 for (i = 0; i < open_max; i++)
3653 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3654 STDIO_STREAM_ARRAY[i]._file < open_max &&
3655 STDIO_STREAM_ARRAY[i]._flag)
3656 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3660 SETERRNO(EBADF,RMS$_IFI);
3666 Perl_my_atof(pTHX_ const char* s) {
3667 #ifdef USE_LOCALE_NUMERIC
3668 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3672 SET_NUMERIC_STANDARD();
3674 SET_NUMERIC_LOCAL();
3675 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
3680 return Perl_atof(s);
3682 return Perl_atof(s);