Update copyrights for 2010.
[make.git] / misc.c
blobf4806acb76d0581d36eac51b8c0e5166032a4029
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, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
20 #include "dep.h"
21 #include "debug.h"
23 /* Variadic functions. We go through contortions to allow proper function
24 prototypes for both ANSI and pre-ANSI C compilers, and also for those
25 which support stdarg.h vs. varargs.h, and finally those which have
26 vfprintf(), etc. and those who have _doprnt... or nothing.
28 This fancy stuff all came from GNU fileutils, except for the VA_PRINTF and
29 VA_END macros used here since we have multiple print functions. */
31 #if USE_VARIADIC
32 # if HAVE_STDARG_H
33 # include <stdarg.h>
34 # define VA_START(args, lastarg) va_start(args, lastarg)
35 # else
36 # include <varargs.h>
37 # define VA_START(args, lastarg) va_start(args)
38 # endif
39 # if HAVE_VPRINTF
40 # define VA_PRINTF(fp, lastarg, args) vfprintf((fp), (lastarg), (args))
41 # else
42 # define VA_PRINTF(fp, lastarg, args) _doprnt((lastarg), (args), (fp))
43 # endif
44 # define VA_END(args) va_end(args)
45 #else
46 /* We can't use any variadic interface! */
47 # define va_alist a1, a2, a3, a4, a5, a6, a7, a8
48 # define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8;
49 # define VA_START(args, lastarg)
50 # define VA_PRINTF(fp, lastarg, args) fprintf((fp), (lastarg), va_alist)
51 # define VA_END(args)
52 #endif
55 /* Compare strings *S1 and *S2.
56 Return negative if the first is less, positive if it is greater,
57 zero if they are equal. */
59 int
60 alpha_compare (const void *v1, const void *v2)
62 const char *s1 = *((char **)v1);
63 const char *s2 = *((char **)v2);
65 if (*s1 != *s2)
66 return *s1 - *s2;
67 return strcmp (s1, s2);
70 /* Discard each backslash-newline combination from LINE.
71 Backslash-backslash-newline combinations become backslash-newlines.
72 This is done by copying the text at LINE into itself. */
74 void
75 collapse_continuations (char *line)
77 register char *in, *out, *p;
78 register int backslash;
79 register unsigned int bs_write;
81 in = strchr (line, '\n');
82 if (in == 0)
83 return;
85 out = in;
86 while (out > line && out[-1] == '\\')
87 --out;
89 while (*in != '\0')
91 /* BS_WRITE gets the number of quoted backslashes at
92 the end just before IN, and BACKSLASH gets nonzero
93 if the next character is quoted. */
94 backslash = 0;
95 bs_write = 0;
96 for (p = in - 1; p >= line && *p == '\\'; --p)
98 if (backslash)
99 ++bs_write;
100 backslash = !backslash;
102 /* It should be impossible to go back this far without exiting,
103 but if we do, we can't get the right answer. */
104 if (in == out - 1)
105 abort ();
108 /* Output the appropriate number of backslashes. */
109 while (bs_write-- > 0)
110 *out++ = '\\';
112 /* Skip the newline. */
113 ++in;
115 /* If the newline is escaped, discard following whitespace leaving just
116 one space. POSIX requires that each backslash/newline/following
117 whitespace sequence be reduced to a single space. */
118 if (backslash)
120 in = next_token (in);
121 /* Removing this loop will fix Savannah bug #16670: do we want to? */
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 string whose contents concatenate the NUM strings provided
164 This string lives in static, re-used memory. */
166 const char *
167 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
168 concat (unsigned int num, ...)
169 #else
170 concat (num, va_alist)
171 unsigned int num;
172 va_dcl
173 #endif
175 static unsigned int rlen = 0;
176 static char *result = NULL;
177 int ri = 0;
179 #if USE_VARIADIC
180 va_list args;
181 #endif
183 VA_START (args, num);
185 while (num-- > 0)
187 const char *s = va_arg (args, const char *);
188 unsigned int l = s ? strlen (s) : 0;
190 if (l == 0)
191 continue;
193 if (ri + l > rlen)
195 rlen = ((rlen ? rlen : 60) + l) * 2;
196 result = xrealloc (result, rlen);
199 memcpy (result + ri, s, l);
200 ri += l;
203 VA_END (args);
205 result[ri] = '\0';
207 return result;
210 /* Print a message on stdout. */
212 void
213 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
214 message (int prefix, const char *fmt, ...)
215 #else
216 message (prefix, fmt, va_alist)
217 int prefix;
218 const char *fmt;
219 va_dcl
220 #endif
222 #if USE_VARIADIC
223 va_list args;
224 #endif
226 log_working_directory (1);
228 if (fmt != 0)
230 if (prefix)
232 if (makelevel == 0)
233 printf ("%s: ", program);
234 else
235 printf ("%s[%u]: ", program, makelevel);
237 VA_START (args, fmt);
238 VA_PRINTF (stdout, fmt, args);
239 VA_END (args);
240 putchar ('\n');
243 fflush (stdout);
246 /* Print an error message. */
248 void
249 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
250 error (const struct floc *flocp, const char *fmt, ...)
251 #else
252 error (flocp, fmt, va_alist)
253 const struct floc *flocp;
254 const char *fmt;
255 va_dcl
256 #endif
258 #if USE_VARIADIC
259 va_list args;
260 #endif
262 log_working_directory (1);
264 if (flocp && flocp->filenm)
265 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
266 else if (makelevel == 0)
267 fprintf (stderr, "%s: ", program);
268 else
269 fprintf (stderr, "%s[%u]: ", program, makelevel);
271 VA_START(args, fmt);
272 VA_PRINTF (stderr, fmt, args);
273 VA_END (args);
275 putc ('\n', stderr);
276 fflush (stderr);
279 /* Print an error message and exit. */
281 void
282 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
283 fatal (const struct floc *flocp, const char *fmt, ...)
284 #else
285 fatal (flocp, fmt, va_alist)
286 const struct floc *flocp;
287 const char *fmt;
288 va_dcl
289 #endif
291 #if USE_VARIADIC
292 va_list args;
293 #endif
295 log_working_directory (1);
297 if (flocp && flocp->filenm)
298 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
299 else if (makelevel == 0)
300 fprintf (stderr, "%s: *** ", program);
301 else
302 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
304 VA_START(args, fmt);
305 VA_PRINTF (stderr, fmt, args);
306 VA_END (args);
308 fputs (_(". Stop.\n"), stderr);
310 die (2);
313 #ifndef HAVE_STRERROR
315 #undef strerror
317 char *
318 strerror (int errnum)
320 extern int errno, sys_nerr;
321 #ifndef __DECC
322 extern char *sys_errlist[];
323 #endif
324 static char buf[] = "Unknown error 12345678901234567890";
326 if (errno < sys_nerr)
327 return sys_errlist[errnum];
329 sprintf (buf, _("Unknown error %d"), errnum);
330 return buf;
332 #endif
334 /* Print an error message from errno. */
336 void
337 perror_with_name (const char *str, const char *name)
339 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
342 /* Print an error message from errno and exit. */
344 void
345 pfatal_with_name (const char *name)
347 fatal (NILF, _("%s: %s"), name, strerror (errno));
349 /* NOTREACHED */
352 /* Like malloc but get fatal error if memory is exhausted. */
353 /* Don't bother if we're using dmalloc; it provides these for us. */
355 #ifndef HAVE_DMALLOC_H
357 #undef xmalloc
358 #undef xcalloc
359 #undef xrealloc
360 #undef xstrdup
362 void *
363 xmalloc (unsigned int size)
365 /* Make sure we don't allocate 0, for pre-ISO implementations. */
366 void *result = malloc (size ? size : 1);
367 if (result == 0)
368 fatal (NILF, _("virtual memory exhausted"));
369 return result;
373 void *
374 xcalloc (unsigned int size)
376 /* Make sure we don't allocate 0, for pre-ISO implementations. */
377 void *result = calloc (size ? size : 1, 1);
378 if (result == 0)
379 fatal (NILF, _("virtual memory exhausted"));
380 return result;
384 void *
385 xrealloc (void *ptr, unsigned int size)
387 void *result;
389 /* Some older implementations of realloc() don't conform to ISO. */
390 if (! size)
391 size = 1;
392 result = ptr ? realloc (ptr, size) : malloc (size);
393 if (result == 0)
394 fatal (NILF, _("virtual memory exhausted"));
395 return result;
399 char *
400 xstrdup (const char *ptr)
402 char *result;
404 #ifdef HAVE_STRDUP
405 result = strdup (ptr);
406 #else
407 result = malloc (strlen (ptr) + 1);
408 #endif
410 if (result == 0)
411 fatal (NILF, _("virtual memory exhausted"));
413 #ifdef HAVE_STRDUP
414 return result;
415 #else
416 return strcpy (result, ptr);
417 #endif
420 #endif /* HAVE_DMALLOC_H */
422 char *
423 xstrndup (const char *str, unsigned int length)
425 char *result;
427 #ifdef HAVE_STRNDUP
428 result = strndup (str, length);
429 if (result == 0)
430 fatal (NILF, _("virtual memory exhausted"));
431 #else
432 result = xmalloc (length + 1);
433 if (length > 0)
434 strncpy (result, str, length);
435 result[length] = '\0';
436 #endif
438 return result;
442 /* Limited INDEX:
443 Search through the string STRING, which ends at LIMIT, for the character C.
444 Returns a pointer to the first occurrence, or nil if none is found.
445 Like INDEX except that the string searched ends where specified
446 instead of at the first null. */
448 char *
449 lindex (const char *s, const char *limit, int c)
451 while (s < limit)
452 if (*s++ == c)
453 return (char *)(s - 1);
455 return 0;
458 /* Return the address of the first whitespace or null in the string S. */
460 char *
461 end_of_token (const char *s)
463 while (*s != '\0' && !isblank ((unsigned char)*s))
464 ++s;
465 return (char *)s;
468 #ifdef WINDOWS32
470 * Same as end_of_token, but take into account a stop character
472 char *
473 end_of_token_w32 (const char *s, char stopchar)
475 const char *p = s;
476 int backslash = 0;
478 while (*p != '\0' && *p != stopchar
479 && (backslash || !isblank ((unsigned char)*p)))
481 if (*p++ == '\\')
483 backslash = !backslash;
484 while (*p == '\\')
486 backslash = !backslash;
487 ++p;
490 else
491 backslash = 0;
494 return (char *)p;
496 #endif
498 /* Return the address of the first nonwhitespace or null in the string S. */
500 char *
501 next_token (const char *s)
503 while (isblank ((unsigned char)*s))
504 ++s;
505 return (char *)s;
508 /* Find the next token in PTR; return the address of it, and store the length
509 of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
510 of the token, so this function can be called repeatedly in a loop. */
512 char *
513 find_next_token (const char **ptr, unsigned int *lengthptr)
515 const char *p = next_token (*ptr);
517 if (*p == '\0')
518 return 0;
520 *ptr = end_of_token (p);
521 if (lengthptr != 0)
522 *lengthptr = *ptr - p;
524 return (char *)p;
528 /* Copy a chain of `struct dep'. For 2nd expansion deps, dup the name. */
530 struct dep *
531 copy_dep_chain (const struct dep *d)
533 struct dep *firstnew = 0;
534 struct dep *lastnew = 0;
536 while (d != 0)
538 struct dep *c = xmalloc (sizeof (struct dep));
539 memcpy (c, d, sizeof (struct dep));
541 if (c->need_2nd_expansion)
542 c->name = xstrdup (c->name);
544 c->next = 0;
545 if (firstnew == 0)
546 firstnew = lastnew = c;
547 else
548 lastnew = lastnew->next = c;
550 d = d->next;
553 return firstnew;
556 /* Free a chain of 'struct dep'. */
558 void
559 free_dep_chain (struct dep *d)
561 while (d != 0)
563 struct dep *df = d;
564 d = d->next;
565 free_dep (df);
569 /* Free a chain of struct nameseq.
570 For struct dep chains use free_dep_chain. */
572 void
573 free_ns_chain (struct nameseq *ns)
575 while (ns != 0)
577 struct nameseq *t = ns;
578 ns = ns->next;
579 free (t);
584 #if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
586 /* If we don't have strcasecmp() (from POSIX), or anything that can substitute
587 for it, define our own version. */
590 strcasecmp (const char *s1, const char *s2)
592 while (1)
594 int c1 = (int) *(s1++);
595 int c2 = (int) *(s2++);
597 if (isalpha (c1))
598 c1 = tolower (c1);
599 if (isalpha (c2))
600 c2 = tolower (c2);
602 if (c1 != '\0' && c1 == c2)
603 continue;
605 return (c1 - c2);
608 #endif
610 #ifdef GETLOADAVG_PRIVILEGED
612 #ifdef POSIX
614 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
615 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
616 for example) which claim to be POSIX.1 also have the BSD setreuid and
617 setregid functions, but they don't work as in BSD and only the POSIX.1
618 way works. */
620 #undef HAVE_SETREUID
621 #undef HAVE_SETREGID
623 #else /* Not POSIX. */
625 /* Some POSIX.1 systems have the seteuid and setegid functions. In a
626 POSIX-like system, they are the best thing to use. However, some
627 non-POSIX systems have them too but they do not work in the POSIX style
628 and we must use setreuid and setregid instead. */
630 #undef HAVE_SETEUID
631 #undef HAVE_SETEGID
633 #endif /* POSIX. */
635 #ifndef HAVE_UNISTD_H
636 extern int getuid (), getgid (), geteuid (), getegid ();
637 extern int setuid (), setgid ();
638 #ifdef HAVE_SETEUID
639 extern int seteuid ();
640 #else
641 #ifdef HAVE_SETREUID
642 extern int setreuid ();
643 #endif /* Have setreuid. */
644 #endif /* Have seteuid. */
645 #ifdef HAVE_SETEGID
646 extern int setegid ();
647 #else
648 #ifdef HAVE_SETREGID
649 extern int setregid ();
650 #endif /* Have setregid. */
651 #endif /* Have setegid. */
652 #endif /* No <unistd.h>. */
654 /* Keep track of the user and group IDs for user- and make- access. */
655 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
656 #define access_inited (user_uid != -1)
657 static enum { make, user } current_access;
660 /* Under -d, write a message describing the current IDs. */
662 static void
663 log_access (const char *flavor)
665 if (! ISDB (DB_JOBS))
666 return;
668 /* All the other debugging messages go to stdout,
669 but we write this one to stderr because it might be
670 run in a child fork whose stdout is piped. */
672 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
673 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
674 (unsigned long) getegid (), (unsigned long) getgid ());
675 fflush (stderr);
679 static void
680 init_access (void)
682 #ifndef VMS
683 user_uid = getuid ();
684 user_gid = getgid ();
686 make_uid = geteuid ();
687 make_gid = getegid ();
689 /* Do these ever fail? */
690 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
691 pfatal_with_name ("get{e}[gu]id");
693 log_access (_("Initialized access"));
695 current_access = make;
696 #endif
699 #endif /* GETLOADAVG_PRIVILEGED */
701 /* Give the process appropriate permissions for access to
702 user data (i.e., to stat files, or to spawn a child process). */
703 void
704 user_access (void)
706 #ifdef GETLOADAVG_PRIVILEGED
708 if (!access_inited)
709 init_access ();
711 if (current_access == user)
712 return;
714 /* We are in "make access" mode. This means that the effective user and
715 group IDs are those of make (if it was installed setuid or setgid).
716 We now want to set the effective user and group IDs to the real IDs,
717 which are the IDs of the process that exec'd make. */
719 #ifdef HAVE_SETEUID
721 /* Modern systems have the seteuid/setegid calls which set only the
722 effective IDs, which is ideal. */
724 if (seteuid (user_uid) < 0)
725 pfatal_with_name ("user_access: seteuid");
727 #else /* Not HAVE_SETEUID. */
729 #ifndef HAVE_SETREUID
731 /* System V has only the setuid/setgid calls to set user/group IDs.
732 There is an effective ID, which can be set by setuid/setgid.
733 It can be set (unless you are root) only to either what it already is
734 (returned by geteuid/getegid, now in make_uid/make_gid),
735 the real ID (return by getuid/getgid, now in user_uid/user_gid),
736 or the saved set ID (what the effective ID was before this set-ID
737 executable (make) was exec'd). */
739 if (setuid (user_uid) < 0)
740 pfatal_with_name ("user_access: setuid");
742 #else /* HAVE_SETREUID. */
744 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
745 They may be set to themselves or each other. So you have two alternatives
746 at any one time. If you use setuid/setgid, the effective will be set to
747 the real, leaving only one alternative. Using setreuid/setregid, however,
748 you can toggle between your two alternatives by swapping the values in a
749 single setreuid or setregid call. */
751 if (setreuid (make_uid, user_uid) < 0)
752 pfatal_with_name ("user_access: setreuid");
754 #endif /* Not HAVE_SETREUID. */
755 #endif /* HAVE_SETEUID. */
757 #ifdef HAVE_SETEGID
758 if (setegid (user_gid) < 0)
759 pfatal_with_name ("user_access: setegid");
760 #else
761 #ifndef HAVE_SETREGID
762 if (setgid (user_gid) < 0)
763 pfatal_with_name ("user_access: setgid");
764 #else
765 if (setregid (make_gid, user_gid) < 0)
766 pfatal_with_name ("user_access: setregid");
767 #endif
768 #endif
770 current_access = user;
772 log_access (_("User access"));
774 #endif /* GETLOADAVG_PRIVILEGED */
777 /* Give the process appropriate permissions for access to
778 make data (i.e., the load average). */
779 void
780 make_access (void)
782 #ifdef GETLOADAVG_PRIVILEGED
784 if (!access_inited)
785 init_access ();
787 if (current_access == make)
788 return;
790 /* See comments in user_access, above. */
792 #ifdef HAVE_SETEUID
793 if (seteuid (make_uid) < 0)
794 pfatal_with_name ("make_access: seteuid");
795 #else
796 #ifndef HAVE_SETREUID
797 if (setuid (make_uid) < 0)
798 pfatal_with_name ("make_access: setuid");
799 #else
800 if (setreuid (user_uid, make_uid) < 0)
801 pfatal_with_name ("make_access: setreuid");
802 #endif
803 #endif
805 #ifdef HAVE_SETEGID
806 if (setegid (make_gid) < 0)
807 pfatal_with_name ("make_access: setegid");
808 #else
809 #ifndef HAVE_SETREGID
810 if (setgid (make_gid) < 0)
811 pfatal_with_name ("make_access: setgid");
812 #else
813 if (setregid (user_gid, make_gid) < 0)
814 pfatal_with_name ("make_access: setregid");
815 #endif
816 #endif
818 current_access = make;
820 log_access (_("Make access"));
822 #endif /* GETLOADAVG_PRIVILEGED */
825 /* Give the process appropriate permissions for a child process.
826 This is like user_access, but you can't get back to make_access. */
827 void
828 child_access (void)
830 #ifdef GETLOADAVG_PRIVILEGED
832 if (!access_inited)
833 abort ();
835 /* Set both the real and effective UID and GID to the user's.
836 They cannot be changed back to make's. */
838 #ifndef HAVE_SETREUID
839 if (setuid (user_uid) < 0)
840 pfatal_with_name ("child_access: setuid");
841 #else
842 if (setreuid (user_uid, user_uid) < 0)
843 pfatal_with_name ("child_access: setreuid");
844 #endif
846 #ifndef HAVE_SETREGID
847 if (setgid (user_gid) < 0)
848 pfatal_with_name ("child_access: setgid");
849 #else
850 if (setregid (user_gid, user_gid) < 0)
851 pfatal_with_name ("child_access: setregid");
852 #endif
854 log_access (_("Child access"));
856 #endif /* GETLOADAVG_PRIVILEGED */
859 #ifdef NEED_GET_PATH_MAX
860 unsigned int
861 get_path_max (void)
863 static unsigned int value;
865 if (value == 0)
867 long int x = pathconf ("/", _PC_PATH_MAX);
868 if (x > 0)
869 value = x;
870 else
871 return MAXPATHLEN;
874 return value;
876 #endif
879 /* This code is stolen from gnulib.
880 If/when we abandon the requirement to work with K&R compilers, we can
881 remove this (and perhaps other parts of GNU make!) and migrate to using
882 gnulib directly.
884 This is called only through atexit(), which means die() has already been
885 invoked. So, call exit() here directly. Apparently that works...?
888 /* Close standard output, exiting with status 'exit_failure' on failure.
889 If a program writes *anything* to stdout, that program should close
890 stdout and make sure that it succeeds before exiting. Otherwise,
891 suppose that you go to the extreme of checking the return status
892 of every function that does an explicit write to stdout. The last
893 printf can succeed in writing to the internal stream buffer, and yet
894 the fclose(stdout) could still fail (due e.g., to a disk full error)
895 when it tries to write out that buffered data. Thus, you would be
896 left with an incomplete output file and the offending program would
897 exit successfully. Even calling fflush is not always sufficient,
898 since some file systems (NFS and CODA) buffer written/flushed data
899 until an actual close call.
901 Besides, it's wasteful to check the return value from every call
902 that writes to stdout -- just let the internal stream state record
903 the failure. That's what the ferror test is checking below.
905 It's important to detect such failures and exit nonzero because many
906 tools (most notably `make' and other build-management systems) depend
907 on being able to detect failure in other tools via their exit status. */
909 void
910 close_stdout (void)
912 int prev_fail = ferror (stdout);
913 int fclose_fail = fclose (stdout);
915 if (prev_fail || fclose_fail)
917 if (fclose_fail)
918 error (NILF, _("write error: %s"), strerror (errno));
919 else
920 error (NILF, _("write error"));
921 exit (EXIT_FAILURE);