- Fixed a bug reported by Michael Matz regarding handling of parallel
[make.git] / misc.c
blobac50270910bc0ec3038b4083fc3f8b2f1720c45c
1 /* Miscellaneous generic support functions for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
22 #include "dep.h"
23 #include "debug.h"
25 /* Variadic functions. We go through contortions to allow proper function
26 prototypes for both ANSI and pre-ANSI C compilers, and also for those
27 which support stdarg.h vs. varargs.h, and finally those which have
28 vfprintf(), etc. and those who have _doprnt... or nothing.
30 This fancy stuff all came from GNU fileutils, except for the VA_PRINTF and
31 VA_END macros used here since we have multiple print functions. */
33 #if USE_VARIADIC
34 # if HAVE_STDARG_H
35 # include <stdarg.h>
36 # define VA_START(args, lastarg) va_start(args, lastarg)
37 # else
38 # include <varargs.h>
39 # define VA_START(args, lastarg) va_start(args)
40 # endif
41 # if HAVE_VPRINTF
42 # define VA_PRINTF(fp, lastarg, args) vfprintf((fp), (lastarg), (args))
43 # else
44 # define VA_PRINTF(fp, lastarg, args) _doprnt((lastarg), (args), (fp))
45 # endif
46 # define VA_END(args) va_end(args)
47 #else
48 /* We can't use any variadic interface! */
49 # define va_alist a1, a2, a3, a4, a5, a6, a7, a8
50 # define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8;
51 # define VA_START(args, lastarg)
52 # define VA_PRINTF(fp, lastarg, args) fprintf((fp), (lastarg), va_alist)
53 # define VA_END(args)
54 #endif
57 /* Compare strings *S1 and *S2.
58 Return negative if the first is less, positive if it is greater,
59 zero if they are equal. */
61 int
62 alpha_compare (const void *v1, const void *v2)
64 const char *s1 = *((char **)v1);
65 const char *s2 = *((char **)v2);
67 if (*s1 != *s2)
68 return *s1 - *s2;
69 return strcmp (s1, s2);
72 /* Discard each backslash-newline combination from LINE.
73 Backslash-backslash-newline combinations become backslash-newlines.
74 This is done by copying the text at LINE into itself. */
76 void
77 collapse_continuations (char *line)
79 register char *in, *out, *p;
80 register int backslash;
81 register unsigned int bs_write;
83 in = strchr (line, '\n');
84 if (in == 0)
85 return;
87 out = in;
88 while (out > line && out[-1] == '\\')
89 --out;
91 while (*in != '\0')
93 /* BS_WRITE gets the number of quoted backslashes at
94 the end just before IN, and BACKSLASH gets nonzero
95 if the next character is quoted. */
96 backslash = 0;
97 bs_write = 0;
98 for (p = in - 1; p >= line && *p == '\\'; --p)
100 if (backslash)
101 ++bs_write;
102 backslash = !backslash;
104 /* It should be impossible to go back this far without exiting,
105 but if we do, we can't get the right answer. */
106 if (in == out - 1)
107 abort ();
110 /* Output the appropriate number of backslashes. */
111 while (bs_write-- > 0)
112 *out++ = '\\';
114 /* Skip the newline. */
115 ++in;
117 /* If the newline is quoted, discard following whitespace
118 and any preceding whitespace; leave just one space. */
119 if (backslash)
121 in = next_token (in);
122 while (out > line && isblank ((unsigned char)out[-1]))
123 --out;
124 *out++ = ' ';
126 else
127 /* If the newline isn't quoted, put it in the output. */
128 *out++ = '\n';
130 /* Now copy the following line to the output.
131 Stop when we find backslashes followed by a newline. */
132 while (*in != '\0')
133 if (*in == '\\')
135 p = in + 1;
136 while (*p == '\\')
137 ++p;
138 if (*p == '\n')
140 in = p;
141 break;
143 while (in < p)
144 *out++ = *in++;
146 else
147 *out++ = *in++;
150 *out = '\0';
153 /* Print N spaces (used in debug for target-depth). */
155 void
156 print_spaces (unsigned int n)
158 while (n-- > 0)
159 putchar (' ');
163 /* Return a newly-allocated string whose contents
164 concatenate those of s1, s2, s3. */
166 char *
167 concat (const char *s1, const char *s2, const char *s3)
169 unsigned int len1, len2, len3;
170 char *result;
172 len1 = *s1 != '\0' ? strlen (s1) : 0;
173 len2 = *s2 != '\0' ? strlen (s2) : 0;
174 len3 = *s3 != '\0' ? strlen (s3) : 0;
176 result = (char *) xmalloc (len1 + len2 + len3 + 1);
178 if (*s1 != '\0')
179 bcopy (s1, result, len1);
180 if (*s2 != '\0')
181 bcopy (s2, result + len1, len2);
182 if (*s3 != '\0')
183 bcopy (s3, result + len1 + len2, len3);
184 *(result + len1 + len2 + len3) = '\0';
186 return result;
189 /* Print a message on stdout. */
191 void
192 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
193 message (int prefix, const char *fmt, ...)
194 #else
195 message (prefix, fmt, va_alist)
196 int prefix;
197 const char *fmt;
198 va_dcl
199 #endif
201 #if USE_VARIADIC
202 va_list args;
203 #endif
205 log_working_directory (1);
207 if (fmt != 0)
209 if (prefix)
211 if (makelevel == 0)
212 printf ("%s: ", program);
213 else
214 printf ("%s[%u]: ", program, makelevel);
216 VA_START (args, fmt);
217 VA_PRINTF (stdout, fmt, args);
218 VA_END (args);
219 putchar ('\n');
222 fflush (stdout);
225 /* Print an error message. */
227 void
228 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
229 error (const struct floc *flocp, const char *fmt, ...)
230 #else
231 error (flocp, fmt, va_alist)
232 const struct floc *flocp;
233 const char *fmt;
234 va_dcl
235 #endif
237 #if USE_VARIADIC
238 va_list args;
239 #endif
241 log_working_directory (1);
243 if (flocp && flocp->filenm)
244 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
245 else if (makelevel == 0)
246 fprintf (stderr, "%s: ", program);
247 else
248 fprintf (stderr, "%s[%u]: ", program, makelevel);
250 VA_START(args, fmt);
251 VA_PRINTF (stderr, fmt, args);
252 VA_END (args);
254 putc ('\n', stderr);
255 fflush (stderr);
258 /* Print an error message and exit. */
260 void
261 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
262 fatal (const struct floc *flocp, const char *fmt, ...)
263 #else
264 fatal (flocp, fmt, va_alist)
265 const struct floc *flocp;
266 const char *fmt;
267 va_dcl
268 #endif
270 #if USE_VARIADIC
271 va_list args;
272 #endif
274 log_working_directory (1);
276 if (flocp && flocp->filenm)
277 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
278 else if (makelevel == 0)
279 fprintf (stderr, "%s: *** ", program);
280 else
281 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
283 VA_START(args, fmt);
284 VA_PRINTF (stderr, fmt, args);
285 VA_END (args);
287 fputs (_(". Stop.\n"), stderr);
289 die (2);
292 #ifndef HAVE_STRERROR
294 #undef strerror
296 char *
297 strerror (int errnum)
299 extern int errno, sys_nerr;
300 #ifndef __DECC
301 extern char *sys_errlist[];
302 #endif
303 static char buf[] = "Unknown error 12345678901234567890";
305 if (errno < sys_nerr)
306 return sys_errlist[errnum];
308 sprintf (buf, _("Unknown error %d"), errnum);
309 return buf;
311 #endif
313 /* Print an error message from errno. */
315 void
316 perror_with_name (const char *str, const char *name)
318 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
321 /* Print an error message from errno and exit. */
323 void
324 pfatal_with_name (const char *name)
326 fatal (NILF, _("%s: %s"), name, strerror (errno));
328 /* NOTREACHED */
331 /* Like malloc but get fatal error if memory is exhausted. */
332 /* Don't bother if we're using dmalloc; it provides these for us. */
334 #ifndef HAVE_DMALLOC_H
336 #undef xmalloc
337 #undef xrealloc
338 #undef xstrdup
340 char *
341 xmalloc (unsigned int size)
343 /* Make sure we don't allocate 0, for pre-ANSI libraries. */
344 char *result = (char *) malloc (size ? size : 1);
345 if (result == 0)
346 fatal (NILF, _("virtual memory exhausted"));
347 return result;
351 char *
352 xrealloc (char *ptr, unsigned int size)
354 char *result;
356 /* Some older implementations of realloc() don't conform to ANSI. */
357 if (! size)
358 size = 1;
359 result = ptr ? realloc (ptr, size) : malloc (size);
360 if (result == 0)
361 fatal (NILF, _("virtual memory exhausted"));
362 return result;
366 char *
367 xstrdup (const char *ptr)
369 char *result;
371 #ifdef HAVE_STRDUP
372 result = strdup (ptr);
373 #else
374 result = (char *) malloc (strlen (ptr) + 1);
375 #endif
377 if (result == 0)
378 fatal (NILF, _("virtual memory exhausted"));
380 #ifdef HAVE_STRDUP
381 return result;
382 #else
383 return strcpy(result, ptr);
384 #endif
387 #endif /* HAVE_DMALLOC_H */
389 char *
390 savestring (const char *str, unsigned int length)
392 register char *out = (char *) xmalloc (length + 1);
393 if (length > 0)
394 bcopy (str, out, length);
395 out[length] = '\0';
396 return out;
400 /* Limited INDEX:
401 Search through the string STRING, which ends at LIMIT, for the character C.
402 Returns a pointer to the first occurrence, or nil if none is found.
403 Like INDEX except that the string searched ends where specified
404 instead of at the first null. */
406 char *
407 lindex (const char *s, const char *limit, int c)
409 while (s < limit)
410 if (*s++ == c)
411 return (char *)(s - 1);
413 return 0;
416 /* Return the address of the first whitespace or null in the string S. */
418 char *
419 end_of_token (const char *s)
421 while (*s != '\0' && !isblank ((unsigned char)*s))
422 ++s;
423 return (char *)s;
426 #ifdef WINDOWS32
428 * Same as end_of_token, but take into account a stop character
430 char *
431 end_of_token_w32 (char *s, char stopchar)
433 register char *p = s;
434 register int backslash = 0;
436 while (*p != '\0' && *p != stopchar
437 && (backslash || !isblank ((unsigned char)*p)))
439 if (*p++ == '\\')
441 backslash = !backslash;
442 while (*p == '\\')
444 backslash = !backslash;
445 ++p;
448 else
449 backslash = 0;
452 return p;
454 #endif
456 /* Return the address of the first nonwhitespace or null in the string S. */
458 char *
459 next_token (const char *s)
461 while (isblank ((unsigned char)*s))
462 ++s;
463 return (char *)s;
466 /* Find the next token in PTR; return the address of it, and store the
467 length of the token into *LENGTHPTR if LENGTHPTR is not nil. */
469 char *
470 find_next_token (char **ptr, unsigned int *lengthptr)
472 char *p = next_token (*ptr);
473 char *end;
475 if (*p == '\0')
476 return 0;
478 *ptr = end = end_of_token (p);
479 if (lengthptr != 0)
480 *lengthptr = end - p;
481 return p;
484 /* Copy a chain of `struct dep', making a new chain
485 with the same contents as the old one. */
487 struct dep *
488 copy_dep_chain (struct dep *d)
490 register struct dep *c;
491 struct dep *firstnew = 0;
492 struct dep *lastnew = 0;
494 while (d != 0)
496 c = (struct dep *) xmalloc (sizeof (struct dep));
497 bcopy ((char *) d, (char *) c, sizeof (struct dep));
498 if (c->name != 0)
499 c->name = xstrdup (c->name);
500 c->next = 0;
501 if (firstnew == 0)
502 firstnew = lastnew = c;
503 else
504 lastnew = lastnew->next = c;
506 d = d->next;
509 return firstnew;
512 /* Free a chain of `struct nameseq'. Each nameseq->name is freed
513 as well. Can be used on `struct dep' chains.*/
515 void
516 free_ns_chain (struct nameseq *n)
518 register struct nameseq *tmp;
520 while (n != 0)
522 if (n->name != 0)
523 free (n->name);
525 tmp = n;
527 n = n->next;
529 free (tmp);
533 #ifdef iAPX286
534 /* The losing compiler on this machine can't handle this macro. */
536 char *
537 dep_name (struct dep *dep)
539 return dep->name == 0 ? dep->file->name : dep->name;
541 #endif
543 #ifdef GETLOADAVG_PRIVILEGED
545 #ifdef POSIX
547 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
548 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
549 for example) which claim to be POSIX.1 also have the BSD setreuid and
550 setregid functions, but they don't work as in BSD and only the POSIX.1
551 way works. */
553 #undef HAVE_SETREUID
554 #undef HAVE_SETREGID
556 #else /* Not POSIX. */
558 /* Some POSIX.1 systems have the seteuid and setegid functions. In a
559 POSIX-like system, they are the best thing to use. However, some
560 non-POSIX systems have them too but they do not work in the POSIX style
561 and we must use setreuid and setregid instead. */
563 #undef HAVE_SETEUID
564 #undef HAVE_SETEGID
566 #endif /* POSIX. */
568 #ifndef HAVE_UNISTD_H
569 extern int getuid (), getgid (), geteuid (), getegid ();
570 extern int setuid (), setgid ();
571 #ifdef HAVE_SETEUID
572 extern int seteuid ();
573 #else
574 #ifdef HAVE_SETREUID
575 extern int setreuid ();
576 #endif /* Have setreuid. */
577 #endif /* Have seteuid. */
578 #ifdef HAVE_SETEGID
579 extern int setegid ();
580 #else
581 #ifdef HAVE_SETREGID
582 extern int setregid ();
583 #endif /* Have setregid. */
584 #endif /* Have setegid. */
585 #endif /* No <unistd.h>. */
587 /* Keep track of the user and group IDs for user- and make- access. */
588 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
589 #define access_inited (user_uid != -1)
590 static enum { make, user } current_access;
593 /* Under -d, write a message describing the current IDs. */
595 static void
596 log_access (char *flavor)
598 if (! ISDB (DB_JOBS))
599 return;
601 /* All the other debugging messages go to stdout,
602 but we write this one to stderr because it might be
603 run in a child fork whose stdout is piped. */
605 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
606 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
607 (unsigned long) getegid (), (unsigned long) getgid ());
608 fflush (stderr);
612 static void
613 init_access (void)
615 #ifndef VMS
616 user_uid = getuid ();
617 user_gid = getgid ();
619 make_uid = geteuid ();
620 make_gid = getegid ();
622 /* Do these ever fail? */
623 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
624 pfatal_with_name ("get{e}[gu]id");
626 log_access (_("Initialized access"));
628 current_access = make;
629 #endif
632 #endif /* GETLOADAVG_PRIVILEGED */
634 /* Give the process appropriate permissions for access to
635 user data (i.e., to stat files, or to spawn a child process). */
636 void
637 user_access (void)
639 #ifdef GETLOADAVG_PRIVILEGED
641 if (!access_inited)
642 init_access ();
644 if (current_access == user)
645 return;
647 /* We are in "make access" mode. This means that the effective user and
648 group IDs are those of make (if it was installed setuid or setgid).
649 We now want to set the effective user and group IDs to the real IDs,
650 which are the IDs of the process that exec'd make. */
652 #ifdef HAVE_SETEUID
654 /* Modern systems have the seteuid/setegid calls which set only the
655 effective IDs, which is ideal. */
657 if (seteuid (user_uid) < 0)
658 pfatal_with_name ("user_access: seteuid");
660 #else /* Not HAVE_SETEUID. */
662 #ifndef HAVE_SETREUID
664 /* System V has only the setuid/setgid calls to set user/group IDs.
665 There is an effective ID, which can be set by setuid/setgid.
666 It can be set (unless you are root) only to either what it already is
667 (returned by geteuid/getegid, now in make_uid/make_gid),
668 the real ID (return by getuid/getgid, now in user_uid/user_gid),
669 or the saved set ID (what the effective ID was before this set-ID
670 executable (make) was exec'd). */
672 if (setuid (user_uid) < 0)
673 pfatal_with_name ("user_access: setuid");
675 #else /* HAVE_SETREUID. */
677 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
678 They may be set to themselves or each other. So you have two alternatives
679 at any one time. If you use setuid/setgid, the effective will be set to
680 the real, leaving only one alternative. Using setreuid/setregid, however,
681 you can toggle between your two alternatives by swapping the values in a
682 single setreuid or setregid call. */
684 if (setreuid (make_uid, user_uid) < 0)
685 pfatal_with_name ("user_access: setreuid");
687 #endif /* Not HAVE_SETREUID. */
688 #endif /* HAVE_SETEUID. */
690 #ifdef HAVE_SETEGID
691 if (setegid (user_gid) < 0)
692 pfatal_with_name ("user_access: setegid");
693 #else
694 #ifndef HAVE_SETREGID
695 if (setgid (user_gid) < 0)
696 pfatal_with_name ("user_access: setgid");
697 #else
698 if (setregid (make_gid, user_gid) < 0)
699 pfatal_with_name ("user_access: setregid");
700 #endif
701 #endif
703 current_access = user;
705 log_access (_("User access"));
707 #endif /* GETLOADAVG_PRIVILEGED */
710 /* Give the process appropriate permissions for access to
711 make data (i.e., the load average). */
712 void
713 make_access (void)
715 #ifdef GETLOADAVG_PRIVILEGED
717 if (!access_inited)
718 init_access ();
720 if (current_access == make)
721 return;
723 /* See comments in user_access, above. */
725 #ifdef HAVE_SETEUID
726 if (seteuid (make_uid) < 0)
727 pfatal_with_name ("make_access: seteuid");
728 #else
729 #ifndef HAVE_SETREUID
730 if (setuid (make_uid) < 0)
731 pfatal_with_name ("make_access: setuid");
732 #else
733 if (setreuid (user_uid, make_uid) < 0)
734 pfatal_with_name ("make_access: setreuid");
735 #endif
736 #endif
738 #ifdef HAVE_SETEGID
739 if (setegid (make_gid) < 0)
740 pfatal_with_name ("make_access: setegid");
741 #else
742 #ifndef HAVE_SETREGID
743 if (setgid (make_gid) < 0)
744 pfatal_with_name ("make_access: setgid");
745 #else
746 if (setregid (user_gid, make_gid) < 0)
747 pfatal_with_name ("make_access: setregid");
748 #endif
749 #endif
751 current_access = make;
753 log_access (_("Make access"));
755 #endif /* GETLOADAVG_PRIVILEGED */
758 /* Give the process appropriate permissions for a child process.
759 This is like user_access, but you can't get back to make_access. */
760 void
761 child_access (void)
763 #ifdef GETLOADAVG_PRIVILEGED
765 if (!access_inited)
766 abort ();
768 /* Set both the real and effective UID and GID to the user's.
769 They cannot be changed back to make's. */
771 #ifndef HAVE_SETREUID
772 if (setuid (user_uid) < 0)
773 pfatal_with_name ("child_access: setuid");
774 #else
775 if (setreuid (user_uid, user_uid) < 0)
776 pfatal_with_name ("child_access: setreuid");
777 #endif
779 #ifndef HAVE_SETREGID
780 if (setgid (user_gid) < 0)
781 pfatal_with_name ("child_access: setgid");
782 #else
783 if (setregid (user_gid, user_gid) < 0)
784 pfatal_with_name ("child_access: setregid");
785 #endif
787 log_access (_("Child access"));
789 #endif /* GETLOADAVG_PRIVILEGED */
792 #ifdef NEED_GET_PATH_MAX
793 unsigned int
794 get_path_max (void)
796 static unsigned int value;
798 if (value == 0)
800 long int x = pathconf ("/", _PC_PATH_MAX);
801 if (x > 0)
802 value = x;
803 else
804 return MAXPATHLEN;
807 return value;
809 #endif
812 /* This code is stolen from gnulib.
813 If/when we abandon the requirement to work with K&R compilers, we can
814 remove this (and perhaps other parts of GNU make!) and migrate to using
815 gnulib directly.
817 This is called only through atexit(), which means die() has already been
818 invoked. So, call exit() here directly. Apparently that works...?
821 /* Close standard output, exiting with status 'exit_failure' on failure.
822 If a program writes *anything* to stdout, that program should close
823 stdout and make sure that it succeeds before exiting. Otherwise,
824 suppose that you go to the extreme of checking the return status
825 of every function that does an explicit write to stdout. The last
826 printf can succeed in writing to the internal stream buffer, and yet
827 the fclose(stdout) could still fail (due e.g., to a disk full error)
828 when it tries to write out that buffered data. Thus, you would be
829 left with an incomplete output file and the offending program would
830 exit successfully. Even calling fflush is not always sufficient,
831 since some file systems (NFS and CODA) buffer written/flushed data
832 until an actual close call.
834 Besides, it's wasteful to check the return value from every call
835 that writes to stdout -- just let the internal stream state record
836 the failure. That's what the ferror test is checking below.
838 It's important to detect such failures and exit nonzero because many
839 tools (most notably `make' and other build-management systems) depend
840 on being able to detect failure in other tools via their exit status. */
842 void
843 close_stdout (void)
845 int prev_fail = ferror (stdout);
846 int fclose_fail = fclose (stdout);
848 if (prev_fail || fclose_fail)
850 if (fclose_fail)
851 error (NILF, _("write error: %s"), strerror (errno));
852 else
853 error (NILF, _("write error"));
854 exit (EXIT_FAILURE);