VirtualBox

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

Last change on this file since 3297 was 3297, checked in by bird, 5 years ago

kmk/win: Two CONFIG_NEW_WIN_CHILDREN fixes (inverted #ifdef's), can now use all threads on systems with more than 64 (for whatever good it does).

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

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