(target_environment): Don't use shell_var if its `value' field is NULL.
[make.git] / misc.c
blobfd5e55815df1cc832b051f82071f6b98a0776e44
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 Free Software
4 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 quoted, discard following whitespace
116 and any preceding whitespace; leave just one space. */
117 if (backslash)
119 in = next_token (in);
120 while (out > line && isblank ((unsigned char)out[-1]))
121 --out;
122 *out++ = ' ';
124 else
125 /* If the newline isn't quoted, put it in the output. */
126 *out++ = '\n';
128 /* Now copy the following line to the output.
129 Stop when we find backslashes followed by a newline. */
130 while (*in != '\0')
131 if (*in == '\\')
133 p = in + 1;
134 while (*p == '\\')
135 ++p;
136 if (*p == '\n')
138 in = p;
139 break;
141 while (in < p)
142 *out++ = *in++;
144 else
145 *out++ = *in++;
148 *out = '\0';
151 /* Print N spaces (used in debug for target-depth). */
153 void
154 print_spaces (unsigned int n)
156 while (n-- > 0)
157 putchar (' ');
161 /* Return a string whose contents concatenate those of s1, s2, s3.
162 This string lives in static, re-used memory. */
164 char *
165 concat (const char *s1, const char *s2, const char *s3)
167 unsigned int len1, len2, len3;
168 static unsigned int rlen = 0;
169 static char *result = NULL;
171 len1 = (s1 && *s1 != '\0') ? strlen (s1) : 0;
172 len2 = (s2 && *s2 != '\0') ? strlen (s2) : 0;
173 len3 = (s3 && *s3 != '\0') ? strlen (s3) : 0;
175 if (len1 + len2 + len3 + 1 > rlen)
176 result = xrealloc (result, (rlen = len1 + len2 + len3 + 10));
178 if (len1)
179 memcpy (result, s1, len1);
180 if (len2)
181 memcpy (result + len1, s2, len2);
182 if (len3)
183 memcpy (result + len1 + len2, s3, len3);
185 result[len1+len2+len3] = '\0';
187 return result;
190 /* Print a message on stdout. */
192 void
193 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
194 message (int prefix, const char *fmt, ...)
195 #else
196 message (prefix, fmt, va_alist)
197 int prefix;
198 const char *fmt;
199 va_dcl
200 #endif
202 #if USE_VARIADIC
203 va_list args;
204 #endif
206 log_working_directory (1);
208 if (fmt != 0)
210 if (prefix)
212 if (makelevel == 0)
213 printf ("%s: ", program);
214 else
215 printf ("%s[%u]: ", program, makelevel);
217 VA_START (args, fmt);
218 VA_PRINTF (stdout, fmt, args);
219 VA_END (args);
220 putchar ('\n');
223 fflush (stdout);
226 /* Print an error message. */
228 void
229 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
230 error (const struct floc *flocp, const char *fmt, ...)
231 #else
232 error (flocp, fmt, va_alist)
233 const struct floc *flocp;
234 const char *fmt;
235 va_dcl
236 #endif
238 #if USE_VARIADIC
239 va_list args;
240 #endif
242 log_working_directory (1);
244 if (flocp && flocp->filenm)
245 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
246 else if (makelevel == 0)
247 fprintf (stderr, "%s: ", program);
248 else
249 fprintf (stderr, "%s[%u]: ", program, makelevel);
251 VA_START(args, fmt);
252 VA_PRINTF (stderr, fmt, args);
253 VA_END (args);
255 putc ('\n', stderr);
256 fflush (stderr);
259 /* Print an error message and exit. */
261 void
262 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
263 fatal (const struct floc *flocp, const char *fmt, ...)
264 #else
265 fatal (flocp, fmt, va_alist)
266 const struct floc *flocp;
267 const char *fmt;
268 va_dcl
269 #endif
271 #if USE_VARIADIC
272 va_list args;
273 #endif
275 log_working_directory (1);
277 if (flocp && flocp->filenm)
278 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
279 else if (makelevel == 0)
280 fprintf (stderr, "%s: *** ", program);
281 else
282 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
284 VA_START(args, fmt);
285 VA_PRINTF (stderr, fmt, args);
286 VA_END (args);
288 fputs (_(". Stop.\n"), stderr);
290 die (2);
293 #ifndef HAVE_STRERROR
295 #undef strerror
297 char *
298 strerror (int errnum)
300 extern int errno, sys_nerr;
301 #ifndef __DECC
302 extern char *sys_errlist[];
303 #endif
304 static char buf[] = "Unknown error 12345678901234567890";
306 if (errno < sys_nerr)
307 return sys_errlist[errnum];
309 sprintf (buf, _("Unknown error %d"), errnum);
310 return buf;
312 #endif
314 /* Print an error message from errno. */
316 void
317 perror_with_name (const char *str, const char *name)
319 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
322 /* Print an error message from errno and exit. */
324 void
325 pfatal_with_name (const char *name)
327 fatal (NILF, _("%s: %s"), name, strerror (errno));
329 /* NOTREACHED */
332 /* Like malloc but get fatal error if memory is exhausted. */
333 /* Don't bother if we're using dmalloc; it provides these for us. */
335 #ifndef HAVE_DMALLOC_H
337 #undef xmalloc
338 #undef xrealloc
339 #undef xstrdup
341 void *
342 xmalloc (unsigned int size)
344 /* Make sure we don't allocate 0, for pre-ANSI libraries. */
345 void *result = malloc (size ? size : 1);
346 if (result == 0)
347 fatal (NILF, _("virtual memory exhausted"));
348 return result;
352 void *
353 xrealloc (void *ptr, unsigned int size)
355 void *result;
357 /* Some older implementations of realloc() don't conform to ANSI. */
358 if (! size)
359 size = 1;
360 result = ptr ? realloc (ptr, size) : malloc (size);
361 if (result == 0)
362 fatal (NILF, _("virtual memory exhausted"));
363 return result;
367 char *
368 xstrdup (const char *ptr)
370 char *result;
372 #ifdef HAVE_STRDUP
373 result = strdup (ptr);
374 #else
375 result = malloc (strlen (ptr) + 1);
376 #endif
378 if (result == 0)
379 fatal (NILF, _("virtual memory exhausted"));
381 #ifdef HAVE_STRDUP
382 return result;
383 #else
384 return strcpy (result, ptr);
385 #endif
388 #endif /* HAVE_DMALLOC_H */
390 char *
391 savestring (const char *str, unsigned int length)
393 char *out = xmalloc (length + 1);
394 if (length > 0)
395 memcpy (out, str, length);
396 out[length] = '\0';
397 return out;
401 /* Limited INDEX:
402 Search through the string STRING, which ends at LIMIT, for the character C.
403 Returns a pointer to the first occurrence, or nil if none is found.
404 Like INDEX except that the string searched ends where specified
405 instead of at the first null. */
407 char *
408 lindex (const char *s, const char *limit, int c)
410 while (s < limit)
411 if (*s++ == c)
412 return (char *)(s - 1);
414 return 0;
417 /* Return the address of the first whitespace or null in the string S. */
419 char *
420 end_of_token (const char *s)
422 while (*s != '\0' && !isblank ((unsigned char)*s))
423 ++s;
424 return (char *)s;
427 #ifdef WINDOWS32
429 * Same as end_of_token, but take into account a stop character
431 char *
432 end_of_token_w32 (const char *s, char stopchar)
434 const char *p = s;
435 int backslash = 0;
437 while (*p != '\0' && *p != stopchar
438 && (backslash || !isblank ((unsigned char)*p)))
440 if (*p++ == '\\')
442 backslash = !backslash;
443 while (*p == '\\')
445 backslash = !backslash;
446 ++p;
449 else
450 backslash = 0;
453 return (char *)p;
455 #endif
457 /* Return the address of the first nonwhitespace or null in the string S. */
459 char *
460 next_token (const char *s)
462 while (isblank ((unsigned char)*s))
463 ++s;
464 return (char *)s;
467 /* Find the next token in PTR; return the address of it, and store the length
468 of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
469 of the token, so this function can be called repeatedly in a loop. */
471 char *
472 find_next_token (const char **ptr, unsigned int *lengthptr)
474 const char *p = next_token (*ptr);
476 if (*p == '\0')
477 return 0;
479 *ptr = end_of_token (p);
480 if (lengthptr != 0)
481 *lengthptr = *ptr - p;
483 return (char *)p;
487 /* Allocate a new `struct dep' with all fields initialized to 0. */
489 struct dep *
490 alloc_dep ()
492 struct dep *d = xmalloc (sizeof (struct dep));
493 memset (d, '\0', sizeof (struct dep));
494 return d;
498 /* Free `struct dep' along with `name' and `stem'. */
500 void
501 free_dep (struct dep *d)
503 free (d);
506 /* Copy a chain of `struct dep', making a new chain
507 with the same contents as the old one. */
509 struct dep *
510 copy_dep_chain (const struct dep *d)
512 struct dep *firstnew = 0;
513 struct dep *lastnew = 0;
515 while (d != 0)
517 struct dep *c = xmalloc (sizeof (struct dep));
518 memcpy (c, d, sizeof (struct dep));
520 c->next = 0;
521 if (firstnew == 0)
522 firstnew = lastnew = c;
523 else
524 lastnew = lastnew->next = c;
526 d = d->next;
529 return firstnew;
532 /* Free a chain of 'struct dep'. */
534 void
535 free_dep_chain (struct dep *d)
537 while (d != 0)
539 struct dep *df = d;
540 d = d->next;
541 free_dep (df);
545 /* Free a chain of struct nameseq.
546 For struct dep chains use free_dep_chain. */
548 void
549 free_ns_chain (struct nameseq *ns)
551 while (ns != 0)
553 struct nameseq *t = ns;
554 ns = ns->next;
555 free (t);
560 #if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
562 /* If we don't have strcasecmp() (from POSIX), or anything that can substitute
563 for it, define our own version. */
566 strcasecmp (const char *s1, const char *s2)
568 while (1)
570 int c1 = (int) *(s1++);
571 int c2 = (int) *(s2++);
573 if (isalpha (c1))
574 c1 = tolower (c1);
575 if (isalpha (c2))
576 c2 = tolower (c2);
578 if (c1 != '\0' && c1 == c2)
579 continue;
581 return (c1 - c2);
584 #endif
586 #ifdef GETLOADAVG_PRIVILEGED
588 #ifdef POSIX
590 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
591 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
592 for example) which claim to be POSIX.1 also have the BSD setreuid and
593 setregid functions, but they don't work as in BSD and only the POSIX.1
594 way works. */
596 #undef HAVE_SETREUID
597 #undef HAVE_SETREGID
599 #else /* Not POSIX. */
601 /* Some POSIX.1 systems have the seteuid and setegid functions. In a
602 POSIX-like system, they are the best thing to use. However, some
603 non-POSIX systems have them too but they do not work in the POSIX style
604 and we must use setreuid and setregid instead. */
606 #undef HAVE_SETEUID
607 #undef HAVE_SETEGID
609 #endif /* POSIX. */
611 #ifndef HAVE_UNISTD_H
612 extern int getuid (), getgid (), geteuid (), getegid ();
613 extern int setuid (), setgid ();
614 #ifdef HAVE_SETEUID
615 extern int seteuid ();
616 #else
617 #ifdef HAVE_SETREUID
618 extern int setreuid ();
619 #endif /* Have setreuid. */
620 #endif /* Have seteuid. */
621 #ifdef HAVE_SETEGID
622 extern int setegid ();
623 #else
624 #ifdef HAVE_SETREGID
625 extern int setregid ();
626 #endif /* Have setregid. */
627 #endif /* Have setegid. */
628 #endif /* No <unistd.h>. */
630 /* Keep track of the user and group IDs for user- and make- access. */
631 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
632 #define access_inited (user_uid != -1)
633 static enum { make, user } current_access;
636 /* Under -d, write a message describing the current IDs. */
638 static void
639 log_access (const char *flavor)
641 if (! ISDB (DB_JOBS))
642 return;
644 /* All the other debugging messages go to stdout,
645 but we write this one to stderr because it might be
646 run in a child fork whose stdout is piped. */
648 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
649 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
650 (unsigned long) getegid (), (unsigned long) getgid ());
651 fflush (stderr);
655 static void
656 init_access (void)
658 #ifndef VMS
659 user_uid = getuid ();
660 user_gid = getgid ();
662 make_uid = geteuid ();
663 make_gid = getegid ();
665 /* Do these ever fail? */
666 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
667 pfatal_with_name ("get{e}[gu]id");
669 log_access (_("Initialized access"));
671 current_access = make;
672 #endif
675 #endif /* GETLOADAVG_PRIVILEGED */
677 /* Give the process appropriate permissions for access to
678 user data (i.e., to stat files, or to spawn a child process). */
679 void
680 user_access (void)
682 #ifdef GETLOADAVG_PRIVILEGED
684 if (!access_inited)
685 init_access ();
687 if (current_access == user)
688 return;
690 /* We are in "make access" mode. This means that the effective user and
691 group IDs are those of make (if it was installed setuid or setgid).
692 We now want to set the effective user and group IDs to the real IDs,
693 which are the IDs of the process that exec'd make. */
695 #ifdef HAVE_SETEUID
697 /* Modern systems have the seteuid/setegid calls which set only the
698 effective IDs, which is ideal. */
700 if (seteuid (user_uid) < 0)
701 pfatal_with_name ("user_access: seteuid");
703 #else /* Not HAVE_SETEUID. */
705 #ifndef HAVE_SETREUID
707 /* System V has only the setuid/setgid calls to set user/group IDs.
708 There is an effective ID, which can be set by setuid/setgid.
709 It can be set (unless you are root) only to either what it already is
710 (returned by geteuid/getegid, now in make_uid/make_gid),
711 the real ID (return by getuid/getgid, now in user_uid/user_gid),
712 or the saved set ID (what the effective ID was before this set-ID
713 executable (make) was exec'd). */
715 if (setuid (user_uid) < 0)
716 pfatal_with_name ("user_access: setuid");
718 #else /* HAVE_SETREUID. */
720 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
721 They may be set to themselves or each other. So you have two alternatives
722 at any one time. If you use setuid/setgid, the effective will be set to
723 the real, leaving only one alternative. Using setreuid/setregid, however,
724 you can toggle between your two alternatives by swapping the values in a
725 single setreuid or setregid call. */
727 if (setreuid (make_uid, user_uid) < 0)
728 pfatal_with_name ("user_access: setreuid");
730 #endif /* Not HAVE_SETREUID. */
731 #endif /* HAVE_SETEUID. */
733 #ifdef HAVE_SETEGID
734 if (setegid (user_gid) < 0)
735 pfatal_with_name ("user_access: setegid");
736 #else
737 #ifndef HAVE_SETREGID
738 if (setgid (user_gid) < 0)
739 pfatal_with_name ("user_access: setgid");
740 #else
741 if (setregid (make_gid, user_gid) < 0)
742 pfatal_with_name ("user_access: setregid");
743 #endif
744 #endif
746 current_access = user;
748 log_access (_("User access"));
750 #endif /* GETLOADAVG_PRIVILEGED */
753 /* Give the process appropriate permissions for access to
754 make data (i.e., the load average). */
755 void
756 make_access (void)
758 #ifdef GETLOADAVG_PRIVILEGED
760 if (!access_inited)
761 init_access ();
763 if (current_access == make)
764 return;
766 /* See comments in user_access, above. */
768 #ifdef HAVE_SETEUID
769 if (seteuid (make_uid) < 0)
770 pfatal_with_name ("make_access: seteuid");
771 #else
772 #ifndef HAVE_SETREUID
773 if (setuid (make_uid) < 0)
774 pfatal_with_name ("make_access: setuid");
775 #else
776 if (setreuid (user_uid, make_uid) < 0)
777 pfatal_with_name ("make_access: setreuid");
778 #endif
779 #endif
781 #ifdef HAVE_SETEGID
782 if (setegid (make_gid) < 0)
783 pfatal_with_name ("make_access: setegid");
784 #else
785 #ifndef HAVE_SETREGID
786 if (setgid (make_gid) < 0)
787 pfatal_with_name ("make_access: setgid");
788 #else
789 if (setregid (user_gid, make_gid) < 0)
790 pfatal_with_name ("make_access: setregid");
791 #endif
792 #endif
794 current_access = make;
796 log_access (_("Make access"));
798 #endif /* GETLOADAVG_PRIVILEGED */
801 /* Give the process appropriate permissions for a child process.
802 This is like user_access, but you can't get back to make_access. */
803 void
804 child_access (void)
806 #ifdef GETLOADAVG_PRIVILEGED
808 if (!access_inited)
809 abort ();
811 /* Set both the real and effective UID and GID to the user's.
812 They cannot be changed back to make's. */
814 #ifndef HAVE_SETREUID
815 if (setuid (user_uid) < 0)
816 pfatal_with_name ("child_access: setuid");
817 #else
818 if (setreuid (user_uid, user_uid) < 0)
819 pfatal_with_name ("child_access: setreuid");
820 #endif
822 #ifndef HAVE_SETREGID
823 if (setgid (user_gid) < 0)
824 pfatal_with_name ("child_access: setgid");
825 #else
826 if (setregid (user_gid, user_gid) < 0)
827 pfatal_with_name ("child_access: setregid");
828 #endif
830 log_access (_("Child access"));
832 #endif /* GETLOADAVG_PRIVILEGED */
835 #ifdef NEED_GET_PATH_MAX
836 unsigned int
837 get_path_max (void)
839 static unsigned int value;
841 if (value == 0)
843 long int x = pathconf ("/", _PC_PATH_MAX);
844 if (x > 0)
845 value = x;
846 else
847 return MAXPATHLEN;
850 return value;
852 #endif
855 /* This code is stolen from gnulib.
856 If/when we abandon the requirement to work with K&R compilers, we can
857 remove this (and perhaps other parts of GNU make!) and migrate to using
858 gnulib directly.
860 This is called only through atexit(), which means die() has already been
861 invoked. So, call exit() here directly. Apparently that works...?
864 /* Close standard output, exiting with status 'exit_failure' on failure.
865 If a program writes *anything* to stdout, that program should close
866 stdout and make sure that it succeeds before exiting. Otherwise,
867 suppose that you go to the extreme of checking the return status
868 of every function that does an explicit write to stdout. The last
869 printf can succeed in writing to the internal stream buffer, and yet
870 the fclose(stdout) could still fail (due e.g., to a disk full error)
871 when it tries to write out that buffered data. Thus, you would be
872 left with an incomplete output file and the offending program would
873 exit successfully. Even calling fflush is not always sufficient,
874 since some file systems (NFS and CODA) buffer written/flushed data
875 until an actual close call.
877 Besides, it's wasteful to check the return value from every call
878 that writes to stdout -- just let the internal stream state record
879 the failure. That's what the ferror test is checking below.
881 It's important to detect such failures and exit nonzero because many
882 tools (most notably `make' and other build-management systems) depend
883 on being able to detect failure in other tools via their exit status. */
885 void
886 close_stdout (void)
888 int prev_fail = ferror (stdout);
889 int fclose_fail = fclose (stdout);
891 if (prev_fail || fclose_fail)
893 if (fclose_fail)
894 error (NILF, _("write error: %s"), strerror (errno));
895 else
896 error (NILF, _("write error"));
897 exit (EXIT_FAILURE);