* Various changes.
[make.git] / main.c
blob7dde4f642dd06a196f30585cb1b7002a8eb5ecc9
1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988,89,90,91,94,95,96,97,98,99 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 MA 02111-1307, USA. */
20 #include "make.h"
21 #include "dep.h"
22 #include "filedef.h"
23 #include "variable.h"
24 #include "job.h"
25 #include "commands.h"
26 #include "rule.h"
27 #include "getopt.h"
28 #include <assert.h>
29 #ifdef _AMIGA
30 # include <dos/dos.h>
31 # include <proto/dos.h>
32 #endif
33 #ifdef WINDOWS32
34 #include <windows.h>
35 #include "pathstuff.h"
36 #endif
37 #if defined(MAKE_JOBSERVER) && defined(HAVE_FCNTL_H)
38 # include <fcntl.h>
39 #endif
41 #ifdef _AMIGA
42 int __stack = 20000; /* Make sure we have 20K of stack space */
43 #endif
45 extern void init_dir PARAMS ((void));
46 extern void remote_setup PARAMS ((void));
47 extern void remote_cleanup PARAMS ((void));
48 extern RETSIGTYPE fatal_error_signal PARAMS ((int sig));
50 extern void print_variable_data_base PARAMS ((void));
51 extern void print_dir_data_base PARAMS ((void));
52 extern void print_rule_data_base PARAMS ((void));
53 extern void print_file_data_base PARAMS ((void));
54 extern void print_vpath_data_base PARAMS ((void));
56 #if defined HAVE_WAITPID || defined HAVE_WAIT3
57 # define HAVE_WAIT_NOHANG
58 #endif
60 #ifndef HAVE_UNISTD_H
61 extern int chdir ();
62 #endif
63 #ifndef STDC_HEADERS
64 # ifndef sun /* Sun has an incorrect decl in a header. */
65 extern void exit PARAMS ((int)) __attribute__ ((noreturn));
66 # endif
67 extern double atof ();
68 #endif
69 extern char *mktemp ();
71 static void print_data_base PARAMS ((void));
72 static void print_version PARAMS ((void));
73 static void decode_switches PARAMS ((int argc, char **argv, int env));
74 static void decode_env_switches PARAMS ((char *envar, unsigned int len));
75 static void define_makeflags PARAMS ((int all, int makefile));
76 static char *quote_as_word PARAMS ((char *out, char *in, int double_dollars));
78 /* The structure that describes an accepted command switch. */
80 struct command_switch
82 char c; /* The switch character. */
84 enum /* Type of the value. */
86 flag, /* Turn int flag on. */
87 flag_off, /* Turn int flag off. */
88 string, /* One string per switch. */
89 int_string, /* One string. */
90 positive_int, /* A positive integer. */
91 floating, /* A floating-point number (double). */
92 ignore /* Ignored. */
93 } type;
95 char *value_ptr; /* Pointer to the value-holding variable. */
97 unsigned int env:1; /* Can come from MAKEFLAGS. */
98 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
99 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
101 char *noarg_value; /* Pointer to value used if no argument is given. */
102 char *default_value;/* Pointer to default value. */
104 char *long_name; /* Long option name. */
105 char *argdesc; /* Descriptive word for argument. */
106 char *description; /* Description for usage message. */
110 /* The structure used to hold the list of strings given
111 in command switches of a type that takes string arguments. */
113 struct stringlist
115 char **list; /* Nil-terminated list of strings. */
116 unsigned int idx; /* Index into above. */
117 unsigned int max; /* Number of pointers allocated. */
121 /* The recognized command switches. */
123 /* Nonzero means do not print commands to be executed (-s). */
125 int silent_flag;
127 /* Nonzero means just touch the files
128 that would appear to need remaking (-t) */
130 int touch_flag;
132 /* Nonzero means just print what commands would need to be executed,
133 don't actually execute them (-n). */
135 int just_print_flag;
137 /* Print debugging trace info (-d). */
139 int debug_flag = 0;
141 #ifdef WINDOWS32
142 /* Suspend make in main for a short time to allow debugger to attach */
144 int suspend_flag = 0;
145 #endif
147 /* Environment variables override makefile definitions. */
149 int env_overrides = 0;
151 /* Nonzero means ignore status codes returned by commands
152 executed to remake files. Just treat them all as successful (-i). */
154 int ignore_errors_flag = 0;
156 /* Nonzero means don't remake anything, just print the data base
157 that results from reading the makefile (-p). */
159 int print_data_base_flag = 0;
161 /* Nonzero means don't remake anything; just return a nonzero status
162 if the specified targets are not up to date (-q). */
164 int question_flag = 0;
166 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
168 int no_builtin_rules_flag = 0;
169 int no_builtin_variables_flag = 0;
171 /* Nonzero means keep going even if remaking some file fails (-k). */
173 int keep_going_flag;
174 int default_keep_going_flag = 0;
176 /* Nonzero means print directory before starting and when done (-w). */
178 int print_directory_flag = 0;
180 /* Nonzero means ignore print_directory_flag and never print the directory.
181 This is necessary because print_directory_flag is set implicitly. */
183 int inhibit_print_directory_flag = 0;
185 /* Nonzero means print version information. */
187 int print_version_flag = 0;
189 /* List of makefiles given with -f switches. */
191 static struct stringlist *makefiles = 0;
193 /* Number of job slots (commands that can be run at once). */
195 unsigned int job_slots = 1;
196 unsigned int default_job_slots = 1;
198 static char *job_slots_str = "1";
200 #ifndef MAKE_JOBSERVER
201 /* Value of job_slots that means no limit. */
202 static unsigned int inf_jobs = 0;
203 #endif
205 /* File descriptors for the jobs pipe. */
207 int job_fds[2] = { -1, -1 };
208 int job_rfd = -1;
210 /* Maximum load average at which multiple jobs will be run.
211 Negative values mean unlimited, while zero means limit to
212 zero load (which could be useful to start infinite jobs remotely
213 but one at a time locally). */
214 #ifndef NO_FLOAT
215 double max_load_average = -1.0;
216 double default_load_average = -1.0;
217 #else
218 int max_load_average = -1;
219 int default_load_average = -1;
220 #endif
222 /* List of directories given with -C switches. */
224 static struct stringlist *directories = 0;
226 /* List of include directories given with -I switches. */
228 static struct stringlist *include_directories = 0;
230 /* List of files given with -o switches. */
232 static struct stringlist *old_files = 0;
234 /* List of files given with -W switches. */
236 static struct stringlist *new_files = 0;
238 /* If nonzero, we should just print usage and exit. */
240 static int print_usage_flag = 0;
242 /* If nonzero, we should print a warning message
243 for each reference to an undefined variable. */
245 int warn_undefined_variables_flag;
247 /* The table of command switches. */
249 static const struct command_switch switches[] =
251 { 'b', ignore, 0, 0, 0, 0, 0, 0,
252 0, 0,
253 _("Ignored for compatibility") },
254 { 'C', string, (char *) &directories, 0, 0, 0, 0, 0,
255 "directory", _("DIRECTORY"),
256 _("Change to DIRECTORY before doing anything") },
257 { 'd', flag, (char *) &debug_flag, 1, 1, 0, 0, 0,
258 "debug", 0,
259 _("Print lots of debugging information") },
260 #ifdef WINDOWS32
261 { 'D', flag, (char *) &suspend_flag, 1, 1, 0, 0, 0,
262 "suspend-for-debug", 0,
263 _("Suspend process to allow a debugger to attach") },
264 #endif
265 { 'e', flag, (char *) &env_overrides, 1, 1, 0, 0, 0,
266 "environment-overrides", 0,
267 _("Environment variables override makefiles") },
268 { 'f', string, (char *) &makefiles, 0, 0, 0, 0, 0,
269 "file", _("FILE"),
270 _("Read FILE as a makefile") },
271 { 'h', flag, (char *) &print_usage_flag, 0, 0, 0, 0, 0,
272 "help", 0,
273 _("Print this message and exit") },
274 { 'i', flag, (char *) &ignore_errors_flag, 1, 1, 0, 0, 0,
275 "ignore-errors", 0,
276 _("Ignore errors from commands") },
277 { 'I', string, (char *) &include_directories, 1, 1, 0, 0, 0,
278 "include-dir", _("DIRECTORY"),
279 _("Search DIRECTORY for included makefiles") },
280 { 'j',
281 #ifndef MAKE_JOBSERVER
282 positive_int, (char *) &job_slots, 1, 1, 0,
283 (char *) &inf_jobs, (char *) &default_job_slots,
284 #else
285 int_string, (char *)&job_slots_str, 1, 1, 0, "0", "1",
286 #endif
287 "jobs", "N",
288 _("Allow N jobs at once; infinite jobs with no arg") },
289 { 'k', flag, (char *) &keep_going_flag, 1, 1, 0,
290 0, (char *) &default_keep_going_flag,
291 "keep-going", 0,
292 _("Keep going when some targets can't be made") },
293 #ifndef NO_FLOAT
294 { 'l', floating, (char *) &max_load_average, 1, 1, 0,
295 (char *) &default_load_average, (char *) &default_load_average,
296 "load-average", "N",
297 _("Don't start multiple jobs unless load is below N") },
298 #else
299 { 'l', positive_int, (char *) &max_load_average, 1, 1, 0,
300 (char *) &default_load_average, (char *) &default_load_average,
301 "load-average", "N",
302 _("Don't start multiple jobs unless load is below N") },
303 #endif
304 { 'm', ignore, 0, 0, 0, 0, 0, 0,
305 0, 0,
306 "-b" },
307 { 'n', flag, (char *) &just_print_flag, 1, 1, 1, 0, 0,
308 "just-print", 0,
309 _("Don't actually run any commands; just print them") },
310 { 'o', string, (char *) &old_files, 0, 0, 0, 0, 0,
311 "old-file", _("FILE"),
312 _("Consider FILE to be very old and don't remake it") },
313 { 'p', flag, (char *) &print_data_base_flag, 1, 1, 0, 0, 0,
314 "print-data-base", 0,
315 _("Print make's internal database") },
316 { 'q', flag, (char *) &question_flag, 1, 1, 1, 0, 0,
317 "question", 0,
318 _("Run no commands; exit status says if up to date") },
319 { 'r', flag, (char *) &no_builtin_rules_flag, 1, 1, 0, 0, 0,
320 "no-builtin-rules", 0,
321 _("Disable the built-in implicit rules") },
322 { 'R', flag, (char *) &no_builtin_variables_flag, 1, 1, 0, 0, 0,
323 "no-builtin-variables", 0,
324 _("Disable the built-in variable settings") },
325 { 's', flag, (char *) &silent_flag, 1, 1, 0, 0, 0,
326 "silent", 0,
327 _("Don't echo commands") },
328 { 'S', flag_off, (char *) &keep_going_flag, 1, 1, 0,
329 0, (char *) &default_keep_going_flag,
330 "no-keep-going", 0,
331 _("Turns off -k") },
332 { 't', flag, (char *) &touch_flag, 1, 1, 1, 0, 0,
333 "touch", 0,
334 _("Touch targets instead of remaking them") },
335 { 'v', flag, (char *) &print_version_flag, 1, 1, 0, 0, 0,
336 "version", 0,
337 _("Print the version number of make and exit") },
338 { 'w', flag, (char *) &print_directory_flag, 1, 1, 0, 0, 0,
339 "print-directory", 0,
340 _("Print the current directory") },
341 { 2, flag, (char *) &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
342 "no-print-directory", 0,
343 _("Turn off -w, even if it was turned on implicitly") },
344 { 'W', string, (char *) &new_files, 0, 0, 0, 0, 0,
345 "what-if", _("FILE"),
346 _("Consider FILE to be infinitely new") },
347 { 3, flag, (char *) &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
348 "warn-undefined-variables", 0,
349 _("Warn when an undefined variable is referenced") },
350 { '\0', }
353 /* Secondary long names for options. */
355 static struct option long_option_aliases[] =
357 { "quiet", no_argument, 0, 's' },
358 { "stop", no_argument, 0, 'S' },
359 { "new-file", required_argument, 0, 'W' },
360 { "assume-new", required_argument, 0, 'W' },
361 { "assume-old", required_argument, 0, 'o' },
362 { "max-load", optional_argument, 0, 'l' },
363 { "dry-run", no_argument, 0, 'n' },
364 { "recon", no_argument, 0, 'n' },
365 { "makefile", required_argument, 0, 'f' },
368 /* The usage message prints the descriptions of options starting in
369 this column. Make sure it leaves enough room for the longest
370 description to fit in less than 80 characters. */
372 #define DESCRIPTION_COLUMN 30
374 /* List of goal targets. */
376 static struct dep *goals, *lastgoal;
378 /* List of variables which were defined on the command line
379 (or, equivalently, in MAKEFLAGS). */
381 struct command_variable
383 struct command_variable *next;
384 struct variable *variable;
386 static struct command_variable *command_variables;
388 /* The name we were invoked with. */
390 char *program;
392 /* Our current directory before processing any -C options. */
394 char *directory_before_chdir;
396 /* Our current directory after processing all -C options. */
398 char *starting_directory;
400 /* Value of the MAKELEVEL variable at startup (or 0). */
402 unsigned int makelevel;
404 /* First file defined in the makefile whose name does not
405 start with `.'. This is the default to remake if the
406 command line does not specify. */
408 struct file *default_goal_file;
410 /* Pointer to structure for the file .DEFAULT
411 whose commands are used for any file that has none of its own.
412 This is zero if the makefiles do not define .DEFAULT. */
414 struct file *default_file;
416 /* Nonzero if we have seen the magic `.POSIX' target.
417 This turns on pedantic compliance with POSIX.2. */
419 int posix_pedantic;
421 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
422 print one warning about it during the run, and (b) we can print a final
423 warning at the end of the run. */
425 int clock_skew_detected;
427 /* Mask of signals that are being caught with fatal_error_signal. */
429 #ifdef POSIX
430 sigset_t fatal_signal_set;
431 #else
432 #ifdef HAVE_SIGSETMASK
433 int fatal_signal_mask;
434 #endif
435 #endif
437 static struct file *
438 enter_command_line_file (name)
439 char *name;
441 if (name[0] == '\0')
442 fatal (NILF, _("empty string invalid as file name"));
444 if (name[0] == '~')
446 char *expanded = tilde_expand (name);
447 if (expanded != 0)
448 name = expanded; /* Memory leak; I don't care. */
451 /* This is also done in parse_file_seq, so this is redundant
452 for names read from makefiles. It is here for names passed
453 on the command line. */
454 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
456 name += 2;
457 while (*name == '/')
458 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
459 ++name;
462 if (*name == '\0')
464 /* It was all slashes! Move back to the dot and truncate
465 it after the first slash, so it becomes just "./". */
467 --name;
468 while (name[0] != '.');
469 name[2] = '\0';
472 return enter_file (xstrdup (name));
475 /* Toggle -d on receipt of SIGUSR1. */
477 static RETSIGTYPE
478 debug_signal_handler (sig)
479 int sig;
481 debug_flag = ! debug_flag;
484 #ifdef WINDOWS32
486 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
487 * exception and print it to stderr instead.
489 * If debug_flag not set, just print a simple message and exit.
490 * If debug_flag set, print a more verbose message.
491 * If compiled for DEBUG, let exception pass through to GUI so that
492 * debuggers can attach.
494 LONG WINAPI
495 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
497 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
498 LPSTR cmdline = GetCommandLine();
499 LPSTR prg = strtok(cmdline, " ");
500 CHAR errmsg[1024];
501 #ifdef USE_EVENT_LOG
502 HANDLE hEventSource;
503 LPTSTR lpszStrings[1];
504 #endif
506 if (!debug_flag)
508 sprintf(errmsg, _("%s: Interrupt/Exception caught "), prg);
509 sprintf(&errmsg[strlen(errmsg)],
510 "(code = 0x%x, addr = 0x%x)\r\n",
511 exrec->ExceptionCode, exrec->ExceptionAddress);
512 fprintf(stderr, errmsg);
513 exit(255);
516 sprintf(errmsg,
517 _("\r\nUnhandled exception filter called from program %s\r\n"), prg);
518 sprintf(&errmsg[strlen(errmsg)], "ExceptionCode = %x\r\n",
519 exrec->ExceptionCode);
520 sprintf(&errmsg[strlen(errmsg)], "ExceptionFlags = %x\r\n",
521 exrec->ExceptionFlags);
522 sprintf(&errmsg[strlen(errmsg)], "ExceptionAddress = %x\r\n",
523 exrec->ExceptionAddress);
525 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
526 && exrec->NumberParameters >= 2)
527 sprintf(&errmsg[strlen(errmsg)],
528 _("Access violation: %s operation at address %x\r\n"),
529 exrec->ExceptionInformation[0] ? _("write"): _("read"),
530 exrec->ExceptionInformation[1]);
532 /* turn this on if we want to put stuff in the event log too */
533 #ifdef USE_EVENT_LOG
534 hEventSource = RegisterEventSource(NULL, "GNU Make");
535 lpszStrings[0] = errmsg;
537 if (hEventSource != NULL)
539 ReportEvent(hEventSource, /* handle of event source */
540 EVENTLOG_ERROR_TYPE, /* event type */
541 0, /* event category */
542 0, /* event ID */
543 NULL, /* current user's SID */
544 1, /* strings in lpszStrings */
545 0, /* no bytes of raw data */
546 lpszStrings, /* array of error strings */
547 NULL); /* no raw data */
549 (VOID) DeregisterEventSource(hEventSource);
551 #endif
553 /* Write the error to stderr too */
554 fprintf(stderr, errmsg);
556 #ifdef DEBUG
557 return EXCEPTION_CONTINUE_SEARCH;
558 #else
559 exit(255);
560 return (255); /* not reached */
561 #endif
565 * On WIN32 systems we don't have the luxury of a /bin directory that
566 * is mapped globally to every drive mounted to the system. Since make could
567 * be invoked from any drive, and we don't want to propogate /bin/sh
568 * to every single drive. Allow ourselves a chance to search for
569 * a value for default shell here (if the default path does not exist).
573 find_and_set_default_shell(char *token)
575 int sh_found = 0;
576 char* search_token;
577 PATH_VAR(sh_path);
578 extern char *default_shell;
580 if (!token)
581 search_token = default_shell;
582 else
583 search_token = token;
585 if (!no_default_sh_exe &&
586 (token == NULL || !strcmp(search_token, default_shell))) {
587 /* no new information, path already set or known */
588 sh_found = 1;
589 } else if (file_exists_p(search_token)) {
590 /* search token path was found */
591 sprintf(sh_path, "%s", search_token);
592 default_shell = xstrdup(w32ify(sh_path,0));
593 if (debug_flag)
594 printf(_("find_and_set_shell setting default_shell = %s\n"), default_shell);
595 sh_found = 1;
596 } else {
597 char *p;
598 struct variable *v = lookup_variable ("Path", 4);
601 * Search Path for shell
603 if (v && v->value) {
604 char *ep;
606 p = v->value;
607 ep = strchr(p, PATH_SEPARATOR_CHAR);
609 while (ep && *ep) {
610 *ep = '\0';
612 if (dir_file_exists_p(p, search_token)) {
613 sprintf(sh_path, "%s/%s", p, search_token);
614 default_shell = xstrdup(w32ify(sh_path,0));
615 sh_found = 1;
616 *ep = PATH_SEPARATOR_CHAR;
618 /* terminate loop */
619 p += strlen(p);
620 } else {
621 *ep = PATH_SEPARATOR_CHAR;
622 p = ++ep;
625 ep = strchr(p, PATH_SEPARATOR_CHAR);
628 /* be sure to check last element of Path */
629 if (p && *p && dir_file_exists_p(p, search_token)) {
630 sprintf(sh_path, "%s/%s", p, search_token);
631 default_shell = xstrdup(w32ify(sh_path,0));
632 sh_found = 1;
635 if (debug_flag && sh_found)
636 printf(_("find_and_set_shell path search set default_shell = %s\n"), default_shell);
640 /* naive test */
641 if (!unixy_shell && sh_found &&
642 (strstr(default_shell, "sh") || strstr(default_shell, "SH"))) {
643 unixy_shell = 1;
644 batch_mode_shell = 0;
647 #ifdef BATCH_MODE_ONLY_SHELL
648 batch_mode_shell = 1;
649 #endif
651 return (sh_found);
653 #endif /* WINDOWS32 */
655 #ifdef __MSDOS__
657 static void
658 msdos_return_to_initial_directory ()
660 if (directory_before_chdir)
661 chdir (directory_before_chdir);
663 #endif
665 #ifndef _AMIGA
667 main (argc, argv, envp)
668 int argc;
669 char **argv;
670 char **envp;
671 #else
672 int main (int argc, char ** argv)
673 #endif
675 static char *stdin_nm = 0;
676 register struct file *f;
677 register unsigned int i;
678 char **p;
679 struct dep *read_makefiles;
680 PATH_VAR (current_directory);
681 #ifdef WINDOWS32
682 char *unix_path = NULL;
683 char *windows32_path = NULL;
685 SetUnhandledExceptionFilter(handle_runtime_exceptions);
687 /* start off assuming we have no shell */
688 unixy_shell = 0;
689 no_default_sh_exe = 1;
690 #endif
692 default_goal_file = 0;
693 reading_file = 0;
695 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
696 /* Request the most powerful version of `system', to
697 make up for the dumb default shell. */
698 __system_flags = (__system_redirect
699 | __system_use_shell
700 | __system_allow_multiple_cmds
701 | __system_allow_long_cmds
702 | __system_handle_null_commands
703 | __system_emulate_chdir);
705 #endif
707 #if !defined (HAVE_STRSIGNAL) && !defined (HAVE_SYS_SIGLIST)
708 signame_init ();
709 #endif
711 #ifdef POSIX
712 sigemptyset (&fatal_signal_set);
713 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
714 #else
715 #ifdef HAVE_SIGSETMASK
716 fatal_signal_mask = 0;
717 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
718 #else
719 #define ADD_SIG(sig)
720 #endif
721 #endif
723 #define FATAL_SIG(sig) \
724 if (signal ((sig), fatal_error_signal) == SIG_IGN) \
725 (void) signal ((sig), SIG_IGN); \
726 else \
727 ADD_SIG (sig);
729 #ifdef SIGHUP
730 FATAL_SIG (SIGHUP);
731 #endif
732 #ifdef SIGQUIT
733 FATAL_SIG (SIGQUIT);
734 #endif
735 FATAL_SIG (SIGINT);
736 FATAL_SIG (SIGTERM);
738 #ifdef SIGDANGER
739 FATAL_SIG (SIGDANGER);
740 #endif
741 #ifdef SIGXCPU
742 FATAL_SIG (SIGXCPU);
743 #endif
744 #ifdef SIGXFSZ
745 FATAL_SIG (SIGXFSZ);
746 #endif
748 #undef FATAL_SIG
750 /* Do not ignore the child-death signal. This must be done before
751 any children could possibly be created; otherwise, the wait
752 functions won't work on systems with the SVR4 ECHILD brain
753 damage, if our invoker is ignoring this signal. */
755 #ifdef HAVE_WAIT_NOHANG
756 # if defined SIGCHLD
757 (void) signal (SIGCHLD, SIG_DFL);
758 # endif
759 # if defined SIGCLD && SIGCLD != SIGCHLD
760 (void) signal (SIGCLD, SIG_DFL);
761 # endif
762 #endif
764 /* Make sure stdout is line-buffered. */
766 #ifdef HAVE_SETLINEBUF
767 setlinebuf (stdout);
768 #else
769 #ifndef SETVBUF_REVERSED
770 setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
771 #else /* setvbuf not reversed. */
772 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
773 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
774 #endif /* setvbuf reversed. */
775 #endif /* setlinebuf missing. */
777 /* Figure out where this program lives. */
779 if (argv[0] == 0)
780 argv[0] = "";
781 if (argv[0][0] == '\0')
782 program = "make";
783 else
785 #ifdef VMS
786 program = rindex (argv[0], ']');
787 #else
788 program = rindex (argv[0], '/');
789 #endif
790 #ifdef __MSDOS__
791 if (program == 0)
792 program = rindex (argv[0], '\\');
793 else
795 /* Some weird environments might pass us argv[0] with
796 both kinds of slashes; we must find the rightmost. */
797 char *p = rindex (argv[0], '\\');
798 if (p && p > program)
799 program = p;
801 if (program == 0 && argv[0][1] == ':')
802 program = argv[0] + 1;
803 #endif
804 if (program == 0)
805 program = argv[0];
806 else
807 ++program;
810 /* Set up to access user data (files). */
811 user_access ();
813 /* Figure out where we are. */
815 #ifdef WINDOWS32
816 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
817 #else
818 if (getcwd (current_directory, GET_PATH_MAX) == 0)
819 #endif
821 #ifdef HAVE_GETCWD
822 perror_with_name ("getcwd: ", "");
823 #else
824 error (NILF, "getwd: %s", current_directory);
825 #endif
826 current_directory[0] = '\0';
827 directory_before_chdir = 0;
829 else
830 directory_before_chdir = xstrdup (current_directory);
831 #ifdef __MSDOS__
832 /* Make sure we will return to the initial directory, come what may. */
833 atexit (msdos_return_to_initial_directory);
834 #endif
836 /* Read in variables from the environment. It is important that this be
837 done before $(MAKE) is figured out so its definitions will not be
838 from the environment. */
840 #ifndef _AMIGA
841 for (i = 0; envp[i] != 0; ++i)
843 int do_not_define;
844 register char *ep = envp[i];
846 /* by default, everything gets defined and exported */
847 do_not_define = 0;
849 while (*ep != '=')
850 ++ep;
851 #ifdef WINDOWS32
852 if (!unix_path && strneq(envp[i], "PATH=", 5))
853 unix_path = ep+1;
854 else if (!windows32_path && !strnicmp(envp[i], "Path=", 5)) {
855 do_not_define = 1; /* it gets defined after loop exits */
856 windows32_path = ep+1;
858 #endif
859 /* The result of pointer arithmetic is cast to unsigned int for
860 machines where ptrdiff_t is a different size that doesn't widen
861 the same. */
862 if (!do_not_define)
863 define_variable (envp[i], (unsigned int) (ep - envp[i]),
864 ep + 1, o_env, 1)
865 /* Force exportation of every variable culled from the environment.
866 We used to rely on target_environment's v_default code to do this.
867 But that does not work for the case where an environment variable
868 is redefined in a makefile with `override'; it should then still
869 be exported, because it was originally in the environment. */
870 ->export = v_export;
872 #ifdef WINDOWS32
874 * Make sure that this particular spelling of 'Path' is available
876 if (windows32_path)
877 define_variable("Path", 4, windows32_path, o_env, 1)->export = v_export;
878 else if (unix_path)
879 define_variable("Path", 4, unix_path, o_env, 1)->export = v_export;
880 else
881 define_variable("Path", 4, "", o_env, 1)->export = v_export;
884 * PATH defaults to Path iff PATH not found and Path is found.
886 if (!unix_path && windows32_path)
887 define_variable("PATH", 4, windows32_path, o_env, 1)->export = v_export;
888 #endif
889 #else /* For Amiga, read the ENV: device, ignoring all dirs */
891 BPTR env, file, old;
892 char buffer[1024];
893 int len;
894 __aligned struct FileInfoBlock fib;
896 env = Lock ("ENV:", ACCESS_READ);
897 if (env)
899 old = CurrentDir (DupLock(env));
900 Examine (env, &fib);
902 while (ExNext (env, &fib))
904 if (fib.fib_DirEntryType < 0) /* File */
906 /* Define an empty variable. It will be filled in
907 variable_lookup(). Makes startup quite a bit
908 faster. */
909 define_variable (fib.fib_FileName,
910 strlen (fib.fib_FileName),
911 "", o_env, 1)->export = v_export;
914 UnLock (env);
915 UnLock(CurrentDir(old));
918 #endif
920 /* Decode the switches. */
922 decode_env_switches ("MAKEFLAGS", 9);
923 #if 0
924 /* People write things like:
925 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
926 and we set the -p, -i and -e switches. Doesn't seem quite right. */
927 decode_env_switches ("MFLAGS", 6);
928 #endif
929 decode_switches (argc, argv, 0);
930 #ifdef WINDOWS32
931 if (suspend_flag) {
932 fprintf(stderr, "%s (pid = %d)\n", argv[0], GetCurrentProcessId());
933 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
934 Sleep(30 * 1000);
935 fprintf(stderr, _("done sleep(30). Continuing.\n"));
937 #endif
939 /* Print version information. */
941 if (print_version_flag || print_data_base_flag || debug_flag)
942 print_version ();
944 /* `make --version' is supposed to just print the version and exit. */
945 if (print_version_flag)
946 die (0);
948 #ifndef VMS
949 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
950 (If it is a relative pathname with a slash, prepend our directory name
951 so the result will run the same program regardless of the current dir.
952 If it is a name with no slash, we can only hope that PATH did not
953 find it in the current directory.) */
954 #ifdef WINDOWS32
956 * Convert from backslashes to forward slashes for
957 * programs like sh which don't like them. Shouldn't
958 * matter if the path is one way or the other for
959 * CreateProcess().
961 if (strpbrk(argv[0], "/:\\") ||
962 strstr(argv[0], "..") ||
963 strneq(argv[0], "//", 2))
964 argv[0] = xstrdup(w32ify(argv[0],1));
965 #else /* WINDOWS32 */
966 #ifdef __MSDOS__
967 if (strchr (argv[0], '\\'))
969 char *p;
971 argv[0] = xstrdup (argv[0]);
972 for (p = argv[0]; *p; p++)
973 if (*p == '\\')
974 *p = '/';
976 #else /* !__MSDOS__ */
977 if (current_directory[0] != '\0'
978 && argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
979 argv[0] = concat (current_directory, "/", argv[0]);
980 #endif /* !__MSDOS__ */
981 #endif /* WINDOWS32 */
982 #endif
984 /* The extra indirection through $(MAKE_COMMAND) is done
985 for hysterical raisins. */
986 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
987 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
989 if (command_variables != 0)
991 struct command_variable *cv;
992 struct variable *v;
993 unsigned int len = 0;
994 char *value, *p;
996 /* Figure out how much space will be taken up by the command-line
997 variable definitions. */
998 for (cv = command_variables; cv != 0; cv = cv->next)
1000 v = cv->variable;
1001 len += 2 * strlen (v->name);
1002 if (! v->recursive)
1003 ++len;
1004 ++len;
1005 len += 3 * strlen (v->value);
1008 /* Now allocate a buffer big enough and fill it. */
1009 p = value = (char *) alloca (len);
1010 for (cv = command_variables; cv != 0; cv = cv->next)
1012 v = cv->variable;
1013 p = quote_as_word (p, v->name, 0);
1014 if (! v->recursive)
1015 *p++ = ':';
1016 *p++ = '=';
1017 p = quote_as_word (p, v->value, 0);
1018 *p++ = ' ';
1020 p[-1] = '\0'; /* Kill the final space and terminate. */
1022 /* Define an unchangeable variable with a name that no POSIX.2
1023 makefile could validly use for its own variable. */
1024 (void) define_variable ("-*-command-variables-*-", 23,
1025 value, o_automatic, 0);
1027 /* Define the variable; this will not override any user definition.
1028 Normally a reference to this variable is written into the value of
1029 MAKEFLAGS, allowing the user to override this value to affect the
1030 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1031 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1032 a reference to this hidden variable is written instead. */
1033 (void) define_variable ("MAKEOVERRIDES", 13,
1034 "${-*-command-variables-*-}", o_env, 1);
1037 /* If there were -C flags, move ourselves about. */
1038 if (directories != 0)
1039 for (i = 0; directories->list[i] != 0; ++i)
1041 char *dir = directories->list[i];
1042 if (dir[0] == '~')
1044 char *expanded = tilde_expand (dir);
1045 if (expanded != 0)
1046 dir = expanded;
1048 if (chdir (dir) < 0)
1049 pfatal_with_name (dir);
1050 if (dir != directories->list[i])
1051 free (dir);
1054 #ifdef WINDOWS32
1056 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1057 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1059 * The functions in dir.c can incorrectly cache information for "."
1060 * before we have changed directory and this can cause file
1061 * lookups to fail because the current directory (.) was pointing
1062 * at the wrong place when it was first evaluated.
1064 no_default_sh_exe = !find_and_set_default_shell(NULL);
1066 #endif /* WINDOWS32 */
1067 /* Figure out the level of recursion. */
1069 struct variable *v = lookup_variable ("MAKELEVEL", 9);
1070 if (v != 0 && *v->value != '\0' && *v->value != '-')
1071 makelevel = (unsigned int) atoi (v->value);
1072 else
1073 makelevel = 0;
1076 /* Except under -s, always do -w in sub-makes and under -C. */
1077 if (!silent_flag && (directories != 0 || makelevel > 0))
1078 print_directory_flag = 1;
1080 /* Let the user disable that with --no-print-directory. */
1081 if (inhibit_print_directory_flag)
1082 print_directory_flag = 0;
1084 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1085 if (no_builtin_variables_flag)
1086 no_builtin_rules_flag = 1;
1088 /* Construct the list of include directories to search. */
1090 construct_include_path (include_directories == 0 ? (char **) 0
1091 : include_directories->list);
1093 /* Figure out where we are now, after chdir'ing. */
1094 if (directories == 0)
1095 /* We didn't move, so we're still in the same place. */
1096 starting_directory = current_directory;
1097 else
1099 #ifdef WINDOWS32
1100 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1101 #else
1102 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1103 #endif
1105 #ifdef HAVE_GETCWD
1106 perror_with_name ("getcwd: ", "");
1107 #else
1108 error (NILF, "getwd: %s", current_directory);
1109 #endif
1110 starting_directory = 0;
1112 else
1113 starting_directory = current_directory;
1116 (void) define_variable ("CURDIR", 6, current_directory, o_default, 0);
1118 /* Read any stdin makefiles into temporary files. */
1120 if (makefiles != 0)
1122 register unsigned int i;
1123 for (i = 0; i < makefiles->idx; ++i)
1124 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1126 /* This makefile is standard input. Since we may re-exec
1127 and thus re-read the makefiles, we read standard input
1128 into a temporary file and read from that. */
1129 FILE *outfile;
1131 /* Make a unique filename. */
1132 #ifdef HAVE_MKTEMP
1134 #ifdef VMS
1135 static char name[] = "sys$scratch:GmXXXXXX";
1136 #else
1137 static char name[] = "/tmp/GmXXXXXX";
1138 #endif
1139 (void) mktemp (name);
1140 #else
1141 static char name[L_tmpnam];
1142 (void) tmpnam (name);
1143 #endif
1145 if (stdin_nm)
1146 fatal (NILF, _("Makefile from standard input specified twice."));
1148 outfile = fopen (name, "w");
1149 if (outfile == 0)
1150 pfatal_with_name (_("fopen (temporary file)"));
1151 while (!feof (stdin))
1153 char buf[2048];
1154 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1155 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1156 pfatal_with_name (_("fwrite (temporary file)"));
1158 (void) fclose (outfile);
1160 /* Replace the name that read_all_makefiles will
1161 see with the name of the temporary file. */
1163 char *temp;
1164 /* SGI compiler requires alloca's result be assigned simply. */
1165 temp = (char *) alloca (sizeof (name));
1166 bcopy (name, temp, sizeof (name));
1167 makefiles->list[i] = temp;
1170 /* Make sure the temporary file will not be remade. */
1171 stdin_nm = savestring (name, sizeof (name) -1);
1172 f = enter_file (stdin_nm);
1173 f->updated = 1;
1174 f->update_status = 0;
1175 f->command_state = cs_finished;
1176 /* Can't be intermediate, or it'll be removed too early for
1177 make re-exec. */
1178 f->intermediate = 0;
1179 f->dontcare = 0;
1183 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1184 /* Set up to handle children dying. This must be done before
1185 reading in the makefiles so that `shell' function calls will work.
1187 If we don't have a hanging wait we have to fall back to old, broken
1188 functionality here and rely on the signal handler and counting
1189 children.
1191 If we're using the jobs pipe we need a signal handler so that
1192 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1193 jobserver pipe in job.c if we're waiting for a token.
1195 If none of these are true, we don't need a signal handler at all. */
1197 extern RETSIGTYPE child_handler PARAMS ((int sig));
1199 # if defined HAVE_SIGACTION
1200 struct sigaction sa;
1202 bzero ((char *)&sa, sizeof (struct sigaction));
1203 sa.sa_handler = child_handler;
1204 # if defined SA_INTERRUPT
1205 /* This is supposed to be the default, but what the heck... */
1206 sa.sa_flags = SA_INTERRUPT;
1207 # endif
1208 # define HANDLESIG(s) sigaction (s, &sa, NULL)
1209 # else
1210 # define HANDLESIG(s) signal (s, child_handler)
1211 # endif
1213 /* OK, now actually install the handlers. */
1214 # if defined SIGCHLD
1215 (void) HANDLESIG (SIGCHLD);
1216 # endif
1217 # if defined SIGCLD && SIGCLD != SIGCHLD
1218 (void) HANDLESIG (SIGCLD);
1219 # endif
1221 #endif
1223 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1224 #ifdef SIGUSR1
1225 (void) signal (SIGUSR1, debug_signal_handler);
1226 #endif
1228 /* Define the initial list of suffixes for old-style rules. */
1230 set_default_suffixes ();
1232 /* Define the file rules for the built-in suffix rules. These will later
1233 be converted into pattern rules. We used to do this in
1234 install_default_implicit_rules, but since that happens after reading
1235 makefiles, it results in the built-in pattern rules taking precedence
1236 over makefile-specified suffix rules, which is wrong. */
1238 install_default_suffix_rules ();
1240 /* Define some internal and special variables. */
1242 define_automatic_variables ();
1244 /* Set up the MAKEFLAGS and MFLAGS variables
1245 so makefiles can look at them. */
1247 define_makeflags (0, 0);
1249 /* Define the default variables. */
1250 define_default_variables ();
1252 /* Read all the makefiles. */
1254 default_file = enter_file (".DEFAULT");
1256 read_makefiles
1257 = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
1259 #ifdef WINDOWS32
1260 /* look one last time after reading all Makefiles */
1261 if (no_default_sh_exe)
1262 no_default_sh_exe = !find_and_set_default_shell(NULL);
1264 if (no_default_sh_exe && job_slots != 1) {
1265 error (NILF, _("Do not specify -j or --jobs if sh.exe is not available."));
1266 error (NILF, _("Resetting make for single job mode."));
1267 job_slots = 1;
1269 #endif /* WINDOWS32 */
1271 #ifdef __MSDOS__
1272 /* We need to know what kind of shell we will be using. */
1274 extern int _is_unixy_shell (const char *_path);
1275 struct variable *shv = lookup_variable("SHELL", 5);
1276 extern int unixy_shell;
1277 extern char *default_shell;
1279 if (shv && *shv->value)
1281 char *shell_path = recursively_expand(shv);
1283 if (shell_path && _is_unixy_shell (shell_path))
1284 unixy_shell = 1;
1285 else
1286 unixy_shell = 0;
1287 if (shell_path)
1288 default_shell = shell_path;
1291 #endif /* __MSDOS__ */
1293 /* Decode switches again, in case the variables were set by the makefile. */
1294 decode_env_switches ("MAKEFLAGS", 9);
1295 #if 0
1296 decode_env_switches ("MFLAGS", 6);
1297 #endif
1299 #ifdef MAKE_JOBSERVER
1300 /* If extended jobs are available then the -j option can have one of 4
1301 formats: (1) not specified: default is "1"; (2) specified with no value:
1302 default is "0" (infinite); (3) specified with a single value: this means
1303 the user wants N job slots; or (4) specified with 2 values separated by
1304 a comma. The latter means we're a submake; the two values are the read
1305 and write FDs, respectively, for the pipe. Note this last form is
1306 undocumented for the user! */
1308 sscanf (job_slots_str, "%d", &job_slots);
1310 char *cp = index (job_slots_str, ',');
1312 /* In case #4, get the FDs. */
1313 if (cp && sscanf (cp+1, "%d", &job_fds[1]) == 1)
1315 /* Set up the first FD and set job_slots to 0. The combination of a
1316 pipe + !job_slots means we're using the jobserver. If !job_slots
1317 and we don't have a pipe, we can start infinite jobs. */
1318 job_fds[0] = job_slots;
1319 job_slots = 0;
1321 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1322 handler. If this fails with EBADF, the parent has closed the pipe
1323 on us because it didn't think we were a submake. If so, print a
1324 warning then default to -j1. */
1325 if ((job_rfd = dup (job_fds[0])) < 0)
1327 if (errno != EBADF)
1328 pfatal_with_name (_("dup jobserver"));
1330 error (NILF,
1331 _("warning: jobserver unavailable (using -j1). Add `+' to parent make rule."));
1332 job_slots = 1;
1333 job_fds[0] = job_fds[1] = -1;
1334 job_slots_str = "1";
1339 /* In case #3 above, set up the pipe and set up the submake options
1340 properly. */
1342 if (job_slots > 1)
1344 char buf[(sizeof ("1024")*2)+1];
1345 char c = '0';
1347 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
1348 pfatal_with_name (_("creating jobs pipe"));
1350 /* Every make assumes that it always has one job it can run. For the
1351 submakes it's the token they were given by their parent. For the
1352 top make, we just subtract one from the number the user wants. */
1354 job_slots = 1; /* !!!!!DEBUG!!!!! */
1356 while (--job_slots)
1358 write (job_fds[1], &c, 1);
1359 if (c == '9')
1360 c = 'a';
1361 else if (c == 'z')
1362 c = 'A';
1363 else if (c == 'Z')
1364 c = '0'; /* Start over again!! */
1365 else
1366 ++c;
1369 sprintf (buf, "%d,%d", job_fds[0], job_fds[1]);
1370 job_slots_str = xstrdup (buf);
1372 #endif
1374 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1376 define_makeflags (1, 0);
1378 /* Make each `struct dep' point at the `struct file' for the file
1379 depended on. Also do magic for special targets. */
1381 snap_deps ();
1383 /* Convert old-style suffix rules to pattern rules. It is important to
1384 do this before installing the built-in pattern rules below, so that
1385 makefile-specified suffix rules take precedence over built-in pattern
1386 rules. */
1388 convert_to_pattern ();
1390 /* Install the default implicit pattern rules.
1391 This used to be done before reading the makefiles.
1392 But in that case, built-in pattern rules were in the chain
1393 before user-defined ones, so they matched first. */
1395 install_default_implicit_rules ();
1397 /* Compute implicit rule limits. */
1399 count_implicit_rule_limits ();
1401 /* Construct the listings of directories in VPATH lists. */
1403 build_vpath_lists ();
1405 /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
1406 and as having been updated already, and files given with -W flags as
1407 brand new (time-stamp as far as possible into the future). */
1409 if (old_files != 0)
1410 for (p = old_files->list; *p != 0; ++p)
1412 f = enter_command_line_file (*p);
1413 f->last_mtime = f->mtime_before_update = (FILE_TIMESTAMP) 1;
1414 f->updated = 1;
1415 f->update_status = 0;
1416 f->command_state = cs_finished;
1419 if (new_files != 0)
1421 for (p = new_files->list; *p != 0; ++p)
1423 f = enter_command_line_file (*p);
1424 f->last_mtime = f->mtime_before_update = NEW_MTIME;
1428 /* Initialize the remote job module. */
1429 remote_setup ();
1431 if (read_makefiles != 0)
1433 /* Update any makefiles if necessary. */
1435 FILE_TIMESTAMP *makefile_mtimes = 0;
1436 unsigned int mm_idx = 0;
1437 char **nargv = argv;
1438 int nargc = argc;
1440 if (debug_flag)
1441 puts (_("Updating makefiles...."));
1443 /* Remove any makefiles we don't want to try to update.
1444 Also record the current modtimes so we can compare them later. */
1446 register struct dep *d, *last;
1447 last = 0;
1448 d = read_makefiles;
1449 while (d != 0)
1451 register struct file *f = d->file;
1452 if (f->double_colon)
1453 for (f = f->double_colon; f != NULL; f = f->prev)
1455 if (f->deps == 0 && f->cmds != 0)
1457 /* This makefile is a :: target with commands, but
1458 no dependencies. So, it will always be remade.
1459 This might well cause an infinite loop, so don't
1460 try to remake it. (This will only happen if
1461 your makefiles are written exceptionally
1462 stupidly; but if you work for Athena, that's how
1463 you write your makefiles.) */
1465 if (debug_flag)
1466 printf (_("Makefile `%s' might loop; not remaking it.\n"),
1467 f->name);
1469 if (last == 0)
1470 read_makefiles = d->next;
1471 else
1472 last->next = d->next;
1474 /* Free the storage. */
1475 free ((char *) d);
1477 d = last == 0 ? read_makefiles : last->next;
1479 break;
1482 if (f == NULL || !f->double_colon)
1484 makefile_mtimes = (FILE_TIMESTAMP *)
1485 xrealloc ((char *) makefile_mtimes,
1486 (mm_idx + 1) * sizeof (FILE_TIMESTAMP));
1487 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
1488 last = d;
1489 d = d->next;
1494 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
1495 define_makeflags (1, 1);
1497 switch (update_goal_chain (read_makefiles, 1))
1499 case 1:
1500 default:
1501 #define BOGUS_UPDATE_STATUS 0
1502 assert (BOGUS_UPDATE_STATUS);
1503 break;
1505 case -1:
1506 /* Did nothing. */
1507 break;
1509 case 2:
1510 /* Failed to update. Figure out if we care. */
1512 /* Nonzero if any makefile was successfully remade. */
1513 int any_remade = 0;
1514 /* Nonzero if any makefile we care about failed
1515 in updating or could not be found at all. */
1516 int any_failed = 0;
1517 register unsigned int i;
1518 struct dep *d;
1520 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
1522 /* Reset the considered flag; we may need to look at the file
1523 again to print an error. */
1524 d->file->considered = 0;
1526 if (d->file->updated)
1528 /* This makefile was updated. */
1529 if (d->file->update_status == 0)
1531 /* It was successfully updated. */
1532 any_remade |= (file_mtime_no_search (d->file)
1533 != makefile_mtimes[i]);
1535 else if (! (d->changed & RM_DONTCARE))
1537 FILE_TIMESTAMP mtime;
1538 /* The update failed and this makefile was not
1539 from the MAKEFILES variable, so we care. */
1540 error (NILF, _("Failed to remake makefile `%s'."),
1541 d->file->name);
1542 mtime = file_mtime_no_search (d->file);
1543 any_remade |= (mtime != (FILE_TIMESTAMP) -1
1544 && mtime != makefile_mtimes[i]);
1547 else
1548 /* This makefile was not found at all. */
1549 if (! (d->changed & RM_DONTCARE))
1551 /* This is a makefile we care about. See how much. */
1552 if (d->changed & RM_INCLUDED)
1553 /* An included makefile. We don't need
1554 to die, but we do want to complain. */
1555 error (NILF,
1556 _("Included makefile `%s' was not found."),
1557 dep_name (d));
1558 else
1560 /* A normal makefile. We must die later. */
1561 error (NILF, _("Makefile `%s' was not found"),
1562 dep_name (d));
1563 any_failed = 1;
1567 /* Reset this to empty so we get the right error message below. */
1568 read_makefiles = 0;
1570 if (any_remade)
1571 goto re_exec;
1572 if (any_failed)
1573 die (2);
1574 break;
1577 case 0:
1578 re_exec:
1579 /* Updated successfully. Re-exec ourselves. */
1581 remove_intermediates (0);
1583 if (print_data_base_flag)
1584 print_data_base ();
1586 log_working_directory (0);
1588 if (makefiles != 0)
1590 /* These names might have changed. */
1591 register unsigned int i, j = 0;
1592 for (i = 1; i < argc; ++i)
1593 if (strneq (argv[i], "-f", 2)) /* XXX */
1595 char *p = &argv[i][2];
1596 if (*p == '\0')
1597 argv[++i] = makefiles->list[j];
1598 else
1599 argv[i] = concat ("-f", makefiles->list[j], "");
1600 ++j;
1604 /* Add -o option for the stdin temporary file, if necessary. */
1605 if (stdin_nm)
1607 nargv = (char **) xmalloc ((nargc + 2) * sizeof (char *));
1608 bcopy ((char *) argv, (char *) nargv, argc * sizeof (char *));
1609 nargv[nargc++] = concat ("-o", stdin_nm, "");
1610 nargv[nargc] = 0;
1613 if (directories != 0 && directories->idx > 0)
1615 char bad;
1616 if (directory_before_chdir != 0)
1618 if (chdir (directory_before_chdir) < 0)
1620 perror_with_name ("chdir", "");
1621 bad = 1;
1623 else
1624 bad = 0;
1626 else
1627 bad = 1;
1628 if (bad)
1629 fatal (NILF, _("Couldn't change back to original directory."));
1632 #ifndef _AMIGA
1633 for (p = environ; *p != 0; ++p)
1634 if (strneq (*p, "MAKELEVEL=", 10))
1636 /* The SGI compiler apparently can't understand
1637 the concept of storing the result of a function
1638 in something other than a local variable. */
1639 char *sgi_loses;
1640 sgi_loses = (char *) alloca (40);
1641 *p = sgi_loses;
1642 sprintf (*p, "MAKELEVEL=%u", makelevel);
1643 break;
1645 #else /* AMIGA */
1647 char buffer[256];
1648 int len;
1650 len = GetVar ("MAKELEVEL", buffer, sizeof (buffer), GVF_GLOBAL_ONLY);
1652 if (len != -1)
1654 sprintf (buffer, "%u", makelevel);
1655 SetVar ("MAKELEVEL", buffer, -1, GVF_GLOBAL_ONLY);
1658 #endif
1660 if (debug_flag)
1662 char **p;
1663 fputs (_("Re-executing:"), stdout);
1664 for (p = nargv; *p != 0; ++p)
1665 printf (" %s", *p);
1666 puts ("");
1669 fflush (stdout);
1670 fflush (stderr);
1672 #ifndef _AMIGA
1673 exec_command (nargv, environ);
1674 #else
1675 exec_command (nargv);
1676 exit (0);
1677 #endif
1678 /* NOTREACHED */
1682 /* Set up `MAKEFLAGS' again for the normal targets. */
1683 define_makeflags (1, 0);
1685 /* If there is a temp file from reading a makefile from stdin, get rid of
1686 it now. */
1687 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
1688 perror_with_name (_("unlink (temporary file): "), stdin_nm);
1691 int status;
1693 /* If there were no command-line goals, use the default. */
1694 if (goals == 0)
1696 if (default_goal_file != 0)
1698 goals = (struct dep *) xmalloc (sizeof (struct dep));
1699 goals->next = 0;
1700 goals->name = 0;
1701 goals->file = default_goal_file;
1704 else
1705 lastgoal->next = 0;
1707 if (!goals)
1709 if (read_makefiles == 0)
1710 fatal (NILF, _("No targets specified and no makefile found"));
1712 fatal (NILF, _("No targets"));
1715 /* Update the goals. */
1717 if (debug_flag)
1718 puts (_("Updating goal targets...."));
1720 switch (update_goal_chain (goals, 0))
1722 case -1:
1723 /* Nothing happened. */
1724 case 0:
1725 /* Updated successfully. */
1726 status = EXIT_SUCCESS;
1727 break;
1728 case 2:
1729 /* Updating failed. POSIX.2 specifies exit status >1 for this;
1730 but in VMS, there is only success and failure. */
1731 status = EXIT_FAILURE ? 2 : EXIT_FAILURE;
1732 break;
1733 case 1:
1734 /* We are under -q and would run some commands. */
1735 status = EXIT_FAILURE;
1736 break;
1737 default:
1738 abort ();
1741 /* If we detected some clock skew, generate one last warning */
1742 if (clock_skew_detected)
1743 error (NILF, _("*** Warning: Clock skew detected. Your build may be incomplete."));
1745 /* Exit. */
1746 die (status);
1749 return 0;
1752 /* Parsing of arguments, decoding of switches. */
1754 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
1755 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
1756 (sizeof (long_option_aliases) /
1757 sizeof (long_option_aliases[0]))];
1759 /* Fill in the string and vector for getopt. */
1760 static void
1761 init_switches ()
1763 register char *p;
1764 register int c;
1765 register unsigned int i;
1767 if (options[0] != '\0')
1768 /* Already done. */
1769 return;
1771 p = options;
1773 /* Return switch and non-switch args in order, regardless of
1774 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
1775 *p++ = '-';
1777 for (i = 0; switches[i].c != '\0'; ++i)
1779 long_options[i].name = (switches[i].long_name == 0 ? "" :
1780 switches[i].long_name);
1781 long_options[i].flag = 0;
1782 long_options[i].val = switches[i].c;
1783 if (isalnum (switches[i].c))
1784 *p++ = switches[i].c;
1785 switch (switches[i].type)
1787 case flag:
1788 case flag_off:
1789 case ignore:
1790 long_options[i].has_arg = no_argument;
1791 break;
1793 case int_string:
1794 case string:
1795 case positive_int:
1796 case floating:
1797 if (isalnum (switches[i].c))
1798 *p++ = ':';
1799 if (switches[i].noarg_value != 0)
1801 if (isalnum (switches[i].c))
1802 *p++ = ':';
1803 long_options[i].has_arg = optional_argument;
1805 else
1806 long_options[i].has_arg = required_argument;
1807 break;
1810 *p = '\0';
1811 for (c = 0; c < (sizeof (long_option_aliases) /
1812 sizeof (long_option_aliases[0]));
1813 ++c)
1814 long_options[i++] = long_option_aliases[c];
1815 long_options[i].name = 0;
1818 static void
1819 handle_non_switch_argument (arg, env)
1820 char *arg;
1821 int env;
1823 /* Non-option argument. It might be a variable definition. */
1824 struct variable *v;
1825 if (arg[0] == '-' && arg[1] == '\0')
1826 /* Ignore plain `-' for compatibility. */
1827 return;
1828 v = try_variable_definition (0, arg, o_command);
1829 if (v != 0)
1831 /* It is indeed a variable definition. Record a pointer to
1832 the variable for later use in define_makeflags. */
1833 struct command_variable *cv
1834 = (struct command_variable *) xmalloc (sizeof (*cv));
1835 cv->variable = v;
1836 cv->next = command_variables;
1837 command_variables = cv;
1839 else if (! env)
1841 /* Not an option or variable definition; it must be a goal
1842 target! Enter it as a file and add it to the dep chain of
1843 goals. */
1844 struct file *f = enter_command_line_file (arg);
1845 f->cmd_target = 1;
1847 if (goals == 0)
1849 goals = (struct dep *) xmalloc (sizeof (struct dep));
1850 lastgoal = goals;
1852 else
1854 lastgoal->next
1855 = (struct dep *) xmalloc (sizeof (struct dep));
1856 lastgoal = lastgoal->next;
1858 lastgoal->name = 0;
1859 lastgoal->file = f;
1862 /* Add this target name to the MAKECMDGOALS variable. */
1863 struct variable *v;
1864 char *value;
1866 v = lookup_variable ("MAKECMDGOALS", 12);
1867 if (v == 0)
1868 value = f->name;
1869 else
1871 /* Paste the old and new values together */
1872 unsigned int oldlen, newlen;
1874 oldlen = strlen (v->value);
1875 newlen = strlen (f->name);
1876 value = (char *) alloca (oldlen + 1 + newlen + 1);
1877 bcopy (v->value, value, oldlen);
1878 value[oldlen] = ' ';
1879 bcopy (f->name, &value[oldlen + 1], newlen + 1);
1881 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
1886 /* Print a nice usage method. */
1888 static void
1889 print_usage (bad)
1890 int bad;
1892 register const struct command_switch *cs;
1893 FILE *usageto;
1895 if (print_version_flag)
1896 print_version ();
1898 usageto = bad ? stderr : stdout;
1900 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
1902 fputs (_("Options:\n"), usageto);
1903 for (cs = switches; cs->c != '\0'; ++cs)
1905 char buf[1024], shortarg[50], longarg[50], *p;
1907 if (cs->description[0] == '-')
1908 continue;
1910 switch (long_options[cs - switches].has_arg)
1912 case no_argument:
1913 shortarg[0] = longarg[0] = '\0';
1914 break;
1915 case required_argument:
1916 sprintf (longarg, "=%s", cs->argdesc);
1917 sprintf (shortarg, " %s", cs->argdesc);
1918 break;
1919 case optional_argument:
1920 sprintf (longarg, "[=%s]", cs->argdesc);
1921 sprintf (shortarg, " [%s]", cs->argdesc);
1922 break;
1925 p = buf;
1927 if (isalnum (cs->c))
1929 sprintf (buf, " -%c%s", cs->c, shortarg);
1930 p += strlen (p);
1932 if (cs->long_name != 0)
1934 unsigned int i;
1935 sprintf (p, "%s--%s%s",
1936 !isalnum (cs->c) ? " " : ", ",
1937 cs->long_name, longarg);
1938 p += strlen (p);
1939 for (i = 0; i < (sizeof (long_option_aliases) /
1940 sizeof (long_option_aliases[0]));
1941 ++i)
1942 if (long_option_aliases[i].val == cs->c)
1944 sprintf (p, ", --%s%s",
1945 long_option_aliases[i].name, longarg);
1946 p += strlen (p);
1950 const struct command_switch *ncs = cs;
1951 while ((++ncs)->c != '\0')
1952 if (ncs->description[0] == '-' &&
1953 ncs->description[1] == cs->c)
1955 /* This is another switch that does the same
1956 one as the one we are processing. We want
1957 to list them all together on one line. */
1958 sprintf (p, ", -%c%s", ncs->c, shortarg);
1959 p += strlen (p);
1960 if (ncs->long_name != 0)
1962 sprintf (p, ", --%s%s", ncs->long_name, longarg);
1963 p += strlen (p);
1968 if (p - buf > DESCRIPTION_COLUMN - 2)
1969 /* The list of option names is too long to fit on the same
1970 line with the description, leaving at least two spaces.
1971 Print it on its own line instead. */
1973 fprintf (usageto, "%s\n", buf);
1974 buf[0] = '\0';
1977 fprintf (usageto, "%*s%s.\n",
1978 - DESCRIPTION_COLUMN,
1979 buf, cs->description);
1983 /* Decode switches from ARGC and ARGV.
1984 They came from the environment if ENV is nonzero. */
1986 static void
1987 decode_switches (argc, argv, env)
1988 int argc;
1989 char **argv;
1990 int env;
1992 int bad = 0;
1993 register const struct command_switch *cs;
1994 register struct stringlist *sl;
1995 register int c;
1997 /* getopt does most of the parsing for us.
1998 First, get its vectors set up. */
2000 init_switches ();
2002 /* Let getopt produce error messages for the command line,
2003 but not for options from the environment. */
2004 opterr = !env;
2005 /* Reset getopt's state. */
2006 optind = 0;
2008 while (optind < argc)
2010 /* Parse the next argument. */
2011 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2012 if (c == EOF)
2013 /* End of arguments, or "--" marker seen. */
2014 break;
2015 else if (c == 1)
2016 /* An argument not starting with a dash. */
2017 handle_non_switch_argument (optarg, env);
2018 else if (c == '?')
2019 /* Bad option. We will print a usage message and die later.
2020 But continue to parse the other options so the user can
2021 see all he did wrong. */
2022 bad = 1;
2023 else
2024 for (cs = switches; cs->c != '\0'; ++cs)
2025 if (cs->c == c)
2027 /* Whether or not we will actually do anything with
2028 this switch. We test this individually inside the
2029 switch below rather than just once outside it, so that
2030 options which are to be ignored still consume args. */
2031 int doit = !env || cs->env;
2033 switch (cs->type)
2035 default:
2036 abort ();
2038 case ignore:
2039 break;
2041 case flag:
2042 case flag_off:
2043 if (doit)
2044 *(int *) cs->value_ptr = cs->type == flag;
2045 break;
2047 case int_string:
2048 if (optarg == 0 && argc > optind
2049 && isdigit (argv[optind][0]))
2050 optarg = argv[optind++];
2052 if (!doit)
2053 break;
2055 if (optarg == 0)
2056 optarg = cs->noarg_value;
2058 *(char **) cs->value_ptr = optarg;
2059 break;
2061 case string:
2062 if (!doit)
2063 break;
2065 if (optarg == 0)
2066 optarg = cs->noarg_value;
2068 sl = *(struct stringlist **) cs->value_ptr;
2069 if (sl == 0)
2071 sl = (struct stringlist *)
2072 xmalloc (sizeof (struct stringlist));
2073 sl->max = 5;
2074 sl->idx = 0;
2075 sl->list = (char **) xmalloc (5 * sizeof (char *));
2076 *(struct stringlist **) cs->value_ptr = sl;
2078 else if (sl->idx == sl->max - 1)
2080 sl->max += 5;
2081 sl->list = (char **)
2082 xrealloc ((char *) sl->list,
2083 sl->max * sizeof (char *));
2085 sl->list[sl->idx++] = optarg;
2086 sl->list[sl->idx] = 0;
2087 break;
2089 case positive_int:
2090 if (optarg == 0 && argc > optind
2091 && isdigit (argv[optind][0]))
2092 optarg = argv[optind++];
2094 if (!doit)
2095 break;
2097 if (optarg != 0)
2099 int i = atoi (optarg);
2100 if (i < 1)
2102 if (doit)
2103 error (NILF, _("the `-%c' option requires a \
2104 positive integral argument"),
2105 cs->c);
2106 bad = 1;
2108 else
2109 *(unsigned int *) cs->value_ptr = i;
2111 else
2112 *(unsigned int *) cs->value_ptr
2113 = *(unsigned int *) cs->noarg_value;
2114 break;
2116 #ifndef NO_FLOAT
2117 case floating:
2118 if (optarg == 0 && optind < argc
2119 && (isdigit (argv[optind][0]) || argv[optind][0] == '.'))
2120 optarg = argv[optind++];
2122 if (doit)
2123 *(double *) cs->value_ptr
2124 = (optarg != 0 ? atof (optarg)
2125 : *(double *) cs->noarg_value);
2127 break;
2128 #endif
2131 /* We've found the switch. Stop looking. */
2132 break;
2136 /* There are no more options according to getting getopt, but there may
2137 be some arguments left. Since we have asked for non-option arguments
2138 to be returned in order, this only happens when there is a "--"
2139 argument to prevent later arguments from being options. */
2140 while (optind < argc)
2141 handle_non_switch_argument (argv[optind++], env);
2144 if (!env && (bad || print_usage_flag))
2146 print_usage (bad);
2147 die (bad ? 2 : 0);
2151 /* Decode switches from environment variable ENVAR (which is LEN chars long).
2152 We do this by chopping the value into a vector of words, prepending a
2153 dash to the first word if it lacks one, and passing the vector to
2154 decode_switches. */
2156 static void
2157 decode_env_switches (envar, len)
2158 char *envar;
2159 unsigned int len;
2161 char *varref = (char *) alloca (2 + len + 2);
2162 char *value, *p;
2163 int argc;
2164 char **argv;
2166 /* Get the variable's value. */
2167 varref[0] = '$';
2168 varref[1] = '(';
2169 bcopy (envar, &varref[2], len);
2170 varref[2 + len] = ')';
2171 varref[2 + len + 1] = '\0';
2172 value = variable_expand (varref);
2174 /* Skip whitespace, and check for an empty value. */
2175 value = next_token (value);
2176 len = strlen (value);
2177 if (len == 0)
2178 return;
2180 /* Allocate a vector that is definitely big enough. */
2181 argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
2183 /* Allocate a buffer to copy the value into while we split it into words
2184 and unquote it. We must use permanent storage for this because
2185 decode_switches may store pointers into the passed argument words. */
2186 p = (char *) xmalloc (2 * len);
2188 /* getopt will look at the arguments starting at ARGV[1].
2189 Prepend a spacer word. */
2190 argv[0] = 0;
2191 argc = 1;
2192 argv[argc] = p;
2193 while (*value != '\0')
2195 if (*value == '\\')
2196 ++value; /* Skip the backslash. */
2197 else if (isblank (*value))
2199 /* End of the word. */
2200 *p++ = '\0';
2201 argv[++argc] = p;
2203 ++value;
2204 while (isblank (*value));
2205 continue;
2207 *p++ = *value++;
2209 *p = '\0';
2210 argv[++argc] = 0;
2212 if (argv[1][0] != '-' && index (argv[1], '=') == 0)
2213 /* The first word doesn't start with a dash and isn't a variable
2214 definition. Add a dash and pass it along to decode_switches. We
2215 need permanent storage for this in case decode_switches saves
2216 pointers into the value. */
2217 argv[1] = concat ("-", argv[1], "");
2219 /* Parse those words. */
2220 decode_switches (argc, argv, 1);
2223 /* Quote the string IN so that it will be interpreted as a single word with
2224 no magic by the shell; if DOUBLE_DOLLARS is nonzero, also double dollar
2225 signs to avoid variable expansion in make itself. Write the result into
2226 OUT, returning the address of the next character to be written.
2227 Allocating space for OUT twice the length of IN (thrice if
2228 DOUBLE_DOLLARS is nonzero) is always sufficient. */
2230 static char *
2231 quote_as_word (out, in, double_dollars)
2232 char *out, *in;
2233 int double_dollars;
2235 while (*in != '\0')
2237 #ifdef VMS
2238 if (index ("^;'\"*?$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2239 #else
2240 if (index ("^;'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2241 #endif
2242 *out++ = '\\';
2243 if (double_dollars && *in == '$')
2244 *out++ = '$';
2245 *out++ = *in++;
2248 return out;
2251 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2252 command switches. Include options with args if ALL is nonzero.
2253 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2255 static void
2256 define_makeflags (all, makefile)
2257 int all, makefile;
2259 static const char ref[] = "$(MAKEOVERRIDES)";
2260 static const char posixref[] = "$(-*-command-variables-*-)";
2261 register const struct command_switch *cs;
2262 char *flagstring;
2263 register char *p;
2264 unsigned int words;
2265 struct variable *v;
2267 /* We will construct a linked list of `struct flag's describing
2268 all the flags which need to go in MAKEFLAGS. Then, once we
2269 know how many there are and their lengths, we can put them all
2270 together in a string. */
2272 struct flag
2274 struct flag *next;
2275 const struct command_switch *cs;
2276 char *arg;
2278 struct flag *flags = 0;
2279 unsigned int flagslen = 0;
2280 #define ADD_FLAG(ARG, LEN) \
2281 do { \
2282 struct flag *new = (struct flag *) alloca (sizeof (struct flag)); \
2283 new->cs = cs; \
2284 new->arg = (ARG); \
2285 new->next = flags; \
2286 flags = new; \
2287 if (new->arg == 0) \
2288 ++flagslen; /* Just a single flag letter. */ \
2289 else \
2290 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2291 if (!isalnum (cs->c)) \
2292 /* This switch has no single-letter version, so we use the long. */ \
2293 flagslen += 2 + strlen (cs->long_name); \
2294 } while (0)
2296 for (cs = switches; cs->c != '\0'; ++cs)
2297 if (cs->toenv && (!makefile || !cs->no_makefile))
2298 switch (cs->type)
2300 default:
2301 abort ();
2303 case ignore:
2304 break;
2306 case flag:
2307 case flag_off:
2308 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2309 && (cs->default_value == 0
2310 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2311 ADD_FLAG (0, 0);
2312 break;
2314 case positive_int:
2315 if (all)
2317 if ((cs->default_value != 0
2318 && (*(unsigned int *) cs->value_ptr
2319 == *(unsigned int *) cs->default_value)))
2320 break;
2321 else if (cs->noarg_value != 0
2322 && (*(unsigned int *) cs->value_ptr ==
2323 *(unsigned int *) cs->noarg_value))
2324 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2325 else if (cs->c == 'j')
2326 /* Special case for `-j'. */
2327 ADD_FLAG ("1", 1);
2328 else
2330 char *buf = (char *) alloca (30);
2331 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
2332 ADD_FLAG (buf, strlen (buf));
2335 break;
2337 #ifndef NO_FLOAT
2338 case floating:
2339 if (all)
2341 if (cs->default_value != 0
2342 && (*(double *) cs->value_ptr
2343 == *(double *) cs->default_value))
2344 break;
2345 else if (cs->noarg_value != 0
2346 && (*(double *) cs->value_ptr
2347 == *(double *) cs->noarg_value))
2348 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2349 else
2351 char *buf = (char *) alloca (100);
2352 sprintf (buf, "%g", *(double *) cs->value_ptr);
2353 ADD_FLAG (buf, strlen (buf));
2356 break;
2357 #endif
2359 case int_string:
2360 if (all)
2362 char *vp = *(char **) cs->value_ptr;
2364 if (cs->default_value != 0
2365 && streq (vp, cs->default_value))
2366 break;
2367 if (cs->noarg_value != 0
2368 && streq (vp, cs->noarg_value))
2369 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2370 else
2371 ADD_FLAG (vp, strlen (vp));
2373 break;
2375 case string:
2376 if (all)
2378 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
2379 if (sl != 0)
2381 /* Add the elements in reverse order, because
2382 all the flags get reversed below; and the order
2383 matters for some switches (like -I). */
2384 register unsigned int i = sl->idx;
2385 while (i-- > 0)
2386 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
2389 break;
2392 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
2394 #undef ADD_FLAG
2396 /* Construct the value in FLAGSTRING.
2397 We allocate enough space for a preceding dash and trailing null. */
2398 flagstring = (char *) alloca (1 + flagslen + 1);
2399 p = flagstring;
2400 words = 1;
2401 *p++ = '-';
2402 while (flags != 0)
2404 /* Add the flag letter or name to the string. */
2405 if (!isalnum (flags->cs->c))
2407 *p++ = '-';
2408 strcpy (p, flags->cs->long_name);
2409 p += strlen (p);
2411 else
2412 *p++ = flags->cs->c;
2413 if (flags->arg != 0)
2415 /* A flag that takes an optional argument which in this case is
2416 omitted is specified by ARG being "". We must distinguish
2417 because a following flag appended without an intervening " -"
2418 is considered the arg for the first. */
2419 if (flags->arg[0] != '\0')
2421 /* Add its argument too. */
2422 *p++ = !isalnum (flags->cs->c) ? '=' : ' ';
2423 p = quote_as_word (p, flags->arg, 1);
2425 ++words;
2426 /* Write a following space and dash, for the next flag. */
2427 *p++ = ' ';
2428 *p++ = '-';
2430 else if (!isalnum (flags->cs->c))
2432 ++words;
2433 /* Long options must each go in their own word,
2434 so we write the following space and dash. */
2435 *p++ = ' ';
2436 *p++ = '-';
2438 flags = flags->next;
2441 /* Define MFLAGS before appending variable definitions. */
2443 if (p == &flagstring[1])
2444 /* No flags. */
2445 flagstring[0] = '\0';
2446 else if (p[-1] == '-')
2448 /* Kill the final space and dash. */
2449 p -= 2;
2450 *p = '\0';
2452 else
2453 /* Terminate the string. */
2454 *p = '\0';
2456 /* Since MFLAGS is not parsed for flags, there is no reason to
2457 override any makefile redefinition. */
2458 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
2460 if (all && command_variables != 0)
2462 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
2463 command-line variable definitions. */
2465 if (p == &flagstring[1])
2466 /* No flags written, so elide the leading dash already written. */
2467 p = flagstring;
2468 else
2470 /* Separate the variables from the switches with a "--" arg. */
2471 if (p[-1] != '-')
2473 /* We did not already write a trailing " -". */
2474 *p++ = ' ';
2475 *p++ = '-';
2477 /* There is a trailing " -"; fill it out to " -- ". */
2478 *p++ = '-';
2479 *p++ = ' ';
2482 /* Copy in the string. */
2483 if (posix_pedantic)
2485 bcopy (posixref, p, sizeof posixref - 1);
2486 p += sizeof posixref - 1;
2488 else
2490 bcopy (ref, p, sizeof ref - 1);
2491 p += sizeof ref - 1;
2494 else if (p == &flagstring[1])
2496 words = 0;
2497 --p;
2499 else if (p[-1] == '-')
2500 /* Kill the final space and dash. */
2501 p -= 2;
2502 /* Terminate the string. */
2503 *p = '\0';
2505 v = define_variable ("MAKEFLAGS", 9,
2506 /* If there are switches, omit the leading dash
2507 unless it is a single long option with two
2508 leading dashes. */
2509 &flagstring[(flagstring[0] == '-'
2510 && flagstring[1] != '-')
2511 ? 1 : 0],
2512 /* This used to use o_env, but that lost when a
2513 makefile defined MAKEFLAGS. Makefiles set
2514 MAKEFLAGS to add switches, but we still want
2515 to redefine its value with the full set of
2516 switches. Of course, an override or command
2517 definition will still take precedence. */
2518 o_file, 1);
2519 if (! all)
2520 /* The first time we are called, set MAKEFLAGS to always be exported.
2521 We should not do this again on the second call, because that is
2522 after reading makefiles which might have done `unexport MAKEFLAGS'. */
2523 v->export = v_export;
2526 /* Print version information. */
2528 static void
2529 print_version ()
2531 static int printed_version = 0;
2533 char *precede = print_data_base_flag ? "# " : "";
2535 if (printed_version)
2536 /* Do it only once. */
2537 return;
2539 printf ("%sGNU Make version %s", precede, version_string);
2540 if (remote_description != 0 && *remote_description != '\0')
2541 printf ("-%s", remote_description);
2543 printf (_(", by Richard Stallman and Roland McGrath.\n\
2544 %sCopyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99\n\
2545 %s\tFree Software Foundation, Inc.\n\
2546 %sThis is free software; see the source for copying conditions.\n\
2547 %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
2548 %sPARTICULAR PURPOSE.\n\n\
2549 %sReport bugs to <bug-make@gnu.org>.\n\n"),
2550 precede, precede, precede, precede, precede, precede);
2552 printed_version = 1;
2554 /* Flush stdout so the user doesn't have to wait to see the
2555 version information while things are thought about. */
2556 fflush (stdout);
2559 /* Print a bunch of information about this and that. */
2561 static void
2562 print_data_base ()
2564 time_t when;
2566 when = time ((time_t *) 0);
2567 printf (_("\n# Make data base, printed on %s"), ctime (&when));
2569 print_variable_data_base ();
2570 print_dir_data_base ();
2571 print_rule_data_base ();
2572 print_file_data_base ();
2573 print_vpath_data_base ();
2575 when = time ((time_t *) 0);
2576 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
2579 /* Exit with STATUS, cleaning up as necessary. */
2581 void
2582 die (status)
2583 int status;
2585 static char dying = 0;
2587 if (!dying)
2589 int err;
2591 dying = 1;
2593 if (print_version_flag)
2594 print_version ();
2596 /* Wait for children to die. */
2597 for (err = status != 0; job_slots_used > 0; err = 0)
2598 reap_children (1, err);
2600 /* Let the remote job module clean up its state. */
2601 remote_cleanup ();
2603 /* Remove the intermediate files. */
2604 remove_intermediates (0);
2606 if (print_data_base_flag)
2607 print_data_base ();
2609 /* Try to move back to the original directory. This is essential on
2610 MS-DOS (where there is really only one process), and on Unix it
2611 puts core files in the original directory instead of the -C
2612 directory. Must wait until after remove_intermediates(), or unlinks
2613 of relative pathnames fail. */
2614 if (directory_before_chdir != 0)
2615 chdir (directory_before_chdir);
2617 log_working_directory (0);
2620 exit (status);
2623 /* Write a message indicating that we've just entered or
2624 left (according to ENTERING) the current directory. */
2626 void
2627 log_working_directory (entering)
2628 int entering;
2630 static int entered = 0;
2631 char *msg = entering ? _("Entering") : _("Leaving");
2633 /* Print nothing without the flag. Don't print the entering message
2634 again if we already have. Don't print the leaving message if we
2635 haven't printed the entering message. */
2636 if (! print_directory_flag || entering == entered)
2637 return;
2639 entered = entering;
2641 if (print_data_base_flag)
2642 fputs ("# ", stdout);
2644 if (makelevel == 0)
2645 printf ("%s: %s ", program, msg);
2646 else
2647 printf ("%s[%u]: %s ", program, makelevel, msg);
2649 if (starting_directory == 0)
2650 puts (_("an unknown directory"));
2651 else
2652 printf (_("directory `%s'\n"), starting_directory);