VirtualBox

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

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

better help for --output-sync.

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