VirtualBox

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

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

kmk/win: Some fixes & docs.

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

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