VirtualBox

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

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

kmk: replaced w32ify() as it uses unsafe static buffer and encourages buffer size assumptions.

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