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 /* paranoid version of system's malloc() */
71 /* NOTE: Do not call the next three routines directly. Use the macros
72 * in handy.h, so that we can easily redefine everything to do tracking of
73 * allocated hunks back to the original New to track down any memory leaks.
74 * XXX This advice seems to be widely ignored :-( --AD August 1996.
78 Perl_safesysmalloc(MEM_SIZE size)
83 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
86 #endif /* HAS_64K_LIMIT */
89 Perl_croak_nocontext("panic: malloc");
91 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
92 #if !(defined(I286) || defined(atarist))
93 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
95 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,PL_an++,(long)size));
102 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
103 WITH_THX(my_exit(1));
109 /* paranoid version of system's realloc() */
112 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
115 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
116 Malloc_t PerlMem_realloc();
117 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
121 PerlIO_printf(PerlIO_stderr(),
122 "Reallocation too large: %lx\n", size) FLUSH;
123 WITH_THX(my_exit(1));
125 #endif /* HAS_64K_LIMIT */
132 return safesysmalloc(size);
135 Perl_croak_nocontext("panic: realloc");
137 ptr = PerlMem_realloc(where,size);
139 #if !(defined(I286) || defined(atarist))
141 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,PL_an++);
142 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
146 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,PL_an++);
147 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,PL_an++,(long)size);
156 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
157 WITH_THX(my_exit(1));
163 /* safe version of system's free() */
166 Perl_safesysfree(Malloc_t where)
168 #if !(defined(I286) || defined(atarist))
169 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,PL_an++));
171 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,PL_an++));
179 /* safe version of system's calloc() */
182 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
187 if (size * count > 0xffff) {
188 PerlIO_printf(PerlIO_stderr(),
189 "Allocation too large: %lx\n", size * count) FLUSH;
190 WITH_THX(my_exit(1));
192 #endif /* HAS_64K_LIMIT */
194 if ((long)size < 0 || (long)count < 0)
195 Perl_croak_nocontext("panic: calloc");
198 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
199 #if !(defined(I286) || defined(atarist))
200 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
202 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,PL_an++,(long)count,(long)size));
205 memset((void*)ptr, 0, size);
211 PerlIO_puts(PerlIO_stderr(),PL_no_mem) FLUSH;
212 WITH_THX(my_exit(1));
220 struct mem_test_strut {
228 # define ALIGN sizeof(struct mem_test_strut)
230 # define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
231 # define typeof_chunk(ch) \
232 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
233 # define set_typeof_chunk(ch,t) \
234 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
235 #define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
238 ? ((size) - 1)/8 + 5 \
242 Perl_safexmalloc(I32 x, MEM_SIZE size)
244 register char* where = (char*)safemalloc(size + ALIGN);
247 xycount[x][SIZE_TO_Y(size)]++;
248 set_typeof_chunk(where, x);
249 sizeof_chunk(where) = size;
250 return (Malloc_t)(where + ALIGN);
254 Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
256 char *where = (char*)wh;
259 return safexmalloc(0,size);
262 MEM_SIZE old = sizeof_chunk(where - ALIGN);
263 int t = typeof_chunk(where - ALIGN);
264 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
266 xycount[t][SIZE_TO_Y(old)]--;
267 xycount[t][SIZE_TO_Y(size)]++;
268 xcount[t] += size - old;
269 sizeof_chunk(new) = size;
270 return (Malloc_t)(new + ALIGN);
275 Perl_safexfree(Malloc_t wh)
278 char *where = (char*)wh;
284 size = sizeof_chunk(where);
285 x = where[0] + 100 * where[1];
287 xycount[x][SIZE_TO_Y(size)]--;
292 Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
294 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
296 xycount[x][SIZE_TO_Y(size)]++;
297 memset((void*)(where + ALIGN), 0, size * count);
298 set_typeof_chunk(where, x);
299 sizeof_chunk(where) = size;
300 return (Malloc_t)(where + ALIGN);
304 S_xstat(pTHX_ int flag)
306 register I32 i, j, total = 0;
307 I32 subtot[MAXYCOUNT];
309 for (j = 0; j < MAXYCOUNT; j++) {
313 PerlIO_printf(PerlIO_stderr(), " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
314 for (i = 0; i < MAXXCOUNT; i++) {
316 for (j = 0; j < MAXYCOUNT; j++) {
317 subtot[j] += xycount[i][j];
320 ? xcount[i] /* Have something */
322 ? xcount[i] != lastxcount[i] /* Changed */
323 : xcount[i] > lastxcount[i])) { /* Growed */
324 PerlIO_printf(PerlIO_stderr(),"%2d %02d %7ld ", i / 100, i % 100,
325 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
326 lastxcount[i] = xcount[i];
327 for (j = 0; j < MAXYCOUNT; j++) {
329 ? xycount[i][j] /* Have something */
331 ? xycount[i][j] != lastxycount[i][j] /* Changed */
332 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
333 PerlIO_printf(PerlIO_stderr(),"%3ld ",
335 ? xycount[i][j] - lastxycount[i][j]
337 lastxycount[i][j] = xycount[i][j];
339 PerlIO_printf(PerlIO_stderr(), " . ", xycount[i][j]);
342 PerlIO_printf(PerlIO_stderr(), "\n");
346 PerlIO_printf(PerlIO_stderr(), "Total %7ld ", total);
347 for (j = 0; j < MAXYCOUNT; j++) {
349 PerlIO_printf(PerlIO_stderr(), "%3ld ", subtot[j]);
351 PerlIO_printf(PerlIO_stderr(), " . ");
354 PerlIO_printf(PerlIO_stderr(), "\n");
358 #endif /* LEAKTEST */
360 /* copy a string up to some (non-backslashed) delimiter, if any */
363 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
366 for (tolen = 0; from < fromend; from++, tolen++) {
368 if (from[1] == delim)
377 else if (*from == delim)
388 /* return ptr to little string in big string, NULL if not found */
389 /* This routine was donated by Corey Satten. */
392 Perl_instr(pTHX_ register const char *big, register const char *little)
394 register const char *s, *x;
405 for (x=big,s=little; *s; /**/ ) {
414 return (char*)(big-1);
419 /* same as instr but allow embedded nulls */
422 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
424 register const char *s, *x;
425 register I32 first = *little;
426 register const char *littleend = lend;
428 if (!first && little >= littleend)
430 if (bigend - big < littleend - little)
432 bigend -= littleend - little++;
433 while (big <= bigend) {
436 for (x=big,s=little; s < littleend; /**/ ) {
443 return (char*)(big-1);
448 /* reverse of the above--find last substring */
451 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
453 register const char *bigbeg;
454 register const char *s, *x;
455 register I32 first = *little;
456 register const char *littleend = lend;
458 if (!first && little >= littleend)
459 return (char*)bigend;
461 big = bigend - (littleend - little++);
462 while (big >= bigbeg) {
465 for (x=big+2,s=little; s < littleend; /**/ ) {
472 return (char*)(big+1);
478 * Set up for a new ctype locale.
481 Perl_new_ctype(pTHX_ const char *newctype)
483 #ifdef USE_LOCALE_CTYPE
487 for (i = 0; i < 256; i++) {
489 PL_fold_locale[i] = toLOWER_LC(i);
490 else if (isLOWER_LC(i))
491 PL_fold_locale[i] = toUPPER_LC(i);
493 PL_fold_locale[i] = i;
496 #endif /* USE_LOCALE_CTYPE */
500 * Set up for a new collation locale.
503 Perl_new_collate(pTHX_ const char *newcoll)
505 #ifdef USE_LOCALE_COLLATE
508 if (PL_collation_name) {
510 Safefree(PL_collation_name);
511 PL_collation_name = NULL;
512 PL_collation_standard = TRUE;
513 PL_collxfrm_base = 0;
514 PL_collxfrm_mult = 2;
519 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
521 Safefree(PL_collation_name);
522 PL_collation_name = savepv(newcoll);
523 PL_collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
526 /* 2: at most so many chars ('a', 'b'). */
527 /* 50: surely no system expands a char more. */
528 #define XFRMBUFSIZE (2 * 50)
529 char xbuf[XFRMBUFSIZE];
530 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
531 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
532 SSize_t mult = fb - fa;
534 Perl_croak(aTHX_ "strxfrm() gets absurd");
535 PL_collxfrm_base = (fa > mult) ? (fa - mult) : 0;
536 PL_collxfrm_mult = mult;
540 #endif /* USE_LOCALE_COLLATE */
544 perl_set_numeric_radix(void)
546 #ifdef USE_LOCALE_NUMERIC
547 # ifdef HAS_LOCALECONV
551 if (lc && lc->decimal_point)
552 /* We assume that decimal separator aka the radix
553 * character is always a single character. If it
554 * ever is a string, this needs to be rethunk. */
555 PL_numeric_radix = *lc->decimal_point;
557 PL_numeric_radix = 0;
558 # endif /* HAS_LOCALECONV */
560 PL_numeric_radix = 0;
561 #endif /* USE_LOCALE_NUMERIC */
565 * Set up for a new numeric locale.
568 Perl_new_numeric(pTHX_ const char *newnum)
570 #ifdef USE_LOCALE_NUMERIC
573 if (PL_numeric_name) {
574 Safefree(PL_numeric_name);
575 PL_numeric_name = NULL;
576 PL_numeric_standard = TRUE;
577 PL_numeric_local = TRUE;
582 if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
583 Safefree(PL_numeric_name);
584 PL_numeric_name = savepv(newnum);
585 PL_numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
586 PL_numeric_local = TRUE;
587 perl_set_numeric_radix();
590 #endif /* USE_LOCALE_NUMERIC */
594 Perl_set_numeric_standard(pTHX)
596 #ifdef USE_LOCALE_NUMERIC
598 if (! PL_numeric_standard) {
599 setlocale(LC_NUMERIC, "C");
600 PL_numeric_standard = TRUE;
601 PL_numeric_local = FALSE;
604 #endif /* USE_LOCALE_NUMERIC */
608 Perl_set_numeric_local(pTHX)
610 #ifdef USE_LOCALE_NUMERIC
612 if (! PL_numeric_local) {
613 setlocale(LC_NUMERIC, PL_numeric_name);
614 PL_numeric_standard = FALSE;
615 PL_numeric_local = TRUE;
616 perl_set_numeric_radix();
619 #endif /* USE_LOCALE_NUMERIC */
623 * Initialize locale awareness.
626 Perl_init_i18nl10n(pTHX_ int printwarn)
630 * 1 = set ok or not applicable,
631 * 0 = fallback to C locale,
632 * -1 = fallback to C locale failed
637 #ifdef USE_LOCALE_CTYPE
638 char *curctype = NULL;
639 #endif /* USE_LOCALE_CTYPE */
640 #ifdef USE_LOCALE_COLLATE
641 char *curcoll = NULL;
642 #endif /* USE_LOCALE_COLLATE */
643 #ifdef USE_LOCALE_NUMERIC
645 #endif /* USE_LOCALE_NUMERIC */
647 char *language = PerlEnv_getenv("LANGUAGE");
649 char *lc_all = PerlEnv_getenv("LC_ALL");
650 char *lang = PerlEnv_getenv("LANG");
651 bool setlocale_failure = FALSE;
653 #ifdef LOCALE_ENVIRON_REQUIRED
656 * Ultrix setlocale(..., "") fails if there are no environment
657 * variables from which to get a locale name.
664 if (setlocale(LC_ALL, ""))
667 setlocale_failure = TRUE;
669 if (!setlocale_failure) {
670 #ifdef USE_LOCALE_CTYPE
673 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
675 setlocale_failure = TRUE;
676 #endif /* USE_LOCALE_CTYPE */
677 #ifdef USE_LOCALE_COLLATE
679 setlocale(LC_COLLATE,
680 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
682 setlocale_failure = TRUE;
683 #endif /* USE_LOCALE_COLLATE */
684 #ifdef USE_LOCALE_NUMERIC
686 setlocale(LC_NUMERIC,
687 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
689 setlocale_failure = TRUE;
690 #endif /* USE_LOCALE_NUMERIC */
695 #endif /* !LOCALE_ENVIRON_REQUIRED */
698 if (! setlocale(LC_ALL, ""))
699 setlocale_failure = TRUE;
702 if (!setlocale_failure) {
703 #ifdef USE_LOCALE_CTYPE
704 if (! (curctype = setlocale(LC_CTYPE, "")))
705 setlocale_failure = TRUE;
706 #endif /* USE_LOCALE_CTYPE */
707 #ifdef USE_LOCALE_COLLATE
708 if (! (curcoll = setlocale(LC_COLLATE, "")))
709 setlocale_failure = TRUE;
710 #endif /* USE_LOCALE_COLLATE */
711 #ifdef USE_LOCALE_NUMERIC
712 if (! (curnum = setlocale(LC_NUMERIC, "")))
713 setlocale_failure = TRUE;
714 #endif /* USE_LOCALE_NUMERIC */
717 if (setlocale_failure) {
719 bool locwarn = (printwarn > 1 ||
721 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
726 PerlIO_printf(PerlIO_stderr(),
727 "perl: warning: Setting locale failed.\n");
731 PerlIO_printf(PerlIO_stderr(),
732 "perl: warning: Setting locale failed for the categories:\n\t");
733 #ifdef USE_LOCALE_CTYPE
735 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
736 #endif /* USE_LOCALE_CTYPE */
737 #ifdef USE_LOCALE_COLLATE
739 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
740 #endif /* USE_LOCALE_COLLATE */
741 #ifdef USE_LOCALE_NUMERIC
743 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
744 #endif /* USE_LOCALE_NUMERIC */
745 PerlIO_printf(PerlIO_stderr(), "\n");
749 PerlIO_printf(PerlIO_stderr(),
750 "perl: warning: Please check that your locale settings:\n");
753 PerlIO_printf(PerlIO_stderr(),
754 "\tLANGUAGE = %c%s%c,\n",
755 language ? '"' : '(',
756 language ? language : "unset",
757 language ? '"' : ')');
760 PerlIO_printf(PerlIO_stderr(),
761 "\tLC_ALL = %c%s%c,\n",
763 lc_all ? lc_all : "unset",
768 for (e = environ; *e; e++) {
769 if (strnEQ(*e, "LC_", 3)
770 && strnNE(*e, "LC_ALL=", 7)
771 && (p = strchr(*e, '=')))
772 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
773 (int)(p - *e), *e, p + 1);
777 PerlIO_printf(PerlIO_stderr(),
780 lang ? lang : "unset",
783 PerlIO_printf(PerlIO_stderr(),
784 " are supported and installed on your system.\n");
789 if (setlocale(LC_ALL, "C")) {
791 PerlIO_printf(PerlIO_stderr(),
792 "perl: warning: Falling back to the standard locale (\"C\").\n");
797 PerlIO_printf(PerlIO_stderr(),
798 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
805 #ifdef USE_LOCALE_CTYPE
806 || !(curctype || setlocale(LC_CTYPE, "C"))
807 #endif /* USE_LOCALE_CTYPE */
808 #ifdef USE_LOCALE_COLLATE
809 || !(curcoll || setlocale(LC_COLLATE, "C"))
810 #endif /* USE_LOCALE_COLLATE */
811 #ifdef USE_LOCALE_NUMERIC
812 || !(curnum || setlocale(LC_NUMERIC, "C"))
813 #endif /* USE_LOCALE_NUMERIC */
817 PerlIO_printf(PerlIO_stderr(),
818 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
822 #endif /* ! LC_ALL */
824 #ifdef USE_LOCALE_CTYPE
825 curctype = setlocale(LC_CTYPE, Nullch);
826 #endif /* USE_LOCALE_CTYPE */
827 #ifdef USE_LOCALE_COLLATE
828 curcoll = setlocale(LC_COLLATE, Nullch);
829 #endif /* USE_LOCALE_COLLATE */
830 #ifdef USE_LOCALE_NUMERIC
831 curnum = setlocale(LC_NUMERIC, Nullch);
832 #endif /* USE_LOCALE_NUMERIC */
835 #ifdef USE_LOCALE_CTYPE
837 #endif /* USE_LOCALE_CTYPE */
839 #ifdef USE_LOCALE_COLLATE
840 new_collate(curcoll);
841 #endif /* USE_LOCALE_COLLATE */
843 #ifdef USE_LOCALE_NUMERIC
845 #endif /* USE_LOCALE_NUMERIC */
847 #endif /* USE_LOCALE */
852 /* Backwards compatibility. */
854 Perl_init_i18nl14n(pTHX_ int printwarn)
856 return init_i18nl10n(printwarn);
859 #ifdef USE_LOCALE_COLLATE
862 * mem_collxfrm() is a bit like strxfrm() but with two important
863 * differences. First, it handles embedded NULs. Second, it allocates
864 * a bit more memory than needed for the transformed data itself.
865 * The real transformed data begins at offset sizeof(collationix).
866 * Please see sv_collxfrm() to see how this is used.
869 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
872 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
874 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
875 /* the +1 is for the terminating NUL. */
877 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
878 New(171, xbuf, xAlloc, char);
882 *(U32*)xbuf = PL_collation_ix;
883 xout = sizeof(PL_collation_ix);
884 for (xin = 0; xin < len; ) {
888 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
891 if (xused < xAlloc - xout)
893 xAlloc = (2 * xAlloc) + 1;
894 Renew(xbuf, xAlloc, char);
899 xin += strlen(s + xin) + 1;
902 /* Embedded NULs are understood but silently skipped
903 * because they make no sense in locale collation. */
907 *xlen = xout - sizeof(PL_collation_ix);
916 #endif /* USE_LOCALE_COLLATE */
918 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
920 /* As a space optimization, we do not compile tables for strings of length
921 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
922 special-cased in fbm_instr().
924 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
927 Perl_fbm_compile(pTHX_ SV *sv, U32 flags /* not used yet */)
936 if (flags & FBMcf_TAIL)
937 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
938 s = (U8*)SvPV_force(sv, len);
939 (void)SvUPGRADE(sv, SVt_PVBM);
940 if (len == 0) /* TAIL might be on on a zero-length string. */
948 Sv_Grow(sv,len + 256 + FBM_TABLE_OFFSET);
949 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
950 s = table - 1 - FBM_TABLE_OFFSET; /* Last char */
951 for (i = 0; i < 256; i++) {
954 table[-1] = flags; /* Not used yet */
958 if (table[*s] == mlen)
963 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
966 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
967 for (i = 0; i < len; i++) {
968 if (PL_freq[s[i]] < frequency) {
970 frequency = PL_freq[s[i]];
973 BmRARE(sv) = s[rarest];
974 BmPREVIOUS(sv) = rarest;
975 BmUSEFUL(sv) = 100; /* Initial value */
976 if (flags & FBMcf_TAIL)
978 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
981 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
982 /* If SvTAIL is actually due to \Z or \z, this gives false positives
986 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
988 register unsigned char *s;
990 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
991 register STRLEN littlelen = l;
992 register I32 multiline = flags & FBMrf_MULTILINE;
994 if (bigend - big < littlelen) {
996 if ( SvTAIL(littlestr)
997 && (bigend - big == littlelen - 1)
999 || *big == *little && memEQ(big, little, littlelen - 1)))
1004 if (littlelen <= 2) { /* Special-cased */
1007 if (littlelen == 1) {
1008 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
1009 /* Know that bigend != big. */
1010 if (bigend[-1] == '\n')
1011 return (char *)(bigend - 1);
1012 return (char *) bigend;
1015 while (s < bigend) {
1020 if (SvTAIL(littlestr))
1021 return (char *) bigend;
1025 return (char*)big; /* Cannot be SvTAIL! */
1027 /* littlelen is 2 */
1028 if (SvTAIL(littlestr) && !multiline) {
1029 if (bigend[-1] == '\n' && bigend[-2] == *little)
1030 return (char*)bigend - 2;
1031 if (bigend[-1] == *little)
1032 return (char*)bigend - 1;
1036 /* This should be better than FBM if c1 == c2, and almost
1037 as good otherwise: maybe better since we do less indirection.
1038 And we save a lot of memory by caching no table. */
1039 register unsigned char c1 = little[0];
1040 register unsigned char c2 = little[1];
1045 while (s <= bigend) {
1048 return (char*)s - 1;
1055 goto check_1char_anchor;
1066 goto check_1char_anchor;
1069 while (s <= bigend) {
1072 return (char*)s - 1;
1074 goto check_1char_anchor;
1083 check_1char_anchor: /* One char and anchor! */
1084 if (SvTAIL(littlestr) && (*bigend == *little))
1085 return (char *)bigend; /* bigend is already decremented. */
1088 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
1089 s = bigend - littlelen;
1091 && bigend[-1] == '\n'
1093 /* Automatically of length > 2 */
1094 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1095 return (char*)s; /* how sweet it is */
1096 if (s[1] == *little && memEQ((char*)s + 2,(char*)little + 1,
1098 return (char*)s + 1; /* how sweet it is */
1101 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1102 char *b = ninstr((char*)big,(char*)bigend,
1103 (char*)little, (char*)little + littlelen);
1105 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
1106 /* Chop \n from littlestr: */
1107 s = bigend - littlelen + 1;
1108 if (*s == *little && memEQ((char*)s + 1, (char*)little + 1,
1116 { /* Do actual FBM. */
1117 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1118 register unsigned char *oldlittle;
1120 if (littlelen > bigend - big)
1122 --littlelen; /* Last char found by table lookup */
1124 s = big + littlelen;
1125 little += littlelen; /* last char */
1132 if (tmp = table[*s]) {
1134 if (bigend - s > tmp) {
1140 if ((s += tmp) < bigend)
1145 else { /* less expensive than calling strncmp() */
1146 register unsigned char *olds = s;
1151 if (*--s == *--little)
1154 s = olds + 1; /* here we pay the price for failure */
1156 if (s < bigend) /* fake up continue to outer loop */
1164 if ( s == bigend && (table[-1] & FBMcf_TAIL)
1165 && memEQ(bigend - littlelen, oldlittle - littlelen, littlelen) )
1166 return (char*)bigend - littlelen;
1171 /* start_shift, end_shift are positive quantities which give offsets
1172 of ends of some substring of bigstr.
1173 If `last' we want the last occurence.
1174 old_posp is the way of communication between consequent calls if
1175 the next call needs to find the .
1176 The initial *old_posp should be -1.
1178 Note that we take into account SvTAIL, so one can get extra
1179 optimizations if _ALL flag is set.
1182 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1183 if PL_multiline. In fact if !PL_multiline the autoritative answer
1184 is not supported yet. */
1187 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1190 register unsigned char *s, *x;
1191 register unsigned char *big;
1193 register I32 previous;
1195 register unsigned char *little;
1196 register I32 stop_pos;
1197 register unsigned char *littleend;
1201 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1202 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1204 if ( BmRARE(littlestr) == '\n'
1205 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1206 little = (unsigned char *)(SvPVX(littlestr));
1207 littleend = little + SvCUR(littlestr);
1214 little = (unsigned char *)(SvPVX(littlestr));
1215 littleend = little + SvCUR(littlestr);
1217 /* The value of pos we can start at: */
1218 previous = BmPREVIOUS(littlestr);
1219 big = (unsigned char *)(SvPVX(bigstr));
1220 /* The value of pos we can stop at: */
1221 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1222 if (previous + start_shift > stop_pos) {
1223 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1227 while (pos < previous + start_shift) {
1228 if (!(pos += PL_screamnext[pos]))
1233 if (pos >= stop_pos) break;
1234 if (big[pos-previous] != first)
1236 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1242 if (s == littleend) {
1244 if (!last) return (char *)(big+pos-previous);
1247 } while ( pos += PL_screamnext[pos] );
1248 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1249 #else /* !POINTERRIGOR */
1252 if (pos >= stop_pos) break;
1253 if (big[pos] != first)
1255 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1261 if (s == littleend) {
1263 if (!last) return (char *)(big+pos);
1266 } while ( pos += PL_screamnext[pos] );
1268 return (char *)(big+(*old_posp));
1269 #endif /* POINTERRIGOR */
1271 if (!SvTAIL(littlestr) || (end_shift > 0))
1273 /* Ignore the trailing "\n". This code is not microoptimized */
1274 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1275 stop_pos = littleend - little; /* Actual littlestr len */
1280 && ((stop_pos == 1) || memEQ(big + 1, little, stop_pos - 1)))
1286 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1288 register U8 *a = (U8 *)s1;
1289 register U8 *b = (U8 *)s2;
1291 if (*a != *b && *a != PL_fold[*b])
1299 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1301 register U8 *a = (U8 *)s1;
1302 register U8 *b = (U8 *)s2;
1304 if (*a != *b && *a != PL_fold_locale[*b])
1311 /* copy a string to a safe spot */
1314 Perl_savepv(pTHX_ const char *sv)
1316 register char *newaddr;
1318 New(902,newaddr,strlen(sv)+1,char);
1319 (void)strcpy(newaddr,sv);
1323 /* same thing but with a known length */
1326 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1328 register char *newaddr;
1330 New(903,newaddr,len+1,char);
1331 Copy(sv,newaddr,len,char); /* might not be null terminated */
1332 newaddr[len] = '\0'; /* is now */
1336 /* the SV for Perl_form() and mess() is not kept in an arena */
1346 return sv_2mortal(newSVpvn("",0));
1351 /* Create as PVMG now, to avoid any upgrading later */
1352 New(905, sv, 1, SV);
1353 Newz(905, any, 1, XPVMG);
1354 SvFLAGS(sv) = SVt_PVMG;
1355 SvANY(sv) = (void*)any;
1356 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1361 #ifdef PERL_IMPLICIT_CONTEXT
1363 Perl_form_nocontext(const char* pat, ...)
1366 SV *sv = mess_alloc();
1368 va_start(args, pat);
1369 sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1376 Perl_form(pTHX_ const char* pat, ...)
1378 SV *sv = mess_alloc();
1380 va_start(args, pat);
1381 sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1387 Perl_mess(pTHX_ const char *pat, va_list *args)
1389 SV *sv = mess_alloc();
1390 static char dgd[] = " during global destruction.\n";
1392 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1393 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1395 if (PL_curcop->cop_line)
1396 Perl_sv_catpvf(aTHX_ sv, " at %_ line %ld",
1397 GvSV(PL_curcop->cop_filegv), (long)PL_curcop->cop_line);
1398 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1399 bool line_mode = (RsSIMPLE(PL_rs) &&
1400 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1401 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %ld",
1402 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1403 line_mode ? "line" : "chunk",
1404 (long)IoLINES(GvIOp(PL_last_in_gv)));
1406 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1412 S_do_die(pTHX_ const char* pat, va_list *args)
1416 int was_in_eval = PL_in_eval;
1423 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1424 "%p: die: curstack = %p, mainstack = %p\n",
1425 thr, PL_curstack, PL_mainstack));
1428 msv = mess(pat, args);
1429 message = SvPV(msv,msglen);
1435 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1436 "%p: die: message = %s\ndiehook = %p\n",
1437 thr, message, PL_diehook));
1439 /* sv_2cv might call Perl_croak() */
1440 SV *olddiehook = PL_diehook;
1442 SAVESPTR(PL_diehook);
1443 PL_diehook = Nullsv;
1444 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1446 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1452 msg = newSVpvn(message, msglen);
1460 PUSHSTACKi(PERLSI_DIEHOOK);
1464 call_sv((SV*)cv, G_DISCARD);
1470 PL_restartop = die_where(message, msglen);
1471 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1472 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1473 thr, PL_restartop, was_in_eval, PL_top_env));
1474 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1476 return PL_restartop;
1479 #ifdef PERL_IMPLICIT_CONTEXT
1481 Perl_die_nocontext(const char* pat, ...)
1486 va_start(args, pat);
1487 o = do_die(aTHX_ pat, &args);
1494 Perl_die(pTHX_ const char* pat, ...)
1498 va_start(args, pat);
1499 o = do_die(aTHX_ pat, &args);
1505 S_do_croak(pTHX_ const char* pat, va_list *args)
1515 msv = mess(pat, args);
1516 message = SvPV(msv,msglen);
1517 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1519 /* sv_2cv might call Perl_croak() */
1520 SV *olddiehook = PL_diehook;
1522 SAVESPTR(PL_diehook);
1523 PL_diehook = Nullsv;
1524 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1526 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1531 msg = newSVpvn(message, msglen);
1535 PUSHSTACKi(PERLSI_DIEHOOK);
1539 call_sv((SV*)cv, G_DISCARD);
1545 PL_restartop = die_where(message, msglen);
1550 /* SFIO can really mess with your errno */
1553 PerlIO_write(PerlIO_stderr(), message, msglen);
1554 (void)PerlIO_flush(PerlIO_stderr());
1562 #ifdef PERL_IMPLICIT_CONTEXT
1564 Perl_croak_nocontext(const char *pat, ...)
1568 va_start(args, pat);
1569 do_croak(pat, &args);
1573 #endif /* PERL_IMPLICIT_CONTEXT */
1576 Perl_croak(pTHX_ const char *pat, ...)
1579 va_start(args, pat);
1580 do_croak(pat, &args);
1586 S_do_warn(pTHX_ const char* pat, va_list *args)
1595 msv = mess(pat, args);
1596 message = SvPV(msv, msglen);
1599 /* sv_2cv might call Perl_warn() */
1601 SV *oldwarnhook = PL_warnhook;
1603 SAVESPTR(PL_warnhook);
1604 PL_warnhook = Nullsv;
1605 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1607 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1612 msg = newSVpvn(message, msglen);
1616 PUSHSTACKi(PERLSI_WARNHOOK);
1620 call_sv((SV*)cv, G_DISCARD);
1626 PerlIO_write(PerlIO_stderr(), message, msglen);
1628 DEBUG_L(*message == '!'
1629 ? (xstat(message[1]=='!'
1630 ? (message[2]=='!' ? 2 : 1)
1635 (void)PerlIO_flush(PerlIO_stderr());
1638 #ifdef PERL_IMPLICIT_CONTEXT
1640 Perl_warn_nocontext(const char *pat, ...)
1644 va_start(args, pat);
1645 do_warn(pat, &args);
1648 #endif /* PERL_IMPLICIT_CONTEXT */
1651 Perl_warn(pTHX_ const char *pat, ...)
1654 va_start(args, pat);
1655 do_warn(pat, &args);
1660 Perl_warner(pTHX_ U32 err, const char* pat,...)
1671 va_start(args, pat);
1672 msv = mess(pat, &args);
1673 message = SvPV(msv, msglen);
1678 DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1679 #endif /* USE_THREADS */
1681 /* sv_2cv might call Perl_croak() */
1682 SV *olddiehook = PL_diehook;
1684 SAVESPTR(PL_diehook);
1685 PL_diehook = Nullsv;
1686 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1688 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1693 msg = newSVpvn(message, msglen);
1700 call_sv((SV*)cv, G_DISCARD);
1706 PL_restartop = die_where(message, msglen);
1709 PerlIO_write(PerlIO_stderr(), message, msglen);
1710 (void)PerlIO_flush(PerlIO_stderr());
1716 /* sv_2cv might call Perl_warn() */
1718 SV *oldwarnhook = PL_warnhook;
1720 SAVESPTR(PL_warnhook);
1721 PL_warnhook = Nullsv;
1722 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1724 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1729 msg = newSVpvn(message, msglen);
1736 call_sv((SV*)cv, G_DISCARD);
1742 PerlIO_write(PerlIO_stderr(), message, msglen);
1746 (void)PerlIO_flush(PerlIO_stderr());
1750 #ifndef VMS /* VMS' my_setenv() is in VMS.c */
1751 #if !defined(WIN32) && !defined(CYGWIN32)
1753 Perl_my_setenv(pTHX_ char *nam, char *val)
1755 #ifndef PERL_USE_SAFE_PUTENV
1756 /* most putenv()s leak, so we manipulate environ directly */
1757 register I32 i=setenv_getix(nam); /* where does it go? */
1759 if (environ == PL_origenviron) { /* need we copy environment? */
1765 for (max = i; environ[max]; max++) ;
1766 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1767 for (j=0; j<max; j++) { /* copy environment */
1768 tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1769 strcpy(tmpenv[j], environ[j]);
1771 tmpenv[max] = Nullch;
1772 environ = tmpenv; /* tell exec where it is now */
1775 safesysfree(environ[i]);
1776 while (environ[i]) {
1777 environ[i] = environ[i+1];
1782 if (!environ[i]) { /* does not exist yet */
1783 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1784 environ[i+1] = Nullch; /* make sure it's null terminated */
1787 safesysfree(environ[i]);
1788 environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1791 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1793 /* MS-DOS requires environment variable names to be in uppercase */
1794 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1795 * some utilities and applications may break because they only look
1796 * for upper case strings. (Fixed strupr() bug here.)]
1798 strcpy(environ[i],nam); strupr(environ[i]);
1799 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1802 #else /* PERL_USE_SAFE_PUTENV */
1805 new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1807 (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1809 strcpy(new_env,nam); strupr(new_env);
1810 (void)sprintf(new_env + strlen(nam),"=%s",val);
1812 (void)putenv(new_env);
1813 #endif /* PERL_USE_SAFE_PUTENV */
1816 #else /* if WIN32 */
1819 Perl_my_setenv(pTHX_ char *nam,char *val)
1822 #ifdef USE_WIN32_RTL_ENV
1824 register char *envstr;
1825 STRLEN namlen = strlen(nam);
1827 char *oldstr = environ[setenv_getix(nam)];
1829 /* putenv() has totally broken semantics in both the Borland
1830 * and Microsoft CRTLs. They either store the passed pointer in
1831 * the environment without making a copy, or make a copy and don't
1832 * free it. And on top of that, they dont free() old entries that
1833 * are being replaced/deleted. This means the caller must
1834 * free any old entries somehow, or we end up with a memory
1835 * leak every time my_setenv() is called. One might think
1836 * one could directly manipulate environ[], like the UNIX code
1837 * above, but direct changes to environ are not allowed when
1838 * calling putenv(), since the RTLs maintain an internal
1839 * *copy* of environ[]. Bad, bad, *bad* stink.
1850 vallen = strlen(val);
1851 envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
1852 (void)sprintf(envstr,"%s=%s",nam,val);
1853 (void)PerlEnv_putenv(envstr);
1855 safesysfree(oldstr);
1857 safesysfree(envstr); /* MSVCRT leaks without this */
1860 #else /* !USE_WIN32_RTL_ENV */
1862 register char *envstr;
1863 STRLEN len = strlen(nam) + 3;
1868 New(904, envstr, len, char);
1869 (void)sprintf(envstr,"%s=%s",nam,val);
1870 (void)PerlEnv_putenv(envstr);
1879 Perl_setenv_getix(pTHX_ char *nam)
1881 register I32 i, len = strlen(nam);
1883 for (i = 0; environ[i]; i++) {
1886 strnicmp(environ[i],nam,len) == 0
1888 strnEQ(environ[i],nam,len)
1890 && environ[i][len] == '=')
1891 break; /* strnEQ must come first to avoid */
1892 } /* potential SEGV's */
1898 #ifdef UNLINK_ALL_VERSIONS
1900 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1904 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1909 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1911 Perl_my_bcopy(pTHX_ register const char *from,register char *to,register I32 len)
1915 if (from - to >= 0) {
1923 *(--to) = *(--from);
1931 Perl_my_memset(pTHX_ register char *loc, register I32 ch, register I32 len)
1941 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1943 Perl_my_bzero(pTHX_ register char *loc, register I32 len)
1953 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1955 Perl_my_memcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1957 register U8 *a = (U8 *)s1;
1958 register U8 *b = (U8 *)s2;
1962 if (tmp = *a++ - *b++)
1967 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1971 #ifdef USE_CHAR_VSPRINTF
1976 vsprintf(char *dest, const char *pat, char *args)
1980 fakebuf._ptr = dest;
1981 fakebuf._cnt = 32767;
1985 fakebuf._flag = _IOWRT|_IOSTRG;
1986 _doprnt(pat, args, &fakebuf); /* what a kludge */
1987 (void)putc('\0', &fakebuf);
1988 #ifdef USE_CHAR_VSPRINTF
1991 return 0; /* perl doesn't use return value */
1995 #endif /* HAS_VPRINTF */
1998 #if BYTEORDER != 0x4321
2000 Perl_my_swap(pTHX_ short s)
2002 #if (BYTEORDER & 1) == 0
2005 result = ((s & 255) << 8) + ((s >> 8) & 255);
2013 Perl_my_htonl(pTHX_ long l)
2017 char c[sizeof(long)];
2020 #if BYTEORDER == 0x1234
2021 u.c[0] = (l >> 24) & 255;
2022 u.c[1] = (l >> 16) & 255;
2023 u.c[2] = (l >> 8) & 255;
2027 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2028 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2033 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2034 u.c[o & 0xf] = (l >> s) & 255;
2042 Perl_my_ntohl(pTHX_ long l)
2046 char c[sizeof(long)];
2049 #if BYTEORDER == 0x1234
2050 u.c[0] = (l >> 24) & 255;
2051 u.c[1] = (l >> 16) & 255;
2052 u.c[2] = (l >> 8) & 255;
2056 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2057 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2064 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2065 l |= (u.c[o & 0xf] & 255) << s;
2072 #endif /* BYTEORDER != 0x4321 */
2076 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2077 * If these functions are defined,
2078 * the BYTEORDER is neither 0x1234 nor 0x4321.
2079 * However, this is not assumed.
2083 #define HTOV(name,type) \
2085 name (register type n) \
2089 char c[sizeof(type)]; \
2093 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2094 u.c[i] = (n >> s) & 0xFF; \
2099 #define VTOH(name,type) \
2101 name (register type n) \
2105 char c[sizeof(type)]; \
2111 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
2112 n += (u.c[i] & 0xFF) << s; \
2117 #if defined(HAS_HTOVS) && !defined(htovs)
2120 #if defined(HAS_HTOVL) && !defined(htovl)
2123 #if defined(HAS_VTOHS) && !defined(vtohs)
2126 #if defined(HAS_VTOHL) && !defined(vtohl)
2130 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2131 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC)
2133 Perl_my_popen(pTHX_ char *cmd, char *mode)
2136 register I32 This, that;
2139 I32 doexec = strNE(cmd,"-");
2143 PERL_FLUSHALL_FOR_CHILD;
2146 return my_syspopen(cmd,mode);
2149 This = (*mode == 'w');
2151 if (doexec && PL_tainting) {
2153 taint_proper("Insecure %s%s", "EXEC");
2155 if (PerlProc_pipe(p) < 0)
2157 if (doexec && PerlProc_pipe(pp) >= 0)
2159 while ((pid = (doexec?vfork():fork())) < 0) {
2160 if (errno != EAGAIN) {
2161 PerlLIO_close(p[This]);
2163 PerlLIO_close(pp[0]);
2164 PerlLIO_close(pp[1]);
2167 Perl_croak(aTHX_ "Can't fork");
2179 PerlLIO_close(p[THAT]);
2181 PerlLIO_close(pp[0]);
2182 #if defined(HAS_FCNTL) && defined(F_SETFD)
2183 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2186 if (p[THIS] != (*mode == 'r')) {
2187 PerlLIO_dup2(p[THIS], *mode == 'r');
2188 PerlLIO_close(p[THIS]);
2192 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2198 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2202 do_exec3(cmd,pp[1],did_pipes); /* may or may not use the shell */
2205 #endif /* defined OS2 */
2207 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2208 sv_setiv(GvSV(tmpgv), (IV)getpid());
2210 hv_clear(PL_pidstatus); /* we have no children */
2215 do_execfree(); /* free any memory malloced by child on vfork */
2216 PerlLIO_close(p[that]);
2218 PerlLIO_close(pp[1]);
2219 if (p[that] < p[This]) {
2220 PerlLIO_dup2(p[This], p[that]);
2221 PerlLIO_close(p[This]);
2224 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2225 (void)SvUPGRADE(sv,SVt_IV);
2227 PL_forkprocess = pid;
2228 if (did_pipes && pid > 0) {
2232 while (n < sizeof(int)) {
2233 n1 = PerlLIO_read(pp[0],
2234 (void*)(((char*)&errkid)+n),
2240 if (n) { /* Error */
2241 if (n != sizeof(int))
2242 Perl_croak(aTHX_ "panic: kid popen errno read");
2243 PerlLIO_close(pp[0]);
2244 errno = errkid; /* Propagate errno from kid */
2249 PerlLIO_close(pp[0]);
2250 return PerlIO_fdopen(p[This], mode);
2253 #if defined(atarist) || defined(DJGPP)
2256 Perl_my_popen(pTHX_ char *cmd, char *mode)
2258 /* Needs work for PerlIO ! */
2259 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
2260 PERL_FLUSHALL_FOR_CHILD;
2261 return popen(PerlIO_exportFILE(cmd, 0), mode);
2265 #endif /* !DOSISH */
2269 Perl_dump_fds(pTHX_ char *s)
2272 struct stat tmpstatbuf;
2274 PerlIO_printf(PerlIO_stderr(),"%s", s);
2275 for (fd = 0; fd < 32; fd++) {
2276 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2277 PerlIO_printf(PerlIO_stderr()," %d",fd);
2279 PerlIO_printf(PerlIO_stderr(),"\n");
2281 #endif /* DUMP_FDS */
2285 dup2(int oldfd, int newfd)
2287 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2290 PerlLIO_close(newfd);
2291 return fcntl(oldfd, F_DUPFD, newfd);
2293 #define DUP2_MAX_FDS 256
2294 int fdtmp[DUP2_MAX_FDS];
2300 PerlLIO_close(newfd);
2301 /* good enough for low fd's... */
2302 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2303 if (fdx >= DUP2_MAX_FDS) {
2311 PerlLIO_close(fdtmp[--fdx]);
2318 #ifdef HAS_SIGACTION
2321 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2323 struct sigaction act, oact;
2325 act.sa_handler = handler;
2326 sigemptyset(&act.sa_mask);
2329 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2332 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2333 act.sa_flags |= SA_NOCLDWAIT;
2335 if (sigaction(signo, &act, &oact) == -1)
2338 return oact.sa_handler;
2342 Perl_rsignal_state(pTHX_ int signo)
2344 struct sigaction oact;
2346 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2349 return oact.sa_handler;
2353 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2355 struct sigaction act;
2357 act.sa_handler = handler;
2358 sigemptyset(&act.sa_mask);
2361 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2364 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2365 act.sa_flags |= SA_NOCLDWAIT;
2367 return sigaction(signo, &act, save);
2371 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2373 return sigaction(signo, save, (struct sigaction *)NULL);
2376 #else /* !HAS_SIGACTION */
2379 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2381 return PerlProc_signal(signo, handler);
2384 static int sig_trapped;
2394 Perl_rsignal_state(pTHX_ int signo)
2396 Sighandler_t oldsig;
2399 oldsig = PerlProc_signal(signo, sig_trap);
2400 PerlProc_signal(signo, oldsig);
2402 PerlProc_kill(getpid(), signo);
2407 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2409 *save = PerlProc_signal(signo, handler);
2410 return (*save == SIG_ERR) ? -1 : 0;
2414 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2416 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2419 #endif /* !HAS_SIGACTION */
2421 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2422 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC)
2424 Perl_my_pclose(pTHX_ PerlIO *ptr)
2426 Sigsave_t hstat, istat, qstat;
2434 int saved_vaxc_errno;
2437 int saved_win32_errno;
2440 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2441 pid = (int)SvIVX(*svp);
2443 *svp = &PL_sv_undef;
2445 if (pid == -1) { /* Opened by popen. */
2446 return my_syspclose(ptr);
2449 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2450 saved_errno = errno;
2452 saved_vaxc_errno = vaxc$errno;
2455 saved_win32_errno = GetLastError();
2459 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2461 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2462 rsignal_save(SIGINT, SIG_IGN, &istat);
2463 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2465 pid2 = wait4pid(pid, &status, 0);
2466 } while (pid2 == -1 && errno == EINTR);
2467 rsignal_restore(SIGHUP, &hstat);
2468 rsignal_restore(SIGINT, &istat);
2469 rsignal_restore(SIGQUIT, &qstat);
2471 SETERRNO(saved_errno, saved_vaxc_errno);
2474 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2476 #endif /* !DOSISH */
2478 #if !defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(CYGWIN32)
2480 Perl_wait4pid(pTHX_ int pid, int *statusp, int flags)
2484 char spid[TYPE_CHARS(int)];
2489 sprintf(spid, "%d", pid);
2490 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2491 if (svp && *svp != &PL_sv_undef) {
2492 *statusp = SvIVX(*svp);
2493 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2500 hv_iterinit(PL_pidstatus);
2501 if (entry = hv_iternext(PL_pidstatus)) {
2502 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2503 sv = hv_iterval(PL_pidstatus,entry);
2504 *statusp = SvIVX(sv);
2505 sprintf(spid, "%d", pid);
2506 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2511 # ifdef HAS_WAITPID_RUNTIME
2512 if (!HAS_WAITPID_RUNTIME)
2515 return PerlProc_waitpid(pid,statusp,flags);
2517 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2518 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2520 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2525 Perl_croak(aTHX_ "Can't do waitpid with flags");
2527 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2528 pidgone(result,*statusp);
2536 #endif /* !DOSISH || OS2 || WIN32 */
2540 Perl_pidgone(pTHX_ int pid, int status)
2543 char spid[TYPE_CHARS(int)];
2545 sprintf(spid, "%d", pid);
2546 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2547 (void)SvUPGRADE(sv,SVt_IV);
2552 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2555 int /* Cannot prototype with I32
2557 my_syspclose(PerlIO *ptr)
2560 Perl_my_pclose(pTHX_ PerlIO *ptr)
2563 /* Needs work for PerlIO ! */
2564 FILE *f = PerlIO_findFILE(ptr);
2565 I32 result = pclose(f);
2566 PerlIO_releaseFILE(ptr,f);
2572 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2575 register const char *frombase = from;
2578 register const char c = *from;
2583 while (count-- > 0) {
2584 for (todo = len; todo > 0; todo--) {
2592 Perl_cast_ulong(pTHX_ double f)
2597 # define BIGDOUBLE 2147483648.0
2599 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2602 return (unsigned long)f;
2604 return (unsigned long)along;
2608 /* Unfortunately, on some systems the cast_uv() function doesn't
2609 work with the system-supplied definition of ULONG_MAX. The
2610 comparison (f >= ULONG_MAX) always comes out true. It must be a
2611 problem with the compiler constant folding.
2613 In any case, this workaround should be fine on any two's complement
2614 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2616 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2619 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2621 -- Kenneth Albanowski <kjahds@kjahds.com>
2625 # define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2629 Perl_cast_i32(pTHX_ double f)
2632 return (I32) I32_MAX;
2634 return (I32) I32_MIN;
2639 Perl_cast_iv(pTHX_ double f)
2644 if (f >= (double)UV_MAX)
2655 Perl_cast_uv(pTHX_ double f)
2658 return (UV) MY_UV_MAX;
2672 Perl_same_dirent(pTHX_ char *a, char *b)
2674 char *fa = strrchr(a,'/');
2675 char *fb = strrchr(b,'/');
2676 struct stat tmpstatbuf1;
2677 struct stat tmpstatbuf2;
2678 SV *tmpsv = sv_newmortal();
2691 sv_setpv(tmpsv, ".");
2693 sv_setpvn(tmpsv, a, fa - a);
2694 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2697 sv_setpv(tmpsv, ".");
2699 sv_setpvn(tmpsv, b, fb - b);
2700 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2702 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2703 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2705 #endif /* !HAS_RENAME */
2708 Perl_scan_bin(pTHX_ char *start, I32 len, I32 *retlen)
2710 register char *s = start;
2711 register UV retval = 0;
2712 bool overflowed = FALSE;
2713 while (len && *s >= '0' && *s <= '1') {
2714 register UV n = retval << 1;
2715 if (!overflowed && (n >> 1) != retval) {
2716 Perl_warn(aTHX_ "Integer overflow in binary number");
2719 retval = n | (*s++ - '0');
2722 if (len && (*s >= '2' && *s <= '9')) {
2724 if (ckWARN(WARN_UNSAFE))
2725 Perl_warner(aTHX_ WARN_UNSAFE, "Illegal binary digit '%c' ignored", *s);
2727 *retlen = s - start;
2731 Perl_scan_oct(pTHX_ char *start, I32 len, I32 *retlen)
2733 register char *s = start;
2734 register UV retval = 0;
2735 bool overflowed = FALSE;
2737 while (len && *s >= '0' && *s <= '7') {
2738 register UV n = retval << 3;
2739 if (!overflowed && (n >> 3) != retval) {
2740 Perl_warn(aTHX_ "Integer overflow in octal number");
2743 retval = n | (*s++ - '0');
2746 if (len && (*s == '8' || *s == '9')) {
2748 if (ckWARN(WARN_OCTAL))
2749 Perl_warner(aTHX_ WARN_OCTAL, "Illegal octal digit '%c' ignored", *s);
2751 *retlen = s - start;
2756 Perl_scan_hex(pTHX_ char *start, I32 len, I32 *retlen)
2758 register char *s = start;
2759 register UV retval = 0;
2760 bool overflowed = FALSE;
2764 while (len-- && *s) {
2765 tmp = strchr((char *) PL_hexdigit, *s++);
2767 if (*(s-1) == '_' || (*(s-1) == 'x' && retval == 0))
2772 if (ckWARN(WARN_UNSAFE))
2773 Perl_warner(aTHX_ WARN_UNSAFE,"Illegal hex digit '%c' ignored", *s);
2778 if (!overflowed && (n >> 4) != retval) {
2779 Perl_warn(aTHX_ "Integer overflow in hex number");
2782 retval = n | ((tmp - PL_hexdigit) & 15);
2784 *retlen = s - start;
2789 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2792 char *xfound = Nullch;
2793 char *xfailed = Nullch;
2794 char tmpbuf[MAXPATHLEN];
2798 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2799 # define SEARCH_EXTS ".bat", ".cmd", NULL
2800 # define MAX_EXT_LEN 4
2803 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2804 # define MAX_EXT_LEN 4
2807 # define SEARCH_EXTS ".pl", ".com", NULL
2808 # define MAX_EXT_LEN 4
2810 /* additional extensions to try in each dir if scriptname not found */
2812 char *exts[] = { SEARCH_EXTS };
2813 char **ext = search_ext ? search_ext : exts;
2814 int extidx = 0, i = 0;
2815 char *curext = Nullch;
2817 # define MAX_EXT_LEN 0
2821 * If dosearch is true and if scriptname does not contain path
2822 * delimiters, search the PATH for scriptname.
2824 * If SEARCH_EXTS is also defined, will look for each
2825 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2826 * while searching the PATH.
2828 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2829 * proceeds as follows:
2830 * If DOSISH or VMSISH:
2831 * + look for ./scriptname{,.foo,.bar}
2832 * + search the PATH for scriptname{,.foo,.bar}
2835 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2836 * this will not look in '.' if it's not in the PATH)
2841 # ifdef ALWAYS_DEFTYPES
2842 len = strlen(scriptname);
2843 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2844 int hasdir, idx = 0, deftypes = 1;
2847 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2850 int hasdir, idx = 0, deftypes = 1;
2853 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2855 /* The first time through, just add SEARCH_EXTS to whatever we
2856 * already have, so we can check for default file types. */
2858 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2864 if ((strlen(tmpbuf) + strlen(scriptname)
2865 + MAX_EXT_LEN) >= sizeof tmpbuf)
2866 continue; /* don't search dir with too-long name */
2867 strcat(tmpbuf, scriptname);
2871 if (strEQ(scriptname, "-"))
2873 if (dosearch) { /* Look in '.' first. */
2874 char *cur = scriptname;
2876 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2878 if (strEQ(ext[i++],curext)) {
2879 extidx = -1; /* already has an ext */
2884 DEBUG_p(PerlIO_printf(Perl_debug_log,
2885 "Looking for %s\n",cur));
2886 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2887 && !S_ISDIR(PL_statbuf.st_mode)) {
2895 if (cur == scriptname) {
2896 len = strlen(scriptname);
2897 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2899 cur = strcpy(tmpbuf, scriptname);
2901 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2902 && strcpy(tmpbuf+len, ext[extidx++]));
2907 if (dosearch && !strchr(scriptname, '/')
2909 && !strchr(scriptname, '\\')
2911 && (s = PerlEnv_getenv("PATH"))) {
2914 PL_bufend = s + strlen(s);
2915 while (s < PL_bufend) {
2916 #if defined(atarist) || defined(DOSISH)
2921 && *s != ';'; len++, s++) {
2922 if (len < sizeof tmpbuf)
2925 if (len < sizeof tmpbuf)
2927 #else /* ! (atarist || DOSISH) */
2928 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2931 #endif /* ! (atarist || DOSISH) */
2934 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2935 continue; /* don't search dir with too-long name */
2937 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2938 && tmpbuf[len - 1] != '/'
2939 && tmpbuf[len - 1] != '\\'
2942 tmpbuf[len++] = '/';
2943 if (len == 2 && tmpbuf[0] == '.')
2945 (void)strcpy(tmpbuf + len, scriptname);
2949 len = strlen(tmpbuf);
2950 if (extidx > 0) /* reset after previous loop */
2954 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2955 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2956 if (S_ISDIR(PL_statbuf.st_mode)) {
2960 } while ( retval < 0 /* not there */
2961 && extidx>=0 && ext[extidx] /* try an extension? */
2962 && strcpy(tmpbuf+len, ext[extidx++])
2967 if (S_ISREG(PL_statbuf.st_mode)
2968 && cando(S_IRUSR,TRUE,&PL_statbuf)
2970 && cando(S_IXUSR,TRUE,&PL_statbuf)
2974 xfound = tmpbuf; /* bingo! */
2978 xfailed = savepv(tmpbuf);
2981 if (!xfound && !seen_dot && !xfailed &&
2982 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2983 || S_ISDIR(PL_statbuf.st_mode)))
2985 seen_dot = 1; /* Disable message. */
2987 if (flags & 1) { /* do or die? */
2988 Perl_croak(aTHX_ "Can't %s %s%s%s",
2989 (xfailed ? "execute" : "find"),
2990 (xfailed ? xfailed : scriptname),
2991 (xfailed ? "" : " on PATH"),
2992 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2994 scriptname = Nullch;
2998 scriptname = xfound;
3000 return (scriptname ? savepv(scriptname) : Nullch);
3006 /* Very simplistic scheduler for now */
3010 thr = thr->i.next_run;
3014 Perl_cond_init(pTHX_ perl_cond *cp)
3020 Perl_cond_signal(pTHX_ perl_cond *cp)
3023 perl_cond cond = *cp;
3028 /* Insert t in the runnable queue just ahead of us */
3029 t->i.next_run = thr->i.next_run;
3030 thr->i.next_run->i.prev_run = t;
3031 t->i.prev_run = thr;
3032 thr->i.next_run = t;
3033 thr->i.wait_queue = 0;
3034 /* Remove from the wait queue */
3040 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3043 perl_cond cond, cond_next;
3045 for (cond = *cp; cond; cond = cond_next) {
3047 /* Insert t in the runnable queue just ahead of us */
3048 t->i.next_run = thr->i.next_run;
3049 thr->i.next_run->i.prev_run = t;
3050 t->i.prev_run = thr;
3051 thr->i.next_run = t;
3052 thr->i.wait_queue = 0;
3053 /* Remove from the wait queue */
3054 cond_next = cond->next;
3061 Perl_cond_wait(pTHX_ perl_cond *cp)
3065 if (thr->i.next_run == thr)
3066 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3068 New(666, cond, 1, struct perl_wait_queue);
3072 thr->i.wait_queue = cond;
3073 /* Remove ourselves from runnable queue */
3074 thr->i.next_run->i.prev_run = thr->i.prev_run;
3075 thr->i.prev_run->i.next_run = thr->i.next_run;
3077 #endif /* FAKE_THREADS */
3079 #ifdef PTHREAD_GETSPECIFIC_INT
3080 struct perl_thread *
3085 if (pthread_getspecific(PL_thr_key, &t))
3086 Perl_croak(aTHX_ "panic: pthread_getspecific");
3087 return (struct perl_thread *) t;
3092 Perl_condpair_magic(pTHX_ SV *sv)
3096 SvUPGRADE(sv, SVt_PVMG);
3097 mg = mg_find(sv, 'm');
3101 New(53, cp, 1, condpair_t);
3102 MUTEX_INIT(&cp->mutex);
3103 COND_INIT(&cp->owner_cond);
3104 COND_INIT(&cp->cond);
3106 MUTEX_LOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3107 mg = mg_find(sv, 'm');
3109 /* someone else beat us to initialising it */
3110 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3111 MUTEX_DESTROY(&cp->mutex);
3112 COND_DESTROY(&cp->owner_cond);
3113 COND_DESTROY(&cp->cond);
3117 sv_magic(sv, Nullsv, 'm', 0, 0);
3119 mg->mg_ptr = (char *)cp;
3120 mg->mg_len = sizeof(cp);
3121 MUTEX_UNLOCK(&PL_cred_mutex); /* XXX need separate mutex? */
3122 DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
3123 "%p: condpair_magic %p\n", thr, sv));)
3130 * Make a new perl thread structure using t as a prototype. Some of the
3131 * fields for the new thread are copied from the prototype thread, t,
3132 * so t should not be running in perl at the time this function is
3133 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3134 * thread calling new_struct_thread) clearly satisfies this constraint.
3136 struct perl_thread *
3137 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3139 #ifndef PERL_IMPLICIT_CONTEXT
3140 struct perl_thread *thr;
3146 sv = newSVpvn("", 0);
3147 SvGROW(sv, sizeof(struct perl_thread) + 1);
3148 SvCUR_set(sv, sizeof(struct perl_thread));
3149 thr = (Thread) SvPVX(sv);
3151 memset(thr, 0xab, sizeof(struct perl_thread));
3158 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3160 Zero(thr, 1, struct perl_thread);
3163 PL_protect = FUNC_NAME_TO_PTR(Perl_default_protect);
3168 PL_curcop = &PL_compiling;
3169 thr->cvcache = newHV();
3170 thr->threadsv = newAV();
3171 thr->specific = newAV();
3172 thr->errsv = newSVpvn("", 0);
3173 thr->errhv = newHV();
3174 thr->flags = THRf_R_JOINABLE;
3175 MUTEX_INIT(&thr->mutex);
3177 /* top_env needs to be non-zero. It points to an area
3178 in which longjmp() stuff is stored, as C callstack
3179 info there at least is thread specific this has to
3180 be per-thread. Otherwise a 'die' in a thread gives
3181 that thread the C stack of last thread to do an eval {}!
3182 See comments in scope.h
3183 Initialize top entry (as in perl.c for main thread)
3185 PL_start_env.je_prev = NULL;
3186 PL_start_env.je_ret = -1;
3187 PL_start_env.je_mustcatch = TRUE;
3188 PL_top_env = &PL_start_env;
3190 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR) */
3193 PL_statname = NEWSV(66,0);
3195 PL_regcompp = FUNC_NAME_TO_PTR(Perl_pregcomp);
3196 PL_regexecp = FUNC_NAME_TO_PTR(Perl_regexec_flags);
3198 PL_reginterp_cnt = 0;
3199 PL_lastscream = Nullsv;
3202 PL_reg_start_tmp = 0;
3203 PL_reg_start_tmpl = 0;
3205 /* parent thread's data needs to be locked while we make copy */
3206 MUTEX_LOCK(&t->mutex);
3208 PL_protect = t->Tprotect;
3210 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3211 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3212 PL_curstash = t->Tcurstash; /* always be set to main? */
3214 PL_tainted = t->Ttainted;
3215 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3216 PL_nrs = newSVsv(t->Tnrs);
3217 PL_rs = SvREFCNT_inc(PL_nrs);
3218 PL_last_in_gv = Nullgv;
3219 PL_ofslen = t->Tofslen;
3220 PL_ofs = savepvn(t->Tofs, PL_ofslen);
3221 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3222 PL_chopset = t->Tchopset;
3223 PL_formtarget = newSVsv(t->Tformtarget);
3224 PL_bodytarget = newSVsv(t->Tbodytarget);
3225 PL_toptarget = newSVsv(t->Ttoptarget);
3227 /* Initialise all per-thread SVs that the template thread used */
3228 svp = AvARRAY(t->threadsv);
3229 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3230 if (*svp && *svp != &PL_sv_undef) {
3231 SV *sv = newSVsv(*svp);
3232 av_store(thr->threadsv, i, sv);
3233 sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3234 DEBUG_S(PerlIO_printf(PerlIO_stderr(),
3235 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
3238 thr->threadsvp = AvARRAY(thr->threadsv);
3240 MUTEX_LOCK(&PL_threads_mutex);
3242 thr->tid = ++PL_threadnum;
3243 thr->next = t->next;
3246 thr->next->prev = thr;
3247 MUTEX_UNLOCK(&PL_threads_mutex);
3249 /* done copying parent's state */
3250 MUTEX_UNLOCK(&t->mutex);
3252 #ifdef HAVE_THREAD_INTERN
3253 Perl_init_thread_intern(thr);
3254 #endif /* HAVE_THREAD_INTERN */
3257 #endif /* USE_THREADS */
3261 * This hack is to force load of "huge" support from libm.a
3262 * So it is in perl for (say) POSIX to use.
3263 * Needed for SunOS with Sun's 'acc' for example.
3272 #ifdef PERL_GLOBAL_STRUCT
3281 Perl_get_op_names(pTHX)
3287 Perl_get_op_descs(pTHX)
3293 Perl_get_no_modify(pTHX)
3295 return (char*)PL_no_modify;
3299 Perl_get_opargs(pTHX)
3305 Perl_get_ppaddr(pTHX)
3310 #ifndef HAS_GETENV_LEN
3312 Perl_getenv_len(pTHX_ char *env_elem, unsigned long *len)
3314 char *env_trans = PerlEnv_getenv(env_elem);
3316 *len = strlen(env_trans);
3323 Perl_get_vtbl(pTHX_ int vtbl_id)
3325 MGVTBL* result = Null(MGVTBL*);
3329 result = &PL_vtbl_sv;
3332 result = &PL_vtbl_env;
3334 case want_vtbl_envelem:
3335 result = &PL_vtbl_envelem;
3338 result = &PL_vtbl_sig;
3340 case want_vtbl_sigelem:
3341 result = &PL_vtbl_sigelem;
3343 case want_vtbl_pack:
3344 result = &PL_vtbl_pack;
3346 case want_vtbl_packelem:
3347 result = &PL_vtbl_packelem;
3349 case want_vtbl_dbline:
3350 result = &PL_vtbl_dbline;
3353 result = &PL_vtbl_isa;
3355 case want_vtbl_isaelem:
3356 result = &PL_vtbl_isaelem;
3358 case want_vtbl_arylen:
3359 result = &PL_vtbl_arylen;
3361 case want_vtbl_glob:
3362 result = &PL_vtbl_glob;
3364 case want_vtbl_mglob:
3365 result = &PL_vtbl_mglob;
3367 case want_vtbl_nkeys:
3368 result = &PL_vtbl_nkeys;
3370 case want_vtbl_taint:
3371 result = &PL_vtbl_taint;
3373 case want_vtbl_substr:
3374 result = &PL_vtbl_substr;
3377 result = &PL_vtbl_vec;
3380 result = &PL_vtbl_pos;
3383 result = &PL_vtbl_bm;
3386 result = &PL_vtbl_fm;
3388 case want_vtbl_uvar:
3389 result = &PL_vtbl_uvar;
3392 case want_vtbl_mutex:
3393 result = &PL_vtbl_mutex;
3396 case want_vtbl_defelem:
3397 result = &PL_vtbl_defelem;
3399 case want_vtbl_regexp:
3400 result = &PL_vtbl_regexp;
3402 case want_vtbl_regdata:
3403 result = &PL_vtbl_regdata;
3405 case want_vtbl_regdatum:
3406 result = &PL_vtbl_regdatum;
3408 #ifdef USE_LOCALE_COLLATE
3409 case want_vtbl_collxfrm:
3410 result = &PL_vtbl_collxfrm;
3413 case want_vtbl_amagic:
3414 result = &PL_vtbl_amagic;
3416 case want_vtbl_amagicelem:
3417 result = &PL_vtbl_amagicelem;
3419 case want_vtbl_backref:
3420 result = &PL_vtbl_backref;
3427 Perl_my_fflush_all(pTHX)
3430 return PerlIO_flush(NULL);
3433 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3434 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3435 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3437 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3438 open_max = sysconf(_SC_OPEN_MAX);
3441 open_max = FOPEN_MAX;
3444 open_max = OPEN_MAX;
3455 for (i = 0; i < open_max; i++)
3456 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3457 STDIO_STREAM_ARRAY[i]._file < open_max &&
3458 STDIO_STREAM_ARRAY[i]._flag)
3459 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3463 SETERRNO(EBADF,RMS$_IFI);
3469 Perl_my_atof(const char* s) {
3470 #ifdef USE_LOCALE_NUMERIC
3471 if ((PL_hints & HINT_LOCALE) && PL_numeric_local) {
3475 SET_NUMERIC_STANDARD();
3477 SET_NUMERIC_LOCAL();
3478 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))