VirtualBox

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

Last change on this file since 3387 was 3357, checked in by bird, 4 years ago

kmk,winchildren.c: Some adjustments to the job object thing, adding a 'login' mode (default) to allow two independent kmk instances to share an mkpdbsrv.exe instance. Split the 'nokill' out of the mode and into a separate option.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use