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

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

kmkbuiltin: stats

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