Another round of cleanups:
[make.git] / main.c
blob126c914be43109bc16a6d2363b798370102781e8
1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 2, or (at your option) any later version.
11 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along with
16 GNU Make; see the file COPYING. If not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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 "rule.h"
26 #include "debug.h"
27 #include "getopt.h"
29 #include <assert.h>
30 #ifdef _AMIGA
31 # include <dos/dos.h>
32 # include <proto/dos.h>
33 #endif
34 #ifdef WINDOWS32
35 #include <windows.h>
36 #include <io.h>
37 #include "pathstuff.h"
38 #endif
39 #ifdef __EMX__
40 # include <sys/types.h>
41 # include <sys/wait.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 # include <fcntl.h>
45 #endif
47 #if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
48 # define SET_STACK_SIZE
49 #endif
51 #ifdef SET_STACK_SIZE
52 # include <sys/resource.h>
53 #endif
55 #ifdef _AMIGA
56 int __stack = 20000; /* Make sure we have 20K of stack space */
57 #endif
59 void init_dir (void);
60 void remote_setup (void);
61 void remote_cleanup (void);
62 RETSIGTYPE fatal_error_signal (int sig);
64 void print_variable_data_base (void);
65 void print_dir_data_base (void);
66 void print_rule_data_base (void);
67 void print_file_data_base (void);
68 void print_vpath_data_base (void);
70 #if defined HAVE_WAITPID || defined HAVE_WAIT3
71 # define HAVE_WAIT_NOHANG
72 #endif
74 #ifndef HAVE_UNISTD_H
75 int chdir ();
76 #endif
77 #ifndef STDC_HEADERS
78 # ifndef sun /* Sun has an incorrect decl in a header. */
79 void exit (int) __attribute__ ((noreturn));
80 # endif
81 double atof ();
82 #endif
84 static void clean_jobserver (int status);
85 static void print_data_base (void);
86 static void print_version (void);
87 static void decode_switches (int argc, char **argv, int env);
88 static void decode_env_switches (char *envar, unsigned int len);
89 static void define_makeflags (int all, int makefile);
90 static char *quote_for_env (char *out, char *in);
91 static void initialize_global_hash_tables (void);
94 /* The structure that describes an accepted command switch. */
96 struct command_switch
98 int c; /* The switch character. */
100 enum /* Type of the value. */
102 flag, /* Turn int flag on. */
103 flag_off, /* Turn int flag off. */
104 string, /* One string per switch. */
105 positive_int, /* A positive integer. */
106 floating, /* A floating-point number (double). */
107 ignore /* Ignored. */
108 } type;
110 char *value_ptr; /* Pointer to the value-holding variable. */
112 unsigned int env:1; /* Can come from MAKEFLAGS. */
113 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
114 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
116 char *noarg_value; /* Pointer to value used if no argument is given. */
117 char *default_value;/* Pointer to default value. */
119 char *long_name; /* Long option name. */
122 /* True if C is a switch value that corresponds to a short option. */
124 #define short_option(c) ((c) <= CHAR_MAX)
126 /* The structure used to hold the list of strings given
127 in command switches of a type that takes string arguments. */
129 struct stringlist
131 char **list; /* Nil-terminated list of strings. */
132 unsigned int idx; /* Index into above. */
133 unsigned int max; /* Number of pointers allocated. */
137 /* The recognized command switches. */
139 /* Nonzero means do not print commands to be executed (-s). */
141 int silent_flag;
143 /* Nonzero means just touch the files
144 that would appear to need remaking (-t) */
146 int touch_flag;
148 /* Nonzero means just print what commands would need to be executed,
149 don't actually execute them (-n). */
151 int just_print_flag;
153 /* Print debugging info (--debug). */
155 static struct stringlist *db_flags;
156 static int debug_flag = 0;
158 int db_level = 0;
160 #ifdef WINDOWS32
161 /* Suspend make in main for a short time to allow debugger to attach */
163 int suspend_flag = 0;
164 #endif
166 /* Environment variables override makefile definitions. */
168 int env_overrides = 0;
170 /* Nonzero means ignore status codes returned by commands
171 executed to remake files. Just treat them all as successful (-i). */
173 int ignore_errors_flag = 0;
175 /* Nonzero means don't remake anything, just print the data base
176 that results from reading the makefile (-p). */
178 int print_data_base_flag = 0;
180 /* Nonzero means don't remake anything; just return a nonzero status
181 if the specified targets are not up to date (-q). */
183 int question_flag = 0;
185 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
187 int no_builtin_rules_flag = 0;
188 int no_builtin_variables_flag = 0;
190 /* Nonzero means keep going even if remaking some file fails (-k). */
192 int keep_going_flag;
193 int default_keep_going_flag = 0;
195 /* Nonzero means check symlink mtimes. */
197 int check_symlink_flag = 0;
199 /* Nonzero means print directory before starting and when done (-w). */
201 int print_directory_flag = 0;
203 /* Nonzero means ignore print_directory_flag and never print the directory.
204 This is necessary because print_directory_flag is set implicitly. */
206 int inhibit_print_directory_flag = 0;
208 /* Nonzero means print version information. */
210 int print_version_flag = 0;
212 /* List of makefiles given with -f switches. */
214 static struct stringlist *makefiles = 0;
216 /* Number of job slots (commands that can be run at once). */
218 unsigned int job_slots = 1;
219 unsigned int default_job_slots = 1;
220 static unsigned int master_job_slots = 0;
222 /* Value of job_slots that means no limit. */
224 static unsigned int inf_jobs = 0;
226 /* File descriptors for the jobs pipe. */
228 static struct stringlist *jobserver_fds = 0;
230 int job_fds[2] = { -1, -1 };
231 int job_rfd = -1;
233 /* Maximum load average at which multiple jobs will be run.
234 Negative values mean unlimited, while zero means limit to
235 zero load (which could be useful to start infinite jobs remotely
236 but one at a time locally). */
237 #ifndef NO_FLOAT
238 double max_load_average = -1.0;
239 double default_load_average = -1.0;
240 #else
241 int max_load_average = -1;
242 int default_load_average = -1;
243 #endif
245 /* List of directories given with -C switches. */
247 static struct stringlist *directories = 0;
249 /* List of include directories given with -I switches. */
251 static struct stringlist *include_directories = 0;
253 /* List of files given with -o switches. */
255 static struct stringlist *old_files = 0;
257 /* List of files given with -W switches. */
259 static struct stringlist *new_files = 0;
261 /* If nonzero, we should just print usage and exit. */
263 static int print_usage_flag = 0;
265 /* If nonzero, we should print a warning message
266 for each reference to an undefined variable. */
268 int warn_undefined_variables_flag;
270 /* If nonzero, always build all targets, regardless of whether
271 they appear out of date or not. */
273 static int always_make_set = 0;
274 int always_make_flag = 0;
276 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
278 int rebuilding_makefiles = 0;
280 /* Remember the original value of the SHELL variable, from the environment. */
282 struct variable shell_var;
285 /* The usage output. We write it this way to make life easier for the
286 translators, especially those trying to translate to right-to-left
287 languages like Hebrew. */
289 static const char *const usage[] =
291 N_("Options:\n"),
292 N_("\
293 -b, -m Ignored for compatibility.\n"),
294 N_("\
295 -B, --always-make Unconditionally make all targets.\n"),
296 N_("\
297 -C DIRECTORY, --directory=DIRECTORY\n\
298 Change to DIRECTORY before doing anything.\n"),
299 N_("\
300 -d Print lots of debugging information.\n"),
301 N_("\
302 --debug[=FLAGS] Print various types of debugging information.\n"),
303 N_("\
304 -e, --environment-overrides\n\
305 Environment variables override makefiles.\n"),
306 N_("\
307 -f FILE, --file=FILE, --makefile=FILE\n\
308 Read FILE as a makefile.\n"),
309 N_("\
310 -h, --help Print this message and exit.\n"),
311 N_("\
312 -i, --ignore-errors Ignore errors from commands.\n"),
313 N_("\
314 -I DIRECTORY, --include-dir=DIRECTORY\n\
315 Search DIRECTORY for included makefiles.\n"),
316 N_("\
317 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
318 N_("\
319 -k, --keep-going Keep going when some targets can't be made.\n"),
320 N_("\
321 -l [N], --load-average[=N], --max-load[=N]\n\
322 Don't start multiple jobs unless load is below N.\n"),
323 N_("\
324 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
325 N_("\
326 -n, --just-print, --dry-run, --recon\n\
327 Don't actually run any commands; just print them.\n"),
328 N_("\
329 -o FILE, --old-file=FILE, --assume-old=FILE\n\
330 Consider FILE to be very old and don't remake it.\n"),
331 N_("\
332 -p, --print-data-base Print make's internal database.\n"),
333 N_("\
334 -q, --question Run no commands; exit status says if up to date.\n"),
335 N_("\
336 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
337 N_("\
338 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
339 N_("\
340 -s, --silent, --quiet Don't echo commands.\n"),
341 N_("\
342 -S, --no-keep-going, --stop\n\
343 Turns off -k.\n"),
344 N_("\
345 -t, --touch Touch targets instead of remaking them.\n"),
346 N_("\
347 -v, --version Print the version number of make and exit.\n"),
348 N_("\
349 -w, --print-directory Print the current directory.\n"),
350 N_("\
351 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
352 N_("\
353 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
354 Consider FILE to be infinitely new.\n"),
355 N_("\
356 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
357 NULL
360 /* The table of command switches. */
362 static const struct command_switch switches[] =
364 { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
365 { 'B', flag, (char *) &always_make_set, 1, 1, 0, 0, 0, "always-make" },
366 { 'C', string, (char *) &directories, 0, 0, 0, 0, 0, "directory" },
367 { 'd', flag, (char *) &debug_flag, 1, 1, 0, 0, 0, 0 },
368 { CHAR_MAX+1, string, (char *) &db_flags, 1, 1, 0, "basic", 0, "debug" },
369 #ifdef WINDOWS32
370 { 'D', flag, (char *) &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
371 #endif
372 { 'e', flag, (char *) &env_overrides, 1, 1, 0, 0, 0,
373 "environment-overrides", },
374 { 'f', string, (char *) &makefiles, 0, 0, 0, 0, 0, "file" },
375 { 'h', flag, (char *) &print_usage_flag, 0, 0, 0, 0, 0, "help" },
376 { 'i', flag, (char *) &ignore_errors_flag, 1, 1, 0, 0, 0,
377 "ignore-errors" },
378 { 'I', string, (char *) &include_directories, 1, 1, 0, 0, 0,
379 "include-dir" },
380 { 'j', positive_int, (char *) &job_slots, 1, 1, 0, (char *) &inf_jobs,
381 (char *) &default_job_slots, "jobs" },
382 { CHAR_MAX+2, string, (char *) &jobserver_fds, 1, 1, 0, 0, 0,
383 "jobserver-fds" },
384 { 'k', flag, (char *) &keep_going_flag, 1, 1, 0, 0,
385 (char *) &default_keep_going_flag, "keep-going" },
386 #ifndef NO_FLOAT
387 { 'l', floating, (char *) &max_load_average, 1, 1, 0,
388 (char *) &default_load_average, (char *) &default_load_average,
389 "load-average" },
390 #else
391 { 'l', positive_int, (char *) &max_load_average, 1, 1, 0,
392 (char *) &default_load_average, (char *) &default_load_average,
393 "load-average" },
394 #endif
395 { 'L', flag, (char *) &check_symlink_flag, 1, 1, 0, 0, 0,
396 "check-symlink-times" },
397 { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
398 { 'n', flag, (char *) &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
399 { 'o', string, (char *) &old_files, 0, 0, 0, 0, 0, "old-file" },
400 { 'p', flag, (char *) &print_data_base_flag, 1, 1, 0, 0, 0,
401 "print-data-base" },
402 { 'q', flag, (char *) &question_flag, 1, 1, 1, 0, 0, "question" },
403 { 'r', flag, (char *) &no_builtin_rules_flag, 1, 1, 0, 0, 0,
404 "no-builtin-rules" },
405 { 'R', flag, (char *) &no_builtin_variables_flag, 1, 1, 0, 0, 0,
406 "no-builtin-variables" },
407 { 's', flag, (char *) &silent_flag, 1, 1, 0, 0, 0, "silent" },
408 { 'S', flag_off, (char *) &keep_going_flag, 1, 1, 0, 0,
409 (char *) &default_keep_going_flag, "no-keep-going" },
410 { 't', flag, (char *) &touch_flag, 1, 1, 1, 0, 0, "touch" },
411 { 'v', flag, (char *) &print_version_flag, 1, 1, 0, 0, 0, "version" },
412 { 'w', flag, (char *) &print_directory_flag, 1, 1, 0, 0, 0,
413 "print-directory" },
414 { CHAR_MAX+3, flag, (char *) &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
415 "no-print-directory" },
416 { 'W', string, (char *) &new_files, 0, 0, 0, 0, 0, "what-if" },
417 { CHAR_MAX+4, flag, (char *) &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
418 "warn-undefined-variables" },
419 { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
422 /* Secondary long names for options. */
424 static struct option long_option_aliases[] =
426 { "quiet", no_argument, 0, 's' },
427 { "stop", no_argument, 0, 'S' },
428 { "new-file", required_argument, 0, 'W' },
429 { "assume-new", required_argument, 0, 'W' },
430 { "assume-old", required_argument, 0, 'o' },
431 { "max-load", optional_argument, 0, 'l' },
432 { "dry-run", no_argument, 0, 'n' },
433 { "recon", no_argument, 0, 'n' },
434 { "makefile", required_argument, 0, 'f' },
437 /* List of goal targets. */
439 static struct dep *goals, *lastgoal;
441 /* List of variables which were defined on the command line
442 (or, equivalently, in MAKEFLAGS). */
444 struct command_variable
446 struct command_variable *next;
447 struct variable *variable;
449 static struct command_variable *command_variables;
451 /* The name we were invoked with. */
453 char *program;
455 /* Our current directory before processing any -C options. */
457 char *directory_before_chdir;
459 /* Our current directory after processing all -C options. */
461 char *starting_directory;
463 /* Value of the MAKELEVEL variable at startup (or 0). */
465 unsigned int makelevel;
467 /* First file defined in the makefile whose name does not
468 start with `.'. This is the default to remake if the
469 command line does not specify. */
471 struct file *default_goal_file;
473 /* Pointer to the value of the .DEFAULT_GOAL special
474 variable. */
475 char ** default_goal_name;
477 /* Pointer to structure for the file .DEFAULT
478 whose commands are used for any file that has none of its own.
479 This is zero if the makefiles do not define .DEFAULT. */
481 struct file *default_file;
483 /* Nonzero if we have seen the magic `.POSIX' target.
484 This turns on pedantic compliance with POSIX.2. */
486 int posix_pedantic;
488 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
489 This turns on secondary expansion of prerequisites. */
491 int second_expansion;
493 /* Nonzero if we have seen the `.NOTPARALLEL' target.
494 This turns off parallel builds for this invocation of make. */
496 int not_parallel;
498 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
499 print one warning about it during the run, and (b) we can print a final
500 warning at the end of the run. */
502 int clock_skew_detected;
504 /* Mask of signals that are being caught with fatal_error_signal. */
506 #ifdef POSIX
507 sigset_t fatal_signal_set;
508 #else
509 # ifdef HAVE_SIGSETMASK
510 int fatal_signal_mask;
511 # endif
512 #endif
514 #if !defined HAVE_BSD_SIGNAL && !defined bsd_signal
515 # if !defined HAVE_SIGACTION
516 # define bsd_signal signal
517 # else
518 typedef RETSIGTYPE (*bsd_signal_ret_t) ();
520 static bsd_signal_ret_t
521 bsd_signal (int sig, bsd_signal_ret_t func)
523 struct sigaction act, oact;
524 act.sa_handler = func;
525 act.sa_flags = SA_RESTART;
526 sigemptyset (&act.sa_mask);
527 sigaddset (&act.sa_mask, sig);
528 if (sigaction (sig, &act, &oact) != 0)
529 return SIG_ERR;
530 return oact.sa_handler;
532 # endif
533 #endif
535 static void
536 initialize_global_hash_tables (void)
538 init_hash_global_variable_set ();
539 strcache_init ();
540 init_hash_files ();
541 hash_init_directories ();
542 hash_init_function_table ();
545 static struct file *
546 enter_command_line_file (char *name)
548 if (name[0] == '\0')
549 fatal (NILF, _("empty string invalid as file name"));
551 if (name[0] == '~')
553 char *expanded = tilde_expand (name);
554 if (expanded != 0)
555 name = expanded; /* Memory leak; I don't care. */
558 /* This is also done in parse_file_seq, so this is redundant
559 for names read from makefiles. It is here for names passed
560 on the command line. */
561 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
563 name += 2;
564 while (*name == '/')
565 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
566 ++name;
569 if (*name == '\0')
571 /* It was all slashes! Move back to the dot and truncate
572 it after the first slash, so it becomes just "./". */
574 --name;
575 while (name[0] != '.');
576 name[2] = '\0';
579 return enter_file (xstrdup (name));
582 /* Toggle -d on receipt of SIGUSR1. */
584 #ifdef SIGUSR1
585 static RETSIGTYPE
586 debug_signal_handler (int sig UNUSED)
588 db_level = db_level ? DB_NONE : DB_BASIC;
590 #endif
592 static void
593 decode_debug_flags (void)
595 char **pp;
597 if (debug_flag)
598 db_level = DB_ALL;
600 if (!db_flags)
601 return;
603 for (pp=db_flags->list; *pp; ++pp)
605 const char *p = *pp;
607 while (1)
609 switch (tolower (p[0]))
611 case 'a':
612 db_level |= DB_ALL;
613 break;
614 case 'b':
615 db_level |= DB_BASIC;
616 break;
617 case 'i':
618 db_level |= DB_BASIC | DB_IMPLICIT;
619 break;
620 case 'j':
621 db_level |= DB_JOBS;
622 break;
623 case 'm':
624 db_level |= DB_BASIC | DB_MAKEFILES;
625 break;
626 case 'v':
627 db_level |= DB_BASIC | DB_VERBOSE;
628 break;
629 default:
630 fatal (NILF, _("unknown debug level specification `%s'"), p);
633 while (*(++p) != '\0')
634 if (*p == ',' || *p == ' ')
635 break;
637 if (*p == '\0')
638 break;
640 ++p;
645 #ifdef WINDOWS32
647 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
648 * exception and print it to stderr instead.
650 * If ! DB_VERBOSE, just print a simple message and exit.
651 * If DB_VERBOSE, print a more verbose message.
652 * If compiled for DEBUG, let exception pass through to GUI so that
653 * debuggers can attach.
655 LONG WINAPI
656 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
658 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
659 LPSTR cmdline = GetCommandLine();
660 LPSTR prg = strtok(cmdline, " ");
661 CHAR errmsg[1024];
662 #ifdef USE_EVENT_LOG
663 HANDLE hEventSource;
664 LPTSTR lpszStrings[1];
665 #endif
667 if (! ISDB (DB_VERBOSE))
669 sprintf(errmsg,
670 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%lx)\n"),
671 prg, exrec->ExceptionCode, (DWORD)exrec->ExceptionAddress);
672 fprintf(stderr, errmsg);
673 exit(255);
676 sprintf(errmsg,
677 _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = %lx\n"),
678 prg, exrec->ExceptionCode, exrec->ExceptionFlags,
679 (DWORD)exrec->ExceptionAddress);
681 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
682 && exrec->NumberParameters >= 2)
683 sprintf(&errmsg[strlen(errmsg)],
684 (exrec->ExceptionInformation[0]
685 ? _("Access violation: write operation at address %lx\n")
686 : _("Access violation: read operation at address %lx\n")),
687 exrec->ExceptionInformation[1]);
689 /* turn this on if we want to put stuff in the event log too */
690 #ifdef USE_EVENT_LOG
691 hEventSource = RegisterEventSource(NULL, "GNU Make");
692 lpszStrings[0] = errmsg;
694 if (hEventSource != NULL)
696 ReportEvent(hEventSource, /* handle of event source */
697 EVENTLOG_ERROR_TYPE, /* event type */
698 0, /* event category */
699 0, /* event ID */
700 NULL, /* current user's SID */
701 1, /* strings in lpszStrings */
702 0, /* no bytes of raw data */
703 lpszStrings, /* array of error strings */
704 NULL); /* no raw data */
706 (VOID) DeregisterEventSource(hEventSource);
708 #endif
710 /* Write the error to stderr too */
711 fprintf(stderr, errmsg);
713 #ifdef DEBUG
714 return EXCEPTION_CONTINUE_SEARCH;
715 #else
716 exit(255);
717 return (255); /* not reached */
718 #endif
722 * On WIN32 systems we don't have the luxury of a /bin directory that
723 * is mapped globally to every drive mounted to the system. Since make could
724 * be invoked from any drive, and we don't want to propogate /bin/sh
725 * to every single drive. Allow ourselves a chance to search for
726 * a value for default shell here (if the default path does not exist).
730 find_and_set_default_shell (char *token)
732 int sh_found = 0;
733 char *search_token;
734 char *tokend;
735 PATH_VAR(sh_path);
736 extern char *default_shell;
738 if (!token)
739 search_token = default_shell;
740 else
741 search_token = token;
744 /* If the user explicitly requests the DOS cmd shell, obey that request.
745 However, make sure that's what they really want by requiring the value
746 of SHELL either equal, or have a final path element of, "cmd" or
747 "cmd.exe" case-insensitive. */
748 tokend = search_token + strlen (search_token) - 3;
749 if (((tokend == search_token
750 || (tokend > search_token
751 && (tokend[-1] == '/' || tokend[-1] == '\\')))
752 && !strcmpi (tokend, "cmd"))
753 || ((tokend - 4 == search_token
754 || (tokend - 4 > search_token
755 && (tokend[-5] == '/' || tokend[-5] == '\\')))
756 && !strcmpi (tokend - 4, "cmd.exe"))) {
757 batch_mode_shell = 1;
758 unixy_shell = 0;
759 sprintf (sh_path, "%s", search_token);
760 default_shell = xstrdup (w32ify (sh_path, 0));
761 DB (DB_VERBOSE,
762 (_("find_and_set_shell setting default_shell = %s\n"), default_shell));
763 sh_found = 1;
764 } else if (!no_default_sh_exe &&
765 (token == NULL || !strcmp (search_token, default_shell))) {
766 /* no new information, path already set or known */
767 sh_found = 1;
768 } else if (file_exists_p(search_token)) {
769 /* search token path was found */
770 sprintf(sh_path, "%s", search_token);
771 default_shell = xstrdup(w32ify(sh_path,0));
772 DB (DB_VERBOSE,
773 (_("find_and_set_shell setting default_shell = %s\n"), default_shell));
774 sh_found = 1;
775 } else {
776 char *p;
777 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
779 /* Search Path for shell */
780 if (v && v->value) {
781 char *ep;
783 p = v->value;
784 ep = strchr(p, PATH_SEPARATOR_CHAR);
786 while (ep && *ep) {
787 *ep = '\0';
789 if (dir_file_exists_p(p, search_token)) {
790 sprintf(sh_path, "%s/%s", p, search_token);
791 default_shell = xstrdup(w32ify(sh_path,0));
792 sh_found = 1;
793 *ep = PATH_SEPARATOR_CHAR;
795 /* terminate loop */
796 p += strlen(p);
797 } else {
798 *ep = PATH_SEPARATOR_CHAR;
799 p = ++ep;
802 ep = strchr(p, PATH_SEPARATOR_CHAR);
805 /* be sure to check last element of Path */
806 if (p && *p && dir_file_exists_p(p, search_token)) {
807 sprintf(sh_path, "%s/%s", p, search_token);
808 default_shell = xstrdup(w32ify(sh_path,0));
809 sh_found = 1;
812 if (sh_found)
813 DB (DB_VERBOSE,
814 (_("find_and_set_shell path search set default_shell = %s\n"),
815 default_shell));
819 /* naive test */
820 if (!unixy_shell && sh_found &&
821 (strstr(default_shell, "sh") || strstr(default_shell, "SH"))) {
822 unixy_shell = 1;
823 batch_mode_shell = 0;
826 #ifdef BATCH_MODE_ONLY_SHELL
827 batch_mode_shell = 1;
828 #endif
830 return (sh_found);
832 #endif /* WINDOWS32 */
834 #ifdef __MSDOS__
836 static void
837 msdos_return_to_initial_directory (void)
839 if (directory_before_chdir)
840 chdir (directory_before_chdir);
842 #endif
844 char *mktemp (char *template);
845 int mkstemp (char *template);
847 FILE *
848 open_tmpfile(char **name, const char *template)
850 #ifdef HAVE_FDOPEN
851 int fd;
852 #endif
854 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
855 # define TEMPLATE_LEN strlen (template)
856 #else
857 # define TEMPLATE_LEN L_tmpnam
858 #endif
859 *name = xmalloc (TEMPLATE_LEN + 1);
860 strcpy (*name, template);
862 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
863 /* It's safest to use mkstemp(), if we can. */
864 fd = mkstemp (*name);
865 if (fd == -1)
866 return 0;
867 return fdopen (fd, "w");
868 #else
869 # ifdef HAVE_MKTEMP
870 (void) mktemp (*name);
871 # else
872 (void) tmpnam (*name);
873 # endif
875 # ifdef HAVE_FDOPEN
876 /* Can't use mkstemp(), but guard against a race condition. */
877 fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
878 if (fd == -1)
879 return 0;
880 return fdopen (fd, "w");
881 # else
882 /* Not secure, but what can we do? */
883 return fopen (*name, "w");
884 # endif
885 #endif
889 #ifdef _AMIGA
891 main (int argc, char **argv)
892 #else
894 main (int argc, char **argv, char **envp)
895 #endif
897 static char *stdin_nm = 0;
898 int makefile_status = MAKE_SUCCESS;
899 struct dep *read_makefiles;
900 PATH_VAR (current_directory);
901 unsigned int restarts = 0;
902 #ifdef WINDOWS32
903 char *unix_path = NULL;
904 char *windows32_path = NULL;
906 SetUnhandledExceptionFilter(handle_runtime_exceptions);
908 /* start off assuming we have no shell */
909 unixy_shell = 0;
910 no_default_sh_exe = 1;
911 #endif
913 #ifdef SET_STACK_SIZE
914 /* Get rid of any avoidable limit on stack size. */
916 struct rlimit rlim;
918 /* Set the stack limit huge so that alloca does not fail. */
919 if (getrlimit (RLIMIT_STACK, &rlim) == 0)
921 rlim.rlim_cur = rlim.rlim_max;
922 setrlimit (RLIMIT_STACK, &rlim);
925 #endif
927 #ifdef HAVE_ATEXIT
928 atexit (close_stdout);
929 #endif
931 /* Needed for OS/2 */
932 initialize_main(&argc, &argv);
934 default_goal_file = 0;
935 reading_file = 0;
937 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
938 /* Request the most powerful version of `system', to
939 make up for the dumb default shell. */
940 __system_flags = (__system_redirect
941 | __system_use_shell
942 | __system_allow_multiple_cmds
943 | __system_allow_long_cmds
944 | __system_handle_null_commands
945 | __system_emulate_chdir);
947 #endif
949 /* Set up gettext/internationalization support. */
950 setlocale (LC_ALL, "");
951 bindtextdomain (PACKAGE, LOCALEDIR);
952 textdomain (PACKAGE);
954 #ifdef POSIX
955 sigemptyset (&fatal_signal_set);
956 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
957 #else
958 #ifdef HAVE_SIGSETMASK
959 fatal_signal_mask = 0;
960 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
961 #else
962 #define ADD_SIG(sig)
963 #endif
964 #endif
966 #define FATAL_SIG(sig) \
967 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
968 bsd_signal (sig, SIG_IGN); \
969 else \
970 ADD_SIG (sig);
972 #ifdef SIGHUP
973 FATAL_SIG (SIGHUP);
974 #endif
975 #ifdef SIGQUIT
976 FATAL_SIG (SIGQUIT);
977 #endif
978 FATAL_SIG (SIGINT);
979 FATAL_SIG (SIGTERM);
981 #ifdef __MSDOS__
982 /* Windows 9X delivers FP exceptions in child programs to their
983 parent! We don't want Make to die when a child divides by zero,
984 so we work around that lossage by catching SIGFPE. */
985 FATAL_SIG (SIGFPE);
986 #endif
988 #ifdef SIGDANGER
989 FATAL_SIG (SIGDANGER);
990 #endif
991 #ifdef SIGXCPU
992 FATAL_SIG (SIGXCPU);
993 #endif
994 #ifdef SIGXFSZ
995 FATAL_SIG (SIGXFSZ);
996 #endif
998 #undef FATAL_SIG
1000 /* Do not ignore the child-death signal. This must be done before
1001 any children could possibly be created; otherwise, the wait
1002 functions won't work on systems with the SVR4 ECHILD brain
1003 damage, if our invoker is ignoring this signal. */
1005 #ifdef HAVE_WAIT_NOHANG
1006 # if defined SIGCHLD
1007 (void) bsd_signal (SIGCHLD, SIG_DFL);
1008 # endif
1009 # if defined SIGCLD && SIGCLD != SIGCHLD
1010 (void) bsd_signal (SIGCLD, SIG_DFL);
1011 # endif
1012 #endif
1014 /* Make sure stdout is line-buffered. */
1016 #ifdef HAVE_SETVBUF
1017 # ifdef SETVBUF_REVERSED
1018 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
1019 # else /* setvbuf not reversed. */
1020 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
1021 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
1022 # endif /* setvbuf reversed. */
1023 #elif HAVE_SETLINEBUF
1024 setlinebuf (stdout);
1025 #endif /* setlinebuf missing. */
1027 /* Figure out where this program lives. */
1029 if (argv[0] == 0)
1030 argv[0] = "";
1031 if (argv[0][0] == '\0')
1032 program = "make";
1033 else
1035 #ifdef VMS
1036 program = strrchr (argv[0], ']');
1037 #else
1038 program = strrchr (argv[0], '/');
1039 #endif
1040 #if defined(__MSDOS__) || defined(__EMX__)
1041 if (program == 0)
1042 program = strrchr (argv[0], '\\');
1043 else
1045 /* Some weird environments might pass us argv[0] with
1046 both kinds of slashes; we must find the rightmost. */
1047 char *p = strrchr (argv[0], '\\');
1048 if (p && p > program)
1049 program = p;
1051 if (program == 0 && argv[0][1] == ':')
1052 program = argv[0] + 1;
1053 #endif
1054 #ifdef WINDOWS32
1055 if (program == 0)
1057 /* Extract program from full path */
1058 int argv0_len;
1059 program = strrchr (argv[0], '\\');
1060 if (program)
1062 argv0_len = strlen(program);
1063 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1064 /* Remove .exe extension */
1065 program[argv0_len - 4] = '\0';
1068 #endif
1069 if (program == 0)
1070 program = argv[0];
1071 else
1072 ++program;
1075 /* Set up to access user data (files). */
1076 user_access ();
1078 initialize_global_hash_tables ();
1080 /* Figure out where we are. */
1082 #ifdef WINDOWS32
1083 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1084 #else
1085 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1086 #endif
1088 #ifdef HAVE_GETCWD
1089 perror_with_name ("getcwd", "");
1090 #else
1091 error (NILF, "getwd: %s", current_directory);
1092 #endif
1093 current_directory[0] = '\0';
1094 directory_before_chdir = 0;
1096 else
1097 directory_before_chdir = xstrdup (current_directory);
1098 #ifdef __MSDOS__
1099 /* Make sure we will return to the initial directory, come what may. */
1100 atexit (msdos_return_to_initial_directory);
1101 #endif
1103 /* Initialize the special variables. */
1104 define_variable (".VARIABLES", 10, "", o_default, 0)->special = 1;
1105 /* define_variable (".TARGETS", 8, "", o_default, 0)->special = 1; */
1107 /* Set up .FEATURES */
1108 define_variable (".FEATURES", 9,
1109 "target-specific order-only second-expansion else-if",
1110 o_default, 0);
1111 #ifndef NO_ARCHIVES
1112 do_variable_definition (NILF, ".FEATURES", "archives",
1113 o_default, f_append, 0);
1114 #endif
1115 #ifdef MAKE_JOBSERVER
1116 do_variable_definition (NILF, ".FEATURES", "jobserver",
1117 o_default, f_append, 0);
1118 #endif
1119 #ifdef MAKE_SYMLINKS
1120 do_variable_definition (NILF, ".FEATURES", "check-symlink",
1121 o_default, f_append, 0);
1122 #endif
1124 /* Read in variables from the environment. It is important that this be
1125 done before $(MAKE) is figured out so its definitions will not be
1126 from the environment. */
1128 #ifndef _AMIGA
1130 unsigned int i;
1132 for (i = 0; envp[i] != 0; ++i)
1134 int do_not_define = 0;
1135 char *ep = envp[i];
1137 while (*ep != '\0' && *ep != '=')
1138 ++ep;
1139 #ifdef WINDOWS32
1140 if (!unix_path && strneq(envp[i], "PATH=", 5))
1141 unix_path = ep+1;
1142 else if (!strnicmp(envp[i], "Path=", 5)) {
1143 do_not_define = 1; /* it gets defined after loop exits */
1144 if (!windows32_path)
1145 windows32_path = ep+1;
1147 #endif
1148 /* The result of pointer arithmetic is cast to unsigned int for
1149 machines where ptrdiff_t is a different size that doesn't widen
1150 the same. */
1151 if (!do_not_define)
1153 struct variable *v;
1155 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1156 ep + 1, o_env, 1);
1157 /* Force exportation of every variable culled from the
1158 environment. We used to rely on target_environment's
1159 v_default code to do this. But that does not work for the
1160 case where an environment variable is redefined in a makefile
1161 with `override'; it should then still be exported, because it
1162 was originally in the environment. */
1163 v->export = v_export;
1165 /* Another wrinkle is that POSIX says the value of SHELL set in
1166 the makefile won't change the value of SHELL given to
1167 subprocesses. */
1168 if (streq (v->name, "SHELL"))
1170 #ifndef __MSDOS__
1171 v->export = v_noexport;
1172 #endif
1173 shell_var.name = "SHELL";
1174 shell_var.value = xstrdup (ep + 1);
1177 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1178 if (streq (v->name, "MAKE_RESTARTS"))
1180 v->export = v_noexport;
1181 restarts = (unsigned int) atoi (ep + 1);
1186 #ifdef WINDOWS32
1187 /* If we didn't find a correctly spelled PATH we define PATH as
1188 * either the first mispelled value or an empty string
1190 if (!unix_path)
1191 define_variable("PATH", 4,
1192 windows32_path ? windows32_path : "",
1193 o_env, 1)->export = v_export;
1194 #endif
1195 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1197 BPTR env, file, old;
1198 char buffer[1024];
1199 int len;
1200 __aligned struct FileInfoBlock fib;
1202 env = Lock ("ENV:", ACCESS_READ);
1203 if (env)
1205 old = CurrentDir (DupLock(env));
1206 Examine (env, &fib);
1208 while (ExNext (env, &fib))
1210 if (fib.fib_DirEntryType < 0) /* File */
1212 /* Define an empty variable. It will be filled in
1213 variable_lookup(). Makes startup quite a bit
1214 faster. */
1215 define_variable (fib.fib_FileName,
1216 strlen (fib.fib_FileName),
1217 "", o_env, 1)->export = v_export;
1220 UnLock (env);
1221 UnLock(CurrentDir(old));
1224 #endif
1226 /* Decode the switches. */
1228 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1229 #if 0
1230 /* People write things like:
1231 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1232 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1233 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1234 #endif
1235 decode_switches (argc, argv, 0);
1236 #ifdef WINDOWS32
1237 if (suspend_flag) {
1238 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1239 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1240 Sleep(30 * 1000);
1241 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1243 #endif
1245 decode_debug_flags ();
1247 /* Set always_make_flag if -B was given and we've not restarted already. */
1248 always_make_flag = always_make_set && (restarts == 0);
1250 /* Print version information. */
1251 if (print_version_flag || print_data_base_flag || db_level)
1253 print_version ();
1255 /* `make --version' is supposed to just print the version and exit. */
1256 if (print_version_flag)
1257 die (0);
1260 #ifndef VMS
1261 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1262 (If it is a relative pathname with a slash, prepend our directory name
1263 so the result will run the same program regardless of the current dir.
1264 If it is a name with no slash, we can only hope that PATH did not
1265 find it in the current directory.) */
1266 #ifdef WINDOWS32
1268 * Convert from backslashes to forward slashes for
1269 * programs like sh which don't like them. Shouldn't
1270 * matter if the path is one way or the other for
1271 * CreateProcess().
1273 if (strpbrk(argv[0], "/:\\") ||
1274 strstr(argv[0], "..") ||
1275 strneq(argv[0], "//", 2))
1276 argv[0] = xstrdup(w32ify(argv[0],1));
1277 #else /* WINDOWS32 */
1278 #if defined (__MSDOS__) || defined (__EMX__)
1279 if (strchr (argv[0], '\\'))
1281 char *p;
1283 argv[0] = xstrdup (argv[0]);
1284 for (p = argv[0]; *p; p++)
1285 if (*p == '\\')
1286 *p = '/';
1288 /* If argv[0] is not in absolute form, prepend the current
1289 directory. This can happen when Make is invoked by another DJGPP
1290 program that uses a non-absolute name. */
1291 if (current_directory[0] != '\0'
1292 && argv[0] != 0
1293 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1294 #ifdef __EMX__
1295 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1296 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1297 # endif
1299 argv[0] = concat (current_directory, "/", argv[0]);
1300 #else /* !__MSDOS__ */
1301 if (current_directory[0] != '\0'
1302 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0)
1303 argv[0] = concat (current_directory, "/", argv[0]);
1304 #endif /* !__MSDOS__ */
1305 #endif /* WINDOWS32 */
1306 #endif
1308 /* The extra indirection through $(MAKE_COMMAND) is done
1309 for hysterical raisins. */
1310 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1311 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1313 if (command_variables != 0)
1315 struct command_variable *cv;
1316 struct variable *v;
1317 unsigned int len = 0;
1318 char *value, *p;
1320 /* Figure out how much space will be taken up by the command-line
1321 variable definitions. */
1322 for (cv = command_variables; cv != 0; cv = cv->next)
1324 v = cv->variable;
1325 len += 2 * strlen (v->name);
1326 if (! v->recursive)
1327 ++len;
1328 ++len;
1329 len += 2 * strlen (v->value);
1330 ++len;
1333 /* Now allocate a buffer big enough and fill it. */
1334 p = value = alloca (len);
1335 for (cv = command_variables; cv != 0; cv = cv->next)
1337 v = cv->variable;
1338 p = quote_for_env (p, v->name);
1339 if (! v->recursive)
1340 *p++ = ':';
1341 *p++ = '=';
1342 p = quote_for_env (p, v->value);
1343 *p++ = ' ';
1345 p[-1] = '\0'; /* Kill the final space and terminate. */
1347 /* Define an unchangeable variable with a name that no POSIX.2
1348 makefile could validly use for its own variable. */
1349 (void) define_variable ("-*-command-variables-*-", 23,
1350 value, o_automatic, 0);
1352 /* Define the variable; this will not override any user definition.
1353 Normally a reference to this variable is written into the value of
1354 MAKEFLAGS, allowing the user to override this value to affect the
1355 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1356 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1357 a reference to this hidden variable is written instead. */
1358 (void) define_variable ("MAKEOVERRIDES", 13,
1359 "${-*-command-variables-*-}", o_env, 1);
1362 /* If there were -C flags, move ourselves about. */
1363 if (directories != 0)
1365 unsigned int i;
1366 for (i = 0; directories->list[i] != 0; ++i)
1368 char *dir = directories->list[i];
1369 char *expanded = 0;
1370 if (dir[0] == '~')
1372 expanded = tilde_expand (dir);
1373 if (expanded != 0)
1374 dir = expanded;
1376 #ifdef WINDOWS32
1377 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1378 But allow -C/ just in case someone wants that. */
1380 char *p = dir + strlen (dir) - 1;
1381 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1382 --p;
1383 p[1] = '\0';
1385 #endif
1386 if (chdir (dir) < 0)
1387 pfatal_with_name (dir);
1388 if (expanded)
1389 free (expanded);
1393 #ifdef WINDOWS32
1395 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1396 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1398 * The functions in dir.c can incorrectly cache information for "."
1399 * before we have changed directory and this can cause file
1400 * lookups to fail because the current directory (.) was pointing
1401 * at the wrong place when it was first evaluated.
1403 no_default_sh_exe = !find_and_set_default_shell(NULL);
1405 #endif /* WINDOWS32 */
1406 /* Figure out the level of recursion. */
1408 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1409 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1410 makelevel = (unsigned int) atoi (v->value);
1411 else
1412 makelevel = 0;
1415 /* Except under -s, always do -w in sub-makes and under -C. */
1416 if (!silent_flag && (directories != 0 || makelevel > 0))
1417 print_directory_flag = 1;
1419 /* Let the user disable that with --no-print-directory. */
1420 if (inhibit_print_directory_flag)
1421 print_directory_flag = 0;
1423 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1424 if (no_builtin_variables_flag)
1425 no_builtin_rules_flag = 1;
1427 /* Construct the list of include directories to search. */
1429 construct_include_path (include_directories == 0
1430 ? 0 : include_directories->list);
1432 /* Figure out where we are now, after chdir'ing. */
1433 if (directories == 0)
1434 /* We didn't move, so we're still in the same place. */
1435 starting_directory = current_directory;
1436 else
1438 #ifdef WINDOWS32
1439 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1440 #else
1441 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1442 #endif
1444 #ifdef HAVE_GETCWD
1445 perror_with_name ("getcwd", "");
1446 #else
1447 error (NILF, "getwd: %s", current_directory);
1448 #endif
1449 starting_directory = 0;
1451 else
1452 starting_directory = current_directory;
1455 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1457 /* Read any stdin makefiles into temporary files. */
1459 if (makefiles != 0)
1461 unsigned int i;
1462 for (i = 0; i < makefiles->idx; ++i)
1463 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1465 /* This makefile is standard input. Since we may re-exec
1466 and thus re-read the makefiles, we read standard input
1467 into a temporary file and read from that. */
1468 FILE *outfile;
1469 char *template, *tmpdir;
1471 if (stdin_nm)
1472 fatal (NILF, _("Makefile from standard input specified twice."));
1474 #ifdef VMS
1475 # define DEFAULT_TMPDIR "sys$scratch:"
1476 #else
1477 # ifdef P_tmpdir
1478 # define DEFAULT_TMPDIR P_tmpdir
1479 # else
1480 # define DEFAULT_TMPDIR "/tmp"
1481 # endif
1482 #endif
1483 #define DEFAULT_TMPFILE "GmXXXXXX"
1485 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1486 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1487 /* These are also used commonly on these platforms. */
1488 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1489 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1490 #endif
1492 tmpdir = DEFAULT_TMPDIR;
1494 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
1495 strcpy (template, tmpdir);
1497 #ifdef HAVE_DOS_PATHS
1498 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1499 strcat (template, "/");
1500 #else
1501 # ifndef VMS
1502 if (template[strlen (template) - 1] != '/')
1503 strcat (template, "/");
1504 # endif /* !VMS */
1505 #endif /* !HAVE_DOS_PATHS */
1507 strcat (template, DEFAULT_TMPFILE);
1508 outfile = open_tmpfile (&stdin_nm, template);
1509 if (outfile == 0)
1510 pfatal_with_name (_("fopen (temporary file)"));
1511 while (!feof (stdin) && ! ferror (stdin))
1513 char buf[2048];
1514 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1515 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1516 pfatal_with_name (_("fwrite (temporary file)"));
1518 fclose (outfile);
1520 /* Replace the name that read_all_makefiles will
1521 see with the name of the temporary file. */
1522 makefiles->list[i] = xstrdup (stdin_nm);
1524 /* Make sure the temporary file will not be remade. */
1526 struct file *f = enter_file (stdin_nm);
1527 f->updated = 1;
1528 f->update_status = 0;
1529 f->command_state = cs_finished;
1530 /* Can't be intermediate, or it'll be removed too early for
1531 make re-exec. */
1532 f->intermediate = 0;
1533 f->dontcare = 0;
1538 #ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
1539 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1540 /* Set up to handle children dying. This must be done before
1541 reading in the makefiles so that `shell' function calls will work.
1543 If we don't have a hanging wait we have to fall back to old, broken
1544 functionality here and rely on the signal handler and counting
1545 children.
1547 If we're using the jobs pipe we need a signal handler so that
1548 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1549 jobserver pipe in job.c if we're waiting for a token.
1551 If none of these are true, we don't need a signal handler at all. */
1553 RETSIGTYPE child_handler (int sig);
1554 # if defined SIGCHLD
1555 bsd_signal (SIGCHLD, child_handler);
1556 # endif
1557 # if defined SIGCLD && SIGCLD != SIGCHLD
1558 bsd_signal (SIGCLD, child_handler);
1559 # endif
1561 #endif
1562 #endif
1564 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1565 #ifdef SIGUSR1
1566 bsd_signal (SIGUSR1, debug_signal_handler);
1567 #endif
1569 /* Define the initial list of suffixes for old-style rules. */
1571 set_default_suffixes ();
1573 /* Define the file rules for the built-in suffix rules. These will later
1574 be converted into pattern rules. We used to do this in
1575 install_default_implicit_rules, but since that happens after reading
1576 makefiles, it results in the built-in pattern rules taking precedence
1577 over makefile-specified suffix rules, which is wrong. */
1579 install_default_suffix_rules ();
1581 /* Define some internal and special variables. */
1583 define_automatic_variables ();
1585 /* Set up the MAKEFLAGS and MFLAGS variables
1586 so makefiles can look at them. */
1588 define_makeflags (0, 0);
1590 /* Define the default variables. */
1591 define_default_variables ();
1593 default_file = enter_file (".DEFAULT");
1596 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
1597 default_goal_name = &v->value;
1600 /* Read all the makefiles. */
1602 read_makefiles
1603 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1605 #ifdef WINDOWS32
1606 /* look one last time after reading all Makefiles */
1607 if (no_default_sh_exe)
1608 no_default_sh_exe = !find_and_set_default_shell(NULL);
1609 #endif /* WINDOWS32 */
1611 #if defined (__MSDOS__) || defined (__EMX__)
1612 /* We need to know what kind of shell we will be using. */
1614 extern int _is_unixy_shell (const char *_path);
1615 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1616 extern int unixy_shell;
1617 extern char *default_shell;
1619 if (shv && *shv->value)
1621 char *shell_path = recursively_expand(shv);
1623 if (shell_path && _is_unixy_shell (shell_path))
1624 unixy_shell = 1;
1625 else
1626 unixy_shell = 0;
1627 if (shell_path)
1628 default_shell = shell_path;
1631 #endif /* __MSDOS__ || __EMX__ */
1633 /* Decode switches again, in case the variables were set by the makefile. */
1634 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1635 #if 0
1636 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1637 #endif
1639 #if defined (__MSDOS__) || defined (__EMX__)
1640 if (job_slots != 1
1641 # ifdef __EMX__
1642 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1643 # endif
1646 error (NILF,
1647 _("Parallel jobs (-j) are not supported on this platform."));
1648 error (NILF, _("Resetting to single job (-j1) mode."));
1649 job_slots = 1;
1651 #endif
1653 #ifdef MAKE_JOBSERVER
1654 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
1656 if (jobserver_fds)
1658 char *cp;
1659 unsigned int ui;
1661 for (ui=1; ui < jobserver_fds->idx; ++ui)
1662 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1663 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1665 /* Now parse the fds string and make sure it has the proper format. */
1667 cp = jobserver_fds->list[0];
1669 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
1670 fatal (NILF,
1671 _("internal error: invalid --jobserver-fds string `%s'"), cp);
1673 /* The combination of a pipe + !job_slots means we're using the
1674 jobserver. If !job_slots and we don't have a pipe, we can start
1675 infinite jobs. If we see both a pipe and job_slots >0 that means the
1676 user set -j explicitly. This is broken; in this case obey the user
1677 (ignore the jobserver pipe for this make) but print a message. */
1679 if (job_slots > 0)
1680 error (NILF,
1681 _("warning: -jN forced in submake: disabling jobserver mode."));
1683 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1684 handler. If this fails with EBADF, the parent has closed the pipe
1685 on us because it didn't think we were a submake. If so, print a
1686 warning then default to -j1. */
1688 else if ((job_rfd = dup (job_fds[0])) < 0)
1690 if (errno != EBADF)
1691 pfatal_with_name (_("dup jobserver"));
1693 error (NILF,
1694 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
1695 job_slots = 1;
1698 if (job_slots > 0)
1700 close (job_fds[0]);
1701 close (job_fds[1]);
1702 job_fds[0] = job_fds[1] = -1;
1703 free (jobserver_fds->list);
1704 free (jobserver_fds);
1705 jobserver_fds = 0;
1709 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
1710 Set up the pipe and install the fds option for our children. */
1712 if (job_slots > 1)
1714 char c = '+';
1716 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
1717 pfatal_with_name (_("creating jobs pipe"));
1719 /* Every make assumes that it always has one job it can run. For the
1720 submakes it's the token they were given by their parent. For the
1721 top make, we just subtract one from the number the user wants. We
1722 want job_slots to be 0 to indicate we're using the jobserver. */
1724 master_job_slots = job_slots;
1726 while (--job_slots)
1728 int r;
1730 EINTRLOOP (r, write (job_fds[1], &c, 1));
1731 if (r != 1)
1732 pfatal_with_name (_("init jobserver pipe"));
1735 /* Fill in the jobserver_fds struct for our children. */
1737 jobserver_fds = (struct stringlist *)
1738 xmalloc (sizeof (struct stringlist));
1739 jobserver_fds->list = xmalloc (sizeof (char *));
1740 jobserver_fds->list[0] = xmalloc ((sizeof ("1024")*2)+1);
1742 sprintf (jobserver_fds->list[0], "%d,%d", job_fds[0], job_fds[1]);
1743 jobserver_fds->idx = 1;
1744 jobserver_fds->max = 1;
1746 #endif
1748 #ifndef MAKE_SYMLINKS
1749 if (check_symlink_flag)
1751 error (NILF, _("Symbolic links not supported: disabling -L."));
1752 check_symlink_flag = 0;
1754 #endif
1756 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1758 define_makeflags (1, 0);
1760 /* Make each `struct dep' point at the `struct file' for the file
1761 depended on. Also do magic for special targets. */
1763 snap_deps ();
1765 /* Convert old-style suffix rules to pattern rules. It is important to
1766 do this before installing the built-in pattern rules below, so that
1767 makefile-specified suffix rules take precedence over built-in pattern
1768 rules. */
1770 convert_to_pattern ();
1772 /* Install the default implicit pattern rules.
1773 This used to be done before reading the makefiles.
1774 But in that case, built-in pattern rules were in the chain
1775 before user-defined ones, so they matched first. */
1777 install_default_implicit_rules ();
1779 /* Compute implicit rule limits. */
1781 count_implicit_rule_limits ();
1783 /* Construct the listings of directories in VPATH lists. */
1785 build_vpath_lists ();
1787 /* Mark files given with -o flags as very old and as having been updated
1788 already, and files given with -W flags as brand new (time-stamp as far
1789 as possible into the future). If restarts is set we'll do -W later. */
1791 if (old_files != 0)
1793 char **p;
1794 for (p = old_files->list; *p != 0; ++p)
1796 struct file *f = enter_command_line_file (*p);
1797 f->last_mtime = f->mtime_before_update = OLD_MTIME;
1798 f->updated = 1;
1799 f->update_status = 0;
1800 f->command_state = cs_finished;
1804 if (!restarts && new_files != 0)
1806 char **p;
1807 for (p = new_files->list; *p != 0; ++p)
1809 struct file *f = enter_command_line_file (*p);
1810 f->last_mtime = f->mtime_before_update = NEW_MTIME;
1814 /* Initialize the remote job module. */
1815 remote_setup ();
1817 if (read_makefiles != 0)
1819 /* Update any makefiles if necessary. */
1821 FILE_TIMESTAMP *makefile_mtimes = 0;
1822 unsigned int mm_idx = 0;
1823 char **nargv = argv;
1824 int nargc = argc;
1825 int orig_db_level = db_level;
1826 int status;
1828 if (! ISDB (DB_MAKEFILES))
1829 db_level = DB_NONE;
1831 DB (DB_BASIC, (_("Updating makefiles....\n")));
1833 /* Remove any makefiles we don't want to try to update.
1834 Also record the current modtimes so we can compare them later. */
1836 register struct dep *d, *last;
1837 last = 0;
1838 d = read_makefiles;
1839 while (d != 0)
1841 struct file *f = d->file;
1842 if (f->double_colon)
1843 for (f = f->double_colon; f != NULL; f = f->prev)
1845 if (f->deps == 0 && f->cmds != 0)
1847 /* This makefile is a :: target with commands, but
1848 no dependencies. So, it will always be remade.
1849 This might well cause an infinite loop, so don't
1850 try to remake it. (This will only happen if
1851 your makefiles are written exceptionally
1852 stupidly; but if you work for Athena, that's how
1853 you write your makefiles.) */
1855 DB (DB_VERBOSE,
1856 (_("Makefile `%s' might loop; not remaking it.\n"),
1857 f->name));
1859 if (last == 0)
1860 read_makefiles = d->next;
1861 else
1862 last->next = d->next;
1864 /* Free the storage. */
1865 free_dep (d);
1867 d = last == 0 ? read_makefiles : last->next;
1869 break;
1872 if (f == NULL || !f->double_colon)
1874 makefile_mtimes = xrealloc (makefile_mtimes,
1875 (mm_idx+1)
1876 * sizeof (FILE_TIMESTAMP));
1877 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
1878 last = d;
1879 d = d->next;
1884 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
1885 define_makeflags (1, 1);
1887 rebuilding_makefiles = 1;
1888 status = update_goal_chain (read_makefiles);
1889 rebuilding_makefiles = 0;
1891 switch (status)
1893 case 1:
1894 /* The only way this can happen is if the user specified -q and asked
1895 * for one of the makefiles to be remade as a target on the command
1896 * line. Since we're not actually updating anything with -q we can
1897 * treat this as "did nothing".
1900 case -1:
1901 /* Did nothing. */
1902 break;
1904 case 2:
1905 /* Failed to update. Figure out if we care. */
1907 /* Nonzero if any makefile was successfully remade. */
1908 int any_remade = 0;
1909 /* Nonzero if any makefile we care about failed
1910 in updating or could not be found at all. */
1911 int any_failed = 0;
1912 unsigned int i;
1913 struct dep *d;
1915 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
1917 /* Reset the considered flag; we may need to look at the file
1918 again to print an error. */
1919 d->file->considered = 0;
1921 if (d->file->updated)
1923 /* This makefile was updated. */
1924 if (d->file->update_status == 0)
1926 /* It was successfully updated. */
1927 any_remade |= (file_mtime_no_search (d->file)
1928 != makefile_mtimes[i]);
1930 else if (! (d->changed & RM_DONTCARE))
1932 FILE_TIMESTAMP mtime;
1933 /* The update failed and this makefile was not
1934 from the MAKEFILES variable, so we care. */
1935 error (NILF, _("Failed to remake makefile `%s'."),
1936 d->file->name);
1937 mtime = file_mtime_no_search (d->file);
1938 any_remade |= (mtime != NONEXISTENT_MTIME
1939 && mtime != makefile_mtimes[i]);
1940 makefile_status = MAKE_FAILURE;
1943 else
1944 /* This makefile was not found at all. */
1945 if (! (d->changed & RM_DONTCARE))
1947 /* This is a makefile we care about. See how much. */
1948 if (d->changed & RM_INCLUDED)
1949 /* An included makefile. We don't need
1950 to die, but we do want to complain. */
1951 error (NILF,
1952 _("Included makefile `%s' was not found."),
1953 dep_name (d));
1954 else
1956 /* A normal makefile. We must die later. */
1957 error (NILF, _("Makefile `%s' was not found"),
1958 dep_name (d));
1959 any_failed = 1;
1963 /* Reset this to empty so we get the right error message below. */
1964 read_makefiles = 0;
1966 if (any_remade)
1967 goto re_exec;
1968 if (any_failed)
1969 die (2);
1970 break;
1973 case 0:
1974 re_exec:
1975 /* Updated successfully. Re-exec ourselves. */
1977 remove_intermediates (0);
1979 if (print_data_base_flag)
1980 print_data_base ();
1982 log_working_directory (0);
1984 clean_jobserver (0);
1986 if (makefiles != 0)
1988 /* These names might have changed. */
1989 int i, j = 0;
1990 for (i = 1; i < argc; ++i)
1991 if (strneq (argv[i], "-f", 2)) /* XXX */
1993 char *p = &argv[i][2];
1994 if (*p == '\0')
1995 argv[++i] = makefiles->list[j];
1996 else
1997 argv[i] = concat ("-f", makefiles->list[j], "");
1998 ++j;
2002 /* Add -o option for the stdin temporary file, if necessary. */
2003 if (stdin_nm)
2005 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2006 memcpy (nargv, argv, argc * sizeof (char *));
2007 nargv[nargc++] = concat ("-o", stdin_nm, "");
2008 nargv[nargc] = 0;
2011 if (directories != 0 && directories->idx > 0)
2013 char bad;
2014 if (directory_before_chdir != 0)
2016 if (chdir (directory_before_chdir) < 0)
2018 perror_with_name ("chdir", "");
2019 bad = 1;
2021 else
2022 bad = 0;
2024 else
2025 bad = 1;
2026 if (bad)
2027 fatal (NILF, _("Couldn't change back to original directory."));
2030 ++restarts;
2032 if (ISDB (DB_BASIC))
2034 char **p;
2035 printf (_("Re-executing[%u]:"), restarts);
2036 for (p = nargv; *p != 0; ++p)
2037 printf (" %s", *p);
2038 putchar ('\n');
2041 #ifndef _AMIGA
2043 char **p;
2044 for (p = environ; *p != 0; ++p)
2046 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2047 && (*p)[MAKELEVEL_LENGTH] == '=')
2049 *p = alloca (40);
2050 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2052 if (strneq (*p, "MAKE_RESTARTS=", 14))
2054 *p = alloca (40);
2055 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2056 restarts = 0;
2060 #else /* AMIGA */
2062 char buffer[256];
2064 sprintf (buffer, "%u", makelevel);
2065 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2067 sprintf (buffer, "%u", restarts);
2068 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2069 restarts = 0;
2071 #endif
2073 /* If we didn't set the restarts variable yet, add it. */
2074 if (restarts)
2076 char *b = alloca (40);
2077 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2078 putenv (b);
2081 fflush (stdout);
2082 fflush (stderr);
2084 /* Close the dup'd jobserver pipe if we opened one. */
2085 if (job_rfd >= 0)
2086 close (job_rfd);
2088 #ifdef _AMIGA
2089 exec_command (nargv);
2090 exit (0);
2091 #elif defined (__EMX__)
2093 /* It is not possible to use execve() here because this
2094 would cause the parent process to be terminated with
2095 exit code 0 before the child process has been terminated.
2096 Therefore it may be the best solution simply to spawn the
2097 child process including all file handles and to wait for its
2098 termination. */
2099 int pid;
2100 int status;
2101 pid = child_execute_job (0, 1, nargv, environ);
2103 /* is this loop really necessary? */
2104 do {
2105 pid = wait (&status);
2106 } while (pid <= 0);
2107 /* use the exit code of the child process */
2108 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2110 #else
2111 exec_command (nargv, environ);
2112 #endif
2113 /* NOTREACHED */
2115 default:
2116 #define BOGUS_UPDATE_STATUS 0
2117 assert (BOGUS_UPDATE_STATUS);
2118 break;
2121 db_level = orig_db_level;
2123 /* Free the makefile mtimes (if we allocated any). */
2124 if (makefile_mtimes)
2125 free (makefile_mtimes);
2128 /* Set up `MAKEFLAGS' again for the normal targets. */
2129 define_makeflags (1, 0);
2131 /* Set always_make_flag if -B was given. */
2132 always_make_flag = always_make_set;
2134 /* If restarts is set we haven't set up -W files yet, so do that now. */
2135 if (restarts && new_files != 0)
2137 char **p;
2138 for (p = new_files->list; *p != 0; ++p)
2140 struct file *f = enter_command_line_file (*p);
2141 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2145 /* If there is a temp file from reading a makefile from stdin, get rid of
2146 it now. */
2147 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2148 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2151 int status;
2153 /* If there were no command-line goals, use the default. */
2154 if (goals == 0)
2156 if (**default_goal_name != '\0')
2158 if (default_goal_file == 0 ||
2159 strcmp (*default_goal_name, default_goal_file->name) != 0)
2161 default_goal_file = lookup_file (*default_goal_name);
2163 /* In case user set .DEFAULT_GOAL to a non-existent target
2164 name let's just enter this name into the table and let
2165 the standard logic sort it out. */
2166 if (default_goal_file == 0)
2168 struct nameseq *ns;
2169 char *p = *default_goal_name;
2171 ns = multi_glob (
2172 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2173 sizeof (struct nameseq));
2175 /* .DEFAULT_GOAL should contain one target. */
2176 if (ns->next != 0)
2177 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2179 default_goal_file = enter_file (ns->name);
2181 ns->name = 0; /* It was reused by enter_file(). */
2182 free_ns_chain (ns);
2186 goals = alloc_dep ();
2187 goals->file = default_goal_file;
2190 else
2191 lastgoal->next = 0;
2194 if (!goals)
2196 if (read_makefiles == 0)
2197 fatal (NILF, _("No targets specified and no makefile found"));
2199 fatal (NILF, _("No targets"));
2202 /* Update the goals. */
2204 DB (DB_BASIC, (_("Updating goal targets....\n")));
2206 switch (update_goal_chain (goals))
2208 case -1:
2209 /* Nothing happened. */
2210 case 0:
2211 /* Updated successfully. */
2212 status = makefile_status;
2213 break;
2214 case 1:
2215 /* We are under -q and would run some commands. */
2216 status = MAKE_TROUBLE;
2217 break;
2218 case 2:
2219 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2220 but in VMS, there is only success and failure. */
2221 status = MAKE_FAILURE;
2222 break;
2223 default:
2224 abort ();
2227 /* If we detected some clock skew, generate one last warning */
2228 if (clock_skew_detected)
2229 error (NILF,
2230 _("warning: Clock skew detected. Your build may be incomplete."));
2232 /* Exit. */
2233 die (status);
2236 /* NOTREACHED */
2237 return 0;
2240 /* Parsing of arguments, decoding of switches. */
2242 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2243 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2244 (sizeof (long_option_aliases) /
2245 sizeof (long_option_aliases[0]))];
2247 /* Fill in the string and vector for getopt. */
2248 static void
2249 init_switches (void)
2251 char *p;
2252 unsigned int c;
2253 unsigned int i;
2255 if (options[0] != '\0')
2256 /* Already done. */
2257 return;
2259 p = options;
2261 /* Return switch and non-switch args in order, regardless of
2262 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2263 *p++ = '-';
2265 for (i = 0; switches[i].c != '\0'; ++i)
2267 long_options[i].name = (switches[i].long_name == 0 ? "" :
2268 switches[i].long_name);
2269 long_options[i].flag = 0;
2270 long_options[i].val = switches[i].c;
2271 if (short_option (switches[i].c))
2272 *p++ = switches[i].c;
2273 switch (switches[i].type)
2275 case flag:
2276 case flag_off:
2277 case ignore:
2278 long_options[i].has_arg = no_argument;
2279 break;
2281 case string:
2282 case positive_int:
2283 case floating:
2284 if (short_option (switches[i].c))
2285 *p++ = ':';
2286 if (switches[i].noarg_value != 0)
2288 if (short_option (switches[i].c))
2289 *p++ = ':';
2290 long_options[i].has_arg = optional_argument;
2292 else
2293 long_options[i].has_arg = required_argument;
2294 break;
2297 *p = '\0';
2298 for (c = 0; c < (sizeof (long_option_aliases) /
2299 sizeof (long_option_aliases[0]));
2300 ++c)
2301 long_options[i++] = long_option_aliases[c];
2302 long_options[i].name = 0;
2305 static void
2306 handle_non_switch_argument (char *arg, int env)
2308 /* Non-option argument. It might be a variable definition. */
2309 struct variable *v;
2310 if (arg[0] == '-' && arg[1] == '\0')
2311 /* Ignore plain `-' for compatibility. */
2312 return;
2313 v = try_variable_definition (0, arg, o_command, 0);
2314 if (v != 0)
2316 /* It is indeed a variable definition. If we don't already have this
2317 one, record a pointer to the variable for later use in
2318 define_makeflags. */
2319 struct command_variable *cv;
2321 for (cv = command_variables; cv != 0; cv = cv->next)
2322 if (cv->variable == v)
2323 break;
2325 if (! cv) {
2326 cv = xmalloc (sizeof (*cv));
2327 cv->variable = v;
2328 cv->next = command_variables;
2329 command_variables = cv;
2332 else if (! env)
2334 /* Not an option or variable definition; it must be a goal
2335 target! Enter it as a file and add it to the dep chain of
2336 goals. */
2337 struct file *f = enter_command_line_file (arg);
2338 f->cmd_target = 1;
2340 if (goals == 0)
2342 goals = alloc_dep ();
2343 lastgoal = goals;
2345 else
2347 lastgoal->next = alloc_dep ();
2348 lastgoal = lastgoal->next;
2351 lastgoal->file = f;
2354 /* Add this target name to the MAKECMDGOALS variable. */
2355 struct variable *gv;
2356 char *value;
2358 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2359 if (gv == 0)
2360 value = f->name;
2361 else
2363 /* Paste the old and new values together */
2364 unsigned int oldlen, newlen;
2366 oldlen = strlen (gv->value);
2367 newlen = strlen (f->name);
2368 value = alloca (oldlen + 1 + newlen + 1);
2369 memcpy (value, gv->value, oldlen);
2370 value[oldlen] = ' ';
2371 memcpy (&value[oldlen + 1], f->name, newlen + 1);
2373 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2378 /* Print a nice usage method. */
2380 static void
2381 print_usage (int bad)
2383 const char *const *cpp;
2384 FILE *usageto;
2386 if (print_version_flag)
2387 print_version ();
2389 usageto = bad ? stderr : stdout;
2391 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2393 for (cpp = usage; *cpp; ++cpp)
2394 fputs (_(*cpp), usageto);
2396 if (!remote_description || *remote_description == '\0')
2397 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2398 else
2399 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2400 make_host, remote_description);
2402 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2405 /* Decode switches from ARGC and ARGV.
2406 They came from the environment if ENV is nonzero. */
2408 static void
2409 decode_switches (int argc, char **argv, int env)
2411 int bad = 0;
2412 register const struct command_switch *cs;
2413 register struct stringlist *sl;
2414 register int c;
2416 /* getopt does most of the parsing for us.
2417 First, get its vectors set up. */
2419 init_switches ();
2421 /* Let getopt produce error messages for the command line,
2422 but not for options from the environment. */
2423 opterr = !env;
2424 /* Reset getopt's state. */
2425 optind = 0;
2427 while (optind < argc)
2429 /* Parse the next argument. */
2430 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2431 if (c == EOF)
2432 /* End of arguments, or "--" marker seen. */
2433 break;
2434 else if (c == 1)
2435 /* An argument not starting with a dash. */
2436 handle_non_switch_argument (optarg, env);
2437 else if (c == '?')
2438 /* Bad option. We will print a usage message and die later.
2439 But continue to parse the other options so the user can
2440 see all he did wrong. */
2441 bad = 1;
2442 else
2443 for (cs = switches; cs->c != '\0'; ++cs)
2444 if (cs->c == c)
2446 /* Whether or not we will actually do anything with
2447 this switch. We test this individually inside the
2448 switch below rather than just once outside it, so that
2449 options which are to be ignored still consume args. */
2450 int doit = !env || cs->env;
2452 switch (cs->type)
2454 default:
2455 abort ();
2457 case ignore:
2458 break;
2460 case flag:
2461 case flag_off:
2462 if (doit)
2463 *(int *) cs->value_ptr = cs->type == flag;
2464 break;
2466 case string:
2467 if (!doit)
2468 break;
2470 if (optarg == 0)
2471 optarg = cs->noarg_value;
2472 else if (*optarg == '\0')
2474 error (NILF, _("the `-%c' option requires a non-empty string argument"),
2475 cs->c);
2476 bad = 1;
2479 sl = *(struct stringlist **) cs->value_ptr;
2480 if (sl == 0)
2482 sl = (struct stringlist *)
2483 xmalloc (sizeof (struct stringlist));
2484 sl->max = 5;
2485 sl->idx = 0;
2486 sl->list = xmalloc (5 * sizeof (char *));
2487 *(struct stringlist **) cs->value_ptr = sl;
2489 else if (sl->idx == sl->max - 1)
2491 sl->max += 5;
2492 sl->list = xrealloc (sl->list,
2493 sl->max * sizeof (char *));
2495 sl->list[sl->idx++] = optarg;
2496 sl->list[sl->idx] = 0;
2497 break;
2499 case positive_int:
2500 /* See if we have an option argument; if we do require that
2501 it's all digits, not something like "10foo". */
2502 if (optarg == 0 && argc > optind)
2504 const char *cp;
2505 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2507 if (cp[0] == '\0')
2508 optarg = argv[optind++];
2511 if (!doit)
2512 break;
2514 if (optarg != 0)
2516 int i = atoi (optarg);
2517 const char *cp;
2519 /* Yes, I realize we're repeating this in some cases. */
2520 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2523 if (i < 1 || cp[0] != '\0')
2525 error (NILF, _("the `-%c' option requires a positive integral argument"),
2526 cs->c);
2527 bad = 1;
2529 else
2530 *(unsigned int *) cs->value_ptr = i;
2532 else
2533 *(unsigned int *) cs->value_ptr
2534 = *(unsigned int *) cs->noarg_value;
2535 break;
2537 #ifndef NO_FLOAT
2538 case floating:
2539 if (optarg == 0 && optind < argc
2540 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2541 optarg = argv[optind++];
2543 if (doit)
2544 *(double *) cs->value_ptr
2545 = (optarg != 0 ? atof (optarg)
2546 : *(double *) cs->noarg_value);
2548 break;
2549 #endif
2552 /* We've found the switch. Stop looking. */
2553 break;
2557 /* There are no more options according to getting getopt, but there may
2558 be some arguments left. Since we have asked for non-option arguments
2559 to be returned in order, this only happens when there is a "--"
2560 argument to prevent later arguments from being options. */
2561 while (optind < argc)
2562 handle_non_switch_argument (argv[optind++], env);
2565 if (!env && (bad || print_usage_flag))
2567 print_usage (bad);
2568 die (bad ? 2 : 0);
2572 /* Decode switches from environment variable ENVAR (which is LEN chars long).
2573 We do this by chopping the value into a vector of words, prepending a
2574 dash to the first word if it lacks one, and passing the vector to
2575 decode_switches. */
2577 static void
2578 decode_env_switches (char *envar, unsigned int len)
2580 char *varref = alloca (2 + len + 2);
2581 char *value, *p;
2582 int argc;
2583 char **argv;
2585 /* Get the variable's value. */
2586 varref[0] = '$';
2587 varref[1] = '(';
2588 memcpy (&varref[2], envar, len);
2589 varref[2 + len] = ')';
2590 varref[2 + len + 1] = '\0';
2591 value = variable_expand (varref);
2593 /* Skip whitespace, and check for an empty value. */
2594 value = next_token (value);
2595 len = strlen (value);
2596 if (len == 0)
2597 return;
2599 /* Allocate a vector that is definitely big enough. */
2600 argv = alloca ((1 + len + 1) * sizeof (char *));
2602 /* Allocate a buffer to copy the value into while we split it into words
2603 and unquote it. We must use permanent storage for this because
2604 decode_switches may store pointers into the passed argument words. */
2605 p = xmalloc (2 * len);
2607 /* getopt will look at the arguments starting at ARGV[1].
2608 Prepend a spacer word. */
2609 argv[0] = 0;
2610 argc = 1;
2611 argv[argc] = p;
2612 while (*value != '\0')
2614 if (*value == '\\' && value[1] != '\0')
2615 ++value; /* Skip the backslash. */
2616 else if (isblank ((unsigned char)*value))
2618 /* End of the word. */
2619 *p++ = '\0';
2620 argv[++argc] = p;
2622 ++value;
2623 while (isblank ((unsigned char)*value));
2624 continue;
2626 *p++ = *value++;
2628 *p = '\0';
2629 argv[++argc] = 0;
2631 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2632 /* The first word doesn't start with a dash and isn't a variable
2633 definition. Add a dash and pass it along to decode_switches. We
2634 need permanent storage for this in case decode_switches saves
2635 pointers into the value. */
2636 argv[1] = concat ("-", argv[1], "");
2638 /* Parse those words. */
2639 decode_switches (argc, argv, 1);
2642 /* Quote the string IN so that it will be interpreted as a single word with
2643 no magic by decode_env_switches; also double dollar signs to avoid
2644 variable expansion in make itself. Write the result into OUT, returning
2645 the address of the next character to be written.
2646 Allocating space for OUT twice the length of IN is always sufficient. */
2648 static char *
2649 quote_for_env (char *out, char *in)
2651 while (*in != '\0')
2653 if (*in == '$')
2654 *out++ = '$';
2655 else if (isblank ((unsigned char)*in) || *in == '\\')
2656 *out++ = '\\';
2657 *out++ = *in++;
2660 return out;
2663 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2664 command switches. Include options with args if ALL is nonzero.
2665 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2667 static void
2668 define_makeflags (int all, int makefile)
2670 static const char ref[] = "$(MAKEOVERRIDES)";
2671 static const char posixref[] = "$(-*-command-variables-*-)";
2672 register const struct command_switch *cs;
2673 char *flagstring;
2674 register char *p;
2675 unsigned int words;
2676 struct variable *v;
2678 /* We will construct a linked list of `struct flag's describing
2679 all the flags which need to go in MAKEFLAGS. Then, once we
2680 know how many there are and their lengths, we can put them all
2681 together in a string. */
2683 struct flag
2685 struct flag *next;
2686 const struct command_switch *cs;
2687 char *arg;
2689 struct flag *flags = 0;
2690 unsigned int flagslen = 0;
2691 #define ADD_FLAG(ARG, LEN) \
2692 do { \
2693 struct flag *new = alloca (sizeof (struct flag)); \
2694 new->cs = cs; \
2695 new->arg = (ARG); \
2696 new->next = flags; \
2697 flags = new; \
2698 if (new->arg == 0) \
2699 ++flagslen; /* Just a single flag letter. */ \
2700 else \
2701 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2702 if (!short_option (cs->c)) \
2703 /* This switch has no single-letter version, so we use the long. */ \
2704 flagslen += 2 + strlen (cs->long_name); \
2705 } while (0)
2707 for (cs = switches; cs->c != '\0'; ++cs)
2708 if (cs->toenv && (!makefile || !cs->no_makefile))
2709 switch (cs->type)
2711 default:
2712 abort ();
2714 case ignore:
2715 break;
2717 case flag:
2718 case flag_off:
2719 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2720 && (cs->default_value == 0
2721 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2722 ADD_FLAG (0, 0);
2723 break;
2725 case positive_int:
2726 if (all)
2728 if ((cs->default_value != 0
2729 && (*(unsigned int *) cs->value_ptr
2730 == *(unsigned int *) cs->default_value)))
2731 break;
2732 else if (cs->noarg_value != 0
2733 && (*(unsigned int *) cs->value_ptr ==
2734 *(unsigned int *) cs->noarg_value))
2735 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2736 else if (cs->c == 'j')
2737 /* Special case for `-j'. */
2738 ADD_FLAG ("1", 1);
2739 else
2741 char *buf = alloca (30);
2742 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
2743 ADD_FLAG (buf, strlen (buf));
2746 break;
2748 #ifndef NO_FLOAT
2749 case floating:
2750 if (all)
2752 if (cs->default_value != 0
2753 && (*(double *) cs->value_ptr
2754 == *(double *) cs->default_value))
2755 break;
2756 else if (cs->noarg_value != 0
2757 && (*(double *) cs->value_ptr
2758 == *(double *) cs->noarg_value))
2759 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2760 else
2762 char *buf = alloca (100);
2763 sprintf (buf, "%g", *(double *) cs->value_ptr);
2764 ADD_FLAG (buf, strlen (buf));
2767 break;
2768 #endif
2770 case string:
2771 if (all)
2773 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
2774 if (sl != 0)
2776 /* Add the elements in reverse order, because
2777 all the flags get reversed below; and the order
2778 matters for some switches (like -I). */
2779 register unsigned int i = sl->idx;
2780 while (i-- > 0)
2781 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
2784 break;
2787 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
2789 #undef ADD_FLAG
2791 /* Construct the value in FLAGSTRING.
2792 We allocate enough space for a preceding dash and trailing null. */
2793 flagstring = alloca (1 + flagslen + 1);
2794 memset (flagstring, '\0', 1 + flagslen + 1);
2795 p = flagstring;
2796 words = 1;
2797 *p++ = '-';
2798 while (flags != 0)
2800 /* Add the flag letter or name to the string. */
2801 if (short_option (flags->cs->c))
2802 *p++ = flags->cs->c;
2803 else
2805 if (*p != '-')
2807 *p++ = ' ';
2808 *p++ = '-';
2810 *p++ = '-';
2811 strcpy (p, flags->cs->long_name);
2812 p += strlen (p);
2814 if (flags->arg != 0)
2816 /* A flag that takes an optional argument which in this case is
2817 omitted is specified by ARG being "". We must distinguish
2818 because a following flag appended without an intervening " -"
2819 is considered the arg for the first. */
2820 if (flags->arg[0] != '\0')
2822 /* Add its argument too. */
2823 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
2824 p = quote_for_env (p, flags->arg);
2826 ++words;
2827 /* Write a following space and dash, for the next flag. */
2828 *p++ = ' ';
2829 *p++ = '-';
2831 else if (!short_option (flags->cs->c))
2833 ++words;
2834 /* Long options must each go in their own word,
2835 so we write the following space and dash. */
2836 *p++ = ' ';
2837 *p++ = '-';
2839 flags = flags->next;
2842 /* Define MFLAGS before appending variable definitions. */
2844 if (p == &flagstring[1])
2845 /* No flags. */
2846 flagstring[0] = '\0';
2847 else if (p[-1] == '-')
2849 /* Kill the final space and dash. */
2850 p -= 2;
2851 *p = '\0';
2853 else
2854 /* Terminate the string. */
2855 *p = '\0';
2857 /* Since MFLAGS is not parsed for flags, there is no reason to
2858 override any makefile redefinition. */
2859 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
2861 if (all && command_variables != 0)
2863 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
2864 command-line variable definitions. */
2866 if (p == &flagstring[1])
2867 /* No flags written, so elide the leading dash already written. */
2868 p = flagstring;
2869 else
2871 /* Separate the variables from the switches with a "--" arg. */
2872 if (p[-1] != '-')
2874 /* We did not already write a trailing " -". */
2875 *p++ = ' ';
2876 *p++ = '-';
2878 /* There is a trailing " -"; fill it out to " -- ". */
2879 *p++ = '-';
2880 *p++ = ' ';
2883 /* Copy in the string. */
2884 if (posix_pedantic)
2886 memcpy (p, posixref, sizeof posixref - 1);
2887 p += sizeof posixref - 1;
2889 else
2891 memcpy (p, ref, sizeof ref - 1);
2892 p += sizeof ref - 1;
2895 else if (p == &flagstring[1])
2897 words = 0;
2898 --p;
2900 else if (p[-1] == '-')
2901 /* Kill the final space and dash. */
2902 p -= 2;
2903 /* Terminate the string. */
2904 *p = '\0';
2906 v = define_variable ("MAKEFLAGS", 9,
2907 /* If there are switches, omit the leading dash
2908 unless it is a single long option with two
2909 leading dashes. */
2910 &flagstring[(flagstring[0] == '-'
2911 && flagstring[1] != '-')
2912 ? 1 : 0],
2913 /* This used to use o_env, but that lost when a
2914 makefile defined MAKEFLAGS. Makefiles set
2915 MAKEFLAGS to add switches, but we still want
2916 to redefine its value with the full set of
2917 switches. Of course, an override or command
2918 definition will still take precedence. */
2919 o_file, 1);
2920 if (! all)
2921 /* The first time we are called, set MAKEFLAGS to always be exported.
2922 We should not do this again on the second call, because that is
2923 after reading makefiles which might have done `unexport MAKEFLAGS'. */
2924 v->export = v_export;
2927 /* Print version information. */
2929 static void
2930 print_version (void)
2932 static int printed_version = 0;
2934 char *precede = print_data_base_flag ? "# " : "";
2936 if (printed_version)
2937 /* Do it only once. */
2938 return;
2940 /* Print this untranslated. The coding standards recommend translating the
2941 (C) to the copyright symbol, but this string is going to change every
2942 year, and none of the rest of it should be translated (including the
2943 word "Copyright", so it hardly seems worth it. */
2945 printf ("%sGNU Make %s\n\
2946 %sCopyright (C) 2006 Free Software Foundation, Inc.\n",
2947 precede, version_string, precede);
2949 printf (_("%sThis is free software; see the source for copying conditions.\n\
2950 %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
2951 %sPARTICULAR PURPOSE.\n"),
2952 precede, precede, precede);
2954 if (!remote_description || *remote_description == '\0')
2955 printf (_("\n%sThis program built for %s\n"), precede, make_host);
2956 else
2957 printf (_("\n%sThis program built for %s (%s)\n"),
2958 precede, make_host, remote_description);
2960 printed_version = 1;
2962 /* Flush stdout so the user doesn't have to wait to see the
2963 version information while things are thought about. */
2964 fflush (stdout);
2967 /* Print a bunch of information about this and that. */
2969 static void
2970 print_data_base ()
2972 time_t when;
2974 when = time ((time_t *) 0);
2975 printf (_("\n# Make data base, printed on %s"), ctime (&when));
2977 print_variable_data_base ();
2978 print_dir_data_base ();
2979 print_rule_data_base ();
2980 print_file_data_base ();
2981 print_vpath_data_base ();
2982 strcache_print_stats ("#");
2984 when = time ((time_t *) 0);
2985 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
2988 static void
2989 clean_jobserver (int status)
2991 char token = '+';
2993 /* Sanity: have we written all our jobserver tokens back? If our
2994 exit status is 2 that means some kind of syntax error; we might not
2995 have written all our tokens so do that now. If tokens are left
2996 after any other error code, that's bad. */
2998 if (job_fds[0] != -1 && jobserver_tokens)
3000 if (status != 2)
3001 error (NILF,
3002 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3003 jobserver_tokens);
3004 else
3005 while (jobserver_tokens--)
3007 int r;
3009 EINTRLOOP (r, write (job_fds[1], &token, 1));
3010 if (r != 1)
3011 perror_with_name ("write", "");
3016 /* Sanity: If we're the master, were all the tokens written back? */
3018 if (master_job_slots)
3020 /* We didn't write one for ourself, so start at 1. */
3021 unsigned int tcnt = 1;
3023 /* Close the write side, so the read() won't hang. */
3024 close (job_fds[1]);
3026 while (read (job_fds[0], &token, 1) == 1)
3027 ++tcnt;
3029 if (tcnt != master_job_slots)
3030 error (NILF,
3031 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3032 tcnt, master_job_slots);
3034 close (job_fds[0]);
3038 /* Exit with STATUS, cleaning up as necessary. */
3040 void
3041 die (int status)
3043 static char dying = 0;
3045 if (!dying)
3047 int err;
3049 dying = 1;
3051 if (print_version_flag)
3052 print_version ();
3054 /* Wait for children to die. */
3055 err = (status != 0);
3056 while (job_slots_used > 0)
3057 reap_children (1, err);
3059 /* Let the remote job module clean up its state. */
3060 remote_cleanup ();
3062 /* Remove the intermediate files. */
3063 remove_intermediates (0);
3065 if (print_data_base_flag)
3066 print_data_base ();
3068 clean_jobserver (status);
3070 /* Try to move back to the original directory. This is essential on
3071 MS-DOS (where there is really only one process), and on Unix it
3072 puts core files in the original directory instead of the -C
3073 directory. Must wait until after remove_intermediates(), or unlinks
3074 of relative pathnames fail. */
3075 if (directory_before_chdir != 0)
3076 chdir (directory_before_chdir);
3078 log_working_directory (0);
3081 exit (status);
3084 /* Write a message indicating that we've just entered or
3085 left (according to ENTERING) the current directory. */
3087 void
3088 log_working_directory (int entering)
3090 static int entered = 0;
3092 /* Print nothing without the flag. Don't print the entering message
3093 again if we already have. Don't print the leaving message if we
3094 haven't printed the entering message. */
3095 if (! print_directory_flag || entering == entered)
3096 return;
3098 entered = entering;
3100 if (print_data_base_flag)
3101 fputs ("# ", stdout);
3103 /* Use entire sentences to give the translators a fighting chance. */
3105 if (makelevel == 0)
3106 if (starting_directory == 0)
3107 if (entering)
3108 printf (_("%s: Entering an unknown directory\n"), program);
3109 else
3110 printf (_("%s: Leaving an unknown directory\n"), program);
3111 else
3112 if (entering)
3113 printf (_("%s: Entering directory `%s'\n"),
3114 program, starting_directory);
3115 else
3116 printf (_("%s: Leaving directory `%s'\n"),
3117 program, starting_directory);
3118 else
3119 if (starting_directory == 0)
3120 if (entering)
3121 printf (_("%s[%u]: Entering an unknown directory\n"),
3122 program, makelevel);
3123 else
3124 printf (_("%s[%u]: Leaving an unknown directory\n"),
3125 program, makelevel);
3126 else
3127 if (entering)
3128 printf (_("%s[%u]: Entering directory `%s'\n"),
3129 program, makelevel, starting_directory);
3130 else
3131 printf (_("%s[%u]: Leaving directory `%s'\n"),
3132 program, makelevel, starting_directory);
3134 /* Flush stdout to be sure this comes before any stderr output. */
3135 fflush (stdout);