VirtualBox

source: kBuild/trunk/src/kmk/main.c@ 3154

Last change on this file since 3154 was 3149, checked in by bird, 7 years ago

(C) update

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette