* Add configure option to enable dmalloc library.
[make.git] / main.c
blobf9ba4f4f66cbbce7f2c12fdf4e026e79625934a5
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 };
209 /* Maximum load average at which multiple jobs will be run.
210 Negative values mean unlimited, while zero means limit to
211 zero load (which could be useful to start infinite jobs remotely
212 but one at a time locally). */
213 #ifndef NO_FLOAT
214 double max_load_average = -1.0;
215 double default_load_average = -1.0;
216 #else
217 int max_load_average = -1;
218 int default_load_average = -1;
219 #endif
221 /* List of directories given with -C switches. */
223 static struct stringlist *directories = 0;
225 /* List of include directories given with -I switches. */
227 static struct stringlist *include_directories = 0;
229 /* List of files given with -o switches. */
231 static struct stringlist *old_files = 0;
233 /* List of files given with -W switches. */
235 static struct stringlist *new_files = 0;
237 /* If nonzero, we should just print usage and exit. */
239 static int print_usage_flag = 0;
241 /* If nonzero, we should print a warning message
242 for each reference to an undefined variable. */
244 int warn_undefined_variables_flag;
246 /* The table of command switches. */
248 static const struct command_switch switches[] =
250 { 'b', ignore, 0, 0, 0, 0, 0, 0,
251 0, 0,
252 "Ignored for compatibility" },
253 { 'C', string, (char *) &directories, 0, 0, 0, 0, 0,
254 "directory", "DIRECTORY",
255 "Change to DIRECTORY before doing anything" },
256 { 'd', flag, (char *) &debug_flag, 1, 1, 0, 0, 0,
257 "debug", 0,
258 "Print lots of debugging information" },
259 #ifdef WINDOWS32
260 { 'D', flag, (char *) &suspend_flag, 1, 1, 0, 0, 0,
261 "suspend-for-debug", 0,
262 "Suspend process to allow a debugger to attach" },
263 #endif
264 { 'e', flag, (char *) &env_overrides, 1, 1, 0, 0, 0,
265 "environment-overrides", 0,
266 "Environment variables override makefiles" },
267 { 'f', string, (char *) &makefiles, 0, 0, 0, 0, 0,
268 "file", "FILE",
269 "Read FILE as a makefile" },
270 { 'h', flag, (char *) &print_usage_flag, 0, 0, 0, 0, 0,
271 "help", 0,
272 "Print this message and exit" },
273 { 'i', flag, (char *) &ignore_errors_flag, 1, 1, 0, 0, 0,
274 "ignore-errors", 0,
275 "Ignore errors from commands" },
276 { 'I', string, (char *) &include_directories, 1, 1, 0, 0, 0,
277 "include-dir", "DIRECTORY",
278 "Search DIRECTORY for included makefiles" },
279 { 'j',
280 #ifndef MAKE_JOBSERVER
281 positive_int, (char *) &job_slots, 1, 1, 0,
282 (char *) &inf_jobs, (char *) &default_job_slots,
283 #else
284 int_string, (char *)&job_slots_str, 1, 1, 0, "0", "1",
285 #endif
286 "jobs", "N",
287 "Allow N jobs at once; infinite jobs with no arg" },
288 { 'k', flag, (char *) &keep_going_flag, 1, 1, 0,
289 0, (char *) &default_keep_going_flag,
290 "keep-going", 0,
291 "Keep going when some targets can't be made" },
292 #ifndef NO_FLOAT
293 { 'l', floating, (char *) &max_load_average, 1, 1, 0,
294 (char *) &default_load_average, (char *) &default_load_average,
295 "load-average", "N",
296 "Don't start multiple jobs unless load is below N" },
297 #else
298 { 'l', positive_int, (char *) &max_load_average, 1, 1, 0,
299 (char *) &default_load_average, (char *) &default_load_average,
300 "load-average", "N",
301 "Don't start multiple jobs unless load is below N" },
302 #endif
303 { 'm', ignore, 0, 0, 0, 0, 0, 0,
304 0, 0,
305 "-b" },
306 { 'n', flag, (char *) &just_print_flag, 1, 1, 1, 0, 0,
307 "just-print", 0,
308 "Don't actually run any commands; just print them" },
309 { 'o', string, (char *) &old_files, 0, 0, 0, 0, 0,
310 "old-file", "FILE",
311 "Consider FILE to be very old and don't remake it" },
312 { 'p', flag, (char *) &print_data_base_flag, 1, 1, 0, 0, 0,
313 "print-data-base", 0,
314 "Print make's internal database" },
315 { 'q', flag, (char *) &question_flag, 1, 1, 1, 0, 0,
316 "question", 0,
317 "Run no commands; exit status says if up to date" },
318 { 'r', flag, (char *) &no_builtin_rules_flag, 1, 1, 0, 0, 0,
319 "no-builtin-rules", 0,
320 "Disable the built-in implicit rules" },
321 { 'R', flag, (char *) &no_builtin_variables_flag, 1, 1, 0, 0, 0,
322 "no-builtin-variables", 0,
323 "Disable the built-in variable settings" },
324 { 's', flag, (char *) &silent_flag, 1, 1, 0, 0, 0,
325 "silent", 0,
326 "Don't echo commands" },
327 { 'S', flag_off, (char *) &keep_going_flag, 1, 1, 0,
328 0, (char *) &default_keep_going_flag,
329 "no-keep-going", 0,
330 "Turns off -k" },
331 { 't', flag, (char *) &touch_flag, 1, 1, 1, 0, 0,
332 "touch", 0,
333 "Touch targets instead of remaking them" },
334 { 'v', flag, (char *) &print_version_flag, 1, 1, 0, 0, 0,
335 "version", 0,
336 "Print the version number of make and exit" },
337 { 'w', flag, (char *) &print_directory_flag, 1, 1, 0, 0, 0,
338 "print-directory", 0,
339 "Print the current directory" },
340 { 2, flag, (char *) &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
341 "no-print-directory", 0,
342 "Turn off -w, even if it was turned on implicitly" },
343 { 'W', string, (char *) &new_files, 0, 0, 0, 0, 0,
344 "what-if", "FILE",
345 "Consider FILE to be infinitely new" },
346 { 3, flag, (char *) &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
347 "warn-undefined-variables", 0,
348 "Warn when an undefined variable is referenced" },
349 { '\0', }
352 /* Secondary long names for options. */
354 static struct option long_option_aliases[] =
356 { "quiet", no_argument, 0, 's' },
357 { "stop", no_argument, 0, 'S' },
358 { "new-file", required_argument, 0, 'W' },
359 { "assume-new", required_argument, 0, 'W' },
360 { "assume-old", required_argument, 0, 'o' },
361 { "max-load", optional_argument, 0, 'l' },
362 { "dry-run", no_argument, 0, 'n' },
363 { "recon", no_argument, 0, 'n' },
364 { "makefile", required_argument, 0, 'f' },
367 /* The usage message prints the descriptions of options starting in
368 this column. Make sure it leaves enough room for the longest
369 description to fit in less than 80 characters. */
371 #define DESCRIPTION_COLUMN 30
373 /* List of goal targets. */
375 static struct dep *goals, *lastgoal;
377 /* List of variables which were defined on the command line
378 (or, equivalently, in MAKEFLAGS). */
380 struct command_variable
382 struct command_variable *next;
383 struct variable *variable;
385 static struct command_variable *command_variables;
387 /* The name we were invoked with. */
389 char *program;
391 /* Our current directory before processing any -C options. */
393 char *directory_before_chdir;
395 /* Our current directory after processing all -C options. */
397 char *starting_directory;
399 /* Value of the MAKELEVEL variable at startup (or 0). */
401 unsigned int makelevel;
403 /* First file defined in the makefile whose name does not
404 start with `.'. This is the default to remake if the
405 command line does not specify. */
407 struct file *default_goal_file;
409 /* Pointer to structure for the file .DEFAULT
410 whose commands are used for any file that has none of its own.
411 This is zero if the makefiles do not define .DEFAULT. */
413 struct file *default_file;
415 /* Nonzero if we have seen the magic `.POSIX' target.
416 This turns on pedantic compliance with POSIX.2. */
418 int posix_pedantic;
420 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
421 print one warning about it during the run, and (b) we can print a final
422 warning at the end of the run. */
424 int clock_skew_detected;
426 /* Mask of signals that are being caught with fatal_error_signal. */
428 #ifdef POSIX
429 sigset_t fatal_signal_set;
430 #else
431 #ifdef HAVE_SIGSETMASK
432 int fatal_signal_mask;
433 #endif
434 #endif
436 static struct file *
437 enter_command_line_file (name)
438 char *name;
440 if (name[0] == '\0')
441 fatal (NILF, "empty string invalid as file name");
443 if (name[0] == '~')
445 char *expanded = tilde_expand (name);
446 if (expanded != 0)
447 name = expanded; /* Memory leak; I don't care. */
450 /* This is also done in parse_file_seq, so this is redundant
451 for names read from makefiles. It is here for names passed
452 on the command line. */
453 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
455 name += 2;
456 while (*name == '/')
457 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
458 ++name;
461 if (*name == '\0')
463 /* It was all slashes! Move back to the dot and truncate
464 it after the first slash, so it becomes just "./". */
466 --name;
467 while (name[0] != '.');
468 name[2] = '\0';
471 return enter_file (xstrdup (name));
474 /* Toggle -d on receipt of SIGUSR1. */
476 static RETSIGTYPE
477 debug_signal_handler (sig)
478 int sig;
480 debug_flag = ! debug_flag;
483 #ifdef WINDOWS32
485 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
486 * exception and print it to stderr instead.
488 * If debug_flag not set, just print a simple message and exit.
489 * If debug_flag set, print a more verbose message.
490 * If compiled for DEBUG, let exception pass through to GUI so that
491 * debuggers can attach.
493 LONG WINAPI
494 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
496 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
497 LPSTR cmdline = GetCommandLine();
498 LPSTR prg = strtok(cmdline, " ");
499 CHAR errmsg[1024];
500 #ifdef USE_EVENT_LOG
501 HANDLE hEventSource;
502 LPTSTR lpszStrings[1];
503 #endif
505 if (!debug_flag)
507 sprintf(errmsg, "%s: Interrupt/Exception caught ", prg);
508 sprintf(&errmsg[strlen(errmsg)],
509 "(code = 0x%x, addr = 0x%x)\r\n",
510 exrec->ExceptionCode, exrec->ExceptionAddress);
511 fprintf(stderr, errmsg);
512 exit(255);
515 sprintf(errmsg,
516 "\r\nUnhandled exception filter called from program %s\r\n", prg);
517 sprintf(&errmsg[strlen(errmsg)], "ExceptionCode = %x\r\n",
518 exrec->ExceptionCode);
519 sprintf(&errmsg[strlen(errmsg)], "ExceptionFlags = %x\r\n",
520 exrec->ExceptionFlags);
521 sprintf(&errmsg[strlen(errmsg)], "ExceptionAddress = %x\r\n",
522 exrec->ExceptionAddress);
524 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
525 && exrec->NumberParameters >= 2)
526 sprintf(&errmsg[strlen(errmsg)],
527 "Access violation: %s operation at address %x\r\n",
528 exrec->ExceptionInformation[0] ? "write": "read",
529 exrec->ExceptionInformation[1]);
531 /* turn this on if we want to put stuff in the event log too */
532 #ifdef USE_EVENT_LOG
533 hEventSource = RegisterEventSource(NULL, "GNU Make");
534 lpszStrings[0] = errmsg;
536 if (hEventSource != NULL)
538 ReportEvent(hEventSource, /* handle of event source */
539 EVENTLOG_ERROR_TYPE, /* event type */
540 0, /* event category */
541 0, /* event ID */
542 NULL, /* current user's SID */
543 1, /* strings in lpszStrings */
544 0, /* no bytes of raw data */
545 lpszStrings, /* array of error strings */
546 NULL); /* no raw data */
548 (VOID) DeregisterEventSource(hEventSource);
550 #endif
552 /* Write the error to stderr too */
553 fprintf(stderr, errmsg);
555 #ifdef DEBUG
556 return EXCEPTION_CONTINUE_SEARCH;
557 #else
558 exit(255);
559 return (255); /* not reached */
560 #endif
564 * On WIN32 systems we don't have the luxury of a /bin directory that
565 * is mapped globally to every drive mounted to the system. Since make could
566 * be invoked from any drive, and we don't want to propogate /bin/sh
567 * to every single drive. Allow ourselves a chance to search for
568 * a value for default shell here (if the default path does not exist).
572 find_and_set_default_shell(char *token)
574 int sh_found = 0;
575 char* search_token;
576 PATH_VAR(sh_path);
577 extern char *default_shell;
579 if (!token)
580 search_token = default_shell;
581 else
582 search_token = token;
584 if (!no_default_sh_exe &&
585 (token == NULL || !strcmp(search_token, default_shell))) {
586 /* no new information, path already set or known */
587 sh_found = 1;
588 } else if (file_exists_p(search_token)) {
589 /* search token path was found */
590 sprintf(sh_path, "%s", search_token);
591 default_shell = xstrdup(w32ify(sh_path,0));
592 if (debug_flag)
593 printf("find_and_set_shell setting default_shell = %s\n", default_shell);
594 sh_found = 1;
595 } else {
596 char *p;
597 struct variable *v = lookup_variable ("Path", 4);
600 * Search Path for shell
602 if (v && v->value) {
603 char *ep;
605 p = v->value;
606 ep = strchr(p, PATH_SEPARATOR_CHAR);
608 while (ep && *ep) {
609 *ep = '\0';
611 if (dir_file_exists_p(p, search_token)) {
612 sprintf(sh_path, "%s/%s", p, search_token);
613 default_shell = xstrdup(w32ify(sh_path,0));
614 sh_found = 1;
615 *ep = PATH_SEPARATOR_CHAR;
617 /* terminate loop */
618 p += strlen(p);
619 } else {
620 *ep = PATH_SEPARATOR_CHAR;
621 p = ++ep;
624 ep = strchr(p, PATH_SEPARATOR_CHAR);
627 /* be sure to check last element of Path */
628 if (p && *p && dir_file_exists_p(p, search_token)) {
629 sprintf(sh_path, "%s/%s", p, search_token);
630 default_shell = xstrdup(w32ify(sh_path,0));
631 sh_found = 1;
634 if (debug_flag && sh_found)
635 printf("find_and_set_shell path search set default_shell = %s\n", default_shell);
639 /* naive test */
640 if (!unixy_shell && sh_found &&
641 (strstr(default_shell, "sh") || strstr(default_shell, "SH"))) {
642 unixy_shell = 1;
643 batch_mode_shell = 0;
646 #ifdef BATCH_MODE_ONLY_SHELL
647 batch_mode_shell = 1;
648 #endif
650 return (sh_found);
652 #endif /* WINDOWS32 */
654 #ifdef __MSDOS__
656 static void
657 msdos_return_to_initial_directory ()
659 if (directory_before_chdir)
660 chdir (directory_before_chdir);
662 #endif
664 #ifndef _AMIGA
666 main (argc, argv, envp)
667 int argc;
668 char **argv;
669 char **envp;
670 #else
671 int main (int argc, char ** argv)
672 #endif
674 static char *stdin_nm = 0;
675 register struct file *f;
676 register unsigned int i;
677 char **p;
678 struct dep *read_makefiles;
679 PATH_VAR (current_directory);
680 #ifdef WINDOWS32
681 char *unix_path = NULL;
682 char *windows32_path = NULL;
684 SetUnhandledExceptionFilter(handle_runtime_exceptions);
686 /* start off assuming we have no shell */
687 unixy_shell = 0;
688 no_default_sh_exe = 1;
689 #endif
691 default_goal_file = 0;
692 reading_file = 0;
694 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
695 /* Request the most powerful version of `system', to
696 make up for the dumb default shell. */
697 __system_flags = (__system_redirect
698 | __system_use_shell
699 | __system_allow_multiple_cmds
700 | __system_allow_long_cmds
701 | __system_handle_null_commands
702 | __system_emulate_chdir);
704 #endif
706 #if !defined (HAVE_STRSIGNAL) && !defined (HAVE_SYS_SIGLIST)
707 signame_init ();
708 #endif
710 #ifdef POSIX
711 sigemptyset (&fatal_signal_set);
712 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
713 #else
714 #ifdef HAVE_SIGSETMASK
715 fatal_signal_mask = 0;
716 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
717 #else
718 #define ADD_SIG(sig)
719 #endif
720 #endif
722 #define FATAL_SIG(sig) \
723 if (signal ((sig), fatal_error_signal) == SIG_IGN) \
724 (void) signal ((sig), SIG_IGN); \
725 else \
726 ADD_SIG (sig);
728 #ifdef SIGHUP
729 FATAL_SIG (SIGHUP);
730 #endif
731 #ifdef SIGQUIT
732 FATAL_SIG (SIGQUIT);
733 #endif
734 FATAL_SIG (SIGINT);
735 FATAL_SIG (SIGTERM);
737 #ifdef SIGDANGER
738 FATAL_SIG (SIGDANGER);
739 #endif
740 #ifdef SIGXCPU
741 FATAL_SIG (SIGXCPU);
742 #endif
743 #ifdef SIGXFSZ
744 FATAL_SIG (SIGXFSZ);
745 #endif
747 #undef FATAL_SIG
749 /* Do not ignore the child-death signal. This must be done before
750 any children could possibly be created; otherwise, the wait
751 functions won't work on systems with the SVR4 ECHILD brain
752 damage, if our invoker is ignoring this signal. */
754 #ifdef HAVE_WAIT_NOHANG
755 # if defined SIGCHLD
756 (void) signal (SIGCHLD, SIG_DFL);
757 # endif
758 # if defined SIGCLD && SIGCLD != SIGCHLD
759 (void) signal (SIGCLD, SIG_DFL);
760 # endif
761 #endif
763 /* Make sure stdout is line-buffered. */
765 #ifdef HAVE_SETLINEBUF
766 setlinebuf (stdout);
767 #else
768 #ifndef SETVBUF_REVERSED
769 setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
770 #else /* setvbuf not reversed. */
771 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
772 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
773 #endif /* setvbuf reversed. */
774 #endif /* setlinebuf missing. */
776 /* Figure out where this program lives. */
778 if (argv[0] == 0)
779 argv[0] = "";
780 if (argv[0][0] == '\0')
781 program = "make";
782 else
784 #ifdef VMS
785 program = rindex (argv[0], ']');
786 #else
787 program = rindex (argv[0], '/');
788 #endif
789 #ifdef __MSDOS__
790 if (program == 0)
791 program = rindex (argv[0], '\\');
792 else
794 /* Some weird environments might pass us argv[0] with
795 both kinds of slashes; we must find the rightmost. */
796 char *p = rindex (argv[0], '\\');
797 if (p && p > program)
798 program = p;
800 if (program == 0 && argv[0][1] == ':')
801 program = argv[0] + 1;
802 #endif
803 if (program == 0)
804 program = argv[0];
805 else
806 ++program;
809 /* Set up to access user data (files). */
810 user_access ();
812 /* Figure out where we are. */
814 #ifdef WINDOWS32
815 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
816 #else
817 if (getcwd (current_directory, GET_PATH_MAX) == 0)
818 #endif
820 #ifdef HAVE_GETCWD
821 perror_with_name ("getcwd: ", "");
822 #else
823 error (NILF, "getwd: %s", current_directory);
824 #endif
825 current_directory[0] = '\0';
826 directory_before_chdir = 0;
828 else
829 directory_before_chdir = xstrdup (current_directory);
830 #ifdef __MSDOS__
831 /* Make sure we will return to the initial directory, come what may. */
832 atexit (msdos_return_to_initial_directory);
833 #endif
835 /* Read in variables from the environment. It is important that this be
836 done before $(MAKE) is figured out so its definitions will not be
837 from the environment. */
839 #ifndef _AMIGA
840 for (i = 0; envp[i] != 0; ++i)
842 int do_not_define;
843 register char *ep = envp[i];
845 /* by default, everything gets defined and exported */
846 do_not_define = 0;
848 while (*ep != '=')
849 ++ep;
850 #ifdef WINDOWS32
851 if (!unix_path && strneq(envp[i], "PATH=", 5))
852 unix_path = ep+1;
853 else if (!windows32_path && !strnicmp(envp[i], "Path=", 5)) {
854 do_not_define = 1; /* it gets defined after loop exits */
855 windows32_path = ep+1;
857 #endif
858 /* The result of pointer arithmetic is cast to unsigned int for
859 machines where ptrdiff_t is a different size that doesn't widen
860 the same. */
861 if (!do_not_define)
862 define_variable (envp[i], (unsigned int) (ep - envp[i]),
863 ep + 1, o_env, 1)
864 /* Force exportation of every variable culled from the environment.
865 We used to rely on target_environment's v_default code to do this.
866 But that does not work for the case where an environment variable
867 is redefined in a makefile with `override'; it should then still
868 be exported, because it was originally in the environment. */
869 ->export = v_export;
871 #ifdef WINDOWS32
873 * Make sure that this particular spelling of 'Path' is available
875 if (windows32_path)
876 define_variable("Path", 4, windows32_path, o_env, 1)->export = v_export;
877 else if (unix_path)
878 define_variable("Path", 4, unix_path, o_env, 1)->export = v_export;
879 else
880 define_variable("Path", 4, "", o_env, 1)->export = v_export;
883 * PATH defaults to Path iff PATH not found and Path is found.
885 if (!unix_path && windows32_path)
886 define_variable("PATH", 4, windows32_path, o_env, 1)->export = v_export;
887 #endif
888 #else /* For Amiga, read the ENV: device, ignoring all dirs */
890 BPTR env, file, old;
891 char buffer[1024];
892 int len;
893 __aligned struct FileInfoBlock fib;
895 env = Lock ("ENV:", ACCESS_READ);
896 if (env)
898 old = CurrentDir (DupLock(env));
899 Examine (env, &fib);
901 while (ExNext (env, &fib))
903 if (fib.fib_DirEntryType < 0) /* File */
905 /* Define an empty variable. It will be filled in
906 variable_lookup(). Makes startup quite a bit
907 faster. */
908 define_variable (fib.fib_FileName,
909 strlen (fib.fib_FileName),
910 "", o_env, 1)->export = v_export;
913 UnLock (env);
914 UnLock(CurrentDir(old));
917 #endif
919 /* Decode the switches. */
921 decode_env_switches ("MAKEFLAGS", 9);
922 #if 0
923 /* People write things like:
924 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
925 and we set the -p, -i and -e switches. Doesn't seem quite right. */
926 decode_env_switches ("MFLAGS", 6);
927 #endif
928 decode_switches (argc, argv, 0);
929 #ifdef WINDOWS32
930 if (suspend_flag) {
931 fprintf(stderr, "%s (pid = %d)\n", argv[0], GetCurrentProcessId());
932 fprintf(stderr, "%s is suspending for 30 seconds...", argv[0]);
933 Sleep(30 * 1000);
934 fprintf(stderr, "done sleep(30). Continuing.\n");
936 #endif
938 /* Print version information. */
940 if (print_version_flag || print_data_base_flag || debug_flag)
941 print_version ();
943 /* `make --version' is supposed to just print the version and exit. */
944 if (print_version_flag)
945 die (0);
947 #if !defined(__MSDOS__) && !defined(VMS)
948 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
949 (If it is a relative pathname with a slash, prepend our directory name
950 so the result will run the same program regardless of the current dir.
951 If it is a name with no slash, we can only hope that PATH did not
952 find it in the current directory.) */
953 #ifdef WINDOWS32
955 * Convert from backslashes to forward slashes for
956 * programs like sh which don't like them. Shouldn't
957 * matter if the path is one way or the other for
958 * CreateProcess().
960 if (strpbrk(argv[0], "/:\\") ||
961 strstr(argv[0], "..") ||
962 strneq(argv[0], "//", 2))
963 argv[0] = xstrdup(w32ify(argv[0],1));
964 #else /* WINDOWS32 */
965 if (current_directory[0] != '\0'
966 && argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
967 argv[0] = concat (current_directory, "/", argv[0]);
968 #endif /* WINDOWS32 */
969 #endif
971 /* The extra indirection through $(MAKE_COMMAND) is done
972 for hysterical raisins. */
973 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
974 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
976 if (command_variables != 0)
978 struct command_variable *cv;
979 struct variable *v;
980 unsigned int len = 0;
981 char *value, *p;
983 /* Figure out how much space will be taken up by the command-line
984 variable definitions. */
985 for (cv = command_variables; cv != 0; cv = cv->next)
987 v = cv->variable;
988 len += 2 * strlen (v->name);
989 if (! v->recursive)
990 ++len;
991 ++len;
992 len += 3 * strlen (v->value);
995 /* Now allocate a buffer big enough and fill it. */
996 p = value = (char *) alloca (len);
997 for (cv = command_variables; cv != 0; cv = cv->next)
999 v = cv->variable;
1000 p = quote_as_word (p, v->name, 0);
1001 if (! v->recursive)
1002 *p++ = ':';
1003 *p++ = '=';
1004 p = quote_as_word (p, v->value, 0);
1005 *p++ = ' ';
1007 p[-1] = '\0'; /* Kill the final space and terminate. */
1009 /* Define an unchangeable variable with a name that no POSIX.2
1010 makefile could validly use for its own variable. */
1011 (void) define_variable ("-*-command-variables-*-", 23,
1012 value, o_automatic, 0);
1014 /* Define the variable; this will not override any user definition.
1015 Normally a reference to this variable is written into the value of
1016 MAKEFLAGS, allowing the user to override this value to affect the
1017 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1018 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1019 a reference to this hidden variable is written instead. */
1020 (void) define_variable ("MAKEOVERRIDES", 13,
1021 "${-*-command-variables-*-}", o_env, 1);
1024 /* If there were -C flags, move ourselves about. */
1025 if (directories != 0)
1026 for (i = 0; directories->list[i] != 0; ++i)
1028 char *dir = directories->list[i];
1029 if (dir[0] == '~')
1031 char *expanded = tilde_expand (dir);
1032 if (expanded != 0)
1033 dir = expanded;
1035 if (chdir (dir) < 0)
1036 pfatal_with_name (dir);
1037 if (dir != directories->list[i])
1038 free (dir);
1041 #ifdef WINDOWS32
1043 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1044 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1046 * The functions in dir.c can incorrectly cache information for "."
1047 * before we have changed directory and this can cause file
1048 * lookups to fail because the current directory (.) was pointing
1049 * at the wrong place when it was first evaluated.
1051 no_default_sh_exe = !find_and_set_default_shell(NULL);
1053 #endif /* WINDOWS32 */
1054 /* Figure out the level of recursion. */
1056 struct variable *v = lookup_variable ("MAKELEVEL", 9);
1057 if (v != 0 && *v->value != '\0' && *v->value != '-')
1058 makelevel = (unsigned int) atoi (v->value);
1059 else
1060 makelevel = 0;
1063 /* Except under -s, always do -w in sub-makes and under -C. */
1064 if (!silent_flag && (directories != 0 || makelevel > 0))
1065 print_directory_flag = 1;
1067 /* Let the user disable that with --no-print-directory. */
1068 if (inhibit_print_directory_flag)
1069 print_directory_flag = 0;
1071 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1072 if (no_builtin_variables_flag)
1073 no_builtin_rules_flag = 1;
1075 /* Construct the list of include directories to search. */
1077 construct_include_path (include_directories == 0 ? (char **) 0
1078 : include_directories->list);
1080 /* Figure out where we are now, after chdir'ing. */
1081 if (directories == 0)
1082 /* We didn't move, so we're still in the same place. */
1083 starting_directory = current_directory;
1084 else
1086 #ifdef WINDOWS32
1087 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1088 #else
1089 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1090 #endif
1092 #ifdef HAVE_GETCWD
1093 perror_with_name ("getcwd: ", "");
1094 #else
1095 error (NILF, "getwd: %s", current_directory);
1096 #endif
1097 starting_directory = 0;
1099 else
1100 starting_directory = current_directory;
1103 (void) define_variable ("CURDIR", 6, current_directory, o_default, 0);
1105 /* Read any stdin makefiles into temporary files. */
1107 if (makefiles != 0)
1109 register unsigned int i;
1110 for (i = 0; i < makefiles->idx; ++i)
1111 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1113 /* This makefile is standard input. Since we may re-exec
1114 and thus re-read the makefiles, we read standard input
1115 into a temporary file and read from that. */
1116 FILE *outfile;
1118 /* Make a unique filename. */
1119 #ifdef HAVE_MKTEMP
1121 #ifdef VMS
1122 static char name[] = "sys$scratch:GmXXXXXX";
1123 #else
1124 static char name[] = "/tmp/GmXXXXXX";
1125 #endif
1126 (void) mktemp (name);
1127 #else
1128 static char name[L_tmpnam];
1129 (void) tmpnam (name);
1130 #endif
1132 if (stdin_nm)
1133 fatal (NILF, "Makefile from standard input specified twice.");
1135 outfile = fopen (name, "w");
1136 if (outfile == 0)
1137 pfatal_with_name ("fopen (temporary file)");
1138 while (!feof (stdin))
1140 char buf[2048];
1141 unsigned int n = fread (buf, 1, sizeof(buf), stdin);
1142 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1143 pfatal_with_name ("fwrite (temporary file)");
1145 (void) fclose (outfile);
1147 /* Replace the name that read_all_makefiles will
1148 see with the name of the temporary file. */
1150 char *temp;
1151 /* SGI compiler requires alloca's result be assigned simply. */
1152 temp = (char *) alloca (sizeof (name));
1153 bcopy (name, temp, sizeof (name));
1154 makefiles->list[i] = temp;
1157 /* Make sure the temporary file will not be remade. */
1158 stdin_nm = savestring (name, sizeof(name) -1);
1159 f = enter_file (stdin_nm);
1160 f->updated = 1;
1161 f->update_status = 0;
1162 f->command_state = cs_finished;
1163 /* Can't be intermediate, or it'll be removed too early for
1164 make re-exec. */
1165 f->intermediate = 0;
1166 f->dontcare = 0;
1170 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1171 /* If we don't have a hanging wait we have to fall back to old, broken
1172 functionality here and rely on the signal handler and counting
1173 children.
1175 Also, if we're using the jobs pipe we need a signal handler so that
1176 SIGCHLD is not ignored; we need it to interrupt select(2) in
1177 job.c:start_waiting_job() if we're waiting on the pipe for a token. */
1179 extern RETSIGTYPE child_handler PARAMS ((int sig));
1181 /* Set up to handle children dying. This must be done before
1182 reading in the makefiles so that `shell' function calls will work. */
1183 # if defined SIGCHLD
1184 (void) signal (SIGCHLD, child_handler);
1185 # endif
1186 # if defined SIGCLD && SIGCLD != SIGCHLD
1187 (void) signal (SIGCLD, child_handler);
1188 # endif
1190 #endif
1192 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1193 #ifdef SIGUSR1
1194 (void) signal (SIGUSR1, debug_signal_handler);
1195 #endif
1197 /* Define the initial list of suffixes for old-style rules. */
1199 set_default_suffixes ();
1201 /* Define the file rules for the built-in suffix rules. These will later
1202 be converted into pattern rules. We used to do this in
1203 install_default_implicit_rules, but since that happens after reading
1204 makefiles, it results in the built-in pattern rules taking precedence
1205 over makefile-specified suffix rules, which is wrong. */
1207 install_default_suffix_rules ();
1209 /* Define some internal and special variables. */
1211 define_automatic_variables ();
1213 /* Set up the MAKEFLAGS and MFLAGS variables
1214 so makefiles can look at them. */
1216 define_makeflags (0, 0);
1218 /* Define the default variables. */
1219 define_default_variables ();
1221 /* Read all the makefiles. */
1223 default_file = enter_file (".DEFAULT");
1225 read_makefiles
1226 = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
1228 #ifdef WINDOWS32
1229 /* look one last time after reading all Makefiles */
1230 if (no_default_sh_exe)
1231 no_default_sh_exe = !find_and_set_default_shell(NULL);
1233 if (no_default_sh_exe && job_slots != 1) {
1234 error (NILF, "Do not specify -j or --jobs if sh.exe is not available.");
1235 error (NILF, "Resetting make for single job mode.");
1236 job_slots = 1;
1238 #endif /* WINDOWS32 */
1240 #ifdef __MSDOS__
1241 /* We need to know what kind of shell we will be using. */
1243 extern int _is_unixy_shell (const char *_path);
1244 struct variable *shv = lookup_variable("SHELL", 5);
1245 extern int unixy_shell;
1246 extern char *default_shell;
1248 if (shv && *shv->value)
1250 char *shell_path = recursively_expand(shv);
1252 if (shell_path && _is_unixy_shell (shell_path))
1253 unixy_shell = 1;
1254 else
1255 unixy_shell = 0;
1256 if (shell_path)
1257 default_shell = shell_path;
1260 #endif /* __MSDOS__ */
1262 /* Decode switches again, in case the variables were set by the makefile. */
1263 decode_env_switches ("MAKEFLAGS", 9);
1264 #if 0
1265 decode_env_switches ("MFLAGS", 6);
1266 #endif
1268 #ifdef MAKE_JOBSERVER
1269 /* If extended jobs are available then the -j option can have one of 4
1270 formats: (1) not specified: default is "1"; (2) specified with no
1271 value: default is "0" (infinite); (3) specified with a single
1272 value: this means the user wants N job slots; or (4) specified with
1273 2 values separated by commas. The latter means we're a submake and
1274 the two values are the read and write FDs, respectively, for the
1275 pipe. Note this last form is undocumented for the user!
1277 sscanf(job_slots_str, "%d", &job_slots);
1279 char *cp = index(job_slots_str, ',');
1281 if (cp && sscanf(cp+1, "%d", &job_fds[1]) == 1)
1283 job_fds[0] = job_slots;
1284 job_slots = 0;
1288 /* In case #3 above, set up the pipe and set up the submake options
1289 properly. */
1291 if (job_slots > 1)
1293 char buf[(sizeof("1024")*2)+1];
1294 char c = '0';
1296 if (pipe(job_fds) < 0)
1297 pfatal_with_name("creating jobs pipe");
1299 /* Set the read FD to nonblocking; we'll use select() to wait
1300 for it in job.c. */
1301 fcntl (job_fds[0], F_SETFL, O_NONBLOCK);
1303 for (; job_slots; --job_slots)
1305 write(job_fds[1], &c, 1);
1306 if (c == '9')
1307 c = 'a';
1308 else if (c == 'z')
1309 c = 'A';
1310 else if (c == 'Z')
1311 c = '0'; /* Start over again!! */
1312 else
1313 ++c;
1316 sprintf(buf, "%d,%d", job_fds[0], job_fds[1]);
1317 job_slots_str = xstrdup(buf);
1319 #endif
1321 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1323 define_makeflags (1, 0);
1325 /* Make each `struct dep' point at the `struct file' for the file
1326 depended on. Also do magic for special targets. */
1328 snap_deps ();
1330 /* Convert old-style suffix rules to pattern rules. It is important to
1331 do this before installing the built-in pattern rules below, so that
1332 makefile-specified suffix rules take precedence over built-in pattern
1333 rules. */
1335 convert_to_pattern ();
1337 /* Install the default implicit pattern rules.
1338 This used to be done before reading the makefiles.
1339 But in that case, built-in pattern rules were in the chain
1340 before user-defined ones, so they matched first. */
1342 install_default_implicit_rules ();
1344 /* Compute implicit rule limits. */
1346 count_implicit_rule_limits ();
1348 /* Construct the listings of directories in VPATH lists. */
1350 build_vpath_lists ();
1352 /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
1353 and as having been updated already, and files given with -W flags as
1354 brand new (time-stamp as far as possible into the future). */
1356 if (old_files != 0)
1357 for (p = old_files->list; *p != 0; ++p)
1359 f = enter_command_line_file (*p);
1360 f->last_mtime = f->mtime_before_update = (FILE_TIMESTAMP) 1;
1361 f->updated = 1;
1362 f->update_status = 0;
1363 f->command_state = cs_finished;
1366 if (new_files != 0)
1368 for (p = new_files->list; *p != 0; ++p)
1370 f = enter_command_line_file (*p);
1371 f->last_mtime = f->mtime_before_update = NEW_MTIME;
1375 /* Initialize the remote job module. */
1376 remote_setup ();
1378 if (read_makefiles != 0)
1380 /* Update any makefiles if necessary. */
1382 FILE_TIMESTAMP *makefile_mtimes = 0;
1383 unsigned int mm_idx = 0;
1384 char **nargv = argv;
1385 int nargc = argc;
1387 if (debug_flag)
1388 puts ("Updating makefiles....");
1390 /* Remove any makefiles we don't want to try to update.
1391 Also record the current modtimes so we can compare them later. */
1393 register struct dep *d, *last;
1394 last = 0;
1395 d = read_makefiles;
1396 while (d != 0)
1398 register struct file *f = d->file;
1399 if (f->double_colon)
1400 for (f = f->double_colon; f != NULL; f = f->prev)
1402 if (f->deps == 0 && f->cmds != 0)
1404 /* This makefile is a :: target with commands, but
1405 no dependencies. So, it will always be remade.
1406 This might well cause an infinite loop, so don't
1407 try to remake it. (This will only happen if
1408 your makefiles are written exceptionally
1409 stupidly; but if you work for Athena, that's how
1410 you write your makefiles.) */
1412 if (debug_flag)
1413 printf ("Makefile `%s' might loop; not remaking it.\n",
1414 f->name);
1416 if (last == 0)
1417 read_makefiles = d->next;
1418 else
1419 last->next = d->next;
1421 /* Free the storage. */
1422 free ((char *) d);
1424 d = last == 0 ? read_makefiles : last->next;
1426 break;
1429 if (f == NULL || !f->double_colon)
1431 makefile_mtimes = (FILE_TIMESTAMP *)
1432 xrealloc ((char *) makefile_mtimes,
1433 (mm_idx + 1) * sizeof (FILE_TIMESTAMP));
1434 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
1435 last = d;
1436 d = d->next;
1441 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
1442 define_makeflags (1, 1);
1444 switch (update_goal_chain (read_makefiles, 1))
1446 case 1:
1447 default:
1448 #define BOGUS_UPDATE_STATUS 0
1449 assert (BOGUS_UPDATE_STATUS);
1450 break;
1452 case -1:
1453 /* Did nothing. */
1454 break;
1456 case 2:
1457 /* Failed to update. Figure out if we care. */
1459 /* Nonzero if any makefile was successfully remade. */
1460 int any_remade = 0;
1461 /* Nonzero if any makefile we care about failed
1462 in updating or could not be found at all. */
1463 int any_failed = 0;
1464 register unsigned int i;
1465 struct dep *d;
1467 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
1468 if (d->file->updated)
1470 /* This makefile was updated. */
1471 if (d->file->update_status == 0)
1473 /* It was successfully updated. */
1474 any_remade |= (file_mtime_no_search (d->file)
1475 != makefile_mtimes[i]);
1477 else if (! (d->changed & RM_DONTCARE))
1479 FILE_TIMESTAMP mtime;
1480 /* The update failed and this makefile was not
1481 from the MAKEFILES variable, so we care. */
1482 error (NILF, "Failed to remake makefile `%s'.",
1483 d->file->name);
1484 mtime = file_mtime_no_search (d->file);
1485 any_remade |= (mtime != (FILE_TIMESTAMP) -1
1486 && mtime != makefile_mtimes[i]);
1489 else
1490 /* This makefile was not found at all. */
1491 if (! (d->changed & RM_DONTCARE))
1493 /* This is a makefile we care about. See how much. */
1494 if (d->changed & RM_INCLUDED)
1495 /* An included makefile. We don't need
1496 to die, but we do want to complain. */
1497 error (NILF, "Included makefile `%s' was not found.",
1498 dep_name (d));
1499 else
1501 /* A normal makefile. We must die later. */
1502 error (NILF, "Makefile `%s' was not found",
1503 dep_name (d));
1504 any_failed = 1;
1507 /* Reset this to empty so we get the right error message below. */
1508 read_makefiles = 0;
1510 if (any_remade)
1511 goto re_exec;
1512 if (any_failed)
1513 die (2);
1514 break;
1517 case 0:
1518 re_exec:
1519 /* Updated successfully. Re-exec ourselves. */
1521 remove_intermediates (0);
1523 if (print_data_base_flag)
1524 print_data_base ();
1526 log_working_directory (0);
1528 if (makefiles != 0)
1530 /* These names might have changed. */
1531 register unsigned int i, j = 0;
1532 for (i = 1; i < argc; ++i)
1533 if (strneq (argv[i], "-f", 2)) /* XXX */
1535 char *p = &argv[i][2];
1536 if (*p == '\0')
1537 argv[++i] = makefiles->list[j];
1538 else
1539 argv[i] = concat ("-f", makefiles->list[j], "");
1540 ++j;
1544 /* Add -o option for the stdin temporary file, if necessary. */
1545 if (stdin_nm)
1547 nargv = (char **)xmalloc((nargc + 2) * sizeof(char *));
1548 bcopy((char *)argv, (char *)nargv, argc * sizeof(char *));
1549 nargv[nargc++] = concat("-o", stdin_nm, "");
1550 nargv[nargc] = 0;
1553 if (directories != 0 && directories->idx > 0)
1555 char bad;
1556 if (directory_before_chdir != 0)
1558 if (chdir (directory_before_chdir) < 0)
1560 perror_with_name ("chdir", "");
1561 bad = 1;
1563 else
1564 bad = 0;
1566 else
1567 bad = 1;
1568 if (bad)
1569 fatal (NILF, "Couldn't change back to original directory.");
1572 #ifndef _AMIGA
1573 for (p = environ; *p != 0; ++p)
1574 if (strneq (*p, "MAKELEVEL=", 10))
1576 /* The SGI compiler apparently can't understand
1577 the concept of storing the result of a function
1578 in something other than a local variable. */
1579 char *sgi_loses;
1580 sgi_loses = (char *) alloca (40);
1581 *p = sgi_loses;
1582 sprintf (*p, "MAKELEVEL=%u", makelevel);
1583 break;
1585 #else /* AMIGA */
1587 char buffer[256];
1588 int len;
1590 len = GetVar ("MAKELEVEL", buffer, sizeof (buffer), GVF_GLOBAL_ONLY);
1592 if (len != -1)
1594 sprintf (buffer, "%u", makelevel);
1595 SetVar ("MAKELEVEL", buffer, -1, GVF_GLOBAL_ONLY);
1598 #endif
1600 if (debug_flag)
1602 char **p;
1603 fputs ("Re-executing:", stdout);
1604 for (p = nargv; *p != 0; ++p)
1605 printf (" %s", *p);
1606 puts ("");
1609 fflush (stdout);
1610 fflush (stderr);
1612 #ifndef _AMIGA
1613 exec_command (nargv, environ);
1614 #else
1615 exec_command (nargv);
1616 exit (0);
1617 #endif
1618 /* NOTREACHED */
1622 /* Set up `MAKEFLAGS' again for the normal targets. */
1623 define_makeflags (1, 0);
1625 /* If there is a temp file from reading a makefile from stdin, get rid of
1626 it now. */
1627 if (stdin_nm && unlink(stdin_nm) < 0 && errno != ENOENT)
1628 perror_with_name("unlink (temporary file): ", stdin_nm);
1631 int status;
1633 /* If there were no command-line goals, use the default. */
1634 if (goals == 0)
1636 if (default_goal_file != 0)
1638 goals = (struct dep *) xmalloc (sizeof (struct dep));
1639 goals->next = 0;
1640 goals->name = 0;
1641 goals->file = default_goal_file;
1644 else
1645 lastgoal->next = 0;
1647 if (!goals)
1649 if (read_makefiles == 0)
1650 fatal (NILF, "No targets specified and no makefile found");
1652 fatal (NILF, "No targets");
1655 /* Update the goals. */
1657 if (debug_flag)
1658 puts ("Updating goal targets....");
1660 switch (update_goal_chain (goals, 0))
1662 case -1:
1663 /* Nothing happened. */
1664 case 0:
1665 /* Updated successfully. */
1666 status = EXIT_SUCCESS;
1667 break;
1668 case 2:
1669 /* Updating failed. POSIX.2 specifies exit status >1 for this;
1670 but in VMS, there is only success and failure. */
1671 status = EXIT_FAILURE ? 2 : EXIT_FAILURE;
1672 break;
1673 case 1:
1674 /* We are under -q and would run some commands. */
1675 status = EXIT_FAILURE;
1676 break;
1677 default:
1678 abort ();
1681 /* If we detected some clock skew, generate one last warning */
1682 if (clock_skew_detected)
1683 error (NILF, "*** Warning: Clock skew detected. Your build may be incomplete.");
1685 /* Exit. */
1686 die (status);
1689 return 0;
1692 /* Parsing of arguments, decoding of switches. */
1694 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
1695 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
1696 (sizeof (long_option_aliases) /
1697 sizeof (long_option_aliases[0]))];
1699 /* Fill in the string and vector for getopt. */
1700 static void
1701 init_switches ()
1703 register char *p;
1704 register int c;
1705 register unsigned int i;
1707 if (options[0] != '\0')
1708 /* Already done. */
1709 return;
1711 p = options;
1713 /* Return switch and non-switch args in order, regardless of
1714 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
1715 *p++ = '-';
1717 for (i = 0; switches[i].c != '\0'; ++i)
1719 long_options[i].name = (switches[i].long_name == 0 ? "" :
1720 switches[i].long_name);
1721 long_options[i].flag = 0;
1722 long_options[i].val = switches[i].c;
1723 if (isalnum (switches[i].c))
1724 *p++ = switches[i].c;
1725 switch (switches[i].type)
1727 case flag:
1728 case flag_off:
1729 case ignore:
1730 long_options[i].has_arg = no_argument;
1731 break;
1733 case int_string:
1734 case string:
1735 case positive_int:
1736 case floating:
1737 if (isalnum (switches[i].c))
1738 *p++ = ':';
1739 if (switches[i].noarg_value != 0)
1741 if (isalnum (switches[i].c))
1742 *p++ = ':';
1743 long_options[i].has_arg = optional_argument;
1745 else
1746 long_options[i].has_arg = required_argument;
1747 break;
1750 *p = '\0';
1751 for (c = 0; c < (sizeof (long_option_aliases) /
1752 sizeof (long_option_aliases[0]));
1753 ++c)
1754 long_options[i++] = long_option_aliases[c];
1755 long_options[i].name = 0;
1758 static void
1759 handle_non_switch_argument (arg, env)
1760 char *arg;
1761 int env;
1763 /* Non-option argument. It might be a variable definition. */
1764 struct variable *v;
1765 if (arg[0] == '-' && arg[1] == '\0')
1766 /* Ignore plain `-' for compatibility. */
1767 return;
1768 v = try_variable_definition (0, arg, o_command);
1769 if (v != 0)
1771 /* It is indeed a variable definition. Record a pointer to
1772 the variable for later use in define_makeflags. */
1773 struct command_variable *cv
1774 = (struct command_variable *) xmalloc (sizeof (*cv));
1775 cv->variable = v;
1776 cv->next = command_variables;
1777 command_variables = cv;
1779 else if (! env)
1781 /* Not an option or variable definition; it must be a goal
1782 target! Enter it as a file and add it to the dep chain of
1783 goals. */
1784 struct file *f = enter_command_line_file (arg);
1785 f->cmd_target = 1;
1787 if (goals == 0)
1789 goals = (struct dep *) xmalloc (sizeof (struct dep));
1790 lastgoal = goals;
1792 else
1794 lastgoal->next
1795 = (struct dep *) xmalloc (sizeof (struct dep));
1796 lastgoal = lastgoal->next;
1798 lastgoal->name = 0;
1799 lastgoal->file = f;
1802 /* Add this target name to the MAKECMDGOALS variable. */
1803 struct variable *v;
1804 char *value;
1806 v = lookup_variable("MAKECMDGOALS", 12);
1807 if (v == 0)
1808 value = f->name;
1809 else
1811 /* Paste the old and new values together */
1812 unsigned int oldlen, newlen;
1814 oldlen = strlen(v->value);
1815 newlen = strlen(f->name);
1816 value = (char *)alloca(oldlen + 1 + newlen + 1);
1817 bcopy(v->value, value, oldlen);
1818 value[oldlen] = ' ';
1819 bcopy(f->name, &value[oldlen + 1], newlen + 1);
1821 define_variable("MAKECMDGOALS", 12, value, o_default, 0);
1826 /* Print a nice usage method. */
1828 static void
1829 print_usage (bad)
1830 int bad;
1832 register const struct command_switch *cs;
1833 FILE *usageto;
1835 if (print_version_flag)
1836 print_version ();
1838 usageto = bad ? stderr : stdout;
1840 fprintf (usageto, "Usage: %s [options] [target] ...\n", program);
1842 fputs ("Options:\n", usageto);
1843 for (cs = switches; cs->c != '\0'; ++cs)
1845 char buf[1024], shortarg[50], longarg[50], *p;
1847 if (cs->description[0] == '-')
1848 continue;
1850 switch (long_options[cs - switches].has_arg)
1852 case no_argument:
1853 shortarg[0] = longarg[0] = '\0';
1854 break;
1855 case required_argument:
1856 sprintf (longarg, "=%s", cs->argdesc);
1857 sprintf (shortarg, " %s", cs->argdesc);
1858 break;
1859 case optional_argument:
1860 sprintf (longarg, "[=%s]", cs->argdesc);
1861 sprintf (shortarg, " [%s]", cs->argdesc);
1862 break;
1865 p = buf;
1867 if (isalnum (cs->c))
1869 sprintf (buf, " -%c%s", cs->c, shortarg);
1870 p += strlen (p);
1872 if (cs->long_name != 0)
1874 unsigned int i;
1875 sprintf (p, "%s--%s%s",
1876 !isalnum (cs->c) ? " " : ", ",
1877 cs->long_name, longarg);
1878 p += strlen (p);
1879 for (i = 0; i < (sizeof (long_option_aliases) /
1880 sizeof (long_option_aliases[0]));
1881 ++i)
1882 if (long_option_aliases[i].val == cs->c)
1884 sprintf (p, ", --%s%s",
1885 long_option_aliases[i].name, longarg);
1886 p += strlen (p);
1890 const struct command_switch *ncs = cs;
1891 while ((++ncs)->c != '\0')
1892 if (ncs->description[0] == '-' &&
1893 ncs->description[1] == cs->c)
1895 /* This is another switch that does the same
1896 one as the one we are processing. We want
1897 to list them all together on one line. */
1898 sprintf (p, ", -%c%s", ncs->c, shortarg);
1899 p += strlen (p);
1900 if (ncs->long_name != 0)
1902 sprintf (p, ", --%s%s", ncs->long_name, longarg);
1903 p += strlen (p);
1908 if (p - buf > DESCRIPTION_COLUMN - 2)
1909 /* The list of option names is too long to fit on the same
1910 line with the description, leaving at least two spaces.
1911 Print it on its own line instead. */
1913 fprintf (usageto, "%s\n", buf);
1914 buf[0] = '\0';
1917 fprintf (usageto, "%*s%s.\n",
1918 - DESCRIPTION_COLUMN,
1919 buf, cs->description);
1923 /* Decode switches from ARGC and ARGV.
1924 They came from the environment if ENV is nonzero. */
1926 static void
1927 decode_switches (argc, argv, env)
1928 int argc;
1929 char **argv;
1930 int env;
1932 int bad = 0;
1933 register const struct command_switch *cs;
1934 register struct stringlist *sl;
1935 register int c;
1937 /* getopt does most of the parsing for us.
1938 First, get its vectors set up. */
1940 init_switches ();
1942 /* Let getopt produce error messages for the command line,
1943 but not for options from the environment. */
1944 opterr = !env;
1945 /* Reset getopt's state. */
1946 optind = 0;
1948 while (optind < argc)
1950 /* Parse the next argument. */
1951 c = getopt_long (argc, argv, options, long_options, (int *) 0);
1952 if (c == EOF)
1953 /* End of arguments, or "--" marker seen. */
1954 break;
1955 else if (c == 1)
1956 /* An argument not starting with a dash. */
1957 handle_non_switch_argument (optarg, env);
1958 else if (c == '?')
1959 /* Bad option. We will print a usage message and die later.
1960 But continue to parse the other options so the user can
1961 see all he did wrong. */
1962 bad = 1;
1963 else
1964 for (cs = switches; cs->c != '\0'; ++cs)
1965 if (cs->c == c)
1967 /* Whether or not we will actually do anything with
1968 this switch. We test this individually inside the
1969 switch below rather than just once outside it, so that
1970 options which are to be ignored still consume args. */
1971 int doit = !env || cs->env;
1973 switch (cs->type)
1975 default:
1976 abort ();
1978 case ignore:
1979 break;
1981 case flag:
1982 case flag_off:
1983 if (doit)
1984 *(int *) cs->value_ptr = cs->type == flag;
1985 break;
1987 case int_string:
1988 if (optarg == 0 && argc > optind
1989 && isdigit (argv[optind][0]))
1990 optarg = argv[optind++];
1992 if (!doit)
1993 break;
1995 if (optarg == 0)
1996 optarg = cs->noarg_value;
1998 *(char **)cs->value_ptr = optarg;
1999 break;
2001 case string:
2002 if (!doit)
2003 break;
2005 if (optarg == 0)
2006 optarg = cs->noarg_value;
2008 sl = *(struct stringlist **) cs->value_ptr;
2009 if (sl == 0)
2011 sl = (struct stringlist *)
2012 xmalloc (sizeof (struct stringlist));
2013 sl->max = 5;
2014 sl->idx = 0;
2015 sl->list = (char **) xmalloc (5 * sizeof (char *));
2016 *(struct stringlist **) cs->value_ptr = sl;
2018 else if (sl->idx == sl->max - 1)
2020 sl->max += 5;
2021 sl->list = (char **)
2022 xrealloc ((char *) sl->list,
2023 sl->max * sizeof (char *));
2025 sl->list[sl->idx++] = optarg;
2026 sl->list[sl->idx] = 0;
2027 break;
2029 case positive_int:
2030 if (optarg == 0 && argc > optind
2031 && isdigit (argv[optind][0]))
2032 optarg = argv[optind++];
2034 if (!doit)
2035 break;
2037 if (optarg != 0)
2039 int i = atoi (optarg);
2040 if (i < 1)
2042 if (doit)
2043 error (NILF, "the `-%c' option requires a \
2044 positive integral argument",
2045 cs->c);
2046 bad = 1;
2048 else
2049 *(unsigned int *) cs->value_ptr = i;
2051 else
2052 *(unsigned int *) cs->value_ptr
2053 = *(unsigned int *) cs->noarg_value;
2054 break;
2056 #ifndef NO_FLOAT
2057 case floating:
2058 if (optarg == 0 && optind < argc
2059 && (isdigit (argv[optind][0]) || argv[optind][0] == '.'))
2060 optarg = argv[optind++];
2062 if (doit)
2063 *(double *) cs->value_ptr
2064 = (optarg != 0 ? atof (optarg)
2065 : *(double *) cs->noarg_value);
2067 break;
2068 #endif
2071 /* We've found the switch. Stop looking. */
2072 break;
2076 /* There are no more options according to getting getopt, but there may
2077 be some arguments left. Since we have asked for non-option arguments
2078 to be returned in order, this only happens when there is a "--"
2079 argument to prevent later arguments from being options. */
2080 while (optind < argc)
2081 handle_non_switch_argument (argv[optind++], env);
2084 if (!env && (bad || print_usage_flag))
2086 print_usage(bad);
2087 die (bad ? 2 : 0);
2091 /* Decode switches from environment variable ENVAR (which is LEN chars long).
2092 We do this by chopping the value into a vector of words, prepending a
2093 dash to the first word if it lacks one, and passing the vector to
2094 decode_switches. */
2096 static void
2097 decode_env_switches (envar, len)
2098 char *envar;
2099 unsigned int len;
2101 char *varref = (char *) alloca (2 + len + 2);
2102 char *value, *p;
2103 int argc;
2104 char **argv;
2106 /* Get the variable's value. */
2107 varref[0] = '$';
2108 varref[1] = '(';
2109 bcopy (envar, &varref[2], len);
2110 varref[2 + len] = ')';
2111 varref[2 + len + 1] = '\0';
2112 value = variable_expand (varref);
2114 /* Skip whitespace, and check for an empty value. */
2115 value = next_token (value);
2116 len = strlen (value);
2117 if (len == 0)
2118 return;
2120 /* Allocate a vector that is definitely big enough. */
2121 argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
2123 /* Allocate a buffer to copy the value into while we split it into words
2124 and unquote it. We must use permanent storage for this because
2125 decode_switches may store pointers into the passed argument words. */
2126 p = (char *) xmalloc (2 * len);
2128 /* getopt will look at the arguments starting at ARGV[1].
2129 Prepend a spacer word. */
2130 argv[0] = 0;
2131 argc = 1;
2132 argv[argc] = p;
2133 while (*value != '\0')
2135 if (*value == '\\')
2136 ++value; /* Skip the backslash. */
2137 else if (isblank (*value))
2139 /* End of the word. */
2140 *p++ = '\0';
2141 argv[++argc] = p;
2143 ++value;
2144 while (isblank (*value));
2145 continue;
2147 *p++ = *value++;
2149 *p = '\0';
2150 argv[++argc] = 0;
2152 if (argv[1][0] != '-' && index (argv[1], '=') == 0)
2153 /* The first word doesn't start with a dash and isn't a variable
2154 definition. Add a dash and pass it along to decode_switches. We
2155 need permanent storage for this in case decode_switches saves
2156 pointers into the value. */
2157 argv[1] = concat ("-", argv[1], "");
2159 /* Parse those words. */
2160 decode_switches (argc, argv, 1);
2163 /* Quote the string IN so that it will be interpreted as a single word with
2164 no magic by the shell; if DOUBLE_DOLLARS is nonzero, also double dollar
2165 signs to avoid variable expansion in make itself. Write the result into
2166 OUT, returning the address of the next character to be written.
2167 Allocating space for OUT twice the length of IN (thrice if
2168 DOUBLE_DOLLARS is nonzero) is always sufficient. */
2170 static char *
2171 quote_as_word (out, in, double_dollars)
2172 char *out, *in;
2173 int double_dollars;
2175 while (*in != '\0')
2177 #ifdef VMS
2178 if (index ("^;'\"*?$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2179 #else
2180 if (index ("^;'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2181 #endif
2182 *out++ = '\\';
2183 if (double_dollars && *in == '$')
2184 *out++ = '$';
2185 *out++ = *in++;
2188 return out;
2191 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2192 command switches. Include options with args if ALL is nonzero.
2193 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2195 static void
2196 define_makeflags (all, makefile)
2197 int all, makefile;
2199 static const char ref[] = "$(MAKEOVERRIDES)";
2200 static const char posixref[] = "$(-*-command-variables-*-)";
2201 register const struct command_switch *cs;
2202 char *flagstring;
2203 register char *p;
2204 unsigned int words;
2205 struct variable *v;
2207 /* We will construct a linked list of `struct flag's describing
2208 all the flags which need to go in MAKEFLAGS. Then, once we
2209 know how many there are and their lengths, we can put them all
2210 together in a string. */
2212 struct flag
2214 struct flag *next;
2215 const struct command_switch *cs;
2216 char *arg;
2218 struct flag *flags = 0;
2219 unsigned int flagslen = 0;
2220 #define ADD_FLAG(ARG, LEN) \
2221 do { \
2222 struct flag *new = (struct flag *) alloca (sizeof (struct flag)); \
2223 new->cs = cs; \
2224 new->arg = (ARG); \
2225 new->next = flags; \
2226 flags = new; \
2227 if (new->arg == 0) \
2228 ++flagslen; /* Just a single flag letter. */ \
2229 else \
2230 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2231 if (!isalnum (cs->c)) \
2232 /* This switch has no single-letter version, so we use the long. */ \
2233 flagslen += 2 + strlen (cs->long_name); \
2234 } while (0)
2236 for (cs = switches; cs->c != '\0'; ++cs)
2237 if (cs->toenv && (!makefile || !cs->no_makefile))
2238 switch (cs->type)
2240 default:
2241 abort ();
2243 case ignore:
2244 break;
2246 case flag:
2247 case flag_off:
2248 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2249 && (cs->default_value == 0
2250 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2251 ADD_FLAG (0, 0);
2252 break;
2254 case positive_int:
2255 if (all)
2257 if ((cs->default_value != 0
2258 && (*(unsigned int *) cs->value_ptr
2259 == *(unsigned int *) cs->default_value)))
2260 break;
2261 else if (cs->noarg_value != 0
2262 && (*(unsigned int *) cs->value_ptr ==
2263 *(unsigned int *) cs->noarg_value))
2264 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2265 else if (cs->c == 'j')
2266 /* Special case for `-j'. */
2267 ADD_FLAG ("1", 1);
2268 else
2270 char *buf = (char *) alloca (30);
2271 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
2272 ADD_FLAG (buf, strlen (buf));
2275 break;
2277 #ifndef NO_FLOAT
2278 case floating:
2279 if (all)
2281 if (cs->default_value != 0
2282 && (*(double *) cs->value_ptr
2283 == *(double *) cs->default_value))
2284 break;
2285 else if (cs->noarg_value != 0
2286 && (*(double *) cs->value_ptr
2287 == *(double *) cs->noarg_value))
2288 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2289 else
2291 char *buf = (char *) alloca (100);
2292 sprintf (buf, "%g", *(double *) cs->value_ptr);
2293 ADD_FLAG (buf, strlen (buf));
2296 break;
2297 #endif
2299 case int_string:
2300 if (all)
2302 char *vp = *(char **)cs->value_ptr;
2304 if (cs->default_value != 0
2305 && streq(vp, cs->default_value))
2306 break;
2307 if (cs->noarg_value != 0
2308 && streq(vp, cs->noarg_value))
2309 ADD_FLAG("", 0); /* Optional value omitted; see below. */
2310 else
2311 ADD_FLAG(vp, strlen(vp));
2313 break;
2315 case string:
2316 if (all)
2318 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
2319 if (sl != 0)
2321 /* Add the elements in reverse order, because
2322 all the flags get reversed below; and the order
2323 matters for some switches (like -I). */
2324 register unsigned int i = sl->idx;
2325 while (i-- > 0)
2326 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
2329 break;
2332 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
2334 #undef ADD_FLAG
2336 /* Construct the value in FLAGSTRING.
2337 We allocate enough space for a preceding dash and trailing null. */
2338 flagstring = (char *) alloca (1 + flagslen + 1);
2339 p = flagstring;
2340 words = 1;
2341 *p++ = '-';
2342 while (flags != 0)
2344 /* Add the flag letter or name to the string. */
2345 if (!isalnum (flags->cs->c))
2347 *p++ = '-';
2348 strcpy (p, flags->cs->long_name);
2349 p += strlen (p);
2351 else
2352 *p++ = flags->cs->c;
2353 if (flags->arg != 0)
2355 /* A flag that takes an optional argument which in this case is
2356 omitted is specified by ARG being "". We must distinguish
2357 because a following flag appended without an intervening " -"
2358 is considered the arg for the first. */
2359 if (flags->arg[0] != '\0')
2361 /* Add its argument too. */
2362 *p++ = !isalnum (flags->cs->c) ? '=' : ' ';
2363 p = quote_as_word (p, flags->arg, 1);
2365 ++words;
2366 /* Write a following space and dash, for the next flag. */
2367 *p++ = ' ';
2368 *p++ = '-';
2370 else if (!isalnum (flags->cs->c))
2372 ++words;
2373 /* Long options must each go in their own word,
2374 so we write the following space and dash. */
2375 *p++ = ' ';
2376 *p++ = '-';
2378 flags = flags->next;
2381 /* Define MFLAGS before appending variable definitions. */
2383 if (p == &flagstring[1])
2384 /* No flags. */
2385 flagstring[0] = '\0';
2386 else if (p[-1] == '-')
2388 /* Kill the final space and dash. */
2389 p -= 2;
2390 *p = '\0';
2392 else
2393 /* Terminate the string. */
2394 *p = '\0';
2396 /* Since MFLAGS is not parsed for flags, there is no reason to
2397 override any makefile redefinition. */
2398 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
2400 if (all && command_variables != 0)
2402 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
2403 command-line variable definitions. */
2405 if (p == &flagstring[1])
2406 /* No flags written, so elide the leading dash already written. */
2407 p = flagstring;
2408 else
2410 /* Separate the variables from the switches with a "--" arg. */
2411 if (p[-1] != '-')
2413 /* We did not already write a trailing " -". */
2414 *p++ = ' ';
2415 *p++ = '-';
2417 /* There is a trailing " -"; fill it out to " -- ". */
2418 *p++ = '-';
2419 *p++ = ' ';
2422 /* Copy in the string. */
2423 if (posix_pedantic)
2425 bcopy (posixref, p, sizeof posixref - 1);
2426 p += sizeof posixref - 1;
2428 else
2430 bcopy (ref, p, sizeof ref - 1);
2431 p += sizeof ref - 1;
2434 else if (p == &flagstring[1])
2436 words = 0;
2437 --p;
2439 else if (p[-1] == '-')
2440 /* Kill the final space and dash. */
2441 p -= 2;
2442 /* Terminate the string. */
2443 *p = '\0';
2445 v = define_variable ("MAKEFLAGS", 9,
2446 /* If there are switches, omit the leading dash
2447 unless it is a single long option with two
2448 leading dashes. */
2449 &flagstring[(flagstring[0] == '-'
2450 && flagstring[1] != '-')
2451 ? 1 : 0],
2452 /* This used to use o_env, but that lost when a
2453 makefile defined MAKEFLAGS. Makefiles set
2454 MAKEFLAGS to add switches, but we still want
2455 to redefine its value with the full set of
2456 switches. Of course, an override or command
2457 definition will still take precedence. */
2458 o_file, 1);
2459 if (! all)
2460 /* The first time we are called, set MAKEFLAGS to always be exported.
2461 We should not do this again on the second call, because that is
2462 after reading makefiles which might have done `unexport MAKEFLAGS'. */
2463 v->export = v_export;
2466 /* Print version information. */
2468 static void
2469 print_version ()
2471 static int printed_version = 0;
2473 char *precede = print_data_base_flag ? "# " : "";
2475 if (printed_version)
2476 /* Do it only once. */
2477 return;
2479 printf ("%sGNU Make version %s", precede, version_string);
2480 if (remote_description != 0 && *remote_description != '\0')
2481 printf ("-%s", remote_description);
2483 printf (", by Richard Stallman and Roland McGrath.\n\
2484 %sCopyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99\n\
2485 %s\tFree Software Foundation, Inc.\n\
2486 %sThis is free software; see the source for copying conditions.\n\
2487 %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
2488 %sPARTICULAR PURPOSE.\n\n\
2489 %sReport bugs to <bug-make@gnu.org>.\n\n",
2490 precede, precede, precede, precede, precede, precede);
2492 printed_version = 1;
2494 /* Flush stdout so the user doesn't have to wait to see the
2495 version information while things are thought about. */
2496 fflush (stdout);
2499 /* Print a bunch of information about this and that. */
2501 static void
2502 print_data_base ()
2504 time_t when;
2506 when = time ((time_t *) 0);
2507 printf ("\n# Make data base, printed on %s", ctime (&when));
2509 print_variable_data_base ();
2510 print_dir_data_base ();
2511 print_rule_data_base ();
2512 print_file_data_base ();
2513 print_vpath_data_base ();
2515 when = time ((time_t *) 0);
2516 printf ("\n# Finished Make data base on %s\n", ctime (&when));
2519 /* Exit with STATUS, cleaning up as necessary. */
2521 void
2522 die (status)
2523 int status;
2525 static char dying = 0;
2527 if (!dying)
2529 int err;
2531 dying = 1;
2533 if (print_version_flag)
2534 print_version ();
2536 /* Wait for children to die. */
2537 for (err = status != 0; job_slots_used > 0; err = 0)
2538 reap_children (1, err);
2540 /* Let the remote job module clean up its state. */
2541 remote_cleanup ();
2543 /* Remove the intermediate files. */
2544 remove_intermediates (0);
2546 if (print_data_base_flag)
2547 print_data_base ();
2549 /* Try to move back to the original directory. This is essential on
2550 MS-DOS (where there is really only one process), and on Unix it
2551 puts core files in the original directory instead of the -C
2552 directory. Must wait until after remove_intermediates(), or unlinks
2553 of relative pathnames fail. */
2554 if (directory_before_chdir != 0)
2555 chdir (directory_before_chdir);
2557 log_working_directory (0);
2560 exit (status);
2563 /* Write a message indicating that we've just entered or
2564 left (according to ENTERING) the current directory. */
2566 void
2567 log_working_directory (entering)
2568 int entering;
2570 static int entered = 0;
2571 char *msg = entering ? "Entering" : "Leaving";
2573 /* Print nothing without the flag. Don't print the entering message
2574 again if we already have. Don't print the leaving message if we
2575 haven't printed the entering message. */
2576 if (! print_directory_flag || entering == entered)
2577 return;
2579 entered = entering;
2581 if (print_data_base_flag)
2582 fputs ("# ", stdout);
2584 if (makelevel == 0)
2585 printf ("%s: %s ", program, msg);
2586 else
2587 printf ("%s[%u]: %s ", program, makelevel, msg);
2589 if (starting_directory == 0)
2590 puts ("an unknown directory");
2591 else
2592 printf ("directory `%s'\n", starting_directory);