source: trunk/src/kmk/main.c@ 3161

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

kmk/win: More child process work, focusing on making kmk_builtin_redirect not requiring the shared lock.

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