Built win.arm64 against r3658
[kbuild-mirror.git] / src / kmk / main.c
blobcf374406a858c77b8e8c98326f96b2160045cc97
1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988-2016 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include "makeint.h"
18 #include "os.h"
19 #include "filedef.h"
20 #include "dep.h"
21 #include "variable.h"
22 #include "job.h"
23 #include "commands.h"
24 #include "rule.h"
25 #include "debug.h"
26 #include "getopt.h"
27 #ifdef KMK
28 # include "kbuild.h"
29 #endif
30 #ifdef CONFIG_WITH_KMK_BUILTIN_STATS
31 # include "kmkbuiltin.h"
32 #endif
34 #include <assert.h>
35 #ifdef _AMIGA
36 # include <dos/dos.h>
37 # include <proto/dos.h>
38 #endif
39 #ifdef WINDOWS32
40 # include <windows.h>
41 # include <io.h>
42 # include "pathstuff.h"
43 # ifndef CONFIG_NEW_WIN_CHILDREN
44 # include "sub_proc.h"
45 # else
46 # include "w32/winchildren.h"
47 # endif
48 # include "w32err.h"
49 #endif
50 #ifdef __EMX__
51 # include <sys/types.h>
52 # include <sys/wait.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 # include <fcntl.h>
56 #endif
57 #ifdef CONFIG_WITH_COMPILER
58 # include "kmk_cc_exec.h"
59 #endif
61 #ifdef KMK /* for get_online_cpu_count */
62 # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
63 # include <sys/sysctl.h>
64 # endif
65 # ifdef __OS2__
66 # define INCL_BASE
67 # include <os2.h>
68 # endif
69 # ifdef __HAIKU__
70 # include <OS.h>
71 # endif
72 #endif /* KMK*/
74 #if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
75 # define SET_STACK_SIZE
76 #endif
78 #ifdef SET_STACK_SIZE
79 # include <sys/resource.h>
80 #endif
82 #ifdef _AMIGA
83 int __stack = 20000; /* Make sure we have 20K of stack space */
84 #endif
85 #ifdef VMS
86 int vms_use_mcr_command = 0;
87 int vms_always_use_cmd_file = 0;
88 int vms_gnv_shell = 0;
89 int vms_legacy_behavior = 0;
90 int vms_comma_separator = 0;
91 int vms_unix_simulation = 0;
92 int vms_report_unix_paths = 0;
94 /* Evaluates if a VMS environment option is set, only look at first character */
95 static int
96 get_vms_env_flag (const char *name, int default_value)
98 char * value;
99 char x;
101 value = getenv (name);
102 if (value == NULL)
103 return default_value;
105 x = toupper (value[0]);
106 switch (x)
108 case '1':
109 case 'T':
110 case 'E':
111 return 1;
112 break;
113 case '0':
114 case 'F':
115 case 'D':
116 return 0;
119 #endif
121 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
122 void print_variable_stats (void);
123 void print_dir_stats (void);
124 void print_file_stats (void);
125 #endif
127 #if defined HAVE_WAITPID || defined HAVE_WAIT3
128 # define HAVE_WAIT_NOHANG
129 #endif
131 #if !defined(HAVE_UNISTD_H) && !defined(_MSC_VER) /* bird */
132 int chdir ();
133 #endif
134 #ifndef STDC_HEADERS
135 # ifndef sun /* Sun has an incorrect decl in a header. */
136 void exit (int) __attribute__ ((noreturn));
137 # endif
138 double atof ();
139 #endif
141 static void clean_jobserver (int status);
142 static void print_data_base (void);
143 static void print_version (void);
144 static void decode_switches (int argc, const char **argv, int env);
145 static void decode_env_switches (const char *envar, unsigned int len);
146 static struct variable *define_makeflags (int all, int makefile);
147 static char *quote_for_env (char *out, const char *in);
148 static void initialize_global_hash_tables (void);
151 /* The structure that describes an accepted command switch. */
153 struct command_switch
155 int c; /* The switch character. */
157 enum /* Type of the value. */
159 flag, /* Turn int flag on. */
160 flag_off, /* Turn int flag off. */
161 string, /* One string per invocation. */
162 strlist, /* One string per switch. */
163 filename, /* A string containing a file name. */
164 positive_int, /* A positive integer. */
165 floating, /* A floating-point number (double). */
166 ignore /* Ignored. */
167 } type;
169 void *value_ptr; /* Pointer to the value-holding variable. */
171 unsigned int env:1; /* Can come from MAKEFLAGS. */
172 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
173 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
175 const void *noarg_value; /* Pointer to value used if no arg given. */
176 const void *default_value; /* Pointer to default value. */
178 const char *long_name; /* Long option name. */
181 /* True if C is a switch value that corresponds to a short option. */
183 #define short_option(c) ((c) <= CHAR_MAX)
185 /* The structure used to hold the list of strings given
186 in command switches of a type that takes strlist arguments. */
188 struct stringlist
190 const char **list; /* Nil-terminated list of strings. */
191 unsigned int idx; /* Index into above. */
192 unsigned int max; /* Number of pointers allocated. */
196 /* The recognized command switches. */
198 /* Nonzero means do extra verification (that may slow things down). */
200 int verify_flag;
202 /* Nonzero means do not print commands to be executed (-s). */
204 int silent_flag;
206 /* Nonzero means just touch the files
207 that would appear to need remaking (-t) */
209 int touch_flag;
211 /* Nonzero means just print what commands would need to be executed,
212 don't actually execute them (-n). */
214 int just_print_flag;
216 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
217 /* Nonzero means to print commands argument for argument skipping blanks. */
219 int pretty_command_printing;
220 #endif
222 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
223 /* Nonzero means to print internal statistics before exiting. */
225 int print_stats_flag;
226 #endif
228 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
229 /* Minimum number of seconds to report, -1 if disabled. */
231 int print_time_min = -1;
232 static int default_print_time_min = -1;
233 static int no_val_print_time_min = 0;
234 static big_int make_start_ts = -1;
235 int print_time_width = 5;
236 #endif
238 /* Print debugging info (--debug). */
240 static struct stringlist *db_flags = 0;
241 static int debug_flag = 0;
243 int db_level = 0;
245 /* Synchronize output (--output-sync). */
247 char *output_sync_option = 0;
249 #ifdef WINDOWS32
250 /* Suspend make in main for a short time to allow debugger to attach */
252 int suspend_flag = 0;
253 #endif
255 /* Environment variables override makefile definitions. */
257 int env_overrides = 0;
259 /* Nonzero means ignore status codes returned by commands
260 executed to remake files. Just treat them all as successful (-i). */
262 int ignore_errors_flag = 0;
264 /* Nonzero means don't remake anything, just print the data base
265 that results from reading the makefile (-p). */
267 int print_data_base_flag = 0;
269 /* Nonzero means don't remake anything; just return a nonzero status
270 if the specified targets are not up to date (-q). */
272 int question_flag = 0;
274 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
276 int no_builtin_rules_flag = 0;
277 int no_builtin_variables_flag = 0;
279 /* Nonzero means keep going even if remaking some file fails (-k). */
281 int keep_going_flag;
282 int default_keep_going_flag = 0;
284 /* Nonzero means check symlink mtimes. */
286 int check_symlink_flag = 0;
288 /* Nonzero means print directory before starting and when done (-w). */
290 int print_directory_flag = 0;
292 /* Nonzero means ignore print_directory_flag and never print the directory.
293 This is necessary because print_directory_flag is set implicitly. */
295 int inhibit_print_directory_flag = 0;
297 /* Nonzero means print version information. */
299 int print_version_flag = 0;
301 /* List of makefiles given with -f switches. */
303 static struct stringlist *makefiles = 0;
305 /* Size of the stack when we started. */
307 #ifdef SET_STACK_SIZE
308 struct rlimit stack_limit;
309 #endif
312 /* Number of job slots for parallelism. */
314 unsigned int job_slots;
316 #define INVALID_JOB_SLOTS (-1)
317 static unsigned int master_job_slots = 0;
318 static int arg_job_slots = INVALID_JOB_SLOTS;
320 #ifdef KMK
321 static int default_job_slots = INVALID_JOB_SLOTS;
322 #else
323 static const int default_job_slots = INVALID_JOB_SLOTS;
324 #endif
326 /* Value of job_slots that means no limit. */
328 static const int inf_jobs = 0;
330 /* Authorization for the jobserver. */
332 static char *jobserver_auth = NULL;
334 /* Handle for the mutex used on Windows to synchronize output of our
335 children under -O. */
337 char *sync_mutex = NULL;
339 /* Maximum load average at which multiple jobs will be run.
340 Negative values mean unlimited, while zero means limit to
341 zero load (which could be useful to start infinite jobs remotely
342 but one at a time locally). */
343 #ifndef NO_FLOAT
344 double max_load_average = -1.0;
345 double default_load_average = -1.0;
346 #else
347 int max_load_average = -1;
348 int default_load_average = -1;
349 #endif
351 /* List of directories given with -C switches. */
353 static struct stringlist *directories = 0;
355 /* List of include directories given with -I switches. */
357 static struct stringlist *include_directories = 0;
359 /* List of files given with -o switches. */
361 static struct stringlist *old_files = 0;
363 /* List of files given with -W switches. */
365 static struct stringlist *new_files = 0;
367 /* List of strings to be eval'd. */
368 static struct stringlist *eval_strings = 0;
370 /* If nonzero, we should just print usage and exit. */
372 static int print_usage_flag = 0;
374 /* If nonzero, we should print a warning message
375 for each reference to an undefined variable. */
377 int warn_undefined_variables_flag;
379 /* If nonzero, always build all targets, regardless of whether
380 they appear out of date or not. */
382 static int always_make_set = 0;
383 int always_make_flag = 0;
385 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
387 int rebuilding_makefiles = 0;
389 /* Remember the original value of the SHELL variable, from the environment. */
391 struct variable shell_var;
393 /* This character introduces a command: it's the first char on the line. */
395 char cmd_prefix = '\t';
397 #ifdef KMK
398 /* Process priority.
399 0 = no change;
400 1 = idle / max nice;
401 2 = below normal / nice 10;
402 3 = normal / nice 0;
403 4 = high / nice -10;
404 5 = realtime / nice -19; */
406 int process_priority = 0;
408 /* Process affinity mask; 0 means any CPU. */
410 int process_affinity = 0;
411 #endif /* KMK */
413 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
414 /* When set, we'll gather expensive statistics like for the heap. */
416 int make_expensive_statistics = 0;
417 #endif
419 #if defined (WINDOWS32) && defined (CONFIG_NEW_WIN_CHILDREN)
420 /* --job-object[=mode]. */
421 char *win_job_object_mode = NULL;
423 /* --job-object-name=name */
424 char *win_job_object_name = NULL;
426 /** --job-object-no-kill. */
427 int win_job_object_no_kill = 0;
428 #endif
431 /* The usage output. We write it this way to make life easier for the
432 translators, especially those trying to translate to right-to-left
433 languages like Hebrew. */
435 static const char *const usage[] =
437 N_("Options:\n"),
438 N_("\
439 -b, -m Ignored for compatibility.\n"),
440 N_("\
441 -B, --always-make Unconditionally make all targets.\n"),
442 N_("\
443 -C DIRECTORY, --directory=DIRECTORY\n\
444 Change to DIRECTORY before doing anything.\n"),
445 N_("\
446 -d Print lots of debugging information.\n"),
447 N_("\
448 --debug[=FLAGS] Print various types of debugging information.\n"),
449 N_("\
450 -e, --environment-overrides\n\
451 Environment variables override makefiles.\n"),
452 N_("\
453 --eval=STRING Evaluate STRING as a makefile statement.\n"),
454 N_("\
455 -f FILE, --file=FILE, --makefile=FILE\n\
456 Read FILE as a makefile.\n"),
457 N_("\
458 -h, --help Print this message and exit.\n"),
459 N_("\
460 -i, --ignore-errors Ignore errors from recipes.\n"),
461 N_("\
462 -I DIRECTORY, --include-dir=DIRECTORY\n\
463 Search DIRECTORY for included makefiles.\n"),
464 #ifdef KMK
465 N_("\
466 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n\
467 The default is the number of active CPUs.\n"),
468 #else
469 N_("\
470 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
471 #endif
472 N_("\
473 -k, --keep-going Keep going when some targets can't be made.\n"),
474 N_("\
475 -l [N], --load-average[=N], --max-load[=N]\n\
476 Don't start multiple jobs unless load is below N.\n"),
477 N_("\
478 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
479 N_("\
480 -n, --just-print, --dry-run, --recon\n\
481 Don't actually run any recipe; just print them.\n"),
482 N_("\
483 -o FILE, --old-file=FILE, --assume-old=FILE\n\
484 Consider FILE to be very old and don't remake it.\n"),
485 #ifndef KMK
486 N_("\
487 -O[TYPE], --output-sync[=TYPE]\n\
488 Synchronize output of parallel jobs by TYPE.\n"),
489 #elif defined(KBUILD_OS_WINDOWS)
490 N_("\
491 -O[TYPE], --output-sync[=TYPE]\n\
492 Synchronize output of parallel jobs by TYPE:\n\
493 none = no synchronization.\n\
494 line = receip line output\n\
495 target = entire receip output (default)\n\
496 recurse = entire recursive invocation\n"),
497 #else
498 N_("\
499 -O[TYPE], --output-sync[=TYPE]\n\
500 Synchronize output of parallel jobs by TYPE:\n\
501 none = no synchronization (default).\n\
502 line = receip line output\n\
503 target = entire receip output\n\
504 recurse = entire recursive invocation\n"),
505 #endif
506 N_("\
507 -p, --print-data-base Print make's internal database.\n"),
508 N_("\
509 -q, --question Run no recipe; exit status says if up to date.\n"),
510 N_("\
511 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
512 N_("\
513 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
514 N_("\
515 -s, --silent, --quiet Don't echo recipes.\n"),
516 N_("\
517 -S, --no-keep-going, --stop\n\
518 Turns off -k.\n"),
519 N_("\
520 -t, --touch Touch targets instead of remaking them.\n"),
521 N_("\
522 --trace Print tracing information.\n"),
523 N_("\
524 -v, --version Print the version number of make and exit.\n"),
525 N_("\
526 -w, --print-directory Print the current directory.\n"),
527 N_("\
528 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
529 N_("\
530 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
531 Consider FILE to be infinitely new.\n"),
532 N_("\
533 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
534 #ifdef KMK
535 N_("\
536 --affinity=mask Sets the CPU affinity on some hosts.\n"),
537 N_("\
538 --priority=1-5 Sets the process priority / nice level:\n\
539 1 = idle / max nice;\n\
540 2 = below normal / nice 10;\n\
541 3 = normal / nice 0;\n\
542 4 = high / nice -10;\n\
543 5 = realtime / nice -19;\n"),
544 N_("\
545 --nice Alias for --priority=1\n"),
546 #endif /* KMK */
547 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
548 N_("\
549 --pretty-command-printing Makes the command echo easier to read.\n"),
550 #endif
551 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
552 N_("\
553 --print-stats Print make statistics.\n"),
554 #endif
555 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
556 N_("\
557 --print-time[=MIN-SEC] Print file build times starting at arg.\n"),
558 #endif
559 #ifdef CONFIG_WITH_MAKE_STATS
560 N_("\
561 --statistics Gather extra statistics for $(make-stats ).\n"),
562 #endif
563 #if defined (WINDOWS32) && defined (CONFIG_NEW_WIN_CHILDREN)
564 N_("\
565 --job-object=mode Windows job object mode:\n\
566 login = Per login session (default).\n\
567 root = Root make instance only.\n\
568 each = Each make instances.\n\
569 none = No job objects.\n"),
570 N_("\
571 --job-object-name=name Name of windows job object to open or create.\n\
572 The default name depends on the level.\n"),
573 N_("\
574 --job-object-no-kill Do not kill orphaned child processes when done.\n"),
575 #endif
576 NULL
579 /* The table of command switches.
580 Order matters here: this is the order MAKEFLAGS will be constructed.
581 So be sure all simple flags (single char, no argument) come first. */
583 static const struct command_switch switches[] =
585 { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
586 { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
587 { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
588 #ifdef WINDOWS32
589 { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
590 #endif
591 { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
592 { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
593 { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
594 { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
595 "keep-going" },
596 { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
597 { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
598 { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
599 { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
600 #ifdef CONFIG_PRETTY_COMMAND_PRINTING
601 { CHAR_MAX+50, flag, (char *) &pretty_command_printing, 1, 1, 1, 0, 0,
602 "pretty-command-printing" },
603 #endif
604 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
605 { CHAR_MAX+51, flag, (char *) &print_stats_flag, 1, 1, 1, 0, 0,
606 "print-stats" },
607 #endif
608 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
609 { CHAR_MAX+52, positive_int, (char *) &print_time_min, 1, 1, 0,
610 (char *) &no_val_print_time_min, (char *) &default_print_time_min,
611 "print-time" },
612 #endif
613 #ifdef KMK
614 { CHAR_MAX+54, positive_int, (char *) &process_priority, 1, 1, 0,
615 (char *) &process_priority, (char *) &process_priority, "priority" },
616 { CHAR_MAX+55, positive_int, (char *) &process_affinity, 1, 1, 0,
617 (char *) &process_affinity, (char *) &process_affinity, "affinity" },
618 { CHAR_MAX+56, flag, (char *) &process_priority, 1, 1, 0, 0, 0, "nice" },
619 #endif
620 { 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
621 { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
622 { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
623 "no-builtin-variables" },
624 { 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },
625 { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
626 "no-keep-going" },
627 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
628 { CHAR_MAX+57, flag, (char *) &make_expensive_statistics, 1, 1, 1, 0, 0,
629 "statistics" },
630 #endif
631 { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
632 { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
633 { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
635 /* These options take arguments. */
636 { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
637 { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
638 { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
639 "include-dir" },
640 { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
641 "jobs" },
642 #ifndef NO_FLOAT
643 { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
644 &default_load_average, "load-average" },
645 #else
646 { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
647 &default_load_average, "load-average" },
648 #endif
649 { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
650 { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
651 { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
653 /* These are long-style options. */
654 { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
655 { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
656 { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
657 { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
658 "no-print-directory" },
659 { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
660 "warn-undefined-variables" },
661 { CHAR_MAX+6, strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
662 { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
663 #if defined (WINDOWS32) && defined (CONFIG_NEW_WIN_CHILDREN)
664 { CHAR_MAX+58, string, &win_job_object_mode, 1, 1, 1, 0, 0, "job-object" },
665 { CHAR_MAX+59, string, &win_job_object_name, 1, 1, 1, 0, 0,
666 "job-object-name" },
667 { CHAR_MAX+60, flag, &win_job_object_no_kill, 1, 1, 1, 0, 0,
668 "job-object-no-kill" },
669 #endif
670 { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
673 /* Secondary long names for options. */
675 static struct option long_option_aliases[] =
677 { "quiet", no_argument, 0, 's' },
678 { "stop", no_argument, 0, 'S' },
679 { "new-file", required_argument, 0, 'W' },
680 { "assume-new", required_argument, 0, 'W' },
681 { "assume-old", required_argument, 0, 'o' },
682 { "max-load", optional_argument, 0, 'l' },
683 { "dry-run", no_argument, 0, 'n' },
684 { "recon", no_argument, 0, 'n' },
685 { "makefile", required_argument, 0, 'f' },
688 /* List of goal targets. */
690 #ifndef KMK
691 static
692 #endif
693 struct goaldep *goals, *lastgoal;
695 /* List of variables which were defined on the command line
696 (or, equivalently, in MAKEFLAGS). */
698 struct command_variable
700 struct command_variable *next;
701 struct variable *variable;
703 static struct command_variable *command_variables;
705 /* The name we were invoked with. */
707 #ifdef WINDOWS32
708 /* On MS-Windows, we chop off the .exe suffix in 'main', so this
709 cannot be 'const'. */
710 char *program;
711 #else
712 const char *program;
713 #endif
715 /* Our current directory before processing any -C options. */
717 char *directory_before_chdir;
719 /* Our current directory after processing all -C options. */
721 char *starting_directory;
723 /* Value of the MAKELEVEL variable at startup (or 0). */
725 unsigned int makelevel;
727 /* Pointer to the value of the .DEFAULT_GOAL special variable.
728 The value will be the name of the goal to remake if the command line
729 does not override it. It can be set by the makefile, or else it's
730 the first target defined in the makefile whose name does not start
731 with '.'. */
733 struct variable * default_goal_var;
735 /* Pointer to structure for the file .DEFAULT
736 whose commands are used for any file that has none of its own.
737 This is zero if the makefiles do not define .DEFAULT. */
739 struct file *default_file;
741 /* Nonzero if we have seen the magic '.POSIX' target.
742 This turns on pedantic compliance with POSIX.2. */
744 int posix_pedantic;
746 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
747 This turns on secondary expansion of prerequisites. */
749 int second_expansion;
751 #ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
752 /* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
753 This turns on secondary expansion of targets. */
755 int second_target_expansion;
756 #endif
758 /* Nonzero if we have seen the '.ONESHELL' target.
759 This causes the entire recipe to be handed to SHELL
760 as a single string, potentially containing newlines. */
762 int one_shell;
764 /* One of OUTPUT_SYNC_* if the "--output-sync" option was given. This
765 attempts to synchronize the output of parallel jobs such that the results
766 of each job stay together. */
768 #ifdef KMK
769 int output_sync = OUTPUT_SYNC_TARGET;
770 #else
771 int output_sync = OUTPUT_SYNC_NONE;
772 #endif
774 /* Nonzero if the "--trace" option was given. */
776 int trace_flag = 0;
778 #ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
780 /* Nonzero if we have seen the '.NOTPARALLEL' target.
781 This turns off parallel builds for this invocation of make. */
783 #else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
785 /* Negative if we have seen the '.NOTPARALLEL' target with an
786 empty dependency list.
788 Zero if no '.NOTPARALLEL' or no file in the dependency list
789 is being executed.
791 Positive when a file in the '.NOTPARALLEL' dependency list
792 is in progress, the value is the number of notparallel files
793 in progress (running or queued for running).
795 In short, any nonzero value means no more parallel builing. */
796 #endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
798 int not_parallel;
800 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
801 print one warning about it during the run, and (b) we can print a final
802 warning at the end of the run. */
804 int clock_skew_detected;
806 /* Map of possible stop characters for searching strings. */
807 #ifndef UCHAR_MAX
808 # define UCHAR_MAX 255
809 #endif
810 #ifdef _MSC_VER
811 __declspec(align(512)) /* bird: improve cacheline & tlb mojo */
812 #endif
813 unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
815 /* If output-sync is enabled we'll collect all the output generated due to
816 options, while reading makefiles, etc. */
818 struct output make_sync;
820 #ifdef KMK
821 /** Current umask() value. */
822 mode_t g_fUMask = 0022;
823 #endif
826 /* Mask of signals that are being caught with fatal_error_signal. */
828 #ifdef POSIX
829 sigset_t fatal_signal_set;
830 #else
831 # ifdef HAVE_SIGSETMASK
832 int fatal_signal_mask;
833 # endif
834 #endif
836 #if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
837 # if !defined HAVE_SIGACTION
838 # define bsd_signal signal
839 # else
840 typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
842 static bsd_signal_ret_t
843 bsd_signal (int sig, bsd_signal_ret_t func)
845 struct sigaction act, oact;
846 act.sa_handler = func;
847 act.sa_flags = SA_RESTART;
848 sigemptyset (&act.sa_mask);
849 sigaddset (&act.sa_mask, sig);
850 if (sigaction (sig, &act, &oact) != 0)
851 return SIG_ERR;
852 return oact.sa_handler;
854 # endif
855 #endif
857 #ifdef CONFIG_WITH_ALLOC_CACHES
858 struct alloccache dep_cache;
859 struct alloccache goaldep_cache;
860 struct alloccache nameseq_cache;
861 struct alloccache file_cache;
862 struct alloccache commands_cache;
863 struct alloccache variable_cache;
864 struct alloccache variable_set_cache;
865 struct alloccache variable_set_list_cache;
867 static void
868 initialize_global_alloc_caches (void)
870 alloccache_init (&dep_cache, sizeof (struct dep), "dep", NULL, NULL);
871 alloccache_init (&goaldep_cache, sizeof (struct goaldep), "goaldep", NULL, NULL);
872 alloccache_init (&nameseq_cache, sizeof (struct nameseq), "nameseq", NULL, NULL);
873 alloccache_init (&file_cache, sizeof (struct file), "file", NULL, NULL);
874 alloccache_init (&commands_cache, sizeof (struct commands), "commands", NULL, NULL);
875 alloccache_init (&variable_cache, sizeof (struct variable), "variable", NULL, NULL);
876 alloccache_init (&variable_set_cache, sizeof (struct variable_set), "variable_set", NULL, NULL);
877 alloccache_init (&variable_set_list_cache, sizeof (struct variable_set_list), "variable_set_list", NULL, NULL);
879 #endif /* CONFIG_WITH_ALLOC_CACHES */
881 static void
882 initialize_global_hash_tables (void)
884 init_hash_global_variable_set ();
885 strcache_init ();
886 init_hash_files ();
887 hash_init_directories ();
888 hash_init_function_table ();
891 /* This character map locate stop chars when parsing GNU makefiles.
892 Each element is true if we should stop parsing on that character. */
894 static void
895 initialize_stopchar_map (void)
897 int i;
899 stopchar_map[(int)'\0'] = MAP_NUL;
900 stopchar_map[(int)'#'] = MAP_COMMENT;
901 stopchar_map[(int)';'] = MAP_SEMI;
902 stopchar_map[(int)'='] = MAP_EQUALS;
903 stopchar_map[(int)':'] = MAP_COLON;
904 stopchar_map[(int)'%'] = MAP_PERCENT;
905 stopchar_map[(int)'|'] = MAP_PIPE;
906 stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
907 stopchar_map[(int)','] = MAP_COMMA;
908 stopchar_map[(int)'$'] = MAP_VARIABLE;
910 stopchar_map[(int)'-'] = MAP_USERFUNC;
911 stopchar_map[(int)'_'] = MAP_USERFUNC;
913 stopchar_map[(int)' '] = MAP_BLANK;
914 stopchar_map[(int)'\t'] = MAP_BLANK;
916 stopchar_map[(int)'/'] = MAP_DIRSEP;
917 #if defined(VMS)
918 stopchar_map[(int)':'] |= MAP_DIRSEP;
919 stopchar_map[(int)']'] |= MAP_DIRSEP;
920 stopchar_map[(int)'>'] |= MAP_DIRSEP;
921 #elif defined(HAVE_DOS_PATHS)
922 stopchar_map[(int)'\\'] |= MAP_DIRSEP;
923 #endif
925 for (i = 1; i <= UCHAR_MAX; ++i)
927 if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
928 /* Don't mark blank characters as newline characters. */
929 stopchar_map[i] |= MAP_NEWLINE;
930 else if (isalnum (i))
931 stopchar_map[i] |= MAP_USERFUNC;
935 static const char *
936 expand_command_line_file (const char *name)
938 const char *cp;
939 char *expanded = 0;
941 if (name[0] == '\0')
942 O (fatal, NILF, _("empty string invalid as file name"));
944 if (name[0] == '~')
946 expanded = tilde_expand (name);
947 if (expanded && expanded[0] != '\0')
948 name = expanded;
951 /* This is also done in parse_file_seq, so this is redundant
952 for names read from makefiles. It is here for names passed
953 on the command line. */
954 while (name[0] == '.' && name[1] == '/')
956 name += 2;
957 while (name[0] == '/')
958 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
959 ++name;
962 if (name[0] == '\0')
964 /* Nothing else but one or more "./", maybe plus slashes! */
965 name = "./";
968 cp = strcache_add (name);
970 free (expanded);
972 return cp;
975 /* Toggle -d on receipt of SIGUSR1. */
977 #ifdef SIGUSR1
978 static RETSIGTYPE
979 debug_signal_handler (int sig UNUSED)
981 db_level = db_level ? DB_NONE : DB_BASIC;
983 #endif
985 static void
986 decode_debug_flags (void)
988 const char **pp;
990 if (debug_flag)
991 db_level = DB_ALL;
993 if (db_flags)
994 for (pp=db_flags->list; *pp; ++pp)
996 const char *p = *pp;
998 while (1)
1000 switch (tolower (p[0]))
1002 case 'a':
1003 db_level |= DB_ALL;
1004 break;
1005 case 'b':
1006 db_level |= DB_BASIC;
1007 break;
1008 case 'i':
1009 db_level |= DB_BASIC | DB_IMPLICIT;
1010 break;
1011 case 'j':
1012 db_level |= DB_JOBS;
1013 break;
1014 case 'm':
1015 db_level |= DB_BASIC | DB_MAKEFILES;
1016 break;
1017 case 'n':
1018 db_level = 0;
1019 break;
1020 case 'v':
1021 db_level |= DB_BASIC | DB_VERBOSE;
1022 break;
1023 #ifdef DB_KMK
1024 case 'k':
1025 db_level |= DB_KMK;
1026 break;
1027 #endif /* DB_KMK */
1028 default:
1029 OS (fatal, NILF,
1030 _("unknown debug level specification '%s'"), p);
1033 while (*(++p) != '\0')
1034 if (*p == ',' || *p == ' ')
1036 ++p;
1037 break;
1040 if (*p == '\0')
1041 break;
1045 if (db_level)
1046 verify_flag = 1;
1048 if (! db_level)
1049 debug_flag = 0;
1052 static void
1053 decode_output_sync_flags (void)
1055 #ifdef NO_OUTPUT_SYNC
1056 output_sync = OUTPUT_SYNC_NONE;
1057 #else
1058 if (output_sync_option)
1060 if (streq (output_sync_option, "none"))
1061 output_sync = OUTPUT_SYNC_NONE;
1062 else if (streq (output_sync_option, "line"))
1063 output_sync = OUTPUT_SYNC_LINE;
1064 else if (streq (output_sync_option, "target"))
1065 output_sync = OUTPUT_SYNC_TARGET;
1066 else if (streq (output_sync_option, "recurse"))
1067 output_sync = OUTPUT_SYNC_RECURSE;
1068 else
1069 OS (fatal, NILF,
1070 _("unknown output-sync type '%s'"), output_sync_option);
1073 if (sync_mutex)
1074 RECORD_SYNC_MUTEX (sync_mutex);
1075 #endif
1079 #ifdef KMK
1080 static void
1081 set_make_priority_and_affinity (void)
1083 # ifdef WINDOWS32
1084 DWORD dwClass, dwPriority;
1086 if (process_affinity)
1087 if (!SetProcessAffinityMask (GetCurrentProcess (), process_affinity))
1088 fprintf (stderr, "warning: SetProcessAffinityMask (,%#x) failed with last error %d\n",
1089 process_affinity, GetLastError ());
1091 switch (process_priority)
1093 case 0: return;
1094 case 1: dwClass = IDLE_PRIORITY_CLASS; dwPriority = THREAD_PRIORITY_IDLE; break;
1095 case 2: dwClass = BELOW_NORMAL_PRIORITY_CLASS; dwPriority = THREAD_PRIORITY_BELOW_NORMAL; break;
1096 case 3: dwClass = NORMAL_PRIORITY_CLASS; dwPriority = THREAD_PRIORITY_NORMAL; break;
1097 case 4: dwClass = HIGH_PRIORITY_CLASS; dwPriority = 0xffffffff; break;
1098 case 5: dwClass = REALTIME_PRIORITY_CLASS; dwPriority = 0xffffffff; break;
1099 default: ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
1101 if (!SetPriorityClass (GetCurrentProcess (), dwClass))
1102 fprintf (stderr, "warning: SetPriorityClass (,%#x) failed with last error %d\n",
1103 dwClass, GetLastError ());
1104 if (dwPriority != 0xffffffff
1105 && !SetThreadPriority (GetCurrentThread (), dwPriority))
1106 fprintf (stderr, "warning: SetThreadPriority (,%#x) failed with last error %d\n",
1107 dwPriority, GetLastError ());
1109 #elif defined(__HAIKU__)
1110 int32 iNewPriority;
1111 status_t error;
1113 switch (process_priority)
1115 case 0: return;
1116 case 1: iNewPriority = B_LOWEST_ACTIVE_PRIORITY; break;
1117 case 2: iNewPriority = B_LOW_PRIORITY; break;
1118 case 3: iNewPriority = B_NORMAL_PRIORITY; break;
1119 case 4: iNewPriority = B_URGENT_DISPLAY_PRIORITY; break;
1120 case 5: iNewPriority = B_REAL_TIME_DISPLAY_PRIORITY; break;
1121 default: ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
1123 error = set_thread_priority (find_thread (NULL), iNewPriority);
1124 if (error != B_OK)
1125 fprintf (stderr, "warning: set_thread_priority (,%d) failed: %s\n",
1126 iNewPriority, strerror (error));
1128 # else /*#elif HAVE_NICE */
1129 int nice_level = 0;
1130 switch (process_priority)
1132 case 0: return;
1133 case 1: nice_level = 19; break;
1134 case 2: nice_level = 10; break;
1135 case 3: nice_level = 0; break;
1136 case 4: nice_level = -10; break;
1137 case 5: nice_level = -19; break;
1138 default: ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
1140 errno = 0;
1141 if (nice (nice_level) == -1 && errno != 0)
1142 fprintf (stderr, "warning: nice (%d) failed: %s\n",
1143 nice_level, strerror (errno));
1144 # endif
1146 #endif /* KMK */
1149 #ifdef WINDOWS32
1151 #ifndef NO_OUTPUT_SYNC
1153 /* This is called from start_job_command when it detects that
1154 output_sync option is in effect. The handle to the synchronization
1155 mutex is passed, as a string, to sub-makes via the --sync-mutex
1156 command-line argument. */
1157 void
1158 # ifdef CONFIG_NEW_WIN_CHILDREN
1159 prepare_mutex_handle_string (const char *mtxname)
1161 if (!sync_mutex)
1163 sync_mutex = xstrdup(mtxname);
1164 define_makeflags (1, 0);
1167 # else
1168 prepare_mutex_handle_string (sync_handle_t handle)
1170 if (!sync_mutex)
1172 /* Prepare the mutex handle string for our children. */
1173 /* 2 hex digits per byte + 2 characters for "0x" + null. */
1174 sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
1175 sprintf (sync_mutex, "0x%Ix", handle);
1176 define_makeflags (1, 0);
1179 # endif
1181 #endif /* NO_OUTPUT_SYNC */
1183 # ifndef KMK /* I'd rather have WER collect dumps. */
1185 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
1186 * exception and print it to stderr instead.
1188 * If ! DB_VERBOSE, just print a simple message and exit.
1189 * If DB_VERBOSE, print a more verbose message.
1190 * If compiled for DEBUG, let exception pass through to GUI so that
1191 * debuggers can attach.
1193 LONG WINAPI
1194 handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
1196 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
1197 LPSTR cmdline = GetCommandLine ();
1198 LPSTR prg = strtok (cmdline, " ");
1199 CHAR errmsg[1024];
1200 #ifdef USE_EVENT_LOG
1201 HANDLE hEventSource;
1202 LPTSTR lpszStrings[1];
1203 #endif
1205 if (! ISDB (DB_VERBOSE))
1207 sprintf (errmsg,
1208 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
1209 prg, exrec->ExceptionCode, exrec->ExceptionAddress);
1210 fprintf (stderr, errmsg);
1211 exit (255);
1214 sprintf (errmsg,
1215 _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
1216 prg, exrec->ExceptionCode, exrec->ExceptionFlags,
1217 exrec->ExceptionAddress);
1219 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
1220 && exrec->NumberParameters >= 2)
1221 sprintf (&errmsg[strlen(errmsg)],
1222 (exrec->ExceptionInformation[0]
1223 ? _("Access violation: write operation at address 0x%p\n")
1224 : _("Access violation: read operation at address 0x%p\n")),
1225 (PVOID)exrec->ExceptionInformation[1]);
1227 /* turn this on if we want to put stuff in the event log too */
1228 #ifdef USE_EVENT_LOG
1229 hEventSource = RegisterEventSource (NULL, "GNU Make");
1230 lpszStrings[0] = errmsg;
1232 if (hEventSource != NULL)
1234 ReportEvent (hEventSource, /* handle of event source */
1235 EVENTLOG_ERROR_TYPE, /* event type */
1236 0, /* event category */
1237 0, /* event ID */
1238 NULL, /* current user's SID */
1239 1, /* strings in lpszStrings */
1240 0, /* no bytes of raw data */
1241 lpszStrings, /* array of error strings */
1242 NULL); /* no raw data */
1244 (VOID) DeregisterEventSource (hEventSource);
1246 #endif
1248 /* Write the error to stderr too */
1249 fprintf (stderr, errmsg);
1251 #ifdef DEBUG
1252 return EXCEPTION_CONTINUE_SEARCH;
1253 #else
1254 exit (255);
1255 return (255); /* not reached */
1256 #endif
1258 # endif /* !KMK */
1261 * On WIN32 systems we don't have the luxury of a /bin directory that
1262 * is mapped globally to every drive mounted to the system. Since make could
1263 * be invoked from any drive, and we don't want to propagate /bin/sh
1264 * to every single drive. Allow ourselves a chance to search for
1265 * a value for default shell here (if the default path does not exist).
1269 find_and_set_default_shell (const char *token)
1271 int sh_found = 0;
1272 char *atoken = 0;
1273 const char *search_token;
1274 const char *tokend;
1275 PATH_VAR(sh_path);
1276 extern const char *default_shell;
1278 if (!token)
1279 search_token = default_shell;
1280 else
1281 search_token = atoken = xstrdup (token);
1283 /* If the user explicitly requests the DOS cmd shell, obey that request.
1284 However, make sure that's what they really want by requiring the value
1285 of SHELL either equal, or have a final path element of, "cmd" or
1286 "cmd.exe" case-insensitive. */
1287 tokend = search_token + strlen (search_token) - 3;
1288 if (((tokend == search_token
1289 || (tokend > search_token
1290 && (tokend[-1] == '/' || tokend[-1] == '\\')))
1291 && !strcasecmp (tokend, "cmd"))
1292 || ((tokend - 4 == search_token
1293 || (tokend - 4 > search_token
1294 && (tokend[-5] == '/' || tokend[-5] == '\\')))
1295 && !strcasecmp (tokend - 4, "cmd.exe")))
1297 batch_mode_shell = 1;
1298 unixy_shell = 0;
1299 # if 1 /* bird: sprintf? wtf. */
1300 default_shell = unix_slashes (xstrdup (search_token));
1301 # else
1302 sprintf (sh_path, "%s", search_token);
1303 default_shell = xstrdup (w32ify (sh_path, 0));
1304 # endif
1305 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
1306 default_shell));
1307 sh_found = 1;
1309 else if (!no_default_sh_exe
1310 && (token == NULL || !strcmp (search_token, default_shell)))
1312 /* no new information, path already set or known */
1313 sh_found = 1;
1315 else if (_access (search_token, 0) == 0)
1317 /* search token path was found */
1318 # if 1 /* bird: sprintf? wtf. */
1319 default_shell = unix_slashes (xstrdup (search_token));
1320 # else
1321 sprintf (sh_path, "%s", search_token);
1322 default_shell = xstrdup (w32ify (sh_path, 0));
1323 # endif
1324 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
1325 default_shell));
1326 sh_found = 1;
1328 else
1330 char *p;
1331 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
1333 /* Search Path for shell */
1334 if (v && v->value)
1336 char *ep;
1338 p = v->value;
1339 ep = strchr (p, PATH_SEPARATOR_CHAR);
1341 while (ep && *ep)
1343 *ep = '\0';
1345 # if 1 /* bird: insanity insurance */
1346 _snprintf (sh_path, GET_PATH_MAX, "%s/%s", p, search_token);
1347 # else
1348 sprintf (sh_path, "%s/%s", p, search_token);
1349 # endif
1350 if (_access (sh_path, 0) == 0)
1352 # if 1 /* bird: we can modify sh_path directly. */
1353 default_shell = xstrdup (unix_slashes (sh_path));
1354 # else
1355 default_shell = xstrdup (w32ify (sh_path, 0));
1356 # endif
1357 sh_found = 1;
1358 *ep = PATH_SEPARATOR_CHAR;
1360 /* terminate loop */
1361 p += strlen (p);
1363 else
1365 *ep = PATH_SEPARATOR_CHAR;
1366 p = ++ep;
1369 ep = strchr (p, PATH_SEPARATOR_CHAR);
1372 /* be sure to check last element of Path */
1373 if (p && *p)
1375 # if 1 /* bird: insanity insurance */
1376 _snprintf (sh_path, GET_PATH_MAX, "%s/%s", p, search_token);
1377 # else
1378 sprintf (sh_path, "%s/%s", p, search_token);
1379 # endif
1380 if (_access (sh_path, 0) == 0)
1382 # if 1 /* bird: we can modify sh_path directly. */
1383 default_shell = xstrdup (unix_slashes (sh_path));
1384 # else
1385 default_shell = xstrdup (w32ify (sh_path, 0));
1386 # endif
1387 sh_found = 1;
1391 if (sh_found)
1392 DB (DB_VERBOSE,
1393 (_("find_and_set_shell() path search set default_shell = %s\n"),
1394 default_shell));
1398 /* naive test */
1399 if (!unixy_shell && sh_found
1400 && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1402 unixy_shell = 1;
1403 batch_mode_shell = 0;
1406 #ifdef BATCH_MODE_ONLY_SHELL
1407 batch_mode_shell = 1;
1408 #endif
1410 free (atoken);
1412 return (sh_found);
1415 /* bird: */
1416 # ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1417 # include <process.h>
1418 static UINT g_tidMainThread = 0;
1419 static int volatile g_sigPending = 0; /* lazy bird */
1420 # ifndef _M_IX86
1421 static LONG volatile g_lTriggered = 0;
1422 static CONTEXT g_Ctx;
1423 # endif
1425 # ifdef _M_IX86
1426 static __declspec(naked) void dispatch_stub(void)
1428 __asm {
1429 pushfd
1430 pushad
1433 fflush(stdout);
1434 /*fprintf(stderr, "dbg: raising %s on the main thread (%d)\n", g_sigPending == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());*/
1435 raise(g_sigPending);
1436 __asm {
1437 popad
1438 popfd
1442 # else /* !_M_IX86 */
1443 static void dispatch_stub(void)
1445 fflush(stdout);
1446 /*fprintf(stderr, "dbg: raising %s on the main thread (%d)\n", g_sigPending == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());*/
1447 raise(g_sigPending);
1449 SetThreadContext(GetCurrentThread(), &g_Ctx);
1450 fprintf(stderr, "fatal error: SetThreadContext failed with last error %d\n", GetLastError());
1451 for (;;)
1452 exit(131);
1454 # endif /* !_M_IX86 */
1456 static BOOL WINAPI ctrl_event(DWORD CtrlType)
1458 int sig = (CtrlType == CTRL_C_EVENT) ? SIGINT : SIGBREAK;
1459 HANDLE hThread;
1460 CONTEXT Ctx;
1462 /*fprintf(stderr, "dbg: ctrl_event sig=%d\n", sig);*/
1463 # ifndef _M_IX86
1464 /* only once. */
1465 if (InterlockedExchange(&g_lTriggered, 1))
1467 Sleep(1);
1468 return TRUE;
1470 # endif
1472 /* open the main thread and suspend it. */
1473 hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, g_tidMainThread);
1474 SuspendThread(hThread);
1476 /* Get the thread context and if we've get a valid Esp, dispatch
1477 it on the main thread otherwise raise the signal in the
1478 ctrl-event thread (this). */
1479 memset(&Ctx, 0, sizeof(Ctx));
1480 Ctx.ContextFlags = CONTEXT_FULL;
1481 if (GetThreadContext(hThread, &Ctx)
1482 # ifdef _M_IX86
1483 && Ctx.Esp >= 0x1000
1484 # else
1485 && Ctx.Rsp >= 0x1000
1486 # endif
1489 # ifdef _M_IX86
1490 ((uintptr_t *)Ctx.Esp)[-1] = Ctx.Eip;
1491 Ctx.Esp -= sizeof(uintptr_t);
1492 Ctx.Eip = (uintptr_t)&dispatch_stub;
1493 # else
1494 g_Ctx = Ctx;
1495 Ctx.Rsp -= 0x80;
1496 Ctx.Rsp &= ~(uintptr_t)0xf;
1497 Ctx.Rsp += 8; /* (Stack aligned before call instruction, not after.) */
1498 Ctx.Rip = (uintptr_t)&dispatch_stub;
1499 # endif
1501 SetThreadContext(hThread, &Ctx);
1502 g_sigPending = sig;
1503 ResumeThread(hThread);
1504 CloseHandle(hThread);
1506 else
1508 fprintf(stderr, "dbg: raising %s on the ctrl-event thread (%d)\n", sig == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());
1509 raise(sig);
1510 ResumeThread(hThread);
1511 CloseHandle(hThread);
1512 exit(130);
1515 Sleep(1);
1516 return TRUE;
1518 # endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1520 #endif /* WINDOWS32 */
1522 #ifdef KMK
1523 /* Determins the number of CPUs that are currently online.
1524 This is used to setup the default number of job slots. */
1525 static int
1526 get_online_cpu_count(void)
1528 # ifdef WINDOWS32
1529 /* Windows: Count the active CPUs. */
1530 int cpus;
1532 /* Process groups (W7+). */
1533 typedef DWORD (WINAPI *PFNGETACTIVEPROCESSORCOUNT)(DWORD);
1534 PFNGETACTIVEPROCESSORCOUNT pfnGetActiveProcessorCount;
1535 pfnGetActiveProcessorCount = (PFNGETACTIVEPROCESSORCOUNT)GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
1536 "GetActiveProcessorCount");
1537 if (pfnGetActiveProcessorCount)
1538 cpus = pfnGetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
1539 /* Legacy (<= Vista). */
1540 else
1542 int i;
1543 SYSTEM_INFO si;
1544 GetSystemInfo(&si);
1545 for (i = cpus = 0; i < sizeof(si.dwActiveProcessorMask) * 8; i++)
1547 if (si.dwActiveProcessorMask & 1)
1548 cpus++;
1549 si.dwActiveProcessorMask >>= 1;
1552 if (!cpus)
1553 cpus = 1;
1554 # ifndef CONFIG_NEW_WIN_CHILDREN
1555 if (cpus > 64)
1556 cpus = 64; /* (wait for multiple objects limit) */
1557 # endif
1558 return cpus;
1560 # elif defined(__OS2__)
1561 /* OS/2: Count the active CPUs. */
1562 int cpus, i, j;
1563 MPAFFINITY mp;
1564 if (DosQueryThreadAffinity(AFNTY_SYSTEM, &mp))
1565 return 1;
1566 for (j = cpus = 0; j < sizeof(mp.mask) / sizeof(mp.mask[0]); j++)
1567 for (i = 0; i < 32; i++)
1568 if (mp.mask[j] & (1UL << i))
1569 cpus++;
1570 return cpus ? cpus : 1;
1572 # else
1573 /* UNIX like systems, try sysconf and sysctl. */
1574 int cpus = -1;
1575 # if defined(CTL_HW)
1576 int mib[2];
1577 size_t sz;
1578 # endif
1580 # ifdef _SC_NPROCESSORS_ONLN
1581 cpus = sysconf(_SC_NPROCESSORS_ONLN);
1582 if (cpus >= 1)
1583 return cpus;
1584 cpus = -1;
1585 # endif
1587 # if defined(CTL_HW)
1588 # ifdef HW_AVAILCPU
1589 sz = sizeof(cpus);
1590 mib[0] = CTL_HW;
1591 mib[1] = HW_AVAILCPU;
1592 if (!sysctl(mib, 2, &cpus, &sz, NULL, 0)
1593 && cpus >= 1)
1594 return cpus;
1595 cpus = -1;
1596 # endif /* HW_AVAILCPU */
1598 sz = sizeof(cpus);
1599 mib[0] = CTL_HW;
1600 mib[1] = HW_NCPU;
1601 if (!sysctl(mib, 2, &cpus, &sz, NULL, 0)
1602 && cpus >= 1)
1603 return cpus;
1604 cpus = -1;
1605 # endif /* CTL_HW */
1607 /* no idea / failure, just return 1. */
1608 return 1;
1609 # endif
1611 #endif /* KMK */
1613 #ifdef __MSDOS__
1614 static void
1615 msdos_return_to_initial_directory (void)
1617 if (directory_before_chdir)
1618 chdir (directory_before_chdir);
1620 #endif /* __MSDOS__ */
1622 static void
1623 reset_jobserver (void)
1625 jobserver_clear ();
1626 free (jobserver_auth);
1627 jobserver_auth = NULL;
1630 #ifdef _AMIGA
1632 main (int argc, char **argv)
1633 #else
1635 main (int argc, char **argv, char **envp)
1636 #endif
1638 static char *stdin_nm = 0;
1639 #ifdef CONFIG_WITH_MAKE_STATS
1640 unsigned long long uStartTick = CURRENT_CLOCK_TICK();
1641 #endif
1642 int makefile_status = MAKE_SUCCESS;
1643 struct goaldep *read_files;
1644 PATH_VAR (current_directory);
1645 unsigned int restarts = 0;
1646 unsigned int syncing = 0;
1647 int argv_slots;
1648 #ifdef WINDOWS32
1649 const char *unix_path = NULL;
1650 const char *windows32_path = NULL;
1652 # ifndef ELECTRIC_HEAP /* Drop this because it prevents JIT debugging. */
1653 # ifndef KMK /* Don't want none of this crap. */
1654 SetUnhandledExceptionFilter (handle_runtime_exceptions);
1655 # endif
1656 # endif /* !ELECTRIC_HEAP */
1658 # ifdef KMK
1659 /* Clear the SEM_NOGPFAULTERRORBOX flag so WER will generate dumps when we run
1660 under cygwin. To void popups, set WER registry value DontShowUI to 1. */
1661 if (getenv("KMK_NO_SET_ERROR_MODE") == NULL)
1662 SetErrorMode(SetErrorMode(0) & ~SEM_NOGPFAULTERRORBOX);
1663 # endif
1665 /* start off assuming we have no shell */
1666 unixy_shell = 0;
1667 no_default_sh_exe = 1;
1668 #endif
1669 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1670 make_start_ts = nano_timestamp ();
1671 #endif
1673 output_init (&make_sync);
1675 initialize_stopchar_map();
1677 #ifdef SET_STACK_SIZE
1678 /* Get rid of any avoidable limit on stack size. */
1680 struct rlimit rlim;
1682 /* Set the stack limit huge so that alloca does not fail. */
1683 if (getrlimit (RLIMIT_STACK, &rlim) == 0
1684 && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
1686 stack_limit = rlim;
1687 rlim.rlim_cur = rlim.rlim_max;
1688 setrlimit (RLIMIT_STACK, &rlim);
1690 else
1691 stack_limit.rlim_cur = 0;
1693 #endif
1695 /* Needed for OS/2 */
1696 initialize_main (&argc, &argv);
1698 #ifdef KMK
1699 init_kbuild (argc, argv);
1700 #endif
1702 #ifdef MAKE_MAINTAINER_MODE
1703 /* In maintainer mode we always enable verification. */
1704 verify_flag = 1;
1705 #endif
1707 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1708 /* Request the most powerful version of 'system', to
1709 make up for the dumb default shell. */
1710 __system_flags = (__system_redirect
1711 | __system_use_shell
1712 | __system_allow_multiple_cmds
1713 | __system_allow_long_cmds
1714 | __system_handle_null_commands
1715 | __system_emulate_chdir);
1717 #endif
1719 /* Set up gettext/internationalization support. */
1720 setlocale (LC_ALL, "");
1721 /* The cast to void shuts up compiler warnings on systems that
1722 disable NLS. */
1723 #ifdef LOCALEDIR /* bird */
1724 (void)bindtextdomain (PACKAGE, LOCALEDIR);
1725 (void)textdomain (PACKAGE);
1726 #endif
1728 #ifdef POSIX
1729 sigemptyset (&fatal_signal_set);
1730 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1731 #else
1732 #ifdef HAVE_SIGSETMASK
1733 fatal_signal_mask = 0;
1734 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1735 #else
1736 #define ADD_SIG(sig) (void)sig
1737 #endif
1738 #endif
1740 #define FATAL_SIG(sig) \
1741 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1742 bsd_signal (sig, SIG_IGN); \
1743 else \
1744 ADD_SIG (sig);
1746 #ifdef SIGHUP
1747 FATAL_SIG (SIGHUP);
1748 #endif
1749 #ifdef SIGQUIT
1750 FATAL_SIG (SIGQUIT);
1751 #endif
1752 FATAL_SIG (SIGINT);
1753 FATAL_SIG (SIGTERM);
1755 #ifdef __MSDOS__
1756 /* Windows 9X delivers FP exceptions in child programs to their
1757 parent! We don't want Make to die when a child divides by zero,
1758 so we work around that lossage by catching SIGFPE. */
1759 FATAL_SIG (SIGFPE);
1760 #endif
1762 #ifdef SIGDANGER
1763 FATAL_SIG (SIGDANGER);
1764 #endif
1765 #ifdef SIGXCPU
1766 FATAL_SIG (SIGXCPU);
1767 #endif
1768 #ifdef SIGXFSZ
1769 FATAL_SIG (SIGXFSZ);
1770 #endif
1772 #ifdef KMK
1773 /* Get the incoming umask so we don't have to modify it later to get it. */
1774 umask(g_fUMask = umask(0077));
1775 #endif
1777 #ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1778 /* bird: dispatch signals in our own way to try avoid deadlocks. */
1779 g_tidMainThread = GetCurrentThreadId ();
1780 SetConsoleCtrlHandler (ctrl_event, TRUE);
1781 #endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1783 #undef FATAL_SIG
1785 /* Do not ignore the child-death signal. This must be done before
1786 any children could possibly be created; otherwise, the wait
1787 functions won't work on systems with the SVR4 ECHILD brain
1788 damage, if our invoker is ignoring this signal. */
1790 #ifdef HAVE_WAIT_NOHANG
1791 # if defined SIGCHLD
1792 (void) bsd_signal (SIGCHLD, SIG_DFL);
1793 # endif
1794 # if defined SIGCLD && SIGCLD != SIGCHLD
1795 (void) bsd_signal (SIGCLD, SIG_DFL);
1796 # endif
1797 #endif
1799 output_init (NULL);
1801 /* Figure out where this program lives. */
1803 if (argv[0] == 0)
1804 argv[0] = (char *)"";
1805 if (argv[0][0] == '\0')
1806 #ifdef KMK
1807 program = "kmk";
1808 #else
1809 program = "make";
1810 #endif
1811 else
1813 program = strrchr (argv[0], '/');
1814 #if defined(__MSDOS__) || defined(__EMX__)
1815 if (program == 0)
1816 program = strrchr (argv[0], '\\');
1817 else
1819 /* Some weird environments might pass us argv[0] with
1820 both kinds of slashes; we must find the rightmost. */
1821 char *p = strrchr (argv[0], '\\');
1822 if (p && p > program)
1823 program = p;
1825 if (program == 0 && argv[0][1] == ':')
1826 program = argv[0] + 1;
1827 #endif
1828 #ifdef WINDOWS32
1829 if (program == 0)
1831 /* Extract program from full path */
1832 program = strrchr (argv[0], '\\');
1833 if (program)
1835 int argv0_len = strlen (program);
1836 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1837 /* Remove .exe extension */
1838 program[argv0_len - 4] = '\0';
1841 #endif
1842 #ifdef VMS
1843 set_program_name (argv[0]);
1844 program = program_name;
1846 const char *shell;
1847 char pwdbuf[256];
1848 char *pwd;
1849 shell = getenv ("SHELL");
1850 if (shell != NULL)
1851 vms_gnv_shell = 1;
1853 /* Need to know if CRTL set to report UNIX paths. Use getcwd as
1854 it works on all versions of VMS. */
1855 pwd = getcwd(pwdbuf, 256);
1856 if (pwd[0] == '/')
1857 vms_report_unix_paths = 1;
1859 vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
1861 vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
1863 /* Legacy behavior is on VMS is older behavior that needed to be
1864 changed to be compatible with standard make behavior.
1865 For now only completely disable when running under a Bash shell.
1866 TODO: Update VMS built in recipes and macros to not need this
1867 behavior, at which time the default may change. */
1868 vms_legacy_behavior = get_vms_env_flag ("GNV$MAKE_OLD_VMS",
1869 !vms_gnv_shell);
1871 /* VMS was changed to use a comma separator in the past, but that is
1872 incompatible with built in functions that expect space separated
1873 lists. Allow this to be selectively turned off. */
1874 vms_comma_separator = get_vms_env_flag ("GNV$MAKE_COMMA",
1875 vms_legacy_behavior);
1877 /* Some Posix shell syntax options are incompatible with VMS syntax.
1878 VMS requires double quotes for strings and escapes quotes
1879 differently. When this option is active, VMS will try
1880 to simulate Posix shell simulations instead of using
1881 VMS DCL behavior. */
1882 vms_unix_simulation = get_vms_env_flag ("GNV$MAKE_SHELL_SIM",
1883 !vms_legacy_behavior);
1886 if (need_vms_symbol () && !vms_use_mcr_command)
1887 create_foreign_command (program_name, argv[0]);
1888 #else
1889 if (program == 0)
1890 program = argv[0];
1891 else
1892 ++program;
1893 #endif
1896 /* Set up to access user data (files). */
1897 user_access ();
1899 # ifdef CONFIG_WITH_COMPILER
1900 kmk_cc_init ();
1901 # endif
1902 #ifdef CONFIG_WITH_ALLOC_CACHES
1903 initialize_global_alloc_caches ();
1904 #endif
1905 initialize_global_hash_tables ();
1906 #ifdef KMK
1907 init_kbuild_object ();
1908 #endif
1910 /* Figure out where we are. */
1912 #ifdef WINDOWS32
1913 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1914 #else
1915 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1916 #endif
1918 #ifdef HAVE_GETCWD
1919 perror_with_name ("getcwd", "");
1920 #else
1921 OS (error, NILF, "getwd: %s", current_directory);
1922 #endif
1923 current_directory[0] = '\0';
1924 directory_before_chdir = 0;
1926 else
1927 directory_before_chdir = xstrdup (current_directory);
1929 #ifdef __MSDOS__
1930 /* Make sure we will return to the initial directory, come what may. */
1931 atexit (msdos_return_to_initial_directory);
1932 #endif
1934 /* Initialize the special variables. */
1935 define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
1936 /* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
1937 define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
1938 define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
1939 define_variable_cname (".LOADED", "", o_default, 0);
1941 /* Set up .FEATURES
1942 Use a separate variable because define_variable_cname() is a macro and
1943 some compilers (MSVC) don't like conditionals in macros. */
1945 const char *features = "target-specific order-only second-expansion"
1946 " else-if shortest-stem undefine oneshell"
1947 #ifndef NO_ARCHIVES
1948 " archives"
1949 #endif
1950 #ifdef MAKE_JOBSERVER
1951 " jobserver"
1952 #endif
1953 #ifndef NO_OUTPUT_SYNC
1954 " output-sync"
1955 #endif
1956 #ifdef MAKE_SYMLINKS
1957 " check-symlink"
1958 #endif
1959 #ifdef HAVE_GUILE
1960 " guile"
1961 #endif
1962 #ifdef MAKE_LOAD
1963 " load"
1964 #endif
1965 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1966 " explicit-multitarget"
1967 #endif
1968 #ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
1969 " prepend-assignment"
1970 #endif
1973 define_variable_cname (".FEATURES", features, o_default, 0);
1976 #ifdef KMK
1977 /* Initialize the default number of jobs to the cpu/core/smt count. */
1978 default_job_slots = arg_job_slots = job_slots = get_online_cpu_count ();
1979 #endif /* KMK */
1981 /* Configure GNU Guile support */
1982 guile_gmake_setup (NILF);
1984 /* Read in variables from the environment. It is important that this be
1985 done before $(MAKE) is figured out so its definitions will not be
1986 from the environment. */
1988 #ifndef _AMIGA
1990 unsigned int i;
1992 for (i = 0; envp[i] != 0; ++i)
1994 struct variable *v;
1995 const char *ep = envp[i];
1996 /* By default, export all variables culled from the environment. */
1997 enum variable_export export = v_export;
1998 unsigned int len;
2000 while (! STOP_SET (*ep, MAP_EQUALS))
2001 ++ep;
2003 /* If there's no equals sign it's a malformed environment. Ignore. */
2004 if (*ep == '\0')
2005 continue;
2007 #ifdef WINDOWS32
2008 if (!unix_path && strneq (envp[i], "PATH=", 5))
2009 unix_path = ep+1;
2010 else if (!strnicmp (envp[i], "Path=", 5))
2012 if (!windows32_path)
2013 windows32_path = ep+1;
2014 /* PATH gets defined after the loop exits. */
2015 continue;
2017 #endif
2019 /* Length of the variable name, and skip the '='. */
2020 len = ep++ - envp[i];
2022 /* If this is MAKE_RESTARTS, check to see if the "already printed
2023 the enter statement" flag is set. */
2024 if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
2026 if (*ep == '-')
2028 OUTPUT_TRACED ();
2029 ++ep;
2031 restarts = (unsigned int) atoi (ep);
2032 export = v_noexport;
2035 v = define_variable (envp[i], len, ep, o_env, 1);
2037 /* POSIX says the value of SHELL set in the makefile won't change the
2038 value of SHELL given to subprocesses. */
2039 if (streq (v->name, "SHELL"))
2041 #ifndef __MSDOS__
2042 export = v_noexport;
2043 #endif
2044 #ifndef CONFIG_WITH_STRCACHE2
2045 shell_var.name = xstrdup ("SHELL");
2046 #else
2047 shell_var.name = v->name;
2048 #endif
2049 shell_var.length = 5;
2050 #ifndef CONFIG_WITH_VALUE_LENGTH
2051 shell_var.value = xstrdup (ep);
2052 #else
2053 shell_var.value = xstrndup (v->value, v->value_length);
2054 shell_var.value_length = v->value_length;
2055 #endif
2058 v->export = export;
2061 #ifdef WINDOWS32
2062 /* If we didn't find a correctly spelled PATH we define PATH as
2063 * either the first misspelled value or an empty string
2065 if (!unix_path)
2066 define_variable_cname ("PATH", windows32_path ? windows32_path : "",
2067 o_env, 1)->export = v_export;
2068 #endif
2069 #else /* For Amiga, read the ENV: device, ignoring all dirs */
2071 BPTR env, file, old;
2072 char buffer[1024];
2073 int len;
2074 __aligned struct FileInfoBlock fib;
2076 env = Lock ("ENV:", ACCESS_READ);
2077 if (env)
2079 old = CurrentDir (DupLock (env));
2080 Examine (env, &fib);
2082 while (ExNext (env, &fib))
2084 if (fib.fib_DirEntryType < 0) /* File */
2086 /* Define an empty variable. It will be filled in
2087 variable_lookup(). Makes startup quite a bit faster. */
2088 define_variable (fib.fib_FileName,
2089 strlen (fib.fib_FileName),
2090 "", o_env, 1)->export = v_export;
2093 UnLock (env);
2094 UnLock (CurrentDir (old));
2097 #endif
2099 /* Decode the switches. */
2100 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
2102 /* Clear GNUMAKEFLAGS to avoid duplication. */
2103 define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
2105 #ifdef KMK
2106 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2107 #else /* !KMK */
2108 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2110 #if 0
2111 /* People write things like:
2112 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
2113 and we set the -p, -i and -e switches. Doesn't seem quite right. */
2114 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2115 #endif
2116 #endif /* !KMK */
2118 /* In output sync mode we need to sync any output generated by reading the
2119 makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */
2121 syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
2122 || output_sync == OUTPUT_SYNC_TARGET);
2123 OUTPUT_SET (&make_sync);
2125 /* Remember the job slots set through the environment vs. command line. */
2127 int env_slots = arg_job_slots;
2128 arg_job_slots = INVALID_JOB_SLOTS;
2130 decode_switches (argc, (const char **)argv, 0);
2131 argv_slots = arg_job_slots;
2133 if (arg_job_slots == INVALID_JOB_SLOTS)
2134 arg_job_slots = env_slots;
2137 /* Set a variable specifying whether stdout/stdin is hooked to a TTY. */
2138 #ifdef HAVE_ISATTY
2139 if (isatty (fileno (stdout)))
2140 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
2142 const char *tty = TTYNAME (fileno (stdout));
2143 define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
2144 o_default, 0)->export = v_export;
2146 if (isatty (fileno (stderr)))
2147 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
2149 const char *tty = TTYNAME (fileno (stderr));
2150 define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
2151 o_default, 0)->export = v_export;
2153 #endif
2155 /* Reset in case the switches changed our minds. */
2156 syncing = (output_sync == OUTPUT_SYNC_LINE
2157 || output_sync == OUTPUT_SYNC_TARGET);
2159 #ifdef KMK
2160 set_make_priority_and_affinity ();
2161 #endif
2163 if (make_sync.syncout && ! syncing)
2164 output_close (&make_sync);
2166 make_sync.syncout = syncing;
2167 OUTPUT_SET (&make_sync);
2169 /* Figure out the level of recursion. */
2171 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
2172 if (v && v->value[0] != '\0' && v->value[0] != '-')
2173 makelevel = (unsigned int) atoi (v->value);
2174 else
2175 makelevel = 0;
2178 #ifdef WINDOWS32
2179 if (suspend_flag)
2181 fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
2182 fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
2183 Sleep (30 * 1000);
2184 fprintf (stderr, _("done sleep(30). Continuing.\n"));
2186 #endif
2188 /* Set always_make_flag if -B was given and we've not restarted already. */
2189 always_make_flag = always_make_set && (restarts == 0);
2191 /* Print version information, and exit. */
2192 if (print_version_flag)
2194 print_version ();
2195 die (MAKE_SUCCESS);
2198 if (ISDB (DB_BASIC))
2199 print_version ();
2201 #ifndef VMS
2202 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
2203 (If it is a relative pathname with a slash, prepend our directory name
2204 so the result will run the same program regardless of the current dir.
2205 If it is a name with no slash, we can only hope that PATH did not
2206 find it in the current directory.) */
2207 #ifdef WINDOWS32
2209 * Convert from backslashes to forward slashes for
2210 * programs like sh which don't like them. Shouldn't
2211 * matter if the path is one way or the other for
2212 * CreateProcess().
2214 if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
2215 || strneq (argv[0], "//", 2))
2216 # if 1 /* bird */
2218 PATH_VAR (tmp_path_buf);
2219 argv[0] = xstrdup (unix_slashes_resolved (argv[0], tmp_path_buf,
2220 GET_PATH_MAX));
2222 # else /* bird */
2223 //argv[0] = xstrdup (w32ify (argv[0], 1));
2224 # endif /* bird */
2225 #else /* WINDOWS32 */
2226 #if defined (__MSDOS__) || defined (__EMX__)
2227 if (strchr (argv[0], '\\'))
2229 char *p;
2231 argv[0] = xstrdup (argv[0]);
2232 for (p = argv[0]; *p; p++)
2233 if (*p == '\\')
2234 *p = '/';
2236 /* If argv[0] is not in absolute form, prepend the current
2237 directory. This can happen when Make is invoked by another DJGPP
2238 program that uses a non-absolute name. */
2239 if (current_directory[0] != '\0'
2240 && argv[0] != 0
2241 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
2242 # ifdef __EMX__
2243 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
2244 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
2245 # endif
2247 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
2248 #else /* !__MSDOS__ */
2249 if (current_directory[0] != '\0'
2250 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
2251 #ifdef HAVE_DOS_PATHS
2252 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
2253 && strchr (argv[0], '\\') != 0
2254 #endif
2256 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
2257 #endif /* !__MSDOS__ */
2258 #endif /* WINDOWS32 */
2259 #endif
2261 /* We may move, but until we do, here we are. */
2262 starting_directory = current_directory;
2264 /* Set up the job_slots value and the jobserver. This can't be usefully set
2265 in the makefile, and we want to verify the authorization is valid before
2266 make has a chance to start using it for something else. */
2268 if (jobserver_auth)
2270 if (argv_slots == INVALID_JOB_SLOTS)
2272 if (jobserver_parse_auth (jobserver_auth))
2274 /* Success! Use the jobserver. */
2275 job_slots = 0;
2276 goto job_setup_complete;
2279 O (error, NILF, _("warning: jobserver unavailable: using -j1. Add '+' to parent make rule."));
2280 arg_job_slots = 1;
2283 /* The user provided a -j setting on the command line: use it. */
2284 else if (!restarts)
2285 /* If restarts is >0 we already printed this message. */
2286 O (error, NILF,
2287 _("warning: -jN forced in submake: disabling jobserver mode."));
2289 /* We failed to use our parent's jobserver. */
2290 reset_jobserver ();
2291 job_slots = (unsigned int)arg_job_slots;
2293 else if (arg_job_slots == INVALID_JOB_SLOTS)
2294 #ifdef KMK
2295 job_slots = default_job_slots; /* The default is set to CPU count early in main. */
2296 #else
2297 /* The default is one job at a time. */
2298 job_slots = 1;
2299 #endif
2300 else
2301 /* Use whatever was provided. */
2302 job_slots = (unsigned int)arg_job_slots;
2304 job_setup_complete:
2306 #if defined (WINDOWS32) && defined(CONFIG_NEW_WIN_CHILDREN)
2307 /* Initialize the windows child management. */
2308 MkWinChildInit(job_slots);
2309 #endif
2311 /* The extra indirection through $(MAKE_COMMAND) is done
2312 for hysterical raisins. */
2314 #ifdef VMS
2315 if (vms_use_mcr_command)
2316 define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
2317 else
2318 define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
2319 #else
2320 define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
2321 #endif
2322 define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
2323 #ifdef KMK
2324 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
2325 #endif
2327 if (command_variables != 0)
2329 struct command_variable *cv;
2330 struct variable *v;
2331 unsigned int len = 0;
2332 char *value, *p;
2334 /* Figure out how much space will be taken up by the command-line
2335 variable definitions. */
2336 for (cv = command_variables; cv != 0; cv = cv->next)
2338 v = cv->variable;
2339 len += 2 * strlen (v->name);
2340 if (! v->recursive)
2341 ++len;
2342 ++len;
2343 len += 2 * strlen (v->value);
2344 ++len;
2347 /* Now allocate a buffer big enough and fill it. */
2348 p = value = alloca (len);
2349 for (cv = command_variables; cv != 0; cv = cv->next)
2351 v = cv->variable;
2352 p = quote_for_env (p, v->name);
2353 if (! v->recursive)
2354 *p++ = ':';
2355 *p++ = '=';
2356 p = quote_for_env (p, v->value);
2357 *p++ = ' ';
2359 p[-1] = '\0'; /* Kill the final space and terminate. */
2361 /* Define an unchangeable variable with a name that no POSIX.2
2362 makefile could validly use for its own variable. */
2363 define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
2365 /* Define the variable; this will not override any user definition.
2366 Normally a reference to this variable is written into the value of
2367 MAKEFLAGS, allowing the user to override this value to affect the
2368 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
2369 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
2370 a reference to this hidden variable is written instead. */
2371 #ifdef KMK
2372 define_variable_cname ("KMK_OVERRIDES", "${-*-command-variables-*-}",
2373 o_env, 1);
2374 #else
2375 define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
2376 o_env, 1);
2377 #endif
2378 #ifdef VMS
2379 vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
2380 #endif
2383 /* If there were -C flags, move ourselves about. */
2384 if (directories != 0)
2386 unsigned int i;
2387 for (i = 0; directories->list[i] != 0; ++i)
2389 const char *dir = directories->list[i];
2390 #ifdef WINDOWS32
2391 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
2392 But allow -C/ just in case someone wants that. */
2394 char *p = (char *)dir + strlen (dir) - 1;
2395 while (p > dir && (p[0] == '/' || p[0] == '\\'))
2396 --p;
2397 p[1] = '\0';
2399 #endif
2400 if (chdir (dir) < 0)
2401 pfatal_with_name (dir);
2405 #ifdef KMK
2406 /* If no [Mm]akefile.kmk in the current directory, we may want to ascend to a
2407 parent directory that contains one. This is explicitly ordered by placing
2408 [Mm]akefile.kup files in the directory. And since 2024-11-04 we
2409 automatically do this when here is a goal (e.g. main.o) on the command
2410 line and no other default makefiles around. This new behvior simplifies
2411 compiling individial source files from the editor without requiring us to
2412 sprinkle Makefile.kup-files around the tree, esp. in 3rd party code.
2414 If no -C arguments were given, fake one to indicate chdir. */
2415 if (makefiles == 0)
2417 struct stat st;
2418 if (stat ("Makefile.kmk", &st) < 0
2419 && stat ("makefile.kmk", &st) < 0)
2421 static char fake_path[3*16 + 32] = "..";
2422 char *cur = &fake_path[2];
2423 int up_levels = 1;
2425 /* If there are any .kup-files. */
2426 if (( stat ("Makefile.kup", &st) == 0
2427 && S_ISREG (st.st_mode) )
2428 || ( stat ("makefile.kup", &st) == 0
2429 && S_ISREG (st.st_mode) ) )
2431 while (up_levels < 16)
2433 /* File with higher precedence. */
2434 strcpy (cur, "/Makefile.kmk");
2435 if (stat (fake_path, &st) == 0)
2436 break;
2437 cur[1] = 'm';
2438 if (stat (fake_path, &st) == 0)
2439 break;
2441 /* the .kup files */
2442 strcpy (cur, "/Makefile.kup");
2443 if ( stat (fake_path, &st) != 0
2444 || !S_ISREG (st.st_mode))
2446 cur[1] = 'm';
2447 if ( stat (fake_path, &st) != 0
2448 || !S_ISREG (st.st_mode))
2449 break;
2452 /* ok */
2453 strcpy (cur, "/..");
2454 cur += 3;
2455 up_levels++;
2457 if (up_levels >= 16)
2458 O (fatal, NILF, _("Makefile.kup recursion is too deep."));
2460 /* If there are no default makefiles either and one or more goals on
2461 the command line, go looking for kmk-files up the parent tree. */
2462 else if (goals != NULL
2463 && stat ("GNUmakefile", &st) < 0
2464 && stat ("makefile", &st) < 0
2465 && stat ("Makefile", &st) < 0
2466 #ifdef WINDOWS32
2467 && stat ("makefile.mak", &st) < 0
2468 #endif
2470 while (up_levels < 16)
2472 /* File with higher precedence.s */
2473 strcpy (cur, "/Makefile.kmk");
2474 if (stat (fake_path, &st) == 0)
2475 break;
2476 cur[1] = 'm';
2477 if (stat (fake_path, &st) == 0)
2478 break;
2480 /* ok */
2481 strcpy (cur, "/..");
2482 cur += 3;
2483 up_levels++;
2485 else
2486 up_levels = 0;
2487 if (up_levels > 0 && up_levels < 16)
2489 /* attempt to change to the directory. */
2490 *cur = '\0';
2491 if (chdir (fake_path) < 0)
2492 pfatal_with_name (fake_path);
2494 /* add the string to the directories. */
2495 if (!directories)
2497 directories = xmalloc (sizeof(*directories));
2498 directories->list = xmalloc (5 * sizeof (char *));
2499 directories->max = 5;
2500 directories->idx = 0;
2502 else if (directories->idx == directories->max - 1)
2504 directories->max += 5;
2505 directories->list = xrealloc ((void *)directories->list,
2506 directories->max * sizeof (char *));
2508 directories->list[directories->idx++] = fake_path;
2512 #endif /* KMK */
2514 #ifdef WINDOWS32
2516 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
2517 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
2519 * The functions in dir.c can incorrectly cache information for "."
2520 * before we have changed directory and this can cause file
2521 * lookups to fail because the current directory (.) was pointing
2522 * at the wrong place when it was first evaluated.
2524 #ifdef KMK /* this is really a candidate for all platforms... */
2526 extern const char *default_shell;
2527 const char *bin = get_kbuild_bin_path();
2528 char *newshell;
2529 size_t len = strlen (bin);
2530 default_shell = newshell = xmalloc (len + sizeof("/kmk_ash.exe"));
2531 memcpy (newshell, bin, len);
2532 strcpy (newshell + len, "/kmk_ash.exe");
2533 no_default_sh_exe = 0;
2534 batch_mode_shell = 1;
2535 unixy_shell = 1;
2537 #else /* !KMK */
2538 no_default_sh_exe = !find_and_set_default_shell (NULL);
2539 #endif /* !KMK */
2540 #endif /* WINDOWS32 */
2542 /* Except under -s, always do -w in sub-makes and under -C. */
2543 if (!silent_flag && (directories != 0 || makelevel > 0))
2544 print_directory_flag = 1;
2546 /* Let the user disable that with --no-print-directory. */
2547 if (inhibit_print_directory_flag)
2548 print_directory_flag = 0;
2550 /* If -R was given, set -r too (doesn't make sense otherwise!) */
2551 if (no_builtin_variables_flag)
2552 no_builtin_rules_flag = 1;
2554 /* Construct the list of include directories to search. */
2556 construct_include_path (include_directories == 0
2557 ? 0 : include_directories->list);
2559 /* If we chdir'ed, figure out where we are now. */
2560 if (directories)
2562 #ifdef WINDOWS32
2563 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
2564 #else
2565 if (getcwd (current_directory, GET_PATH_MAX) == 0)
2566 #endif
2568 #ifdef HAVE_GETCWD
2569 perror_with_name ("getcwd", "");
2570 #else
2571 OS (error, NILF, "getwd: %s", current_directory);
2572 #endif
2573 starting_directory = 0;
2575 else
2576 starting_directory = current_directory;
2579 define_variable_cname ("CURDIR", current_directory, o_file, 0);
2581 /* Read any stdin makefiles into temporary files. */
2583 if (makefiles != 0)
2585 unsigned int i;
2586 for (i = 0; i < makefiles->idx; ++i)
2587 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
2589 /* This makefile is standard input. Since we may re-exec
2590 and thus re-read the makefiles, we read standard input
2591 into a temporary file and read from that. */
2592 FILE *outfile;
2593 char *template;
2594 const char *tmpdir;
2596 if (stdin_nm)
2597 O (fatal, NILF,
2598 _("Makefile from standard input specified twice."));
2600 #ifdef VMS
2601 # define DEFAULT_TMPDIR "/sys$scratch/"
2602 #else
2603 # ifdef P_tmpdir
2604 # define DEFAULT_TMPDIR P_tmpdir
2605 # else
2606 # define DEFAULT_TMPDIR "/tmp"
2607 # endif
2608 #endif
2609 #define DEFAULT_TMPFILE "GmXXXXXX"
2611 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
2612 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2613 /* These are also used commonly on these platforms. */
2614 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
2615 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
2616 #endif
2618 tmpdir = DEFAULT_TMPDIR;
2620 template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
2621 strcpy (template, tmpdir);
2623 #ifdef HAVE_DOS_PATHS
2624 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
2625 strcat (template, "/");
2626 #else
2627 # ifndef VMS
2628 if (template[strlen (template) - 1] != '/')
2629 strcat (template, "/");
2630 # endif /* !VMS */
2631 #endif /* !HAVE_DOS_PATHS */
2633 strcat (template, DEFAULT_TMPFILE);
2634 outfile = output_tmpfile (&stdin_nm, template);
2635 if (outfile == 0)
2636 pfatal_with_name (_("fopen (temporary file)"));
2637 while (!feof (stdin) && ! ferror (stdin))
2639 char buf[2048];
2640 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
2641 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2642 pfatal_with_name (_("fwrite (temporary file)"));
2644 fclose (outfile);
2646 /* Replace the name that read_all_makefiles will
2647 see with the name of the temporary file. */
2648 makefiles->list[i] = strcache_add (stdin_nm);
2650 /* Make sure the temporary file will not be remade. */
2652 struct file *f = enter_file (strcache_add (stdin_nm));
2653 f->updated = 1;
2654 f->update_status = us_success;
2655 f->command_state = cs_finished;
2656 /* Can't be intermediate, or it'll be removed too early for
2657 make re-exec. */
2658 f->intermediate = 0;
2659 f->dontcare = 0;
2664 #if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
2665 #if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
2666 /* Set up to handle children dying. This must be done before
2667 reading in the makefiles so that 'shell' function calls will work.
2669 If we don't have a hanging wait we have to fall back to old, broken
2670 functionality here and rely on the signal handler and counting
2671 children.
2673 If we're using the jobs pipe we need a signal handler so that SIGCHLD is
2674 not ignored; we need it to interrupt the read(2) of the jobserver pipe if
2675 we're waiting for a token.
2677 If none of these are true, we don't need a signal handler at all. */
2679 # if defined SIGCHLD
2680 bsd_signal (SIGCHLD, child_handler);
2681 # endif
2682 # if defined SIGCLD && SIGCLD != SIGCHLD
2683 bsd_signal (SIGCLD, child_handler);
2684 # endif
2687 #ifdef HAVE_PSELECT
2688 /* If we have pselect() then we need to block SIGCHLD so it's deferred. */
2690 sigset_t block;
2691 sigemptyset (&block);
2692 sigaddset (&block, SIGCHLD);
2693 if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
2694 pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
2696 #endif
2698 #endif
2699 #endif
2701 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2702 #ifdef SIGUSR1
2703 bsd_signal (SIGUSR1, debug_signal_handler);
2704 #endif
2706 /* Define the initial list of suffixes for old-style rules. */
2707 set_default_suffixes ();
2709 /* Define the file rules for the built-in suffix rules. These will later
2710 be converted into pattern rules. We used to do this in
2711 install_default_implicit_rules, but since that happens after reading
2712 makefiles, it results in the built-in pattern rules taking precedence
2713 over makefile-specified suffix rules, which is wrong. */
2714 install_default_suffix_rules ();
2716 /* Define some internal and special variables. */
2717 define_automatic_variables ();
2719 /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
2720 Initialize it to be exported but allow the makefile to reset it. */
2721 define_makeflags (0, 0)->export = v_export;
2723 /* Define the default variables. */
2724 define_default_variables ();
2726 default_file = enter_file (strcache_add (".DEFAULT"));
2728 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
2730 /* Evaluate all strings provided with --eval.
2731 Also set up the $(-*-eval-flags-*-) variable. */
2733 if (eval_strings)
2735 char *p, *value;
2736 unsigned int i;
2737 unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
2739 for (i = 0; i < eval_strings->idx; ++i)
2741 #ifndef CONFIG_WITH_VALUE_LENGTH
2742 p = xstrdup (eval_strings->list[i]);
2743 len += 2 * strlen (p);
2744 eval_buffer (p, NULL);
2745 #else
2746 unsigned int sub_len = strlen(eval_strings->list[i]);
2747 p = xstrndup (eval_strings->list[i], sub_len);
2748 len += 2 * sub_len;
2749 eval_buffer (p, NULL, p + sub_len);
2750 #endif
2751 free (p);
2754 p = value = alloca (len);
2755 for (i = 0; i < eval_strings->idx; ++i)
2757 strcpy (p, "--eval=");
2758 p += CSTRLEN ("--eval=");
2759 p = quote_for_env (p, eval_strings->list[i]);
2760 *(p++) = ' ';
2762 p[-1] = '\0';
2764 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
2767 /* Read all the makefiles. */
2769 read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2771 #ifdef WINDOWS32
2772 /* look one last time after reading all Makefiles */
2773 if (no_default_sh_exe)
2774 no_default_sh_exe = !find_and_set_default_shell (NULL);
2775 #endif /* WINDOWS32 */
2777 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2778 /* We need to know what kind of shell we will be using. */
2780 extern int _is_unixy_shell (const char *_path);
2781 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2782 extern int unixy_shell;
2783 extern const char *default_shell;
2785 if (shv && *shv->value)
2787 char *shell_path = recursively_expand (shv);
2789 if (shell_path && _is_unixy_shell (shell_path))
2790 unixy_shell = 1;
2791 else
2792 unixy_shell = 0;
2793 if (shell_path)
2794 default_shell = shell_path;
2797 #endif /* __MSDOS__ || __EMX__ */
2800 int old_builtin_rules_flag = no_builtin_rules_flag;
2801 int old_builtin_variables_flag = no_builtin_variables_flag;
2803 /* Decode switches again, for variables set by the makefile. */
2804 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
2806 /* Clear GNUMAKEFLAGS to avoid duplication. */
2807 define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
2809 #ifdef KMK
2810 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2811 #else /* !KMK */
2812 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2813 #if 0
2814 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2815 #endif
2816 #endif /* !KMK */
2818 /* Reset in case the switches changed our mind. */
2819 syncing = (output_sync == OUTPUT_SYNC_LINE
2820 || output_sync == OUTPUT_SYNC_TARGET);
2822 if (make_sync.syncout && ! syncing)
2823 output_close (&make_sync);
2825 make_sync.syncout = syncing;
2826 OUTPUT_SET (&make_sync);
2828 /* If we've disabled builtin rules, get rid of them. */
2829 if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2831 if (suffix_file->builtin)
2833 free_dep_chain (suffix_file->deps);
2834 suffix_file->deps = 0;
2836 define_variable_cname ("SUFFIXES", "", o_default, 0);
2839 /* If we've disabled builtin variables, get rid of them. */
2840 if (no_builtin_variables_flag && ! old_builtin_variables_flag)
2841 undefine_default_variables ();
2844 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2845 if (arg_job_slots != 1
2846 # ifdef __EMX__
2847 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2848 # endif
2851 O (error, NILF,
2852 _("Parallel jobs (-j) are not supported on this platform."));
2853 O (error, NILF, _("Resetting to single job (-j1) mode."));
2854 arg_job_slots = job_slots = 1;
2856 #endif
2858 /* If we have >1 slot at this point, then we're a top-level make.
2859 Set up the jobserver.
2861 Every make assumes that it always has one job it can run. For the
2862 submakes it's the token they were given by their parent. For the top
2863 make, we just subtract one from the number the user wants. */
2865 if (job_slots > 1 && jobserver_setup (job_slots - 1))
2867 /* Fill in the jobserver_auth for our children. */
2868 jobserver_auth = jobserver_get_auth ();
2870 if (jobserver_auth)
2872 /* We're using the jobserver so set job_slots to 0. */
2873 master_job_slots = job_slots;
2874 job_slots = 0;
2878 /* If we're not using parallel jobs, then we don't need output sync.
2879 This is so people can enable output sync in GNUMAKEFLAGS or similar, but
2880 not have it take effect unless parallel builds are enabled. */
2881 if (syncing && job_slots == 1)
2883 OUTPUT_UNSET ();
2884 output_close (&make_sync);
2885 syncing = 0;
2886 output_sync = OUTPUT_SYNC_NONE;
2889 #ifndef MAKE_SYMLINKS
2890 if (check_symlink_flag)
2892 O (error, NILF, _("Symbolic links not supported: disabling -L."));
2893 check_symlink_flag = 0;
2895 #endif
2897 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2899 define_makeflags (1, 0);
2901 /* Make each 'struct goaldep' point at the 'struct file' for the file
2902 depended on. Also do magic for special targets. */
2904 snap_deps ();
2906 /* Convert old-style suffix rules to pattern rules. It is important to
2907 do this before installing the built-in pattern rules below, so that
2908 makefile-specified suffix rules take precedence over built-in pattern
2909 rules. */
2911 convert_to_pattern ();
2913 /* Install the default implicit pattern rules.
2914 This used to be done before reading the makefiles.
2915 But in that case, built-in pattern rules were in the chain
2916 before user-defined ones, so they matched first. */
2918 install_default_implicit_rules ();
2920 /* Compute implicit rule limits. */
2922 count_implicit_rule_limits ();
2924 /* Construct the listings of directories in VPATH lists. */
2926 build_vpath_lists ();
2928 /* Mark files given with -o flags as very old and as having been updated
2929 already, and files given with -W flags as brand new (time-stamp as far
2930 as possible into the future). If restarts is set we'll do -W later. */
2932 if (old_files != 0)
2934 const char **p;
2935 for (p = old_files->list; *p != 0; ++p)
2937 struct file *f = enter_file (*p);
2938 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2939 f->updated = 1;
2940 f->update_status = us_success;
2941 f->command_state = cs_finished;
2945 if (!restarts && new_files != 0)
2947 const char **p;
2948 for (p = new_files->list; *p != 0; ++p)
2950 struct file *f = enter_file (*p);
2951 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2955 /* Initialize the remote job module. */
2956 remote_setup ();
2958 /* Dump any output we've collected. */
2960 OUTPUT_UNSET ();
2961 output_close (&make_sync);
2963 if (read_files != 0)
2965 /* Update any makefiles if necessary. */
2967 FILE_TIMESTAMP *makefile_mtimes = 0;
2968 unsigned int mm_idx = 0;
2969 char **aargv = NULL;
2970 const char **nargv;
2971 int nargc;
2972 enum update_status status;
2974 DB (DB_BASIC, (_("Updating makefiles....\n")));
2976 /* Remove any makefiles we don't want to try to update.
2977 Also record the current modtimes so we can compare them later. */
2979 register struct goaldep *d, *last;
2980 last = 0;
2981 d = read_files;
2982 while (d != 0)
2984 struct file *f = d->file;
2985 if (f->double_colon)
2986 for (f = f->double_colon; f != NULL; f = f->prev)
2988 if (f->deps == 0 && f->cmds != 0)
2990 /* This makefile is a :: target with commands, but
2991 no dependencies. So, it will always be remade.
2992 This might well cause an infinite loop, so don't
2993 try to remake it. (This will only happen if
2994 your makefiles are written exceptionally
2995 stupidly; but if you work for Athena, that's how
2996 you write your makefiles.) */
2998 DB (DB_VERBOSE,
2999 (_("Makefile '%s' might loop; not remaking it.\n"),
3000 f->name));
3002 if (last == 0)
3003 read_files = d->next;
3004 else
3005 last->next = d->next;
3007 /* Free the storage. */
3008 free_goaldep (d);
3010 d = last == 0 ? read_files : last->next;
3012 break;
3016 if (f == NULL || !f->double_colon)
3018 makefile_mtimes = xrealloc (makefile_mtimes,
3019 (mm_idx+1)
3020 * sizeof (FILE_TIMESTAMP));
3021 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
3022 last = d;
3023 d = d->next;
3028 /* Set up 'MAKEFLAGS' specially while remaking makefiles. */
3029 define_makeflags (1, 1);
3032 int orig_db_level = db_level;
3034 if (! ISDB (DB_MAKEFILES))
3035 db_level = DB_NONE;
3037 rebuilding_makefiles = 1;
3038 status = update_goal_chain (read_files);
3039 rebuilding_makefiles = 0;
3041 db_level = orig_db_level;
3044 switch (status)
3046 case us_question:
3047 /* The only way this can happen is if the user specified -q and asked
3048 for one of the makefiles to be remade as a target on the command
3049 line. Since we're not actually updating anything with -q we can
3050 treat this as "did nothing". */
3052 case us_none:
3053 /* Did nothing. */
3054 break;
3056 case us_failed:
3057 /* Failed to update. Figure out if we care. */
3059 /* Nonzero if any makefile was successfully remade. */
3060 int any_remade = 0;
3061 /* Nonzero if any makefile we care about failed
3062 in updating or could not be found at all. */
3063 int any_failed = 0;
3064 unsigned int i;
3065 struct goaldep *d;
3067 for (i = 0, d = read_files; d != 0; ++i, d = d->next)
3069 if (d->file->updated)
3071 /* This makefile was updated. */
3072 if (d->file->update_status == us_success)
3074 /* It was successfully updated. */
3075 any_remade |= (file_mtime_no_search (d->file)
3076 != makefile_mtimes[i]);
3078 else if (! (d->flags & RM_DONTCARE))
3080 FILE_TIMESTAMP mtime;
3081 /* The update failed and this makefile was not
3082 from the MAKEFILES variable, so we care. */
3083 OS (error, NILF, _("Failed to remake makefile '%s'."),
3084 d->file->name);
3085 mtime = file_mtime_no_search (d->file);
3086 any_remade |= (mtime != NONEXISTENT_MTIME
3087 && mtime != makefile_mtimes[i]);
3088 makefile_status = MAKE_FAILURE;
3091 else
3092 /* This makefile was not found at all. */
3093 if (! (d->flags & RM_DONTCARE))
3095 const char *dnm = dep_name (d);
3096 size_t l = strlen (dnm);
3098 /* This is a makefile we care about. See how much. */
3099 if (d->flags & RM_INCLUDED)
3100 /* An included makefile. We don't need to die, but we
3101 do want to complain. */
3102 error (NILF, l,
3103 _("Included makefile '%s' was not found."), dnm);
3104 else
3106 /* A normal makefile. We must die later. */
3107 error (NILF, l,
3108 _("Makefile '%s' was not found"), dnm);
3109 any_failed = 1;
3113 /* Reset this to empty so we get the right error message below. */
3114 read_files = 0;
3116 if (any_remade)
3117 goto re_exec;
3118 if (any_failed)
3119 die (MAKE_FAILURE);
3120 break;
3123 case us_success:
3124 re_exec:
3125 /* Updated successfully. Re-exec ourselves. */
3127 remove_intermediates (0);
3129 if (print_data_base_flag)
3130 print_data_base ();
3132 clean_jobserver (0);
3134 if (makefiles != 0)
3136 /* These names might have changed. */
3137 int i, j = 0;
3138 for (i = 1; i < argc; ++i)
3139 if (strneq (argv[i], "-f", 2)) /* XXX */
3141 if (argv[i][2] == '\0')
3142 /* This cast is OK since we never modify argv. */
3143 argv[++i] = (char *) makefiles->list[j];
3144 else
3145 argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
3146 ++j;
3150 /* Add -o option for the stdin temporary file, if necessary. */
3151 nargc = argc;
3152 if (stdin_nm)
3154 void *m = xmalloc ((nargc + 2) * sizeof (char *));
3155 aargv = m;
3156 memcpy (aargv, argv, argc * sizeof (char *));
3157 aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
3158 aargv[nargc] = 0;
3159 nargv = m;
3161 else
3162 nargv = (const char**)argv;
3164 if (directories != 0 && directories->idx > 0)
3166 int bad = 1;
3167 if (directory_before_chdir != 0)
3169 if (chdir (directory_before_chdir) < 0)
3170 perror_with_name ("chdir", "");
3171 else
3172 bad = 0;
3174 if (bad)
3175 O (fatal, NILF,
3176 _("Couldn't change back to original directory."));
3179 ++restarts;
3181 if (ISDB (DB_BASIC))
3183 const char **p;
3184 printf (_("Re-executing[%u]:"), restarts);
3185 for (p = nargv; *p != 0; ++p)
3186 printf (" %s", *p);
3187 putchar ('\n');
3188 fflush (stdout);
3191 #ifndef _AMIGA
3193 char **p;
3194 for (p = environ; *p != 0; ++p)
3196 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
3198 *p = alloca (40);
3199 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
3200 #ifdef VMS
3201 vms_putenv_symbol (*p);
3202 #endif
3204 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
3206 *p = alloca (40);
3207 sprintf (*p, "MAKE_RESTARTS=%s%u",
3208 OUTPUT_IS_TRACED () ? "-" : "", restarts);
3209 restarts = 0;
3213 #else /* AMIGA */
3215 char buffer[256];
3217 sprintf (buffer, "%u", makelevel);
3218 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
3220 sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
3221 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
3222 restarts = 0;
3224 #endif
3226 /* If we didn't set the restarts variable yet, add it. */
3227 if (restarts)
3229 char *b = alloca (40);
3230 sprintf (b, "MAKE_RESTARTS=%s%u",
3231 OUTPUT_IS_TRACED () ? "-" : "", restarts);
3232 putenv (b);
3235 fflush (stdout);
3236 fflush (stderr);
3238 #ifdef _AMIGA
3239 exec_command (nargv);
3240 exit (0);
3241 #elif defined (__EMX__)
3243 /* It is not possible to use execve() here because this
3244 would cause the parent process to be terminated with
3245 exit code 0 before the child process has been terminated.
3246 Therefore it may be the best solution simply to spawn the
3247 child process including all file handles and to wait for its
3248 termination. */
3249 int pid;
3250 int r;
3251 pid = child_execute_job (NULL, 1, nargv, environ);
3253 /* is this loop really necessary? */
3254 do {
3255 pid = wait (&r);
3256 } while (pid <= 0);
3257 /* use the exit code of the child process */
3258 exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
3260 #else
3261 #ifdef SET_STACK_SIZE
3262 /* Reset limits, if necessary. */
3263 if (stack_limit.rlim_cur)
3264 setrlimit (RLIMIT_STACK, &stack_limit);
3265 #endif
3266 # if !defined(WINDOWS32) || !defined(CONFIG_NEW_WIN_CHILDREN)
3267 exec_command ((char **)nargv, environ);
3268 # else
3269 MkWinChildReExecMake ((char **)nargv, environ);
3270 # endif
3271 #endif
3272 free (aargv);
3273 break;
3276 /* Free the makefile mtimes. */
3277 free (makefile_mtimes);
3280 /* Set up 'MAKEFLAGS' again for the normal targets. */
3281 define_makeflags (1, 0);
3283 /* Set always_make_flag if -B was given. */
3284 always_make_flag = always_make_set;
3286 /* If restarts is set we haven't set up -W files yet, so do that now. */
3287 if (restarts && new_files != 0)
3289 const char **p;
3290 for (p = new_files->list; *p != 0; ++p)
3292 struct file *f = enter_file (*p);
3293 f->last_mtime = f->mtime_before_update = NEW_MTIME;
3297 /* If there is a temp file from reading a makefile from stdin, get rid of
3298 it now. */
3299 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
3300 perror_with_name (_("unlink (temporary file): "), stdin_nm);
3302 /* If there were no command-line goals, use the default. */
3303 if (goals == 0)
3305 char *p;
3307 if (default_goal_var->recursive)
3308 p = variable_expand (default_goal_var->value);
3309 else
3311 p = variable_buffer_output (variable_buffer, default_goal_var->value,
3312 strlen (default_goal_var->value));
3313 *p = '\0';
3314 p = variable_buffer;
3317 if (*p != '\0')
3319 struct file *f = lookup_file (p);
3321 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
3322 table and let the standard logic sort it out. */
3323 if (f == 0)
3325 struct nameseq *ns;
3327 ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
3328 if (ns)
3330 /* .DEFAULT_GOAL should contain one target. */
3331 if (ns->next != 0)
3332 O (fatal, NILF,
3333 _(".DEFAULT_GOAL contains more than one target"));
3335 #ifndef CONFIG_WITH_VALUE_LENGTH
3336 f = enter_file (strcache_add (ns->name));
3337 #else
3338 f = enter_file (ns->name);
3339 #endif
3341 ns->name = 0; /* It was reused by enter_file(). */
3342 free_ns_chain (ns);
3346 if (f)
3348 goals = alloc_goaldep ();
3349 goals->file = f;
3353 else
3354 lastgoal->next = 0;
3357 if (!goals)
3359 if (read_files == 0)
3360 O (fatal, NILF, _("No targets specified and no makefile found"));
3362 O (fatal, NILF, _("No targets"));
3365 /* Update the goals. */
3367 DB (DB_BASIC, (_("Updating goal targets....\n")));
3370 switch (update_goal_chain (goals))
3372 case us_none:
3373 /* Nothing happened. */
3374 /* FALLTHROUGH */
3375 case us_success:
3376 /* Keep the previous result. */
3377 break;
3378 case us_question:
3379 /* We are under -q and would run some commands. */
3380 makefile_status = MAKE_TROUBLE;
3381 break;
3382 case us_failed:
3383 /* Updating failed. POSIX.2 specifies exit status >1 for this; */
3384 makefile_status = MAKE_FAILURE;
3385 break;
3388 /* If we detected some clock skew, generate one last warning */
3389 if (clock_skew_detected)
3390 O (error, NILF,
3391 _("warning: Clock skew detected. Your build may be incomplete."));
3393 MAKE_STATS_2(if (uStartTick) printf("main ticks elapsed: %llu\n", (unsigned long long)(CURRENT_CLOCK_TICK() - uStartTick)) );
3394 /* Exit. */
3395 die (makefile_status);
3398 /* NOTREACHED */
3399 exit (MAKE_SUCCESS);
3402 /* Parsing of arguments, decoding of switches. */
3404 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
3405 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
3406 (sizeof (long_option_aliases) /
3407 sizeof (long_option_aliases[0]))];
3409 /* Fill in the string and vector for getopt. */
3410 static void
3411 init_switches (void)
3413 char *p;
3414 unsigned int c;
3415 unsigned int i;
3417 if (options[0] != '\0')
3418 /* Already done. */
3419 return;
3421 p = options;
3423 /* Return switch and non-switch args in order, regardless of
3424 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
3425 *p++ = '-';
3427 for (i = 0; switches[i].c != '\0'; ++i)
3429 long_options[i].name = (switches[i].long_name == 0 ? "" :
3430 switches[i].long_name);
3431 long_options[i].flag = 0;
3432 long_options[i].val = switches[i].c;
3433 if (short_option (switches[i].c))
3434 *p++ = switches[i].c;
3435 switch (switches[i].type)
3437 case flag:
3438 case flag_off:
3439 case ignore:
3440 long_options[i].has_arg = no_argument;
3441 break;
3443 case string:
3444 case strlist:
3445 case filename:
3446 case positive_int:
3447 case floating:
3448 if (short_option (switches[i].c))
3449 *p++ = ':';
3450 if (switches[i].noarg_value != 0)
3452 if (short_option (switches[i].c))
3453 *p++ = ':';
3454 long_options[i].has_arg = optional_argument;
3456 else
3457 long_options[i].has_arg = required_argument;
3458 break;
3461 *p = '\0';
3462 for (c = 0; c < (sizeof (long_option_aliases) /
3463 sizeof (long_option_aliases[0]));
3464 ++c)
3465 long_options[i++] = long_option_aliases[c];
3466 long_options[i].name = 0;
3470 /* Non-option argument. It might be a variable definition. */
3471 static void
3472 handle_non_switch_argument (const char *arg, int env)
3474 struct variable *v;
3476 if (arg[0] == '-' && arg[1] == '\0')
3477 /* Ignore plain '-' for compatibility. */
3478 return;
3480 #ifdef VMS
3482 /* VMS DCL quoting can result in foo="bar baz" showing up here.
3483 Need to remove the double quotes from the value. */
3484 char * eq_ptr;
3485 char * new_arg;
3486 eq_ptr = strchr (arg, '=');
3487 if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
3489 int len;
3490 int seg1;
3491 int seg2;
3492 len = strlen(arg);
3493 new_arg = alloca(len);
3494 seg1 = eq_ptr - arg + 1;
3495 strncpy(new_arg, arg, (seg1));
3496 seg2 = len - seg1 - 1;
3497 strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
3498 new_arg[seg1 + seg2] = 0;
3499 if (new_arg[seg1 + seg2 - 1] == '"')
3500 new_arg[seg1 + seg2 - 1] = 0;
3501 arg = new_arg;
3504 #endif
3505 v = try_variable_definition (0, arg IF_WITH_VALUE_LENGTH_PARAM(NULL), o_command, 0);
3506 if (v != 0)
3508 /* It is indeed a variable definition. If we don't already have this
3509 one, record a pointer to the variable for later use in
3510 define_makeflags. */
3511 struct command_variable *cv;
3513 for (cv = command_variables; cv != 0; cv = cv->next)
3514 if (cv->variable == v)
3515 break;
3517 if (! cv)
3519 cv = xmalloc (sizeof (*cv));
3520 cv->variable = v;
3521 cv->next = command_variables;
3522 command_variables = cv;
3525 else if (! env)
3527 /* Not an option or variable definition; it must be a goal
3528 target! Enter it as a file and add it to the dep chain of
3529 goals. */
3530 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
3531 f->cmd_target = 1;
3533 if (goals == 0)
3535 goals = alloc_goaldep ();
3536 lastgoal = goals;
3538 else
3540 lastgoal->next = alloc_goaldep ();
3541 lastgoal = lastgoal->next;
3544 lastgoal->file = f;
3547 /* Add this target name to the MAKECMDGOALS variable. */
3548 struct variable *gv;
3549 const char *value;
3551 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
3552 if (gv == 0)
3553 value = f->name;
3554 else
3556 /* Paste the old and new values together */
3557 unsigned int oldlen, newlen;
3558 char *vp;
3560 oldlen = strlen (gv->value);
3561 newlen = strlen (f->name);
3562 vp = alloca (oldlen + 1 + newlen + 1);
3563 memcpy (vp, gv->value, oldlen);
3564 vp[oldlen] = ' ';
3565 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
3566 value = vp;
3568 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
3573 /* Print a nice usage method. */
3575 static void
3576 print_usage (int bad)
3578 const char *const *cpp;
3579 FILE *usageto;
3581 if (print_version_flag)
3582 print_version ();
3584 usageto = bad ? stderr : stdout;
3586 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
3588 for (cpp = usage; *cpp; ++cpp)
3589 fputs (_(*cpp), usageto);
3591 #ifdef KMK
3592 if (!remote_description || *remote_description == '\0')
3593 fprintf (usageto, _("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3594 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3595 else
3596 fprintf (usageto, _("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3597 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3598 #else /* !KMK */
3599 if (!remote_description || *remote_description == '\0')
3600 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
3601 else
3602 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
3603 make_host, remote_description);
3604 #endif /* !KMK */
3606 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
3609 /* Decode switches from ARGC and ARGV.
3610 They came from the environment if ENV is nonzero. */
3612 static void
3613 decode_switches (int argc, const char **argv, int env)
3615 int bad = 0;
3616 register const struct command_switch *cs;
3617 register struct stringlist *sl;
3618 register int c;
3620 /* getopt does most of the parsing for us.
3621 First, get its vectors set up. */
3623 init_switches ();
3625 /* Let getopt produce error messages for the command line,
3626 but not for options from the environment. */
3627 opterr = !env;
3628 /* Reset getopt's state. */
3629 optind = 0;
3631 while (optind < argc)
3633 const char *coptarg;
3635 /* Parse the next argument. */
3636 c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
3637 coptarg = optarg;
3638 if (c == EOF)
3639 /* End of arguments, or "--" marker seen. */
3640 break;
3641 else if (c == 1)
3642 /* An argument not starting with a dash. */
3643 handle_non_switch_argument (coptarg, env);
3644 else if (c == '?')
3645 /* Bad option. We will print a usage message and die later.
3646 But continue to parse the other options so the user can
3647 see all he did wrong. */
3648 bad = 1;
3649 else
3650 for (cs = switches; cs->c != '\0'; ++cs)
3651 if (cs->c == c)
3653 /* Whether or not we will actually do anything with
3654 this switch. We test this individually inside the
3655 switch below rather than just once outside it, so that
3656 options which are to be ignored still consume args. */
3657 int doit = !env || cs->env;
3659 switch (cs->type)
3661 default:
3662 abort ();
3664 case ignore:
3665 break;
3667 case flag:
3668 case flag_off:
3669 if (doit)
3670 *(int *) cs->value_ptr = cs->type == flag;
3671 break;
3673 case string:
3674 case strlist:
3675 case filename:
3676 if (!doit)
3677 break;
3679 if (! coptarg)
3680 coptarg = xstrdup (cs->noarg_value);
3681 else if (*coptarg == '\0')
3683 char opt[2] = "c";
3684 const char *op = opt;
3686 if (short_option (cs->c))
3687 opt[0] = cs->c;
3688 else
3689 op = cs->long_name;
3691 error (NILF, strlen (op),
3692 _("the '%s%s' option requires a non-empty string argument"),
3693 short_option (cs->c) ? "-" : "--", op);
3694 bad = 1;
3695 break;
3698 if (cs->type == string)
3700 char **val = (char **)cs->value_ptr;
3701 free (*val);
3702 *val = xstrdup (coptarg);
3703 break;
3706 sl = *(struct stringlist **) cs->value_ptr;
3707 if (sl == 0)
3709 sl = xmalloc (sizeof (struct stringlist));
3710 sl->max = 5;
3711 sl->idx = 0;
3712 sl->list = xmalloc (5 * sizeof (char *));
3713 *(struct stringlist **) cs->value_ptr = sl;
3715 else if (sl->idx == sl->max - 1)
3717 sl->max += 5;
3718 /* MSVC erroneously warns without a cast here. */
3719 sl->list = xrealloc ((void *)sl->list,
3720 sl->max * sizeof (char *));
3722 if (cs->type == filename)
3723 sl->list[sl->idx++] = expand_command_line_file (coptarg);
3724 else
3725 sl->list[sl->idx++] = xstrdup (coptarg);
3726 sl->list[sl->idx] = 0;
3727 break;
3729 case positive_int:
3730 /* See if we have an option argument; if we do require that
3731 it's all digits, not something like "10foo". */
3732 if (coptarg == 0 && argc > optind)
3734 const char *cp;
3735 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3737 if (cp[0] == '\0')
3738 coptarg = argv[optind++];
3741 if (!doit)
3742 break;
3744 if (coptarg)
3746 int i = atoi (coptarg);
3747 const char *cp;
3749 /* Yes, I realize we're repeating this in some cases. */
3750 for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
3753 if (i < 1 || cp[0] != '\0')
3755 error (NILF, 0,
3756 _("the '-%c' option requires a positive integer argument"),
3757 cs->c);
3758 bad = 1;
3760 else
3761 *(unsigned int *) cs->value_ptr = i;
3763 else
3764 *(unsigned int *) cs->value_ptr
3765 = *(unsigned int *) cs->noarg_value;
3766 break;
3768 #ifndef NO_FLOAT
3769 case floating:
3770 if (coptarg == 0 && optind < argc
3771 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3772 coptarg = argv[optind++];
3774 if (doit)
3775 *(double *) cs->value_ptr
3776 = (coptarg != 0 ? atof (coptarg)
3777 : *(double *) cs->noarg_value);
3779 break;
3780 #endif
3783 /* We've found the switch. Stop looking. */
3784 break;
3788 /* There are no more options according to getting getopt, but there may
3789 be some arguments left. Since we have asked for non-option arguments
3790 to be returned in order, this only happens when there is a "--"
3791 argument to prevent later arguments from being options. */
3792 while (optind < argc)
3793 handle_non_switch_argument (argv[optind++], env);
3795 if (!env && (bad || print_usage_flag))
3797 print_usage (bad);
3798 die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
3801 /* If there are any options that need to be decoded do it now. */
3802 decode_debug_flags ();
3803 decode_output_sync_flags ();
3805 #if defined (WINDOWS32) && defined (CONFIG_NEW_WIN_CHILDREN)
3806 /* validate the job object mode value . */
3807 if (win_job_object_mode == NULL)
3808 win_job_object_mode = xstrdup ("login");
3809 else if ( strcmp (win_job_object_mode, "none") != 0
3810 && strcmp (win_job_object_mode, "login") != 0
3811 && strcmp (win_job_object_mode, "root") != 0
3812 && strcmp (win_job_object_mode, "each") != 0)
3813 OS (fatal, NILF, _("unknown job object mode '%s'"), win_job_object_mode);
3814 #endif
3817 /* Decode switches from environment variable ENVAR (which is LEN chars long).
3818 We do this by chopping the value into a vector of words, prepending a
3819 dash to the first word if it lacks one, and passing the vector to
3820 decode_switches. */
3822 static void
3823 decode_env_switches (const char *envar, unsigned int len)
3825 char *varref = alloca (2 + len + 2);
3826 char *value, *p, *buf;
3827 int argc;
3828 const char **argv;
3830 /* Get the variable's value. */
3831 varref[0] = '$';
3832 varref[1] = '(';
3833 memcpy (&varref[2], envar, len);
3834 varref[2 + len] = ')';
3835 varref[2 + len + 1] = '\0';
3836 value = variable_expand (varref);
3838 /* Skip whitespace, and check for an empty value. */
3839 NEXT_TOKEN (value);
3840 len = strlen (value);
3841 if (len == 0)
3842 return;
3844 /* Allocate a vector that is definitely big enough. */
3845 argv = alloca ((1 + len + 1) * sizeof (char *));
3847 /* getopt will look at the arguments starting at ARGV[1].
3848 Prepend a spacer word. */
3849 argv[0] = 0;
3850 argc = 1;
3852 /* We need a buffer to copy the value into while we split it into words
3853 and unquote it. Set up in case we need to prepend a dash later. */
3854 buf = alloca (1 + len + 1);
3855 buf[0] = '-';
3856 p = buf+1;
3857 argv[argc] = p;
3858 while (*value != '\0')
3860 if (*value == '\\' && value[1] != '\0')
3861 ++value; /* Skip the backslash. */
3862 else if (ISBLANK (*value))
3864 /* End of the word. */
3865 *p++ = '\0';
3866 argv[++argc] = p;
3868 ++value;
3869 while (ISBLANK (*value));
3870 continue;
3872 *p++ = *value++;
3874 *p = '\0';
3875 argv[++argc] = 0;
3876 assert (p < buf + len + 2);
3878 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3879 /* The first word doesn't start with a dash and isn't a variable
3880 definition, so add a dash. */
3881 argv[1] = buf;
3883 /* Parse those words. */
3884 decode_switches (argc, argv, 1);
3887 /* Quote the string IN so that it will be interpreted as a single word with
3888 no magic by decode_env_switches; also double dollar signs to avoid
3889 variable expansion in make itself. Write the result into OUT, returning
3890 the address of the next character to be written.
3891 Allocating space for OUT twice the length of IN is always sufficient. */
3893 static char *
3894 quote_for_env (char *out, const char *in)
3896 while (*in != '\0')
3898 if (*in == '$')
3899 *out++ = '$';
3900 else if (ISBLANK (*in) || *in == '\\')
3901 *out++ = '\\';
3902 *out++ = *in++;
3905 return out;
3908 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3909 command switches. Include options with args if ALL is nonzero.
3910 Don't include options with the 'no_makefile' flag set if MAKEFILE. */
3912 static struct variable *
3913 define_makeflags (int all, int makefile)
3915 #ifdef KMK
3916 static const char ref[] = "$(KMK_OVERRIDES)";
3917 #else
3918 static /*<- bird*/ const char ref[] = "$(MAKEOVERRIDES)";
3919 #endif
3920 static /*<- bird*/ const char posixref[] = "$(-*-command-variables-*-)";
3921 static /*<- bird*/ const char evalref[] = "$(-*-eval-flags-*-)";
3922 const struct command_switch *cs;
3923 char *flagstring;
3924 char *p;
3926 /* We will construct a linked list of 'struct flag's describing
3927 all the flags which need to go in MAKEFLAGS. Then, once we
3928 know how many there are and their lengths, we can put them all
3929 together in a string. */
3931 struct flag
3933 struct flag *next;
3934 const struct command_switch *cs;
3935 const char *arg;
3937 struct flag *flags = 0;
3938 struct flag *last = 0;
3939 unsigned int flagslen = 0;
3940 #define ADD_FLAG(ARG, LEN) \
3941 do { \
3942 struct flag *new = alloca (sizeof (struct flag)); \
3943 new->cs = cs; \
3944 new->arg = (ARG); \
3945 new->next = 0; \
3946 if (! flags) \
3947 flags = new; \
3948 else \
3949 last->next = new; \
3950 last = new; \
3951 if (new->arg == 0) \
3952 /* Just a single flag letter: " -x" */ \
3953 flagslen += 3; \
3954 else \
3955 /* " -xfoo", plus space to escape "foo". */ \
3956 flagslen += 1 + 1 + 1 + (3 * (LEN)); \
3957 if (!short_option (cs->c)) \
3958 /* This switch has no single-letter version, so we use the long. */ \
3959 flagslen += 2 + strlen (cs->long_name); \
3960 } while (0)
3962 for (cs = switches; cs->c != '\0'; ++cs)
3963 if (cs->toenv && (!makefile || !cs->no_makefile))
3964 switch (cs->type)
3966 case ignore:
3967 break;
3969 case flag:
3970 case flag_off:
3971 if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3972 && (cs->default_value == 0
3973 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3974 ADD_FLAG (0, 0);
3975 break;
3977 case positive_int:
3978 if (all)
3980 if ((cs->default_value != 0
3981 && (*(unsigned int *) cs->value_ptr
3982 == *(unsigned int *) cs->default_value)))
3983 break;
3984 else if (cs->noarg_value != 0
3985 && (*(unsigned int *) cs->value_ptr ==
3986 *(unsigned int *) cs->noarg_value))
3987 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3988 else
3990 char *buf = alloca (30);
3991 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3992 ADD_FLAG (buf, strlen (buf));
3995 break;
3997 #ifndef NO_FLOAT
3998 case floating:
3999 if (all)
4001 if (cs->default_value != 0
4002 && (*(double *) cs->value_ptr
4003 == *(double *) cs->default_value))
4004 break;
4005 else if (cs->noarg_value != 0
4006 && (*(double *) cs->value_ptr
4007 == *(double *) cs->noarg_value))
4008 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
4009 else
4011 char *buf = alloca (100);
4012 sprintf (buf, "%g", *(double *) cs->value_ptr);
4013 ADD_FLAG (buf, strlen (buf));
4016 break;
4017 #endif
4019 case string:
4020 if (all)
4022 p = *((char **)cs->value_ptr);
4023 if (p)
4024 ADD_FLAG (p, strlen (p));
4026 break;
4028 case filename:
4029 case strlist:
4030 if (all)
4032 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
4033 if (sl != 0)
4035 unsigned int i;
4036 for (i = 0; i < sl->idx; ++i)
4037 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
4040 break;
4042 default:
4043 abort ();
4046 #undef ADD_FLAG
4048 /* Four more for the possible " -- ", plus variable references. */
4049 flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
4051 /* Construct the value in FLAGSTRING.
4052 We allocate enough space for a preceding dash and trailing null. */
4053 flagstring = alloca (1 + flagslen + 1);
4054 memset (flagstring, '\0', 1 + flagslen + 1);
4055 p = flagstring;
4057 /* Start with a dash, for MFLAGS. */
4058 *p++ = '-';
4060 /* Add simple options as a group. */
4061 while (flags != 0 && !flags->arg && short_option (flags->cs->c))
4063 *p++ = flags->cs->c;
4064 flags = flags->next;
4067 /* Now add more complex flags: ones with options and/or long names. */
4068 while (flags)
4070 *p++ = ' ';
4071 *p++ = '-';
4073 /* Add the flag letter or name to the string. */
4074 if (short_option (flags->cs->c))
4075 *p++ = flags->cs->c;
4076 else
4078 /* Long options require a double-dash. */
4079 *p++ = '-';
4080 strcpy (p, flags->cs->long_name);
4081 p += strlen (p);
4083 /* An omitted optional argument has an ARG of "". */
4084 if (flags->arg && flags->arg[0] != '\0')
4086 if (!short_option (flags->cs->c))
4087 /* Long options require '='. */
4088 *p++ = '=';
4089 p = quote_for_env (p, flags->arg);
4091 flags = flags->next;
4094 /* If no flags at all, get rid of the initial dash. */
4095 if (p == &flagstring[1])
4097 flagstring[0] = '\0';
4098 p = flagstring;
4101 #ifdef KMK
4102 /* Define MFLAGS before appending variable definitions. Omit an initial
4103 empty dash. Since MFLAGS is not parsed for flags, there is no reason to
4104 override any makefile redefinition. */
4105 define_variable_cname ("MFLAGS",
4106 flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
4107 o_env, 1);
4108 #endif /* !KMK */
4110 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
4111 flag options. */
4112 if (eval_strings)
4114 *p++ = ' ';
4115 memcpy (p, evalref, CSTRLEN (evalref));
4116 p += CSTRLEN (evalref);
4119 if (all && command_variables)
4121 /* Write a reference to $(MAKEOVERRIDES), which contains all the
4122 command-line variable definitions. Separate the variables from the
4123 switches with a "--" arg. */
4125 strcpy (p, " -- ");
4126 p += 4;
4128 /* Copy in the string. */
4129 if (posix_pedantic)
4131 memcpy (p, posixref, CSTRLEN (posixref));
4132 p += CSTRLEN (posixref);
4134 else
4136 memcpy (p, ref, CSTRLEN (ref));
4137 p += CSTRLEN (ref);
4141 /* If there is a leading dash, omit it. */
4142 if (flagstring[0] == '-')
4143 ++flagstring;
4145 #ifdef KMK
4146 /* Provide simple access to some of the options. */
4148 char val[32];
4149 sprintf (val, "%u", job_slots ? job_slots : master_job_slots);
4150 define_variable_cname ("KMK_OPTS_JOBS", val, o_default, 1);
4151 sprintf (val, "%u", default_job_slots);
4152 define_variable_cname ("KMK_OPTS_JOBS_DEFAULT", val, o_default, 1);
4153 define_variable_cname ("KMK_OPTS_KEEP_GOING", keep_going_flag ? "1" : "0", o_default, 1);
4154 define_variable_cname ("KMK_OPTS_JUST_PRINT", just_print_flag ? "1" : "0", o_default, 1);
4155 define_variable_cname ("KMK_OPTS_PRETTY_COMMAND_PRINTING",
4156 pretty_command_printing ? "1" : "0", o_default, 1);
4157 sprintf (val, "%u", process_priority);
4158 define_variable_cname ("KMK_OPTS_PRORITY", val, o_default, 1);
4159 sprintf (val, "%u", process_affinity);
4160 define_variable_cname ("KMK_OPTS_AFFINITY", val, o_default, 1);
4161 # if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
4162 define_variable_cname ("KMK_OPTS_STATISTICS", make_expensive_statistics ? "1" : "0",
4163 o_default, 1);
4164 # endif
4165 # ifdef CONFIG_WITH_PRINT_TIME_SWITCH
4166 sprintf (val, "%u", print_time_min);
4167 define_variable_cname ("KMK_OPTS_PRINT_TIME", val, o_default, 1);
4168 # endif
4170 #endif
4172 /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
4173 Makefiles set MAKEFLAGS to add switches, but we still want to redefine
4174 its value with the full set of switches. Then we used o_file, but that
4175 lost when users added -e, causing a previous MAKEFLAGS env. var. to take
4176 precedence over the new one. Of course, an override or command
4177 definition will still take precedence. */
4178 #ifdef KMK
4179 return define_variable_cname ("KMK_FLAGS", flagstring,
4180 env_overrides ? o_env_override : o_file, 1);
4181 #else
4182 return define_variable_cname ("MAKEFLAGS", flagstring,
4183 env_overrides ? o_env_override : o_file, 1);
4184 #endif
4187 /* Print version information. */
4189 static void
4190 print_version (void)
4192 static int printed_version = 0;
4194 const char *precede = print_data_base_flag ? "# " : "";
4196 if (printed_version)
4197 /* Do it only once. */
4198 return;
4200 #ifdef KMK
4201 printf ("%skmk - kBuild version %d.%d.%d (r%u)\n\
4202 \n",
4203 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR,
4204 KBUILD_VERSION_PATCH, KBUILD_SVN_REV);
4206 printf("%sBased on GNU Make %s:\n", precede, version_string);
4208 #else /* !KMK */
4209 printf ("%sGNU Make %s\n", precede, version_string);
4211 if (!remote_description || *remote_description == '\0')
4212 printf (_("%sBuilt for %s\n"), precede, make_host);
4213 else
4214 printf (_("%sBuilt for %s (%s)\n"),
4215 precede, make_host, remote_description);
4216 #endif /* !KMK */
4218 /* Print this untranslated. The coding standards recommend translating the
4219 (C) to the copyright symbol, but this string is going to change every
4220 year, and none of the rest of it should be translated (including the
4221 word "Copyright"), so it hardly seems worth it. */
4223 printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
4224 precede);
4226 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
4227 %sThis is free software: you are free to change and redistribute it.\n\
4228 %sThere is NO WARRANTY, to the extent permitted by law.\n"),
4229 precede, precede, precede);
4231 #ifdef KMK
4232 printf ("\n\
4233 %skBuild modifications:\n\
4234 %s Copyright (c) 2005-2018 knut st. osmundsen.\n\
4236 %skmkbuiltin commands derived from *BSD sources:\n\
4237 %s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
4238 %s The Regents of the University of California. All rights reserved.\n\
4239 %s Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>\n",
4240 precede, precede, precede, precede, precede, precede);
4242 # ifdef KBUILD_PATH
4243 printf (_("\n\
4244 %sKBUILD_PATH: '%s' (default '%s')\n\
4245 %sKBUILD_BIN_PATH: '%s' (default '%s')\n\
4246 \n"),
4247 precede, get_kbuild_path(), KBUILD_PATH,
4248 precede, get_kbuild_bin_path(), KBUILD_BIN_PATH);
4249 # else /* !KBUILD_PATH */
4250 printf ("\n\
4251 %sKBUILD_PATH: '%s'\n\
4252 %sKBUILD_BIN_PATH: '%s'\n\
4253 \n",
4254 precede, get_kbuild_path(),
4255 precede, get_kbuild_bin_path());
4256 # endif /* !KBUILD_PATH */
4258 if (!remote_description || *remote_description == '\0')
4259 printf (_("%sThis program is a %s build, built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n\n"),
4260 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
4261 else
4262 printf (_("%sThis program is a %s build, built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n\n"),
4263 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
4265 #endif /* KMK */
4267 printed_version = 1;
4269 /* Flush stdout so the user doesn't have to wait to see the
4270 version information while make thinks about things. */
4271 fflush (stdout);
4274 /* Print a bunch of information about this and that. */
4276 static void
4277 print_data_base (void)
4279 time_t when = time ((time_t *) 0);
4281 print_version ();
4283 printf (_("\n# Make data base, printed on %s"), ctime (&when));
4285 print_variable_data_base ();
4286 print_dir_data_base ();
4287 print_rule_data_base ();
4288 print_file_data_base ();
4289 print_vpath_data_base ();
4290 #ifdef KMK
4291 print_kbuild_data_base ();
4292 #endif
4293 #ifndef CONFIG_WITH_STRCACHE2
4294 strcache_print_stats ("#");
4295 #else
4296 strcache2_print_stats_all ("#");
4297 #endif
4298 #ifdef CONFIG_WITH_ALLOC_CACHES
4299 alloccache_print_all ();
4300 #endif
4301 #ifdef CONFIG_WITH_COMPILER
4302 kmk_cc_print_stats ();
4303 #endif
4305 when = time ((time_t *) 0);
4306 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
4308 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
4310 static void
4311 print_stats ()
4313 time_t when;
4315 when = time ((time_t *) 0);
4316 printf (_("\n# Make statistics, printed on %s"), ctime (&when));
4318 /* Allocators: */
4319 # ifdef CONFIG_WITH_COMPILER
4320 kmk_cc_print_stats ();
4321 # endif
4322 # ifndef CONFIG_WITH_STRCACHE2
4323 strcache_print_stats ("#");
4324 # else
4325 strcache2_print_stats_all ("#");
4326 # endif
4327 # ifdef CONFIG_WITH_ALLOC_CACHES
4328 alloccache_print_all ();
4329 # endif
4330 print_heap_stats ();
4332 /* Make stuff: */
4333 print_variable_stats ();
4334 print_file_stats ();
4335 print_dir_stats ();
4336 # ifdef KMK
4337 print_kbuild_define_stats ();
4338 # endif
4339 # ifdef CONFIG_WITH_KMK_BUILTIN_STATS
4340 kmk_builtin_print_stats (stdout, "# ");
4341 # endif
4342 # ifdef CONFIG_WITH_COMPILER
4343 kmk_cc_print_stats ();
4344 # endif
4346 when = time ((time_t *) 0);
4347 printf (_("\n# Finished Make statistics on %s\n"), ctime (&when));
4349 #endif /* CONFIG_WITH_PRINT_STATS_SWITCH */
4351 static void
4352 clean_jobserver (int status)
4354 /* Sanity: have we written all our jobserver tokens back? If our
4355 exit status is 2 that means some kind of syntax error; we might not
4356 have written all our tokens so do that now. If tokens are left
4357 after any other error code, that's bad. */
4359 if (jobserver_enabled() && jobserver_tokens)
4361 if (status != 2)
4362 ON (error, NILF,
4363 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
4364 jobserver_tokens);
4365 else
4366 /* Don't write back the "free" token */
4367 while (--jobserver_tokens)
4368 jobserver_release (0);
4372 /* Sanity: If we're the master, were all the tokens written back? */
4374 if (master_job_slots)
4376 /* We didn't write one for ourself, so start at 1. */
4377 unsigned int tokens = 1 + jobserver_acquire_all ();
4379 if (tokens != master_job_slots)
4380 ONN (error, NILF,
4381 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
4382 tokens, master_job_slots);
4384 reset_jobserver ();
4388 /* Exit with STATUS, cleaning up as necessary. */
4390 void
4391 #ifdef KMK
4392 die_with_job_output (int status, struct output *out)
4393 #else
4394 die (int status)
4395 #endif
4397 static char dying = 0;
4398 #ifdef KMK
4399 static char need_2nd_error = 0;
4400 static char need_2nd_error_output = 0;
4401 #endif
4403 if (!dying)
4405 int err;
4407 dying = 1;
4409 if (print_version_flag)
4410 print_version ();
4412 #ifdef KMK
4413 /* Flag 2nd error message. */
4414 if (status != 0
4415 && ( job_slots_used > 0
4416 || print_data_base_flag
4417 || print_stats_flag))
4419 need_2nd_error = 1;
4420 need_2nd_error_output = job_slots_used >= 2
4421 && out != NULL
4422 && out != &make_sync;
4423 if (need_2nd_error_output)
4424 output_metered = 0;
4426 #endif /* KMK */
4428 /* Wait for children to die. */
4429 err = (status != 0);
4430 while (job_slots_used > 0)
4431 reap_children (1, err);
4433 /* Let the remote job module clean up its state. */
4434 remote_cleanup ();
4436 /* Remove the intermediate files. */
4437 remove_intermediates (0);
4439 if (print_data_base_flag)
4440 print_data_base ();
4442 #ifdef CONFIG_WITH_PRINT_STATS_SWITCH
4443 if (print_stats_flag)
4444 print_stats ();
4445 #endif
4446 if (verify_flag)
4447 verify_file_data_base ();
4449 #ifdef NDEBUG /* bird: Don't waste time on debug sanity checks. */
4450 if (print_data_base_flag || db_level)
4451 #endif
4452 verify_file_data_base ();
4454 clean_jobserver (status);
4456 if (output_context)
4458 /* die() might be called in a recipe output context due to an
4459 $(error ...) function. */
4460 output_close (output_context);
4462 if (output_context != &make_sync)
4463 output_close (&make_sync);
4465 OUTPUT_UNSET ();
4468 output_close (NULL);
4470 /* Try to move back to the original directory. This is essential on
4471 MS-DOS (where there is really only one process), and on Unix it
4472 puts core files in the original directory instead of the -C
4473 directory. Must wait until after remove_intermediates(), or unlinks
4474 of relative pathnames fail. */
4475 if (directory_before_chdir != 0)
4477 /* If it fails we don't care: shut up GCC. */
4478 int _x UNUSED;
4479 _x = chdir (directory_before_chdir);
4482 #ifdef CONFIG_WITH_PRINT_TIME_SWITCH
4483 if (print_time_min != -1)
4485 big_int elapsed = nano_timestamp () - make_start_ts;
4486 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
4488 char buf[64];
4489 format_elapsed_nano (buf, sizeof (buf), elapsed);
4490 message (1, strlen (buf), _("%*s"), print_time_width, buf);
4493 #endif
4496 #ifdef KMK
4497 /* The failure might be lost in a -j <lots> run, so mention the
4498 failure again before exiting. */
4499 if (need_2nd_error != 0)
4500 ON (error, NILF, _("*** Exiting with status %d"), status);
4501 if (out)
4503 out->dont_truncate = 0;
4504 if (need_2nd_error_output && output_metered > 20)
4505 output_dump (out);
4506 else
4507 output_reset (out);
4508 output_close (out);
4510 #endif
4512 exit (status);
4515 #ifdef KMK
4516 void die (int status)
4518 die_with_job_output (status, NULL);
4520 #endif