Renamed to README.W32 at RMS' request.
[make.git] / main.c
blobb5ff42fe70611706db803efc39df98426d2ca767
1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 94, 95, 96 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 WIN32
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 WIN32
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 WIN32
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 /* Mask of signals that are being caught with fatal_error_signal. */
398 #ifdef POSIX
399 sigset_t fatal_signal_set;
400 #else
401 #ifdef HAVE_SIGSETMASK
402 int fatal_signal_mask;
403 #endif
404 #endif
406 static struct file *
407 enter_command_line_file (name)
408 char *name;
410 if (name[0] == '\0')
411 fatal ("empty string invalid as file name");
413 if (name[0] == '~')
415 char *expanded = tilde_expand (name);
416 if (expanded != 0)
417 name = expanded; /* Memory leak; I don't care. */
420 /* This is also done in parse_file_seq, so this is redundant
421 for names read from makefiles. It is here for names passed
422 on the command line. */
423 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
425 name += 2;
426 while (*name == '/')
427 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
428 ++name;
431 if (*name == '\0')
433 /* It was all slashes! Move back to the dot and truncate
434 it after the first slash, so it becomes just "./". */
436 --name;
437 while (name[0] != '.');
438 name[2] = '\0';
441 return enter_file (savestring (name, strlen (name)));
444 /* Toggle -d on receipt of SIGUSR1. */
446 static RETSIGTYPE
447 debug_signal_handler (sig)
448 int sig;
450 debug_flag = ! debug_flag;
453 #ifndef _AMIGA
455 main (argc, argv, envp)
456 int argc;
457 char **argv;
458 char **envp;
459 #else
460 int main (int argc, char ** argv)
461 #endif
463 register struct file *f;
464 register unsigned int i;
465 char **p;
466 struct dep *read_makefiles;
467 PATH_VAR (current_directory);
468 #ifdef WIN32
469 extern int no_default_sh_exe;
470 char *unix_path = NULL;
471 char *win32_path = NULL;
472 #endif
474 default_goal_file = 0;
475 reading_filename = 0;
476 reading_lineno_ptr = 0;
478 #if !defined (HAVE_STRSIGNAL) && !defined (HAVE_SYS_SIGLIST)
479 signame_init ();
480 #endif
482 #ifdef POSIX
483 sigemptyset (&fatal_signal_set);
484 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
485 #else
486 #ifdef HAVE_SIGSETMASK
487 fatal_signal_mask = 0;
488 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
489 #else
490 #define ADD_SIG(sig)
491 #endif
492 #endif
494 #define FATAL_SIG(sig) \
495 if (signal ((sig), fatal_error_signal) == SIG_IGN) \
496 (void) signal ((sig), SIG_IGN); \
497 else \
498 ADD_SIG (sig);
500 #ifdef SIGHUP
501 FATAL_SIG (SIGHUP);
502 #endif
503 #ifdef SIGQUIT
504 FATAL_SIG (SIGQUIT);
505 #endif
506 FATAL_SIG (SIGINT);
507 FATAL_SIG (SIGTERM);
509 #ifdef SIGDANGER
510 FATAL_SIG (SIGDANGER);
511 #endif
512 #ifdef SIGXCPU
513 FATAL_SIG (SIGXCPU);
514 #endif
515 #ifdef SIGXFSZ
516 FATAL_SIG (SIGXFSZ);
517 #endif
519 #undef FATAL_SIG
521 /* Make sure stdout is line-buffered. */
523 #ifdef HAVE_SETLINEBUF
524 setlinebuf (stdout);
525 #else
526 #ifndef SETVBUF_REVERSED
527 setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
528 #else /* setvbuf not reversed. */
529 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
530 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
531 #endif /* setvbuf reversed. */
532 #endif /* setlinebuf missing. */
534 /* Figure out where this program lives. */
536 if (argv[0] == 0)
537 argv[0] = "";
538 if (argv[0][0] == '\0')
539 program = "make";
540 else
542 #ifdef VMS
543 program = rindex (argv[0], ']');
544 #else
545 program = rindex (argv[0], '/');
546 #endif
547 #ifdef __MSDOS__
548 if (program == 0)
549 program = rindex (argv[0], '\\');
550 if (program == 0)
551 program = rindex (argv[0], ':');
552 #endif
553 if (program == 0)
554 program = argv[0];
555 else
556 ++program;
559 /* Set up to access user data (files). */
560 user_access ();
562 /* Figure out where we are. */
564 #ifdef WIN32
565 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
566 #else
567 if (getcwd (current_directory, GET_PATH_MAX) == 0)
568 #endif
570 #ifdef HAVE_GETCWD
571 perror_with_name ("getcwd: ", "");
572 #else
573 error ("getwd: %s", current_directory);
574 #endif
575 current_directory[0] = '\0';
576 directory_before_chdir = 0;
578 else
579 directory_before_chdir = savestring (current_directory,
580 strlen (current_directory));
582 /* Read in variables from the environment. It is important that this be
583 done before $(MAKE) is are figured out so its definitions will not be
584 one from the environment. */
586 #ifndef _AMIGA
587 for (i = 0; envp[i] != 0; ++i)
589 register char *ep = envp[i];
590 while (*ep != '=')
591 ++ep;
592 #ifdef WIN32
593 if (!strncmp(ep, "PATH", 4))
594 unix_path = &ep[5];
595 if (!strncmp(ep, "Path", 4))
596 win32_path = &ep[5];
597 #endif
598 /* The result of pointer arithmetic is cast to unsigned int for
599 machines where ptrdiff_t is a different size that doesn't widen
600 the same. */
601 define_variable (envp[i], (unsigned int) (ep - envp[i]),
602 ep + 1, o_env, 1)
603 /* Force exportation of every variable culled from the environment.
604 We used to rely on target_environment's v_default code to do this.
605 But that does not work for the case where an environment variable
606 is redefined in a makefile with `override'; it should then still
607 be exported, because it was originally in the environment. */
608 ->export = v_export;
610 #ifdef WIN32
612 * PATH defaults to Path iff PATH not found and Path is found.
614 if (!unix_path && win32_path)
615 define_variable("PATH", 4, win32_path, o_env, 1)->export = v_export;
616 #endif
617 #else /* For Amiga, read the ENV: device, ignoring all dirs */
619 BPTR env, file, old;
620 char buffer[1024];
621 int len;
622 __aligned struct FileInfoBlock fib;
624 env = Lock ("ENV:", ACCESS_READ);
625 if (env)
627 old = CurrentDir (DupLock(env));
628 Examine (env, &fib);
630 while (ExNext (env, &fib))
632 if (fib.fib_DirEntryType < 0) /* File */
634 /* Define an empty variable. It will be filled in
635 variable_lookup(). Makes startup quite a bit
636 faster. */
637 define_variable (fib.fib_FileName,
638 strlen (fib.fib_FileName),
639 "", o_env, 1)->export = v_export;
642 UnLock (env);
643 UnLock(CurrentDir(old));
646 #endif
648 /* Decode the switches. */
650 decode_env_switches ("MAKEFLAGS", 9);
651 #if 0
652 /* People write things like:
653 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
654 and we set the -p, -i and -e switches. Doesn't seem quite right. */
655 decode_env_switches ("MFLAGS", 6);
656 #endif
657 decode_switches (argc, argv, 0);
658 #ifdef WIN32
659 if (suspend_flag) {
660 fprintf(stderr, "%s (pid = %d)\n", argv[0], GetCurrentProcessId());
661 fprintf(stderr, "%s is suspending for 30 seconds...", argv[0]);
662 Sleep(30 * 1000);
663 fprintf(stderr, "done sleep(30). Continuing.\n");
665 #endif
667 /* Print version information. */
669 if (print_version_flag || print_data_base_flag || debug_flag)
670 print_version ();
672 /* `make --version' is supposed to just print the version and exit. */
673 if (print_version_flag)
674 die (0);
676 #if !defined(__MSDOS__) && !defined(VMS)
677 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
678 (If it is a relative pathname with a slash, prepend our directory name
679 so the result will run the same program regardless of the current dir.
680 If it is a name with no slash, we can only hope that PATH did not
681 find it in the current directory.) */
682 #ifdef WIN32
684 * Convert from backslashes to forward slashes for
685 * programs like sh which don't like them. Shouldn't
686 * matter if the path is one way or the other for
687 * CreateProcess().
689 if (strpbrk(argv[0], "/:\\") ||
690 strstr(argv[0], "..") ||
691 !strncmp(argv[0], "//", 2))
692 argv[0] = strdup(w32ify(argv[0],1));
693 #else /* WIN32 */
694 if (current_directory[0] != '\0'
695 && argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
696 argv[0] = concat (current_directory, "/", argv[0]);
697 #endif /* WIN32 */
698 #endif
700 /* The extra indirection through $(MAKE_COMMAND) is done
701 for hysterical raisins. */
702 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
703 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
705 if (command_variables != 0)
707 struct command_variable *cv;
708 struct variable *v;
709 unsigned int len = 0;
710 char *value, *p;
712 /* Figure out how much space will be taken up by the command-line
713 variable definitions. */
714 for (cv = command_variables; cv != 0; cv = cv->next)
716 v = cv->variable;
717 len += 2 * strlen (v->name);
718 if (! v->recursive)
719 ++len;
720 ++len;
721 len += 2 * strlen (v->value);
724 /* Now allocate a buffer big enough and fill it. */
725 p = value = (char *) alloca (len);
726 for (cv = command_variables; cv != 0; cv = cv->next)
728 v = cv->variable;
729 p = quote_as_word (p, v->name, 0);
730 if (! v->recursive)
731 *p++ = ':';
732 *p++ = '=';
733 p = quote_as_word (p, v->value, 0);
734 *p++ = ' ';
736 p[-1] = '\0'; /* Kill the final space and terminate. */
738 /* Define an unchangeable variable with a name that no POSIX.2
739 makefile could validly use for its own variable. */
740 (void) define_variable ("-*-command-variables-*-", 23,
741 value, o_automatic, 0);
743 /* Define the variable; this will not override any user definition.
744 Normally a reference to this variable is written into the value of
745 MAKEFLAGS, allowing the user to override this value to affect the
746 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
747 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
748 a reference to this hidden variable is written instead. */
749 (void) define_variable ("MAKEOVERRIDES", 13,
750 "${-*-command-variables-*-}", o_env, 1);
753 /* If there were -C flags, move ourselves about. */
754 if (directories != 0)
755 for (i = 0; directories->list[i] != 0; ++i)
757 char *dir = directories->list[i];
758 if (dir[0] == '~')
760 char *expanded = tilde_expand (dir);
761 if (expanded != 0)
762 dir = expanded;
764 if (chdir (dir) < 0)
765 pfatal_with_name (dir);
766 if (dir != directories->list[i])
767 free (dir);
770 #ifdef WIN32
772 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
773 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
775 * The functions in dir.c can incorrectly cache information for "."
776 * before we have changed directory and this can cause file
777 * lookups to fail because the current directory (.) was pointing
778 * at the wrong place when it was first evaluated.
782 * On Windows/NT, we don't have the luxury of a /bin directory that
783 * is mapped globally to every drive mounted to the system. Since make could
784 * be invoked from any drive, and we don't want to propogate /bin/sh
785 * to every single drive. Allow ourselves a chance to search for
786 * a value for default shell here (if the default path does not exist).
788 * The value of default_shell is set here, but it could get reset after
789 * the Makefiles are read in. See logic below where SHELL is checked
790 * after the call to read_all_makefiles() completes.
792 * The reason SHELL is set here is so that macros can be safely evaluated
793 * as makefiles are read in (some macros require $SHELL).
797 extern char *default_shell;
799 if (!file_exists_p(default_shell)) {
800 char *p;
801 struct variable *v = lookup_variable ("Path", 4);
804 * Try and make sure we have a full path to default_shell before
805 * we parse makefiles.
807 if (v && v->value) {
808 PATH_VAR(sh_path);
809 char *ep;
811 p = v->value;
812 ep = strchr(p, PATH_SEPARATOR_CHAR);
814 while (ep && *ep) {
815 *ep = '\0';
817 if (dir_file_exists_p(p, default_shell)) {
818 sprintf(sh_path, "%s/%s", p, default_shell);
819 default_shell = strdup(w32ify(sh_path,0));
820 no_default_sh_exe = 0;
821 *ep = PATH_SEPARATOR_CHAR;
823 /* terminate loop */
824 p += strlen(p);
825 } else {
826 *ep = PATH_SEPARATOR_CHAR;
827 p = ++ep;
830 ep = strchr(p, PATH_SEPARATOR_CHAR);
833 /* be sure to check last element of Path */
834 if (p && *p && dir_file_exists_p(p, default_shell)) {
835 sprintf(sh_path, "%s/%s", p, default_shell);
836 default_shell = strdup(w32ify(sh_path,0));
837 no_default_sh_exe = 0;
842 #endif /* WIN32 */
843 /* Figure out the level of recursion. */
845 struct variable *v = lookup_variable ("MAKELEVEL", 9);
846 if (v != 0 && *v->value != '\0' && *v->value != '-')
847 makelevel = (unsigned int) atoi (v->value);
848 else
849 makelevel = 0;
852 /* Except under -s, always do -w in sub-makes and under -C. */
853 if (!silent_flag && (directories != 0 || makelevel > 0))
854 print_directory_flag = 1;
856 /* Let the user disable that with --no-print-directory. */
857 if (inhibit_print_directory_flag)
858 print_directory_flag = 0;
860 /* Construct the list of include directories to search. */
862 construct_include_path (include_directories == 0 ? (char **) 0
863 : include_directories->list);
865 /* Figure out where we are now, after chdir'ing. */
866 if (directories == 0)
867 /* We didn't move, so we're still in the same place. */
868 starting_directory = current_directory;
869 else
871 #ifdef WIN32
872 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
873 #else
874 if (getcwd (current_directory, GET_PATH_MAX) == 0)
875 #endif
877 #ifdef HAVE_GETCWD
878 perror_with_name ("getcwd: ", "");
879 #else
880 error ("getwd: %s", current_directory);
881 #endif
882 starting_directory = 0;
884 else
885 starting_directory = current_directory;
888 /* Read any stdin makefiles into temporary files. */
890 if (makefiles != 0)
892 register unsigned int i;
893 for (i = 0; i < makefiles->idx; ++i)
894 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
896 /* This makefile is standard input. Since we may re-exec
897 and thus re-read the makefiles, we read standard input
898 into a temporary file and read from that. */
899 FILE *outfile;
901 /* Make a unique filename. */
902 #ifdef HAVE_MKTEMP
904 #ifdef VMS
905 static char name[] = "sys$scratch:GmXXXXXX";
906 #else
907 static char name[] = "/tmp/GmXXXXXX";
908 #endif
909 (void) mktemp (name);
910 #else
911 static char name[L_tmpnam];
912 (void) tmpnam (name);
913 #endif
915 outfile = fopen (name, "w");
916 if (outfile == 0)
917 pfatal_with_name ("fopen (temporary file)");
918 while (!feof (stdin))
920 char buf[2048];
921 unsigned int n = fread (buf, 1, sizeof(buf), stdin);
922 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
923 pfatal_with_name ("fwrite (temporary file)");
925 /* Try to make sure we won't remake the temporary
926 file when we are re-exec'd. Kludge-o-matic! */
927 fprintf (outfile, "%s:;\n", name);
928 (void) fclose (outfile);
930 /* Replace the name that read_all_makefiles will
931 see with the name of the temporary file. */
933 char *temp;
934 /* SGI compiler requires alloca's result be assigned simply. */
935 temp = (char *) alloca (sizeof (name));
936 bcopy (name, temp, sizeof (name));
937 makefiles->list[i] = temp;
940 /* Make sure the temporary file will not be remade. */
941 f = enter_file (savestring (name, sizeof name - 1));
942 f->updated = 1;
943 f->update_status = 0;
944 f->command_state = cs_finished;
945 /* Let it be removed when we're done. */
946 f->intermediate = 1;
947 /* But don't mention it. */
948 f->dontcare = 1;
952 /* Set up to handle children dying. This must be done before
953 reading in the makefiles so that `shell' function calls will work. */
955 #ifdef SIGCHLD
956 (void) signal (SIGCHLD, child_handler);
957 #endif
958 #ifdef SIGCLD
959 (void) signal (SIGCLD, child_handler);
960 #endif
962 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
963 #ifdef SIGUSR1
964 (void) signal (SIGUSR1, debug_signal_handler);
965 #endif
967 /* Define the initial list of suffixes for old-style rules. */
969 set_default_suffixes ();
971 /* Define the file rules for the built-in suffix rules. These will later
972 be converted into pattern rules. We used to do this in
973 install_default_implicit_rules, but since that happens after reading
974 makefiles, it results in the built-in pattern rules taking precedence
975 over makefile-specified suffix rules, which is wrong. */
977 install_default_suffix_rules ();
979 /* Define some internal and special variables. */
981 define_automatic_variables ();
983 /* Set up the MAKEFLAGS and MFLAGS variables
984 so makefiles can look at them. */
986 define_makeflags (0, 0);
988 #ifdef WIN32
990 * Now that makefiles are parsed, see if a Makefile gave a
991 * value for SHELL and use that for default_shell instead if
992 * that filename exists. This should speed up the
993 * construct_argv_internal() function by avoiding unnecessary
994 * recursion.
997 struct variable *v = lookup_variable("SHELL", 5);
998 extern char* default_shell;
1001 * to change value:
1003 * SHELL must be found, SHELL must be set, value of SHELL
1004 * must be different from current value, and the
1005 * specified file must exist. Whew!
1007 if (v != 0 && *v->value != '\0') {
1008 char *fn = recursively_expand(v);
1010 if (fn && strcmp(fn, default_shell) && file_exists_p(fn)) {
1011 char *p;
1013 default_shell = fn;
1015 /* if Makefile says SHELL is sh.exe, believe it */
1016 if (strstr(default_shell, "sh.exe"))
1017 no_default_sh_exe = 0;
1020 * Convert from backslashes to forward slashes so
1021 * create_command_line_argv_internal() is not confused.
1023 for (p = strchr(default_shell, '\\'); p; p = strchr(default_shell, '\\'))
1024 *p = '/';
1028 if (no_default_sh_exe && job_slots != 1) {
1029 error("Do not specify -j or --jobs if sh.exe is not available.");
1030 error("Resetting make for single job mode.");
1031 job_slots = 1;
1033 #endif /* WIN32 */
1035 /* Define the default variables. */
1036 define_default_variables ();
1038 /* Read all the makefiles. */
1040 default_file = enter_file (".DEFAULT");
1042 read_makefiles
1043 = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
1045 /* Decode switches again, in case the variables were set by the makefile. */
1046 decode_env_switches ("MAKEFLAGS", 9);
1047 #if 0
1048 decode_env_switches ("MFLAGS", 6);
1049 #endif
1051 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1053 define_makeflags (1, 0);
1055 /* Make each `struct dep' point at the `struct file' for the file
1056 depended on. Also do magic for special targets. */
1058 snap_deps ();
1060 /* Convert old-style suffix rules to pattern rules. It is important to
1061 do this before installing the built-in pattern rules below, so that
1062 makefile-specified suffix rules take precedence over built-in pattern
1063 rules. */
1065 convert_to_pattern ();
1067 /* Install the default implicit pattern rules.
1068 This used to be done before reading the makefiles.
1069 But in that case, built-in pattern rules were in the chain
1070 before user-defined ones, so they matched first. */
1072 install_default_implicit_rules ();
1074 /* Compute implicit rule limits. */
1076 count_implicit_rule_limits ();
1078 /* Construct the listings of directories in VPATH lists. */
1080 build_vpath_lists ();
1082 /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
1083 and as having been updated already, and files given with -W flags as
1084 brand new (time-stamp as far as possible into the future). */
1086 if (old_files != 0)
1087 for (p = old_files->list; *p != 0; ++p)
1089 f = enter_command_line_file (*p);
1090 f->last_mtime = (time_t) 1;
1091 f->updated = 1;
1092 f->update_status = 0;
1093 f->command_state = cs_finished;
1096 if (new_files != 0)
1098 for (p = new_files->list; *p != 0; ++p)
1100 f = enter_command_line_file (*p);
1101 f->last_mtime = NEW_MTIME;
1105 /* Initialize the remote job module. */
1106 remote_setup ();
1108 if (read_makefiles != 0)
1110 /* Update any makefiles if necessary. */
1112 time_t *makefile_mtimes = 0;
1113 unsigned int mm_idx = 0;
1115 if (debug_flag)
1116 puts ("Updating makefiles....");
1118 /* Remove any makefiles we don't want to try to update.
1119 Also record the current modtimes so we can compare them later. */
1121 register struct dep *d, *last;
1122 last = 0;
1123 d = read_makefiles;
1124 while (d != 0)
1126 register struct file *f = d->file;
1127 if (f->double_colon)
1128 for (f = f->double_colon; f != NULL; f = f->prev)
1130 if (f->deps == 0 && f->cmds != 0)
1132 /* This makefile is a :: target with commands, but
1133 no dependencies. So, it will always be remade.
1134 This might well cause an infinite loop, so don't
1135 try to remake it. (This will only happen if
1136 your makefiles are written exceptionally
1137 stupidly; but if you work for Athena, that's how
1138 you write your makefiles.) */
1140 if (debug_flag)
1141 printf ("Makefile `%s' might loop; not remaking it.\n",
1142 f->name);
1144 if (last == 0)
1145 read_makefiles = d->next;
1146 else
1147 last->next = d->next;
1149 /* Free the storage. */
1150 free ((char *) d);
1152 d = last == 0 ? 0 : last->next;
1154 break;
1157 if (f == NULL || !f->double_colon)
1159 if (makefile_mtimes == 0)
1160 makefile_mtimes = (time_t *) xmalloc (sizeof (time_t));
1161 else
1162 makefile_mtimes = (time_t *)
1163 xrealloc ((char *) makefile_mtimes,
1164 (mm_idx + 1) * sizeof (time_t));
1165 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
1166 last = d;
1167 d = d->next;
1172 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
1173 define_makeflags (1, 1);
1175 switch (update_goal_chain (read_makefiles, 1))
1177 case 1:
1178 default:
1179 #define BOGUS_UPDATE_STATUS 0
1180 assert (BOGUS_UPDATE_STATUS);
1181 break;
1183 case -1:
1184 /* Did nothing. */
1185 break;
1187 case 2:
1188 /* Failed to update. Figure out if we care. */
1190 /* Nonzero if any makefile was successfully remade. */
1191 int any_remade = 0;
1192 /* Nonzero if any makefile we care about failed
1193 in updating or could not be found at all. */
1194 int any_failed = 0;
1195 register unsigned int i;
1197 for (i = 0; read_makefiles != 0; ++i)
1199 struct dep *d = read_makefiles;
1200 read_makefiles = d->next;
1201 if (d->file->updated)
1203 /* This makefile was updated. */
1204 if (d->file->update_status == 0)
1206 /* It was successfully updated. */
1207 any_remade |= (file_mtime_no_search (d->file)
1208 != makefile_mtimes[i]);
1210 else if (! (d->changed & RM_DONTCARE))
1212 time_t mtime;
1213 /* The update failed and this makefile was not
1214 from the MAKEFILES variable, so we care. */
1215 error ("Failed to remake makefile `%s'.",
1216 d->file->name);
1217 mtime = file_mtime_no_search (d->file);
1218 any_remade |= (mtime != (time_t) -1
1219 && mtime != makefile_mtimes[i]);
1222 else
1223 /* This makefile was not found at all. */
1224 if (! (d->changed & RM_DONTCARE))
1226 /* This is a makefile we care about. See how much. */
1227 if (d->changed & RM_INCLUDED)
1228 /* An included makefile. We don't need
1229 to die, but we do want to complain. */
1230 error ("Included makefile `%s' was not found.",
1231 dep_name (d));
1232 else
1234 /* A normal makefile. We must die later. */
1235 error ("Makefile `%s' was not found", dep_name (d));
1236 any_failed = 1;
1240 free ((char *) d);
1243 if (any_remade)
1244 goto re_exec;
1245 else if (any_failed)
1246 die (2);
1247 else
1248 break;
1251 case 0:
1252 re_exec:
1253 /* Updated successfully. Re-exec ourselves. */
1255 remove_intermediates (0);
1257 if (print_data_base_flag)
1258 print_data_base ();
1260 log_working_directory (0);
1262 if (makefiles != 0)
1264 /* These names might have changed. */
1265 register unsigned int i, j = 0;
1266 for (i = 1; i < argc; ++i)
1267 if (!strcmp (argv[i], "-f")) /* XXX */
1269 char *p = &argv[i][2];
1270 if (*p == '\0')
1271 argv[++i] = makefiles->list[j];
1272 else
1273 argv[i] = concat ("-f", makefiles->list[j], "");
1274 ++j;
1278 if (directories != 0 && directories->idx > 0)
1280 char bad;
1281 if (directory_before_chdir != 0)
1283 if (chdir (directory_before_chdir) < 0)
1285 perror_with_name ("chdir", "");
1286 bad = 1;
1288 else
1289 bad = 0;
1291 else
1292 bad = 1;
1293 if (bad)
1294 fatal ("Couldn't change back to original directory.");
1297 #ifndef _AMIGA
1298 for (p = environ; *p != 0; ++p)
1299 if (!strncmp (*p, "MAKELEVEL=", 10))
1301 /* The SGI compiler apparently can't understand
1302 the concept of storing the result of a function
1303 in something other than a local variable. */
1304 char *sgi_loses;
1305 sgi_loses = (char *) alloca (40);
1306 *p = sgi_loses;
1307 sprintf (*p, "MAKELEVEL=%u", makelevel);
1308 break;
1310 #else /* AMIGA */
1312 char buffer[256];
1313 int len;
1315 len = GetVar ("MAKELEVEL", buffer, sizeof (buffer), GVF_GLOBAL_ONLY);
1317 if (len != -1)
1319 sprintf (buffer, "%u", makelevel);
1320 SetVar ("MAKELEVEL", buffer, -1, GVF_GLOBAL_ONLY);
1323 #endif
1325 if (debug_flag)
1327 char **p;
1328 fputs ("Re-executing:", stdout);
1329 for (p = argv; *p != 0; ++p)
1330 printf (" %s", *p);
1331 puts ("");
1334 fflush (stdout);
1335 fflush (stderr);
1337 #ifndef _AMIGA
1338 exec_command (argv, environ);
1339 #else
1340 exec_command (argv);
1341 exit (0);
1342 #endif
1343 /* NOTREACHED */
1347 /* Set up `MAKEFLAGS' again for the normal targets. */
1348 define_makeflags (1, 0);
1351 int status;
1353 /* If there were no command-line goals, use the default. */
1354 if (goals == 0)
1356 if (default_goal_file != 0)
1358 goals = (struct dep *) xmalloc (sizeof (struct dep));
1359 goals->next = 0;
1360 goals->name = 0;
1361 goals->file = default_goal_file;
1364 else
1365 lastgoal->next = 0;
1367 if (goals != 0)
1369 /* Update the goals. */
1371 if (debug_flag)
1372 puts ("Updating goal targets....");
1374 switch (update_goal_chain (goals, 0))
1376 case -1:
1377 /* Nothing happened. */
1378 case 0:
1379 /* Updated successfully. */
1380 status = EXIT_SUCCESS;
1381 break;
1382 case 2:
1383 /* Updating failed. POSIX.2 specifies exit status >1 for this;
1384 but in VMS, there is only success and failure. */
1385 status = EXIT_FAILURE ? 2 : EXIT_FAILURE;
1386 break;
1387 case 1:
1388 /* We are under -q and would run some commands. */
1389 status = EXIT_FAILURE;
1390 break;
1391 default:
1392 abort ();
1395 else
1397 if (read_makefiles == 0)
1398 fatal ("No targets specified and no makefile found");
1399 else
1400 fatal ("No targets");
1403 /* Exit. */
1404 die (status);
1407 return 0;
1410 /* Parsing of arguments, decoding of switches. */
1412 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
1413 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
1414 (sizeof (long_option_aliases) /
1415 sizeof (long_option_aliases[0]))];
1417 /* Fill in the string and vector for getopt. */
1418 static void
1419 init_switches ()
1421 register char *p;
1422 register int c;
1423 register unsigned int i;
1425 if (options[0] != '\0')
1426 /* Already done. */
1427 return;
1429 p = options;
1431 /* Return switch and non-switch args in order, regardless of
1432 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
1433 *p++ = '-';
1435 for (i = 0; switches[i].c != '\0'; ++i)
1437 long_options[i].name = (switches[i].long_name == 0 ? "" :
1438 switches[i].long_name);
1439 long_options[i].flag = 0;
1440 long_options[i].val = switches[i].c;
1441 if (isalnum (switches[i].c))
1442 *p++ = switches[i].c;
1443 switch (switches[i].type)
1445 case flag:
1446 case flag_off:
1447 case ignore:
1448 long_options[i].has_arg = no_argument;
1449 break;
1451 case string:
1452 case positive_int:
1453 case floating:
1454 if (isalnum (switches[i].c))
1455 *p++ = ':';
1456 if (switches[i].noarg_value != 0)
1458 if (isalnum (switches[i].c))
1459 *p++ = ':';
1460 long_options[i].has_arg = optional_argument;
1462 else
1463 long_options[i].has_arg = required_argument;
1464 break;
1467 *p = '\0';
1468 for (c = 0; c < (sizeof (long_option_aliases) /
1469 sizeof (long_option_aliases[0]));
1470 ++c)
1471 long_options[i++] = long_option_aliases[c];
1472 long_options[i].name = 0;
1475 static void
1476 handle_non_switch_argument (arg, env)
1477 char *arg;
1478 int env;
1480 /* Non-option argument. It might be a variable definition. */
1481 struct variable *v;
1482 if (arg[0] == '-' && arg[1] == '\0')
1483 /* Ignore plain `-' for compatibility. */
1484 return;
1485 v = try_variable_definition ((char *) 0, 0, arg, o_command);
1486 if (v != 0)
1488 /* It is indeed a variable definition. Record a pointer to
1489 the variable for later use in define_makeflags. */
1490 struct command_variable *cv
1491 = (struct command_variable *) xmalloc (sizeof (*cv));
1492 cv->variable = v;
1493 cv->next = command_variables;
1494 command_variables = cv;
1496 else if (! env)
1498 /* Not an option or variable definition; it must be a goal
1499 target! Enter it as a file and add it to the dep chain of
1500 goals. */
1501 struct file *f = enter_command_line_file (arg);
1502 f->cmd_target = 1;
1504 if (goals == 0)
1506 goals = (struct dep *) xmalloc (sizeof (struct dep));
1507 lastgoal = goals;
1509 else
1511 lastgoal->next
1512 = (struct dep *) xmalloc (sizeof (struct dep));
1513 lastgoal = lastgoal->next;
1515 lastgoal->name = 0;
1516 lastgoal->file = f;
1520 /* Decode switches from ARGC and ARGV.
1521 They came from the environment if ENV is nonzero. */
1523 static void
1524 decode_switches (argc, argv, env)
1525 int argc;
1526 char **argv;
1527 int env;
1529 int bad = 0;
1530 register const struct command_switch *cs;
1531 register struct stringlist *sl;
1532 register int c;
1534 /* getopt does most of the parsing for us.
1535 First, get its vectors set up. */
1537 init_switches ();
1539 /* Let getopt produce error messages for the command line,
1540 but not for options from the environment. */
1541 opterr = !env;
1542 /* Reset getopt's state. */
1543 optind = 0;
1545 while (optind < argc)
1547 /* Parse the next argument. */
1548 c = getopt_long (argc, argv, options, long_options, (int *) 0);
1549 if (c == EOF)
1550 /* End of arguments, or "--" marker seen. */
1551 break;
1552 else if (c == 1)
1553 /* An argument not starting with a dash. */
1554 handle_non_switch_argument (optarg, env);
1555 else if (c == '?')
1556 /* Bad option. We will print a usage message and die later.
1557 But continue to parse the other options so the user can
1558 see all he did wrong. */
1559 bad = 1;
1560 else
1561 for (cs = switches; cs->c != '\0'; ++cs)
1562 if (cs->c == c)
1564 /* Whether or not we will actually do anything with
1565 this switch. We test this individually inside the
1566 switch below rather than just once outside it, so that
1567 options which are to be ignored still consume args. */
1568 int doit = !env || cs->env;
1570 switch (cs->type)
1572 default:
1573 abort ();
1575 case ignore:
1576 break;
1578 case flag:
1579 case flag_off:
1580 if (doit)
1581 *(int *) cs->value_ptr = cs->type == flag;
1582 break;
1584 case string:
1585 if (!doit)
1586 break;
1588 if (optarg == 0)
1589 optarg = cs->noarg_value;
1591 sl = *(struct stringlist **) cs->value_ptr;
1592 if (sl == 0)
1594 sl = (struct stringlist *)
1595 xmalloc (sizeof (struct stringlist));
1596 sl->max = 5;
1597 sl->idx = 0;
1598 sl->list = (char **) xmalloc (5 * sizeof (char *));
1599 *(struct stringlist **) cs->value_ptr = sl;
1601 else if (sl->idx == sl->max - 1)
1603 sl->max += 5;
1604 sl->list = (char **)
1605 xrealloc ((char *) sl->list,
1606 sl->max * sizeof (char *));
1608 sl->list[sl->idx++] = optarg;
1609 sl->list[sl->idx] = 0;
1610 break;
1612 case positive_int:
1613 if (optarg == 0 && argc > optind
1614 && isdigit (argv[optind][0]))
1615 optarg = argv[optind++];
1617 if (!doit)
1618 break;
1620 if (optarg != 0)
1622 int i = atoi (optarg);
1623 if (i < 1)
1625 if (doit)
1626 error ("the `-%c' option requires a \
1627 positive integral argument",
1628 cs->c);
1629 bad = 1;
1631 else
1632 *(unsigned int *) cs->value_ptr = i;
1634 else
1635 *(unsigned int *) cs->value_ptr
1636 = *(unsigned int *) cs->noarg_value;
1637 break;
1639 #ifndef NO_FLOAT
1640 case floating:
1641 if (optarg == 0 && optind < argc
1642 && (isdigit (argv[optind][0]) || argv[optind][0] == '.'))
1643 optarg = argv[optind++];
1645 if (doit)
1646 *(double *) cs->value_ptr
1647 = (optarg != 0 ? atof (optarg)
1648 : *(double *) cs->noarg_value);
1650 break;
1651 #endif
1654 /* We've found the switch. Stop looking. */
1655 break;
1659 /* There are no more options according to getting getopt, but there may
1660 be some arguments left. Since we have asked for non-option arguments
1661 to be returned in order, this only happens when there is a "--"
1662 argument to prevent later arguments from being options. */
1663 while (optind < argc)
1664 handle_non_switch_argument (argv[optind++], env);
1667 if (!env && (bad || print_usage_flag))
1669 /* Print a nice usage message. */
1670 FILE *usageto;
1672 if (print_version_flag)
1673 print_version ();
1675 usageto = bad ? stderr : stdout;
1677 fprintf (usageto, "Usage: %s [options] [target] ...\n", program);
1679 fputs ("Options:\n", usageto);
1680 for (cs = switches; cs->c != '\0'; ++cs)
1682 char buf[1024], shortarg[50], longarg[50], *p;
1684 if (cs->description[0] == '-')
1685 continue;
1687 switch (long_options[cs - switches].has_arg)
1689 case no_argument:
1690 shortarg[0] = longarg[0] = '\0';
1691 break;
1692 case required_argument:
1693 sprintf (longarg, "=%s", cs->argdesc);
1694 sprintf (shortarg, " %s", cs->argdesc);
1695 break;
1696 case optional_argument:
1697 sprintf (longarg, "[=%s]", cs->argdesc);
1698 sprintf (shortarg, " [%s]", cs->argdesc);
1699 break;
1702 p = buf;
1704 if (isalnum (cs->c))
1706 sprintf (buf, " -%c%s", cs->c, shortarg);
1707 p += strlen (p);
1709 if (cs->long_name != 0)
1711 unsigned int i;
1712 sprintf (p, "%s--%s%s",
1713 !isalnum (cs->c) ? " " : ", ",
1714 cs->long_name, longarg);
1715 p += strlen (p);
1716 for (i = 0; i < (sizeof (long_option_aliases) /
1717 sizeof (long_option_aliases[0]));
1718 ++i)
1719 if (long_option_aliases[i].val == cs->c)
1721 sprintf (p, ", --%s%s",
1722 long_option_aliases[i].name, longarg);
1723 p += strlen (p);
1727 const struct command_switch *ncs = cs;
1728 while ((++ncs)->c != '\0')
1729 if (ncs->description[0] == '-' &&
1730 ncs->description[1] == cs->c)
1732 /* This is another switch that does the same
1733 one as the one we are processing. We want
1734 to list them all together on one line. */
1735 sprintf (p, ", -%c%s", ncs->c, shortarg);
1736 p += strlen (p);
1737 if (ncs->long_name != 0)
1739 sprintf (p, ", --%s%s", ncs->long_name, longarg);
1740 p += strlen (p);
1745 if (p - buf > DESCRIPTION_COLUMN - 2)
1746 /* The list of option names is too long to fit on the same
1747 line with the description, leaving at least two spaces.
1748 Print it on its own line instead. */
1750 fprintf (usageto, "%s\n", buf);
1751 buf[0] = '\0';
1754 fprintf (usageto, "%*s%s.\n",
1755 - DESCRIPTION_COLUMN,
1756 buf, cs->description);
1759 die (bad ? 2 : 0);
1763 /* Decode switches from environment variable ENVAR (which is LEN chars long).
1764 We do this by chopping the value into a vector of words, prepending a
1765 dash to the first word if it lacks one, and passing the vector to
1766 decode_switches. */
1768 static void
1769 decode_env_switches (envar, len)
1770 char *envar;
1771 unsigned int len;
1773 char *varref = (char *) alloca (2 + len + 2);
1774 char *value, *p;
1775 int argc;
1776 char **argv;
1778 /* Get the variable's value. */
1779 varref[0] = '$';
1780 varref[1] = '(';
1781 bcopy (envar, &varref[2], len);
1782 varref[2 + len] = ')';
1783 varref[2 + len + 1] = '\0';
1784 value = variable_expand (varref);
1786 /* Skip whitespace, and check for an empty value. */
1787 value = next_token (value);
1788 len = strlen (value);
1789 if (len == 0)
1790 return;
1792 /* Allocate a vector that is definitely big enough. */
1793 argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
1795 /* Allocate a buffer to copy the value into while we split it into words
1796 and unquote it. We must use permanent storage for this because
1797 decode_switches may store pointers into the passed argument words. */
1798 p = (char *) xmalloc (2 * len);
1800 /* getopt will look at the arguments starting at ARGV[1].
1801 Prepend a spacer word. */
1802 argv[0] = 0;
1803 argc = 1;
1804 argv[argc] = p;
1805 while (*value != '\0')
1807 if (*value == '\\')
1808 ++value; /* Skip the backslash. */
1809 else if (isblank (*value))
1811 /* End of the word. */
1812 *p++ = '\0';
1813 argv[++argc] = p;
1815 ++value;
1816 while (isblank (*value));
1817 continue;
1819 *p++ = *value++;
1821 *p = '\0';
1822 argv[++argc] = 0;
1824 if (argv[1][0] != '-' && index (argv[1], '=') == 0)
1825 /* The first word doesn't start with a dash and isn't a variable
1826 definition. Add a dash and pass it along to decode_switches. We
1827 need permanent storage for this in case decode_switches saves
1828 pointers into the value. */
1829 argv[1] = concat ("-", argv[1], "");
1831 /* Parse those words. */
1832 decode_switches (argc, argv, 1);
1835 /* Quote the string IN so that it will be interpreted as a single word with
1836 no magic by the shell; if DOUBLE_DOLLARS is nonzero, also double dollar
1837 signs to avoid variable expansion in make itself. Write the result into
1838 OUT, returning the address of the next character to be written.
1839 Allocating space for OUT twice the length of IN (thrice if
1840 DOUBLE_DOLLARS is nonzero) is always sufficient. */
1842 static char *
1843 quote_as_word (out, in, double_dollars)
1844 char *out, *in;
1845 int double_dollars;
1847 while (*in != '\0')
1849 #ifdef VMS
1850 if (index ("^;'\"*?$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
1851 #else
1852 if (index ("^;'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
1853 #endif
1854 *out++ = '\\';
1855 if (double_dollars && *in == '$')
1856 *out++ = '$';
1857 *out++ = *in++;
1860 return out;
1863 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
1864 command switches. Include options with args if ALL is nonzero.
1865 Don't include options with the `no_makefile' flag set if MAKEFILE. */
1867 static void
1868 define_makeflags (all, makefile)
1869 int all, makefile;
1871 static const char ref[] = "$(MAKEOVERRIDES)";
1872 static const char posixref[] = "$(-*-command-variables-*-)";
1873 register const struct command_switch *cs;
1874 char *flagstring;
1875 register char *p;
1876 unsigned int words;
1877 struct variable *v;
1879 /* We will construct a linked list of `struct flag's describing
1880 all the flags which need to go in MAKEFLAGS. Then, once we
1881 know how many there are and their lengths, we can put them all
1882 together in a string. */
1884 struct flag
1886 struct flag *next;
1887 const struct command_switch *cs;
1888 char *arg;
1890 struct flag *flags = 0;
1891 unsigned int flagslen = 0;
1892 #define ADD_FLAG(ARG, LEN) \
1893 do { \
1894 struct flag *new = (struct flag *) alloca (sizeof (struct flag)); \
1895 new->cs = cs; \
1896 new->arg = (ARG); \
1897 new->next = flags; \
1898 flags = new; \
1899 if (new->arg == 0) \
1900 ++flagslen; /* Just a single flag letter. */ \
1901 else \
1902 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
1903 if (!isalnum (cs->c)) \
1904 /* This switch has no single-letter version, so we use the long. */ \
1905 flagslen += 2 + strlen (cs->long_name); \
1906 } while (0)
1908 for (cs = switches; cs->c != '\0'; ++cs)
1909 if (cs->toenv && (!makefile || !cs->no_makefile))
1910 switch (cs->type)
1912 default:
1913 abort ();
1915 case ignore:
1916 break;
1918 case flag:
1919 case flag_off:
1920 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
1921 && (cs->default_value == 0
1922 || *(int *) cs->value_ptr != *(int *) cs->default_value))
1923 ADD_FLAG (0, 0);
1924 break;
1926 case positive_int:
1927 if (all)
1929 if ((cs->default_value != 0
1930 && (*(unsigned int *) cs->value_ptr
1931 == *(unsigned int *) cs->default_value)))
1932 break;
1933 else if (cs->noarg_value != 0
1934 && (*(unsigned int *) cs->value_ptr ==
1935 *(unsigned int *) cs->noarg_value))
1936 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
1937 else if (cs->c == 'j')
1938 /* Special case for `-j'. */
1939 ADD_FLAG ("1", 1);
1940 else
1942 char *buf = (char *) alloca (30);
1943 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
1944 ADD_FLAG (buf, strlen (buf));
1947 break;
1949 #ifndef NO_FLOAT
1950 case floating:
1951 if (all)
1953 if (cs->default_value != 0
1954 && (*(double *) cs->value_ptr
1955 == *(double *) cs->default_value))
1956 break;
1957 else if (cs->noarg_value != 0
1958 && (*(double *) cs->value_ptr
1959 == *(double *) cs->noarg_value))
1960 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
1961 else
1963 char *buf = (char *) alloca (100);
1964 sprintf (buf, "%g", *(double *) cs->value_ptr);
1965 ADD_FLAG (buf, strlen (buf));
1968 break;
1969 #endif
1971 case string:
1972 if (all)
1974 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
1975 if (sl != 0)
1977 /* Add the elements in reverse order, because
1978 all the flags get reversed below; and the order
1979 matters for some switches (like -I). */
1980 register unsigned int i = sl->idx;
1981 while (i-- > 0)
1982 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
1985 break;
1988 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
1990 #undef ADD_FLAG
1992 /* Construct the value in FLAGSTRING.
1993 We allocate enough space for a preceding dash and trailing null. */
1994 flagstring = (char *) alloca (1 + flagslen + 1);
1995 p = flagstring;
1996 words = 1;
1997 *p++ = '-';
1998 while (flags != 0)
2000 /* Add the flag letter or name to the string. */
2001 if (!isalnum (flags->cs->c))
2003 *p++ = '-';
2004 strcpy (p, flags->cs->long_name);
2005 p += strlen (p);
2007 else
2008 *p++ = flags->cs->c;
2009 if (flags->arg != 0)
2011 /* A flag that takes an optional argument which in this case is
2012 omitted is specified by ARG being "". We must distinguish
2013 because a following flag appended without an intervening " -"
2014 is considered the arg for the first. */
2015 if (flags->arg[0] != '\0')
2017 /* Add its argument too. */
2018 *p++ = !isalnum (flags->cs->c) ? '=' : ' ';
2019 p = quote_as_word (p, flags->arg, 1);
2021 ++words;
2022 /* Write a following space and dash, for the next flag. */
2023 *p++ = ' ';
2024 *p++ = '-';
2026 else if (!isalnum (flags->cs->c))
2028 ++words;
2029 /* Long options must each go in their own word,
2030 so we write the following space and dash. */
2031 *p++ = ' ';
2032 *p++ = '-';
2034 flags = flags->next;
2037 /* Define MFLAGS before appending variable definitions. */
2039 if (p == &flagstring[1])
2040 /* No flags. */
2041 flagstring[0] = '\0';
2042 else if (p[-1] == '-')
2044 /* Kill the final space and dash. */
2045 p -= 2;
2046 *p = '\0';
2048 else
2049 /* Terminate the string. */
2050 *p = '\0';
2052 /* Since MFLAGS is not parsed for flags, there is no reason to
2053 override any makefile redefinition. */
2054 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
2056 if (all && command_variables != 0)
2058 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
2059 command-line variable definitions. */
2061 if (p == &flagstring[1])
2062 /* No flags written, so elide the leading dash already written. */
2063 p = flagstring;
2064 else
2066 /* Separate the variables from the switches with a "--" arg. */
2067 if (p[-1] != '-')
2069 /* We did not already write a trailing " -". */
2070 *p++ = ' ';
2071 *p++ = '-';
2073 /* There is a trailing " -"; fill it out to " -- ". */
2074 *p++ = '-';
2075 *p++ = ' ';
2078 /* Copy in the string. */
2079 if (posix_pedantic)
2081 bcopy (posixref, p, sizeof posixref - 1);
2082 p += sizeof posixref - 1;
2084 else
2086 bcopy (ref, p, sizeof ref - 1);
2087 p += sizeof ref - 1;
2090 else if (p == &flagstring[1])
2092 words = 0;
2093 --p;
2095 else if (p[-1] == '-')
2096 /* Kill the final space and dash. */
2097 p -= 2;
2098 /* Terminate the string. */
2099 *p = '\0';
2101 v = define_variable ("MAKEFLAGS", 9,
2102 /* If there are switches, omit the leading dash
2103 unless it is a single long option with two
2104 leading dashes. */
2105 &flagstring[(flagstring[0] == '-'
2106 && flagstring[1] != '-')
2107 ? 1 : 0],
2108 /* This used to use o_env, but that lost when a
2109 makefile defined MAKEFLAGS. Makefiles set
2110 MAKEFLAGS to add switches, but we still want
2111 to redefine its value with the full set of
2112 switches. Of course, an override or command
2113 definition will still take precedence. */
2114 o_file, 1);
2115 if (! all)
2116 /* The first time we are called, set MAKEFLAGS to always be exported.
2117 We should not do this again on the second call, because that is
2118 after reading makefiles which might have done `unexport MAKEFLAGS'. */
2119 v->export = v_export;
2122 /* Print version information. */
2124 static void
2125 print_version ()
2127 static int printed_version = 0;
2129 char *precede = print_data_base_flag ? "# " : "";
2131 if (printed_version)
2132 /* Do it only once. */
2133 return;
2135 printf ("%sGNU Make version %s", precede, version_string);
2136 if (remote_description != 0 && *remote_description != '\0')
2137 printf ("-%s", remote_description);
2139 printf (", by Richard Stallman and Roland McGrath.\n\
2140 %sCopyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96\n\
2141 %s\tFree Software Foundation, Inc.\n\
2142 %sThis is free software; see the source for copying conditions.\n\
2143 %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
2144 %sPARTICULAR PURPOSE.\n\n\
2145 %sReport bugs to <bug-gnu-utils@prep.ai.mit.edu>.\n\n",
2146 precede, precede, precede, precede, precede, precede);
2148 printed_version = 1;
2150 /* Flush stdout so the user doesn't have to wait to see the
2151 version information while things are thought about. */
2152 fflush (stdout);
2155 /* Print a bunch of information about this and that. */
2157 static void
2158 print_data_base ()
2160 time_t when;
2162 when = time ((time_t *) 0);
2163 printf ("\n# Make data base, printed on %s", ctime (&when));
2165 print_variable_data_base ();
2166 print_dir_data_base ();
2167 print_rule_data_base ();
2168 print_file_data_base ();
2169 print_vpath_data_base ();
2171 when = time ((time_t *) 0);
2172 printf ("\n# Finished Make data base on %s\n", ctime (&when));
2175 /* Exit with STATUS, cleaning up as necessary. */
2177 void
2178 die (status)
2179 int status;
2181 static char dying = 0;
2183 if (!dying)
2185 int err;
2187 dying = 1;
2189 /* Try to move back to the original directory. This is essential on
2190 MS-DOS (where there is really only one process), and on Unix it
2191 puts core files in the original directory instead of the -C
2192 directory. */
2193 if (directory_before_chdir != 0)
2194 chdir (directory_before_chdir);
2196 if (print_version_flag)
2197 print_version ();
2199 /* Wait for children to die. */
2200 for (err = status != 0; job_slots_used > 0; err = 0)
2201 reap_children (1, err);
2203 /* Let the remote job module clean up its state. */
2204 remote_cleanup ();
2206 /* Remove the intermediate files. */
2207 remove_intermediates (0);
2209 if (print_data_base_flag)
2210 print_data_base ();
2212 log_working_directory (0);
2215 exit (status);
2218 /* Write a message indicating that we've just entered or
2219 left (according to ENTERING) the current directory. */
2221 void
2222 log_working_directory (entering)
2223 int entering;
2225 static int entered = 0;
2226 char *message = entering ? "Entering" : "Leaving";
2228 /* Print nothing without the flag. Don't print the entering message
2229 again if we already have. Don't print the leaving message if we
2230 haven't printed the entering message. */
2231 if (! print_directory_flag || entering == entered)
2232 return;
2234 entered = entering;
2236 if (print_data_base_flag)
2237 fputs ("# ", stdout);
2239 if (makelevel == 0)
2240 printf ("%s: %s ", program, message);
2241 else
2242 printf ("%s[%u]: %s ", program, makelevel, message);
2244 if (starting_directory == 0)
2245 puts ("an unknown directory");
2246 else
2247 printf ("directory `%s'\n", starting_directory);