Changes for GNU make 3.76
[make.git] / main.c
blob11bfc8832d84e4a2e28c38c51be062920d9379fb
1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988,89,90,91,94,95,96,97 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "dep.h"
21 #include "filedef.h"
22 #include "variable.h"
23 #include "job.h"
24 #include "commands.h"
25 #include "getopt.h"
26 #include <assert.h>
27 #ifdef _AMIGA
28 # include <dos/dos.h>
29 # include <proto/dos.h>
30 #endif
31 #ifdef WINDOWS32
32 #include <windows.h>
33 #include "pathstuff.h"
34 #endif
36 #ifdef _AMIGA
37 int __stack = 20000; /* Make sure we have 20K of stack space */
38 #endif
40 extern void init_dir PARAMS ((void));
41 extern void remote_setup PARAMS ((void));
42 extern void remote_cleanup PARAMS ((void));
43 extern RETSIGTYPE fatal_error_signal PARAMS ((int sig));
44 extern RETSIGTYPE child_handler PARAMS ((int sig));
46 extern void print_variable_data_base PARAMS ((void));
47 extern void print_dir_data_base PARAMS ((void));
48 extern void print_rule_data_base PARAMS ((void));
49 extern void print_file_data_base PARAMS ((void));
50 extern void print_vpath_data_base PARAMS ((void));
52 #ifndef HAVE_UNISTD_H
53 extern int chdir ();
54 #endif
55 #ifndef STDC_HEADERS
56 #ifndef sun /* Sun has an incorrect decl in a header. */
57 extern void exit ();
58 #endif
59 extern double atof ();
60 #endif
61 extern char *mktemp ();
63 static void print_data_base PARAMS((void));
64 static void print_version PARAMS ((void));
65 static void decode_switches PARAMS ((int argc, char **argv, int env));
66 static void decode_env_switches PARAMS ((char *envar, unsigned int len));
67 static void define_makeflags PARAMS ((int all, int makefile));
68 static char *quote_as_word PARAMS ((char *out, char *in, int double_dollars));
70 /* The structure that describes an accepted command switch. */
72 struct command_switch
74 char c; /* The switch character. */
76 enum /* Type of the value. */
78 flag, /* Turn int flag on. */
79 flag_off, /* Turn int flag off. */
80 string, /* One string per switch. */
81 positive_int, /* A positive integer. */
82 floating, /* A floating-point number (double). */
83 ignore /* Ignored. */
84 } type;
86 char *value_ptr; /* Pointer to the value-holding variable. */
88 unsigned int env:1; /* Can come from MAKEFLAGS. */
89 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
90 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
92 char *noarg_value; /* Pointer to value used if no argument is given. */
93 char *default_value;/* Pointer to default value. */
95 char *long_name; /* Long option name. */
96 char *argdesc; /* Descriptive word for argument. */
97 char *description; /* Description for usage message. */
101 /* The structure used to hold the list of strings given
102 in command switches of a type that takes string arguments. */
104 struct stringlist
106 char **list; /* Nil-terminated list of strings. */
107 unsigned int idx; /* Index into above. */
108 unsigned int max; /* Number of pointers allocated. */
112 /* The recognized command switches. */
114 /* Nonzero means do not print commands to be executed (-s). */
116 int silent_flag;
118 /* Nonzero means just touch the files
119 that would appear to need remaking (-t) */
121 int touch_flag;
123 /* Nonzero means just print what commands would need to be executed,
124 don't actually execute them (-n). */
126 int just_print_flag;
128 /* Print debugging trace info (-d). */
130 int debug_flag = 0;
132 #ifdef WINDOWS32
133 /* Suspend make in main for a short time to allow debugger to attach */
135 int suspend_flag = 0;
136 #endif
138 /* Environment variables override makefile definitions. */
140 int env_overrides = 0;
142 /* Nonzero means ignore status codes returned by commands
143 executed to remake files. Just treat them all as successful (-i). */
145 int ignore_errors_flag = 0;
147 /* Nonzero means don't remake anything, just print the data base
148 that results from reading the makefile (-p). */
150 int print_data_base_flag = 0;
152 /* Nonzero means don't remake anything; just return a nonzero status
153 if the specified targets are not up to date (-q). */
155 int question_flag = 0;
157 /* Nonzero means do not use any of the builtin rules (-r). */
159 int no_builtin_rules_flag = 0;
161 /* Nonzero means keep going even if remaking some file fails (-k). */
163 int keep_going_flag;
164 int default_keep_going_flag = 0;
166 /* Nonzero means print directory before starting and when done (-w). */
168 int print_directory_flag = 0;
170 /* Nonzero means ignore print_directory_flag and never print the directory.
171 This is necessary because print_directory_flag is set implicitly. */
173 int inhibit_print_directory_flag = 0;
175 /* Nonzero means print version information. */
177 int print_version_flag = 0;
179 /* List of makefiles given with -f switches. */
181 static struct stringlist *makefiles = 0;
184 /* Number of job slots (commands that can be run at once). */
186 unsigned int job_slots = 1;
187 unsigned int default_job_slots = 1;
189 /* Value of job_slots that means no limit. */
191 static unsigned int inf_jobs = 0;
193 /* Maximum load average at which multiple jobs will be run.
194 Negative values mean unlimited, while zero means limit to
195 zero load (which could be useful to start infinite jobs remotely
196 but one at a time locally). */
197 #ifndef NO_FLOAT
198 double max_load_average = -1.0;
199 double default_load_average = -1.0;
200 #else
201 int max_load_average = -1;
202 int default_load_average = -1;
203 #endif
205 /* List of directories given with -C switches. */
207 static struct stringlist *directories = 0;
209 /* List of include directories given with -I switches. */
211 static struct stringlist *include_directories = 0;
213 /* List of files given with -o switches. */
215 static struct stringlist *old_files = 0;
217 /* List of files given with -W switches. */
219 static struct stringlist *new_files = 0;
221 /* If nonzero, we should just print usage and exit. */
223 static int print_usage_flag = 0;
225 /* If nonzero, we should print a warning message
226 for each reference to an undefined variable. */
228 int warn_undefined_variables_flag;
230 /* The table of command switches. */
232 static const struct command_switch switches[] =
234 { 'b', ignore, 0, 0, 0, 0, 0, 0,
235 0, 0,
236 "Ignored for compatibility" },
237 { 'C', string, (char *) &directories, 0, 0, 0, 0, 0,
238 "directory", "DIRECTORY",
239 "Change to DIRECTORY before doing anything" },
240 { 'd', flag, (char *) &debug_flag, 1, 1, 0, 0, 0,
241 "debug", 0,
242 "Print lots of debugging information" },
243 #ifdef WINDOWS32
244 { 'D', flag, (char *) &suspend_flag, 1, 1, 0, 0, 0,
245 "suspend-for-debug", 0,
246 "Suspend process to allow a debugger to attach" },
247 #endif
248 { 'e', flag, (char *) &env_overrides, 1, 1, 0, 0, 0,
249 "environment-overrides", 0,
250 "Environment variables override makefiles" },
251 { 'f', string, (char *) &makefiles, 0, 0, 0, 0, 0,
252 "file", "FILE",
253 "Read FILE as a makefile" },
254 { 'h', flag, (char *) &print_usage_flag, 0, 0, 0, 0, 0,
255 "help", 0,
256 "Print this message and exit" },
257 { 'i', flag, (char *) &ignore_errors_flag, 1, 1, 0, 0, 0,
258 "ignore-errors", 0,
259 "Ignore errors from commands" },
260 { 'I', string, (char *) &include_directories, 1, 1, 0, 0, 0,
261 "include-dir", "DIRECTORY",
262 "Search DIRECTORY for included makefiles" },
263 { 'j', positive_int, (char *) &job_slots, 1, 1, 0,
264 (char *) &inf_jobs, (char *) &default_job_slots,
265 "jobs", "N",
266 "Allow N jobs at once; infinite jobs with no arg" },
267 { 'k', flag, (char *) &keep_going_flag, 1, 1, 0,
268 0, (char *) &default_keep_going_flag,
269 "keep-going", 0,
270 "Keep going when some targets can't be made" },
271 #ifndef NO_FLOAT
272 { 'l', floating, (char *) &max_load_average, 1, 1, 0,
273 (char *) &default_load_average, (char *) &default_load_average,
274 "load-average", "N",
275 "Don't start multiple jobs unless load is below N" },
276 #else
277 { 'l', positive_int, (char *) &max_load_average, 1, 1, 0,
278 (char *) &default_load_average, (char *) &default_load_average,
279 "load-average", "N",
280 "Don't start multiple jobs unless load is below N" },
281 #endif
282 { 'm', ignore, 0, 0, 0, 0, 0, 0,
283 0, 0,
284 "-b" },
285 { 'n', flag, (char *) &just_print_flag, 1, 1, 1, 0, 0,
286 "just-print", 0,
287 "Don't actually run any commands; just print them" },
288 { 'o', string, (char *) &old_files, 0, 0, 0, 0, 0,
289 "old-file", "FILE",
290 "Consider FILE to be very old and don't remake it" },
291 { 'p', flag, (char *) &print_data_base_flag, 1, 1, 0, 0, 0,
292 "print-data-base", 0,
293 "Print make's internal database" },
294 { 'q', flag, (char *) &question_flag, 1, 1, 1, 0, 0,
295 "question", 0,
296 "Run no commands; exit status says if up to date" },
297 { 'r', flag, (char *) &no_builtin_rules_flag, 1, 1, 0, 0, 0,
298 "no-builtin-rules", 0,
299 "Disable the built-in implicit rules" },
300 { 's', flag, (char *) &silent_flag, 1, 1, 0, 0, 0,
301 "silent", 0,
302 "Don't echo commands" },
303 { 'S', flag_off, (char *) &keep_going_flag, 1, 1, 0,
304 0, (char *) &default_keep_going_flag,
305 "no-keep-going", 0,
306 "Turns off -k" },
307 { 't', flag, (char *) &touch_flag, 1, 1, 1, 0, 0,
308 "touch", 0,
309 "Touch targets instead of remaking them" },
310 { 'v', flag, (char *) &print_version_flag, 1, 1, 0, 0, 0,
311 "version", 0,
312 "Print the version number of make and exit" },
313 { 'w', flag, (char *) &print_directory_flag, 1, 1, 0, 0, 0,
314 "print-directory", 0,
315 "Print the current directory" },
316 { 2, flag, (char *) &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
317 "no-print-directory", 0,
318 "Turn off -w, even if it was turned on implicitly" },
319 { 'W', string, (char *) &new_files, 0, 0, 0, 0, 0,
320 "what-if", "FILE",
321 "Consider FILE to be infinitely new" },
322 { 3, flag, (char *) &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
323 "warn-undefined-variables", 0,
324 "Warn when an undefined variable is referenced" },
325 { '\0', }
328 /* Secondary long names for options. */
330 static struct option long_option_aliases[] =
332 { "quiet", no_argument, 0, 's' },
333 { "stop", no_argument, 0, 'S' },
334 { "new-file", required_argument, 0, 'W' },
335 { "assume-new", required_argument, 0, 'W' },
336 { "assume-old", required_argument, 0, 'o' },
337 { "max-load", optional_argument, 0, 'l' },
338 { "dry-run", no_argument, 0, 'n' },
339 { "recon", no_argument, 0, 'n' },
340 { "makefile", required_argument, 0, 'f' },
343 /* The usage message prints the descriptions of options starting in
344 this column. Make sure it leaves enough room for the longest
345 description to fit in less than 80 characters. */
347 #define DESCRIPTION_COLUMN 30
349 /* List of goal targets. */
351 static struct dep *goals, *lastgoal;
353 /* List of variables which were defined on the command line
354 (or, equivalently, in MAKEFLAGS). */
356 struct command_variable
358 struct command_variable *next;
359 struct variable *variable;
361 static struct command_variable *command_variables;
363 /* The name we were invoked with. */
365 char *program;
367 /* Our current directory before processing any -C options. */
369 char *directory_before_chdir;
371 /* Our current directory after processing all -C options. */
373 char *starting_directory;
375 /* Value of the MAKELEVEL variable at startup (or 0). */
377 unsigned int makelevel;
379 /* First file defined in the makefile whose name does not
380 start with `.'. This is the default to remake if the
381 command line does not specify. */
383 struct file *default_goal_file;
385 /* Pointer to structure for the file .DEFAULT
386 whose commands are used for any file that has none of its own.
387 This is zero if the makefiles do not define .DEFAULT. */
389 struct file *default_file;
391 /* Nonzero if we have seen the magic `.POSIX' target.
392 This turns on pedantic compliance with POSIX.2. */
394 int posix_pedantic;
396 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
397 print one warning about it during the run, and (b) we can print a final
398 warning at the end of the run. */
400 int clock_skew_detected;
402 /* Mask of signals that are being caught with fatal_error_signal. */
404 #ifdef POSIX
405 sigset_t fatal_signal_set;
406 #else
407 #ifdef HAVE_SIGSETMASK
408 int fatal_signal_mask;
409 #endif
410 #endif
412 static struct file *
413 enter_command_line_file (name)
414 char *name;
416 if (name[0] == '\0')
417 fatal ("empty string invalid as file name");
419 if (name[0] == '~')
421 char *expanded = tilde_expand (name);
422 if (expanded != 0)
423 name = expanded; /* Memory leak; I don't care. */
426 /* This is also done in parse_file_seq, so this is redundant
427 for names read from makefiles. It is here for names passed
428 on the command line. */
429 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
431 name += 2;
432 while (*name == '/')
433 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
434 ++name;
437 if (*name == '\0')
439 /* It was all slashes! Move back to the dot and truncate
440 it after the first slash, so it becomes just "./". */
442 --name;
443 while (name[0] != '.');
444 name[2] = '\0';
447 return enter_file (savestring (name, strlen (name)));
450 /* Toggle -d on receipt of SIGUSR1. */
452 static RETSIGTYPE
453 debug_signal_handler (sig)
454 int sig;
456 debug_flag = ! debug_flag;
459 #ifdef WINDOWS32
461 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
462 * exception and print it to stderr instead.
464 * If debug_flag not set, just print a simple message and exit.
465 * If debug_flag set, print a more verbose message.
466 * If compiled for DEBUG, let exception pass through to GUI so that
467 * debuggers can attach.
469 LONG WINAPI
470 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
472 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
473 LPSTR cmdline = GetCommandLine();
474 LPSTR prg = strtok(cmdline, " ");
475 CHAR errmsg[1024];
476 #ifdef USE_EVENT_LOG
477 HANDLE hEventSource;
478 LPTSTR lpszStrings[1];
479 #endif
481 if (!debug_flag)
483 sprintf(errmsg, "%s: Interrupt/Exception caught ", prg);
484 sprintf(&errmsg[strlen(errmsg)],
485 "(code = 0x%x, addr = 0x%x)\r\n",
486 exrec->ExceptionCode, exrec->ExceptionAddress);
487 fprintf(stderr, errmsg);
488 exit(255);
491 sprintf(errmsg,
492 "\r\nUnhandled exception filter called from program %s\r\n", prg);
493 sprintf(&errmsg[strlen(errmsg)], "ExceptionCode = %x\r\n",
494 exrec->ExceptionCode);
495 sprintf(&errmsg[strlen(errmsg)], "ExceptionFlags = %x\r\n",
496 exrec->ExceptionFlags);
497 sprintf(&errmsg[strlen(errmsg)], "ExceptionAddress = %x\r\n",
498 exrec->ExceptionAddress);
500 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
501 && exrec->NumberParameters >= 2)
502 sprintf(&errmsg[strlen(errmsg)],
503 "Access violation: %s operation at address %x\r\n",
504 exrec->ExceptionInformation[0] ? "write": "read",
505 exrec->ExceptionInformation[1]);
507 /* turn this on if we want to put stuff in the event log too */
508 #ifdef USE_EVENT_LOG
509 hEventSource = RegisterEventSource(NULL, "GNU Make");
510 lpszStrings[0] = errmsg;
512 if (hEventSource != NULL)
514 ReportEvent(hEventSource, /* handle of event source */
515 EVENTLOG_ERROR_TYPE, /* event type */
516 0, /* event category */
517 0, /* event ID */
518 NULL, /* current user's SID */
519 1, /* strings in lpszStrings */
520 0, /* no bytes of raw data */
521 lpszStrings, /* array of error strings */
522 NULL); /* no raw data */
524 (VOID) DeregisterEventSource(hEventSource);
526 #endif
528 /* Write the error to stderr too */
529 fprintf(stderr, errmsg);
531 #ifdef DEBUG
532 return EXCEPTION_CONTINUE_SEARCH;
533 #else
534 exit(255);
535 #endif
537 #endif /* WINDOWS32 */
539 #ifdef __MSDOS__
541 static void
542 msdos_return_to_initial_directory ()
544 if (directory_before_chdir)
545 chdir (directory_before_chdir);
547 #endif
549 #ifndef _AMIGA
551 main (argc, argv, envp)
552 int argc;
553 char **argv;
554 char **envp;
555 #else
556 int main (int argc, char ** argv)
557 #endif
559 register struct file *f;
560 register unsigned int i;
561 char **p;
562 struct dep *read_makefiles;
563 PATH_VAR (current_directory);
564 #ifdef WINDOWS32
565 extern int no_default_sh_exe;
566 char *unix_path = NULL;
567 char *windows32_path = NULL;
569 SetUnhandledExceptionFilter(handle_runtime_exceptions);
570 #endif
572 default_goal_file = 0;
573 reading_filename = 0;
574 reading_lineno_ptr = 0;
576 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
577 /* Request the most powerful version of `system', to
578 make up for the dumb default shell. */
579 __system_flags = (__system_redirect
580 | __system_use_shell
581 | __system_allow_multiple_cmds
582 | __system_allow_long_cmds
583 | __system_handle_null_commands
584 | __system_emulate_chdir);
586 #endif
588 #if !defined (HAVE_STRSIGNAL) && !defined (HAVE_SYS_SIGLIST)
589 signame_init ();
590 #endif
592 #ifdef POSIX
593 sigemptyset (&fatal_signal_set);
594 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
595 #else
596 #ifdef HAVE_SIGSETMASK
597 fatal_signal_mask = 0;
598 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
599 #else
600 #define ADD_SIG(sig)
601 #endif
602 #endif
604 #define FATAL_SIG(sig) \
605 if (signal ((sig), fatal_error_signal) == SIG_IGN) \
606 (void) signal ((sig), SIG_IGN); \
607 else \
608 ADD_SIG (sig);
610 #ifdef SIGHUP
611 FATAL_SIG (SIGHUP);
612 #endif
613 #ifdef SIGQUIT
614 FATAL_SIG (SIGQUIT);
615 #endif
616 FATAL_SIG (SIGINT);
617 FATAL_SIG (SIGTERM);
619 #ifdef SIGDANGER
620 FATAL_SIG (SIGDANGER);
621 #endif
622 #ifdef SIGXCPU
623 FATAL_SIG (SIGXCPU);
624 #endif
625 #ifdef SIGXFSZ
626 FATAL_SIG (SIGXFSZ);
627 #endif
629 #undef FATAL_SIG
631 /* Make sure stdout is line-buffered. */
633 #ifdef HAVE_SETLINEBUF
634 setlinebuf (stdout);
635 #else
636 #ifndef SETVBUF_REVERSED
637 setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
638 #else /* setvbuf not reversed. */
639 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
640 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
641 #endif /* setvbuf reversed. */
642 #endif /* setlinebuf missing. */
644 /* Figure out where this program lives. */
646 if (argv[0] == 0)
647 argv[0] = "";
648 if (argv[0][0] == '\0')
649 program = "make";
650 else
652 #ifdef VMS
653 program = rindex (argv[0], ']');
654 #else
655 program = rindex (argv[0], '/');
656 #endif
657 #ifdef __MSDOS__
658 if (program == 0)
659 program = rindex (argv[0], '\\');
660 else
662 /* Some weird environments might pass us argv[0] with
663 both kinds of slashes; we must find the rightmost. */
664 char *p = rindex (argv[0], '\\');
665 if (p && p > program)
666 program = p;
668 if (program == 0 && argv[0][1] == ':')
669 program = argv[0] + 1;
670 #endif
671 if (program == 0)
672 program = argv[0];
673 else
674 ++program;
677 /* Set up to access user data (files). */
678 user_access ();
680 /* Figure out where we are. */
682 #ifdef WINDOWS32
683 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
684 #else
685 if (getcwd (current_directory, GET_PATH_MAX) == 0)
686 #endif
688 #ifdef HAVE_GETCWD
689 perror_with_name ("getcwd: ", "");
690 #else
691 error ("getwd: %s", current_directory);
692 #endif
693 current_directory[0] = '\0';
694 directory_before_chdir = 0;
696 else
697 directory_before_chdir = savestring (current_directory,
698 strlen (current_directory));
699 #ifdef __MSDOS__
700 /* Make sure we will return to the initial directory, come what may. */
701 atexit (msdos_return_to_initial_directory);
702 #endif
704 /* Read in variables from the environment. It is important that this be
705 done before $(MAKE) is figured out so its definitions will not be
706 from the environment. */
708 #ifndef _AMIGA
709 for (i = 0; envp[i] != 0; ++i)
711 register char *ep = envp[i];
712 while (*ep != '=')
713 ++ep;
714 #ifdef WINDOWS32
715 if (!unix_path && !strncmp(envp[i], "PATH=", 5))
716 unix_path = ep+1;
717 if (!windows32_path && !strncmp(envp[i], "Path=", 5))
718 windows32_path = ep+1;
719 #endif
720 /* The result of pointer arithmetic is cast to unsigned int for
721 machines where ptrdiff_t is a different size that doesn't widen
722 the same. */
723 define_variable (envp[i], (unsigned int) (ep - envp[i]),
724 ep + 1, o_env, 1)
725 /* Force exportation of every variable culled from the environment.
726 We used to rely on target_environment's v_default code to do this.
727 But that does not work for the case where an environment variable
728 is redefined in a makefile with `override'; it should then still
729 be exported, because it was originally in the environment. */
730 ->export = v_export;
732 #ifdef WINDOWS32
734 * PATH defaults to Path iff PATH not found and Path is found.
736 if (!unix_path && windows32_path)
737 define_variable("PATH", 4, windows32_path, o_env, 1)->export = v_export;
738 #endif
739 #else /* For Amiga, read the ENV: device, ignoring all dirs */
741 BPTR env, file, old;
742 char buffer[1024];
743 int len;
744 __aligned struct FileInfoBlock fib;
746 env = Lock ("ENV:", ACCESS_READ);
747 if (env)
749 old = CurrentDir (DupLock(env));
750 Examine (env, &fib);
752 while (ExNext (env, &fib))
754 if (fib.fib_DirEntryType < 0) /* File */
756 /* Define an empty variable. It will be filled in
757 variable_lookup(). Makes startup quite a bit
758 faster. */
759 define_variable (fib.fib_FileName,
760 strlen (fib.fib_FileName),
761 "", o_env, 1)->export = v_export;
764 UnLock (env);
765 UnLock(CurrentDir(old));
768 #endif
770 /* Decode the switches. */
772 decode_env_switches ("MAKEFLAGS", 9);
773 #if 0
774 /* People write things like:
775 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
776 and we set the -p, -i and -e switches. Doesn't seem quite right. */
777 decode_env_switches ("MFLAGS", 6);
778 #endif
779 decode_switches (argc, argv, 0);
780 #ifdef WINDOWS32
781 if (suspend_flag) {
782 fprintf(stderr, "%s (pid = %d)\n", argv[0], GetCurrentProcessId());
783 fprintf(stderr, "%s is suspending for 30 seconds...", argv[0]);
784 Sleep(30 * 1000);
785 fprintf(stderr, "done sleep(30). Continuing.\n");
787 #endif
789 /* Print version information. */
791 if (print_version_flag || print_data_base_flag || debug_flag)
792 print_version ();
794 /* `make --version' is supposed to just print the version and exit. */
795 if (print_version_flag)
796 die (0);
798 #if !defined(__MSDOS__) && !defined(VMS)
799 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
800 (If it is a relative pathname with a slash, prepend our directory name
801 so the result will run the same program regardless of the current dir.
802 If it is a name with no slash, we can only hope that PATH did not
803 find it in the current directory.) */
804 #ifdef WINDOWS32
806 * Convert from backslashes to forward slashes for
807 * programs like sh which don't like them. Shouldn't
808 * matter if the path is one way or the other for
809 * CreateProcess().
811 if (strpbrk(argv[0], "/:\\") ||
812 strstr(argv[0], "..") ||
813 !strncmp(argv[0], "//", 2))
814 argv[0] = strdup(w32ify(argv[0],1));
815 #else /* WINDOWS32 */
816 if (current_directory[0] != '\0'
817 && argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
818 argv[0] = concat (current_directory, "/", argv[0]);
819 #endif /* WINDOWS32 */
820 #endif
822 /* The extra indirection through $(MAKE_COMMAND) is done
823 for hysterical raisins. */
824 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
825 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
827 if (command_variables != 0)
829 struct command_variable *cv;
830 struct variable *v;
831 unsigned int len = 0;
832 char *value, *p;
834 /* Figure out how much space will be taken up by the command-line
835 variable definitions. */
836 for (cv = command_variables; cv != 0; cv = cv->next)
838 v = cv->variable;
839 len += 2 * strlen (v->name);
840 if (! v->recursive)
841 ++len;
842 ++len;
843 len += 2 * strlen (v->value);
846 /* Now allocate a buffer big enough and fill it. */
847 p = value = (char *) alloca (len);
848 for (cv = command_variables; cv != 0; cv = cv->next)
850 v = cv->variable;
851 p = quote_as_word (p, v->name, 0);
852 if (! v->recursive)
853 *p++ = ':';
854 *p++ = '=';
855 p = quote_as_word (p, v->value, 0);
856 *p++ = ' ';
858 p[-1] = '\0'; /* Kill the final space and terminate. */
860 /* Define an unchangeable variable with a name that no POSIX.2
861 makefile could validly use for its own variable. */
862 (void) define_variable ("-*-command-variables-*-", 23,
863 value, o_automatic, 0);
865 /* Define the variable; this will not override any user definition.
866 Normally a reference to this variable is written into the value of
867 MAKEFLAGS, allowing the user to override this value to affect the
868 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
869 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
870 a reference to this hidden variable is written instead. */
871 (void) define_variable ("MAKEOVERRIDES", 13,
872 "${-*-command-variables-*-}", o_env, 1);
875 /* If there were -C flags, move ourselves about. */
876 if (directories != 0)
877 for (i = 0; directories->list[i] != 0; ++i)
879 char *dir = directories->list[i];
880 if (dir[0] == '~')
882 char *expanded = tilde_expand (dir);
883 if (expanded != 0)
884 dir = expanded;
886 if (chdir (dir) < 0)
887 pfatal_with_name (dir);
888 if (dir != directories->list[i])
889 free (dir);
892 #ifdef WINDOWS32
894 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
895 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
897 * The functions in dir.c can incorrectly cache information for "."
898 * before we have changed directory and this can cause file
899 * lookups to fail because the current directory (.) was pointing
900 * at the wrong place when it was first evaluated.
904 * On Windows/NT, we don't have the luxury of a /bin directory that
905 * is mapped globally to every drive mounted to the system. Since make could
906 * be invoked from any drive, and we don't want to propogate /bin/sh
907 * to every single drive. Allow ourselves a chance to search for
908 * a value for default shell here (if the default path does not exist).
910 * The value of default_shell is set here, but it could get reset after
911 * the Makefiles are read in. See logic below where SHELL is checked
912 * after the call to read_all_makefiles() completes.
914 * The reason SHELL is set here is so that macros can be safely evaluated
915 * as makefiles are read in (some macros require $SHELL).
919 extern char *default_shell;
921 if (!file_exists_p(default_shell)) {
922 char *p;
923 struct variable *v = lookup_variable ("Path", 4);
926 * Try and make sure we have a full path to default_shell before
927 * we parse makefiles.
929 if (v && v->value) {
930 PATH_VAR(sh_path);
931 char *ep;
933 p = v->value;
934 ep = strchr(p, PATH_SEPARATOR_CHAR);
936 while (ep && *ep) {
937 *ep = '\0';
939 if (dir_file_exists_p(p, default_shell)) {
940 sprintf(sh_path, "%s/%s", p, default_shell);
941 default_shell = strdup(w32ify(sh_path,0));
942 no_default_sh_exe = 0;
943 *ep = PATH_SEPARATOR_CHAR;
945 /* terminate loop */
946 p += strlen(p);
947 } else {
948 *ep = PATH_SEPARATOR_CHAR;
949 p = ++ep;
952 ep = strchr(p, PATH_SEPARATOR_CHAR);
955 /* be sure to check last element of Path */
956 if (p && *p && dir_file_exists_p(p, default_shell)) {
957 sprintf(sh_path, "%s/%s", p, default_shell);
958 default_shell = strdup(w32ify(sh_path,0));
959 no_default_sh_exe = 0;
964 #endif /* WINDOWS32 */
965 /* Figure out the level of recursion. */
967 struct variable *v = lookup_variable ("MAKELEVEL", 9);
968 if (v != 0 && *v->value != '\0' && *v->value != '-')
969 makelevel = (unsigned int) atoi (v->value);
970 else
971 makelevel = 0;
974 /* Except under -s, always do -w in sub-makes and under -C. */
975 if (!silent_flag && (directories != 0 || makelevel > 0))
976 print_directory_flag = 1;
978 /* Let the user disable that with --no-print-directory. */
979 if (inhibit_print_directory_flag)
980 print_directory_flag = 0;
982 /* Construct the list of include directories to search. */
984 construct_include_path (include_directories == 0 ? (char **) 0
985 : include_directories->list);
987 /* Figure out where we are now, after chdir'ing. */
988 if (directories == 0)
989 /* We didn't move, so we're still in the same place. */
990 starting_directory = current_directory;
991 else
993 #ifdef WINDOWS32
994 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
995 #else
996 if (getcwd (current_directory, GET_PATH_MAX) == 0)
997 #endif
999 #ifdef HAVE_GETCWD
1000 perror_with_name ("getcwd: ", "");
1001 #else
1002 error ("getwd: %s", current_directory);
1003 #endif
1004 starting_directory = 0;
1006 else
1007 starting_directory = current_directory;
1010 /* Read any stdin makefiles into temporary files. */
1012 if (makefiles != 0)
1014 register unsigned int i;
1015 for (i = 0; i < makefiles->idx; ++i)
1016 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1018 /* This makefile is standard input. Since we may re-exec
1019 and thus re-read the makefiles, we read standard input
1020 into a temporary file and read from that. */
1021 FILE *outfile;
1023 /* Make a unique filename. */
1024 #ifdef HAVE_MKTEMP
1026 #ifdef VMS
1027 static char name[] = "sys$scratch:GmXXXXXX";
1028 #else
1029 static char name[] = "/tmp/GmXXXXXX";
1030 #endif
1031 (void) mktemp (name);
1032 #else
1033 static char name[L_tmpnam];
1034 (void) tmpnam (name);
1035 #endif
1037 outfile = fopen (name, "w");
1038 if (outfile == 0)
1039 pfatal_with_name ("fopen (temporary file)");
1040 while (!feof (stdin))
1042 char buf[2048];
1043 unsigned int n = fread (buf, 1, sizeof(buf), stdin);
1044 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1045 pfatal_with_name ("fwrite (temporary file)");
1047 /* Try to make sure we won't remake the temporary
1048 file when we are re-exec'd. Kludge-o-matic! */
1049 fprintf (outfile, "%s:;\n", name);
1050 (void) fclose (outfile);
1052 /* Replace the name that read_all_makefiles will
1053 see with the name of the temporary file. */
1055 char *temp;
1056 /* SGI compiler requires alloca's result be assigned simply. */
1057 temp = (char *) alloca (sizeof (name));
1058 bcopy (name, temp, sizeof (name));
1059 makefiles->list[i] = temp;
1062 /* Make sure the temporary file will not be remade. */
1063 f = enter_file (savestring (name, sizeof name - 1));
1064 f->updated = 1;
1065 f->update_status = 0;
1066 f->command_state = cs_finished;
1067 /* Let it be removed when we're done. */
1068 f->intermediate = 1;
1069 /* But don't mention it. */
1070 f->dontcare = 1;
1074 /* Set up to handle children dying. This must be done before
1075 reading in the makefiles so that `shell' function calls will work. */
1077 #ifdef SIGCHLD
1078 (void) signal (SIGCHLD, child_handler);
1079 #endif
1080 #ifdef SIGCLD
1081 (void) signal (SIGCLD, child_handler);
1082 #endif
1084 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1085 #ifdef SIGUSR1
1086 (void) signal (SIGUSR1, debug_signal_handler);
1087 #endif
1089 /* Define the initial list of suffixes for old-style rules. */
1091 set_default_suffixes ();
1093 /* Define the file rules for the built-in suffix rules. These will later
1094 be converted into pattern rules. We used to do this in
1095 install_default_implicit_rules, but since that happens after reading
1096 makefiles, it results in the built-in pattern rules taking precedence
1097 over makefile-specified suffix rules, which is wrong. */
1099 install_default_suffix_rules ();
1101 /* Define some internal and special variables. */
1103 define_automatic_variables ();
1105 /* Set up the MAKEFLAGS and MFLAGS variables
1106 so makefiles can look at them. */
1108 define_makeflags (0, 0);
1110 #ifdef WINDOWS32
1112 * Now that makefiles are parsed, see if a Makefile gave a
1113 * value for SHELL and use that for default_shell instead if
1114 * that filename exists. This should speed up the
1115 * construct_argv_internal() function by avoiding unnecessary
1116 * recursion.
1119 struct variable *v = lookup_variable("SHELL", 5);
1120 extern char* default_shell;
1123 * to change value:
1125 * SHELL must be found, SHELL must be set, value of SHELL
1126 * must be different from current value, and the
1127 * specified file must exist. Whew!
1129 if (v != 0 && *v->value != '\0') {
1130 char *fn = recursively_expand(v);
1132 if (fn && strcmp(fn, default_shell) && file_exists_p(fn)) {
1133 char *p;
1135 default_shell = fn;
1137 /* if Makefile says SHELL is sh.exe, believe it */
1138 if (strstr(default_shell, "sh.exe"))
1139 no_default_sh_exe = 0;
1142 * Convert from backslashes to forward slashes so
1143 * create_command_line_argv_internal() is not confused.
1145 for (p = strchr(default_shell, '\\'); p; p = strchr(default_shell, '\\'))
1146 *p = '/';
1150 if (no_default_sh_exe && job_slots != 1) {
1151 error("Do not specify -j or --jobs if sh.exe is not available.");
1152 error("Resetting make for single job mode.");
1153 job_slots = 1;
1155 #endif /* WINDOWS32 */
1157 /* Define the default variables. */
1158 define_default_variables ();
1160 /* Read all the makefiles. */
1162 default_file = enter_file (".DEFAULT");
1164 read_makefiles
1165 = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
1167 #ifdef __MSDOS__
1168 /* We need to know what kind of shell we will be using. */
1170 extern int _is_unixy_shell (const char *_path);
1171 struct variable *shv = lookup_variable("SHELL", 5);
1172 extern int unixy_shell;
1173 extern char *default_shell;
1175 if (shv && *shv->value)
1177 char *shell_path = recursively_expand(shv);
1179 if (shell_path && _is_unixy_shell (shell_path))
1180 unixy_shell = 1;
1181 else
1182 unixy_shell = 0;
1183 if (shell_path)
1184 default_shell = shell_path;
1187 #endif /* __MSDOS__ */
1189 /* Decode switches again, in case the variables were set by the makefile. */
1190 decode_env_switches ("MAKEFLAGS", 9);
1191 #if 0
1192 decode_env_switches ("MFLAGS", 6);
1193 #endif
1195 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1197 define_makeflags (1, 0);
1199 /* Make each `struct dep' point at the `struct file' for the file
1200 depended on. Also do magic for special targets. */
1202 snap_deps ();
1204 /* Convert old-style suffix rules to pattern rules. It is important to
1205 do this before installing the built-in pattern rules below, so that
1206 makefile-specified suffix rules take precedence over built-in pattern
1207 rules. */
1209 convert_to_pattern ();
1211 /* Install the default implicit pattern rules.
1212 This used to be done before reading the makefiles.
1213 But in that case, built-in pattern rules were in the chain
1214 before user-defined ones, so they matched first. */
1216 install_default_implicit_rules ();
1218 /* Compute implicit rule limits. */
1220 count_implicit_rule_limits ();
1222 /* Construct the listings of directories in VPATH lists. */
1224 build_vpath_lists ();
1226 /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
1227 and as having been updated already, and files given with -W flags as
1228 brand new (time-stamp as far as possible into the future). */
1230 if (old_files != 0)
1231 for (p = old_files->list; *p != 0; ++p)
1233 f = enter_command_line_file (*p);
1234 f->last_mtime = (time_t) 1;
1235 f->updated = 1;
1236 f->update_status = 0;
1237 f->command_state = cs_finished;
1240 if (new_files != 0)
1242 for (p = new_files->list; *p != 0; ++p)
1244 f = enter_command_line_file (*p);
1245 f->last_mtime = NEW_MTIME;
1249 /* Initialize the remote job module. */
1250 remote_setup ();
1252 if (read_makefiles != 0)
1254 /* Update any makefiles if necessary. */
1256 time_t *makefile_mtimes = 0;
1257 unsigned int mm_idx = 0;
1258 char **nargv = argv;
1259 char nargc = argc;
1261 if (debug_flag)
1262 puts ("Updating makefiles....");
1264 /* Remove any makefiles we don't want to try to update.
1265 Also record the current modtimes so we can compare them later. */
1267 register struct dep *d, *last;
1268 last = 0;
1269 d = read_makefiles;
1270 while (d != 0)
1272 register struct file *f = d->file;
1273 if (f->double_colon)
1274 for (f = f->double_colon; f != NULL; f = f->prev)
1276 if (f->deps == 0 && f->cmds != 0)
1278 /* This makefile is a :: target with commands, but
1279 no dependencies. So, it will always be remade.
1280 This might well cause an infinite loop, so don't
1281 try to remake it. (This will only happen if
1282 your makefiles are written exceptionally
1283 stupidly; but if you work for Athena, that's how
1284 you write your makefiles.) */
1286 if (debug_flag)
1287 printf ("Makefile `%s' might loop; not remaking it.\n",
1288 f->name);
1290 if (last == 0)
1291 read_makefiles = d->next;
1292 else
1293 last->next = d->next;
1295 /* Free the storage. */
1296 free ((char *) d);
1298 d = last == 0 ? 0 : last->next;
1300 break;
1303 if (f == NULL || !f->double_colon)
1305 if (makefile_mtimes == 0)
1306 makefile_mtimes = (time_t *) xmalloc (sizeof (time_t));
1307 else
1308 makefile_mtimes = (time_t *)
1309 xrealloc ((char *) makefile_mtimes,
1310 (mm_idx + 1) * sizeof (time_t));
1311 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
1312 last = d;
1313 d = d->next;
1318 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
1319 define_makeflags (1, 1);
1321 switch (update_goal_chain (read_makefiles, 1))
1323 case 1:
1324 default:
1325 #define BOGUS_UPDATE_STATUS 0
1326 assert (BOGUS_UPDATE_STATUS);
1327 break;
1329 case -1:
1330 /* Did nothing. */
1331 break;
1333 case 2:
1334 /* Failed to update. Figure out if we care. */
1336 /* Nonzero if any makefile was successfully remade. */
1337 int any_remade = 0;
1338 /* Nonzero if any makefile we care about failed
1339 in updating or could not be found at all. */
1340 int any_failed = 0;
1341 register unsigned int i;
1342 struct dep *d;
1344 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
1345 if (d->file->updated)
1347 /* This makefile was updated. */
1348 if (d->file->update_status == 0)
1350 /* It was successfully updated. */
1351 any_remade |= (file_mtime_no_search (d->file)
1352 != makefile_mtimes[i]);
1354 else if (! (d->changed & RM_DONTCARE))
1356 time_t mtime;
1357 /* The update failed and this makefile was not
1358 from the MAKEFILES variable, so we care. */
1359 error ("Failed to remake makefile `%s'.",
1360 d->file->name);
1361 mtime = file_mtime_no_search (d->file);
1362 any_remade |= (mtime != (time_t) -1
1363 && mtime != makefile_mtimes[i]);
1366 else
1367 /* This makefile was not found at all. */
1368 if (! (d->changed & RM_DONTCARE))
1370 /* This is a makefile we care about. See how much. */
1371 if (d->changed & RM_INCLUDED)
1372 /* An included makefile. We don't need
1373 to die, but we do want to complain. */
1374 error ("Included makefile `%s' was not found.",
1375 dep_name (d));
1376 else
1378 /* A normal makefile. We must die later. */
1379 error ("Makefile `%s' was not found", dep_name (d));
1380 any_failed = 1;
1384 if (any_remade)
1385 goto re_exec;
1386 else if (any_failed)
1387 die (2);
1388 else
1389 break;
1392 case 0:
1393 re_exec:
1394 /* Updated successfully. Re-exec ourselves. */
1396 remove_intermediates (0);
1398 if (print_data_base_flag)
1399 print_data_base ();
1401 log_working_directory (0);
1403 if (makefiles != 0)
1405 /* These names might have changed. */
1406 register unsigned int i, j = 0;
1407 for (i = 1; i < argc; ++i)
1408 if (!strncmp (argv[i], "-f", 2)) /* XXX */
1410 char *p = &argv[i][2];
1411 if (*p == '\0')
1412 argv[++i] = makefiles->list[j];
1413 else
1414 argv[i] = concat ("-f", makefiles->list[j], "");
1415 ++j;
1419 /* Add -o options for all makefiles that were remade */
1421 register unsigned int i;
1422 struct dep *d;
1424 for (i = argc+1, d = read_makefiles; d != 0; d = d->next)
1425 i += d->file->updated != 0;
1427 nargv = (char **)xmalloc(i * sizeof(char *));
1428 bcopy(argv, nargv, argc * sizeof(char *));
1430 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
1432 if (d->file->updated)
1433 nargv[nargc++] = concat("-o", dep_name(d), "");
1435 nargv[nargc] = 0;
1438 if (directories != 0 && directories->idx > 0)
1440 char bad;
1441 if (directory_before_chdir != 0)
1443 if (chdir (directory_before_chdir) < 0)
1445 perror_with_name ("chdir", "");
1446 bad = 1;
1448 else
1449 bad = 0;
1451 else
1452 bad = 1;
1453 if (bad)
1454 fatal ("Couldn't change back to original directory.");
1457 #ifndef _AMIGA
1458 for (p = environ; *p != 0; ++p)
1459 if (!strncmp (*p, "MAKELEVEL=", 10))
1461 /* The SGI compiler apparently can't understand
1462 the concept of storing the result of a function
1463 in something other than a local variable. */
1464 char *sgi_loses;
1465 sgi_loses = (char *) alloca (40);
1466 *p = sgi_loses;
1467 sprintf (*p, "MAKELEVEL=%u", makelevel);
1468 break;
1470 #else /* AMIGA */
1472 char buffer[256];
1473 int len;
1475 len = GetVar ("MAKELEVEL", buffer, sizeof (buffer), GVF_GLOBAL_ONLY);
1477 if (len != -1)
1479 sprintf (buffer, "%u", makelevel);
1480 SetVar ("MAKELEVEL", buffer, -1, GVF_GLOBAL_ONLY);
1483 #endif
1485 if (debug_flag)
1487 char **p;
1488 fputs ("Re-executing:", stdout);
1489 for (p = nargv; *p != 0; ++p)
1490 printf (" %s", *p);
1491 puts ("");
1494 fflush (stdout);
1495 fflush (stderr);
1497 #ifndef _AMIGA
1498 exec_command (nargv, environ);
1499 #else
1500 exec_command (nargv);
1501 exit (0);
1502 #endif
1503 /* NOTREACHED */
1507 /* Set up `MAKEFLAGS' again for the normal targets. */
1508 define_makeflags (1, 0);
1511 int status;
1513 /* If there were no command-line goals, use the default. */
1514 if (goals == 0)
1516 if (default_goal_file != 0)
1518 goals = (struct dep *) xmalloc (sizeof (struct dep));
1519 goals->next = 0;
1520 goals->name = 0;
1521 goals->file = default_goal_file;
1524 else
1525 lastgoal->next = 0;
1527 if (goals != 0)
1529 /* Update the goals. */
1531 if (debug_flag)
1532 puts ("Updating goal targets....");
1534 switch (update_goal_chain (goals, 0))
1536 case -1:
1537 /* Nothing happened. */
1538 case 0:
1539 /* Updated successfully. */
1540 status = EXIT_SUCCESS;
1541 break;
1542 case 2:
1543 /* Updating failed. POSIX.2 specifies exit status >1 for this;
1544 but in VMS, there is only success and failure. */
1545 status = EXIT_FAILURE ? 2 : EXIT_FAILURE;
1546 break;
1547 case 1:
1548 /* We are under -q and would run some commands. */
1549 status = EXIT_FAILURE;
1550 break;
1551 default:
1552 abort ();
1555 else
1557 if (read_makefiles == 0)
1558 fatal ("No targets specified and no makefile found");
1559 else
1560 fatal ("No targets");
1563 /* If we detected some clock skew, generate one last warning */
1564 if (clock_skew_detected)
1565 error("*** Warning: Clock skew detected. Your build may be incomplete.");
1567 /* Exit. */
1568 die (status);
1571 return 0;
1574 /* Parsing of arguments, decoding of switches. */
1576 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
1577 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
1578 (sizeof (long_option_aliases) /
1579 sizeof (long_option_aliases[0]))];
1581 /* Fill in the string and vector for getopt. */
1582 static void
1583 init_switches ()
1585 register char *p;
1586 register int c;
1587 register unsigned int i;
1589 if (options[0] != '\0')
1590 /* Already done. */
1591 return;
1593 p = options;
1595 /* Return switch and non-switch args in order, regardless of
1596 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
1597 *p++ = '-';
1599 for (i = 0; switches[i].c != '\0'; ++i)
1601 long_options[i].name = (switches[i].long_name == 0 ? "" :
1602 switches[i].long_name);
1603 long_options[i].flag = 0;
1604 long_options[i].val = switches[i].c;
1605 if (isalnum (switches[i].c))
1606 *p++ = switches[i].c;
1607 switch (switches[i].type)
1609 case flag:
1610 case flag_off:
1611 case ignore:
1612 long_options[i].has_arg = no_argument;
1613 break;
1615 case string:
1616 case positive_int:
1617 case floating:
1618 if (isalnum (switches[i].c))
1619 *p++ = ':';
1620 if (switches[i].noarg_value != 0)
1622 if (isalnum (switches[i].c))
1623 *p++ = ':';
1624 long_options[i].has_arg = optional_argument;
1626 else
1627 long_options[i].has_arg = required_argument;
1628 break;
1631 *p = '\0';
1632 for (c = 0; c < (sizeof (long_option_aliases) /
1633 sizeof (long_option_aliases[0]));
1634 ++c)
1635 long_options[i++] = long_option_aliases[c];
1636 long_options[i].name = 0;
1639 static void
1640 handle_non_switch_argument (arg, env)
1641 char *arg;
1642 int env;
1644 /* Non-option argument. It might be a variable definition. */
1645 struct variable *v;
1646 if (arg[0] == '-' && arg[1] == '\0')
1647 /* Ignore plain `-' for compatibility. */
1648 return;
1649 v = try_variable_definition ((char *) 0, 0, arg, o_command);
1650 if (v != 0)
1652 /* It is indeed a variable definition. Record a pointer to
1653 the variable for later use in define_makeflags. */
1654 struct command_variable *cv
1655 = (struct command_variable *) xmalloc (sizeof (*cv));
1656 cv->variable = v;
1657 cv->next = command_variables;
1658 command_variables = cv;
1660 else if (! env)
1662 /* Not an option or variable definition; it must be a goal
1663 target! Enter it as a file and add it to the dep chain of
1664 goals. */
1665 struct file *f = enter_command_line_file (arg);
1666 f->cmd_target = 1;
1668 if (goals == 0)
1670 goals = (struct dep *) xmalloc (sizeof (struct dep));
1671 lastgoal = goals;
1673 else
1675 lastgoal->next
1676 = (struct dep *) xmalloc (sizeof (struct dep));
1677 lastgoal = lastgoal->next;
1679 lastgoal->name = 0;
1680 lastgoal->file = f;
1683 /* Add this target name to the MAKECMDGOALS variable. */
1684 struct variable *v;
1685 char *value;
1687 v = lookup_variable("MAKECMDGOALS", 12);
1688 if (v == 0)
1689 value = f->name;
1690 else
1692 /* Paste the old and new values together */
1693 unsigned int oldlen, newlen;
1695 oldlen = strlen(v->value);
1696 newlen = strlen(f->name);
1697 value = (char *)alloca(oldlen + 1 + newlen + 1);
1698 bcopy(v->value, value, oldlen);
1699 value[oldlen] = ' ';
1700 bcopy(f->name, &value[oldlen + 1], newlen + 1);
1702 define_variable("MAKECMDGOALS", 12, value, o_default, 0);
1707 /* Decode switches from ARGC and ARGV.
1708 They came from the environment if ENV is nonzero. */
1710 static void
1711 decode_switches (argc, argv, env)
1712 int argc;
1713 char **argv;
1714 int env;
1716 int bad = 0;
1717 register const struct command_switch *cs;
1718 register struct stringlist *sl;
1719 register int c;
1721 /* getopt does most of the parsing for us.
1722 First, get its vectors set up. */
1724 init_switches ();
1726 /* Let getopt produce error messages for the command line,
1727 but not for options from the environment. */
1728 opterr = !env;
1729 /* Reset getopt's state. */
1730 optind = 0;
1732 while (optind < argc)
1734 /* Parse the next argument. */
1735 c = getopt_long (argc, argv, options, long_options, (int *) 0);
1736 if (c == EOF)
1737 /* End of arguments, or "--" marker seen. */
1738 break;
1739 else if (c == 1)
1740 /* An argument not starting with a dash. */
1741 handle_non_switch_argument (optarg, env);
1742 else if (c == '?')
1743 /* Bad option. We will print a usage message and die later.
1744 But continue to parse the other options so the user can
1745 see all he did wrong. */
1746 bad = 1;
1747 else
1748 for (cs = switches; cs->c != '\0'; ++cs)
1749 if (cs->c == c)
1751 /* Whether or not we will actually do anything with
1752 this switch. We test this individually inside the
1753 switch below rather than just once outside it, so that
1754 options which are to be ignored still consume args. */
1755 int doit = !env || cs->env;
1757 switch (cs->type)
1759 default:
1760 abort ();
1762 case ignore:
1763 break;
1765 case flag:
1766 case flag_off:
1767 if (doit)
1768 *(int *) cs->value_ptr = cs->type == flag;
1769 break;
1771 case string:
1772 if (!doit)
1773 break;
1775 if (optarg == 0)
1776 optarg = cs->noarg_value;
1778 sl = *(struct stringlist **) cs->value_ptr;
1779 if (sl == 0)
1781 sl = (struct stringlist *)
1782 xmalloc (sizeof (struct stringlist));
1783 sl->max = 5;
1784 sl->idx = 0;
1785 sl->list = (char **) xmalloc (5 * sizeof (char *));
1786 *(struct stringlist **) cs->value_ptr = sl;
1788 else if (sl->idx == sl->max - 1)
1790 sl->max += 5;
1791 sl->list = (char **)
1792 xrealloc ((char *) sl->list,
1793 sl->max * sizeof (char *));
1795 sl->list[sl->idx++] = optarg;
1796 sl->list[sl->idx] = 0;
1797 break;
1799 case positive_int:
1800 if (optarg == 0 && argc > optind
1801 && isdigit (argv[optind][0]))
1802 optarg = argv[optind++];
1804 if (!doit)
1805 break;
1807 if (optarg != 0)
1809 int i = atoi (optarg);
1810 if (i < 1)
1812 if (doit)
1813 error ("the `-%c' option requires a \
1814 positive integral argument",
1815 cs->c);
1816 bad = 1;
1818 else
1819 *(unsigned int *) cs->value_ptr = i;
1821 else
1822 *(unsigned int *) cs->value_ptr
1823 = *(unsigned int *) cs->noarg_value;
1824 break;
1826 #ifndef NO_FLOAT
1827 case floating:
1828 if (optarg == 0 && optind < argc
1829 && (isdigit (argv[optind][0]) || argv[optind][0] == '.'))
1830 optarg = argv[optind++];
1832 if (doit)
1833 *(double *) cs->value_ptr
1834 = (optarg != 0 ? atof (optarg)
1835 : *(double *) cs->noarg_value);
1837 break;
1838 #endif
1841 /* We've found the switch. Stop looking. */
1842 break;
1846 /* There are no more options according to getting getopt, but there may
1847 be some arguments left. Since we have asked for non-option arguments
1848 to be returned in order, this only happens when there is a "--"
1849 argument to prevent later arguments from being options. */
1850 while (optind < argc)
1851 handle_non_switch_argument (argv[optind++], env);
1854 if (!env && (bad || print_usage_flag))
1856 /* Print a nice usage message. */
1857 FILE *usageto;
1859 if (print_version_flag)
1860 print_version ();
1862 usageto = bad ? stderr : stdout;
1864 fprintf (usageto, "Usage: %s [options] [target] ...\n", program);
1866 fputs ("Options:\n", usageto);
1867 for (cs = switches; cs->c != '\0'; ++cs)
1869 char buf[1024], shortarg[50], longarg[50], *p;
1871 if (cs->description[0] == '-')
1872 continue;
1874 switch (long_options[cs - switches].has_arg)
1876 case no_argument:
1877 shortarg[0] = longarg[0] = '\0';
1878 break;
1879 case required_argument:
1880 sprintf (longarg, "=%s", cs->argdesc);
1881 sprintf (shortarg, " %s", cs->argdesc);
1882 break;
1883 case optional_argument:
1884 sprintf (longarg, "[=%s]", cs->argdesc);
1885 sprintf (shortarg, " [%s]", cs->argdesc);
1886 break;
1889 p = buf;
1891 if (isalnum (cs->c))
1893 sprintf (buf, " -%c%s", cs->c, shortarg);
1894 p += strlen (p);
1896 if (cs->long_name != 0)
1898 unsigned int i;
1899 sprintf (p, "%s--%s%s",
1900 !isalnum (cs->c) ? " " : ", ",
1901 cs->long_name, longarg);
1902 p += strlen (p);
1903 for (i = 0; i < (sizeof (long_option_aliases) /
1904 sizeof (long_option_aliases[0]));
1905 ++i)
1906 if (long_option_aliases[i].val == cs->c)
1908 sprintf (p, ", --%s%s",
1909 long_option_aliases[i].name, longarg);
1910 p += strlen (p);
1914 const struct command_switch *ncs = cs;
1915 while ((++ncs)->c != '\0')
1916 if (ncs->description[0] == '-' &&
1917 ncs->description[1] == cs->c)
1919 /* This is another switch that does the same
1920 one as the one we are processing. We want
1921 to list them all together on one line. */
1922 sprintf (p, ", -%c%s", ncs->c, shortarg);
1923 p += strlen (p);
1924 if (ncs->long_name != 0)
1926 sprintf (p, ", --%s%s", ncs->long_name, longarg);
1927 p += strlen (p);
1932 if (p - buf > DESCRIPTION_COLUMN - 2)
1933 /* The list of option names is too long to fit on the same
1934 line with the description, leaving at least two spaces.
1935 Print it on its own line instead. */
1937 fprintf (usageto, "%s\n", buf);
1938 buf[0] = '\0';
1941 fprintf (usageto, "%*s%s.\n",
1942 - DESCRIPTION_COLUMN,
1943 buf, cs->description);
1946 die (bad ? 2 : 0);
1950 /* Decode switches from environment variable ENVAR (which is LEN chars long).
1951 We do this by chopping the value into a vector of words, prepending a
1952 dash to the first word if it lacks one, and passing the vector to
1953 decode_switches. */
1955 static void
1956 decode_env_switches (envar, len)
1957 char *envar;
1958 unsigned int len;
1960 char *varref = (char *) alloca (2 + len + 2);
1961 char *value, *p;
1962 int argc;
1963 char **argv;
1965 /* Get the variable's value. */
1966 varref[0] = '$';
1967 varref[1] = '(';
1968 bcopy (envar, &varref[2], len);
1969 varref[2 + len] = ')';
1970 varref[2 + len + 1] = '\0';
1971 value = variable_expand (varref);
1973 /* Skip whitespace, and check for an empty value. */
1974 value = next_token (value);
1975 len = strlen (value);
1976 if (len == 0)
1977 return;
1979 /* Allocate a vector that is definitely big enough. */
1980 argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
1982 /* Allocate a buffer to copy the value into while we split it into words
1983 and unquote it. We must use permanent storage for this because
1984 decode_switches may store pointers into the passed argument words. */
1985 p = (char *) xmalloc (2 * len);
1987 /* getopt will look at the arguments starting at ARGV[1].
1988 Prepend a spacer word. */
1989 argv[0] = 0;
1990 argc = 1;
1991 argv[argc] = p;
1992 while (*value != '\0')
1994 if (*value == '\\')
1995 ++value; /* Skip the backslash. */
1996 else if (isblank (*value))
1998 /* End of the word. */
1999 *p++ = '\0';
2000 argv[++argc] = p;
2002 ++value;
2003 while (isblank (*value));
2004 continue;
2006 *p++ = *value++;
2008 *p = '\0';
2009 argv[++argc] = 0;
2011 if (argv[1][0] != '-' && index (argv[1], '=') == 0)
2012 /* The first word doesn't start with a dash and isn't a variable
2013 definition. Add a dash and pass it along to decode_switches. We
2014 need permanent storage for this in case decode_switches saves
2015 pointers into the value. */
2016 argv[1] = concat ("-", argv[1], "");
2018 /* Parse those words. */
2019 decode_switches (argc, argv, 1);
2022 /* Quote the string IN so that it will be interpreted as a single word with
2023 no magic by the shell; if DOUBLE_DOLLARS is nonzero, also double dollar
2024 signs to avoid variable expansion in make itself. Write the result into
2025 OUT, returning the address of the next character to be written.
2026 Allocating space for OUT twice the length of IN (thrice if
2027 DOUBLE_DOLLARS is nonzero) is always sufficient. */
2029 static char *
2030 quote_as_word (out, in, double_dollars)
2031 char *out, *in;
2032 int double_dollars;
2034 while (*in != '\0')
2036 #ifdef VMS
2037 if (index ("^;'\"*?$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2038 #else
2039 if (index ("^;'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
2040 #endif
2041 *out++ = '\\';
2042 if (double_dollars && *in == '$')
2043 *out++ = '$';
2044 *out++ = *in++;
2047 return out;
2050 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2051 command switches. Include options with args if ALL is nonzero.
2052 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2054 static void
2055 define_makeflags (all, makefile)
2056 int all, makefile;
2058 static const char ref[] = "$(MAKEOVERRIDES)";
2059 static const char posixref[] = "$(-*-command-variables-*-)";
2060 register const struct command_switch *cs;
2061 char *flagstring;
2062 register char *p;
2063 unsigned int words;
2064 struct variable *v;
2066 /* We will construct a linked list of `struct flag's describing
2067 all the flags which need to go in MAKEFLAGS. Then, once we
2068 know how many there are and their lengths, we can put them all
2069 together in a string. */
2071 struct flag
2073 struct flag *next;
2074 const struct command_switch *cs;
2075 char *arg;
2077 struct flag *flags = 0;
2078 unsigned int flagslen = 0;
2079 #define ADD_FLAG(ARG, LEN) \
2080 do { \
2081 struct flag *new = (struct flag *) alloca (sizeof (struct flag)); \
2082 new->cs = cs; \
2083 new->arg = (ARG); \
2084 new->next = flags; \
2085 flags = new; \
2086 if (new->arg == 0) \
2087 ++flagslen; /* Just a single flag letter. */ \
2088 else \
2089 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2090 if (!isalnum (cs->c)) \
2091 /* This switch has no single-letter version, so we use the long. */ \
2092 flagslen += 2 + strlen (cs->long_name); \
2093 } while (0)
2095 for (cs = switches; cs->c != '\0'; ++cs)
2096 if (cs->toenv && (!makefile || !cs->no_makefile))
2097 switch (cs->type)
2099 default:
2100 abort ();
2102 case ignore:
2103 break;
2105 case flag:
2106 case flag_off:
2107 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2108 && (cs->default_value == 0
2109 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2110 ADD_FLAG (0, 0);
2111 break;
2113 case positive_int:
2114 if (all)
2116 if ((cs->default_value != 0
2117 && (*(unsigned int *) cs->value_ptr
2118 == *(unsigned int *) cs->default_value)))
2119 break;
2120 else if (cs->noarg_value != 0
2121 && (*(unsigned int *) cs->value_ptr ==
2122 *(unsigned int *) cs->noarg_value))
2123 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2124 else if (cs->c == 'j')
2125 /* Special case for `-j'. */
2126 ADD_FLAG ("1", 1);
2127 else
2129 char *buf = (char *) alloca (30);
2130 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
2131 ADD_FLAG (buf, strlen (buf));
2134 break;
2136 #ifndef NO_FLOAT
2137 case floating:
2138 if (all)
2140 if (cs->default_value != 0
2141 && (*(double *) cs->value_ptr
2142 == *(double *) cs->default_value))
2143 break;
2144 else if (cs->noarg_value != 0
2145 && (*(double *) cs->value_ptr
2146 == *(double *) cs->noarg_value))
2147 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2148 else
2150 char *buf = (char *) alloca (100);
2151 sprintf (buf, "%g", *(double *) cs->value_ptr);
2152 ADD_FLAG (buf, strlen (buf));
2155 break;
2156 #endif
2158 case string:
2159 if (all)
2161 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
2162 if (sl != 0)
2164 /* Add the elements in reverse order, because
2165 all the flags get reversed below; and the order
2166 matters for some switches (like -I). */
2167 register unsigned int i = sl->idx;
2168 while (i-- > 0)
2169 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
2172 break;
2175 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
2177 #undef ADD_FLAG
2179 /* Construct the value in FLAGSTRING.
2180 We allocate enough space for a preceding dash and trailing null. */
2181 flagstring = (char *) alloca (1 + flagslen + 1);
2182 p = flagstring;
2183 words = 1;
2184 *p++ = '-';
2185 while (flags != 0)
2187 /* Add the flag letter or name to the string. */
2188 if (!isalnum (flags->cs->c))
2190 *p++ = '-';
2191 strcpy (p, flags->cs->long_name);
2192 p += strlen (p);
2194 else
2195 *p++ = flags->cs->c;
2196 if (flags->arg != 0)
2198 /* A flag that takes an optional argument which in this case is
2199 omitted is specified by ARG being "". We must distinguish
2200 because a following flag appended without an intervening " -"
2201 is considered the arg for the first. */
2202 if (flags->arg[0] != '\0')
2204 /* Add its argument too. */
2205 *p++ = !isalnum (flags->cs->c) ? '=' : ' ';
2206 p = quote_as_word (p, flags->arg, 1);
2208 ++words;
2209 /* Write a following space and dash, for the next flag. */
2210 *p++ = ' ';
2211 *p++ = '-';
2213 else if (!isalnum (flags->cs->c))
2215 ++words;
2216 /* Long options must each go in their own word,
2217 so we write the following space and dash. */
2218 *p++ = ' ';
2219 *p++ = '-';
2221 flags = flags->next;
2224 /* Define MFLAGS before appending variable definitions. */
2226 if (p == &flagstring[1])
2227 /* No flags. */
2228 flagstring[0] = '\0';
2229 else if (p[-1] == '-')
2231 /* Kill the final space and dash. */
2232 p -= 2;
2233 *p = '\0';
2235 else
2236 /* Terminate the string. */
2237 *p = '\0';
2239 /* Since MFLAGS is not parsed for flags, there is no reason to
2240 override any makefile redefinition. */
2241 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
2243 if (all && command_variables != 0)
2245 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
2246 command-line variable definitions. */
2248 if (p == &flagstring[1])
2249 /* No flags written, so elide the leading dash already written. */
2250 p = flagstring;
2251 else
2253 /* Separate the variables from the switches with a "--" arg. */
2254 if (p[-1] != '-')
2256 /* We did not already write a trailing " -". */
2257 *p++ = ' ';
2258 *p++ = '-';
2260 /* There is a trailing " -"; fill it out to " -- ". */
2261 *p++ = '-';
2262 *p++ = ' ';
2265 /* Copy in the string. */
2266 if (posix_pedantic)
2268 bcopy (posixref, p, sizeof posixref - 1);
2269 p += sizeof posixref - 1;
2271 else
2273 bcopy (ref, p, sizeof ref - 1);
2274 p += sizeof ref - 1;
2277 else if (p == &flagstring[1])
2279 words = 0;
2280 --p;
2282 else if (p[-1] == '-')
2283 /* Kill the final space and dash. */
2284 p -= 2;
2285 /* Terminate the string. */
2286 *p = '\0';
2288 v = define_variable ("MAKEFLAGS", 9,
2289 /* If there are switches, omit the leading dash
2290 unless it is a single long option with two
2291 leading dashes. */
2292 &flagstring[(flagstring[0] == '-'
2293 && flagstring[1] != '-')
2294 ? 1 : 0],
2295 /* This used to use o_env, but that lost when a
2296 makefile defined MAKEFLAGS. Makefiles set
2297 MAKEFLAGS to add switches, but we still want
2298 to redefine its value with the full set of
2299 switches. Of course, an override or command
2300 definition will still take precedence. */
2301 o_file, 1);
2302 if (! all)
2303 /* The first time we are called, set MAKEFLAGS to always be exported.
2304 We should not do this again on the second call, because that is
2305 after reading makefiles which might have done `unexport MAKEFLAGS'. */
2306 v->export = v_export;
2309 /* Print version information. */
2311 static void
2312 print_version ()
2314 static int printed_version = 0;
2316 char *precede = print_data_base_flag ? "# " : "";
2318 if (printed_version)
2319 /* Do it only once. */
2320 return;
2322 printf ("%sGNU Make version %s", precede, version_string);
2323 if (remote_description != 0 && *remote_description != '\0')
2324 printf ("-%s", remote_description);
2326 printf (", by Richard Stallman and Roland McGrath.\n\
2327 %sCopyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96, 97\n\
2328 %s\tFree Software Foundation, Inc.\n\
2329 %sThis is free software; see the source for copying conditions.\n\
2330 %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
2331 %sPARTICULAR PURPOSE.\n\n\
2332 %sReport bugs to <bug-gnu-utils@prep.ai.mit.edu>.\n\n",
2333 precede, precede, precede, precede, precede, precede);
2335 printed_version = 1;
2337 /* Flush stdout so the user doesn't have to wait to see the
2338 version information while things are thought about. */
2339 fflush (stdout);
2342 /* Print a bunch of information about this and that. */
2344 static void
2345 print_data_base ()
2347 time_t when;
2349 when = time ((time_t *) 0);
2350 printf ("\n# Make data base, printed on %s", ctime (&when));
2352 print_variable_data_base ();
2353 print_dir_data_base ();
2354 print_rule_data_base ();
2355 print_file_data_base ();
2356 print_vpath_data_base ();
2358 when = time ((time_t *) 0);
2359 printf ("\n# Finished Make data base on %s\n", ctime (&when));
2362 /* Exit with STATUS, cleaning up as necessary. */
2364 void
2365 die (status)
2366 int status;
2368 static char dying = 0;
2370 if (!dying)
2372 int err;
2374 dying = 1;
2376 /* Try to move back to the original directory. This is essential on
2377 MS-DOS (where there is really only one process), and on Unix it
2378 puts core files in the original directory instead of the -C
2379 directory. */
2380 if (directory_before_chdir != 0)
2381 chdir (directory_before_chdir);
2383 if (print_version_flag)
2384 print_version ();
2386 /* Wait for children to die. */
2387 for (err = status != 0; job_slots_used > 0; err = 0)
2388 reap_children (1, err);
2390 /* Let the remote job module clean up its state. */
2391 remote_cleanup ();
2393 /* Remove the intermediate files. */
2394 remove_intermediates (0);
2396 if (print_data_base_flag)
2397 print_data_base ();
2399 log_working_directory (0);
2402 exit (status);
2405 /* Write a message indicating that we've just entered or
2406 left (according to ENTERING) the current directory. */
2408 void
2409 log_working_directory (entering)
2410 int entering;
2412 static int entered = 0;
2413 char *message = entering ? "Entering" : "Leaving";
2415 /* Print nothing without the flag. Don't print the entering message
2416 again if we already have. Don't print the leaving message if we
2417 haven't printed the entering message. */
2418 if (! print_directory_flag || entering == entered)
2419 return;
2421 entered = entering;
2423 if (print_data_base_flag)
2424 fputs ("# ", stdout);
2426 if (makelevel == 0)
2427 printf ("%s: %s ", program, message);
2428 else
2429 printf ("%s[%u]: %s ", program, makelevel, message);
2431 if (starting_directory == 0)
2432 puts ("an unknown directory");
2433 else
2434 printf ("directory `%s'\n", starting_directory);