- Fixes Savannah bug #18435
[make/kirr.git] / misc.c
blob078da25f6295b9adbebb3c985b1c86e8d3c0c17e
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 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 those of s1, s2, s3.
164 This string lives in static, re-used memory. */
166 char *
167 concat (const char *s1, const char *s2, const char *s3)
169 unsigned int len1, len2, len3;
170 static unsigned int rlen = 0;
171 static char *result = NULL;
173 len1 = (s1 && *s1 != '\0') ? strlen (s1) : 0;
174 len2 = (s2 && *s2 != '\0') ? strlen (s2) : 0;
175 len3 = (s3 && *s3 != '\0') ? strlen (s3) : 0;
177 if (len1 + len2 + len3 + 1 > rlen)
178 result = xrealloc (result, (rlen = len1 + len2 + len3 + 10));
180 if (len1)
181 memcpy (result, s1, len1);
182 if (len2)
183 memcpy (result + len1, s2, len2);
184 if (len3)
185 memcpy (result + len1 + len2, s3, len3);
187 result[len1+len2+len3] = '\0';
189 return result;
192 /* Print a message on stdout. */
194 void
195 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
196 message (int prefix, const char *fmt, ...)
197 #else
198 message (prefix, fmt, va_alist)
199 int prefix;
200 const char *fmt;
201 va_dcl
202 #endif
204 #if USE_VARIADIC
205 va_list args;
206 #endif
208 log_working_directory (1);
210 if (fmt != 0)
212 if (prefix)
214 if (makelevel == 0)
215 printf ("%s: ", program);
216 else
217 printf ("%s[%u]: ", program, makelevel);
219 VA_START (args, fmt);
220 VA_PRINTF (stdout, fmt, args);
221 VA_END (args);
222 putchar ('\n');
225 fflush (stdout);
228 /* Print an error message. */
230 void
231 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
232 error (const struct floc *flocp, const char *fmt, ...)
233 #else
234 error (flocp, fmt, va_alist)
235 const struct floc *flocp;
236 const char *fmt;
237 va_dcl
238 #endif
240 #if USE_VARIADIC
241 va_list args;
242 #endif
244 log_working_directory (1);
246 if (flocp && flocp->filenm)
247 fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
248 else if (makelevel == 0)
249 fprintf (stderr, "%s: ", program);
250 else
251 fprintf (stderr, "%s[%u]: ", program, makelevel);
253 VA_START(args, fmt);
254 VA_PRINTF (stderr, fmt, args);
255 VA_END (args);
257 putc ('\n', stderr);
258 fflush (stderr);
261 /* Print an error message and exit. */
263 void
264 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
265 fatal (const struct floc *flocp, const char *fmt, ...)
266 #else
267 fatal (flocp, fmt, va_alist)
268 const struct floc *flocp;
269 const char *fmt;
270 va_dcl
271 #endif
273 #if USE_VARIADIC
274 va_list args;
275 #endif
277 log_working_directory (1);
279 if (flocp && flocp->filenm)
280 fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
281 else if (makelevel == 0)
282 fprintf (stderr, "%s: *** ", program);
283 else
284 fprintf (stderr, "%s[%u]: *** ", program, makelevel);
286 VA_START(args, fmt);
287 VA_PRINTF (stderr, fmt, args);
288 VA_END (args);
290 fputs (_(". Stop.\n"), stderr);
292 die (2);
295 #ifndef HAVE_STRERROR
297 #undef strerror
299 char *
300 strerror (int errnum)
302 extern int errno, sys_nerr;
303 #ifndef __DECC
304 extern char *sys_errlist[];
305 #endif
306 static char buf[] = "Unknown error 12345678901234567890";
308 if (errno < sys_nerr)
309 return sys_errlist[errnum];
311 sprintf (buf, _("Unknown error %d"), errnum);
312 return buf;
314 #endif
316 /* Print an error message from errno. */
318 void
319 perror_with_name (const char *str, const char *name)
321 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
324 /* Print an error message from errno and exit. */
326 void
327 pfatal_with_name (const char *name)
329 fatal (NILF, _("%s: %s"), name, strerror (errno));
331 /* NOTREACHED */
334 /* Like malloc but get fatal error if memory is exhausted. */
335 /* Don't bother if we're using dmalloc; it provides these for us. */
337 #ifndef HAVE_DMALLOC_H
339 #undef xmalloc
340 #undef xrealloc
341 #undef xstrdup
343 void *
344 xmalloc (unsigned int size)
346 /* Make sure we don't allocate 0, for pre-ANSI libraries. */
347 void *result = malloc (size ? size : 1);
348 if (result == 0)
349 fatal (NILF, _("virtual memory exhausted"));
350 return result;
354 void *
355 xrealloc (void *ptr, unsigned int size)
357 void *result;
359 /* Some older implementations of realloc() don't conform to ANSI. */
360 if (! size)
361 size = 1;
362 result = ptr ? realloc (ptr, size) : malloc (size);
363 if (result == 0)
364 fatal (NILF, _("virtual memory exhausted"));
365 return result;
369 char *
370 xstrdup (const char *ptr)
372 char *result;
374 #ifdef HAVE_STRDUP
375 result = strdup (ptr);
376 #else
377 result = malloc (strlen (ptr) + 1);
378 #endif
380 if (result == 0)
381 fatal (NILF, _("virtual memory exhausted"));
383 #ifdef HAVE_STRDUP
384 return result;
385 #else
386 return strcpy (result, ptr);
387 #endif
390 #endif /* HAVE_DMALLOC_H */
392 char *
393 xstrndup (const char *str, unsigned int length)
395 char *result;
397 #ifdef HAVE_STRNDUP
398 result = strndup (str, length);
399 if (result == 0)
400 fatal (NILF, _("virtual memory exhausted"));
401 #else
402 result = xmalloc (length + 1);
403 strncpy (result, str, length);
404 result[length] = '\0';
405 #endif
407 return result;
411 /* Limited INDEX:
412 Search through the string STRING, which ends at LIMIT, for the character C.
413 Returns a pointer to the first occurrence, or nil if none is found.
414 Like INDEX except that the string searched ends where specified
415 instead of at the first null. */
417 char *
418 lindex (const char *s, const char *limit, int c)
420 while (s < limit)
421 if (*s++ == c)
422 return (char *)(s - 1);
424 return 0;
427 /* Return the address of the first whitespace or null in the string S. */
429 char *
430 end_of_token (const char *s)
432 while (*s != '\0' && !isblank ((unsigned char)*s))
433 ++s;
434 return (char *)s;
437 #ifdef WINDOWS32
439 * Same as end_of_token, but take into account a stop character
441 char *
442 end_of_token_w32 (const char *s, char stopchar)
444 const char *p = s;
445 int backslash = 0;
447 while (*p != '\0' && *p != stopchar
448 && (backslash || !isblank ((unsigned char)*p)))
450 if (*p++ == '\\')
452 backslash = !backslash;
453 while (*p == '\\')
455 backslash = !backslash;
456 ++p;
459 else
460 backslash = 0;
463 return (char *)p;
465 #endif
467 /* Return the address of the first nonwhitespace or null in the string S. */
469 char *
470 next_token (const char *s)
472 while (isblank ((unsigned char)*s))
473 ++s;
474 return (char *)s;
477 /* Find the next token in PTR; return the address of it, and store the length
478 of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
479 of the token, so this function can be called repeatedly in a loop. */
481 char *
482 find_next_token (const char **ptr, unsigned int *lengthptr)
484 const char *p = next_token (*ptr);
486 if (*p == '\0')
487 return 0;
489 *ptr = end_of_token (p);
490 if (lengthptr != 0)
491 *lengthptr = *ptr - p;
493 return (char *)p;
497 /* Allocate a new `struct dep' with all fields initialized to 0. */
499 struct dep *
500 alloc_dep ()
502 struct dep *d = xmalloc (sizeof (struct dep));
503 memset (d, '\0', sizeof (struct dep));
504 return d;
508 /* Free `struct dep' along with `name' and `stem'. */
510 void
511 free_dep (struct dep *d)
513 free (d);
516 /* Copy a chain of `struct dep', making a new chain
517 with the same contents as the old one. */
519 struct dep *
520 copy_dep_chain (const struct dep *d)
522 struct dep *firstnew = 0;
523 struct dep *lastnew = 0;
525 while (d != 0)
527 struct dep *c = xmalloc (sizeof (struct dep));
528 memcpy (c, d, sizeof (struct dep));
530 c->next = 0;
531 if (firstnew == 0)
532 firstnew = lastnew = c;
533 else
534 lastnew = lastnew->next = c;
536 d = d->next;
539 return firstnew;
542 /* Free a chain of 'struct dep'. */
544 void
545 free_dep_chain (struct dep *d)
547 while (d != 0)
549 struct dep *df = d;
550 d = d->next;
551 free_dep (df);
555 /* Free a chain of struct nameseq.
556 For struct dep chains use free_dep_chain. */
558 void
559 free_ns_chain (struct nameseq *ns)
561 while (ns != 0)
563 struct nameseq *t = ns;
564 ns = ns->next;
565 free (t);
570 #if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
572 /* If we don't have strcasecmp() (from POSIX), or anything that can substitute
573 for it, define our own version. */
576 strcasecmp (const char *s1, const char *s2)
578 while (1)
580 int c1 = (int) *(s1++);
581 int c2 = (int) *(s2++);
583 if (isalpha (c1))
584 c1 = tolower (c1);
585 if (isalpha (c2))
586 c2 = tolower (c2);
588 if (c1 != '\0' && c1 == c2)
589 continue;
591 return (c1 - c2);
594 #endif
596 #ifdef GETLOADAVG_PRIVILEGED
598 #ifdef POSIX
600 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
601 functions, they work as POSIX.1 says. Some systems (Alpha OSF/1 1.2,
602 for example) which claim to be POSIX.1 also have the BSD setreuid and
603 setregid functions, but they don't work as in BSD and only the POSIX.1
604 way works. */
606 #undef HAVE_SETREUID
607 #undef HAVE_SETREGID
609 #else /* Not POSIX. */
611 /* Some POSIX.1 systems have the seteuid and setegid functions. In a
612 POSIX-like system, they are the best thing to use. However, some
613 non-POSIX systems have them too but they do not work in the POSIX style
614 and we must use setreuid and setregid instead. */
616 #undef HAVE_SETEUID
617 #undef HAVE_SETEGID
619 #endif /* POSIX. */
621 #ifndef HAVE_UNISTD_H
622 extern int getuid (), getgid (), geteuid (), getegid ();
623 extern int setuid (), setgid ();
624 #ifdef HAVE_SETEUID
625 extern int seteuid ();
626 #else
627 #ifdef HAVE_SETREUID
628 extern int setreuid ();
629 #endif /* Have setreuid. */
630 #endif /* Have seteuid. */
631 #ifdef HAVE_SETEGID
632 extern int setegid ();
633 #else
634 #ifdef HAVE_SETREGID
635 extern int setregid ();
636 #endif /* Have setregid. */
637 #endif /* Have setegid. */
638 #endif /* No <unistd.h>. */
640 /* Keep track of the user and group IDs for user- and make- access. */
641 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
642 #define access_inited (user_uid != -1)
643 static enum { make, user } current_access;
646 /* Under -d, write a message describing the current IDs. */
648 static void
649 log_access (const char *flavor)
651 if (! ISDB (DB_JOBS))
652 return;
654 /* All the other debugging messages go to stdout,
655 but we write this one to stderr because it might be
656 run in a child fork whose stdout is piped. */
658 fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
659 flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
660 (unsigned long) getegid (), (unsigned long) getgid ());
661 fflush (stderr);
665 static void
666 init_access (void)
668 #ifndef VMS
669 user_uid = getuid ();
670 user_gid = getgid ();
672 make_uid = geteuid ();
673 make_gid = getegid ();
675 /* Do these ever fail? */
676 if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
677 pfatal_with_name ("get{e}[gu]id");
679 log_access (_("Initialized access"));
681 current_access = make;
682 #endif
685 #endif /* GETLOADAVG_PRIVILEGED */
687 /* Give the process appropriate permissions for access to
688 user data (i.e., to stat files, or to spawn a child process). */
689 void
690 user_access (void)
692 #ifdef GETLOADAVG_PRIVILEGED
694 if (!access_inited)
695 init_access ();
697 if (current_access == user)
698 return;
700 /* We are in "make access" mode. This means that the effective user and
701 group IDs are those of make (if it was installed setuid or setgid).
702 We now want to set the effective user and group IDs to the real IDs,
703 which are the IDs of the process that exec'd make. */
705 #ifdef HAVE_SETEUID
707 /* Modern systems have the seteuid/setegid calls which set only the
708 effective IDs, which is ideal. */
710 if (seteuid (user_uid) < 0)
711 pfatal_with_name ("user_access: seteuid");
713 #else /* Not HAVE_SETEUID. */
715 #ifndef HAVE_SETREUID
717 /* System V has only the setuid/setgid calls to set user/group IDs.
718 There is an effective ID, which can be set by setuid/setgid.
719 It can be set (unless you are root) only to either what it already is
720 (returned by geteuid/getegid, now in make_uid/make_gid),
721 the real ID (return by getuid/getgid, now in user_uid/user_gid),
722 or the saved set ID (what the effective ID was before this set-ID
723 executable (make) was exec'd). */
725 if (setuid (user_uid) < 0)
726 pfatal_with_name ("user_access: setuid");
728 #else /* HAVE_SETREUID. */
730 /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
731 They may be set to themselves or each other. So you have two alternatives
732 at any one time. If you use setuid/setgid, the effective will be set to
733 the real, leaving only one alternative. Using setreuid/setregid, however,
734 you can toggle between your two alternatives by swapping the values in a
735 single setreuid or setregid call. */
737 if (setreuid (make_uid, user_uid) < 0)
738 pfatal_with_name ("user_access: setreuid");
740 #endif /* Not HAVE_SETREUID. */
741 #endif /* HAVE_SETEUID. */
743 #ifdef HAVE_SETEGID
744 if (setegid (user_gid) < 0)
745 pfatal_with_name ("user_access: setegid");
746 #else
747 #ifndef HAVE_SETREGID
748 if (setgid (user_gid) < 0)
749 pfatal_with_name ("user_access: setgid");
750 #else
751 if (setregid (make_gid, user_gid) < 0)
752 pfatal_with_name ("user_access: setregid");
753 #endif
754 #endif
756 current_access = user;
758 log_access (_("User access"));
760 #endif /* GETLOADAVG_PRIVILEGED */
763 /* Give the process appropriate permissions for access to
764 make data (i.e., the load average). */
765 void
766 make_access (void)
768 #ifdef GETLOADAVG_PRIVILEGED
770 if (!access_inited)
771 init_access ();
773 if (current_access == make)
774 return;
776 /* See comments in user_access, above. */
778 #ifdef HAVE_SETEUID
779 if (seteuid (make_uid) < 0)
780 pfatal_with_name ("make_access: seteuid");
781 #else
782 #ifndef HAVE_SETREUID
783 if (setuid (make_uid) < 0)
784 pfatal_with_name ("make_access: setuid");
785 #else
786 if (setreuid (user_uid, make_uid) < 0)
787 pfatal_with_name ("make_access: setreuid");
788 #endif
789 #endif
791 #ifdef HAVE_SETEGID
792 if (setegid (make_gid) < 0)
793 pfatal_with_name ("make_access: setegid");
794 #else
795 #ifndef HAVE_SETREGID
796 if (setgid (make_gid) < 0)
797 pfatal_with_name ("make_access: setgid");
798 #else
799 if (setregid (user_gid, make_gid) < 0)
800 pfatal_with_name ("make_access: setregid");
801 #endif
802 #endif
804 current_access = make;
806 log_access (_("Make access"));
808 #endif /* GETLOADAVG_PRIVILEGED */
811 /* Give the process appropriate permissions for a child process.
812 This is like user_access, but you can't get back to make_access. */
813 void
814 child_access (void)
816 #ifdef GETLOADAVG_PRIVILEGED
818 if (!access_inited)
819 abort ();
821 /* Set both the real and effective UID and GID to the user's.
822 They cannot be changed back to make's. */
824 #ifndef HAVE_SETREUID
825 if (setuid (user_uid) < 0)
826 pfatal_with_name ("child_access: setuid");
827 #else
828 if (setreuid (user_uid, user_uid) < 0)
829 pfatal_with_name ("child_access: setreuid");
830 #endif
832 #ifndef HAVE_SETREGID
833 if (setgid (user_gid) < 0)
834 pfatal_with_name ("child_access: setgid");
835 #else
836 if (setregid (user_gid, user_gid) < 0)
837 pfatal_with_name ("child_access: setregid");
838 #endif
840 log_access (_("Child access"));
842 #endif /* GETLOADAVG_PRIVILEGED */
845 #ifdef NEED_GET_PATH_MAX
846 unsigned int
847 get_path_max (void)
849 static unsigned int value;
851 if (value == 0)
853 long int x = pathconf ("/", _PC_PATH_MAX);
854 if (x > 0)
855 value = x;
856 else
857 return MAXPATHLEN;
860 return value;
862 #endif
865 /* This code is stolen from gnulib.
866 If/when we abandon the requirement to work with K&R compilers, we can
867 remove this (and perhaps other parts of GNU make!) and migrate to using
868 gnulib directly.
870 This is called only through atexit(), which means die() has already been
871 invoked. So, call exit() here directly. Apparently that works...?
874 /* Close standard output, exiting with status 'exit_failure' on failure.
875 If a program writes *anything* to stdout, that program should close
876 stdout and make sure that it succeeds before exiting. Otherwise,
877 suppose that you go to the extreme of checking the return status
878 of every function that does an explicit write to stdout. The last
879 printf can succeed in writing to the internal stream buffer, and yet
880 the fclose(stdout) could still fail (due e.g., to a disk full error)
881 when it tries to write out that buffered data. Thus, you would be
882 left with an incomplete output file and the offending program would
883 exit successfully. Even calling fflush is not always sufficient,
884 since some file systems (NFS and CODA) buffer written/flushed data
885 until an actual close call.
887 Besides, it's wasteful to check the return value from every call
888 that writes to stdout -- just let the internal stream state record
889 the failure. That's what the ferror test is checking below.
891 It's important to detect such failures and exit nonzero because many
892 tools (most notably `make' and other build-management systems) depend
893 on being able to detect failure in other tools via their exit status. */
895 void
896 close_stdout (void)
898 int prev_fail = ferror (stdout);
899 int fclose_fail = fclose (stdout);
901 if (prev_fail || fclose_fail)
903 if (fclose_fail)
904 error (NILF, _("write error: %s"), strerror (errno));
905 else
906 error (NILF, _("write error"));
907 exit (EXIT_FAILURE);