*: Updated copyright to 2009 and normalized name & email.
[kbuild-mirror.git] / src / kmk / main.c
blobe901e98119a37b74841b7e46c865c76d2128758d
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, 2007 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 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
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"
28 #ifdef KMK
29 # include "kbuild.h"
30 #endif
32 #include <assert.h>
33 #ifdef _AMIGA
34 # include <dos/dos.h>
35 # include <proto/dos.h>
36 #endif
37 #ifdef WINDOWS32
38 #include <windows.h>
39 #include <io.h>
40 #include "pathstuff.h"
41 #endif
42 #ifdef __EMX__
43 # include <sys/types.h>
44 # include <sys/wait.h>
45 #endif
46 #ifdef HAVE_FCNTL_H
47 # include <fcntl.h>
48 #endif
50 #ifdef KMK /* for get_online_cpu_count */
51 # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
52 # include <sys/sysctl.h>
53 # endif
54 # ifdef __OS2__
55 # define INCL_BASE
56 # include <os2.h>
57 # endif
58 #endif /* KMK*/
60 #if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
61 # define SET_STACK_SIZE
62 #endif
64 #ifdef SET_STACK_SIZE
65 # include <sys/resource.h>
66 #endif
68 #ifdef _AMIGA
69 int __stack = 20000; /* Make sure we have 20K of stack space */
70 #endif
72 void init_dir (void);
73 void remote_setup (void);
74 void remote_cleanup (void);
75 RETSIGTYPE fatal_error_signal (int sig);
77 void print_variable_data_base (void);
78 void print_dir_data_base (void);
79 void print_rule_data_base (void);
80 void print_file_data_base (void);
81 void print_vpath_data_base (void);
83 void verify_file_data_base (void);
85 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
86 void print_variable_stats (void);
87 void print_file_stats (void);
88 #endif
90 #if defined HAVE_WAITPID || defined HAVE_WAIT3
91 # define HAVE_WAIT_NOHANG
92 #endif
94 #if !defined(HAVE_UNISTD_H) && !defined(_MSC_VER) /* bird */
95 int chdir ();
96 #endif
97 #ifndef STDC_HEADERS
98 # ifndef sun /* Sun has an incorrect decl in a header. */
99 void exit (int) __attribute__ ((noreturn));
100 # endif
101 double atof ();
102 #endif
104 static void clean_jobserver (int status);
105 static void print_data_base (void);
106 static void print_version (void);
107 static void decode_switches (int argc, char **argv, int env);
108 static void decode_env_switches (char *envar, unsigned int len);
109 static void define_makeflags (int all, int makefile);
110 static char *quote_for_env (char *out, const char *in);
111 static void initialize_global_hash_tables (void);
114 /* The structure that describes an accepted command switch. */
116 struct command_switch
118 int c; /* The switch character. */
120 enum /* Type of the value. */
122 flag, /* Turn int flag on. */
123 flag_off, /* Turn int flag off. */
124 string, /* One string per switch. */
125 filename, /* A string containing a file name. */
126 positive_int, /* A positive integer. */
127 floating, /* A floating-point number (double). */
128 ignore /* Ignored. */
129 } type;
131 void *value_ptr; /* Pointer to the value-holding variable. */
133 unsigned int env:1; /* Can come from MAKEFLAGS. */
134 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
135 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
137 const void *noarg_value; /* Pointer to value used if no arg given. */
138 const void *default_value; /* Pointer to default value. */
140 char *long_name; /* Long option name. */
143 /* True if C is a switch value that corresponds to a short option. */
145 #define short_option(c) ((c) <= CHAR_MAX)
147 /* The structure used to hold the list of strings given
148 in command switches of a type that takes string arguments. */
150 struct stringlist
152 const char **list; /* Nil-terminated list of strings. */
153 unsigned int idx; /* Index into above. */
154 unsigned int max; /* Number of pointers allocated. */
158 /* The recognized command switches. */
160 /* Nonzero means do not print commands to be executed (-s). */
162 int silent_flag;
164 /* Nonzero means just touch the files
165 that would appear to need remaking (-t) */
167 int touch_flag;
169 /* Nonzero means just print what commands would need to be executed,
170 don't actually execute them (-n). */
172 int just_print_flag;
174 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
175 /* Nonzero means to print commands argument for argument skipping blanks. */
177 int pretty_command_printing;
178 #endif
180 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
181 /* Nonzero means to print internal statistics before exiting. */
183 int print_stats_flag;
184 #endif
186 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
187 /* Minimum number of seconds to report, -1 if disabled. */
189 int print_time_min = -1;
190 static int default_print_time_min = -1;
191 static int no_val_print_time_min = 0;
192 static big_int make_start_ts = -1;
193 int print_time_width = 5;
194 #endif
196 /* Print debugging info (--debug). */
198 static struct stringlist *db_flags;
199 static int debug_flag = 0;
201 int db_level = 0;
203 /* Output level (--verbosity). */
205 static struct stringlist *verbosity_flags;
207 #ifdef WINDOWS32
208 /* Suspend make in main for a short time to allow debugger to attach */
210 int suspend_flag = 0;
211 #endif
213 /* Environment variables override makefile definitions. */
215 int env_overrides = 0;
217 /* Nonzero means ignore status codes returned by commands
218 executed to remake files. Just treat them all as successful (-i). */
220 int ignore_errors_flag = 0;
222 /* Nonzero means don't remake anything, just print the data base
223 that results from reading the makefile (-p). */
225 int print_data_base_flag = 0;
227 /* Nonzero means don't remake anything; just return a nonzero status
228 if the specified targets are not up to date (-q). */
230 int question_flag = 0;
232 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
234 int no_builtin_rules_flag = 0;
235 int no_builtin_variables_flag = 0;
237 /* Nonzero means keep going even if remaking some file fails (-k). */
239 int keep_going_flag;
240 int default_keep_going_flag = 0;
242 /* Nonzero means check symlink mtimes. */
244 int check_symlink_flag = 0;
246 /* Nonzero means print directory before starting and when done (-w). */
248 int print_directory_flag = 0;
250 /* Nonzero means ignore print_directory_flag and never print the directory.
251 This is necessary because print_directory_flag is set implicitly. */
253 int inhibit_print_directory_flag = 0;
255 /* Nonzero means print version information. */
257 int print_version_flag = 0;
259 /* List of makefiles given with -f switches. */
261 static struct stringlist *makefiles = 0;
263 /* Number of job slots (commands that can be run at once). */
265 unsigned int job_slots = 1;
266 unsigned int default_job_slots = 1;
267 static unsigned int master_job_slots = 0;
269 /* Value of job_slots that means no limit. */
271 static unsigned int inf_jobs = 0;
273 /* File descriptors for the jobs pipe. */
275 static struct stringlist *jobserver_fds = 0;
277 int job_fds[2] = { -1, -1 };
278 int job_rfd = -1;
280 /* Maximum load average at which multiple jobs will be run.
281 Negative values mean unlimited, while zero means limit to
282 zero load (which could be useful to start infinite jobs remotely
283 but one at a time locally). */
284 #ifndef NO_FLOAT
285 double max_load_average = -1.0;
286 double default_load_average = -1.0;
287 #else
288 int max_load_average = -1;
289 int default_load_average = -1;
290 #endif
292 /* List of directories given with -C switches. */
294 static struct stringlist *directories = 0;
296 /* List of include directories given with -I switches. */
298 static struct stringlist *include_directories = 0;
300 /* List of files given with -o switches. */
302 static struct stringlist *old_files = 0;
304 /* List of files given with -W switches. */
306 static struct stringlist *new_files = 0;
308 /* If nonzero, we should just print usage and exit. */
310 static int print_usage_flag = 0;
312 /* If nonzero, we should print a warning message
313 for each reference to an undefined variable. */
315 int warn_undefined_variables_flag;
317 /* If nonzero, always build all targets, regardless of whether
318 they appear out of date or not. */
320 static int always_make_set = 0;
321 int always_make_flag = 0;
323 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
325 int rebuilding_makefiles = 0;
327 /* Remember the original value of the SHELL variable, from the environment. */
329 struct variable shell_var;
331 /* This character introduces a command: it's the first char on the line. */
333 char cmd_prefix = '\t';
335 #ifdef KMK
336 /* Process priority.
337 0 = no change;
338 1 = idle / max nice;
339 2 = below normal / nice 10;
340 3 = normal / nice 0;
341 4 = high / nice -10;
342 5 = realtime / nice -19; */
344 int process_priority = 0;
346 /* Process affinity mask; 0 means any CPU. */
348 int process_affinity = 0;
349 #endif /* KMK */
351 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
352 /* When set, we'll gather expensive statistics like for the heap. */
354 int make_expensive_statistics = 0;
355 #endif
358 /* The usage output. We write it this way to make life easier for the
359 translators, especially those trying to translate to right-to-left
360 languages like Hebrew. */
362 static const char *const usage[] =
364 N_("Options:\n"),
365 N_("\
366 -b, -m Ignored for compatibility.\n"),
367 N_("\
368 -B, --always-make Unconditionally make all targets.\n"),
369 N_("\
370 -C DIRECTORY, --directory=DIRECTORY\n\
371 Change to DIRECTORY before doing anything.\n"),
372 N_("\
373 -d Print lots of debugging information.\n"),
374 N_("\
375 --debug[=FLAGS] Print various types of debugging information.\n"),
376 N_("\
377 -e, --environment-overrides\n\
378 Environment variables override makefiles.\n"),
379 N_("\
380 -f FILE, --file=FILE, --makefile=FILE\n\
381 Read FILE as a makefile.\n"),
382 N_("\
383 -h, --help Print this message and exit.\n"),
384 N_("\
385 -i, --ignore-errors Ignore errors from recipes.\n"),
386 N_("\
387 -I DIRECTORY, --include-dir=DIRECTORY\n\
388 Search DIRECTORY for included makefiles.\n"),
389 #ifdef KMK
390 N_("\
391 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n\
392 The default is the number of active CPUs.\n"),
393 #else
394 N_("\
395 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
396 #endif
397 N_("\
398 -k, --keep-going Keep going when some targets can't be made.\n"),
399 N_("\
400 -l [N], --load-average[=N], --max-load[=N]\n\
401 Don't start multiple jobs unless load is below N.\n"),
402 N_("\
403 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
404 N_("\
405 -n, --just-print, --dry-run, --recon\n\
406 Don't actually run any recipe; just print them.\n"),
407 N_("\
408 -o FILE, --old-file=FILE, --assume-old=FILE\n\
409 Consider FILE to be very old and don't remake it.\n"),
410 N_("\
411 -p, --print-data-base Print make's internal database.\n"),
412 N_("\
413 -q, --question Run no recipe; exit status says if up to date.\n"),
414 N_("\
415 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
416 N_("\
417 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
418 N_("\
419 -s, --silent, --quiet Don't echo recipes.\n"),
420 N_("\
421 -S, --no-keep-going, --stop\n\
422 Turns off -k.\n"),
423 N_("\
424 -t, --touch Touch targets instead of remaking them.\n"),
425 N_("\
426 -v, --version Print the version number of make and exit.\n"),
427 N_("\
428 -w, --print-directory Print the current directory.\n"),
429 N_("\
430 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
431 N_("\
432 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
433 Consider FILE to be infinitely new.\n"),
434 N_("\
435 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
436 #ifdef KMK
437 N_("\
438 --affinity=mask Sets the CPU affinity on some hosts.\n"),
439 N_("\
440 --priority=1-5 Sets the process priority / nice level:\n\
441 1 = idle / max nice;\n\
442 2 = below normal / nice 10;\n\
443 3 = normal / nice 0;\n\
444 4 = high / nice -10;\n\
445 5 = realtime / nice -19;\n"),
446 #endif /* KMK */
447 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
448 N_("\
449 --pretty-command-printing Makes the command echo easier to read.\n"),
450 #endif
451 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
452 N_("\
453 --print-stats Print make statistics.\n"),
454 #endif
455 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
456 N_("\
457 --print-time[=MIN-SEC] Print file build times starting at arg.\n"),
458 #endif
459 #ifdef CONFIG_WITH_MAKE_STATS
460 N_("\
461 --statistics Gather extra statistics for $(make-stats ).\n"),
462 #endif
463 NULL
466 /* The table of command switches. */
468 static const struct command_switch switches[] =
470 { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
471 { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
472 { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
473 { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
474 { CHAR_MAX+1, string, &db_flags, 1, 1, 0, "basic", 0, "debug" },
475 #ifdef WINDOWS32
476 { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
477 #endif
478 { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
479 { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
480 { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
481 { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
482 { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
483 "include-dir" },
484 { 'j', positive_int, &job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
485 "jobs" },
486 { CHAR_MAX+2, string, &jobserver_fds, 1, 1, 0, 0, 0, "jobserver-fds" },
487 { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
488 "keep-going" },
489 #ifndef NO_FLOAT
490 { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
491 &default_load_average, "load-average" },
492 #else
493 { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
494 &default_load_average, "load-average" },
495 #endif
496 { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
497 { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
498 { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
499 { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
500 { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
501 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
502 { CHAR_MAX+10, flag, (char *) &pretty_command_printing, 1, 1, 1, 0, 0,
503 "pretty-command-printing" },
504 #endif
505 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
506 { CHAR_MAX+11, flag, (char *) &print_stats_flag, 1, 1, 1, 0, 0,
507 "print-stats" },
508 #endif
509 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
510 { CHAR_MAX+12, positive_int, (char *) &print_time_min, 1, 1, 0,
511 (char *) &no_val_print_time_min, (char *) &default_print_time_min,
512 "print-time" },
513 #endif
514 #ifdef KMK
515 { CHAR_MAX+14, positive_int, (char *) &process_priority, 1, 1, 0,
516 (char *) &process_priority, (char *) &process_priority, "priority" },
517 { CHAR_MAX+15, positive_int, (char *) &process_affinity, 1, 1, 0,
518 (char *) &process_affinity, (char *) &process_affinity, "affinity" },
519 #endif
520 { 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
521 { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
522 { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
523 "no-builtin-variables" },
524 { 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },
525 { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
526 "no-keep-going" },
527 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
528 { CHAR_MAX+16, flag, (char *) &make_expensive_statistics, 1, 1, 1, 0, 0,
529 "statistics" },
530 #endif
531 { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
532 { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
533 { CHAR_MAX+3, string, &verbosity_flags, 1, 1, 0, 0, 0,
534 "verbosity" },
535 { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
536 { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
537 "no-print-directory" },
538 { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
539 { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
540 "warn-undefined-variables" },
541 { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
544 /* Secondary long names for options. */
546 static struct option long_option_aliases[] =
548 { "quiet", no_argument, 0, 's' },
549 { "stop", no_argument, 0, 'S' },
550 { "new-file", required_argument, 0, 'W' },
551 { "assume-new", required_argument, 0, 'W' },
552 { "assume-old", required_argument, 0, 'o' },
553 { "max-load", optional_argument, 0, 'l' },
554 { "dry-run", no_argument, 0, 'n' },
555 { "recon", no_argument, 0, 'n' },
556 { "makefile", required_argument, 0, 'f' },
559 /* List of goal targets. */
561 #ifndef KMK
562 static
563 #endif
564 struct dep *goals, *lastgoal;
566 /* List of variables which were defined on the command line
567 (or, equivalently, in MAKEFLAGS). */
569 struct command_variable
571 struct command_variable *next;
572 struct variable *variable;
574 static struct command_variable *command_variables;
576 /* The name we were invoked with. */
578 char *program;
580 /* Our current directory before processing any -C options. */
582 char *directory_before_chdir;
584 /* Our current directory after processing all -C options. */
586 char *starting_directory;
588 /* Value of the MAKELEVEL variable at startup (or 0). */
590 unsigned int makelevel;
592 /* First file defined in the makefile whose name does not
593 start with `.'. This is the default to remake if the
594 command line does not specify. */
596 struct file *default_goal_file;
598 /* Pointer to the value of the .DEFAULT_GOAL special
599 variable. */
600 char ** default_goal_name;
602 /* Pointer to structure for the file .DEFAULT
603 whose commands are used for any file that has none of its own.
604 This is zero if the makefiles do not define .DEFAULT. */
606 struct file *default_file;
608 /* Nonzero if we have seen the magic `.POSIX' target.
609 This turns on pedantic compliance with POSIX.2. */
611 int posix_pedantic;
613 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
614 This turns on secondary expansion of prerequisites. */
616 int second_expansion;
618 #ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
619 /* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
620 This turns on secondary expansion of targets. */
622 int second_target_expansion;
623 #endif
625 #ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
626 /* Nonzero if we have seen the `.NOTPARALLEL' target.
627 This turns off parallel builds for this invocation of make. */
629 #else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
631 /* Negative if we have seen the `.NOTPARALLEL' target with an
632 empty dependency list.
634 Zero if no `.NOTPARALLEL' or no file in the dependency list
635 is being executed.
637 Positive when a file in the `.NOTPARALLEL' dependency list
638 is in progress, the value is the number of notparallel files
639 in progress (running or queued for running).
641 In short, any nonzero value means no more parallel builing. */
642 #endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
644 int not_parallel;
646 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
647 print one warning about it during the run, and (b) we can print a final
648 warning at the end of the run. */
650 int clock_skew_detected;
652 /* Mask of signals that are being caught with fatal_error_signal. */
654 #ifdef POSIX
655 sigset_t fatal_signal_set;
656 #else
657 # ifdef HAVE_SIGSETMASK
658 int fatal_signal_mask;
659 # endif
660 #endif
662 #if !defined HAVE_BSD_SIGNAL && !defined bsd_signal
663 # if !defined HAVE_SIGACTION
664 # define bsd_signal signal
665 # else
666 typedef RETSIGTYPE (*bsd_signal_ret_t) ();
668 static bsd_signal_ret_t
669 bsd_signal (int sig, bsd_signal_ret_t func)
671 struct sigaction act, oact;
672 act.sa_handler = func;
673 act.sa_flags = SA_RESTART;
674 sigemptyset (&act.sa_mask);
675 sigaddset (&act.sa_mask, sig);
676 if (sigaction (sig, &act, &oact) != 0)
677 return SIG_ERR;
678 return oact.sa_handler;
680 # endif
681 #endif
683 #ifdef CONFIG_WITH_ALLOC_CACHES
684 struct alloccache dep_cache;
685 struct alloccache file_cache;
686 struct alloccache commands_cache;
687 struct alloccache nameseq_cache;
688 struct alloccache variable_cache;
689 struct alloccache variable_set_cache;
690 struct alloccache variable_set_list_cache;
692 static void
693 initialize_global_alloc_caches (void)
695 alloccache_init (&dep_cache, sizeof (struct dep), "dep", NULL, NULL);
696 alloccache_init (&file_cache, sizeof (struct file), "file", NULL, NULL);
697 alloccache_init (&commands_cache, sizeof (struct commands), "commands", NULL, NULL);
698 alloccache_init (&nameseq_cache, sizeof (struct nameseq), "nameseq", NULL, NULL);
699 alloccache_init (&variable_cache, sizeof (struct variable), "variable", NULL, NULL);
700 alloccache_init (&variable_set_cache, sizeof (struct variable_set), "variable_set", NULL, NULL);
701 alloccache_init (&variable_set_list_cache, sizeof (struct variable_set_list), "variable_set_list", NULL, NULL);
703 #endif /* CONFIG_WITH_ALLOC_CACHES */
705 static void
706 initialize_global_hash_tables (void)
708 init_hash_global_variable_set ();
709 strcache_init ();
710 init_hash_files ();
711 hash_init_directories ();
712 hash_init_function_table ();
715 static const char *
716 expand_command_line_file (char *name)
718 const char *cp;
719 char *expanded = 0;
721 if (name[0] == '\0')
722 fatal (NILF, _("empty string invalid as file name"));
724 if (name[0] == '~')
726 expanded = tilde_expand (name);
727 if (expanded != 0)
728 name = expanded;
731 /* This is also done in parse_file_seq, so this is redundant
732 for names read from makefiles. It is here for names passed
733 on the command line. */
734 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
736 name += 2;
737 while (*name == '/')
738 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
739 ++name;
742 if (*name == '\0')
744 /* It was all slashes! Move back to the dot and truncate
745 it after the first slash, so it becomes just "./". */
747 --name;
748 while (name[0] != '.');
749 name[2] = '\0';
752 cp = strcache_add (name);
754 if (expanded)
755 free (expanded);
757 return cp;
760 /* Toggle -d on receipt of SIGUSR1. */
762 #ifdef SIGUSR1
763 static RETSIGTYPE
764 debug_signal_handler (int sig UNUSED)
766 db_level = db_level ? DB_NONE : DB_BASIC;
768 #endif
770 static void
771 decode_debug_flags (void)
773 const char **pp;
775 if (debug_flag)
776 db_level = DB_ALL;
778 if (!db_flags)
779 return;
781 for (pp=db_flags->list; *pp; ++pp)
783 const char *p = *pp;
785 while (1)
787 switch (tolower (p[0]))
789 case 'a':
790 db_level |= DB_ALL;
791 break;
792 case 'b':
793 db_level |= DB_BASIC;
794 break;
795 case 'i':
796 db_level |= DB_BASIC | DB_IMPLICIT;
797 break;
798 case 'j':
799 db_level |= DB_JOBS;
800 break;
801 case 'm':
802 db_level |= DB_BASIC | DB_MAKEFILES;
803 break;
804 case 'v':
805 db_level |= DB_BASIC | DB_VERBOSE;
806 break;
807 #ifdef DB_KMK
808 case 'k':
809 db_level |= DB_KMK;
810 break;
811 #endif /* DB_KMK */
812 default:
813 fatal (NILF, _("unknown debug level specification `%s'"), p);
816 while (*(++p) != '\0')
817 if (*p == ',' || *p == ' ')
818 break;
820 if (*p == '\0')
821 break;
823 ++p;
829 #ifdef KMK
830 static void
831 set_make_priority_and_affinity (void)
833 # ifdef WINDOWS32
834 DWORD dwPriority;
835 if (process_affinity)
836 if (!SetProcessAffinityMask (GetCurrentProcess (), process_affinity))
837 fprintf (stderr, "warning: SetPriorityClass (,%#x) failed with last error %d\n",
838 process_affinity, GetLastError());
840 switch (process_priority)
842 case 0: return;
843 case 1: dwPriority = IDLE_PRIORITY_CLASS; break;
844 case 2: dwPriority = BELOW_NORMAL_PRIORITY_CLASS; break;
845 case 3: dwPriority = NORMAL_PRIORITY_CLASS; break;
846 case 4: dwPriority = HIGH_PRIORITY_CLASS; break;
847 case 5: dwPriority = REALTIME_PRIORITY_CLASS; break;
848 default: fatal(NILF, _("invalid priority %d\n"), process_priority);
850 if (!SetPriorityClass (GetCurrentProcess (), dwPriority))
851 fprintf (stderr, "warning: SetPriorityClass (,%#x) failed with last error %d\n",
852 dwPriority, GetLastError ());
854 # else /*#elif HAVE_NICE */
855 int nice_level = 0;
856 switch (process_priority)
858 case 0: return;
859 case 1: nice_level = 19; break;
860 case 2: nice_level = 10; break;
861 case 3: nice_level = 0; break;
862 case 4: nice_level = -10; break;
863 case 5: nice_level = -19; break;
864 default: fatal(NILF, _("invalid priority %d\n"), process_priority);
866 errno = 0;
867 if (nice (nice_level) == -1 && errno != 0)
868 fprintf (stderr, "warning: nice (%d) failed: %s\n",
869 nice_level, strerror (errno));
870 # endif
872 #endif /* KMK */
875 #ifdef WINDOWS32
877 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
878 * exception and print it to stderr instead.
880 * If ! DB_VERBOSE, just print a simple message and exit.
881 * If DB_VERBOSE, print a more verbose message.
882 * If compiled for DEBUG, let exception pass through to GUI so that
883 * debuggers can attach.
885 LONG WINAPI
886 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
888 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
889 LPSTR cmdline = GetCommandLine();
890 LPSTR prg = strtok(cmdline, " ");
891 CHAR errmsg[1024];
892 #ifdef USE_EVENT_LOG
893 HANDLE hEventSource;
894 LPTSTR lpszStrings[1];
895 #endif
897 if (! ISDB (DB_VERBOSE))
899 sprintf(errmsg,
900 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%lx)\n"),
901 prg, exrec->ExceptionCode, (DWORD)exrec->ExceptionAddress);
902 fprintf(stderr, errmsg);
903 exit(255);
906 sprintf(errmsg,
907 _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = %lx\n"),
908 prg, exrec->ExceptionCode, exrec->ExceptionFlags,
909 (DWORD)exrec->ExceptionAddress);
911 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
912 && exrec->NumberParameters >= 2)
913 sprintf(&errmsg[strlen(errmsg)],
914 (exrec->ExceptionInformation[0]
915 ? _("Access violation: write operation at address %lx\n")
916 : _("Access violation: read operation at address %lx\n")),
917 exrec->ExceptionInformation[1]);
919 /* turn this on if we want to put stuff in the event log too */
920 #ifdef USE_EVENT_LOG
921 hEventSource = RegisterEventSource(NULL, "GNU Make");
922 lpszStrings[0] = errmsg;
924 if (hEventSource != NULL)
926 ReportEvent(hEventSource, /* handle of event source */
927 EVENTLOG_ERROR_TYPE, /* event type */
928 0, /* event category */
929 0, /* event ID */
930 NULL, /* current user's SID */
931 1, /* strings in lpszStrings */
932 0, /* no bytes of raw data */
933 lpszStrings, /* array of error strings */
934 NULL); /* no raw data */
936 (VOID) DeregisterEventSource(hEventSource);
938 #endif
940 /* Write the error to stderr too */
941 fprintf(stderr, errmsg);
943 #ifdef DEBUG
944 return EXCEPTION_CONTINUE_SEARCH;
945 #else
946 exit(255);
947 return (255); /* not reached */
948 #endif
952 * On WIN32 systems we don't have the luxury of a /bin directory that
953 * is mapped globally to every drive mounted to the system. Since make could
954 * be invoked from any drive, and we don't want to propogate /bin/sh
955 * to every single drive. Allow ourselves a chance to search for
956 * a value for default shell here (if the default path does not exist).
960 find_and_set_default_shell (const char *token)
962 int sh_found = 0;
963 char *atoken = 0;
964 char *search_token;
965 char *tokend;
966 PATH_VAR(sh_path);
967 extern char *default_shell;
969 if (!token)
970 search_token = default_shell;
971 else
972 atoken = search_token = xstrdup (token);
974 /* If the user explicitly requests the DOS cmd shell, obey that request.
975 However, make sure that's what they really want by requiring the value
976 of SHELL either equal, or have a final path element of, "cmd" or
977 "cmd.exe" case-insensitive. */
978 tokend = search_token + strlen (search_token) - 3;
979 if (((tokend == search_token
980 || (tokend > search_token
981 && (tokend[-1] == '/' || tokend[-1] == '\\')))
982 && !strcasecmp (tokend, "cmd"))
983 || ((tokend - 4 == search_token
984 || (tokend - 4 > search_token
985 && (tokend[-5] == '/' || tokend[-5] == '\\')))
986 && !strcasecmp (tokend - 4, "cmd.exe"))) {
987 batch_mode_shell = 1;
988 unixy_shell = 0;
989 sprintf (sh_path, "%s", search_token);
990 default_shell = xstrdup (w32ify (sh_path, 0));
991 DB (DB_VERBOSE,
992 (_("find_and_set_shell setting default_shell = %s\n"), default_shell));
993 sh_found = 1;
994 } else if (!no_default_sh_exe &&
995 (token == NULL || !strcmp (search_token, default_shell))) {
996 /* no new information, path already set or known */
997 sh_found = 1;
998 } else if (file_exists_p (search_token)) {
999 /* search token path was found */
1000 sprintf (sh_path, "%s", search_token);
1001 default_shell = xstrdup (w32ify (sh_path, 0));
1002 DB (DB_VERBOSE,
1003 (_("find_and_set_shell setting default_shell = %s\n"), default_shell));
1004 sh_found = 1;
1005 } else {
1006 char *p;
1007 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
1009 /* Search Path for shell */
1010 if (v && v->value) {
1011 char *ep;
1013 p = v->value;
1014 ep = strchr (p, PATH_SEPARATOR_CHAR);
1016 while (ep && *ep) {
1017 *ep = '\0';
1019 if (dir_file_exists_p (p, search_token)) {
1020 sprintf (sh_path, "%s/%s", p, search_token);
1021 default_shell = xstrdup (w32ify (sh_path, 0));
1022 sh_found = 1;
1023 *ep = PATH_SEPARATOR_CHAR;
1025 /* terminate loop */
1026 p += strlen (p);
1027 } else {
1028 *ep = PATH_SEPARATOR_CHAR;
1029 p = ++ep;
1032 ep = strchr (p, PATH_SEPARATOR_CHAR);
1035 /* be sure to check last element of Path */
1036 if (p && *p && dir_file_exists_p (p, search_token)) {
1037 sprintf (sh_path, "%s/%s", p, search_token);
1038 default_shell = xstrdup (w32ify (sh_path, 0));
1039 sh_found = 1;
1042 if (sh_found)
1043 DB (DB_VERBOSE,
1044 (_("find_and_set_shell path search set default_shell = %s\n"),
1045 default_shell));
1049 #if 0/* def KMK - has been fixed in sub_proc.c */
1050 /* WORKAROUND:
1051 With GNU Make 3.81, this kludge was necessary to get double quotes
1052 working correctly again (worked fine with the 3.81beta1 code).
1053 beta1 was forcing batch_mode_shell I think, so let's enforce that
1054 for the kBuild shell. */
1055 if (sh_found && strstr(default_shell, "kmk_ash")) {
1056 unixy_shell = 1;
1057 batch_mode_shell = 1;
1058 } else
1059 #endif
1060 /* naive test */
1061 if (!unixy_shell && sh_found &&
1062 (strstr (default_shell, "sh") || strstr (default_shell, "SH"))) {
1063 unixy_shell = 1;
1064 batch_mode_shell = 0;
1067 #ifdef BATCH_MODE_ONLY_SHELL
1068 batch_mode_shell = 1;
1069 #endif
1071 if (atoken)
1072 free (atoken);
1074 return (sh_found);
1077 /* bird: */
1078 #ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1079 #include <process.h>
1080 static UINT g_tidMainThread = 0;
1081 static int volatile g_sigPending = 0; /* lazy bird */
1082 # ifndef _M_IX86
1083 static LONG volatile g_lTriggered = 0;
1084 static CONTEXT g_Ctx;
1085 # endif
1087 # ifdef _M_IX86
1088 static __declspec(naked) void dispatch_stub(void)
1090 __asm {
1091 pushfd
1092 pushad
1095 fflush(stdout);
1096 /*fprintf(stderr, "dbg: raising %s on the main thread (%d)\n", g_sigPending == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());*/
1097 raise(g_sigPending);
1098 __asm {
1099 popad
1100 popfd
1104 # else /* !_M_IX86 */
1105 static void dispatch_stub(void)
1107 fflush(stdout);
1108 /*fprintf(stderr, "dbg: raising %s on the main thread (%d)\n", g_sigPending == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());*/
1109 raise(g_sigPending);
1111 SetThreadContext(GetCurrentThread(), &g_Ctx);
1112 fprintf(stderr, "fatal error: SetThreadContext failed with last error %d\n", GetLastError());
1113 for (;;)
1114 exit(131);
1116 # endif /* !_M_IX86 */
1118 static BOOL WINAPI ctrl_event(DWORD CtrlType)
1120 int sig = (CtrlType == CTRL_C_EVENT) ? SIGINT : SIGBREAK;
1121 HANDLE hThread;
1122 CONTEXT Ctx;
1124 #ifndef _M_IX86
1125 /* only once. */
1126 if (InterlockedExchange(&g_lTriggered, 1))
1128 Sleep(1);
1129 return TRUE;
1131 #endif
1133 /* open the main thread and suspend it. */
1134 hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, g_tidMainThread);
1135 SuspendThread(hThread);
1137 /* Get the thread context and if we've get a valid Esp, dispatch
1138 it on the main thread otherwise raise the signal in the
1139 ctrl-event thread (this). */
1140 memset(&Ctx, 0, sizeof(Ctx));
1141 Ctx.ContextFlags = CONTEXT_FULL;
1142 if (GetThreadContext(hThread, &Ctx)
1143 #ifdef _M_IX86
1144 && Ctx.Esp >= 0x1000
1145 #else
1146 && Ctx.Rsp >= 0x1000
1147 #endif
1150 #ifdef _M_IX86
1151 ((uintptr_t *)Ctx.Esp)[-1] = Ctx.Eip;
1152 Ctx.Esp -= sizeof(uintptr_t);
1153 Ctx.Eip = (uintptr_t)&dispatch_stub;
1154 #else
1155 g_Ctx = Ctx;
1156 Ctx.Rsp -= 0x20;
1157 Ctx.Rsp &= ~(uintptr_t)0xf;
1158 Ctx.Rip = (uintptr_t)&dispatch_stub;
1159 #endif
1161 SetThreadContext(hThread, &Ctx);
1162 g_sigPending = sig;
1163 ResumeThread(hThread);
1164 CloseHandle(hThread);
1166 else
1168 fprintf(stderr, "dbg: raising %s on the ctrl-event thread (%d)\n", sig == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());
1169 raise(sig);
1170 ResumeThread(hThread);
1171 CloseHandle(hThread);
1172 exit(130);
1175 Sleep(1);
1176 return TRUE;
1178 #endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1180 #endif /* WINDOWS32 */
1182 #ifdef KMK
1183 /* Determins the number of CPUs that are currently online.
1184 This is used to setup the default number of job slots. */
1185 static int
1186 get_online_cpu_count(void)
1188 # ifdef WINDOWS32
1189 /* Windows: Count the active CPUs. */
1190 int cpus, i;
1191 SYSTEM_INFO si;
1192 GetSystemInfo(&si);
1193 for (i = cpus = 0; i < sizeof(si.dwActiveProcessorMask) * 8; i++)
1195 if (si.dwActiveProcessorMask & 1)
1196 cpus++;
1197 si.dwActiveProcessorMask >>= 1;
1199 return cpus ? cpus : 1;
1201 # elif defined(__OS2__)
1202 /* OS/2: Count the active CPUs. */
1203 int cpus, i, j;
1204 MPAFFINITY mp;
1205 if (DosQueryThreadAffinity(AFNTY_SYSTEM, &mp))
1206 return 1;
1207 for (j = cpus = 0; j < sizeof(mp.mask) / sizeof(mp.mask[0]); j++)
1208 for (i = 0; i < 32; i++)
1209 if (mp.mask[j] & (1UL << i))
1210 cpus++;
1211 return cpus ? cpus : 1;
1213 # else
1214 /* UNIX like systems, try sysconf and sysctl. */
1215 int cpus = -1;
1216 # if defined(CTL_HW)
1217 int mib[2];
1218 size_t sz;
1219 # endif
1221 # ifdef _SC_NPROCESSORS_ONLN
1222 cpus = sysconf(_SC_NPROCESSORS_ONLN);
1223 if (cpus >= 1)
1224 return cpus;
1225 cpus = -1;
1226 # endif
1228 # if defined(CTL_HW)
1229 # ifdef HW_AVAILCPU
1230 sz = sizeof(cpus);
1231 mib[0] = CTL_HW;
1232 mib[1] = HW_AVAILCPU;
1233 if (!sysctl(mib, 2, &cpus, &sz, NULL, 0)
1234 && cpus >= 1)
1235 return cpus;
1236 cpus = -1;
1237 # endif /* HW_AVAILCPU */
1239 sz = sizeof(cpus);
1240 mib[0] = CTL_HW;
1241 mib[1] = HW_NCPU;
1242 if (!sysctl(mib, 2, &cpus, &sz, NULL, 0)
1243 && cpus >= 1)
1244 return cpus;
1245 cpus = -1;
1246 # endif /* CTL_HW */
1248 /* no idea / failure, just return 1. */
1249 return 1;
1250 # endif
1252 #endif /* KMK */
1254 #ifdef __MSDOS__
1255 static void
1256 msdos_return_to_initial_directory (void)
1258 if (directory_before_chdir)
1259 chdir (directory_before_chdir);
1261 #endif /* __MSDOS__ */
1263 #ifndef _MSC_VER /* bird */
1264 char *mktemp (char *template);
1265 #endif
1266 int mkstemp (char *template);
1268 FILE *
1269 open_tmpfile(char **name, const char *template)
1271 #ifdef HAVE_FDOPEN
1272 int fd;
1273 #endif
1275 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
1276 # define TEMPLATE_LEN strlen (template)
1277 #else
1278 # define TEMPLATE_LEN L_tmpnam
1279 #endif
1280 *name = xmalloc (TEMPLATE_LEN + 1);
1281 strcpy (*name, template);
1283 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
1284 /* It's safest to use mkstemp(), if we can. */
1285 fd = mkstemp (*name);
1286 if (fd == -1)
1287 return 0;
1288 return fdopen (fd, "w");
1289 #else
1290 # ifdef HAVE_MKTEMP
1291 (void) mktemp (*name);
1292 # else
1293 (void) tmpnam (*name);
1294 # endif
1296 # ifdef HAVE_FDOPEN
1297 /* Can't use mkstemp(), but guard against a race condition. */
1298 fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
1299 if (fd == -1)
1300 return 0;
1301 return fdopen (fd, "w");
1302 # else
1303 /* Not secure, but what can we do? */
1304 return fopen (*name, "w");
1305 # endif
1306 #endif
1309 #ifdef CONFIG_WITH_FAST_IS_SPACE /*bird*/
1310 char space_map[space_map_size];
1311 #endif /* CONFIG_WITH_FAST_IS_SPACE */
1314 #ifdef _AMIGA
1316 main (int argc, char **argv)
1317 #else
1319 main (int argc, char **argv, char **envp)
1320 #endif
1322 static char *stdin_nm = 0;
1323 int makefile_status = MAKE_SUCCESS;
1324 struct dep *read_makefiles;
1325 PATH_VAR (current_directory);
1326 unsigned int restarts = 0;
1327 #ifdef WINDOWS32
1328 char *unix_path = NULL;
1329 char *windows32_path = NULL;
1331 #ifndef ELECTRIC_HEAP /* Drop this because it prevents JIT debugging. */
1332 SetUnhandledExceptionFilter(handle_runtime_exceptions);
1333 #endif /* !ELECTRIC_HEAP */
1335 /* start off assuming we have no shell */
1336 unixy_shell = 0;
1337 no_default_sh_exe = 1;
1338 #endif
1339 # ifdef CONFIG_WITH_FAST_IS_SPACE /* bird */
1340 memset (space_map, '\0', sizeof(space_map));
1341 set_space_map_entry (' ');
1342 set_space_map_entry ('\f');
1343 set_space_map_entry ('\n');
1344 set_space_map_entry ('\r');
1345 set_space_map_entry ('\t');
1346 set_space_map_entry ('\v');
1347 # endif /* CONFIG_WITH_FAST_IS_SPACE */
1349 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1350 make_start_ts = nano_timestamp ();
1351 #endif
1353 #ifdef SET_STACK_SIZE
1354 /* Get rid of any avoidable limit on stack size. */
1356 struct rlimit rlim;
1358 /* Set the stack limit huge so that alloca does not fail. */
1359 if (getrlimit (RLIMIT_STACK, &rlim) == 0)
1361 rlim.rlim_cur = rlim.rlim_max;
1362 setrlimit (RLIMIT_STACK, &rlim);
1365 #endif
1367 #ifdef HAVE_ATEXIT
1368 atexit (close_stdout);
1369 #endif
1371 /* Needed for OS/2 */
1372 initialize_main(&argc, &argv);
1374 #ifdef KMK
1375 init_kbuild (argc, argv);
1376 #endif
1378 default_goal_file = 0;
1379 reading_file = 0;
1381 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1382 /* Request the most powerful version of `system', to
1383 make up for the dumb default shell. */
1384 __system_flags = (__system_redirect
1385 | __system_use_shell
1386 | __system_allow_multiple_cmds
1387 | __system_allow_long_cmds
1388 | __system_handle_null_commands
1389 | __system_emulate_chdir);
1391 #endif
1393 /* Set up gettext/internationalization support. */
1394 setlocale (LC_ALL, "");
1395 #ifdef LOCALEDIR /* bird */
1396 bindtextdomain (PACKAGE, LOCALEDIR);
1397 textdomain (PACKAGE);
1398 #endif
1400 #ifdef POSIX
1401 sigemptyset (&fatal_signal_set);
1402 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1403 #else
1404 #ifdef HAVE_SIGSETMASK
1405 fatal_signal_mask = 0;
1406 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1407 #else
1408 #define ADD_SIG(sig)
1409 #endif
1410 #endif
1412 #define FATAL_SIG(sig) \
1413 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1414 bsd_signal (sig, SIG_IGN); \
1415 else \
1416 ADD_SIG (sig);
1418 #ifdef SIGHUP
1419 FATAL_SIG (SIGHUP);
1420 #endif
1421 #ifdef SIGQUIT
1422 FATAL_SIG (SIGQUIT);
1423 #endif
1424 FATAL_SIG (SIGINT);
1425 FATAL_SIG (SIGTERM);
1427 #ifdef __MSDOS__
1428 /* Windows 9X delivers FP exceptions in child programs to their
1429 parent! We don't want Make to die when a child divides by zero,
1430 so we work around that lossage by catching SIGFPE. */
1431 FATAL_SIG (SIGFPE);
1432 #endif
1434 #ifdef SIGDANGER
1435 FATAL_SIG (SIGDANGER);
1436 #endif
1437 #ifdef SIGXCPU
1438 FATAL_SIG (SIGXCPU);
1439 #endif
1440 #ifdef SIGXFSZ
1441 FATAL_SIG (SIGXFSZ);
1442 #endif
1444 #ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1445 /* bird: dispatch signals in our own way to try avoid deadlocks. */
1446 g_tidMainThread = GetCurrentThreadId ();
1447 SetConsoleCtrlHandler (ctrl_event, TRUE);
1448 #endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1450 #undef FATAL_SIG
1452 /* Do not ignore the child-death signal. This must be done before
1453 any children could possibly be created; otherwise, the wait
1454 functions won't work on systems with the SVR4 ECHILD brain
1455 damage, if our invoker is ignoring this signal. */
1457 #ifdef HAVE_WAIT_NOHANG
1458 # if defined SIGCHLD
1459 (void) bsd_signal (SIGCHLD, SIG_DFL);
1460 # endif
1461 # if defined SIGCLD && SIGCLD != SIGCHLD
1462 (void) bsd_signal (SIGCLD, SIG_DFL);
1463 # endif
1464 #endif
1466 /* Make sure stdout is line-buffered. */
1468 #ifdef HAVE_SETVBUF
1469 # ifdef SETVBUF_REVERSED
1470 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
1471 # else /* setvbuf not reversed. */
1472 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
1473 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
1474 # endif /* setvbuf reversed. */
1475 #elif HAVE_SETLINEBUF
1476 setlinebuf (stdout);
1477 #endif /* setlinebuf missing. */
1479 /* Figure out where this program lives. */
1481 if (argv[0] == 0)
1482 argv[0] = "";
1483 if (argv[0][0] == '\0')
1484 #ifdef KMK
1485 program = "kmk";
1486 #else
1487 program = "make";
1488 #endif
1489 else
1491 #ifdef VMS
1492 program = strrchr (argv[0], ']');
1493 #else
1494 program = strrchr (argv[0], '/');
1495 #endif
1496 #if defined(__MSDOS__) || defined(__EMX__)
1497 if (program == 0)
1498 program = strrchr (argv[0], '\\');
1499 else
1501 /* Some weird environments might pass us argv[0] with
1502 both kinds of slashes; we must find the rightmost. */
1503 char *p = strrchr (argv[0], '\\');
1504 if (p && p > program)
1505 program = p;
1507 if (program == 0 && argv[0][1] == ':')
1508 program = argv[0] + 1;
1509 #endif
1510 #ifdef WINDOWS32
1511 if (program == 0)
1513 /* Extract program from full path */
1514 int argv0_len;
1515 program = strrchr (argv[0], '\\');
1516 if (program)
1518 argv0_len = strlen(program);
1519 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1520 /* Remove .exe extension */
1521 program[argv0_len - 4] = '\0';
1524 #endif
1525 if (program == 0)
1526 program = argv[0];
1527 else
1528 ++program;
1531 /* Set up to access user data (files). */
1532 user_access ();
1534 #ifdef CONFIG_WITH_ALLOC_CACHES
1535 initialize_global_alloc_caches ();
1536 #endif
1537 initialize_global_hash_tables ();
1539 /* Figure out where we are. */
1541 #ifdef WINDOWS32
1542 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1543 #else
1544 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1545 #endif
1547 #ifdef HAVE_GETCWD
1548 perror_with_name ("getcwd", "");
1549 #else
1550 error (NILF, "getwd: %s", current_directory);
1551 #endif
1552 current_directory[0] = '\0';
1553 directory_before_chdir = 0;
1555 else
1556 directory_before_chdir = xstrdup (current_directory);
1557 #ifdef __MSDOS__
1558 /* Make sure we will return to the initial directory, come what may. */
1559 atexit (msdos_return_to_initial_directory);
1560 #endif
1562 /* Initialize the special variables. */
1563 define_variable (".VARIABLES", 10, "", o_default, 0)->special = 1;
1564 /* define_variable (".TARGETS", 8, "", o_default, 0)->special = 1; */
1565 define_variable (".RECIPEPREFIX", 13, "", o_default, 0)->special = 1;
1567 /* Set up .FEATURES */
1568 define_variable (".FEATURES", 9,
1569 "target-specific order-only second-expansion else-if",
1570 o_default, 0);
1571 #ifndef NO_ARCHIVES
1572 do_variable_definition (NILF, ".FEATURES", "archives",
1573 o_default, f_append, 0);
1574 #endif
1575 #ifdef MAKE_JOBSERVER
1576 do_variable_definition (NILF, ".FEATURES", "jobserver",
1577 o_default, f_append, 0);
1578 #endif
1579 #ifdef MAKE_SYMLINKS
1580 do_variable_definition (NILF, ".FEATURES", "check-symlink",
1581 o_default, f_append, 0);
1582 #endif
1583 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1584 do_variable_definition (NILF, ".FEATURES", "explicit-multitarget",
1585 o_default, f_append, 0);
1586 #endif
1587 #ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
1588 do_variable_definition (NILF, ".FEATURES", "prepend-assignment",
1589 o_default, f_append, 0);
1590 #endif
1592 #ifdef KMK
1593 /* Initialize the default number of jobs to the cpu/core/smt count. */
1594 default_job_slots = job_slots = get_online_cpu_count ();
1595 #endif /* KMK */
1597 /* Read in variables from the environment. It is important that this be
1598 done before $(MAKE) is figured out so its definitions will not be
1599 from the environment. */
1601 #ifndef _AMIGA
1603 unsigned int i;
1605 for (i = 0; envp[i] != 0; ++i)
1607 int do_not_define = 0;
1608 char *ep = envp[i];
1610 while (*ep != '\0' && *ep != '=')
1611 ++ep;
1612 #ifdef WINDOWS32
1613 if (!unix_path && strneq(envp[i], "PATH=", 5))
1614 unix_path = ep+1;
1615 else if (!strnicmp(envp[i], "Path=", 5)) {
1616 do_not_define = 1; /* it gets defined after loop exits */
1617 if (!windows32_path)
1618 windows32_path = ep+1;
1620 #endif
1621 /* The result of pointer arithmetic is cast to unsigned int for
1622 machines where ptrdiff_t is a different size that doesn't widen
1623 the same. */
1624 if (!do_not_define)
1626 struct variable *v;
1628 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1629 ep + 1, o_env, 1);
1630 /* Force exportation of every variable culled from the
1631 environment. We used to rely on target_environment's
1632 v_default code to do this. But that does not work for the
1633 case where an environment variable is redefined in a makefile
1634 with `override'; it should then still be exported, because it
1635 was originally in the environment. */
1636 v->export = v_export;
1638 /* Another wrinkle is that POSIX says the value of SHELL set in
1639 the makefile won't change the value of SHELL given to
1640 subprocesses. */
1641 if (streq (v->name, "SHELL"))
1643 #ifndef __MSDOS__
1644 v->export = v_noexport;
1645 #endif
1646 #ifndef CONFIG_WITH_STRCACHE2
1647 shell_var.name = "SHELL";
1648 #else
1649 shell_var.name = v->name;
1650 #endif
1651 shell_var.length = 5; /* bird - gotta set the length too! */
1652 #ifndef CONFIG_WITH_VALUE_LENGTH
1653 shell_var.value = xstrdup (ep + 1);
1654 #else
1655 shell_var.value = savestring (v->value, v->value_length);
1656 shell_var.value_length = v->value_length;
1657 #endif
1661 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1662 if (streq (v->name, "MAKE_RESTARTS"))
1664 v->export = v_noexport;
1665 restarts = (unsigned int) atoi (ep + 1);
1670 #ifdef WINDOWS32
1671 /* If we didn't find a correctly spelled PATH we define PATH as
1672 * either the first mispelled value or an empty string
1674 if (!unix_path)
1675 define_variable("PATH", 4,
1676 windows32_path ? windows32_path : "",
1677 o_env, 1)->export = v_export;
1678 #endif
1679 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1681 BPTR env, file, old;
1682 char buffer[1024];
1683 int len;
1684 __aligned struct FileInfoBlock fib;
1686 env = Lock ("ENV:", ACCESS_READ);
1687 if (env)
1689 old = CurrentDir (DupLock(env));
1690 Examine (env, &fib);
1692 while (ExNext (env, &fib))
1694 if (fib.fib_DirEntryType < 0) /* File */
1696 /* Define an empty variable. It will be filled in
1697 variable_lookup(). Makes startup quite a bit
1698 faster. */
1699 define_variable (fib.fib_FileName,
1700 strlen (fib.fib_FileName),
1701 "", o_env, 1)->export = v_export;
1704 UnLock (env);
1705 UnLock(CurrentDir(old));
1708 #endif
1710 /* Decode the switches. */
1712 #ifdef KMK
1713 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
1714 #else /* !KMK */
1715 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1716 #if 0
1717 /* People write things like:
1718 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1719 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1720 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1721 #endif
1722 #endif /* !KMK */
1723 decode_switches (argc, argv, 0);
1724 #ifdef WINDOWS32
1725 if (suspend_flag) {
1726 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1727 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1728 Sleep(30 * 1000);
1729 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1731 #endif
1733 decode_debug_flags ();
1735 #ifdef KMK
1736 set_make_priority_and_affinity ();
1737 #endif
1739 /* Set always_make_flag if -B was given and we've not restarted already. */
1740 always_make_flag = always_make_set && (restarts == 0);
1742 /* Print version information. */
1743 if (print_version_flag || print_data_base_flag || db_level)
1745 print_version ();
1747 /* `make --version' is supposed to just print the version and exit. */
1748 if (print_version_flag)
1749 die (0);
1752 #ifndef VMS
1753 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1754 (If it is a relative pathname with a slash, prepend our directory name
1755 so the result will run the same program regardless of the current dir.
1756 If it is a name with no slash, we can only hope that PATH did not
1757 find it in the current directory.) */
1758 #ifdef WINDOWS32
1760 * Convert from backslashes to forward slashes for
1761 * programs like sh which don't like them. Shouldn't
1762 * matter if the path is one way or the other for
1763 * CreateProcess().
1765 if (strpbrk(argv[0], "/:\\") ||
1766 strstr(argv[0], "..") ||
1767 strneq(argv[0], "//", 2))
1768 argv[0] = xstrdup(w32ify(argv[0],1));
1769 #else /* WINDOWS32 */
1770 #if defined (__MSDOS__) || defined (__EMX__)
1771 if (strchr (argv[0], '\\'))
1773 char *p;
1775 argv[0] = xstrdup (argv[0]);
1776 for (p = argv[0]; *p; p++)
1777 if (*p == '\\')
1778 *p = '/';
1780 /* If argv[0] is not in absolute form, prepend the current
1781 directory. This can happen when Make is invoked by another DJGPP
1782 program that uses a non-absolute name. */
1783 if (current_directory[0] != '\0'
1784 && argv[0] != 0
1785 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1786 # ifdef __EMX__
1787 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1788 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1789 # endif
1791 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1792 #else /* !__MSDOS__ */
1793 if (current_directory[0] != '\0'
1794 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1795 #ifdef HAVE_DOS_PATHS
1796 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1797 && strchr (argv[0], '\\') != 0
1798 #endif
1800 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1801 #endif /* !__MSDOS__ */
1802 #endif /* WINDOWS32 */
1803 #endif
1805 /* The extra indirection through $(MAKE_COMMAND) is done
1806 for hysterical raisins. */
1807 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1808 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1809 #ifdef KMK
1810 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1811 #endif
1813 if (command_variables != 0)
1815 struct command_variable *cv;
1816 struct variable *v;
1817 unsigned int len = 0;
1818 char *value, *p;
1820 /* Figure out how much space will be taken up by the command-line
1821 variable definitions. */
1822 for (cv = command_variables; cv != 0; cv = cv->next)
1824 v = cv->variable;
1825 len += 2 * strlen (v->name);
1826 if (! v->recursive)
1827 ++len;
1828 ++len;
1829 len += 2 * strlen (v->value);
1830 ++len;
1833 /* Now allocate a buffer big enough and fill it. */
1834 p = value = alloca (len);
1835 for (cv = command_variables; cv != 0; cv = cv->next)
1837 v = cv->variable;
1838 p = quote_for_env (p, v->name);
1839 if (! v->recursive)
1840 *p++ = ':';
1841 *p++ = '=';
1842 p = quote_for_env (p, v->value);
1843 *p++ = ' ';
1845 p[-1] = '\0'; /* Kill the final space and terminate. */
1847 /* Define an unchangeable variable with a name that no POSIX.2
1848 makefile could validly use for its own variable. */
1849 (void) define_variable ("-*-command-variables-*-", 23,
1850 value, o_automatic, 0);
1852 /* Define the variable; this will not override any user definition.
1853 Normally a reference to this variable is written into the value of
1854 MAKEFLAGS, allowing the user to override this value to affect the
1855 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1856 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1857 a reference to this hidden variable is written instead. */
1858 #ifdef KMK
1859 (void) define_variable ("KMK_OVERRIDES", 13,
1860 "${-*-command-variables-*-}", o_env, 1);
1861 #else
1862 (void) define_variable ("MAKEOVERRIDES", 13,
1863 "${-*-command-variables-*-}", o_env, 1);
1864 #endif
1867 /* If there were -C flags, move ourselves about. */
1868 if (directories != 0)
1870 unsigned int i;
1871 for (i = 0; directories->list[i] != 0; ++i)
1873 const char *dir = directories->list[i];
1874 #ifdef WINDOWS32
1875 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1876 But allow -C/ just in case someone wants that. */
1878 char *p = (char *)dir + strlen (dir) - 1;
1879 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1880 --p;
1881 p[1] = '\0';
1883 #endif
1884 if (chdir (dir) < 0)
1885 pfatal_with_name (dir);
1889 #ifdef KMK
1890 /* Check for [Mm]akefile.kup and change directory when found.
1891 Makefile.kmk overrides Makefile.kup but not plain Makefile.
1892 If no -C arguments were given, fake one to indicate chdir. */
1893 if (makefiles == 0)
1895 struct stat st;
1896 if (( ( stat ("Makefile.kup", &st) == 0
1897 && S_ISREG (st.st_mode) )
1898 || ( stat ("makefile.kup", &st) == 0
1899 && S_ISREG (st.st_mode) ) )
1900 && stat ("Makefile.kmk", &st) < 0
1901 && stat ("makefile.kmk", &st) < 0)
1903 static char fake_path[3*16 + 32] = "..";
1904 char *cur = &fake_path[2];
1905 int up_levels = 1;
1906 while (up_levels < 16)
1908 /* File with higher precedence.s */
1909 strcpy (cur, "/Makefile.kmk");
1910 if (stat (fake_path, &st) == 0)
1911 break;
1912 strcpy (cur, "/makefile.kmk");
1913 if (stat (fake_path, &st) == 0)
1914 break;
1916 /* the .kup files */
1917 strcpy (cur, "/Makefile.kup");
1918 if ( stat (fake_path, &st) != 0
1919 || !S_ISREG (st.st_mode))
1921 strcpy (cur, "/makefile.kup");
1922 if ( stat (fake_path, &st) != 0
1923 || !S_ISREG (st.st_mode))
1924 break;
1927 /* ok */
1928 strcpy (cur, "/..");
1929 cur += 3;
1930 up_levels++;
1933 if (up_levels >= 16)
1934 fatal (NILF, _("Makefile.kup recursion is too deep."));
1936 /* attempt to change to the directory. */
1937 *cur = '\0';
1938 if (chdir (fake_path) < 0)
1939 pfatal_with_name (fake_path);
1941 /* add the string to the directories. */
1942 if (!directories)
1944 directories = xmalloc (sizeof(*directories));
1945 directories->list = xmalloc (5 * sizeof (char *));
1946 directories->max = 5;
1947 directories->idx = 0;
1949 else if (directories->idx == directories->max - 1)
1951 directories->max += 5;
1952 directories->list = xrealloc ((void *)directories->list,
1953 directories->max * sizeof (char *));
1955 directories->list[directories->idx++] = fake_path;
1958 #endif /* KMK */
1960 #ifdef WINDOWS32
1962 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1963 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1965 * The functions in dir.c can incorrectly cache information for "."
1966 * before we have changed directory and this can cause file
1967 * lookups to fail because the current directory (.) was pointing
1968 * at the wrong place when it was first evaluated.
1970 #ifdef KMK /* this is really a candidate for all platforms... */
1972 extern char *default_shell;
1973 const char *bin = get_kbuild_bin_path();
1974 size_t len = strlen (bin);
1975 default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
1976 memcpy (default_shell, bin, len);
1977 strcpy (default_shell + len, "/kmk_ash.exe");
1978 no_default_sh_exe = 0;
1979 batch_mode_shell = 1;
1981 #else /* !KMK */
1982 no_default_sh_exe = !find_and_set_default_shell(NULL);
1983 #endif /* !KMK */
1984 #endif /* WINDOWS32 */
1985 /* Figure out the level of recursion. */
1987 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1988 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1989 makelevel = (unsigned int) atoi (v->value);
1990 else
1991 makelevel = 0;
1994 /* Except under -s, always do -w in sub-makes and under -C. */
1995 if (!silent_flag && (directories != 0 || makelevel > 0))
1996 print_directory_flag = 1;
1998 /* Let the user disable that with --no-print-directory. */
1999 if (inhibit_print_directory_flag)
2000 print_directory_flag = 0;
2002 /* If -R was given, set -r too (doesn't make sense otherwise!) */
2003 if (no_builtin_variables_flag)
2004 no_builtin_rules_flag = 1;
2006 /* Construct the list of include directories to search. */
2008 construct_include_path (include_directories == 0
2009 ? 0 : include_directories->list);
2011 /* Figure out where we are now, after chdir'ing. */
2012 if (directories == 0)
2013 /* We didn't move, so we're still in the same place. */
2014 starting_directory = current_directory;
2015 else
2017 #ifdef WINDOWS32
2018 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
2019 #else
2020 if (getcwd (current_directory, GET_PATH_MAX) == 0)
2021 #endif
2023 #ifdef HAVE_GETCWD
2024 perror_with_name ("getcwd", "");
2025 #else
2026 error (NILF, "getwd: %s", current_directory);
2027 #endif
2028 starting_directory = 0;
2030 else
2031 starting_directory = current_directory;
2034 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
2036 /* Read any stdin makefiles into temporary files. */
2038 if (makefiles != 0)
2040 unsigned int i;
2041 for (i = 0; i < makefiles->idx; ++i)
2042 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
2044 /* This makefile is standard input. Since we may re-exec
2045 and thus re-read the makefiles, we read standard input
2046 into a temporary file and read from that. */
2047 FILE *outfile;
2048 char *template, *tmpdir;
2050 if (stdin_nm)
2051 fatal (NILF, _("Makefile from standard input specified twice."));
2053 #ifdef VMS
2054 # define DEFAULT_TMPDIR "sys$scratch:"
2055 #else
2056 # ifdef P_tmpdir
2057 # define DEFAULT_TMPDIR P_tmpdir
2058 # else
2059 # define DEFAULT_TMPDIR "/tmp"
2060 # endif
2061 #endif
2062 #define DEFAULT_TMPFILE "GmXXXXXX"
2064 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
2065 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2066 /* These are also used commonly on these platforms. */
2067 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
2068 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
2069 #endif
2071 tmpdir = DEFAULT_TMPDIR;
2073 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
2074 strcpy (template, tmpdir);
2076 #ifdef HAVE_DOS_PATHS
2077 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
2078 strcat (template, "/");
2079 #else
2080 # ifndef VMS
2081 if (template[strlen (template) - 1] != '/')
2082 strcat (template, "/");
2083 # endif /* !VMS */
2084 #endif /* !HAVE_DOS_PATHS */
2086 strcat (template, DEFAULT_TMPFILE);
2087 outfile = open_tmpfile (&stdin_nm, template);
2088 if (outfile == 0)
2089 pfatal_with_name (_("fopen (temporary file)"));
2090 while (!feof (stdin) && ! ferror (stdin))
2092 char buf[2048];
2093 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
2094 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2095 pfatal_with_name (_("fwrite (temporary file)"));
2097 fclose (outfile);
2099 /* Replace the name that read_all_makefiles will
2100 see with the name of the temporary file. */
2101 makefiles->list[i] = strcache_add (stdin_nm);
2103 /* Make sure the temporary file will not be remade. */
2105 struct file *f = enter_file (strcache_add (stdin_nm));
2106 f->updated = 1;
2107 f->update_status = 0;
2108 f->command_state = cs_finished;
2109 /* Can't be intermediate, or it'll be removed too early for
2110 make re-exec. */
2111 f->intermediate = 0;
2112 f->dontcare = 0;
2117 #if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
2118 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
2119 /* Set up to handle children dying. This must be done before
2120 reading in the makefiles so that `shell' function calls will work.
2122 If we don't have a hanging wait we have to fall back to old, broken
2123 functionality here and rely on the signal handler and counting
2124 children.
2126 If we're using the jobs pipe we need a signal handler so that
2127 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
2128 jobserver pipe in job.c if we're waiting for a token.
2130 If none of these are true, we don't need a signal handler at all. */
2132 RETSIGTYPE child_handler (int sig);
2133 # if defined SIGCHLD
2134 bsd_signal (SIGCHLD, child_handler);
2135 # endif
2136 # if defined SIGCLD && SIGCLD != SIGCHLD
2137 bsd_signal (SIGCLD, child_handler);
2138 # endif
2140 #endif
2141 #endif
2143 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2144 #ifdef SIGUSR1
2145 bsd_signal (SIGUSR1, debug_signal_handler);
2146 #endif
2148 /* Define the initial list of suffixes for old-style rules. */
2150 set_default_suffixes ();
2152 /* Define the file rules for the built-in suffix rules. These will later
2153 be converted into pattern rules. We used to do this in
2154 install_default_implicit_rules, but since that happens after reading
2155 makefiles, it results in the built-in pattern rules taking precedence
2156 over makefile-specified suffix rules, which is wrong. */
2158 install_default_suffix_rules ();
2160 /* Define some internal and special variables. */
2162 define_automatic_variables ();
2164 /* Set up the MAKEFLAGS and MFLAGS variables
2165 so makefiles can look at them. */
2167 define_makeflags (0, 0);
2169 /* Define the default variables. */
2170 define_default_variables ();
2172 default_file = enter_file (strcache_add (".DEFAULT"));
2175 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
2176 default_goal_name = &v->value;
2179 /* Read all the makefiles. */
2181 read_makefiles
2182 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2184 #ifdef WINDOWS32
2185 /* look one last time after reading all Makefiles */
2186 if (no_default_sh_exe)
2187 no_default_sh_exe = !find_and_set_default_shell(NULL);
2188 #endif /* WINDOWS32 */
2190 #if defined (__MSDOS__) || defined (__EMX__)
2191 /* We need to know what kind of shell we will be using. */
2193 extern int _is_unixy_shell (const char *_path);
2194 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2195 extern int unixy_shell;
2196 extern char *default_shell;
2198 if (shv && *shv->value)
2200 char *shell_path = recursively_expand(shv);
2202 if (shell_path && _is_unixy_shell (shell_path))
2203 unixy_shell = 1;
2204 else
2205 unixy_shell = 0;
2206 if (shell_path)
2207 default_shell = shell_path;
2210 #endif /* __MSDOS__ || __EMX__ */
2212 /* Decode switches again, in case the variables were set by the makefile. */
2213 #ifdef KMK
2214 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2215 #else /* !KMK */
2216 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2217 #if 0
2218 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2219 #endif
2220 #endif /* !KMK */
2222 #if defined (__MSDOS__) || defined (__EMX__)
2223 if (job_slots != 1
2224 # ifdef __EMX__
2225 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2226 # endif
2229 error (NILF,
2230 _("Parallel jobs (-j) are not supported on this platform."));
2231 error (NILF, _("Resetting to single job (-j1) mode."));
2232 job_slots = 1;
2234 #endif
2236 #ifdef MAKE_JOBSERVER
2237 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
2239 if (jobserver_fds)
2241 const char *cp;
2242 unsigned int ui;
2244 for (ui=1; ui < jobserver_fds->idx; ++ui)
2245 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
2246 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
2248 /* Now parse the fds string and make sure it has the proper format. */
2250 cp = jobserver_fds->list[0];
2252 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
2253 fatal (NILF,
2254 _("internal error: invalid --jobserver-fds string `%s'"), cp);
2256 DB (DB_JOBS,
2257 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
2259 /* The combination of a pipe + !job_slots means we're using the
2260 jobserver. If !job_slots and we don't have a pipe, we can start
2261 infinite jobs. If we see both a pipe and job_slots >0 that means the
2262 user set -j explicitly. This is broken; in this case obey the user
2263 (ignore the jobserver pipe for this make) but print a message. */
2265 if (job_slots > 0)
2266 error (NILF,
2267 _("warning: -jN forced in submake: disabling jobserver mode."));
2269 /* Create a duplicate pipe, that will be closed in the SIGCHLD
2270 handler. If this fails with EBADF, the parent has closed the pipe
2271 on us because it didn't think we were a submake. If so, print a
2272 warning then default to -j1. */
2274 else if ((job_rfd = dup (job_fds[0])) < 0)
2276 if (errno != EBADF)
2277 pfatal_with_name (_("dup jobserver"));
2279 error (NILF,
2280 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
2281 job_slots = 1;
2284 if (job_slots > 0)
2286 close (job_fds[0]);
2287 close (job_fds[1]);
2288 job_fds[0] = job_fds[1] = -1;
2289 free (jobserver_fds->list);
2290 free (jobserver_fds);
2291 jobserver_fds = 0;
2295 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
2296 Set up the pipe and install the fds option for our children. */
2298 if (job_slots > 1)
2300 char *cp;
2301 char c = '+';
2303 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
2304 pfatal_with_name (_("creating jobs pipe"));
2306 /* Every make assumes that it always has one job it can run. For the
2307 submakes it's the token they were given by their parent. For the
2308 top make, we just subtract one from the number the user wants. We
2309 want job_slots to be 0 to indicate we're using the jobserver. */
2311 master_job_slots = job_slots;
2313 while (--job_slots)
2315 int r;
2317 EINTRLOOP (r, write (job_fds[1], &c, 1));
2318 if (r != 1)
2319 pfatal_with_name (_("init jobserver pipe"));
2322 /* Fill in the jobserver_fds struct for our children. */
2324 cp = xmalloc ((sizeof ("1024")*2)+1);
2325 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2327 jobserver_fds = (struct stringlist *)
2328 xmalloc (sizeof (struct stringlist));
2329 jobserver_fds->list = xmalloc (sizeof (char *));
2330 jobserver_fds->list[0] = cp;
2331 jobserver_fds->idx = 1;
2332 jobserver_fds->max = 1;
2334 #endif
2336 #ifndef MAKE_SYMLINKS
2337 if (check_symlink_flag)
2339 error (NILF, _("Symbolic links not supported: disabling -L."));
2340 check_symlink_flag = 0;
2342 #endif
2344 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2346 define_makeflags (1, 0);
2348 /* Make each `struct dep' point at the `struct file' for the file
2349 depended on. Also do magic for special targets. */
2351 snap_deps ();
2353 /* Convert old-style suffix rules to pattern rules. It is important to
2354 do this before installing the built-in pattern rules below, so that
2355 makefile-specified suffix rules take precedence over built-in pattern
2356 rules. */
2358 convert_to_pattern ();
2360 /* Install the default implicit pattern rules.
2361 This used to be done before reading the makefiles.
2362 But in that case, built-in pattern rules were in the chain
2363 before user-defined ones, so they matched first. */
2365 install_default_implicit_rules ();
2367 /* Compute implicit rule limits. */
2369 count_implicit_rule_limits ();
2371 /* Construct the listings of directories in VPATH lists. */
2373 build_vpath_lists ();
2375 /* Mark files given with -o flags as very old and as having been updated
2376 already, and files given with -W flags as brand new (time-stamp as far
2377 as possible into the future). If restarts is set we'll do -W later. */
2379 if (old_files != 0)
2381 const char **p;
2382 for (p = old_files->list; *p != 0; ++p)
2384 struct file *f = enter_file (*p);
2385 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2386 f->updated = 1;
2387 f->update_status = 0;
2388 f->command_state = cs_finished;
2392 if (!restarts && new_files != 0)
2394 const char **p;
2395 for (p = new_files->list; *p != 0; ++p)
2397 struct file *f = enter_file (*p);
2398 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2402 /* Initialize the remote job module. */
2403 remote_setup ();
2405 if (read_makefiles != 0)
2407 /* Update any makefiles if necessary. */
2409 FILE_TIMESTAMP *makefile_mtimes = 0;
2410 unsigned int mm_idx = 0;
2411 char **nargv = argv;
2412 int nargc = argc;
2413 int orig_db_level = db_level;
2414 int status;
2416 if (! ISDB (DB_MAKEFILES))
2417 db_level = DB_NONE;
2419 DB (DB_BASIC, (_("Updating makefiles....\n")));
2421 /* Remove any makefiles we don't want to try to update.
2422 Also record the current modtimes so we can compare them later. */
2424 register struct dep *d, *last;
2425 last = 0;
2426 d = read_makefiles;
2427 while (d != 0)
2429 struct file *f = d->file;
2430 if (f->double_colon)
2431 for (f = f->double_colon; f != NULL; f = f->prev)
2433 if (f->deps == 0 && f->cmds != 0)
2435 /* This makefile is a :: target with commands, but
2436 no dependencies. So, it will always be remade.
2437 This might well cause an infinite loop, so don't
2438 try to remake it. (This will only happen if
2439 your makefiles are written exceptionally
2440 stupidly; but if you work for Athena, that's how
2441 you write your makefiles.) */
2443 DB (DB_VERBOSE,
2444 (_("Makefile `%s' might loop; not remaking it.\n"),
2445 f->name));
2447 if (last == 0)
2448 read_makefiles = d->next;
2449 else
2450 last->next = d->next;
2452 /* Free the storage. */
2453 free_dep (d);
2455 d = last == 0 ? read_makefiles : last->next;
2457 break;
2460 if (f == NULL || !f->double_colon)
2462 makefile_mtimes = xrealloc (makefile_mtimes,
2463 (mm_idx+1)
2464 * sizeof (FILE_TIMESTAMP));
2465 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2466 last = d;
2467 d = d->next;
2472 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2473 define_makeflags (1, 1);
2475 rebuilding_makefiles = 1;
2476 status = update_goal_chain (read_makefiles);
2477 rebuilding_makefiles = 0;
2479 switch (status)
2481 case 1:
2482 /* The only way this can happen is if the user specified -q and asked
2483 * for one of the makefiles to be remade as a target on the command
2484 * line. Since we're not actually updating anything with -q we can
2485 * treat this as "did nothing".
2488 case -1:
2489 /* Did nothing. */
2490 break;
2492 case 2:
2493 /* Failed to update. Figure out if we care. */
2495 /* Nonzero if any makefile was successfully remade. */
2496 int any_remade = 0;
2497 /* Nonzero if any makefile we care about failed
2498 in updating or could not be found at all. */
2499 int any_failed = 0;
2500 unsigned int i;
2501 struct dep *d;
2503 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2505 /* Reset the considered flag; we may need to look at the file
2506 again to print an error. */
2507 d->file->considered = 0;
2509 if (d->file->updated)
2511 /* This makefile was updated. */
2512 if (d->file->update_status == 0)
2514 /* It was successfully updated. */
2515 any_remade |= (file_mtime_no_search (d->file)
2516 != makefile_mtimes[i]);
2518 else if (! (d->changed & RM_DONTCARE))
2520 FILE_TIMESTAMP mtime;
2521 /* The update failed and this makefile was not
2522 from the MAKEFILES variable, so we care. */
2523 error (NILF, _("Failed to remake makefile `%s'."),
2524 d->file->name);
2525 mtime = file_mtime_no_search (d->file);
2526 any_remade |= (mtime != NONEXISTENT_MTIME
2527 && mtime != makefile_mtimes[i]);
2528 makefile_status = MAKE_FAILURE;
2531 else
2532 /* This makefile was not found at all. */
2533 if (! (d->changed & RM_DONTCARE))
2535 /* This is a makefile we care about. See how much. */
2536 if (d->changed & RM_INCLUDED)
2537 /* An included makefile. We don't need
2538 to die, but we do want to complain. */
2539 error (NILF,
2540 _("Included makefile `%s' was not found."),
2541 dep_name (d));
2542 else
2544 /* A normal makefile. We must die later. */
2545 error (NILF, _("Makefile `%s' was not found"),
2546 dep_name (d));
2547 any_failed = 1;
2551 /* Reset this to empty so we get the right error message below. */
2552 read_makefiles = 0;
2554 if (any_remade)
2555 goto re_exec;
2556 if (any_failed)
2557 die (2);
2558 break;
2561 case 0:
2562 re_exec:
2563 /* Updated successfully. Re-exec ourselves. */
2565 remove_intermediates (0);
2567 if (print_data_base_flag)
2568 print_data_base ();
2570 log_working_directory (0);
2572 clean_jobserver (0);
2574 if (makefiles != 0)
2576 /* These names might have changed. */
2577 int i, j = 0;
2578 for (i = 1; i < argc; ++i)
2579 if (strneq (argv[i], "-f", 2)) /* XXX */
2581 char *p = &argv[i][2];
2582 if (*p == '\0')
2583 /* This cast is OK since we never modify argv. */
2584 argv[++i] = (char *) makefiles->list[j];
2585 else
2586 argv[i] = xstrdup (concat ("-f", makefiles->list[j], ""));
2587 ++j;
2591 /* Add -o option for the stdin temporary file, if necessary. */
2592 if (stdin_nm)
2594 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2595 memcpy (nargv, argv, argc * sizeof (char *));
2596 nargv[nargc++] = xstrdup (concat ("-o", stdin_nm, ""));
2597 nargv[nargc] = 0;
2600 if (directories != 0 && directories->idx > 0)
2602 int bad = 1;
2603 if (directory_before_chdir != 0)
2605 if (chdir (directory_before_chdir) < 0)
2606 perror_with_name ("chdir", "");
2607 else
2608 bad = 0;
2610 if (bad)
2611 fatal (NILF, _("Couldn't change back to original directory."));
2614 ++restarts;
2616 if (ISDB (DB_BASIC))
2618 char **p;
2619 printf (_("Re-executing[%u]:"), restarts);
2620 for (p = nargv; *p != 0; ++p)
2621 printf (" %s", *p);
2622 putchar ('\n');
2625 #ifndef _AMIGA
2627 char **p;
2628 for (p = environ; *p != 0; ++p)
2630 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2631 && (*p)[MAKELEVEL_LENGTH] == '=')
2633 *p = alloca (40);
2634 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2636 if (strneq (*p, "MAKE_RESTARTS=", 14))
2638 *p = alloca (40);
2639 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2640 restarts = 0;
2644 #else /* AMIGA */
2646 char buffer[256];
2648 sprintf (buffer, "%u", makelevel);
2649 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2651 sprintf (buffer, "%u", restarts);
2652 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2653 restarts = 0;
2655 #endif
2657 /* If we didn't set the restarts variable yet, add it. */
2658 if (restarts)
2660 char *b = alloca (40);
2661 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2662 putenv (b);
2665 fflush (stdout);
2666 fflush (stderr);
2668 /* Close the dup'd jobserver pipe if we opened one. */
2669 if (job_rfd >= 0)
2670 close (job_rfd);
2672 #ifdef _AMIGA
2673 exec_command (nargv);
2674 exit (0);
2675 #elif defined (__EMX__)
2677 /* It is not possible to use execve() here because this
2678 would cause the parent process to be terminated with
2679 exit code 0 before the child process has been terminated.
2680 Therefore it may be the best solution simply to spawn the
2681 child process including all file handles and to wait for its
2682 termination. */
2683 int pid;
2684 int status;
2685 pid = child_execute_job (0, 1, nargv, environ);
2687 /* is this loop really necessary? */
2688 do {
2689 pid = wait (&status);
2690 } while (pid <= 0);
2691 /* use the exit code of the child process */
2692 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2694 #else
2695 exec_command (nargv, environ);
2696 #endif
2697 /* NOTREACHED */
2699 default:
2700 #define BOGUS_UPDATE_STATUS 0
2701 assert (BOGUS_UPDATE_STATUS);
2702 break;
2705 db_level = orig_db_level;
2707 /* Free the makefile mtimes (if we allocated any). */
2708 if (makefile_mtimes)
2709 free (makefile_mtimes);
2712 /* Set up `MAKEFLAGS' again for the normal targets. */
2713 define_makeflags (1, 0);
2715 /* Set always_make_flag if -B was given. */
2716 always_make_flag = always_make_set;
2718 /* If restarts is set we haven't set up -W files yet, so do that now. */
2719 if (restarts && new_files != 0)
2721 const char **p;
2722 for (p = new_files->list; *p != 0; ++p)
2724 struct file *f = enter_file (*p);
2725 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2729 /* If there is a temp file from reading a makefile from stdin, get rid of
2730 it now. */
2731 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2732 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2735 int status;
2737 /* If there were no command-line goals, use the default. */
2738 if (goals == 0)
2740 if (**default_goal_name != '\0')
2742 if (default_goal_file == 0 ||
2743 strcmp (*default_goal_name, default_goal_file->name) != 0)
2745 default_goal_file = lookup_file (*default_goal_name);
2747 /* In case user set .DEFAULT_GOAL to a non-existent target
2748 name let's just enter this name into the table and let
2749 the standard logic sort it out. */
2750 if (default_goal_file == 0)
2752 struct nameseq *ns;
2753 char *p = *default_goal_name;
2755 #ifndef CONFIG_WITH_ALLOC_CACHES
2756 ns = multi_glob (
2757 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2758 sizeof (struct nameseq));
2759 #else
2760 ns = multi_glob (
2761 parse_file_seq (&p, '\0', &nameseq_cache, 1),
2762 &nameseq_cache);
2763 #endif
2765 /* .DEFAULT_GOAL should contain one target. */
2766 if (ns->next != 0)
2767 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2769 #ifndef CONFIG_WITH_VALUE_LENGTH
2770 default_goal_file = enter_file (strcache_add (ns->name));
2771 #else
2772 default_goal_file = enter_file (ns->name);
2773 #endif
2775 ns->name = 0; /* It was reused by enter_file(). */
2776 free_ns_chain (ns);
2780 goals = alloc_dep ();
2781 goals->file = default_goal_file;
2784 else
2785 lastgoal->next = 0;
2788 if (!goals)
2790 if (read_makefiles == 0)
2791 fatal (NILF, _("No targets specified and no makefile found"));
2793 fatal (NILF, _("No targets"));
2796 /* Update the goals. */
2798 DB (DB_BASIC, (_("Updating goal targets....\n")));
2800 switch (update_goal_chain (goals))
2802 case -1:
2803 /* Nothing happened. */
2804 case 0:
2805 /* Updated successfully. */
2806 status = makefile_status;
2807 break;
2808 case 1:
2809 /* We are under -q and would run some commands. */
2810 status = MAKE_TROUBLE;
2811 break;
2812 case 2:
2813 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2814 but in VMS, there is only success and failure. */
2815 status = MAKE_FAILURE;
2816 break;
2817 default:
2818 abort ();
2821 /* If we detected some clock skew, generate one last warning */
2822 if (clock_skew_detected)
2823 error (NILF,
2824 _("warning: Clock skew detected. Your build may be incomplete."));
2826 /* Exit. */
2827 die (status);
2830 /* NOTREACHED */
2831 return 0;
2834 /* Parsing of arguments, decoding of switches. */
2836 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2837 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2838 (sizeof (long_option_aliases) /
2839 sizeof (long_option_aliases[0]))];
2841 /* Fill in the string and vector for getopt. */
2842 static void
2843 init_switches (void)
2845 char *p;
2846 unsigned int c;
2847 unsigned int i;
2849 if (options[0] != '\0')
2850 /* Already done. */
2851 return;
2853 p = options;
2855 /* Return switch and non-switch args in order, regardless of
2856 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2857 *p++ = '-';
2859 for (i = 0; switches[i].c != '\0'; ++i)
2861 long_options[i].name = (switches[i].long_name == 0 ? "" :
2862 switches[i].long_name);
2863 long_options[i].flag = 0;
2864 long_options[i].val = switches[i].c;
2865 if (short_option (switches[i].c))
2866 *p++ = switches[i].c;
2867 switch (switches[i].type)
2869 case flag:
2870 case flag_off:
2871 case ignore:
2872 long_options[i].has_arg = no_argument;
2873 break;
2875 case string:
2876 case filename:
2877 case positive_int:
2878 case floating:
2879 if (short_option (switches[i].c))
2880 *p++ = ':';
2881 if (switches[i].noarg_value != 0)
2883 if (short_option (switches[i].c))
2884 *p++ = ':';
2885 long_options[i].has_arg = optional_argument;
2887 else
2888 long_options[i].has_arg = required_argument;
2889 break;
2892 *p = '\0';
2893 for (c = 0; c < (sizeof (long_option_aliases) /
2894 sizeof (long_option_aliases[0]));
2895 ++c)
2896 long_options[i++] = long_option_aliases[c];
2897 long_options[i].name = 0;
2900 static void
2901 handle_non_switch_argument (char *arg, int env)
2903 /* Non-option argument. It might be a variable definition. */
2904 struct variable *v;
2905 if (arg[0] == '-' && arg[1] == '\0')
2906 /* Ignore plain `-' for compatibility. */
2907 return;
2908 #ifndef CONFIG_WITH_VALUE_LENGTH
2909 v = try_variable_definition (0, arg, o_command, 0);
2910 #else
2911 v = try_variable_definition (0, arg, NULL, o_command, 0);
2912 #endif
2913 if (v != 0)
2915 /* It is indeed a variable definition. If we don't already have this
2916 one, record a pointer to the variable for later use in
2917 define_makeflags. */
2918 struct command_variable *cv;
2920 for (cv = command_variables; cv != 0; cv = cv->next)
2921 if (cv->variable == v)
2922 break;
2924 if (! cv) {
2925 cv = xmalloc (sizeof (*cv));
2926 cv->variable = v;
2927 cv->next = command_variables;
2928 command_variables = cv;
2931 else if (! env)
2933 /* Not an option or variable definition; it must be a goal
2934 target! Enter it as a file and add it to the dep chain of
2935 goals. */
2936 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2937 f->cmd_target = 1;
2939 if (goals == 0)
2941 goals = alloc_dep ();
2942 lastgoal = goals;
2944 else
2946 lastgoal->next = alloc_dep ();
2947 lastgoal = lastgoal->next;
2950 lastgoal->file = f;
2953 /* Add this target name to the MAKECMDGOALS variable. */
2954 struct variable *gv;
2955 const char *value;
2957 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2958 if (gv == 0)
2959 value = f->name;
2960 else
2962 /* Paste the old and new values together */
2963 unsigned int oldlen, newlen;
2964 char *vp;
2966 oldlen = strlen (gv->value);
2967 newlen = strlen (f->name);
2968 vp = alloca (oldlen + 1 + newlen + 1);
2969 memcpy (vp, gv->value, oldlen);
2970 vp[oldlen] = ' ';
2971 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2972 value = vp;
2974 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2979 /* Print a nice usage method. */
2981 static void
2982 print_usage (int bad)
2984 const char *const *cpp;
2985 FILE *usageto;
2987 if (print_version_flag)
2988 print_version ();
2990 usageto = bad ? stderr : stdout;
2992 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2994 for (cpp = usage; *cpp; ++cpp)
2995 fputs (_(*cpp), usageto);
2997 #ifdef KMK
2998 if (!remote_description || *remote_description == '\0')
2999 fprintf (usageto, _("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3000 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3001 else
3002 fprintf (usageto, _("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3003 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3004 #else /* !KMK */
3005 if (!remote_description || *remote_description == '\0')
3006 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
3007 else
3008 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
3009 make_host, remote_description);
3010 #endif /* !KMK */
3012 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
3015 /* Decode switches from ARGC and ARGV.
3016 They came from the environment if ENV is nonzero. */
3018 static void
3019 decode_switches (int argc, char **argv, int env)
3021 int bad = 0;
3022 register const struct command_switch *cs;
3023 register struct stringlist *sl;
3024 register int c;
3026 /* getopt does most of the parsing for us.
3027 First, get its vectors set up. */
3029 init_switches ();
3031 /* Let getopt produce error messages for the command line,
3032 but not for options from the environment. */
3033 opterr = !env;
3034 /* Reset getopt's state. */
3035 optind = 0;
3037 while (optind < argc)
3039 /* Parse the next argument. */
3040 c = getopt_long (argc, argv, options, long_options, (int *) 0);
3041 if (c == EOF)
3042 /* End of arguments, or "--" marker seen. */
3043 break;
3044 else if (c == 1)
3045 /* An argument not starting with a dash. */
3046 handle_non_switch_argument (optarg, env);
3047 else if (c == '?')
3048 /* Bad option. We will print a usage message and die later.
3049 But continue to parse the other options so the user can
3050 see all he did wrong. */
3051 bad = 1;
3052 else
3053 for (cs = switches; cs->c != '\0'; ++cs)
3054 if (cs->c == c)
3056 /* Whether or not we will actually do anything with
3057 this switch. We test this individually inside the
3058 switch below rather than just once outside it, so that
3059 options which are to be ignored still consume args. */
3060 int doit = !env || cs->env;
3062 switch (cs->type)
3064 default:
3065 abort ();
3067 case ignore:
3068 break;
3070 case flag:
3071 case flag_off:
3072 if (doit)
3073 *(int *) cs->value_ptr = cs->type == flag;
3074 break;
3076 case string:
3077 case filename:
3078 if (!doit)
3079 break;
3081 if (optarg == 0)
3082 optarg = xstrdup (cs->noarg_value);
3083 else if (*optarg == '\0')
3085 error (NILF, _("the `-%c' option requires a non-empty string argument"),
3086 cs->c);
3087 bad = 1;
3090 sl = *(struct stringlist **) cs->value_ptr;
3091 if (sl == 0)
3093 sl = (struct stringlist *)
3094 xmalloc (sizeof (struct stringlist));
3095 sl->max = 5;
3096 sl->idx = 0;
3097 sl->list = xmalloc (5 * sizeof (char *));
3098 *(struct stringlist **) cs->value_ptr = sl;
3100 else if (sl->idx == sl->max - 1)
3102 sl->max += 5;
3103 sl->list = xrealloc ((void *)sl->list, /* bird */
3104 sl->max * sizeof (char *));
3106 if (cs->type == filename)
3107 sl->list[sl->idx++] = expand_command_line_file (optarg);
3108 else
3109 sl->list[sl->idx++] = optarg;
3110 sl->list[sl->idx] = 0;
3111 break;
3113 case positive_int:
3114 /* See if we have an option argument; if we do require that
3115 it's all digits, not something like "10foo". */
3116 if (optarg == 0 && argc > optind)
3118 const char *cp;
3119 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3121 if (cp[0] == '\0')
3122 optarg = argv[optind++];
3125 if (!doit)
3126 break;
3128 if (optarg != 0)
3130 int i = atoi (optarg);
3131 const char *cp;
3133 /* Yes, I realize we're repeating this in some cases. */
3134 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
3137 if (i < 1 || cp[0] != '\0')
3139 error (NILF, _("the `-%c' option requires a positive integral argument"),
3140 cs->c);
3141 bad = 1;
3143 else
3144 *(unsigned int *) cs->value_ptr = i;
3146 else
3147 *(unsigned int *) cs->value_ptr
3148 = *(unsigned int *) cs->noarg_value;
3149 break;
3151 #ifndef NO_FLOAT
3152 case floating:
3153 if (optarg == 0 && optind < argc
3154 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3155 optarg = argv[optind++];
3157 if (doit)
3158 *(double *) cs->value_ptr
3159 = (optarg != 0 ? atof (optarg)
3160 : *(double *) cs->noarg_value);
3162 break;
3163 #endif
3166 /* We've found the switch. Stop looking. */
3167 break;
3171 /* There are no more options according to getting getopt, but there may
3172 be some arguments left. Since we have asked for non-option arguments
3173 to be returned in order, this only happens when there is a "--"
3174 argument to prevent later arguments from being options. */
3175 while (optind < argc)
3176 handle_non_switch_argument (argv[optind++], env);
3179 if (!env && (bad || print_usage_flag))
3181 print_usage (bad);
3182 die (bad ? 2 : 0);
3186 /* Decode switches from environment variable ENVAR (which is LEN chars long).
3187 We do this by chopping the value into a vector of words, prepending a
3188 dash to the first word if it lacks one, and passing the vector to
3189 decode_switches. */
3191 static void
3192 decode_env_switches (char *envar, unsigned int len)
3194 char *varref = alloca (2 + len + 2);
3195 char *value, *p;
3196 int argc;
3197 char **argv;
3199 /* Get the variable's value. */
3200 varref[0] = '$';
3201 varref[1] = '(';
3202 memcpy (&varref[2], envar, len);
3203 varref[2 + len] = ')';
3204 varref[2 + len + 1] = '\0';
3205 value = variable_expand (varref);
3207 /* Skip whitespace, and check for an empty value. */
3208 value = next_token (value);
3209 len = strlen (value);
3210 if (len == 0)
3211 return;
3213 /* Allocate a vector that is definitely big enough. */
3214 argv = alloca ((1 + len + 1) * sizeof (char *));
3216 /* Allocate a buffer to copy the value into while we split it into words
3217 and unquote it. We must use permanent storage for this because
3218 decode_switches may store pointers into the passed argument words. */
3219 p = xmalloc (2 * len);
3221 /* getopt will look at the arguments starting at ARGV[1].
3222 Prepend a spacer word. */
3223 argv[0] = 0;
3224 argc = 1;
3225 argv[argc] = p;
3226 while (*value != '\0')
3228 if (*value == '\\' && value[1] != '\0')
3229 ++value; /* Skip the backslash. */
3230 else if (isblank ((unsigned char)*value))
3232 /* End of the word. */
3233 *p++ = '\0';
3234 argv[++argc] = p;
3236 ++value;
3237 while (isblank ((unsigned char)*value));
3238 continue;
3240 *p++ = *value++;
3242 *p = '\0';
3243 argv[++argc] = 0;
3245 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3246 /* The first word doesn't start with a dash and isn't a variable
3247 definition. Add a dash and pass it along to decode_switches. We
3248 need permanent storage for this in case decode_switches saves
3249 pointers into the value. */
3250 argv[1] = xstrdup (concat ("-", argv[1], ""));
3252 /* Parse those words. */
3253 decode_switches (argc, argv, 1);
3256 /* Quote the string IN so that it will be interpreted as a single word with
3257 no magic by decode_env_switches; also double dollar signs to avoid
3258 variable expansion in make itself. Write the result into OUT, returning
3259 the address of the next character to be written.
3260 Allocating space for OUT twice the length of IN is always sufficient. */
3262 static char *
3263 quote_for_env (char *out, const char *in)
3265 while (*in != '\0')
3267 if (*in == '$')
3268 *out++ = '$';
3269 else if (isblank ((unsigned char)*in) || *in == '\\')
3270 *out++ = '\\';
3271 *out++ = *in++;
3274 return out;
3277 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3278 command switches. Include options with args if ALL is nonzero.
3279 Don't include options with the `no_makefile' flag set if MAKEFILE. */
3281 static void
3282 define_makeflags (int all, int makefile)
3284 #ifdef KMK
3285 static const char ref[] = "$(KMK_OVERRIDES)";
3286 #else
3287 static const char ref[] = "$(MAKEOVERRIDES)";
3288 #endif
3289 static const char posixref[] = "$(-*-command-variables-*-)";
3290 register const struct command_switch *cs;
3291 char *flagstring;
3292 register char *p;
3293 unsigned int words;
3294 struct variable *v;
3296 /* We will construct a linked list of `struct flag's describing
3297 all the flags which need to go in MAKEFLAGS. Then, once we
3298 know how many there are and their lengths, we can put them all
3299 together in a string. */
3301 struct flag
3303 struct flag *next;
3304 const struct command_switch *cs;
3305 const char *arg;
3307 struct flag *flags = 0;
3308 unsigned int flagslen = 0;
3309 #define ADD_FLAG(ARG, LEN) \
3310 do { \
3311 struct flag *new = alloca (sizeof (struct flag)); \
3312 new->cs = cs; \
3313 new->arg = (ARG); \
3314 new->next = flags; \
3315 flags = new; \
3316 if (new->arg == 0) \
3317 ++flagslen; /* Just a single flag letter. */ \
3318 else \
3319 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
3320 if (!short_option (cs->c)) \
3321 /* This switch has no single-letter version, so we use the long. */ \
3322 flagslen += 2 + strlen (cs->long_name); \
3323 } while (0)
3325 for (cs = switches; cs->c != '\0'; ++cs)
3326 if (cs->toenv && (!makefile || !cs->no_makefile))
3327 switch (cs->type)
3329 case ignore:
3330 break;
3332 case flag:
3333 case flag_off:
3334 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3335 && (cs->default_value == 0
3336 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3337 ADD_FLAG (0, 0);
3338 break;
3340 case positive_int:
3341 if (all)
3343 if ((cs->default_value != 0
3344 && (*(unsigned int *) cs->value_ptr
3345 == *(unsigned int *) cs->default_value)))
3346 break;
3347 else if (cs->noarg_value != 0
3348 && (*(unsigned int *) cs->value_ptr ==
3349 *(unsigned int *) cs->noarg_value))
3350 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3351 #if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
3352 else if (cs->c == 'j')
3353 /* Special case for `-j'. */
3354 ADD_FLAG ("1", 1);
3355 #endif
3356 else
3358 char *buf = alloca (30);
3359 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3360 ADD_FLAG (buf, strlen (buf));
3363 break;
3365 #ifndef NO_FLOAT
3366 case floating:
3367 if (all)
3369 if (cs->default_value != 0
3370 && (*(double *) cs->value_ptr
3371 == *(double *) cs->default_value))
3372 break;
3373 else if (cs->noarg_value != 0
3374 && (*(double *) cs->value_ptr
3375 == *(double *) cs->noarg_value))
3376 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3377 else
3379 char *buf = alloca (100);
3380 sprintf (buf, "%g", *(double *) cs->value_ptr);
3381 ADD_FLAG (buf, strlen (buf));
3384 break;
3385 #endif
3387 case filename:
3388 case string:
3389 if (all)
3391 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3392 if (sl != 0)
3394 /* Add the elements in reverse order, because all the flags
3395 get reversed below; and the order matters for some
3396 switches (like -I). */
3397 unsigned int i = sl->idx;
3398 while (i-- > 0)
3399 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3402 break;
3404 default:
3405 abort ();
3408 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3410 #undef ADD_FLAG
3412 /* Construct the value in FLAGSTRING.
3413 We allocate enough space for a preceding dash and trailing null. */
3414 flagstring = alloca (1 + flagslen + 1);
3415 memset (flagstring, '\0', 1 + flagslen + 1);
3416 p = flagstring;
3417 words = 1;
3418 *p++ = '-';
3419 while (flags != 0)
3421 /* Add the flag letter or name to the string. */
3422 if (short_option (flags->cs->c))
3423 *p++ = flags->cs->c;
3424 else
3426 if (*p != '-')
3428 *p++ = ' ';
3429 *p++ = '-';
3431 *p++ = '-';
3432 strcpy (p, flags->cs->long_name);
3433 p += strlen (p);
3435 if (flags->arg != 0)
3437 /* A flag that takes an optional argument which in this case is
3438 omitted is specified by ARG being "". We must distinguish
3439 because a following flag appended without an intervening " -"
3440 is considered the arg for the first. */
3441 if (flags->arg[0] != '\0')
3443 /* Add its argument too. */
3444 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3445 p = quote_for_env (p, flags->arg);
3447 ++words;
3448 /* Write a following space and dash, for the next flag. */
3449 *p++ = ' ';
3450 *p++ = '-';
3452 else if (!short_option (flags->cs->c))
3454 ++words;
3455 /* Long options must each go in their own word,
3456 so we write the following space and dash. */
3457 *p++ = ' ';
3458 *p++ = '-';
3460 flags = flags->next;
3463 /* Define MFLAGS before appending variable definitions. */
3465 if (p == &flagstring[1])
3466 /* No flags. */
3467 flagstring[0] = '\0';
3468 else if (p[-1] == '-')
3470 /* Kill the final space and dash. */
3471 p -= 2;
3472 *p = '\0';
3474 else
3475 /* Terminate the string. */
3476 *p = '\0';
3478 #ifdef KMK
3479 /* Since MFLAGS is not parsed for flags, there is no reason to
3480 override any makefile redefinition. */
3481 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3482 #endif /* !KMK */
3484 if (all && command_variables != 0)
3486 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3487 command-line variable definitions. */
3489 if (p == &flagstring[1])
3490 /* No flags written, so elide the leading dash already written. */
3491 p = flagstring;
3492 else
3494 /* Separate the variables from the switches with a "--" arg. */
3495 if (p[-1] != '-')
3497 /* We did not already write a trailing " -". */
3498 *p++ = ' ';
3499 *p++ = '-';
3501 /* There is a trailing " -"; fill it out to " -- ". */
3502 *p++ = '-';
3503 *p++ = ' ';
3506 /* Copy in the string. */
3507 if (posix_pedantic)
3509 memcpy (p, posixref, sizeof posixref - 1);
3510 p += sizeof posixref - 1;
3512 else
3514 memcpy (p, ref, sizeof ref - 1);
3515 p += sizeof ref - 1;
3518 else if (p == &flagstring[1])
3520 words = 0;
3521 --p;
3523 else if (p[-1] == '-')
3524 /* Kill the final space and dash. */
3525 p -= 2;
3526 /* Terminate the string. */
3527 *p = '\0';
3529 #ifdef KMK
3530 v = define_variable ("KMK_FLAGS", 9,
3531 /* If there are switches, omit the leading dash
3532 unless it is a single long option with two
3533 leading dashes. */
3534 &flagstring[(flagstring[0] == '-'
3535 && flagstring[1] != '-')
3536 ? 1 : 0],
3537 /* This used to use o_env, but that lost when a
3538 makefile defined MAKEFLAGS. Makefiles set
3539 MAKEFLAGS to add switches, but we still want
3540 to redefine its value with the full set of
3541 switches. Of course, an override or command
3542 definition will still take precedence. */
3543 o_file, 1);
3544 #else
3545 v = define_variable ("MAKEFLAGS", 9,
3546 /* If there are switches, omit the leading dash
3547 unless it is a single long option with two
3548 leading dashes. */
3549 &flagstring[(flagstring[0] == '-'
3550 && flagstring[1] != '-')
3551 ? 1 : 0],
3552 /* This used to use o_env, but that lost when a
3553 makefile defined MAKEFLAGS. Makefiles set
3554 MAKEFLAGS to add switches, but we still want
3555 to redefine its value with the full set of
3556 switches. Of course, an override or command
3557 definition will still take precedence. */
3558 o_file, 1);
3559 #endif
3560 if (! all)
3561 /* The first time we are called, set MAKEFLAGS to always be exported.
3562 We should not do this again on the second call, because that is
3563 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3564 v->export = v_export;
3566 #ifdef KMK
3567 /* Provide simple access to some of the options. */
3569 char val[32];
3570 sprintf (val, "%u", job_slots);
3571 define_variable ("KMK_OPTS_JOBS", sizeof("KMK_OPTS_JOBS") - 1,
3572 val, o_default, 1);
3573 define_variable ("KMK_OPTS_KEEP_GOING", sizeof("KMK_OPTS_KEEP_GOING") - 1,
3574 keep_going_flag ? "1" : "0", o_default, 1);
3575 define_variable ("KMK_OPTS_JUST_PRINT", sizeof("KMK_OPTS_JUST_PRINT") - 1,
3576 just_print_flag ? "1" : "0", o_default, 1);
3577 define_variable ("KMK_OPTS_PRETTY_COMMAND_PRINTING", sizeof("KMK_OPTS_PRETTY_COMMAND_PRINTING") - 1,
3578 pretty_command_printing ? "1" : "0", o_default, 1);
3579 sprintf (val, "%u", process_priority);
3580 define_variable ("KMK_OPTS_PRORITY", sizeof("KMK_OPTS_PRORITY") - 1,
3581 val, o_default, 1);
3582 sprintf (val, "%u", process_affinity);
3583 define_variable ("KMK_OPTS_AFFINITY", sizeof("KMK_OPTS_AFFINITY") - 1,
3584 val, o_default, 1);
3585 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
3586 define_variable ("KMK_OPTS_STATISTICS", sizeof("KMK_OPTS_STATISTICS") - 1,
3587 make_expensive_statistics ? "1" : "0", o_default, 1);
3588 # endif
3589 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
3590 sprintf (val, "%u", print_time_min);
3591 define_variable ("KMK_OPTS_PRINT_TIME", sizeof("KMK_OPTS_PRINT_TIME") - 1,
3592 val, o_default, 1);
3593 #endif
3595 #endif
3598 /* Print version information. */
3600 static void
3601 print_version (void)
3603 static int printed_version = 0;
3605 char *precede = print_data_base_flag ? "# " : "";
3607 if (printed_version)
3608 /* Do it only once. */
3609 return;
3611 #ifdef KMK
3612 printf ("%skmk - kBuild version %d.%d.%d (r%u)\n\
3613 \n",
3614 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR,
3615 KBUILD_VERSION_PATCH, KBUILD_SVN_REV);
3617 printf("%sBased on GNU Make %s:\n", precede, version_string);
3619 #else /* !KMK */
3620 printf ("%sGNU Make %s\n", precede, version_string);
3622 if (!remote_description || *remote_description == '\0')
3623 printf (_("%sBuilt for %s\n"), precede, make_host);
3624 else
3625 printf (_("%sBuilt for %s (%s)\n"),
3626 precede, make_host, remote_description);
3627 #endif /* !KMK */
3629 /* Print this untranslated. The coding standards recommend translating the
3630 (C) to the copyright symbol, but this string is going to change every
3631 year, and none of the rest of it should be translated (including the
3632 word "Copyright", so it hardly seems worth it. */
3634 printf ("%sCopyright (C) 2007 Free Software Foundation, Inc.\n", precede);
3636 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
3637 %sThis is free software: you are free to change and redistribute it.\n\
3638 %sThere is NO WARRANTY, to the extent permitted by law.\n"),
3639 precede, precede, precede);
3641 #ifdef KMK
3642 printf ("\n\
3643 %skBuild modifications:\n\
3644 %s Copyright (c) 2005-2009 knut st. osmundsen.\n\
3646 %skmkbuiltin commands derived from *BSD sources:\n\
3647 %s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3648 %s The Regents of the University of California. All rights reserved.\n\
3649 %s Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>\n",
3650 precede, precede, precede, precede, precede, precede);
3652 # ifdef KBUILD_PATH
3653 printf (_("\n\
3654 %sKBUILD_PATH: '%s' (default '%s')\n\
3655 %sKBUILD_BIN_PATH: '%s' (default '%s')\n\
3656 \n"),
3657 precede, get_kbuild_path(), KBUILD_PATH,
3658 precede, get_kbuild_bin_path(), KBUILD_BIN_PATH);
3659 # else /* !KBUILD_PATH */
3660 printf ("\n\
3661 %sKBUILD_PATH: '%s'\n\
3662 %sKBUILD_BIN_PATH: '%s'\n\
3663 \n",
3664 precede, get_kbuild_path(),
3665 precede, get_kbuild_bin_path());
3666 # endif /* !KBUILD_PATH */
3668 if (!remote_description || *remote_description == '\0')
3669 printf (_("%sThis program is a %s build, built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n\n"),
3670 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3671 else
3672 printf (_("%sThis program is a %s build, built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n\n"),
3673 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3675 #endif /* KMK */
3677 printed_version = 1;
3679 /* Flush stdout so the user doesn't have to wait to see the
3680 version information while things are thought about. */
3681 fflush (stdout);
3684 /* Print a bunch of information about this and that. */
3686 static void
3687 print_data_base ()
3689 time_t when;
3691 when = time ((time_t *) 0);
3692 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3694 print_variable_data_base ();
3695 print_dir_data_base ();
3696 print_rule_data_base ();
3697 print_file_data_base ();
3698 print_vpath_data_base ();
3699 #ifndef CONFIG_WITH_STRCACHE2
3700 strcache_print_stats ("#");
3701 #else
3702 strcache2_print_stats_all ("#");
3703 #endif
3704 #ifdef CONFIG_WITH_ALLOC_CACHES
3705 alloccache_print_all ();
3706 #endif
3708 when = time ((time_t *) 0);
3709 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3711 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
3713 static void
3714 print_stats ()
3716 time_t when;
3718 when = time ((time_t *) 0);
3719 printf (_("\n# Make statistics, printed on %s"), ctime (&when));
3721 print_variable_stats ();
3722 print_file_stats ();
3723 # ifndef CONFIG_WITH_STRCACHE2
3724 strcache_print_stats ("#");
3725 # else
3726 strcache2_print_stats_all ("#");
3727 # endif
3728 # ifdef CONFIG_WITH_ALLOC_CACHES
3729 alloccache_print_all ();
3730 # endif
3731 print_heap_stats ();
3733 when = time ((time_t *) 0);
3734 printf (_("\n# Finished Make statistics on %s\n"), ctime (&when));
3736 #endif
3738 static void
3739 clean_jobserver (int status)
3741 char token = '+';
3743 /* Sanity: have we written all our jobserver tokens back? If our
3744 exit status is 2 that means some kind of syntax error; we might not
3745 have written all our tokens so do that now. If tokens are left
3746 after any other error code, that's bad. */
3748 if (job_fds[0] != -1 && jobserver_tokens)
3750 if (status != 2)
3751 error (NILF,
3752 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3753 jobserver_tokens);
3754 else
3755 while (jobserver_tokens--)
3757 int r;
3759 EINTRLOOP (r, write (job_fds[1], &token, 1));
3760 if (r != 1)
3761 perror_with_name ("write", "");
3766 /* Sanity: If we're the master, were all the tokens written back? */
3768 if (master_job_slots)
3770 /* We didn't write one for ourself, so start at 1. */
3771 unsigned int tcnt = 1;
3773 /* Close the write side, so the read() won't hang. */
3774 close (job_fds[1]);
3776 while (read (job_fds[0], &token, 1) == 1)
3777 ++tcnt;
3779 if (tcnt != master_job_slots)
3780 error (NILF,
3781 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3782 tcnt, master_job_slots);
3784 close (job_fds[0]);
3788 /* Exit with STATUS, cleaning up as necessary. */
3790 void
3791 die (int status)
3793 static char dying = 0;
3794 #ifdef KMK
3795 static char need_2nd_error = 0;
3796 #endif
3798 if (!dying)
3800 int err;
3802 dying = 1;
3804 if (print_version_flag)
3805 print_version ();
3807 #ifdef KMK
3808 /* Flag 2nd error message. */
3809 if (status != 0
3810 && ( job_slots_used > 0
3811 || print_data_base_flag
3812 || print_stats_flag))
3813 need_2nd_error = 1;
3814 #endif /* KMK */
3816 /* Wait for children to die. */
3817 err = (status != 0);
3818 while (job_slots_used > 0)
3819 reap_children (1, err);
3821 /* Let the remote job module clean up its state. */
3822 remote_cleanup ();
3824 /* Remove the intermediate files. */
3825 remove_intermediates (0);
3827 if (print_data_base_flag)
3828 print_data_base ();
3830 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
3831 if (print_stats_flag)
3832 print_stats ();
3833 #endif
3835 #ifdef NDEBUG /* bird: Don't waste time on debug sanity checks. */
3836 if (print_data_base_flag || db_level)
3837 #endif
3838 verify_file_data_base ();
3840 clean_jobserver (status);
3842 /* Try to move back to the original directory. This is essential on
3843 MS-DOS (where there is really only one process), and on Unix it
3844 puts core files in the original directory instead of the -C
3845 directory. Must wait until after remove_intermediates(), or unlinks
3846 of relative pathnames fail. */
3847 if (directory_before_chdir != 0)
3848 chdir (directory_before_chdir);
3850 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
3851 if (print_time_min != -1)
3853 big_int elapsed = nano_timestamp () - make_start_ts;
3854 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
3856 char buf[64];
3857 format_elapsed_nano (buf, sizeof (buf), elapsed);
3858 message (1, _("%*s"), print_time_width, buf);
3861 #endif
3863 log_working_directory (0);
3866 #ifdef KMK
3867 /* The failure might be lost in a -j <lots> run, so mention the
3868 failure again before exiting. */
3869 if (need_2nd_error != 0)
3870 error (NILF, _("*** Exiting with status %d"), status);
3871 #endif
3873 exit (status);
3876 /* Write a message indicating that we've just entered or
3877 left (according to ENTERING) the current directory. */
3879 void
3880 log_working_directory (int entering)
3882 static int entered = 0;
3884 /* Print nothing without the flag. Don't print the entering message
3885 again if we already have. Don't print the leaving message if we
3886 haven't printed the entering message. */
3887 if (! print_directory_flag || entering == entered)
3888 return;
3890 entered = entering;
3892 if (print_data_base_flag)
3893 fputs ("# ", stdout);
3895 /* Use entire sentences to give the translators a fighting chance. */
3897 if (makelevel == 0)
3898 if (starting_directory == 0)
3899 if (entering)
3900 printf (_("%s: Entering an unknown directory\n"), program);
3901 else
3902 printf (_("%s: Leaving an unknown directory\n"), program);
3903 else
3904 if (entering)
3905 printf (_("%s: Entering directory `%s'\n"),
3906 program, starting_directory);
3907 else
3908 printf (_("%s: Leaving directory `%s'\n"),
3909 program, starting_directory);
3910 else
3911 if (starting_directory == 0)
3912 if (entering)
3913 printf (_("%s[%u]: Entering an unknown directory\n"),
3914 program, makelevel);
3915 else
3916 printf (_("%s[%u]: Leaving an unknown directory\n"),
3917 program, makelevel);
3918 else
3919 if (entering)
3920 printf (_("%s[%u]: Entering directory `%s'\n"),
3921 program, makelevel, starting_directory);
3922 else
3923 printf (_("%s[%u]: Leaving directory `%s'\n"),
3924 program, makelevel, starting_directory);
3926 /* Flush stdout to be sure this comes before any stderr output. */
3927 fflush (stdout);