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.
81 #ifdef MACOS_TRADITIONAL
82 extern void * gSacrificialGoat;
83 #define MAC_CHECK_GOAT(p) if (!gSacrificialGoat && p) { PerlMem_free(p); p = NULL; } else
87 Perl_safesysmalloc(MEM_SIZE size)
93 PerlIO_printf(Perl_error_log,
94 "Allocation too large: %lx\n", size) FLUSH;
97 #endif /* HAS_64K_LIMIT */
100 Perl_croak_nocontext("panic: malloc");
102 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
103 #ifdef MACOS_TRADITIONAL
106 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05d) malloc %ld bytes\n",PTR2UV(ptr),PL_an++,(long)size));
112 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
119 /* paranoid version of system's realloc() */
122 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
126 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
127 Malloc_t PerlMem_realloc();
128 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
132 PerlIO_printf(Perl_error_log,
133 "Reallocation too large: %lx\n", size) FLUSH;
136 #endif /* HAS_64K_LIMIT */
143 return safesysmalloc(size);
146 Perl_croak_nocontext("panic: realloc");
148 ptr = PerlMem_realloc(where,size);
150 #ifdef MACOS_TRADITIONAL
154 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05d) rfree\n",PTR2UV(where),PL_an++));
155 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05d) realloc %ld bytes\n",PTR2UV(ptr),PL_an++,(long)size));
162 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
169 /* safe version of system's free() */
172 Perl_safesysfree(Malloc_t where)
175 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05d) free\n",PTR2UV(where),PL_an++));
182 /* safe version of system's calloc() */
185 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
191 if (size * count > 0xffff) {
192 PerlIO_printf(Perl_error_log,
193 "Allocation too large: %lx\n", size * count) FLUSH;
196 #endif /* HAS_64K_LIMIT */
198 if ((long)size < 0 || (long)count < 0)
199 Perl_croak_nocontext("panic: calloc");
202 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
203 #ifdef MACOS_TRADITIONAL
206 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05d) calloc %ld x %ld bytes\n",PTR2UV(ptr),PL_an++,(long)count,(long)size));
208 memset((void*)ptr, 0, size);
214 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
223 struct mem_test_strut {
231 # define ALIGN sizeof(struct mem_test_strut)
233 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
234 # define typeof_chunk(ch) \
235 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
236 # define set_typeof_chunk(ch,t) \
237 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
238 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
241 ? ((size) - 1)/8 + 5 \
245 Perl_safexmalloc(I32 x, MEM_SIZE size)
247 register char* where = (char*)safemalloc(size + ALIGN);
250 xycount[x][SIZE_TO_Y(size)]++;
251 set_typeof_chunk(where, x);
252 sizeof_chunk(where) = size;
253 return (Malloc_t)(where + ALIGN);
257 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
259 char *where = (char*)wh;
262 return safexmalloc(0,size);
265 MEM_SIZE old = sizeof_chunk(where - ALIGN);
266 int t = typeof_chunk(where - ALIGN);
267 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
269 xycount[t][SIZE_TO_Y(old)]--;
270 xycount[t][SIZE_TO_Y(size)]++;
271 xcount[t] += size - old;
272 sizeof_chunk(new) = size;
273 return (Malloc_t)(new + ALIGN);
278 Perl_safexfree(Malloc_t wh)
281 char *where = (char*)wh;
287 size = sizeof_chunk(where);
288 x = where[0] + 100 * where[1];
290 xycount[x][SIZE_TO_Y(size)]--;
295 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
297 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
299 xycount[x][SIZE_TO_Y(size)]++;
300 memset((void*)(where + ALIGN), 0, size * count);
301 set_typeof_chunk(where, x);
302 sizeof_chunk(where) = size;
303 return (Malloc_t)(where + ALIGN);
307 S_xstat(pTHX_ int flag)
309 register I32 i, j, total = 0;
310 I32 subtot[MAXYCOUNT];
312 for (j = 0; j < MAXYCOUNT; j++) {
316 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);
317 for (i = 0; i < MAXXCOUNT; i++) {
319 for (j = 0; j < MAXYCOUNT; j++) {
320 subtot[j] += xycount[i][j];
323 ? xcount[i] /* Have something */
325 ? xcount[i] != lastxcount[i] /* Changed */
326 : xcount[i] > lastxcount[i])) { /* Growed */
327 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
328 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
329 lastxcount[i] = xcount[i];
330 for (j = 0; j < MAXYCOUNT; j++) {
332 ? xycount[i][j] /* Have something */
334 ? xycount[i][j] != lastxycount[i][j] /* Changed */
335 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
336 PerlIO_printf(Perl_debug_log,"%3ld ",
338 ? xycount[i][j] - lastxycount[i][j]
340 lastxycount[i][j] = xycount[i][j];
342 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
345 PerlIO_printf(Perl_debug_log, "\n");
349 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
350 for (j = 0; j < MAXYCOUNT; j++) {
352 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
354 PerlIO_printf(Perl_debug_log, " . ");
357 PerlIO_printf(Perl_debug_log, "\n");
361 #endif /* LEAKTEST */
363 /* copy a string up to some (non-backslashed) delimiter, if any */
366 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
369 for (tolen = 0; from < fromend; from++, tolen++) {
371 if (from[1] == delim)
380 else if (*from == delim)
391 /* return ptr to little string in big string, NULL if not found */
392 /* This routine was donated by Corey Satten. */
395 Perl_instr(pTHX_ register const char *big, register const char *little)
397 register const char *s, *x;
408 for (x=big,s=little; *s; /**/ ) {
417 return (char*)(big-1);
422 /* same as instr but allow embedded nulls */
425 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
427 register const char *s, *x;
428 register I32 first = *little;
429 register const char *littleend = lend;
431 if (!first && little >= littleend)
433 if (bigend - big < littleend - little)
435 bigend -= littleend - little++;
436 while (big <= bigend) {
439 for (x=big,s=little; s < littleend; /**/ ) {
446 return (char*)(big-1);
451 /* reverse of the above--find last substring */
454 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
456 register const char *bigbeg;
457 register const char *s, *x;
458 register I32 first = *little;
459 register const char *littleend = lend;
461 if (!first && little >= littleend)
462 return (char*)bigend;
464 big = bigend - (littleend - little++);
465 while (big >= bigbeg) {
468 for (x=big+2,s=little; s < littleend; /**/ ) {
475 return (char*)(big+1);
481 * Set up for a new ctype locale.
484 Perl_new_ctype(pTHX_ const char *newctype)
486 #ifdef USE_LOCALE_CTYPE
490 for (i = 0; i < 256; i++) {
492 PL_fold_locale[i] = toLOWER_LC(i);
493 else if (isLOWER_LC(i))
494 PL_fold_locale[i] = toUPPER_LC(i);
496 PL_fold_locale[i] = i;
499 #endif /* USE_LOCALE_CTYPE */
503 * Set up for a new collation locale.
506 Perl_new_collate(pTHX_ const char *newcoll)
508 #ifdef USE_LOCALE_COLLATE
511 if (PL_collation_name) {
513 Safefree(PL_collation_name);
514 PL_collation_name = NULL;
515 PL_collation_standard = TRUE;
516 PL_collxfrm_base = 0;
517 PL_collxfrm_mult = 2;
522 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
524 Safefree(PL_collation_name);
525 PL_collation_name = savepv(newcoll);
526 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
529 /* 2: at most so many chars ('a', 'b'). */
530 /* 50: surely no system expands a char more. */
531 #define XFRMBUFSIZE (2 * 50)
532 char xbuf[XFRMBUFSIZE];
533 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
534 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
535 SSize_t mult = fb - fa;
537 Perl_croak(aTHX_ "strxfrm() gets absurd");
538 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
539 PL_collxfrm_mult = mult;
543 #endif /* USE_LOCALE_COLLATE */
547 Perl_set_numeric_radix(pTHX)
549 #ifdef USE_LOCALE_NUMERIC
550 # ifdef HAS_LOCALECONV
554 if (lc && lc->decimal_point)
555 /* We assume that decimal separator aka the radix
556 * character is always a single character. If it
557 * ever is a string, this needs to be rethunk. */
558 PL_numeric_radix = *lc->decimal_point;
560 PL_numeric_radix = 0;
561 # endif /* HAS_LOCALECONV */
562 #endif /* USE_LOCALE_NUMERIC */
566 * Set up for a new numeric locale.
569 Perl_new_numeric(pTHX_ const char *newnum)
571 #ifdef USE_LOCALE_NUMERIC
574 if (PL_numeric_name) {
575 Safefree(PL_numeric_name);
576 PL_numeric_name = NULL;
577 PL_numeric_standard = TRUE;
578 PL_numeric_local = TRUE;
583 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
584 Safefree(PL_numeric_name);
585 PL_numeric_name = savepv(newnum);
586 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
587 PL_numeric_local = TRUE;
591 #endif /* USE_LOCALE_NUMERIC */
595 Perl_set_numeric_standard(pTHX)
597 #ifdef USE_LOCALE_NUMERIC
599 if (! PL_numeric_standard) {
600 setlocale(LC_NUMERIC, "C");
601 PL_numeric_standard = TRUE;
602 PL_numeric_local = FALSE;
605 #endif /* USE_LOCALE_NUMERIC */
609 Perl_set_numeric_local(pTHX)
611 #ifdef USE_LOCALE_NUMERIC
613 if (! PL_numeric_local) {
614 setlocale(LC_NUMERIC, PL_numeric_name);
615 PL_numeric_standard = FALSE;
616 PL_numeric_local = TRUE;
620 #endif /* USE_LOCALE_NUMERIC */
624 * Initialize locale awareness.
627 Perl_init_i18nl10n(pTHX_ int printwarn)
631 * 1 = set ok or not applicable,
632 * 0 = fallback to C locale,
633 * -1 = fallback to C locale failed
638 #ifdef USE_LOCALE_CTYPE
639 char *curctype = NULL;
640 #endif /* USE_LOCALE_CTYPE */
641 #ifdef USE_LOCALE_COLLATE
642 char *curcoll = NULL;
643 #endif /* USE_LOCALE_COLLATE */
644 #ifdef USE_LOCALE_NUMERIC
646 #endif /* USE_LOCALE_NUMERIC */
648 char *language = PerlEnv_getenv("LANGUAGE");
650 char *lc_all = PerlEnv_getenv("LC_ALL");
651 char *lang = PerlEnv_getenv("LANG");
652 bool setlocale_failure = FALSE;
654 #ifdef LOCALE_ENVIRON_REQUIRED
657 * Ultrix setlocale(..., "") fails if there are no environment
658 * variables from which to get a locale name.
665 if (setlocale(LC_ALL, ""))
668 setlocale_failure = TRUE;
670 if (!setlocale_failure) {
671 #ifdef USE_LOCALE_CTYPE
674 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
676 setlocale_failure = TRUE;
677 #endif /* USE_LOCALE_CTYPE */
678 #ifdef USE_LOCALE_COLLATE
680 setlocale(LC_COLLATE,
681 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
683 setlocale_failure = TRUE;
684 #endif /* USE_LOCALE_COLLATE */
685 #ifdef USE_LOCALE_NUMERIC
687 setlocale(LC_NUMERIC,
688 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
690 setlocale_failure = TRUE;
691 #endif /* USE_LOCALE_NUMERIC */
696 #endif /* !LOCALE_ENVIRON_REQUIRED */
699 if (! setlocale(LC_ALL, ""))
700 setlocale_failure = TRUE;
703 if (!setlocale_failure) {
704 #ifdef USE_LOCALE_CTYPE
705 if (! (curctype = setlocale(LC_CTYPE, "")))
706 setlocale_failure = TRUE;
707 #endif /* USE_LOCALE_CTYPE */
708 #ifdef USE_LOCALE_COLLATE
709 if (! (curcoll = setlocale(LC_COLLATE, "")))
710 setlocale_failure = TRUE;
711 #endif /* USE_LOCALE_COLLATE */
712 #ifdef USE_LOCALE_NUMERIC
713 if (! (curnum = setlocale(LC_NUMERIC, "")))
714 setlocale_failure = TRUE;
715 #endif /* USE_LOCALE_NUMERIC */
718 if (setlocale_failure) {
720 bool locwarn = (printwarn > 1 ||
722 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
727 PerlIO_printf(Perl_error_log,
728 "perl: warning: Setting locale failed.\n");
732 PerlIO_printf(Perl_error_log,
733 "perl: warning: Setting locale failed for the categories:\n\t");
734 #ifdef USE_LOCALE_CTYPE
736 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
737 #endif /* USE_LOCALE_CTYPE */
738 #ifdef USE_LOCALE_COLLATE
740 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
741 #endif /* USE_LOCALE_COLLATE */
742 #ifdef USE_LOCALE_NUMERIC
744 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
745 #endif /* USE_LOCALE_NUMERIC */
746 PerlIO_printf(Perl_error_log, "\n");
750 PerlIO_printf(Perl_error_log,
751 "perl: warning: Please check that your locale settings:\n");
754 PerlIO_printf(Perl_error_log,
755 "\tLANGUAGE = %c%s%c,\n",
756 language ? '"' : '(',
757 language ? language : "unset",
758 language ? '"' : ')');
761 PerlIO_printf(Perl_error_log,
762 "\tLC_ALL = %c%s%c,\n",
764 lc_all ? lc_all : "unset",
769 for (e = environ; *e; e++) {
770 if (strnEQ(*e, "LC_", 3)
771 && strnNE(*e, "LC_ALL=", 7)
772 && (p = strchr(*e, '=')))
773 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
774 (int)(p - *e), *e, p + 1);
778 PerlIO_printf(Perl_error_log,
781 lang ? lang : "unset",
784 PerlIO_printf(Perl_error_log,
785 " are supported and installed on your system.\n");
790 if (setlocale(LC_ALL, "C")) {
792 PerlIO_printf(Perl_error_log,
793 "perl: warning: Falling back to the standard locale (\"C\").\n");
798 PerlIO_printf(Perl_error_log,
799 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
806 #ifdef USE_LOCALE_CTYPE
807 || !(curctype || setlocale(LC_CTYPE, "C"))
808 #endif /* USE_LOCALE_CTYPE */
809 #ifdef USE_LOCALE_COLLATE
810 || !(curcoll || setlocale(LC_COLLATE, "C"))
811 #endif /* USE_LOCALE_COLLATE */
812 #ifdef USE_LOCALE_NUMERIC
813 || !(curnum || setlocale(LC_NUMERIC, "C"))
814 #endif /* USE_LOCALE_NUMERIC */
818 PerlIO_printf(Perl_error_log,
819 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
823 #endif /* ! LC_ALL */
825 #ifdef USE_LOCALE_CTYPE
826 curctype = setlocale(LC_CTYPE, Nullch);
827 #endif /* USE_LOCALE_CTYPE */
828 #ifdef USE_LOCALE_COLLATE
829 curcoll = setlocale(LC_COLLATE, Nullch);
830 #endif /* USE_LOCALE_COLLATE */
831 #ifdef USE_LOCALE_NUMERIC
832 curnum = setlocale(LC_NUMERIC, Nullch);
833 #endif /* USE_LOCALE_NUMERIC */
836 #ifdef USE_LOCALE_CTYPE
838 #endif /* USE_LOCALE_CTYPE */
840 #ifdef USE_LOCALE_COLLATE
841 new_collate(curcoll);
842 #endif /* USE_LOCALE_COLLATE */
844 #ifdef USE_LOCALE_NUMERIC
846 #endif /* USE_LOCALE_NUMERIC */
848 #endif /* USE_LOCALE */
853 /* Backwards compatibility. */
855 Perl_init_i18nl14n(pTHX_ int printwarn)
857 return init_i18nl10n(printwarn);
860 #ifdef USE_LOCALE_COLLATE
863 * mem_collxfrm() is a bit like strxfrm() but with two important
864 * differences. First, it handles embedded NULs. Second, it allocates
865 * a bit more memory than needed for the transformed data itself.
866 * The real transformed data begins at offset sizeof(collationix).
867 * Please see sv_collxfrm() to see how this is used.
870 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
873 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
875 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
876 /* the +1 is for the terminating NUL. */
878 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
879 New(171, xbuf, xAlloc, char);
883 *(U32*)xbuf = PL_collation_ix;
884 xout = sizeof(PL_collation_ix);
885 for (xin = 0; xin < len; ) {
889 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
892 if (xused < xAlloc - xout)
894 xAlloc = (2 * xAlloc) + 1;
895 Renew(xbuf, xAlloc, char);
900 xin += strlen(s + xin) + 1;
903 /* Embedded NULs are understood but silently skipped
904 * because they make no sense in locale collation. */
908 *xlen = xout - sizeof(PL_collation_ix);
917 #endif /* USE_LOCALE_COLLATE */
919 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
921 /* As a space optimization, we do not compile tables for strings of length
922 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
923 special-cased in fbm_instr().
925 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
928 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
937 if (flags & FBMcf_TAIL)
938 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
939 s = (U8*)SvPV_force(sv, len);
940 (void)SvUPGRADE(sv, SVt_PVBM);
941 if (len == 0) /* TAIL might be on on a zero-length string. */
951 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
952 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
953 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
954 memset((void*)table, mlen, 256);
955 table[-1] = (U8)flags;
957 sb = s - mlen + 1; /* first char (maybe) */
959 if (table[*s] == mlen)
964 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
967 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
968 for (i = 0; i < len; i++) {
969 if (PL_freq[s[i]] < frequency) {
971 frequency = PL_freq[s[i]];
974 BmRARE(sv) = s[rarest];
975 BmPREVIOUS(sv) = rarest;
976 BmUSEFUL(sv) = 100; /* Initial value */
977 if (flags & FBMcf_TAIL)
979 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
980 BmRARE(sv),BmPREVIOUS(sv)));
983 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
984 /* If SvTAIL is actually due to \Z or \z, this gives false positives
988 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
990 register unsigned char *s;
992 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
993 register STRLEN littlelen = l;
994 register I32 multiline = flags & FBMrf_MULTILINE;
996 if (bigend - big < littlelen) {
998 if ( SvTAIL(littlestr)
999 && (bigend - big == littlelen - 1)
1001 || *big == *little && memEQ(big, little, littlelen - 1)))
1006 if (littlelen <= 2) { /* Special-cased */
1009 if (littlelen == 1) {
1010 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1011 /* Know that bigend != big. */
1012 if (bigend[-1] == '\n')
1013 return (char *)(bigend - 1);
1014 return (char *) bigend;
1017 while (s < bigend) {
1022 if (SvTAIL(littlestr))
1023 return (char *) bigend;
1027 return (char*)big; /* Cannot be SvTAIL! */
1029 /* littlelen is 2 */
1030 if (SvTAIL(littlestr) && !multiline) {
1031 if (bigend[-1] == '\n' && bigend[-2] == *little)
1032 return (char*)bigend - 2;
1033 if (bigend[-1] == *little)
1034 return (char*)bigend - 1;
1038 /* This should be better than FBM if c1 == c2, and almost
1039 as good otherwise: maybe better since we do less indirection.
1040 And we save a lot of memory by caching no table. */
1041 register unsigned char c1 = little[0];
1042 register unsigned char c2 = little[1];
1047 while (s <= bigend) {
1050 return (char*)s - 1;
1057 goto check_1char_anchor;
1068 goto check_1char_anchor;
1071 while (s <= bigend) {
1074 return (char*)s - 1;
1076 goto check_1char_anchor;
1085 check_1char_anchor: /* One char and anchor! */
1086 if (SvTAIL(littlestr) && (*bigend == *little))
1087 return (char *)bigend; /* bigend is already decremented. */
1090 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1091 s = bigend - littlelen;
1092 if (s >= big && bigend[-1] == '\n' && *s == *little
1093 /* Automatically of length > 2 */
1094 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1096 return (char*)s; /* how sweet it is */
1099 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1101 return (char*)s + 1; /* how sweet it is */
1105 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1106 char *b = ninstr((char*)big,(char*)bigend,
1107 (char*)little, (char*)little + littlelen);
1109 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1110 /* Chop \n from littlestr: */
1111 s = bigend - littlelen + 1;
1113 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1122 { /* Do actual FBM. */
1123 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1124 register unsigned char *oldlittle;
1126 if (littlelen > bigend - big)
1128 --littlelen; /* Last char found by table lookup */
1130 s = big + littlelen;
1131 little += littlelen; /* last char */
1138 if ((tmp = table[*s])) {
1140 if (bigend - s > tmp) {
1146 if ((s += tmp) < bigend)
1151 else { /* less expensive than calling strncmp() */
1152 register unsigned char *olds = s;
1157 if (*--s == *--little)
1160 s = olds + 1; /* here we pay the price for failure */
1162 if (s < bigend) /* fake up continue to outer loop */
1170 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1171 && memEQ(bigend - littlelen, oldlittle - littlelen, littlelen) )
1172 return (char*)bigend - littlelen;
1177 /* start_shift, end_shift are positive quantities which give offsets
1178 of ends of some substring of bigstr.
1179 If `last' we want the last occurence.
1180 old_posp is the way of communication between consequent calls if
1181 the next call needs to find the .
1182 The initial *old_posp should be -1.
1184 Note that we take into account SvTAIL, so one can get extra
1185 optimizations if _ALL flag is set.
1188 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1189 if PL_multiline. In fact if !PL_multiline the autoritative answer
1190 is not supported yet. */
1193 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1196 register unsigned char *s, *x;
1197 register unsigned char *big;
1199 register I32 previous;
1201 register unsigned char *little;
1202 register I32 stop_pos;
1203 register unsigned char *littleend;
1207 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1208 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1210 if ( BmRARE(littlestr) == '\n'
1211 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1212 little = (unsigned char *)(SvPVX(littlestr));
1213 littleend = little + SvCUR(littlestr);
1220 little = (unsigned char *)(SvPVX(littlestr));
1221 littleend = little + SvCUR(littlestr);
1223 /* The value of pos we can start at: */
1224 previous = BmPREVIOUS(littlestr);
1225 big = (unsigned char *)(SvPVX(bigstr));
1226 /* The value of pos we can stop at: */
1227 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1228 if (previous + start_shift > stop_pos) {
1229 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1233 while (pos < previous + start_shift) {
1234 if (!(pos += PL_screamnext[pos]))
1239 if (pos >= stop_pos) break;
1240 if (big[pos-previous] != first)
1242 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1248 if (s == littleend) {
1250 if (!last) return (char *)(big+pos-previous);
1253 } while ( pos += PL_screamnext[pos] );
1254 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1255 #else /* !POINTERRIGOR */
1258 if (pos >= stop_pos) break;
1259 if (big[pos] != first)
1261 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1267 if (s == littleend) {
1269 if (!last) return (char *)(big+pos);
1272 } while ( pos += PL_screamnext[pos] );
1274 return (char *)(big+(*old_posp));
1275 #endif /* POINTERRIGOR */
1277 if (!SvTAIL(littlestr) || (end_shift > 0))
1279 /* Ignore the trailing "\n". This code is not microoptimized */
1280 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1281 stop_pos = littleend - little; /* Actual littlestr len */
1286 && ((stop_pos == 1) || memEQ(big + 1, little, stop_pos - 1)))
1292 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1294 register U8 *a = (U8 *)s1;
1295 register U8 *b = (U8 *)s2;
1297 if (*a != *b && *a != PL_fold[*b])
1305 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1307 register U8 *a = (U8 *)s1;
1308 register U8 *b = (U8 *)s2;
1310 if (*a != *b && *a != PL_fold_locale[*b])
1317 /* copy a string to a safe spot */
1320 Perl_savepv(pTHX_ const char *sv)
1322 register char *newaddr;
1324 New(902,newaddr,strlen(sv)+1,char);
1325 (void)strcpy(newaddr,sv);
1329 /* same thing but with a known length */
1332 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1334 register char *newaddr;
1336 New(903,newaddr,len+1,char);
1337 Copy(sv,newaddr,len,char); /* might not be null terminated */
1338 newaddr[len] = '\0'; /* is now */
1342 /* the SV for Perl_form() and mess() is not kept in an arena */
1352 return sv_2mortal(newSVpvn("",0));
1357 /* Create as PVMG now, to avoid any upgrading later */
1358 New(905, sv, 1, SV);
1359 Newz(905, any, 1, XPVMG);
1360 SvFLAGS(sv) = SVt_PVMG;
1361 SvANY(sv) = (void*)any;
1362 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1367 #if defined(PERL_IMPLICIT_CONTEXT)
1369 Perl_form_nocontext(const char* pat, ...)
1374 va_start(args, pat);
1375 retval = vform(pat, &args);
1379 #endif /* PERL_IMPLICIT_CONTEXT */
1382 Perl_form(pTHX_ const char* pat, ...)
1386 va_start(args, pat);
1387 retval = vform(pat, &args);
1393 Perl_vform(pTHX_ const char *pat, va_list *args)
1395 SV *sv = mess_alloc();
1396 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1400 #if defined(PERL_IMPLICIT_CONTEXT)
1402 Perl_mess_nocontext(const char *pat, ...)
1407 va_start(args, pat);
1408 retval = vmess(pat, &args);
1412 #endif /* PERL_IMPLICIT_CONTEXT */
1415 Perl_mess(pTHX_ const char *pat, ...)
1419 va_start(args, pat);
1420 retval = vmess(pat, &args);
1426 Perl_vmess(pTHX_ const char *pat, va_list *args)
1428 SV *sv = mess_alloc();
1429 static char dgd[] = " during global destruction.\n";
1431 #ifdef MACOS_TRADITIONAL
1433 sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1434 if (SvPVX(sv)[2] == '#')
1435 sv_insert(sv, 0, 2, "", 0);
1437 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1439 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1441 if (PL_curcop->cop_line)
1442 Perl_sv_catpvf(aTHX_ sv, " at %_ line %"IVdf,
1443 GvSV(PL_curcop->cop_filegv), (IV)PL_curcop->cop_line);
1444 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1445 bool line_mode = (RsSIMPLE(PL_rs) &&
1446 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1447 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1448 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1449 line_mode ? "line" : "chunk",
1450 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1454 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1456 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1457 #ifdef MACOS_TRADITIONAL
1458 if (PL_curcop->cop_line) {
1459 MPWPosIndication(sv, SvPVX(GvSV(PL_curcop->cop_filegv)), PL_curcop->cop_line);
1468 Perl_vdie(pTHX_ const char* pat, va_list *args)
1472 int was_in_eval = PL_in_eval;
1479 DEBUG_S(PerlIO_printf(Perl_debug_log,
1480 "%p: die: curstack = %p, mainstack = %p\n",
1481 thr, PL_curstack, PL_mainstack));
1484 msv = vmess(pat, args);
1485 if (PL_errors && SvCUR(PL_errors)) {
1486 sv_catsv(PL_errors, msv);
1487 message = SvPV(PL_errors, msglen);
1488 SvCUR_set(PL_errors, 0);
1491 message = SvPV(msv,msglen);
1497 DEBUG_S(PerlIO_printf(Perl_debug_log,
1498 "%p: die: message = %s\ndiehook = %p\n",
1499 thr, message, PL_diehook));
1501 /* sv_2cv might call Perl_croak() */
1502 SV *olddiehook = PL_diehook;
1504 SAVESPTR(PL_diehook);
1505 PL_diehook = Nullsv;
1506 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1508 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1514 msg = newSVpvn(message, msglen);
1522 PUSHSTACKi(PERLSI_DIEHOOK);
1526 call_sv((SV*)cv, G_DISCARD);
1532 PL_restartop = die_where(message, msglen);
1533 DEBUG_S(PerlIO_printf(Perl_debug_log,
1534 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1535 thr, PL_restartop, was_in_eval, PL_top_env));
1536 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1538 return PL_restartop;
1541 #if defined(PERL_IMPLICIT_CONTEXT)
1543 Perl_die_nocontext(const char* pat, ...)
1548 va_start(args, pat);
1549 o = vdie(pat, &args);
1553 #endif /* PERL_IMPLICIT_CONTEXT */
1556 Perl_die(pTHX_ const char* pat, ...)
1560 va_start(args, pat);
1561 o = vdie(pat, &args);
1567 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1577 msv = vmess(pat, args);
1578 if (PL_errors && SvCUR(PL_errors)) {
1579 sv_catsv(PL_errors, msv);
1580 message = SvPV(PL_errors, msglen);
1581 SvCUR_set(PL_errors, 0);
1584 message = SvPV(msv,msglen);
1586 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1587 PTR2UV(thr), message));
1590 /* sv_2cv might call Perl_croak() */
1591 SV *olddiehook = PL_diehook;
1593 SAVESPTR(PL_diehook);
1594 PL_diehook = Nullsv;
1595 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1597 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1602 msg = newSVpvn(message, msglen);
1606 PUSHSTACKi(PERLSI_DIEHOOK);
1610 call_sv((SV*)cv, G_DISCARD);
1616 PL_restartop = die_where(message, msglen);
1621 /* SFIO can really mess with your errno */
1624 PerlIO *serr = Perl_error_log;
1626 PerlIO_write(serr, message, msglen);
1627 (void)PerlIO_flush(serr);
1632 #ifdef MACOS_TRADITIONAL
1638 #if defined(PERL_IMPLICIT_CONTEXT)
1640 Perl_croak_nocontext(const char *pat, ...)
1644 va_start(args, pat);
1649 #endif /* PERL_IMPLICIT_CONTEXT */
1652 Perl_croak(pTHX_ const char *pat, ...)
1655 va_start(args, pat);
1662 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1671 msv = vmess(pat, args);
1672 message = SvPV(msv, msglen);
1675 /* sv_2cv might call Perl_warn() */
1677 SV *oldwarnhook = PL_warnhook;
1679 SAVESPTR(PL_warnhook);
1680 PL_warnhook = Nullsv;
1681 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1683 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1688 msg = newSVpvn(message, msglen);
1692 PUSHSTACKi(PERLSI_WARNHOOK);
1696 call_sv((SV*)cv, G_DISCARD);
1703 PerlIO *serr = Perl_error_log;
1705 PerlIO_write(serr, message, msglen);
1707 DEBUG_L(*message == '!'
1708 ? (xstat(message[1]=='!'
1709 ? (message[2]=='!' ? 2 : 1)
1714 (void)PerlIO_flush(serr);
1718 #if defined(PERL_IMPLICIT_CONTEXT)
1720 Perl_warn_nocontext(const char *pat, ...)
1724 va_start(args, pat);
1728 #endif /* PERL_IMPLICIT_CONTEXT */
1731 Perl_warn(pTHX_ const char *pat, ...)
1734 va_start(args, pat);
1739 #if defined(PERL_IMPLICIT_CONTEXT)
1741 Perl_warner_nocontext(U32 err, const char *pat, ...)
1745 va_start(args, pat);
1746 vwarner(err, pat, &args);
1749 #endif /* PERL_IMPLICIT_CONTEXT */
1752 Perl_warner(pTHX_ U32 err, const char* pat,...)
1755 va_start(args, pat);
1756 vwarner(err, pat, &args);
1761 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1771 msv = vmess(pat, args);
1772 message = SvPV(msv, msglen);
1776 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1777 #endif /* USE_THREADS */
1779 /* sv_2cv might call Perl_croak() */
1780 SV *olddiehook = PL_diehook;
1782 SAVESPTR(PL_diehook);
1783 PL_diehook = Nullsv;
1784 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1786 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1791 msg = newSVpvn(message, msglen);
1798 call_sv((SV*)cv, G_DISCARD);
1804 PL_restartop = die_where(message, msglen);
1808 PerlIO *serr = Perl_error_log;
1809 PerlIO_write(serr, message, msglen);
1810 (void)PerlIO_flush(serr);
1817 /* sv_2cv might call Perl_warn() */
1819 SV *oldwarnhook = PL_warnhook;
1821 SAVESPTR(PL_warnhook);
1822 PL_warnhook = Nullsv;
1823 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1825 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1830 msg = newSVpvn(message, msglen);
1837 call_sv((SV*)cv, G_DISCARD);
1844 PerlIO *serr = Perl_error_log;
1845 PerlIO_write(serr, message, msglen);
1849 (void)PerlIO_flush(serr);
1854 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1855 #if !defined(WIN32) && !defined(CYGWIN)
1857 Perl_my_setenv(pTHX_ char *nam, char *val)
1859 #ifndef PERL_USE_SAFE_PUTENV
1860 /* most putenv()s leak, so we manipulate environ directly */
1861 register I32 i=setenv_getix(nam); /* where does it go? */
1863 if (environ == PL_origenviron) { /* need we copy environment? */
1869 for (max = i; environ[max]; max++) ;
1870 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1871 for (j=0; j<max; j++) { /* copy environment */
1872 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1873 strcpy(tmpenv[j], environ[j]);
1875 tmpenv[max] = Nullch;
1876 environ = tmpenv; /* tell exec where it is now */
1879 safesysfree(environ[i]);
1880 while (environ[i]) {
1881 environ[i] = environ[i+1];
1886 if (!environ[i]) { /* does not exist yet */
1887 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1888 environ[i+1] = Nullch; /* make sure it's null terminated */
1891 safesysfree(environ[i]);
1892 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1894 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1896 #else /* PERL_USE_SAFE_PUTENV */
1899 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1900 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1901 (void)putenv(new_env);
1902 #endif /* PERL_USE_SAFE_PUTENV */
1905 #else /* WIN32 || CYGWIN */
1908 * Save environ of perl.exe, currently Cygwin links in separate environ's
1909 * for each exe/dll. Probably should be a member of impure_ptr.
1911 static char ***Perl_main_environ;
1914 Perl_my_setenv_init(char ***penviron)
1916 Perl_main_environ = penviron;
1920 my_setenv(char *nam, char *val)
1922 /* You can not directly manipulate the environ[] array because
1923 * the routines do some additional work that syncs the Cygwin
1924 * environment with the Windows environment.
1926 char *oldstr = environ[setenv_getix(nam)];
1935 setenv(nam, val, 1);
1936 environ = *Perl_main_environ; /* environ realloc can occur in setenv */
1937 if(oldstr && environ[setenv_getix(nam)] != oldstr)
1940 #else /* if WIN32 */
1943 Perl_my_setenv(pTHX_ char *nam,char *val)
1946 #ifdef USE_WIN32_RTL_ENV
1948 register char *envstr;
1949 STRLEN namlen = strlen(nam);
1951 char *oldstr = environ[setenv_getix(nam)];
1953 /* putenv() has totally broken semantics in both the Borland
1954 * and Microsoft CRTLs. They either store the passed pointer in
1955 * the environment without making a copy, or make a copy and don't
1956 * free it. And on top of that, they dont free() old entries that
1957 * are being replaced/deleted. This means the caller must
1958 * free any old entries somehow, or we end up with a memory
1959 * leak every time my_setenv() is called. One might think
1960 * one could directly manipulate environ[], like the UNIX code
1961 * above, but direct changes to environ are not allowed when
1962 * calling putenv(), since the RTLs maintain an internal
1963 * *copy* of environ[]. Bad, bad, *bad* stink.
1974 vallen = strlen(val);
1975 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
1976 (void)sprintf(envstr,"%s=%s",nam,val);
1977 (void)PerlEnv_putenv(envstr);
1979 safesysfree(oldstr);
1981 safesysfree(envstr); /* MSVCRT leaks without this */
1984 #else /* !USE_WIN32_RTL_ENV */
1986 register char *envstr;
1987 STRLEN len = strlen(nam) + 3;
1992 New(904, envstr, len, char);
1993 (void)sprintf(envstr,"%s=%s",nam,val);
1994 (void)PerlEnv_putenv(envstr);
2004 Perl_setenv_getix(pTHX_ char *nam)
2006 register I32 i, len = strlen(nam);
2008 for (i = 0; environ[i]; i++) {
2011 strnicmp(environ[i],nam,len) == 0
2013 strnEQ(environ[i],nam,len)
2015 && environ[i][len] == '=')
2016 break; /* strnEQ must come first to avoid */
2017 } /* potential SEGV's */
2023 #ifdef UNLINK_ALL_VERSIONS
2025 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
2029 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
2034 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
2036 Perl_my_bcopy(pTHX_ register const char *from,register char *to,register I32 len)
2040 if (from - to >= 0) {
2048 *(--to) = *(--from);
2056 Perl_my_memset(pTHX_ register char *loc, register I32 ch, register I32 len)
2066 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2068 Perl_my_bzero(pTHX_ register char *loc, register I32 len)
2078 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2080 Perl_my_memcmp(pTHX_ const char *s1, const char *s2, register I32 len)
2082 register U8 *a = (U8 *)s1;
2083 register U8 *b = (U8 *)s2;
2087 if (tmp = *a++ - *b++)
2092 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2096 #ifdef USE_CHAR_VSPRINTF
2101 vsprintf(char *dest, const char *pat, char *args)
2105 fakebuf._ptr = dest;
2106 fakebuf._cnt = 32767;
2110 fakebuf._flag = _IOWRT|_IOSTRG;
2111 _doprnt(pat, args, &fakebuf); /* what a kludge */
2112 (void)putc('\0', &fakebuf);
2113 #ifdef USE_CHAR_VSPRINTF
2116 return 0; /* perl doesn't use return value */
2120 #endif /* HAS_VPRINTF */
2123 #if BYTEORDER != 0x4321
2125 Perl_my_swap(pTHX_ short s)
2127 #if (BYTEORDER & 1) == 0
2130 result = ((s & 255) << 8) + ((s >> 8) & 255);
2138 Perl_my_htonl(pTHX_ long l)
2142 char c[sizeof(long)];
2145 #if BYTEORDER == 0x1234
2146 u.c[0] = (l >> 24) & 255;
2147 u.c[1] = (l >> 16) & 255;
2148 u.c[2] = (l >> 8) & 255;
2152 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2153 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2158 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2159 u.c[o & 0xf] = (l >> s) & 255;
2167 Perl_my_ntohl(pTHX_ long l)
2171 char c[sizeof(long)];
2174 #if BYTEORDER == 0x1234
2175 u.c[0] = (l >> 24) & 255;
2176 u.c[1] = (l >> 16) & 255;
2177 u.c[2] = (l >> 8) & 255;
2181 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2182 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2189 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2190 l |= (u.c[o & 0xf] & 255) << s;
2197 #endif /* BYTEORDER != 0x4321 */
2201 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2202 * If these functions are defined,
2203 * the BYTEORDER is neither 0x1234 nor 0x4321.
2204 * However, this is not assumed.
2208 #define HTOV(name,type) \
2210 name (register type n) \
2214 char c[sizeof(type)]; \
2218 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2219 u.c[i] = (n >> s) & 0xFF; \
2224 #define VTOH(name,type) \
2226 name (register type n) \
2230 char c[sizeof(type)]; \
2236 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2237 n += (u.c[i] & 0xFF) << s; \
2242 #if defined(HAS_HTOVS) && !defined(htovs)
2245 #if defined(HAS_HTOVL) && !defined(htovl)
2248 #if defined(HAS_VTOHS) && !defined(vtohs)
2251 #if defined(HAS_VTOHL) && !defined(vtohl)
2255 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2256 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2258 Perl_my_popen(pTHX_ char *cmd, char *mode)
2261 register I32 This, that;
2264 I32 doexec = strNE(cmd,"-");
2268 PERL_FLUSHALL_FOR_CHILD;
2271 return my_syspopen(cmd,mode);
2274 This = (*mode == 'w');
2276 if (doexec && PL_tainting) {
2278 taint_proper("Insecure %s%s", "EXEC");
2280 if (PerlProc_pipe(p) < 0)
2282 if (doexec && PerlProc_pipe(pp) >= 0)
2284 while ((pid = (doexec?vfork():fork())) < 0) {
2285 if (errno != EAGAIN) {
2286 PerlLIO_close(p[This]);
2288 PerlLIO_close(pp[0]);
2289 PerlLIO_close(pp[1]);
2292 Perl_croak(aTHX_ "Can't fork");
2304 PerlLIO_close(p[THAT]);
2306 PerlLIO_close(pp[0]);
2307 #if defined(HAS_FCNTL) && defined(F_SETFD)
2308 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2311 if (p[THIS] != (*mode == 'r')) {
2312 PerlLIO_dup2(p[THIS], *mode == 'r');
2313 PerlLIO_close(p[THIS]);
2317 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2323 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2327 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2330 #endif /* defined OS2 */
2332 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2333 sv_setiv(GvSV(tmpgv), getpid());
2335 hv_clear(PL_pidstatus); /* we have no children */
2340 do_execfree(); /* free any memory malloced by child on vfork */
2341 PerlLIO_close(p[that]);
2343 PerlLIO_close(pp[1]);
2344 if (p[that] < p[This]) {
2345 PerlLIO_dup2(p[This], p[that]);
2346 PerlLIO_close(p[This]);
2349 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2350 (void)SvUPGRADE(sv,SVt_IV);
2352 PL_forkprocess = pid;
2353 if (did_pipes && pid > 0) {
2357 while (n < sizeof(int)) {
2358 n1 = PerlLIO_read(pp[0],
2359 (void*)(((char*)&errkid)+n),
2365 PerlLIO_close(pp[0]);
2367 if (n) { /* Error */
2368 if (n != sizeof(int))
2369 Perl_croak(aTHX_ "panic: kid popen errno read");
2370 errno = errkid; /* Propagate errno from kid */
2375 PerlLIO_close(pp[0]);
2376 return PerlIO_fdopen(p[This], mode);
2379 #if defined(atarist) || defined(DJGPP)
2382 Perl_my_popen(pTHX_ char *cmd, char *mode)
2384 /* Needs work for PerlIO ! */
2385 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
2386 PERL_FLUSHALL_FOR_CHILD;
2387 return popen(PerlIO_exportFILE(cmd, 0), mode);
2391 #endif /* !DOSISH */
2395 Perl_dump_fds(pTHX_ char *s)
2398 struct stat tmpstatbuf;
2400 PerlIO_printf(Perl_debug_log,"%s", s);
2401 for (fd = 0; fd < 32; fd++) {
2402 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2403 PerlIO_printf(Perl_debug_log," %d",fd);
2405 PerlIO_printf(Perl_debug_log,"\n");
2407 #endif /* DUMP_FDS */
2411 dup2(int oldfd, int newfd)
2413 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2416 PerlLIO_close(newfd);
2417 return fcntl(oldfd, F_DUPFD, newfd);
2419 #define DUP2_MAX_FDS 256
2420 int fdtmp[DUP2_MAX_FDS];
2426 PerlLIO_close(newfd);
2427 /* good enough for low fd's... */
2428 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2429 if (fdx >= DUP2_MAX_FDS) {
2437 PerlLIO_close(fdtmp[--fdx]);
2444 #ifdef HAS_SIGACTION
2447 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2449 struct sigaction act, oact;
2451 act.sa_handler = handler;
2452 sigemptyset(&act.sa_mask);
2455 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2458 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2459 act.sa_flags |= SA_NOCLDWAIT;
2461 if (sigaction(signo, &act, &oact) == -1)
2464 return oact.sa_handler;
2468 Perl_rsignal_state(pTHX_ int signo)
2470 struct sigaction oact;
2472 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2475 return oact.sa_handler;
2479 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2481 struct sigaction act;
2483 act.sa_handler = handler;
2484 sigemptyset(&act.sa_mask);
2487 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2490 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2491 act.sa_flags |= SA_NOCLDWAIT;
2493 return sigaction(signo, &act, save);
2497 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2499 return sigaction(signo, save, (struct sigaction *)NULL);
2502 #else /* !HAS_SIGACTION */
2505 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2507 return PerlProc_signal(signo, handler);
2510 static int sig_trapped;
2520 Perl_rsignal_state(pTHX_ int signo)
2522 Sighandler_t oldsig;
2525 oldsig = PerlProc_signal(signo, sig_trap);
2526 PerlProc_signal(signo, oldsig);
2528 PerlProc_kill(getpid(), signo);
2533 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2535 *save = PerlProc_signal(signo, handler);
2536 return (*save == SIG_ERR) ? -1 : 0;
2540 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2542 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2545 #endif /* !HAS_SIGACTION */
2547 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2548 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2550 Perl_my_pclose(pTHX_ PerlIO *ptr)
2552 Sigsave_t hstat, istat, qstat;
2560 int saved_vaxc_errno;
2563 int saved_win32_errno;
2566 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2569 *svp = &PL_sv_undef;
2571 if (pid == -1) { /* Opened by popen. */
2572 return my_syspclose(ptr);
2575 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2576 saved_errno = errno;
2578 saved_vaxc_errno = vaxc$errno;
2581 saved_win32_errno = GetLastError();
2585 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2587 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2588 rsignal_save(SIGINT, SIG_IGN, &istat);
2589 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2591 pid2 = wait4pid(pid, &status, 0);
2592 } while (pid2 == -1 && errno == EINTR);
2593 rsignal_restore(SIGHUP, &hstat);
2594 rsignal_restore(SIGINT, &istat);
2595 rsignal_restore(SIGQUIT, &qstat);
2597 SETERRNO(saved_errno, saved_vaxc_errno);
2600 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2602 #endif /* !DOSISH */
2604 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
2606 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2610 char spid[TYPE_CHARS(int)];
2615 sprintf(spid, "%"IVdf, (IV)pid);
2616 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2617 if (svp && *svp != &PL_sv_undef) {
2618 *statusp = SvIVX(*svp);
2619 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2626 hv_iterinit(PL_pidstatus);
2627 if (entry = hv_iternext(PL_pidstatus)) {
2628 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2629 sv = hv_iterval(PL_pidstatus,entry);
2630 *statusp = SvIVX(sv);
2631 sprintf(spid, "%"IVdf, (IV)pid);
2632 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2637 # ifdef HAS_WAITPID_RUNTIME
2638 if (!HAS_WAITPID_RUNTIME)
2641 return PerlProc_waitpid(pid,statusp,flags);
2643 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2644 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2646 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2651 Perl_croak(aTHX_ "Can't do waitpid with flags");
2653 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2654 pidgone(result,*statusp);
2662 #endif /* !DOSISH || OS2 || WIN32 */
2666 Perl_pidgone(pTHX_ Pid_t pid, int status)
2669 char spid[TYPE_CHARS(int)];
2671 sprintf(spid, "%"IVdf, (IV)pid);
2672 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2673 (void)SvUPGRADE(sv,SVt_IV);
2678 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2681 int /* Cannot prototype with I32
2683 my_syspclose(PerlIO *ptr)
2686 Perl_my_pclose(pTHX_ PerlIO *ptr)
2689 /* Needs work for PerlIO ! */
2690 FILE *f = PerlIO_findFILE(ptr);
2691 I32 result = pclose(f);
2693 result = (result << 8) & 0xff00;
2695 PerlIO_releaseFILE(ptr,f);
2701 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2704 register const char *frombase = from;
2707 register const char c = *from;
2712 while (count-- > 0) {
2713 for (todo = len; todo > 0; todo--) {
2721 Perl_cast_ulong(pTHX_ NV f)
2726 # define BIGDOUBLE 2147483648.0
2728 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2731 return (unsigned long)f;
2733 return (unsigned long)along;
2737 /* Unfortunately, on some systems the cast_uv() function doesn't
2738 work with the system-supplied definition of ULONG_MAX. The
2739 comparison (f >= ULONG_MAX) always comes out true. It must be a
2740 problem with the compiler constant folding.
2742 In any case, this workaround should be fine on any two's complement
2743 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2745 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2748 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2750 -- Kenneth Albanowski <kjahds@kjahds.com>
2754 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2758 Perl_cast_i32(pTHX_ NV f)
2761 return (I32) I32_MAX;
2763 return (I32) I32_MIN;
2768 Perl_cast_iv(pTHX_ NV f)
2773 if (f >= (NV)UV_MAX)
2784 Perl_cast_uv(pTHX_ NV f)
2787 return (UV) MY_UV_MAX;
2801 Perl_same_dirent(pTHX_ char *a, char *b)
2803 char *fa = strrchr(a,'/');
2804 char *fb = strrchr(b,'/');
2805 struct stat tmpstatbuf1;
2806 struct stat tmpstatbuf2;
2807 SV *tmpsv = sv_newmortal();
2820 sv_setpv(tmpsv, ".");
2822 sv_setpvn(tmpsv, a, fa - a);
2823 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2826 sv_setpv(tmpsv, ".");
2828 sv_setpvn(tmpsv, b, fb - b);
2829 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2831 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2832 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2834 #endif /* !HAS_RENAME */
2837 Perl_scan_bin(pTHX_ char *start, I32 len, I32 *retlen)
2839 register char *s = start;
2840 register NV rnv = 0.0;
2841 register UV ruv = 0;
2842 register bool seenb = FALSE;
2843 register bool overflowed = FALSE;
2845 for (; len-- && *s; s++) {
2846 if (!(*s == '0' || *s == '1')) {
2848 continue; /* Note: does not check for __ and the like. */
2849 if (seenb == FALSE && *s == 'b' && ruv == 0) {
2850 /* Disallow 0bbb0b0bbb... */
2856 if (ckWARN(WARN_DIGIT))
2857 Perl_warner(aTHX_ WARN_DIGIT,
2858 "Illegal binary digit '%c' ignored", *s);
2863 register UV xuv = ruv << 1;
2865 if ((xuv >> 1) != ruv) {
2869 if (ckWARN_d(WARN_OVERFLOW))
2870 Perl_warner(aTHX_ WARN_OVERFLOW,
2871 "Integer overflow in binary number");
2873 ruv = xuv | (*s - '0');
2877 /* If an NV has not enough bits in its mantissa to
2878 * represent an UV this summing of small low-order numbers
2879 * is a waste of time (because the NV cannot preserve
2880 * the low-order bits anyway): we could just remember when
2881 * did we overflow and in the end just multiply rnv by the
2888 if ( ( overflowed && rnv > 4294967295.0)
2890 || (!overflowed && ruv > 0xffffffff )
2894 if (ckWARN(WARN_PORTABLE))
2895 Perl_warner(aTHX_ WARN_PORTABLE,
2896 "Binary number > 0b11111111111111111111111111111111 non-portable");
2898 *retlen = s - start;
2903 Perl_scan_oct(pTHX_ char *start, I32 len, I32 *retlen)
2905 register char *s = start;
2906 register NV rnv = 0.0;
2907 register UV ruv = 0;
2908 register bool overflowed = FALSE;
2910 for (; len-- && *s; s++) {
2911 if (!(*s >= '0' && *s <= '7')) {
2913 continue; /* Note: does not check for __ and the like. */
2915 /* Allow \octal to work the DWIM way (that is, stop scanning
2916 * as soon as non-octal characters are seen, complain only iff
2917 * someone seems to want to use the digits eight and nine). */
2918 if (*s == '8' || *s == '9') {
2920 if (ckWARN(WARN_DIGIT))
2921 Perl_warner(aTHX_ WARN_DIGIT,
2922 "Illegal octal digit '%c' ignored", *s);
2928 register UV xuv = ruv << 3;
2930 if ((xuv >> 3) != ruv) {
2934 if (ckWARN_d(WARN_OVERFLOW))
2935 Perl_warner(aTHX_ WARN_OVERFLOW,
2936 "Integer overflow in octal number");
2938 ruv = xuv | (*s - '0');
2942 /* If an NV has not enough bits in its mantissa to
2943 * represent an UV this summing of small low-order numbers
2944 * is a waste of time (because the NV cannot preserve
2945 * the low-order bits anyway): we could just remember when
2946 * did we overflow and in the end just multiply rnv by the
2947 * right amount of 8-tuples. */
2948 rnv += (NV)(*s - '0');
2953 if ( ( overflowed && rnv > 4294967295.0)
2955 || (!overflowed && ruv > 0xffffffff )
2959 if (ckWARN(WARN_PORTABLE))
2960 Perl_warner(aTHX_ WARN_PORTABLE,
2961 "Octal number > 037777777777 non-portable");
2963 *retlen = s - start;
2968 Perl_scan_hex(pTHX_ char *start, I32 len, I32 *retlen)
2970 register char *s = start;
2971 register NV rnv = 0.0;
2972 register UV ruv = 0;
2973 register bool seenx = FALSE;
2974 register bool overflowed = FALSE;
2977 for (; len-- && *s; s++) {
2978 hexdigit = strchr((char *) PL_hexdigit, *s);
2981 continue; /* Note: does not check for __ and the like. */
2982 if (seenx == FALSE && *s == 'x' && ruv == 0) {
2983 /* Disallow 0xxx0x0xxx... */
2989 if (ckWARN(WARN_DIGIT))
2990 Perl_warner(aTHX_ WARN_DIGIT,
2991 "Illegal hexadecimal digit '%c' ignored", *s);
2996 register UV xuv = ruv << 4;
2998 if ((xuv >> 4) != ruv) {
3002 if (ckWARN_d(WARN_OVERFLOW))
3003 Perl_warner(aTHX_ WARN_OVERFLOW,
3004 "Integer overflow in hexadecimal number");
3006 ruv = xuv | ((hexdigit - PL_hexdigit) & 15);
3010 /* If an NV has not enough bits in its mantissa to
3011 * represent an UV this summing of small low-order numbers
3012 * is a waste of time (because the NV cannot preserve
3013 * the low-order bits anyway): we could just remember when
3014 * did we overflow and in the end just multiply rnv by the
3015 * right amount of 16-tuples. */
3016 rnv += (NV)((hexdigit - PL_hexdigit) & 15);
3021 if ( ( overflowed && rnv > 4294967295.0)
3023 || (!overflowed && ruv > 0xffffffff )
3027 if (ckWARN(WARN_PORTABLE))
3028 Perl_warner(aTHX_ WARN_PORTABLE,
3029 "Hexadecimal number > 0xffffffff non-portable");
3031 *retlen = s - start;
3036 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
3039 char *xfound = Nullch;
3040 char *xfailed = Nullch;
3041 char tmpbuf[MAXPATHLEN];
3045 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3046 # define SEARCH_EXTS ".bat", ".cmd", NULL
3047 # define MAX_EXT_LEN 4
3050 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3051 # define MAX_EXT_LEN 4
3054 # define SEARCH_EXTS ".pl", ".com", NULL
3055 # define MAX_EXT_LEN 4
3057 /* additional extensions to try in each dir if scriptname not found */
3059 char *exts[] = { SEARCH_EXTS };
3060 char **ext = search_ext ? search_ext : exts;
3061 int extidx = 0, i = 0;
3062 char *curext = Nullch;
3064 # define MAX_EXT_LEN 0
3068 * If dosearch is true and if scriptname does not contain path
3069 * delimiters, search the PATH for scriptname.
3071 * If SEARCH_EXTS is also defined, will look for each
3072 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3073 * while searching the PATH.
3075 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3076 * proceeds as follows:
3077 * If DOSISH or VMSISH:
3078 * + look for ./scriptname{,.foo,.bar}
3079 * + search the PATH for scriptname{,.foo,.bar}
3082 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3083 * this will not look in '.' if it's not in the PATH)
3088 # ifdef ALWAYS_DEFTYPES
3089 len = strlen(scriptname);
3090 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3091 int hasdir, idx = 0, deftypes = 1;
3094 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
3097 int hasdir, idx = 0, deftypes = 1;
3100 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
3102 /* The first time through, just add SEARCH_EXTS to whatever we
3103 * already have, so we can check for default file types. */
3105 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3111 if ((strlen(tmpbuf) + strlen(scriptname)
3112 + MAX_EXT_LEN) >= sizeof tmpbuf)
3113 continue; /* don't search dir with too-long name */
3114 strcat(tmpbuf, scriptname);
3118 if (strEQ(scriptname, "-"))
3120 if (dosearch) { /* Look in '.' first. */
3121 char *cur = scriptname;
3123 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3125 if (strEQ(ext[i++],curext)) {
3126 extidx = -1; /* already has an ext */
3131 DEBUG_p(PerlIO_printf(Perl_debug_log,
3132 "Looking for %s\n",cur));
3133 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3134 && !S_ISDIR(PL_statbuf.st_mode)) {
3142 if (cur == scriptname) {
3143 len = strlen(scriptname);
3144 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3146 cur = strcpy(tmpbuf, scriptname);
3148 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3149 && strcpy(tmpbuf+len, ext[extidx++]));
3154 #ifdef MACOS_TRADITIONAL
3155 if (dosearch && !strchr(scriptname, ':') &&
3156 (s = PerlEnv_getenv("Commands")))
3158 if (dosearch && !strchr(scriptname, '/')
3160 && !strchr(scriptname, '\\')
3162 && (s = PerlEnv_getenv("PATH")))
3167 PL_bufend = s + strlen(s);
3168 while (s < PL_bufend) {
3169 #ifdef MACOS_TRADITIONAL
3170 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3174 #if defined(atarist) || defined(DOSISH)
3179 && *s != ';'; len++, s++) {
3180 if (len < sizeof tmpbuf)
3183 if (len < sizeof tmpbuf)
3185 #else /* ! (atarist || DOSISH) */
3186 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3189 #endif /* ! (atarist || DOSISH) */
3190 #endif /* MACOS_TRADITIONAL */
3193 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3194 continue; /* don't search dir with too-long name */
3195 #ifdef MACOS_TRADITIONAL
3196 if (len && tmpbuf[len - 1] != ':')
3197 tmpbuf[len++] = ':';
3200 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3201 && tmpbuf[len - 1] != '/'
3202 && tmpbuf[len - 1] != '\\'
3205 tmpbuf[len++] = '/';
3206 if (len == 2 && tmpbuf[0] == '.')
3209 (void)strcpy(tmpbuf + len, scriptname);
3213 len = strlen(tmpbuf);
3214 if (extidx > 0) /* reset after previous loop */
3218 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3219 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3220 if (S_ISDIR(PL_statbuf.st_mode)) {
3224 } while ( retval < 0 /* not there */
3225 && extidx>=0 && ext[extidx] /* try an extension? */
3226 && strcpy(tmpbuf+len, ext[extidx++])
3231 if (S_ISREG(PL_statbuf.st_mode)
3232 && cando(S_IRUSR,TRUE,&PL_statbuf)
3233 #if !defined(DOSISH) && !defined(MACOS_TRDITIONAL)
3234 && cando(S_IXUSR,TRUE,&PL_statbuf)
3238 xfound = tmpbuf; /* bingo! */
3242 xfailed = savepv(tmpbuf);
3245 if (!xfound && !seen_dot && !xfailed &&
3246 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3247 || S_ISDIR(PL_statbuf.st_mode)))
3249 seen_dot = 1; /* Disable message. */
3251 if (flags & 1) { /* do or die? */
3252 Perl_croak(aTHX_ "Can't %s %s%s%s",
3253 (xfailed ? "execute" : "find"),
3254 (xfailed ? xfailed : scriptname),
3255 (xfailed ? "" : " on PATH"),
3256 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3258 scriptname = Nullch;
3262 scriptname = xfound;
3264 return (scriptname ? savepv(scriptname) : Nullch);
3270 /* Very simplistic scheduler for now */
3274 thr = thr->i.next_run;
3278 Perl_cond_init(pTHX_ perl_cond *cp)
3284 Perl_cond_signal(pTHX_ perl_cond *cp)
3287 perl_cond cond = *cp;
3292 /* Insert t in the runnable queue just ahead of us */
3293 t->i.next_run = thr->i.next_run;
3294 thr->i.next_run->i.prev_run = t;
3295 t->i.prev_run = thr;
3296 thr->i.next_run = t;
3297 thr->i.wait_queue = 0;
3298 /* Remove from the wait queue */
3304 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3307 perl_cond cond, cond_next;
3309 for (cond = *cp; cond; cond = cond_next) {
3311 /* Insert t in the runnable queue just ahead of us */
3312 t->i.next_run = thr->i.next_run;
3313 thr->i.next_run->i.prev_run = t;
3314 t->i.prev_run = thr;
3315 thr->i.next_run = t;
3316 thr->i.wait_queue = 0;
3317 /* Remove from the wait queue */
3318 cond_next = cond->next;
3325 Perl_cond_wait(pTHX_ perl_cond *cp)
3329 if (thr->i.next_run == thr)
3330 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3332 New(666, cond, 1, struct perl_wait_queue);
3336 thr->i.wait_queue = cond;
3337 /* Remove ourselves from runnable queue */
3338 thr->i.next_run->i.prev_run = thr->i.prev_run;
3339 thr->i.prev_run->i.next_run = thr->i.next_run;
3341 #endif /* FAKE_THREADS */
3343 #ifdef PTHREAD_GETSPECIFIC_INT
3344 struct perl_thread *
3349 if (pthread_getspecific(PL_thr_key, &t))
3350 Perl_croak(aTHX_ "panic: pthread_getspecific");
3351 return (struct perl_thread *) t;
3356 Perl_condpair_magic(pTHX_ SV *sv)
3360 SvUPGRADE(sv, SVt_PVMG);
3361 mg = mg_find(sv, 'm');
3365 New(53, cp, 1, condpair_t);
3366 MUTEX_INIT(&cp->mutex);
3367 COND_INIT(&cp->owner_cond);
3368 COND_INIT(&cp->cond);
3370 MUTEX_LOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3371 mg = mg_find(sv, 'm');
3373 /* someone else beat us to initialising it */
3374 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3375 MUTEX_DESTROY(&cp->mutex);
3376 COND_DESTROY(&cp->owner_cond);
3377 COND_DESTROY(&cp->cond);
3381 sv_magic(sv, Nullsv, 'm', 0, 0);
3383 mg->mg_ptr = (char *)cp;
3384 mg->mg_len = sizeof(cp);
3385 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3386 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3387 "%p: condpair_magic %p\n", thr, sv));)
3394 * Make a new perl thread structure using t as a prototype. Some of the
3395 * fields for the new thread are copied from the prototype thread, t,
3396 * so t should not be running in perl at the time this function is
3397 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3398 * thread calling new_struct_thread) clearly satisfies this constraint.
3400 struct perl_thread *
3401 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3403 #if !defined(PERL_IMPLICIT_CONTEXT)
3404 struct perl_thread *thr;
3410 sv = newSVpvn("", 0);
3411 SvGROW(sv, sizeof(struct perl_thread) + 1);
3412 SvCUR_set(sv, sizeof(struct perl_thread));
3413 thr = (Thread) SvPVX(sv);
3415 memset(thr, 0xab, sizeof(struct perl_thread));
3422 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3424 Zero(thr, 1, struct perl_thread);
3427 PL_protect = MEMBER_TO_FPTR(Perl_default_protect);
3432 PL_curcop = &PL_compiling;
3433 thr->interp = t->interp;
3434 thr->cvcache = newHV();
3435 thr->threadsv = newAV();
3436 thr->specific = newAV();
3437 thr->errsv = newSVpvn("", 0);
3438 thr->flags = THRf_R_JOINABLE;
3439 MUTEX_INIT(&thr->mutex);
3441 /* top_env needs to be non-zero. It points to an area
3442 in which longjmp() stuff is stored, as C callstack
3443 info there at least is thread specific this has to
3444 be per-thread. Otherwise a 'die' in a thread gives
3445 that thread the C stack of last thread to do an eval {}!
3446 See comments in scope.h
3447 Initialize top entry (as in perl.c for main thread)
3449 PL_start_env.je_prev = NULL;
3450 PL_start_env.je_ret = -1;
3451 PL_start_env.je_mustcatch = TRUE;
3452 PL_top_env = &PL_start_env;
3454 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR) */
3457 PL_statname = NEWSV(66,0);
3458 PL_errors = newSVpvn("", 0);
3460 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3461 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3462 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3463 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3464 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3466 PL_reginterp_cnt = 0;
3467 PL_lastscream = Nullsv;
3470 PL_reg_start_tmp = 0;
3471 PL_reg_start_tmpl = 0;
3472 PL_reg_poscache = Nullch;
3474 /* parent thread's data needs to be locked while we make copy */
3475 MUTEX_LOCK(&t->mutex);
3477 PL_protect = t->Tprotect;
3479 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3480 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3481 PL_curstash = t->Tcurstash; /* always be set to main? */
3483 PL_tainted = t->Ttainted;
3484 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3485 PL_nrs = newSVsv(t->Tnrs);
3486 PL_rs = SvREFCNT_inc(PL_nrs);
3487 PL_last_in_gv = Nullgv;
3488 PL_ofslen = t->Tofslen;
3489 PL_ofs = savepvn(t->Tofs, PL_ofslen);
3490 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3491 PL_chopset = t->Tchopset;
3492 PL_formtarget = newSVsv(t->Tformtarget);
3493 PL_bodytarget = newSVsv(t->Tbodytarget);
3494 PL_toptarget = newSVsv(t->Ttoptarget);
3496 /* Initialise all per-thread SVs that the template thread used */
3497 svp = AvARRAY(t->threadsv);
3498 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3499 if (*svp && *svp != &PL_sv_undef) {
3500 SV *sv = newSVsv(*svp);
3501 av_store(thr->threadsv, i, sv);
3502 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3503 DEBUG_S(PerlIO_printf(Perl_debug_log,
3504 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
3507 thr->threadsvp = AvARRAY(thr->threadsv);
3509 MUTEX_LOCK(&PL_threads_mutex);
3511 thr->tid = ++PL_threadnum;
3512 thr->next = t->next;
3515 thr->next->prev = thr;
3516 MUTEX_UNLOCK(&PL_threads_mutex);
3518 /* done copying parent's state */
3519 MUTEX_UNLOCK(&t->mutex);
3521 #ifdef HAVE_THREAD_INTERN
3522 Perl_init_thread_intern(thr);
3523 #endif /* HAVE_THREAD_INTERN */
3526 #endif /* USE_THREADS */
3530 * This hack is to force load of "huge" support from libm.a
3531 * So it is in perl for (say) POSIX to use.
3532 * Needed for SunOS with Sun's 'acc' for example.
3541 #ifdef PERL_GLOBAL_STRUCT
3550 Perl_get_op_names(pTHX)
3556 Perl_get_op_descs(pTHX)
3562 Perl_get_no_modify(pTHX)
3564 return (char*)PL_no_modify;
3568 Perl_get_opargs(pTHX)
3574 Perl_get_ppaddr(pTHX)
3579 #ifndef HAS_GETENV_LEN
3581 Perl_getenv_len(pTHX_ char *env_elem, unsigned long *len)
3583 char *env_trans = PerlEnv_getenv(env_elem);
3585 *len = strlen(env_trans);
3592 Perl_get_vtbl(pTHX_ int vtbl_id)
3594 MGVTBL* result = Null(MGVTBL*);
3598 result = &PL_vtbl_sv;
3601 result = &PL_vtbl_env;
3603 case want_vtbl_envelem:
3604 result = &PL_vtbl_envelem;
3607 result = &PL_vtbl_sig;
3609 case want_vtbl_sigelem:
3610 result = &PL_vtbl_sigelem;
3612 case want_vtbl_pack:
3613 result = &PL_vtbl_pack;
3615 case want_vtbl_packelem:
3616 result = &PL_vtbl_packelem;
3618 case want_vtbl_dbline:
3619 result = &PL_vtbl_dbline;
3622 result = &PL_vtbl_isa;
3624 case want_vtbl_isaelem:
3625 result = &PL_vtbl_isaelem;
3627 case want_vtbl_arylen:
3628 result = &PL_vtbl_arylen;
3630 case want_vtbl_glob:
3631 result = &PL_vtbl_glob;
3633 case want_vtbl_mglob:
3634 result = &PL_vtbl_mglob;
3636 case want_vtbl_nkeys:
3637 result = &PL_vtbl_nkeys;
3639 case want_vtbl_taint:
3640 result = &PL_vtbl_taint;
3642 case want_vtbl_substr:
3643 result = &PL_vtbl_substr;
3646 result = &PL_vtbl_vec;
3649 result = &PL_vtbl_pos;
3652 result = &PL_vtbl_bm;
3655 result = &PL_vtbl_fm;
3657 case want_vtbl_uvar:
3658 result = &PL_vtbl_uvar;
3661 case want_vtbl_mutex:
3662 result = &PL_vtbl_mutex;
3665 case want_vtbl_defelem:
3666 result = &PL_vtbl_defelem;
3668 case want_vtbl_regexp:
3669 result = &PL_vtbl_regexp;
3671 case want_vtbl_regdata:
3672 result = &PL_vtbl_regdata;
3674 case want_vtbl_regdatum:
3675 result = &PL_vtbl_regdatum;
3677 #ifdef USE_LOCALE_COLLATE
3678 case want_vtbl_collxfrm:
3679 result = &PL_vtbl_collxfrm;
3682 case want_vtbl_amagic:
3683 result = &PL_vtbl_amagic;
3685 case want_vtbl_amagicelem:
3686 result = &PL_vtbl_amagicelem;
3688 case want_vtbl_backref:
3689 result = &PL_vtbl_backref;
3696 Perl_my_fflush_all(pTHX)
3699 return PerlIO_flush(NULL);
3702 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3703 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3704 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3706 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3707 open_max = sysconf(_SC_OPEN_MAX);
3710 open_max = FOPEN_MAX;
3713 open_max = OPEN_MAX;
3724 for (i = 0; i < open_max; i++)
3725 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3726 STDIO_STREAM_ARRAY[i]._file < open_max &&
3727 STDIO_STREAM_ARRAY[i]._flag)
3728 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3732 SETERRNO(EBADF,RMS$_IFI);
3738 Perl_my_atof(pTHX_ const char* s) {
3739 #ifdef USE_LOCALE_NUMERIC
3740 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3744 SET_NUMERIC_STANDARD();
3746 SET_NUMERIC_LOCAL();
3747 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
3752 return Perl_atof(s);
3754 return Perl_atof(s);