VirtualBox

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

Last change on this file since 3633 was 3481, checked in by bird, 4 years ago

kmk: remove debug fprintf from previous commit.

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

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