VirtualBox

source: kBuild/trunk/src/kmk/misc.c@ 2989

Last change on this file since 2989 was 2904, checked in by bird, 8 years ago

kmk: faster messages.

  • Property svn:eol-style set to native
File size: 37.0 KB
Line 
1/* Miscellaneous generic support functions for GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
42010 Free Software Foundation, Inc.
5This file is part of GNU Make.
6
7GNU Make is free software; you can redistribute it and/or modify it under the
8terms of the GNU General Public License as published by the Free Software
9Foundation; either version 3 of the License, or (at your option) any later
10version.
11
12GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License along with
17this program. If not, see <http://www.gnu.org/licenses/>. */
18
19#include "make.h"
20#include "dep.h"
21#include "debug.h"
22#if defined (CONFIG_WITH_VALUE_LENGTH) || defined (CONFIG_WITH_ALLOC_CACHES)
23# include <assert.h>
24#endif
25#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
26# ifdef __APPLE__
27# include <malloc/malloc.h>
28# endif
29# if defined(__GLIBC__) || defined(HAVE_MALLINFO)
30# include <malloc.h>
31# endif
32#endif
33
34#if defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_PRINT_TIME_SWITCH)
35# ifdef WINDOWS32
36# include <Windows.h>
37# endif
38#endif
39
40/* All bcopy calls in this file can be replaced by memcpy and save a tick or two. */
41#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
42# undef bcopy
43# if defined(__GNUC__) && defined(CONFIG_WITH_OPTIMIZATION_HACKS)
44# define bcopy(src, dst, size) __builtin_memcpy ((dst), (src), (size))
45# else
46# define bcopy(src, dst, size) memcpy ((dst), (src), (size))
47# endif
48#endif
49
50/* Variadic functions. We go through contortions to allow proper function
51 prototypes for both ANSI and pre-ANSI C compilers, and also for those
52 which support stdarg.h vs. varargs.h, and finally those which have
53 vfprintf(), etc. and those who have _doprnt... or nothing.
54
55 This fancy stuff all came from GNU fileutils, except for the VA_PRINTF and
56 VA_END macros used here since we have multiple print functions. */
57
58#if USE_VARIADIC
59# if HAVE_STDARG_H
60# include <stdarg.h>
61# define VA_START(args, lastarg) va_start(args, lastarg)
62# else
63# include <varargs.h>
64# define VA_START(args, lastarg) va_start(args)
65# endif
66# if HAVE_VPRINTF
67# define VA_PRINTF(fp, lastarg, args) vfprintf((fp), (lastarg), (args))
68# else
69# define VA_PRINTF(fp, lastarg, args) _doprnt((lastarg), (args), (fp))
70# endif
71# define VA_END(args) va_end(args)
72#else
73/* We can't use any variadic interface! */
74# define va_alist a1, a2, a3, a4, a5, a6, a7, a8
75# define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8;
76# define VA_START(args, lastarg)
77# define VA_PRINTF(fp, lastarg, args) fprintf((fp), (lastarg), va_alist)
78# define VA_END(args)
79#endif
80
81
82/* Compare strings *S1 and *S2.
83 Return negative if the first is less, positive if it is greater,
84 zero if they are equal. */
85
86int
87alpha_compare (const void *v1, const void *v2)
88{
89 const char *s1 = *((char **)v1);
90 const char *s2 = *((char **)v2);
91
92 if (*s1 != *s2)
93 return *s1 - *s2;
94 return strcmp (s1, s2);
95}
96
97
98/* Discard each backslash-newline combination from LINE.
99 Backslash-backslash-newline combinations become backslash-newlines.
100 This is done by copying the text at LINE into itself. */
101
102#ifndef CONFIG_WITH_VALUE_LENGTH
103void
104collapse_continuations (char *line)
105#else
106char *
107collapse_continuations (char *line, unsigned int linelen)
108#endif
109{
110 register char *in, *out, *p;
111 register int backslash;
112 register unsigned int bs_write;
113
114#ifndef CONFIG_WITH_VALUE_LENGTH
115 in = strchr (line, '\n');
116 if (in == 0)
117 return;
118#else
119 assert (strlen (line) == linelen);
120 in = memchr (line, '\n', linelen);
121 if (in == 0)
122 return line + linelen;
123 if (in == line || in[-1] != '\\')
124 {
125 do
126 {
127 unsigned int off_in = in - line;
128 if (off_in == linelen)
129 return in;
130 in = memchr (in + 1, '\n', linelen - off_in - 1);
131 if (in == 0)
132 return line + linelen;
133 }
134 while (in[-1] != '\\');
135 }
136#endif
137
138 out = in;
139 while (out > line && out[-1] == '\\')
140 --out;
141
142 while (*in != '\0')
143 {
144 /* BS_WRITE gets the number of quoted backslashes at
145 the end just before IN, and BACKSLASH gets nonzero
146 if the next character is quoted. */
147 backslash = 0;
148 bs_write = 0;
149 for (p = in - 1; p >= line && *p == '\\'; --p)
150 {
151 if (backslash)
152 ++bs_write;
153 backslash = !backslash;
154
155 /* It should be impossible to go back this far without exiting,
156 but if we do, we can't get the right answer. */
157 if (in == out - 1)
158 abort ();
159 }
160
161 /* Output the appropriate number of backslashes. */
162 while (bs_write-- > 0)
163 *out++ = '\\';
164
165 /* Skip the newline. */
166 ++in;
167
168 /* If the newline is escaped, discard following whitespace leaving just
169 one space. POSIX requires that each backslash/newline/following
170 whitespace sequence be reduced to a single space. */
171 if (backslash)
172 {
173 in = next_token (in);
174 /* Removing this loop will fix Savannah bug #16670: do we want to? */
175 while (out > line && isblank ((unsigned char)out[-1]))
176 --out;
177 *out++ = ' ';
178 }
179 else
180 /* If the newline isn't quoted, put it in the output. */
181 *out++ = '\n';
182
183 /* Now copy the following line to the output.
184 Stop when we find backslashes followed by a newline. */
185 while (*in != '\0')
186 if (*in == '\\')
187 {
188 p = in + 1;
189 while (*p == '\\')
190 ++p;
191 if (*p == '\n')
192 {
193 in = p;
194 break;
195 }
196 while (in < p)
197 *out++ = *in++;
198 }
199 else
200 *out++ = *in++;
201 }
202
203 *out = '\0';
204#ifdef CONFIG_WITH_VALUE_LENGTH
205 assert (strchr (line, '\0') == out);
206 return out;
207#endif
208}
209
210
211/* Print N spaces (used in debug for target-depth). */
212
213void
214print_spaces (unsigned int n)
215{
216 while (n-- > 0)
217 putchar (' ');
218}
219
220
221
222/* Return a string whose contents concatenate the NUM strings provided
223 This string lives in static, re-used memory. */
224
225const char *
226#if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
227concat (unsigned int num, ...)
228#else
229concat (num, va_alist)
230 unsigned int num;
231 va_dcl
232#endif
233{
234 static unsigned int rlen = 0;
235 static char *result = NULL;
236 unsigned int ri = 0; /* bird: must be unsigned */
237
238#if USE_VARIADIC
239 va_list args;
240#endif
241
242 VA_START (args, num);
243
244 while (num-- > 0)
245 {
246 const char *s = va_arg (args, const char *);
247 unsigned int l = s ? strlen (s) : 0;
248
249 if (l == 0)
250 continue;
251
252 if (ri + l > rlen)
253 {
254 rlen = ((rlen ? rlen : 60) + l) * 2;
255 result = xrealloc (result, rlen);
256 }
257
258 memcpy (result + ri, s, l);
259 ri += l;
260 }
261
262 VA_END (args);
263
264 /* Get some more memory if we don't have enough space for the
265 terminating '\0'. */
266 if (ri == rlen)
267 {
268 rlen = (rlen ? rlen : 60) * 2;
269 result = xrealloc (result, rlen);
270 }
271
272 result[ri] = '\0';
273
274 return result;
275}
276
277
278/* Print a message on stdout. */
279
280void
281#if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
282message (int prefix, const char *fmt, ...)
283#else
284message (prefix, fmt, va_alist)
285 int prefix;
286 const char *fmt;
287 va_dcl
288#endif
289{
290#if USE_VARIADIC
291 va_list args;
292#endif
293
294 log_working_directory (1);
295
296 if (fmt != 0)
297 {
298#ifdef KBUILD_OS_WINDOWS
299 char szMsg[16384];
300 int cchMsg = 0;
301 int cchUser;
302 if (prefix)
303 {
304 if (makelevel == 0)
305 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: ", program);
306 else
307 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: ", program, makelevel);
308 }
309 VA_START (args, fmt);
310 cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
311 VA_END (args);
312 if ( cchMsg < sizeof(szMsg)
313 && cchUser >= 0)
314 {
315 extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
316 szMsg[cchMsg++] = '\n';
317 maybe_con_fwrite(szMsg, cchMsg, 1, stdout);
318 }
319 else
320 {
321#endif
322 if (prefix)
323 {
324 if (makelevel == 0)
325 printf ("%s: ", program);
326 else
327 printf ("%s[%u]: ", program, makelevel);
328 }
329 VA_START (args, fmt);
330 VA_PRINTF (stdout, fmt, args);
331 VA_END (args);
332 putchar ('\n');
333#ifdef KBUILD_OS_WINDOWS
334 }
335#endif
336 }
337
338 fflush (stdout);
339}
340
341/* Print an error message. */
342
343void
344#if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
345error (const struct floc *flocp, const char *fmt, ...)
346#else
347error (flocp, fmt, va_alist)
348 const struct floc *flocp;
349 const char *fmt;
350 va_dcl
351#endif
352{
353#if USE_VARIADIC
354 va_list args;
355#endif
356#ifdef KMK
357 char szMsg[16384];
358 int cchMsg = 0;
359 int cchUser;
360#endif
361
362 log_working_directory (1);
363
364#ifdef KMK /* Try avoid getting the error split by child output. */
365 if (flocp && flocp->filenm)
366 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s:%lu: ", flocp->filenm, flocp->lineno);
367 else if (makelevel == 0)
368 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: ", program);
369 else
370 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: ", program, makelevel);
371
372 VA_START (args, fmt);
373 cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
374 VA_END (args);
375 if ( cchMsg < sizeof(szMsg)
376 && cchUser >= 0)
377 {
378 extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
379 szMsg[cchMsg++] = '\n';
380 maybe_con_fwrite(szMsg, cchMsg, 1, stderr);
381 }
382 else
383 {
384#endif /* KMK */
385
386 if (flocp && flocp->filenm)
387 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
388 else if (makelevel == 0)
389 fprintf (stderr, "%s: ", program);
390 else
391 fprintf (stderr, "%s[%u]: ", program, makelevel);
392
393 VA_START(args, fmt);
394 VA_PRINTF (stderr, fmt, args);
395 VA_END (args);
396
397 putc ('\n', stderr);
398#ifdef KMK
399 }
400#endif
401 fflush (stderr);
402}
403
404/* Print an error message and exit. */
405
406void
407#if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
408fatal (const struct floc *flocp, const char *fmt, ...)
409#else
410fatal (flocp, fmt, va_alist)
411 const struct floc *flocp;
412 const char *fmt;
413 va_dcl
414#endif
415{
416#if USE_VARIADIC
417 va_list args;
418#endif
419#ifdef KMK
420 char szMsg[16384];
421 int cchMsg = 0;
422 int cchUser;
423 const char *pszStop = _(". Stop.\n");
424 int cchStop = (int)strlen(pszStop);
425#endif
426
427 log_working_directory (1);
428
429#ifdef KMK /* Try avoid getting the error split by child output. */
430 if (flocp && flocp->filenm)
431 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s:%lu: *** ", flocp->filenm, flocp->lineno);
432 else if (makelevel == 0)
433 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: *** ", program);
434 else
435 cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: *** ", program, makelevel);
436
437 VA_START (args, fmt);
438 cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
439 VA_END (args);
440 if ( cchMsg + cchStop <= sizeof(szMsg)
441 && cchUser >= 0)
442 {
443 extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
444 memcpy(&szMsg[cchMsg], pszStop, cchStop);
445 cchMsg += cchStop;
446 maybe_con_fwrite(szMsg, cchMsg, 1, stderr);
447 }
448 else
449 {
450#endif /* KMK */
451 if (flocp && flocp->filenm)
452 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
453 else if (makelevel == 0)
454 fprintf (stderr, "%s: *** ", program);
455 else
456 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
457
458 VA_START(args, fmt);
459 VA_PRINTF (stderr, fmt, args);
460 VA_END (args);
461
462 fputs (_(". Stop.\n"), stderr);
463#ifdef KMK
464 }
465#endif
466
467 die (2);
468}
469
470#ifndef HAVE_STRERROR
471
472#undef strerror
473
474char *
475strerror (int errnum)
476{
477 extern int errno, sys_nerr;
478#ifndef __DECC
479 extern char *sys_errlist[];
480#endif
481 static char buf[] = "Unknown error 12345678901234567890";
482
483 if (errno < sys_nerr)
484 return sys_errlist[errnum];
485
486 sprintf (buf, _("Unknown error %d"), errnum);
487 return buf;
488}
489#endif
490
491/* Print an error message from errno. */
492
493void
494perror_with_name (const char *str, const char *name)
495{
496 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
497}
498
499/* Print an error message from errno and exit. */
500
501void
502pfatal_with_name (const char *name)
503{
504 fatal (NILF, _("%s: %s"), name, strerror (errno));
505
506 /* NOTREACHED */
507}
508
509
510/* Like malloc but get fatal error if memory is exhausted. */
511/* Don't bother if we're using dmalloc; it provides these for us. */
512
513#if !defined(HAVE_DMALLOC_H) && !defined(ELECTRIC_HEAP) /* bird */
514
515#undef xmalloc
516#undef xcalloc
517#undef xrealloc
518#undef xstrdup
519
520void *
521xmalloc (unsigned int size)
522{
523 /* Make sure we don't allocate 0, for pre-ISO implementations. */
524 void *result = malloc (size ? size : 1);
525 if (result == 0)
526 fatal (NILF, _("virtual memory exhausted"));
527
528#ifdef CONFIG_WITH_MAKE_STATS
529 make_stats_allocations++;
530 if (make_expensive_statistics)
531 make_stats_allocated += SIZE_OF_HEAP_BLOCK (result);
532 else
533 make_stats_allocated += size;
534#endif
535 return result;
536}
537
538
539void *
540xcalloc (unsigned int size)
541{
542 /* Make sure we don't allocate 0, for pre-ISO implementations. */
543 void *result = calloc (size ? size : 1, 1);
544 if (result == 0)
545 fatal (NILF, _("virtual memory exhausted"));
546
547#ifdef CONFIG_WITH_MAKE_STATS
548 make_stats_allocations++;
549 if (make_expensive_statistics)
550 make_stats_allocated += SIZE_OF_HEAP_BLOCK (result);
551 else
552 make_stats_allocated += size;
553#endif
554 return result;
555}
556
557
558void *
559xrealloc (void *ptr, unsigned int size)
560{
561 void *result;
562#ifdef CONFIG_WITH_MAKE_STATS
563 if (make_expensive_statistics && ptr != NULL)
564 make_stats_allocated -= SIZE_OF_HEAP_BLOCK (ptr);
565 if (ptr)
566 make_stats_reallocations++;
567 else
568 make_stats_allocations++;
569#endif
570
571 /* Some older implementations of realloc() don't conform to ISO. */
572 if (! size)
573 size = 1;
574 result = ptr ? realloc (ptr, size) : malloc (size);
575 if (result == 0)
576 fatal (NILF, _("virtual memory exhausted"));
577
578#ifdef CONFIG_WITH_MAKE_STATS
579 if (make_expensive_statistics)
580 make_stats_allocated += SIZE_OF_HEAP_BLOCK (result);
581 else
582 make_stats_allocated += size;
583#endif
584 return result;
585}
586
587
588char *
589xstrdup (const char *ptr)
590{
591 char *result;
592
593#ifdef HAVE_STRDUP
594 result = strdup (ptr);
595#else
596 result = malloc (strlen (ptr) + 1);
597#endif
598
599 if (result == 0)
600 fatal (NILF, _("virtual memory exhausted"));
601
602#ifdef CONFIG_WITH_MAKE_STATS
603 make_stats_allocations++;
604 if (make_expensive_statistics)
605 make_stats_allocated += SIZE_OF_HEAP_BLOCK (result);
606 else
607 make_stats_allocated += strlen (ptr) + 1;
608#endif
609#ifdef HAVE_STRDUP
610 return result;
611#else
612 return strcpy (result, ptr);
613#endif
614}
615
616#endif /* HAVE_DMALLOC_H */
617
618char *
619xstrndup (const char *str, unsigned int length)
620{
621 char *result;
622
623#if defined(HAVE_STRNDUP) && !defined(KMK)
624 result = strndup (str, length);
625 if (result == 0)
626 fatal (NILF, _("virtual memory exhausted"));
627#else
628 result = xmalloc (length + 1);
629 if (length > 0)
630 strncpy (result, str, length);
631 result[length] = '\0';
632#endif
633
634 return result;
635}
636
637
638
639#ifndef CONFIG_WITH_OPTIMIZATION_HACKS /* This is really a reimplemntation of
640 memchr, only slower. It's been replaced by a macro in the header file. */
641
642/* Limited INDEX:
643 Search through the string STRING, which ends at LIMIT, for the character C.
644 Returns a pointer to the first occurrence, or nil if none is found.
645 Like INDEX except that the string searched ends where specified
646 instead of at the first null. */
647
648char *
649lindex (const char *s, const char *limit, int c)
650{
651 while (s < limit)
652 if (*s++ == c)
653 return (char *)(s - 1);
654
655 return 0;
656}
657#endif /* CONFIG_WITH_OPTIMIZATION_HACKS */
658
659
660/* Return the address of the first whitespace or null in the string S. */
661
662char *
663end_of_token (const char *s)
664{
665#ifdef KMK
666 for (;;)
667 {
668 unsigned char ch0, ch1, ch2, ch3;
669
670 ch0 = *s;
671 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch0)))
672 return (char *)s;
673 ch1 = s[1];
674 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch1)))
675 return (char *)s + 1;
676 ch2 = s[2];
677 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch2)))
678 return (char *)s + 2;
679 ch3 = s[3];
680 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch3)))
681 return (char *)s + 3;
682
683 s += 4;
684 }
685
686#else
687 while (*s != '\0' && !isblank ((unsigned char)*s))
688 ++s;
689 return (char *)s;
690#endif
691}
692
693#ifdef WINDOWS32
694/*
695 * Same as end_of_token, but take into account a stop character
696 */
697char *
698end_of_token_w32 (const char *s, char stopchar)
699{
700 const char *p = s;
701 int backslash = 0;
702
703 while (*p != '\0' && *p != stopchar
704 && (backslash || !isblank ((unsigned char)*p)))
705 {
706 if (*p++ == '\\')
707 {
708 backslash = !backslash;
709 while (*p == '\\')
710 {
711 backslash = !backslash;
712 ++p;
713 }
714 }
715 else
716 backslash = 0;
717 }
718
719 return (char *)p;
720}
721#endif
722
723/* Return the address of the first nonwhitespace or null in the string S. */
724
725char *
726next_token (const char *s)
727{
728#ifdef KMK
729 for (;;)
730 {
731 unsigned char ch0, ch1, ch2, ch3;
732
733 ch0 = *s;
734 if (MY_PREDICT_FALSE(!MY_IS_BLANK(ch0)))
735 return (char *)s;
736 ch1 = s[1];
737 if (MY_PREDICT_TRUE(!MY_IS_BLANK(ch1)))
738 return (char *)s + 1;
739 ch2 = s[2];
740 if (MY_PREDICT_FALSE(!MY_IS_BLANK(ch2)))
741 return (char *)s + 2;
742 ch3 = s[3];
743 if (MY_PREDICT_TRUE(!MY_IS_BLANK(ch3)))
744 return (char *)s + 3;
745
746 s += 4;
747 }
748
749#else /* !KMK */
750 while (isblank ((unsigned char)*s))
751 ++s;
752 return (char *)s;
753#endif /* !KMK */
754}
755
756/* Find the next token in PTR; return the address of it, and store the length
757 of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
758 of the token, so this function can be called repeatedly in a loop. */
759
760char *
761find_next_token (const char **ptr, unsigned int *lengthptr)
762{
763#ifdef KMK
764 const char *p = *ptr;
765 const char *e;
766
767 /* skip blanks */
768# if 0 /* a moderate version */
769 for (;; p++)
770 {
771 unsigned char ch = *p;
772 if (!MY_IS_BLANK(ch))
773 {
774 if (!ch)
775 return NULL;
776 break;
777 }
778 }
779
780# else /* (too) big unroll */
781 for (;; p += 4)
782 {
783 unsigned char ch0, ch1, ch2, ch3;
784
785 ch0 = *p;
786 if (MY_PREDICT_FALSE(!MY_IS_BLANK(ch0)))
787 {
788 if (!ch0)
789 return NULL;
790 break;
791 }
792 ch1 = p[1];
793 if (MY_PREDICT_TRUE(!MY_IS_BLANK(ch1)))
794 {
795 if (!ch1)
796 return NULL;
797 p += 1;
798 break;
799 }
800 ch2 = p[2];
801 if (MY_PREDICT_FALSE(!MY_IS_BLANK(ch2)))
802 {
803 if (!ch2)
804 return NULL;
805 p += 2;
806 break;
807 }
808 ch3 = p[3];
809 if (MY_PREDICT_TRUE(!MY_IS_BLANK(ch3)))
810 {
811 if (!ch3)
812 return NULL;
813 p += 3;
814 break;
815 }
816 }
817# endif
818
819 /* skip ahead until EOS or blanks. */
820# if 0 /* a moderate version */
821 for (e = p + 1; ; e++)
822 {
823 unsigned char ch = *e;
824 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch)))
825 break;
826 }
827# else /* (too) big unroll */
828 for (e = p + 1; ; e += 4)
829 {
830 unsigned char ch0, ch1, ch2, ch3;
831
832 ch0 = *e;
833 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch0)))
834 break;
835 ch1 = e[1];
836 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch1)))
837 {
838 e += 1;
839 break;
840 }
841 ch2 = e[2];
842 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch2)))
843 {
844 e += 2;
845 break;
846 }
847 ch3 = e[3];
848 if (MY_PREDICT_FALSE(MY_IS_BLANK_OR_EOS(ch3)))
849 {
850 e += 3;
851 break;
852 }
853 }
854# endif
855 *ptr = e;
856
857 if (lengthptr != 0)
858 *lengthptr = e - p;
859
860 return (char *)p;
861
862#else
863 const char *p = next_token (*ptr);
864
865 if (*p == '\0')
866 return 0;
867
868 *ptr = end_of_token (p);
869 if (lengthptr != 0)
870 *lengthptr = *ptr - p;
871
872 return (char *)p;
873#endif
874}
875#ifdef KMK
876
877/* Same as find_next_token with two exception:
878 - The string ends at EOS or '\0'.
879 - We keep track of $() and ${}, allowing functions to be used. */
880
881char *
882find_next_token_eos (const char **ptr, const char *eos, unsigned int *lengthptr)
883{
884 const char *p = *ptr;
885 const char *e;
886 int level = 0;
887
888 /* skip blanks */
889 for (; p != eos; p++)
890 {
891 unsigned char ch = *p;
892 if (!MY_IS_BLANK(ch))
893 {
894 if (!ch)
895 return NULL;
896 break;
897 }
898 }
899 if (p == eos)
900 return NULL;
901
902 /* skip ahead until EOS or blanks. */
903 for (e = p; e != eos; e++)
904 {
905 unsigned char ch = *e;
906 if (MY_IS_BLANK_OR_EOS(ch))
907 {
908 if (!ch || level == 0)
909 break;
910 }
911 else if (ch == '$')
912 {
913 if (&e[1] != eos && (e[1] == '(' || e[1] == '{'))
914 {
915 level++;
916 e++;
917 }
918 }
919 else if ((ch == ')' || ch == '}') && level > 0)
920 level--;
921 }
922
923 *ptr = e;
924 if (lengthptr != 0)
925 *lengthptr = e - p;
926
927 return (char *)p;
928}
929
930#endif /* KMK */
931
932
933
934/* Copy a chain of `struct dep'. For 2nd expansion deps, dup the name. */
935
936struct dep *
937copy_dep_chain (const struct dep *d)
938{
939 struct dep *firstnew = 0;
940 struct dep *lastnew = 0;
941
942 while (d != 0)
943 {
944#ifndef CONFIG_WITH_ALLOC_CACHES
945 struct dep *c = xmalloc (sizeof (struct dep));
946#else
947 struct dep *c = alloccache_alloc(&dep_cache);
948#endif
949 memcpy (c, d, sizeof (struct dep));
950
951 /** @todo KMK: Check if we need this duplication! */
952 if (c->need_2nd_expansion)
953 c->name = xstrdup (c->name);
954
955 c->next = 0;
956 if (firstnew == 0)
957 firstnew = lastnew = c;
958 else
959 lastnew = lastnew->next = c;
960
961 d = d->next;
962 }
963
964 return firstnew;
965}
966
967/* Free a chain of 'struct dep'. */
968
969void
970free_dep_chain (struct dep *d)
971{
972 while (d != 0)
973 {
974 struct dep *df = d;
975 d = d->next;
976 free_dep (df);
977 }
978}
979
980/* Free a chain of struct nameseq.
981 For struct dep chains use free_dep_chain. */
982
983void
984free_ns_chain (struct nameseq *ns)
985{
986 while (ns != 0)
987 {
988 struct nameseq *t = ns;
989 ns = ns->next;
990#ifndef CONFIG_WITH_ALLOC_CACHES
991 free (t);
992#else
993 alloccache_free (&nameseq_cache, t);
994#endif
995 }
996}
997
998
999
1000#if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
1001
1002/* If we don't have strcasecmp() (from POSIX), or anything that can substitute
1003 for it, define our own version. */
1004
1005int
1006strcasecmp (const char *s1, const char *s2)
1007{
1008 while (1)
1009 {
1010 int c1 = (int) *(s1++);
1011 int c2 = (int) *(s2++);
1012
1013 if (isalpha (c1))
1014 c1 = tolower (c1);
1015 if (isalpha (c2))
1016 c2 = tolower (c2);
1017
1018 if (c1 != '\0' && c1 == c2)
1019 continue;
1020
1021 return (c1 - c2);
1022 }
1023}
1024#endif
1025
1026#if !HAVE_STRNCASECMP && !HAVE_STRNICMP && !HAVE_STRNCMPI
1027
1028/* If we don't have strncasecmp() (from POSIX), or anything that can
1029 substitute for it, define our own version. */
1030
1031int
1032strncasecmp (const char *s1, const char *s2, int n)
1033{
1034 while (n-- > 0)
1035 {
1036 int c1 = (int) *(s1++);
1037 int c2 = (int) *(s2++);
1038
1039 if (isalpha (c1))
1040 c1 = tolower (c1);
1041 if (isalpha (c2))
1042 c2 = tolower (c2);
1043
1044 if (c1 != '\0' && c1 == c2)
1045 continue;
1046
1047 return (c1 - c2);
1048 }
1049
1050 return 0;
1051}
1052#endif
1053
1054
1055#ifdef GETLOADAVG_PRIVILEGED
1056
1057#ifdef POSIX
1058
1059/* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
1060 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
1061 for example) which claim to be POSIX.1 also have the BSD setreuid and
1062 setregid functions, but they don't work as in BSD and only the POSIX.1
1063 way works. */
1064
1065#undef HAVE_SETREUID
1066#undef HAVE_SETREGID
1067
1068#else /* Not POSIX. */
1069
1070/* Some POSIX.1 systems have the seteuid and setegid functions. In a
1071 POSIX-like system, they are the best thing to use. However, some
1072 non-POSIX systems have them too but they do not work in the POSIX style
1073 and we must use setreuid and setregid instead. */
1074
1075#undef HAVE_SETEUID
1076#undef HAVE_SETEGID
1077
1078#endif /* POSIX. */
1079
1080#ifndef HAVE_UNISTD_H
1081extern int getuid (), getgid (), geteuid (), getegid ();
1082extern int setuid (), setgid ();
1083#ifdef HAVE_SETEUID
1084extern int seteuid ();
1085#else
1086#ifdef HAVE_SETREUID
1087extern int setreuid ();
1088#endif /* Have setreuid. */
1089#endif /* Have seteuid. */
1090#ifdef HAVE_SETEGID
1091extern int setegid ();
1092#else
1093#ifdef HAVE_SETREGID
1094extern int setregid ();
1095#endif /* Have setregid. */
1096#endif /* Have setegid. */
1097#endif /* No <unistd.h>. */
1098
1099/* Keep track of the user and group IDs for user- and make- access. */
1100static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
1101#define access_inited (user_uid != -1)
1102static enum { make, user } current_access;
1103
1104
1105/* Under -d, write a message describing the current IDs. */
1106
1107static void
1108log_access (const char *flavor)
1109{
1110 if (! ISDB (DB_JOBS))
1111 return;
1112
1113 /* All the other debugging messages go to stdout,
1114 but we write this one to stderr because it might be
1115 run in a child fork whose stdout is piped. */
1116
1117 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
1118 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
1119 (unsigned long) getegid (), (unsigned long) getgid ());
1120 fflush (stderr);
1121}
1122
1123
1124static void
1125init_access (void)
1126{
1127#ifndef VMS
1128 user_uid = getuid ();
1129 user_gid = getgid ();
1130
1131 make_uid = geteuid ();
1132 make_gid = getegid ();
1133
1134 /* Do these ever fail? */
1135 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
1136 pfatal_with_name ("get{e}[gu]id");
1137
1138 log_access (_("Initialized access"));
1139
1140 current_access = make;
1141#endif
1142}
1143
1144#endif /* GETLOADAVG_PRIVILEGED */
1145
1146/* Give the process appropriate permissions for access to
1147 user data (i.e., to stat files, or to spawn a child process). */
1148void
1149user_access (void)
1150{
1151#ifdef GETLOADAVG_PRIVILEGED
1152
1153 if (!access_inited)
1154 init_access ();
1155
1156 if (current_access == user)
1157 return;
1158
1159 /* We are in "make access" mode. This means that the effective user and
1160 group IDs are those of make (if it was installed setuid or setgid).
1161 We now want to set the effective user and group IDs to the real IDs,
1162 which are the IDs of the process that exec'd make. */
1163
1164#ifdef HAVE_SETEUID
1165
1166 /* Modern systems have the seteuid/setegid calls which set only the
1167 effective IDs, which is ideal. */
1168
1169 if (seteuid (user_uid) < 0)
1170 pfatal_with_name ("user_access: seteuid");
1171
1172#else /* Not HAVE_SETEUID. */
1173
1174#ifndef HAVE_SETREUID
1175
1176 /* System V has only the setuid/setgid calls to set user/group IDs.
1177 There is an effective ID, which can be set by setuid/setgid.
1178 It can be set (unless you are root) only to either what it already is
1179 (returned by geteuid/getegid, now in make_uid/make_gid),
1180 the real ID (return by getuid/getgid, now in user_uid/user_gid),
1181 or the saved set ID (what the effective ID was before this set-ID
1182 executable (make) was exec'd). */
1183
1184 if (setuid (user_uid) < 0)
1185 pfatal_with_name ("user_access: setuid");
1186
1187#else /* HAVE_SETREUID. */
1188
1189 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
1190 They may be set to themselves or each other. So you have two alternatives
1191 at any one time. If you use setuid/setgid, the effective will be set to
1192 the real, leaving only one alternative. Using setreuid/setregid, however,
1193 you can toggle between your two alternatives by swapping the values in a
1194 single setreuid or setregid call. */
1195
1196 if (setreuid (make_uid, user_uid) < 0)
1197 pfatal_with_name ("user_access: setreuid");
1198
1199#endif /* Not HAVE_SETREUID. */
1200#endif /* HAVE_SETEUID. */
1201
1202#ifdef HAVE_SETEGID
1203 if (setegid (user_gid) < 0)
1204 pfatal_with_name ("user_access: setegid");
1205#else
1206#ifndef HAVE_SETREGID
1207 if (setgid (user_gid) < 0)
1208 pfatal_with_name ("user_access: setgid");
1209#else
1210 if (setregid (make_gid, user_gid) < 0)
1211 pfatal_with_name ("user_access: setregid");
1212#endif
1213#endif
1214
1215 current_access = user;
1216
1217 log_access (_("User access"));
1218
1219#endif /* GETLOADAVG_PRIVILEGED */
1220}
1221
1222/* Give the process appropriate permissions for access to
1223 make data (i.e., the load average). */
1224void
1225make_access (void)
1226{
1227#ifdef GETLOADAVG_PRIVILEGED
1228
1229 if (!access_inited)
1230 init_access ();
1231
1232 if (current_access == make)
1233 return;
1234
1235 /* See comments in user_access, above. */
1236
1237#ifdef HAVE_SETEUID
1238 if (seteuid (make_uid) < 0)
1239 pfatal_with_name ("make_access: seteuid");
1240#else
1241#ifndef HAVE_SETREUID
1242 if (setuid (make_uid) < 0)
1243 pfatal_with_name ("make_access: setuid");
1244#else
1245 if (setreuid (user_uid, make_uid) < 0)
1246 pfatal_with_name ("make_access: setreuid");
1247#endif
1248#endif
1249
1250#ifdef HAVE_SETEGID
1251 if (setegid (make_gid) < 0)
1252 pfatal_with_name ("make_access: setegid");
1253#else
1254#ifndef HAVE_SETREGID
1255 if (setgid (make_gid) < 0)
1256 pfatal_with_name ("make_access: setgid");
1257#else
1258 if (setregid (user_gid, make_gid) < 0)
1259 pfatal_with_name ("make_access: setregid");
1260#endif
1261#endif
1262
1263 current_access = make;
1264
1265 log_access (_("Make access"));
1266
1267#endif /* GETLOADAVG_PRIVILEGED */
1268}
1269
1270/* Give the process appropriate permissions for a child process.
1271 This is like user_access, but you can't get back to make_access. */
1272void
1273child_access (void)
1274{
1275#ifdef GETLOADAVG_PRIVILEGED
1276
1277 if (!access_inited)
1278 abort ();
1279
1280 /* Set both the real and effective UID and GID to the user's.
1281 They cannot be changed back to make's. */
1282
1283#ifndef HAVE_SETREUID
1284 if (setuid (user_uid) < 0)
1285 pfatal_with_name ("child_access: setuid");
1286#else
1287 if (setreuid (user_uid, user_uid) < 0)
1288 pfatal_with_name ("child_access: setreuid");
1289#endif
1290
1291#ifndef HAVE_SETREGID
1292 if (setgid (user_gid) < 0)
1293 pfatal_with_name ("child_access: setgid");
1294#else
1295 if (setregid (user_gid, user_gid) < 0)
1296 pfatal_with_name ("child_access: setregid");
1297#endif
1298
1299 log_access (_("Child access"));
1300
1301#endif /* GETLOADAVG_PRIVILEGED */
1302}
1303
1304
1305#ifdef NEED_GET_PATH_MAX
1306unsigned int
1307get_path_max (void)
1308{
1309 static unsigned int value;
1310
1311 if (value == 0)
1312 {
1313 long int x = pathconf ("/", _PC_PATH_MAX);
1314 if (x > 0)
1315 value = x;
1316 else
1317 return MAXPATHLEN;
1318 }
1319
1320 return value;
1321}
1322#endif
1323
1324
1325
1326/* This code is stolen from gnulib.
1327 If/when we abandon the requirement to work with K&R compilers, we can
1328 remove this (and perhaps other parts of GNU make!) and migrate to using
1329 gnulib directly.
1330
1331 This is called only through atexit(), which means die() has already been
1332 invoked. So, call exit() here directly. Apparently that works...?
1333*/
1334
1335/* Close standard output, exiting with status 'exit_failure' on failure.
1336 If a program writes *anything* to stdout, that program should close
1337 stdout and make sure that it succeeds before exiting. Otherwise,
1338 suppose that you go to the extreme of checking the return status
1339 of every function that does an explicit write to stdout. The last
1340 printf can succeed in writing to the internal stream buffer, and yet
1341 the fclose(stdout) could still fail (due e.g., to a disk full error)
1342 when it tries to write out that buffered data. Thus, you would be
1343 left with an incomplete output file and the offending program would
1344 exit successfully. Even calling fflush is not always sufficient,
1345 since some file systems (NFS and CODA) buffer written/flushed data
1346 until an actual close call.
1347
1348 Besides, it's wasteful to check the return value from every call
1349 that writes to stdout -- just let the internal stream state record
1350 the failure. That's what the ferror test is checking below.
1351
1352 It's important to detect such failures and exit nonzero because many
1353 tools (most notably `make' and other build-management systems) depend
1354 on being able to detect failure in other tools via their exit status. */
1355
1356void
1357close_stdout (void)
1358{
1359 int prev_fail = ferror (stdout);
1360 int fclose_fail = fclose (stdout);
1361
1362 if (prev_fail || fclose_fail)
1363 {
1364 if (fclose_fail)
1365 error (NILF, _("write error: %s"), strerror (errno));
1366 else
1367 error (NILF, _("write error"));
1368 exit (EXIT_FAILURE);
1369 }
1370}
1371
1372#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
1373/* Print heap statistics if supported by the platform. */
1374void
1375print_heap_stats (void)
1376{
1377 /* Darwin / Mac OS X */
1378# ifdef __APPLE__
1379 malloc_statistics_t s;
1380
1381 malloc_zone_statistics (NULL, &s);
1382 printf (_("\n# CRT Heap: %u bytes in use, in %u blocks, avg %u bytes/block\n"),
1383 (unsigned)s.size_in_use, (unsigned)s.blocks_in_use,
1384 (unsigned)(s.size_in_use / s.blocks_in_use));
1385 printf (_("# %u bytes max in use (high water mark)\n"),
1386 (unsigned)s.max_size_in_use);
1387 printf (_("# %u bytes reserved, %u bytes free (estimate)\n"),
1388 (unsigned)s.size_allocated,
1389 (unsigned)(s.size_allocated - s.size_in_use));
1390# endif /* __APPLE__ */
1391
1392 /* MSC / Windows */
1393# ifdef _MSC_VER
1394 unsigned int blocks_used = 0;
1395 unsigned int bytes_used = 0;
1396 unsigned int blocks_avail = 0;
1397 unsigned int bytes_avail = 0;
1398 _HEAPINFO hinfo;
1399
1400 memset (&hinfo, '\0', sizeof (hinfo));
1401 while (_heapwalk(&hinfo) == _HEAPOK)
1402 {
1403 if (hinfo._useflag == _USEDENTRY)
1404 {
1405 blocks_used++;
1406 bytes_used += hinfo._size;
1407 }
1408 else
1409 {
1410 blocks_avail++;
1411 bytes_avail += hinfo._size;
1412 }
1413 }
1414
1415 printf (_("\n# CRT Heap: %u bytes in use, in %u blocks, avg %u bytes/block\n"),
1416 bytes_used, blocks_used, bytes_used / blocks_used);
1417 printf (_("# %u bytes avail, in %u blocks, avg %u bytes/block\n"),
1418 bytes_avail, blocks_avail, bytes_avail / blocks_avail);
1419# endif /* _MSC_VER */
1420
1421 /* Darwin Libc sources indicates that something like this may be
1422 found in GLIBC, however, it's not in any current one... */
1423# if 0 /* ??? */
1424 struct mstats m;
1425
1426 m = mstats();
1427 printf (_("\n# CRT Heap: %zu blocks / %zu bytes in use, %zu blocks / %zu bytes free\n"),
1428 m.chunks_used, m.bytes_used, m.chunks_free, m.bytes_free);
1429 printf (_("# %zu bytes reserved\n"),
1430 m.bytes_total);
1431# endif /* ??? */
1432
1433 /* XVID2/XPG mallinfo (displayed per GLIBC documentation). */
1434# if defined(__GLIBC__) || defined(HAVE_MALLINFO)
1435 struct mallinfo m;
1436
1437 m = mallinfo();
1438 printf (_("\n# CRT Heap: %d bytes in use, %d bytes free\n"),
1439 m.uordblks, m.fordblks);
1440
1441 printf (_("# # free chunks=%d, # fastbin blocks=%d\n"),
1442 m.ordblks, m.smblks);
1443 printf (_("# # mapped regions=%d, space in mapped regions=%d\n"),
1444 m.hblks, m.hblkhd);
1445 printf (_("# non-mapped space allocated from system=%d\n"),
1446 m.arena);
1447 printf (_("# maximum total allocated space=%d\n"),
1448 m.usmblks);
1449 printf (_("# top-most releasable space=%d\n"),
1450 m.keepcost);
1451# endif /* __GLIBC__ || HAVE_MALLINFO */
1452
1453# ifdef CONFIG_WITH_MAKE_STATS
1454 printf(_("# %lu malloc calls, %lu realloc calls\n"),
1455 make_stats_allocations, make_stats_reallocations);
1456 printf(_("# %lu MBs alloc sum, not counting freed, add pinch of salt\n"), /* XXX: better wording */
1457 make_stats_allocated / (1024*1024));
1458# endif
1459
1460 /* XXX: windows */
1461}
1462#endif /* CONFIG_WITH_PRINT_STATS_SWITCH */
1463
1464#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1465/* Get a nanosecond timestamp, from a monotonic time source if
1466 possible. Returns -1 after calling error() on failure. */
1467
1468big_int
1469nano_timestamp (void)
1470{
1471 big_int ts;
1472#if defined (WINDOWS32)
1473 static int s_state = -1;
1474 static LARGE_INTEGER s_freq;
1475
1476 if (s_state == -1)
1477 s_state = QueryPerformanceFrequency (&s_freq);
1478 if (s_state)
1479 {
1480 LARGE_INTEGER pc;
1481 if (!QueryPerformanceCounter (&pc))
1482 {
1483 s_state = 0;
1484 return nano_timestamp ();
1485 }
1486 ts = (big_int)((long double)pc.QuadPart / (long double)s_freq.QuadPart * 1000000000);
1487 }
1488 else
1489 {
1490 /* fall back to low resolution system time. */
1491 LARGE_INTEGER bigint;
1492 FILETIME ft = {0,0};
1493 GetSystemTimeAsFileTime (&ft);
1494 bigint.u.LowPart = ft.dwLowDateTime;
1495 bigint.u.HighPart = ft.dwLowDateTime;
1496 ts = bigint.QuadPart * 100;
1497 }
1498
1499#elif HAVE_GETTIMEOFDAY
1500/* FIXME: Linux and others have the realtime clock_* api, detect and use it. */
1501 struct timeval tv;
1502 if (!gettimeofday (&tv, NULL))
1503 ts = (big_int)tv.tv_sec * 1000000000
1504 + tv.tv_usec * 1000;
1505 else
1506 {
1507 error (NILF, _("gettimeofday failed"));
1508 ts = -1;
1509 }
1510
1511#else
1512# error "PORTME"
1513#endif
1514
1515 return ts;
1516}
1517
1518/* Formats the elapsed time (nano seconds) in the manner easiest
1519 to read, with millisecond percision for larger numbers. */
1520
1521int
1522format_elapsed_nano (char *buf, size_t size, big_int ts)
1523{
1524 unsigned sz;
1525 if (ts < 1000)
1526 sz = sprintf (buf, "%uns", (unsigned)ts);
1527 else if (ts < 100000)
1528 sz = sprintf (buf, "%u.%03uus",
1529 (unsigned)(ts / 1000),
1530 (unsigned)(ts % 1000));
1531 else
1532 {
1533 ts /= 1000;
1534 if (ts < 1000)
1535 sz = sprintf (buf, "%uus", (unsigned)ts);
1536 else if (ts < 100000)
1537 sz = sprintf (buf, "%u.%03ums",
1538 (unsigned)(ts / 1000),
1539 (unsigned)(ts % 1000));
1540 else
1541 {
1542 ts /= 1000;
1543 if (ts < BIG_INT_C(60000))
1544 sz = sprintf (buf,
1545 "%u.%03us",
1546 (unsigned)(ts / 1000),
1547 (unsigned)(ts % 1000));
1548 else
1549 sz = sprintf (buf,
1550 "%um%u.%03us",
1551 (unsigned)( ts / BIG_INT_C(60000)),
1552 (unsigned)((ts % BIG_INT_C(60000)) / 1000),
1553 (unsigned)((ts % BIG_INT_C(60000)) % 1000));
1554 }
1555 }
1556 if (sz >= size)
1557 fatal (NILF, _("format_elapsed_nano buffer overflow: %u written, %lu buffer"),
1558 sz, (unsigned long)size);
1559 return sz;
1560}
1561#endif /* CONFIG_WITH_PRINT_TIME_SWITCH */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette