More copyright/license updates.
[make.git] / misc.c
blob6df9556815a39cb864924061ff67527b92b13e82
1 /* Miscellaneous generic support functions for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006 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 it under the
7 terms of the GNU General Public License as published by the Free Software
8 Foundation; either version 2, or (at your option) any later version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 GNU Make; see the file COPYING. If not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
18 #include "make.h"
19 #include "dep.h"
20 #include "debug.h"
22 /* Variadic functions. We go through contortions to allow proper function
23 prototypes for both ANSI and pre-ANSI C compilers, and also for those
24 which support stdarg.h vs. varargs.h, and finally those which have
25 vfprintf(), etc. and those who have _doprnt... or nothing.
27 This fancy stuff all came from GNU fileutils, except for the VA_PRINTF and
28 VA_END macros used here since we have multiple print functions. */
30 #if USE_VARIADIC
31 # if HAVE_STDARG_H
32 # include <stdarg.h>
33 # define VA_START(args, lastarg) va_start(args, lastarg)
34 # else
35 # include <varargs.h>
36 # define VA_START(args, lastarg) va_start(args)
37 # endif
38 # if HAVE_VPRINTF
39 # define VA_PRINTF(fp, lastarg, args) vfprintf((fp), (lastarg), (args))
40 # else
41 # define VA_PRINTF(fp, lastarg, args) _doprnt((lastarg), (args), (fp))
42 # endif
43 # define VA_END(args) va_end(args)
44 #else
45 /* We can't use any variadic interface! */
46 # define va_alist a1, a2, a3, a4, a5, a6, a7, a8
47 # define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8;
48 # define VA_START(args, lastarg)
49 # define VA_PRINTF(fp, lastarg, args) fprintf((fp), (lastarg), va_alist)
50 # define VA_END(args)
51 #endif
54 /* Compare strings *S1 and *S2.
55 Return negative if the first is less, positive if it is greater,
56 zero if they are equal. */
58 int
59 alpha_compare (const void *v1, const void *v2)
61 const char *s1 = *((char **)v1);
62 const char *s2 = *((char **)v2);
64 if (*s1 != *s2)
65 return *s1 - *s2;
66 return strcmp (s1, s2);
69 /* Discard each backslash-newline combination from LINE.
70 Backslash-backslash-newline combinations become backslash-newlines.
71 This is done by copying the text at LINE into itself. */
73 void
74 collapse_continuations (char *line)
76 register char *in, *out, *p;
77 register int backslash;
78 register unsigned int bs_write;
80 in = strchr (line, '\n');
81 if (in == 0)
82 return;
84 out = in;
85 while (out > line && out[-1] == '\\')
86 --out;
88 while (*in != '\0')
90 /* BS_WRITE gets the number of quoted backslashes at
91 the end just before IN, and BACKSLASH gets nonzero
92 if the next character is quoted. */
93 backslash = 0;
94 bs_write = 0;
95 for (p = in - 1; p >= line && *p == '\\'; --p)
97 if (backslash)
98 ++bs_write;
99 backslash = !backslash;
101 /* It should be impossible to go back this far without exiting,
102 but if we do, we can't get the right answer. */
103 if (in == out - 1)
104 abort ();
107 /* Output the appropriate number of backslashes. */
108 while (bs_write-- > 0)
109 *out++ = '\\';
111 /* Skip the newline. */
112 ++in;
114 /* If the newline is quoted, discard following whitespace
115 and any preceding whitespace; leave just one space. */
116 if (backslash)
118 in = next_token (in);
119 while (out > line && isblank ((unsigned char)out[-1]))
120 --out;
121 *out++ = ' ';
123 else
124 /* If the newline isn't quoted, put it in the output. */
125 *out++ = '\n';
127 /* Now copy the following line to the output.
128 Stop when we find backslashes followed by a newline. */
129 while (*in != '\0')
130 if (*in == '\\')
132 p = in + 1;
133 while (*p == '\\')
134 ++p;
135 if (*p == '\n')
137 in = p;
138 break;
140 while (in < p)
141 *out++ = *in++;
143 else
144 *out++ = *in++;
147 *out = '\0';
150 /* Print N spaces (used in debug for target-depth). */
152 void
153 print_spaces (unsigned int n)
155 while (n-- > 0)
156 putchar (' ');
160 /* Return a newly-allocated string whose contents
161 concatenate those of s1, s2, s3. */
163 char *
164 concat (const char *s1, const char *s2, const char *s3)
166 unsigned int len1, len2, len3;
167 char *result;
169 len1 = *s1 != '\0' ? strlen (s1) : 0;
170 len2 = *s2 != '\0' ? strlen (s2) : 0;
171 len3 = *s3 != '\0' ? strlen (s3) : 0;
173 result = (char *) xmalloc (len1 + len2 + len3 + 1);
175 if (*s1 != '\0')
176 bcopy (s1, result, len1);
177 if (*s2 != '\0')
178 bcopy (s2, result + len1, len2);
179 if (*s3 != '\0')
180 bcopy (s3, result + len1 + len2, len3);
181 *(result + len1 + len2 + len3) = '\0';
183 return result;
186 /* Print a message on stdout. */
188 void
189 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
190 message (int prefix, const char *fmt, ...)
191 #else
192 message (prefix, fmt, va_alist)
193 int prefix;
194 const char *fmt;
195 va_dcl
196 #endif
198 #if USE_VARIADIC
199 va_list args;
200 #endif
202 log_working_directory (1);
204 if (fmt != 0)
206 if (prefix)
208 if (makelevel == 0)
209 printf ("%s: ", program);
210 else
211 printf ("%s[%u]: ", program, makelevel);
213 VA_START (args, fmt);
214 VA_PRINTF (stdout, fmt, args);
215 VA_END (args);
216 putchar ('\n');
219 fflush (stdout);
222 /* Print an error message. */
224 void
225 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
226 error (const struct floc *flocp, const char *fmt, ...)
227 #else
228 error (flocp, fmt, va_alist)
229 const struct floc *flocp;
230 const char *fmt;
231 va_dcl
232 #endif
234 #if USE_VARIADIC
235 va_list args;
236 #endif
238 log_working_directory (1);
240 if (flocp && flocp->filenm)
241 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
242 else if (makelevel == 0)
243 fprintf (stderr, "%s: ", program);
244 else
245 fprintf (stderr, "%s[%u]: ", program, makelevel);
247 VA_START(args, fmt);
248 VA_PRINTF (stderr, fmt, args);
249 VA_END (args);
251 putc ('\n', stderr);
252 fflush (stderr);
255 /* Print an error message and exit. */
257 void
258 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
259 fatal (const struct floc *flocp, const char *fmt, ...)
260 #else
261 fatal (flocp, fmt, va_alist)
262 const struct floc *flocp;
263 const char *fmt;
264 va_dcl
265 #endif
267 #if USE_VARIADIC
268 va_list args;
269 #endif
271 log_working_directory (1);
273 if (flocp && flocp->filenm)
274 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
275 else if (makelevel == 0)
276 fprintf (stderr, "%s: *** ", program);
277 else
278 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
280 VA_START(args, fmt);
281 VA_PRINTF (stderr, fmt, args);
282 VA_END (args);
284 fputs (_(". Stop.\n"), stderr);
286 die (2);
289 #ifndef HAVE_STRERROR
291 #undef strerror
293 char *
294 strerror (int errnum)
296 extern int errno, sys_nerr;
297 #ifndef __DECC
298 extern char *sys_errlist[];
299 #endif
300 static char buf[] = "Unknown error 12345678901234567890";
302 if (errno < sys_nerr)
303 return sys_errlist[errnum];
305 sprintf (buf, _("Unknown error %d"), errnum);
306 return buf;
308 #endif
310 /* Print an error message from errno. */
312 void
313 perror_with_name (const char *str, const char *name)
315 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
318 /* Print an error message from errno and exit. */
320 void
321 pfatal_with_name (const char *name)
323 fatal (NILF, _("%s: %s"), name, strerror (errno));
325 /* NOTREACHED */
328 /* Like malloc but get fatal error if memory is exhausted. */
329 /* Don't bother if we're using dmalloc; it provides these for us. */
331 #ifndef HAVE_DMALLOC_H
333 #undef xmalloc
334 #undef xrealloc
335 #undef xstrdup
337 char *
338 xmalloc (unsigned int size)
340 /* Make sure we don't allocate 0, for pre-ANSI libraries. */
341 char *result = (char *) malloc (size ? size : 1);
342 if (result == 0)
343 fatal (NILF, _("virtual memory exhausted"));
344 return result;
348 char *
349 xrealloc (char *ptr, unsigned int size)
351 char *result;
353 /* Some older implementations of realloc() don't conform to ANSI. */
354 if (! size)
355 size = 1;
356 result = ptr ? realloc (ptr, size) : malloc (size);
357 if (result == 0)
358 fatal (NILF, _("virtual memory exhausted"));
359 return result;
363 char *
364 xstrdup (const char *ptr)
366 char *result;
368 #ifdef HAVE_STRDUP
369 result = strdup (ptr);
370 #else
371 result = (char *) malloc (strlen (ptr) + 1);
372 #endif
374 if (result == 0)
375 fatal (NILF, _("virtual memory exhausted"));
377 #ifdef HAVE_STRDUP
378 return result;
379 #else
380 return strcpy(result, ptr);
381 #endif
384 #endif /* HAVE_DMALLOC_H */
386 char *
387 savestring (const char *str, unsigned int length)
389 register char *out = (char *) xmalloc (length + 1);
390 if (length > 0)
391 bcopy (str, out, length);
392 out[length] = '\0';
393 return out;
397 /* Limited INDEX:
398 Search through the string STRING, which ends at LIMIT, for the character C.
399 Returns a pointer to the first occurrence, or nil if none is found.
400 Like INDEX except that the string searched ends where specified
401 instead of at the first null. */
403 char *
404 lindex (const char *s, const char *limit, int c)
406 while (s < limit)
407 if (*s++ == c)
408 return (char *)(s - 1);
410 return 0;
413 /* Return the address of the first whitespace or null in the string S. */
415 char *
416 end_of_token (const char *s)
418 while (*s != '\0' && !isblank ((unsigned char)*s))
419 ++s;
420 return (char *)s;
423 #ifdef WINDOWS32
425 * Same as end_of_token, but take into account a stop character
427 char *
428 end_of_token_w32 (char *s, char stopchar)
430 register char *p = s;
431 register int backslash = 0;
433 while (*p != '\0' && *p != stopchar
434 && (backslash || !isblank ((unsigned char)*p)))
436 if (*p++ == '\\')
438 backslash = !backslash;
439 while (*p == '\\')
441 backslash = !backslash;
442 ++p;
445 else
446 backslash = 0;
449 return p;
451 #endif
453 /* Return the address of the first nonwhitespace or null in the string S. */
455 char *
456 next_token (const char *s)
458 while (isblank ((unsigned char)*s))
459 ++s;
460 return (char *)s;
463 /* Find the next token in PTR; return the address of it, and store the
464 length of the token into *LENGTHPTR if LENGTHPTR is not nil. */
466 char *
467 find_next_token (char **ptr, unsigned int *lengthptr)
469 char *p = next_token (*ptr);
470 char *end;
472 if (*p == '\0')
473 return 0;
475 *ptr = end = end_of_token (p);
476 if (lengthptr != 0)
477 *lengthptr = end - p;
478 return p;
481 /* Copy a chain of `struct dep', making a new chain
482 with the same contents as the old one. */
484 struct dep *
485 copy_dep_chain (const struct dep *d)
487 register struct dep *c;
488 struct dep *firstnew = 0;
489 struct dep *lastnew = 0;
491 while (d != 0)
493 c = (struct dep *) xmalloc (sizeof (struct dep));
494 bcopy ((char *) d, (char *) c, sizeof (struct dep));
495 if (c->name != 0)
496 c->name = xstrdup (c->name);
497 c->next = 0;
498 if (firstnew == 0)
499 firstnew = lastnew = c;
500 else
501 lastnew = lastnew->next = c;
503 d = d->next;
506 return firstnew;
509 /* Free a chain of 'struct dep'. */
511 void
512 free_dep_chain (struct dep *d)
514 while (d != 0)
516 struct dep *df = d;
517 d = d->next;
519 free (df->name);
520 free ((char *)df);
524 /* Free a chain of `struct nameseq'. Each nameseq->name is freed
525 as well. Can be used on `struct dep' chains.*/
527 void
528 free_ns_chain (struct nameseq *n)
530 register struct nameseq *tmp;
532 while (n != 0)
534 if (n->name != 0)
535 free (n->name);
537 tmp = n;
539 n = n->next;
541 free (tmp);
545 #ifdef iAPX286
546 /* The losing compiler on this machine can't handle this macro. */
548 char *
549 dep_name (struct dep *dep)
551 return dep->name == 0 ? dep->file->name : dep->name;
553 #endif
555 #ifdef GETLOADAVG_PRIVILEGED
557 #ifdef POSIX
559 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
560 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
561 for example) which claim to be POSIX.1 also have the BSD setreuid and
562 setregid functions, but they don't work as in BSD and only the POSIX.1
563 way works. */
565 #undef HAVE_SETREUID
566 #undef HAVE_SETREGID
568 #else /* Not POSIX. */
570 /* Some POSIX.1 systems have the seteuid and setegid functions. In a
571 POSIX-like system, they are the best thing to use. However, some
572 non-POSIX systems have them too but they do not work in the POSIX style
573 and we must use setreuid and setregid instead. */
575 #undef HAVE_SETEUID
576 #undef HAVE_SETEGID
578 #endif /* POSIX. */
580 #ifndef HAVE_UNISTD_H
581 extern int getuid (), getgid (), geteuid (), getegid ();
582 extern int setuid (), setgid ();
583 #ifdef HAVE_SETEUID
584 extern int seteuid ();
585 #else
586 #ifdef HAVE_SETREUID
587 extern int setreuid ();
588 #endif /* Have setreuid. */
589 #endif /* Have seteuid. */
590 #ifdef HAVE_SETEGID
591 extern int setegid ();
592 #else
593 #ifdef HAVE_SETREGID
594 extern int setregid ();
595 #endif /* Have setregid. */
596 #endif /* Have setegid. */
597 #endif /* No <unistd.h>. */
599 /* Keep track of the user and group IDs for user- and make- access. */
600 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
601 #define access_inited (user_uid != -1)
602 static enum { make, user } current_access;
605 /* Under -d, write a message describing the current IDs. */
607 static void
608 log_access (char *flavor)
610 if (! ISDB (DB_JOBS))
611 return;
613 /* All the other debugging messages go to stdout,
614 but we write this one to stderr because it might be
615 run in a child fork whose stdout is piped. */
617 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
618 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
619 (unsigned long) getegid (), (unsigned long) getgid ());
620 fflush (stderr);
624 static void
625 init_access (void)
627 #ifndef VMS
628 user_uid = getuid ();
629 user_gid = getgid ();
631 make_uid = geteuid ();
632 make_gid = getegid ();
634 /* Do these ever fail? */
635 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
636 pfatal_with_name ("get{e}[gu]id");
638 log_access (_("Initialized access"));
640 current_access = make;
641 #endif
644 #endif /* GETLOADAVG_PRIVILEGED */
646 /* Give the process appropriate permissions for access to
647 user data (i.e., to stat files, or to spawn a child process). */
648 void
649 user_access (void)
651 #ifdef GETLOADAVG_PRIVILEGED
653 if (!access_inited)
654 init_access ();
656 if (current_access == user)
657 return;
659 /* We are in "make access" mode. This means that the effective user and
660 group IDs are those of make (if it was installed setuid or setgid).
661 We now want to set the effective user and group IDs to the real IDs,
662 which are the IDs of the process that exec'd make. */
664 #ifdef HAVE_SETEUID
666 /* Modern systems have the seteuid/setegid calls which set only the
667 effective IDs, which is ideal. */
669 if (seteuid (user_uid) < 0)
670 pfatal_with_name ("user_access: seteuid");
672 #else /* Not HAVE_SETEUID. */
674 #ifndef HAVE_SETREUID
676 /* System V has only the setuid/setgid calls to set user/group IDs.
677 There is an effective ID, which can be set by setuid/setgid.
678 It can be set (unless you are root) only to either what it already is
679 (returned by geteuid/getegid, now in make_uid/make_gid),
680 the real ID (return by getuid/getgid, now in user_uid/user_gid),
681 or the saved set ID (what the effective ID was before this set-ID
682 executable (make) was exec'd). */
684 if (setuid (user_uid) < 0)
685 pfatal_with_name ("user_access: setuid");
687 #else /* HAVE_SETREUID. */
689 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
690 They may be set to themselves or each other. So you have two alternatives
691 at any one time. If you use setuid/setgid, the effective will be set to
692 the real, leaving only one alternative. Using setreuid/setregid, however,
693 you can toggle between your two alternatives by swapping the values in a
694 single setreuid or setregid call. */
696 if (setreuid (make_uid, user_uid) < 0)
697 pfatal_with_name ("user_access: setreuid");
699 #endif /* Not HAVE_SETREUID. */
700 #endif /* HAVE_SETEUID. */
702 #ifdef HAVE_SETEGID
703 if (setegid (user_gid) < 0)
704 pfatal_with_name ("user_access: setegid");
705 #else
706 #ifndef HAVE_SETREGID
707 if (setgid (user_gid) < 0)
708 pfatal_with_name ("user_access: setgid");
709 #else
710 if (setregid (make_gid, user_gid) < 0)
711 pfatal_with_name ("user_access: setregid");
712 #endif
713 #endif
715 current_access = user;
717 log_access (_("User access"));
719 #endif /* GETLOADAVG_PRIVILEGED */
722 /* Give the process appropriate permissions for access to
723 make data (i.e., the load average). */
724 void
725 make_access (void)
727 #ifdef GETLOADAVG_PRIVILEGED
729 if (!access_inited)
730 init_access ();
732 if (current_access == make)
733 return;
735 /* See comments in user_access, above. */
737 #ifdef HAVE_SETEUID
738 if (seteuid (make_uid) < 0)
739 pfatal_with_name ("make_access: seteuid");
740 #else
741 #ifndef HAVE_SETREUID
742 if (setuid (make_uid) < 0)
743 pfatal_with_name ("make_access: setuid");
744 #else
745 if (setreuid (user_uid, make_uid) < 0)
746 pfatal_with_name ("make_access: setreuid");
747 #endif
748 #endif
750 #ifdef HAVE_SETEGID
751 if (setegid (make_gid) < 0)
752 pfatal_with_name ("make_access: setegid");
753 #else
754 #ifndef HAVE_SETREGID
755 if (setgid (make_gid) < 0)
756 pfatal_with_name ("make_access: setgid");
757 #else
758 if (setregid (user_gid, make_gid) < 0)
759 pfatal_with_name ("make_access: setregid");
760 #endif
761 #endif
763 current_access = make;
765 log_access (_("Make access"));
767 #endif /* GETLOADAVG_PRIVILEGED */
770 /* Give the process appropriate permissions for a child process.
771 This is like user_access, but you can't get back to make_access. */
772 void
773 child_access (void)
775 #ifdef GETLOADAVG_PRIVILEGED
777 if (!access_inited)
778 abort ();
780 /* Set both the real and effective UID and GID to the user's.
781 They cannot be changed back to make's. */
783 #ifndef HAVE_SETREUID
784 if (setuid (user_uid) < 0)
785 pfatal_with_name ("child_access: setuid");
786 #else
787 if (setreuid (user_uid, user_uid) < 0)
788 pfatal_with_name ("child_access: setreuid");
789 #endif
791 #ifndef HAVE_SETREGID
792 if (setgid (user_gid) < 0)
793 pfatal_with_name ("child_access: setgid");
794 #else
795 if (setregid (user_gid, user_gid) < 0)
796 pfatal_with_name ("child_access: setregid");
797 #endif
799 log_access (_("Child access"));
801 #endif /* GETLOADAVG_PRIVILEGED */
804 #ifdef NEED_GET_PATH_MAX
805 unsigned int
806 get_path_max (void)
808 static unsigned int value;
810 if (value == 0)
812 long int x = pathconf ("/", _PC_PATH_MAX);
813 if (x > 0)
814 value = x;
815 else
816 return MAXPATHLEN;
819 return value;
821 #endif
824 /* This code is stolen from gnulib.
825 If/when we abandon the requirement to work with K&R compilers, we can
826 remove this (and perhaps other parts of GNU make!) and migrate to using
827 gnulib directly.
829 This is called only through atexit(), which means die() has already been
830 invoked. So, call exit() here directly. Apparently that works...?
833 /* Close standard output, exiting with status 'exit_failure' on failure.
834 If a program writes *anything* to stdout, that program should close
835 stdout and make sure that it succeeds before exiting. Otherwise,
836 suppose that you go to the extreme of checking the return status
837 of every function that does an explicit write to stdout. The last
838 printf can succeed in writing to the internal stream buffer, and yet
839 the fclose(stdout) could still fail (due e.g., to a disk full error)
840 when it tries to write out that buffered data. Thus, you would be
841 left with an incomplete output file and the offending program would
842 exit successfully. Even calling fflush is not always sufficient,
843 since some file systems (NFS and CODA) buffer written/flushed data
844 until an actual close call.
846 Besides, it's wasteful to check the return value from every call
847 that writes to stdout -- just let the internal stream state record
848 the failure. That's what the ferror test is checking below.
850 It's important to detect such failures and exit nonzero because many
851 tools (most notably `make' and other build-management systems) depend
852 on being able to detect failure in other tools via their exit status. */
854 void
855 close_stdout (void)
857 int prev_fail = ferror (stdout);
858 int fclose_fail = fclose (stdout);
860 if (prev_fail || fclose_fail)
862 if (fclose_fail)
863 error (NILF, _("write error: %s"), strerror (errno));
864 else
865 error (NILF, _("write error"));
866 exit (EXIT_FAILURE);