source: trunk/src/kmk/main.c@ 3653

Last change on this file since 3653 was 3653, checked in by bird, 9 months ago

kmk: Automatically ascend if no makefile found and a goal was given on the command line. This is to eliminating the need for Makefile.kup-files as far as compiling individual source files from an editor is concerned.

  • Property svn:eol-style set to native
File size: 136.3 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 /* If no [Mm]akefile.kmk in the current directory, we may want to ascend to a
2411 parent directory that contains one. This is explicitly ordered by placing
2412 [Mm]akefile.kup files in the directory. And since 2024-11-04 we
2413 automatically do this when here is a goal (e.g. main.o) on the command
2414 line and no other default makefiles around. This new behvior simplifies
2415 compiling individial source files from the editor without requiring us to
2416 sprinkle Makefile.kup-files around the tree, esp. in 3rd party code.
2417
2418 If no -C arguments were given, fake one to indicate chdir. */
2419 if (makefiles == 0)
2420 {
2421 struct stat st;
2422 if (stat ("Makefile.kmk", &st) < 0
2423 && stat ("makefile.kmk", &st) < 0)
2424 {
2425 static char fake_path[3*16 + 32] = "..";
2426 char *cur = &fake_path[2];
2427 int up_levels = 1;
2428
2429 /* If there are any .kup-files. */
2430 if (( stat ("Makefile.kup", &st) == 0
2431 && S_ISREG (st.st_mode) )
2432 || ( stat ("makefile.kup", &st) == 0
2433 && S_ISREG (st.st_mode) ) )
2434 {
2435 while (up_levels < 16)
2436 {
2437 /* File with higher precedence. */
2438 strcpy (cur, "/Makefile.kmk");
2439 if (stat (fake_path, &st) == 0)
2440 break;
2441 cur[1] = 'm';
2442 if (stat (fake_path, &st) == 0)
2443 break;
2444
2445 /* the .kup files */
2446 strcpy (cur, "/Makefile.kup");
2447 if ( stat (fake_path, &st) != 0
2448 || !S_ISREG (st.st_mode))
2449 {
2450 cur[1] = 'm';
2451 if ( stat (fake_path, &st) != 0
2452 || !S_ISREG (st.st_mode))
2453 break;
2454 }
2455
2456 /* ok */
2457 strcpy (cur, "/..");
2458 cur += 3;
2459 up_levels++;
2460 }
2461 if (up_levels >= 16)
2462 O (fatal, NILF, _("Makefile.kup recursion is too deep."));
2463 }
2464 /* If there are no default makefiles either and one or more goals on
2465 the command line, go looking for kmk-files up the parent tree. */
2466 else if (goals != NULL
2467 && stat ("GNUmakefile", &st) < 0
2468 && stat ("makefile", &st) < 0
2469 && stat ("Makefile", &st) < 0
2470#ifdef WINDOWS32
2471 && stat ("makefile.mak", &st) < 0
2472#endif
2473 )
2474 while (up_levels < 16)
2475 {
2476 /* File with higher precedence.s */
2477 strcpy (cur, "/Makefile.kmk");
2478 if (stat (fake_path, &st) == 0)
2479 break;
2480 cur[1] = 'm';
2481 if (stat (fake_path, &st) == 0)
2482 break;
2483
2484 /* ok */
2485 strcpy (cur, "/..");
2486 cur += 3;
2487 up_levels++;
2488 }
2489 else
2490 up_levels = 0;
2491 if (up_levels > 0 && up_levels < 16)
2492 {
2493 /* attempt to change to the directory. */
2494 *cur = '\0';
2495 if (chdir (fake_path) < 0)
2496 pfatal_with_name (fake_path);
2497
2498 /* add the string to the directories. */
2499 if (!directories)
2500 {
2501 directories = xmalloc (sizeof(*directories));
2502 directories->list = xmalloc (5 * sizeof (char *));
2503 directories->max = 5;
2504 directories->idx = 0;
2505 }
2506 else if (directories->idx == directories->max - 1)
2507 {
2508 directories->max += 5;
2509 directories->list = xrealloc ((void *)directories->list,
2510 directories->max * sizeof (char *));
2511 }
2512 directories->list[directories->idx++] = fake_path;
2513 }
2514 }
2515 }
2516#endif /* KMK */
2517
2518#ifdef WINDOWS32
2519 /*
2520 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
2521 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
2522 *
2523 * The functions in dir.c can incorrectly cache information for "."
2524 * before we have changed directory and this can cause file
2525 * lookups to fail because the current directory (.) was pointing
2526 * at the wrong place when it was first evaluated.
2527 */
2528#ifdef KMK /* this is really a candidate for all platforms... */
2529 {
2530 extern const char *default_shell;
2531 const char *bin = get_kbuild_bin_path();
2532 char *newshell;
2533 size_t len = strlen (bin);
2534 default_shell = newshell = xmalloc (len + sizeof("/kmk_ash.exe"));
2535 memcpy (newshell, bin, len);
2536 strcpy (newshell + len, "/kmk_ash.exe");
2537 no_default_sh_exe = 0;
2538 batch_mode_shell = 1;
2539 unixy_shell = 1;
2540 }
2541#else /* !KMK */
2542 no_default_sh_exe = !find_and_set_default_shell (NULL);
2543#endif /* !KMK */
2544#endif /* WINDOWS32 */
2545
2546 /* Except under -s, always do -w in sub-makes and under -C. */
2547 if (!silent_flag && (directories != 0 || makelevel > 0))
2548 print_directory_flag = 1;
2549
2550 /* Let the user disable that with --no-print-directory. */
2551 if (inhibit_print_directory_flag)
2552 print_directory_flag = 0;
2553
2554 /* If -R was given, set -r too (doesn't make sense otherwise!) */
2555 if (no_builtin_variables_flag)
2556 no_builtin_rules_flag = 1;
2557
2558 /* Construct the list of include directories to search. */
2559
2560 construct_include_path (include_directories == 0
2561 ? 0 : include_directories->list);
2562
2563 /* If we chdir'ed, figure out where we are now. */
2564 if (directories)
2565 {
2566#ifdef WINDOWS32
2567 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
2568#else
2569 if (getcwd (current_directory, GET_PATH_MAX) == 0)
2570#endif
2571 {
2572#ifdef HAVE_GETCWD
2573 perror_with_name ("getcwd", "");
2574#else
2575 OS (error, NILF, "getwd: %s", current_directory);
2576#endif
2577 starting_directory = 0;
2578 }
2579 else
2580 starting_directory = current_directory;
2581 }
2582
2583 define_variable_cname ("CURDIR", current_directory, o_file, 0);
2584
2585 /* Read any stdin makefiles into temporary files. */
2586
2587 if (makefiles != 0)
2588 {
2589 unsigned int i;
2590 for (i = 0; i < makefiles->idx; ++i)
2591 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
2592 {
2593 /* This makefile is standard input. Since we may re-exec
2594 and thus re-read the makefiles, we read standard input
2595 into a temporary file and read from that. */
2596 FILE *outfile;
2597 char *template;
2598 const char *tmpdir;
2599
2600 if (stdin_nm)
2601 O (fatal, NILF,
2602 _("Makefile from standard input specified twice."));
2603
2604#ifdef VMS
2605# define DEFAULT_TMPDIR "/sys$scratch/"
2606#else
2607# ifdef P_tmpdir
2608# define DEFAULT_TMPDIR P_tmpdir
2609# else
2610# define DEFAULT_TMPDIR "/tmp"
2611# endif
2612#endif
2613#define DEFAULT_TMPFILE "GmXXXXXX"
2614
2615 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
2616#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2617 /* These are also used commonly on these platforms. */
2618 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
2619 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
2620#endif
2621 )
2622 tmpdir = DEFAULT_TMPDIR;
2623
2624 template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
2625 strcpy (template, tmpdir);
2626
2627#ifdef HAVE_DOS_PATHS
2628 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
2629 strcat (template, "/");
2630#else
2631# ifndef VMS
2632 if (template[strlen (template) - 1] != '/')
2633 strcat (template, "/");
2634# endif /* !VMS */
2635#endif /* !HAVE_DOS_PATHS */
2636
2637 strcat (template, DEFAULT_TMPFILE);
2638 outfile = output_tmpfile (&stdin_nm, template);
2639 if (outfile == 0)
2640 pfatal_with_name (_("fopen (temporary file)"));
2641 while (!feof (stdin) && ! ferror (stdin))
2642 {
2643 char buf[2048];
2644 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
2645 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2646 pfatal_with_name (_("fwrite (temporary file)"));
2647 }
2648 fclose (outfile);
2649
2650 /* Replace the name that read_all_makefiles will
2651 see with the name of the temporary file. */
2652 makefiles->list[i] = strcache_add (stdin_nm);
2653
2654 /* Make sure the temporary file will not be remade. */
2655 {
2656 struct file *f = enter_file (strcache_add (stdin_nm));
2657 f->updated = 1;
2658 f->update_status = us_success;
2659 f->command_state = cs_finished;
2660 /* Can't be intermediate, or it'll be removed too early for
2661 make re-exec. */
2662 f->intermediate = 0;
2663 f->dontcare = 0;
2664 }
2665 }
2666 }
2667
2668#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
2669#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
2670 /* Set up to handle children dying. This must be done before
2671 reading in the makefiles so that 'shell' function calls will work.
2672
2673 If we don't have a hanging wait we have to fall back to old, broken
2674 functionality here and rely on the signal handler and counting
2675 children.
2676
2677 If we're using the jobs pipe we need a signal handler so that SIGCHLD is
2678 not ignored; we need it to interrupt the read(2) of the jobserver pipe if
2679 we're waiting for a token.
2680
2681 If none of these are true, we don't need a signal handler at all. */
2682 {
2683# if defined SIGCHLD
2684 bsd_signal (SIGCHLD, child_handler);
2685# endif
2686# if defined SIGCLD && SIGCLD != SIGCHLD
2687 bsd_signal (SIGCLD, child_handler);
2688# endif
2689 }
2690
2691#ifdef HAVE_PSELECT
2692 /* If we have pselect() then we need to block SIGCHLD so it's deferred. */
2693 {
2694 sigset_t block;
2695 sigemptyset (&block);
2696 sigaddset (&block, SIGCHLD);
2697 if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
2698 pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
2699 }
2700#endif
2701
2702#endif
2703#endif
2704
2705 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2706#ifdef SIGUSR1
2707 bsd_signal (SIGUSR1, debug_signal_handler);
2708#endif
2709
2710 /* Define the initial list of suffixes for old-style rules. */
2711 set_default_suffixes ();
2712
2713 /* Define the file rules for the built-in suffix rules. These will later
2714 be converted into pattern rules. We used to do this in
2715 install_default_implicit_rules, but since that happens after reading
2716 makefiles, it results in the built-in pattern rules taking precedence
2717 over makefile-specified suffix rules, which is wrong. */
2718 install_default_suffix_rules ();
2719
2720 /* Define some internal and special variables. */
2721 define_automatic_variables ();
2722
2723 /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
2724 Initialize it to be exported but allow the makefile to reset it. */
2725 define_makeflags (0, 0)->export = v_export;
2726
2727 /* Define the default variables. */
2728 define_default_variables ();
2729
2730 default_file = enter_file (strcache_add (".DEFAULT"));
2731
2732 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
2733
2734 /* Evaluate all strings provided with --eval.
2735 Also set up the $(-*-eval-flags-*-) variable. */
2736
2737 if (eval_strings)
2738 {
2739 char *p, *value;
2740 unsigned int i;
2741 unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
2742
2743 for (i = 0; i < eval_strings->idx; ++i)
2744 {
2745#ifndef CONFIG_WITH_VALUE_LENGTH
2746 p = xstrdup (eval_strings->list[i]);
2747 len += 2 * strlen (p);
2748 eval_buffer (p, NULL);
2749#else
2750 unsigned int sub_len = strlen(eval_strings->list[i]);
2751 p = xstrndup (eval_strings->list[i], sub_len);
2752 len += 2 * sub_len;
2753 eval_buffer (p, NULL, p + sub_len);
2754#endif
2755 free (p);
2756 }
2757
2758 p = value = alloca (len);
2759 for (i = 0; i < eval_strings->idx; ++i)
2760 {
2761 strcpy (p, "--eval=");
2762 p += CSTRLEN ("--eval=");
2763 p = quote_for_env (p, eval_strings->list[i]);
2764 *(p++) = ' ';
2765 }
2766 p[-1] = '\0';
2767
2768 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
2769 }
2770
2771 /* Read all the makefiles. */
2772
2773 read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2774
2775#ifdef WINDOWS32
2776 /* look one last time after reading all Makefiles */
2777 if (no_default_sh_exe)
2778 no_default_sh_exe = !find_and_set_default_shell (NULL);
2779#endif /* WINDOWS32 */
2780
2781#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2782 /* We need to know what kind of shell we will be using. */
2783 {
2784 extern int _is_unixy_shell (const char *_path);
2785 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2786 extern int unixy_shell;
2787 extern const char *default_shell;
2788
2789 if (shv && *shv->value)
2790 {
2791 char *shell_path = recursively_expand (shv);
2792
2793 if (shell_path && _is_unixy_shell (shell_path))
2794 unixy_shell = 1;
2795 else
2796 unixy_shell = 0;
2797 if (shell_path)
2798 default_shell = shell_path;
2799 }
2800 }
2801#endif /* __MSDOS__ || __EMX__ */
2802
2803 {
2804 int old_builtin_rules_flag = no_builtin_rules_flag;
2805 int old_builtin_variables_flag = no_builtin_variables_flag;
2806
2807 /* Decode switches again, for variables set by the makefile. */
2808 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
2809
2810 /* Clear GNUMAKEFLAGS to avoid duplication. */
2811 define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
2812
2813#ifdef KMK
2814 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2815#else /* !KMK */
2816 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2817#if 0
2818 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2819#endif
2820#endif /* !KMK */
2821
2822 /* Reset in case the switches changed our mind. */
2823 syncing = (output_sync == OUTPUT_SYNC_LINE
2824 || output_sync == OUTPUT_SYNC_TARGET);
2825
2826 if (make_sync.syncout && ! syncing)
2827 output_close (&make_sync);
2828
2829 make_sync.syncout = syncing;
2830 OUTPUT_SET (&make_sync);
2831
2832 /* If we've disabled builtin rules, get rid of them. */
2833 if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2834 {
2835 if (suffix_file->builtin)
2836 {
2837 free_dep_chain (suffix_file->deps);
2838 suffix_file->deps = 0;
2839 }
2840 define_variable_cname ("SUFFIXES", "", o_default, 0);
2841 }
2842
2843 /* If we've disabled builtin variables, get rid of them. */
2844 if (no_builtin_variables_flag && ! old_builtin_variables_flag)
2845 undefine_default_variables ();
2846 }
2847
2848#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2849 if (arg_job_slots != 1
2850# ifdef __EMX__
2851 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2852# endif
2853 )
2854 {
2855 O (error, NILF,
2856 _("Parallel jobs (-j) are not supported on this platform."));
2857 O (error, NILF, _("Resetting to single job (-j1) mode."));
2858 arg_job_slots = job_slots = 1;
2859 }
2860#endif
2861
2862 /* If we have >1 slot at this point, then we're a top-level make.
2863 Set up the jobserver.
2864
2865 Every make assumes that it always has one job it can run. For the
2866 submakes it's the token they were given by their parent. For the top
2867 make, we just subtract one from the number the user wants. */
2868
2869 if (job_slots > 1 && jobserver_setup (job_slots - 1))
2870 {
2871 /* Fill in the jobserver_auth for our children. */
2872 jobserver_auth = jobserver_get_auth ();
2873
2874 if (jobserver_auth)
2875 {
2876 /* We're using the jobserver so set job_slots to 0. */
2877 master_job_slots = job_slots;
2878 job_slots = 0;
2879 }
2880 }
2881
2882 /* If we're not using parallel jobs, then we don't need output sync.
2883 This is so people can enable output sync in GNUMAKEFLAGS or similar, but
2884 not have it take effect unless parallel builds are enabled. */
2885 if (syncing && job_slots == 1)
2886 {
2887 OUTPUT_UNSET ();
2888 output_close (&make_sync);
2889 syncing = 0;
2890 output_sync = OUTPUT_SYNC_NONE;
2891 }
2892
2893#ifndef MAKE_SYMLINKS
2894 if (check_symlink_flag)
2895 {
2896 O (error, NILF, _("Symbolic links not supported: disabling -L."));
2897 check_symlink_flag = 0;
2898 }
2899#endif
2900
2901 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2902
2903 define_makeflags (1, 0);
2904
2905 /* Make each 'struct goaldep' point at the 'struct file' for the file
2906 depended on. Also do magic for special targets. */
2907
2908 snap_deps ();
2909
2910 /* Convert old-style suffix rules to pattern rules. It is important to
2911 do this before installing the built-in pattern rules below, so that
2912 makefile-specified suffix rules take precedence over built-in pattern
2913 rules. */
2914
2915 convert_to_pattern ();
2916
2917 /* Install the default implicit pattern rules.
2918 This used to be done before reading the makefiles.
2919 But in that case, built-in pattern rules were in the chain
2920 before user-defined ones, so they matched first. */
2921
2922 install_default_implicit_rules ();
2923
2924 /* Compute implicit rule limits. */
2925
2926 count_implicit_rule_limits ();
2927
2928 /* Construct the listings of directories in VPATH lists. */
2929
2930 build_vpath_lists ();
2931
2932 /* Mark files given with -o flags as very old and as having been updated
2933 already, and files given with -W flags as brand new (time-stamp as far
2934 as possible into the future). If restarts is set we'll do -W later. */
2935
2936 if (old_files != 0)
2937 {
2938 const char **p;
2939 for (p = old_files->list; *p != 0; ++p)
2940 {
2941 struct file *f = enter_file (*p);
2942 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2943 f->updated = 1;
2944 f->update_status = us_success;
2945 f->command_state = cs_finished;
2946 }
2947 }
2948
2949 if (!restarts && new_files != 0)
2950 {
2951 const char **p;
2952 for (p = new_files->list; *p != 0; ++p)
2953 {
2954 struct file *f = enter_file (*p);
2955 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2956 }
2957 }
2958
2959 /* Initialize the remote job module. */
2960 remote_setup ();
2961
2962 /* Dump any output we've collected. */
2963
2964 OUTPUT_UNSET ();
2965 output_close (&make_sync);
2966
2967 if (read_files != 0)
2968 {
2969 /* Update any makefiles if necessary. */
2970
2971 FILE_TIMESTAMP *makefile_mtimes = 0;
2972 unsigned int mm_idx = 0;
2973 char **aargv = NULL;
2974 const char **nargv;
2975 int nargc;
2976 enum update_status status;
2977
2978 DB (DB_BASIC, (_("Updating makefiles....\n")));
2979
2980 /* Remove any makefiles we don't want to try to update.
2981 Also record the current modtimes so we can compare them later. */
2982 {
2983 register struct goaldep *d, *last;
2984 last = 0;
2985 d = read_files;
2986 while (d != 0)
2987 {
2988 struct file *f = d->file;
2989 if (f->double_colon)
2990 for (f = f->double_colon; f != NULL; f = f->prev)
2991 {
2992 if (f->deps == 0 && f->cmds != 0)
2993 {
2994 /* This makefile is a :: target with commands, but
2995 no dependencies. So, it will always be remade.
2996 This might well cause an infinite loop, so don't
2997 try to remake it. (This will only happen if
2998 your makefiles are written exceptionally
2999 stupidly; but if you work for Athena, that's how
3000 you write your makefiles.) */
3001
3002 DB (DB_VERBOSE,
3003 (_("Makefile '%s' might loop; not remaking it.\n"),
3004 f->name));
3005
3006 if (last == 0)
3007 read_files = d->next;
3008 else
3009 last->next = d->next;
3010
3011 /* Free the storage. */
3012 free_goaldep (d);
3013
3014 d = last == 0 ? read_files : last->next;
3015
3016 break;
3017 }
3018 }
3019
3020 if (f == NULL || !f->double_colon)
3021 {
3022 makefile_mtimes = xrealloc (makefile_mtimes,
3023 (mm_idx+1)
3024 * sizeof (FILE_TIMESTAMP));
3025 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
3026 last = d;
3027 d = d->next;
3028 }
3029 }
3030 }
3031
3032 /* Set up 'MAKEFLAGS' specially while remaking makefiles. */
3033 define_makeflags (1, 1);
3034
3035 {
3036 int orig_db_level = db_level;
3037
3038 if (! ISDB (DB_MAKEFILES))
3039 db_level = DB_NONE;
3040
3041 rebuilding_makefiles = 1;
3042 status = update_goal_chain (read_files);
3043 rebuilding_makefiles = 0;
3044
3045 db_level = orig_db_level;
3046 }
3047
3048 switch (status)
3049 {
3050 case us_question:
3051 /* The only way this can happen is if the user specified -q and asked
3052 for one of the makefiles to be remade as a target on the command
3053 line. Since we're not actually updating anything with -q we can
3054 treat this as "did nothing". */
3055
3056 case us_none:
3057 /* Did nothing. */
3058 break;
3059
3060 case us_failed:
3061 /* Failed to update. Figure out if we care. */
3062 {
3063 /* Nonzero if any makefile was successfully remade. */
3064 int any_remade = 0;
3065 /* Nonzero if any makefile we care about failed
3066 in updating or could not be found at all. */
3067 int any_failed = 0;
3068 unsigned int i;
3069 struct goaldep *d;
3070
3071 for (i = 0, d = read_files; d != 0; ++i, d = d->next)
3072 {
3073 if (d->file->updated)
3074 {
3075 /* This makefile was updated. */
3076 if (d->file->update_status == us_success)
3077 {
3078 /* It was successfully updated. */
3079 any_remade |= (file_mtime_no_search (d->file)
3080 != makefile_mtimes[i]);
3081 }
3082 else if (! (d->flags & RM_DONTCARE))
3083 {
3084 FILE_TIMESTAMP mtime;
3085 /* The update failed and this makefile was not
3086 from the MAKEFILES variable, so we care. */
3087 OS (error, NILF, _("Failed to remake makefile '%s'."),
3088 d->file->name);
3089 mtime = file_mtime_no_search (d->file);
3090 any_remade |= (mtime != NONEXISTENT_MTIME
3091 && mtime != makefile_mtimes[i]);
3092 makefile_status = MAKE_FAILURE;
3093 }
3094 }
3095 else
3096 /* This makefile was not found at all. */
3097 if (! (d->flags & RM_DONTCARE))
3098 {
3099 const char *dnm = dep_name (d);
3100 size_t l = strlen (dnm);
3101
3102 /* This is a makefile we care about. See how much. */
3103 if (d->flags & RM_INCLUDED)
3104 /* An included makefile. We don't need to die, but we
3105 do want to complain. */
3106 error (NILF, l,
3107 _("Included makefile '%s' was not found."), dnm);
3108 else
3109 {
3110 /* A normal makefile. We must die later. */
3111 error (NILF, l,
3112 _("Makefile '%s' was not found"), dnm);
3113 any_failed = 1;
3114 }
3115 }
3116 }
3117 /* Reset this to empty so we get the right error message below. */
3118 read_files = 0;
3119
3120 if (any_remade)
3121 goto re_exec;
3122 if (any_failed)
3123 die (MAKE_FAILURE);
3124 break;
3125 }
3126
3127 case us_success:
3128 re_exec:
3129 /* Updated successfully. Re-exec ourselves. */
3130
3131 remove_intermediates (0);
3132
3133 if (print_data_base_flag)
3134 print_data_base ();
3135
3136 clean_jobserver (0);
3137
3138 if (makefiles != 0)
3139 {
3140 /* These names might have changed. */
3141 int i, j = 0;
3142 for (i = 1; i < argc; ++i)
3143 if (strneq (argv[i], "-f", 2)) /* XXX */
3144 {
3145 if (argv[i][2] == '\0')
3146 /* This cast is OK since we never modify argv. */
3147 argv[++i] = (char *) makefiles->list[j];
3148 else
3149 argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
3150 ++j;
3151 }
3152 }
3153
3154 /* Add -o option for the stdin temporary file, if necessary. */
3155 nargc = argc;
3156 if (stdin_nm)
3157 {
3158 void *m = xmalloc ((nargc + 2) * sizeof (char *));
3159 aargv = m;
3160 memcpy (aargv, argv, argc * sizeof (char *));
3161 aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
3162 aargv[nargc] = 0;
3163 nargv = m;
3164 }
3165 else
3166 nargv = (const char**)argv;
3167
3168 if (directories != 0 && directories->idx > 0)
3169 {
3170 int bad = 1;
3171 if (directory_before_chdir != 0)
3172 {
3173 if (chdir (directory_before_chdir) < 0)
3174 perror_with_name ("chdir", "");
3175 else
3176 bad = 0;
3177 }
3178 if (bad)
3179 O (fatal, NILF,
3180 _("Couldn't change back to original directory."));
3181 }
3182
3183 ++restarts;
3184
3185 if (ISDB (DB_BASIC))
3186 {
3187 const char **p;
3188 printf (_("Re-executing[%u]:"), restarts);
3189 for (p = nargv; *p != 0; ++p)
3190 printf (" %s", *p);
3191 putchar ('\n');
3192 fflush (stdout);
3193 }
3194
3195#ifndef _AMIGA
3196 {
3197 char **p;
3198 for (p = environ; *p != 0; ++p)
3199 {
3200 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
3201 {
3202 *p = alloca (40);
3203 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
3204#ifdef VMS
3205 vms_putenv_symbol (*p);
3206#endif
3207 }
3208 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
3209 {
3210 *p = alloca (40);
3211 sprintf (*p, "MAKE_RESTARTS=%s%u",
3212 OUTPUT_IS_TRACED () ? "-" : "", restarts);
3213 restarts = 0;
3214 }
3215 }
3216 }
3217#else /* AMIGA */
3218 {
3219 char buffer[256];
3220
3221 sprintf (buffer, "%u", makelevel);
3222 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
3223
3224 sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
3225 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
3226 restarts = 0;
3227 }
3228#endif
3229
3230 /* If we didn't set the restarts variable yet, add it. */
3231 if (restarts)
3232 {
3233 char *b = alloca (40);
3234 sprintf (b, "MAKE_RESTARTS=%s%u",
3235 OUTPUT_IS_TRACED () ? "-" : "", restarts);
3236 putenv (b);
3237 }
3238
3239 fflush (stdout);
3240 fflush (stderr);
3241
3242#ifdef _AMIGA
3243 exec_command (nargv);
3244 exit (0);
3245#elif defined (__EMX__)
3246 {
3247 /* It is not possible to use execve() here because this
3248 would cause the parent process to be terminated with
3249 exit code 0 before the child process has been terminated.
3250 Therefore it may be the best solution simply to spawn the
3251 child process including all file handles and to wait for its
3252 termination. */
3253 int pid;
3254 int r;
3255 pid = child_execute_job (NULL, 1, nargv, environ);
3256
3257 /* is this loop really necessary? */
3258 do {
3259 pid = wait (&r);
3260 } while (pid <= 0);
3261 /* use the exit code of the child process */
3262 exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
3263 }
3264#else
3265#ifdef SET_STACK_SIZE
3266 /* Reset limits, if necessary. */
3267 if (stack_limit.rlim_cur)
3268 setrlimit (RLIMIT_STACK, &stack_limit);
3269#endif
3270# if !defined(WINDOWS32) || !defined(CONFIG_NEW_WIN_CHILDREN)
3271 exec_command ((char **)nargv, environ);
3272# else
3273 MkWinChildReExecMake ((char **)nargv, environ);
3274# endif
3275#endif
3276 free (aargv);
3277 break;
3278 }
3279
3280 /* Free the makefile mtimes. */
3281 free (makefile_mtimes);
3282 }
3283
3284 /* Set up 'MAKEFLAGS' again for the normal targets. */
3285 define_makeflags (1, 0);
3286
3287 /* Set always_make_flag if -B was given. */
3288 always_make_flag = always_make_set;
3289
3290 /* If restarts is set we haven't set up -W files yet, so do that now. */
3291 if (restarts && new_files != 0)
3292 {
3293 const char **p;
3294 for (p = new_files->list; *p != 0; ++p)
3295 {
3296 struct file *f = enter_file (*p);
3297 f->last_mtime = f->mtime_before_update = NEW_MTIME;
3298 }
3299 }
3300
3301 /* If there is a temp file from reading a makefile from stdin, get rid of
3302 it now. */
3303 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
3304 perror_with_name (_("unlink (temporary file): "), stdin_nm);
3305
3306 /* If there were no command-line goals, use the default. */
3307 if (goals == 0)
3308 {
3309 char *p;
3310
3311 if (default_goal_var->recursive)
3312 p = variable_expand (default_goal_var->value);
3313 else
3314 {
3315 p = variable_buffer_output (variable_buffer, default_goal_var->value,
3316 strlen (default_goal_var->value));
3317 *p = '\0';
3318 p = variable_buffer;
3319 }
3320
3321 if (*p != '\0')
3322 {
3323 struct file *f = lookup_file (p);
3324
3325 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
3326 table and let the standard logic sort it out. */
3327 if (f == 0)
3328 {
3329 struct nameseq *ns;
3330
3331 ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
3332 if (ns)
3333 {
3334 /* .DEFAULT_GOAL should contain one target. */
3335 if (ns->next != 0)
3336 O (fatal, NILF,
3337 _(".DEFAULT_GOAL contains more than one target"));
3338
3339#ifndef CONFIG_WITH_VALUE_LENGTH
3340 f = enter_file (strcache_add (ns->name));
3341#else
3342 f = enter_file (ns->name);
3343#endif
3344
3345 ns->name = 0; /* It was reused by enter_file(). */
3346 free_ns_chain (ns);
3347 }
3348 }
3349
3350 if (f)
3351 {
3352 goals = alloc_goaldep ();
3353 goals->file = f;
3354 }
3355 }
3356 }
3357 else
3358 lastgoal->next = 0;
3359
3360
3361 if (!goals)
3362 {
3363 if (read_files == 0)
3364 O (fatal, NILF, _("No targets specified and no makefile found"));
3365
3366 O (fatal, NILF, _("No targets"));
3367 }
3368
3369 /* Update the goals. */
3370
3371 DB (DB_BASIC, (_("Updating goal targets....\n")));
3372
3373 {
3374 switch (update_goal_chain (goals))
3375 {
3376 case us_none:
3377 /* Nothing happened. */
3378 /* FALLTHROUGH */
3379 case us_success:
3380 /* Keep the previous result. */
3381 break;
3382 case us_question:
3383 /* We are under -q and would run some commands. */
3384 makefile_status = MAKE_TROUBLE;
3385 break;
3386 case us_failed:
3387 /* Updating failed. POSIX.2 specifies exit status >1 for this; */
3388 makefile_status = MAKE_FAILURE;
3389 break;
3390 }
3391
3392 /* If we detected some clock skew, generate one last warning */
3393 if (clock_skew_detected)
3394 O (error, NILF,
3395 _("warning: Clock skew detected. Your build may be incomplete."));
3396
3397 MAKE_STATS_2(if (uStartTick) printf("main ticks elapsed: %llu\n", (unsigned long long)(CURRENT_CLOCK_TICK() - uStartTick)) );
3398 /* Exit. */
3399 die (makefile_status);
3400 }
3401
3402 /* NOTREACHED */
3403 exit (MAKE_SUCCESS);
3404}
3405
3406
3407/* Parsing of arguments, decoding of switches. */
3408
3409static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
3410static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
3411 (sizeof (long_option_aliases) /
3412 sizeof (long_option_aliases[0]))];
3413
3414/* Fill in the string and vector for getopt. */
3415static void
3416init_switches (void)
3417{
3418 char *p;
3419 unsigned int c;
3420 unsigned int i;
3421
3422 if (options[0] != '\0')
3423 /* Already done. */
3424 return;
3425
3426 p = options;
3427
3428 /* Return switch and non-switch args in order, regardless of
3429 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
3430 *p++ = '-';
3431
3432 for (i = 0; switches[i].c != '\0'; ++i)
3433 {
3434 long_options[i].name = (switches[i].long_name == 0 ? "" :
3435 switches[i].long_name);
3436 long_options[i].flag = 0;
3437 long_options[i].val = switches[i].c;
3438 if (short_option (switches[i].c))
3439 *p++ = switches[i].c;
3440 switch (switches[i].type)
3441 {
3442 case flag:
3443 case flag_off:
3444 case ignore:
3445 long_options[i].has_arg = no_argument;
3446 break;
3447
3448 case string:
3449 case strlist:
3450 case filename:
3451 case positive_int:
3452 case floating:
3453 if (short_option (switches[i].c))
3454 *p++ = ':';
3455 if (switches[i].noarg_value != 0)
3456 {
3457 if (short_option (switches[i].c))
3458 *p++ = ':';
3459 long_options[i].has_arg = optional_argument;
3460 }
3461 else
3462 long_options[i].has_arg = required_argument;
3463 break;
3464 }
3465 }
3466 *p = '\0';
3467 for (c = 0; c < (sizeof (long_option_aliases) /
3468 sizeof (long_option_aliases[0]));
3469 ++c)
3470 long_options[i++] = long_option_aliases[c];
3471 long_options[i].name = 0;
3472}
3473
3474
3475/* Non-option argument. It might be a variable definition. */
3476static void
3477handle_non_switch_argument (const char *arg, int env)
3478{
3479 struct variable *v;
3480
3481 if (arg[0] == '-' && arg[1] == '\0')
3482 /* Ignore plain '-' for compatibility. */
3483 return;
3484
3485#ifdef VMS
3486 {
3487 /* VMS DCL quoting can result in foo="bar baz" showing up here.
3488 Need to remove the double quotes from the value. */
3489 char * eq_ptr;
3490 char * new_arg;
3491 eq_ptr = strchr (arg, '=');
3492 if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
3493 {
3494 int len;
3495 int seg1;
3496 int seg2;
3497 len = strlen(arg);
3498 new_arg = alloca(len);
3499 seg1 = eq_ptr - arg + 1;
3500 strncpy(new_arg, arg, (seg1));
3501 seg2 = len - seg1 - 1;
3502 strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
3503 new_arg[seg1 + seg2] = 0;
3504 if (new_arg[seg1 + seg2 - 1] == '"')
3505 new_arg[seg1 + seg2 - 1] = 0;
3506 arg = new_arg;
3507 }
3508 }
3509#endif
3510 v = try_variable_definition (0, arg IF_WITH_VALUE_LENGTH_PARAM(NULL), o_command, 0);
3511 if (v != 0)
3512 {
3513 /* It is indeed a variable definition. If we don't already have this
3514 one, record a pointer to the variable for later use in
3515 define_makeflags. */
3516 struct command_variable *cv;
3517
3518 for (cv = command_variables; cv != 0; cv = cv->next)
3519 if (cv->variable == v)
3520 break;
3521
3522 if (! cv)
3523 {
3524 cv = xmalloc (sizeof (*cv));
3525 cv->variable = v;
3526 cv->next = command_variables;
3527 command_variables = cv;
3528 }
3529 }
3530 else if (! env)
3531 {
3532 /* Not an option or variable definition; it must be a goal
3533 target! Enter it as a file and add it to the dep chain of
3534 goals. */
3535 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
3536 f->cmd_target = 1;
3537
3538 if (goals == 0)
3539 {
3540 goals = alloc_goaldep ();
3541 lastgoal = goals;
3542 }
3543 else
3544 {
3545 lastgoal->next = alloc_goaldep ();
3546 lastgoal = lastgoal->next;
3547 }
3548
3549 lastgoal->file = f;
3550
3551 {
3552 /* Add this target name to the MAKECMDGOALS variable. */
3553 struct variable *gv;
3554 const char *value;
3555
3556 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
3557 if (gv == 0)
3558 value = f->name;
3559 else
3560 {
3561 /* Paste the old and new values together */
3562 unsigned int oldlen, newlen;
3563 char *vp;
3564
3565 oldlen = strlen (gv->value);
3566 newlen = strlen (f->name);
3567 vp = alloca (oldlen + 1 + newlen + 1);
3568 memcpy (vp, gv->value, oldlen);
3569 vp[oldlen] = ' ';
3570 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
3571 value = vp;
3572 }
3573 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
3574 }
3575 }
3576}
3577
3578/* Print a nice usage method. */
3579
3580static void
3581print_usage (int bad)
3582{
3583 const char *const *cpp;
3584 FILE *usageto;
3585
3586 if (print_version_flag)
3587 print_version ();
3588
3589 usageto = bad ? stderr : stdout;
3590
3591 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
3592
3593 for (cpp = usage; *cpp; ++cpp)
3594 fputs (_(*cpp), usageto);
3595
3596#ifdef KMK
3597 if (!remote_description || *remote_description == '\0')
3598 fprintf (usageto, _("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3599 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3600 else
3601 fprintf (usageto, _("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3602 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3603#else /* !KMK */
3604 if (!remote_description || *remote_description == '\0')
3605 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
3606 else
3607 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
3608 make_host, remote_description);
3609#endif /* !KMK */
3610
3611 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
3612}
3613
3614/* Decode switches from ARGC and ARGV.
3615 They came from the environment if ENV is nonzero. */
3616
3617static void
3618decode_switches (int argc, const char **argv, int env)
3619{
3620 int bad = 0;
3621 register const struct command_switch *cs;
3622 register struct stringlist *sl;
3623 register int c;
3624
3625 /* getopt does most of the parsing for us.
3626 First, get its vectors set up. */
3627
3628 init_switches ();
3629
3630 /* Let getopt produce error messages for the command line,
3631 but not for options from the environment. */
3632 opterr = !env;
3633 /* Reset getopt's state. */
3634 optind = 0;
3635
3636 while (optind < argc)
3637 {
3638 const char *coptarg;
3639
3640 /* Parse the next argument. */
3641 c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
3642 coptarg = optarg;
3643 if (c == EOF)
3644 /* End of arguments, or "--" marker seen. */
3645 break;
3646 else if (c == 1)
3647 /* An argument not starting with a dash. */
3648 handle_non_switch_argument (coptarg, env);
3649 else if (c == '?')
3650 /* Bad option. We will print a usage message and die later.
3651 But continue to parse the other options so the user can
3652 see all he did wrong. */
3653 bad = 1;
3654 else
3655 for (cs = switches; cs->c != '\0'; ++cs)
3656 if (cs->c == c)
3657 {
3658 /* Whether or not we will actually do anything with
3659 this switch. We test this individually inside the
3660 switch below rather than just once outside it, so that
3661 options which are to be ignored still consume args. */
3662 int doit = !env || cs->env;
3663
3664 switch (cs->type)
3665 {
3666 default:
3667 abort ();
3668
3669 case ignore:
3670 break;
3671
3672 case flag:
3673 case flag_off:
3674 if (doit)
3675 *(int *) cs->value_ptr = cs->type == flag;
3676 break;
3677
3678 case string:
3679 case strlist:
3680 case filename:
3681 if (!doit)
3682 break;
3683
3684 if (! coptarg)
3685 coptarg = xstrdup (cs->noarg_value);
3686 else if (*coptarg == '\0')
3687 {
3688 char opt[2] = "c";
3689 const char *op = opt;
3690
3691 if (short_option (cs->c))
3692 opt[0] = cs->c;
3693 else
3694 op = cs->long_name;
3695
3696 error (NILF, strlen (op),
3697 _("the '%s%s' option requires a non-empty string argument"),
3698 short_option (cs->c) ? "-" : "--", op);
3699 bad = 1;
3700 break;
3701 }
3702
3703 if (cs->type == string)
3704 {
3705 char **val = (char **)cs->value_ptr;
3706 free (*val);
3707 *val = xstrdup (coptarg);
3708 break;
3709 }
3710
3711 sl = *(struct stringlist **) cs->value_ptr;
3712 if (sl == 0)
3713 {
3714 sl = xmalloc (sizeof (struct stringlist));
3715 sl->max = 5;
3716 sl->idx = 0;
3717 sl->list = xmalloc (5 * sizeof (char *));
3718 *(struct stringlist **) cs->value_ptr = sl;
3719 }
3720 else if (sl->idx == sl->max - 1)
3721 {
3722 sl->max += 5;
3723 /* MSVC erroneously warns without a cast here. */
3724 sl->list = xrealloc ((void *)sl->list,
3725 sl->max * sizeof (char *));
3726 }
3727 if (cs->type == filename)
3728 sl->list[sl->idx++] = expand_command_line_file (coptarg);
3729 else
3730 sl->list[sl->idx++] = xstrdup (coptarg);
3731 sl->list[sl->idx] = 0;
3732 break;
3733
3734 case positive_int:
3735 /* See if we have an option argument; if we do require that
3736 it's all digits, not something like "10foo". */
3737 if (coptarg == 0 && argc > optind)
3738 {
3739 const char *cp;
3740 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3741 ;
3742 if (cp[0] == '\0')
3743 coptarg = argv[optind++];
3744 }
3745
3746 if (!doit)
3747 break;
3748
3749 if (coptarg)
3750 {
3751 int i = atoi (coptarg);
3752 const char *cp;
3753
3754 /* Yes, I realize we're repeating this in some cases. */
3755 for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
3756 ;
3757
3758 if (i < 1 || cp[0] != '\0')
3759 {
3760 error (NILF, 0,
3761 _("the '-%c' option requires a positive integer argument"),
3762 cs->c);
3763 bad = 1;
3764 }
3765 else
3766 *(unsigned int *) cs->value_ptr = i;
3767 }
3768 else
3769 *(unsigned int *) cs->value_ptr
3770 = *(unsigned int *) cs->noarg_value;
3771 break;
3772
3773#ifndef NO_FLOAT
3774 case floating:
3775 if (coptarg == 0 && optind < argc
3776 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3777 coptarg = argv[optind++];
3778
3779 if (doit)
3780 *(double *) cs->value_ptr
3781 = (coptarg != 0 ? atof (coptarg)
3782 : *(double *) cs->noarg_value);
3783
3784 break;
3785#endif
3786 }
3787
3788 /* We've found the switch. Stop looking. */
3789 break;
3790 }
3791 }
3792
3793 /* There are no more options according to getting getopt, but there may
3794 be some arguments left. Since we have asked for non-option arguments
3795 to be returned in order, this only happens when there is a "--"
3796 argument to prevent later arguments from being options. */
3797 while (optind < argc)
3798 handle_non_switch_argument (argv[optind++], env);
3799
3800 if (!env && (bad || print_usage_flag))
3801 {
3802 print_usage (bad);
3803 die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
3804 }
3805
3806 /* If there are any options that need to be decoded do it now. */
3807 decode_debug_flags ();
3808 decode_output_sync_flags ();
3809
3810#if defined (WINDOWS32) && defined (CONFIG_NEW_WIN_CHILDREN)
3811 /* validate the job object mode value . */
3812 if (win_job_object_mode == NULL)
3813 win_job_object_mode = xstrdup ("login");
3814 else if ( strcmp (win_job_object_mode, "none") != 0
3815 && strcmp (win_job_object_mode, "login") != 0
3816 && strcmp (win_job_object_mode, "root") != 0
3817 && strcmp (win_job_object_mode, "each") != 0)
3818 OS (fatal, NILF, _("unknown job object mode '%s'"), win_job_object_mode);
3819#endif
3820}
3821
3822/* Decode switches from environment variable ENVAR (which is LEN chars long).
3823 We do this by chopping the value into a vector of words, prepending a
3824 dash to the first word if it lacks one, and passing the vector to
3825 decode_switches. */
3826
3827static void
3828decode_env_switches (const char *envar, unsigned int len)
3829{
3830 char *varref = alloca (2 + len + 2);
3831 char *value, *p, *buf;
3832 int argc;
3833 const char **argv;
3834
3835 /* Get the variable's value. */
3836 varref[0] = '$';
3837 varref[1] = '(';
3838 memcpy (&varref[2], envar, len);
3839 varref[2 + len] = ')';
3840 varref[2 + len + 1] = '\0';
3841 value = variable_expand (varref);
3842
3843 /* Skip whitespace, and check for an empty value. */
3844 NEXT_TOKEN (value);
3845 len = strlen (value);
3846 if (len == 0)
3847 return;
3848
3849 /* Allocate a vector that is definitely big enough. */
3850 argv = alloca ((1 + len + 1) * sizeof (char *));
3851
3852 /* getopt will look at the arguments starting at ARGV[1].
3853 Prepend a spacer word. */
3854 argv[0] = 0;
3855 argc = 1;
3856
3857 /* We need a buffer to copy the value into while we split it into words
3858 and unquote it. Set up in case we need to prepend a dash later. */
3859 buf = alloca (1 + len + 1);
3860 buf[0] = '-';
3861 p = buf+1;
3862 argv[argc] = p;
3863 while (*value != '\0')
3864 {
3865 if (*value == '\\' && value[1] != '\0')
3866 ++value; /* Skip the backslash. */
3867 else if (ISBLANK (*value))
3868 {
3869 /* End of the word. */
3870 *p++ = '\0';
3871 argv[++argc] = p;
3872 do
3873 ++value;
3874 while (ISBLANK (*value));
3875 continue;
3876 }
3877 *p++ = *value++;
3878 }
3879 *p = '\0';
3880 argv[++argc] = 0;
3881 assert (p < buf + len + 2);
3882
3883 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3884 /* The first word doesn't start with a dash and isn't a variable
3885 definition, so add a dash. */
3886 argv[1] = buf;
3887
3888 /* Parse those words. */
3889 decode_switches (argc, argv, 1);
3890}
3891
3892
3893/* Quote the string IN so that it will be interpreted as a single word with
3894 no magic by decode_env_switches; also double dollar signs to avoid
3895 variable expansion in make itself. Write the result into OUT, returning
3896 the address of the next character to be written.
3897 Allocating space for OUT twice the length of IN is always sufficient. */
3898
3899static char *
3900quote_for_env (char *out, const char *in)
3901{
3902 while (*in != '\0')
3903 {
3904 if (*in == '$')
3905 *out++ = '$';
3906 else if (ISBLANK (*in) || *in == '\\')
3907 *out++ = '\\';
3908 *out++ = *in++;
3909 }
3910
3911 return out;
3912}
3913
3914/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3915 command switches. Include options with args if ALL is nonzero.
3916 Don't include options with the 'no_makefile' flag set if MAKEFILE. */
3917
3918static struct variable *
3919define_makeflags (int all, int makefile)
3920{
3921#ifdef KMK
3922 static const char ref[] = "$(KMK_OVERRIDES)";
3923#else
3924 static /*<- bird*/ const char ref[] = "$(MAKEOVERRIDES)";
3925#endif
3926 static /*<- bird*/ const char posixref[] = "$(-*-command-variables-*-)";
3927 static /*<- bird*/ const char evalref[] = "$(-*-eval-flags-*-)";
3928 const struct command_switch *cs;
3929 char *flagstring;
3930 char *p;
3931
3932 /* We will construct a linked list of 'struct flag's describing
3933 all the flags which need to go in MAKEFLAGS. Then, once we
3934 know how many there are and their lengths, we can put them all
3935 together in a string. */
3936
3937 struct flag
3938 {
3939 struct flag *next;
3940 const struct command_switch *cs;
3941 const char *arg;
3942 };
3943 struct flag *flags = 0;
3944 struct flag *last = 0;
3945 unsigned int flagslen = 0;
3946#define ADD_FLAG(ARG, LEN) \
3947 do { \
3948 struct flag *new = alloca (sizeof (struct flag)); \
3949 new->cs = cs; \
3950 new->arg = (ARG); \
3951 new->next = 0; \
3952 if (! flags) \
3953 flags = new; \
3954 else \
3955 last->next = new; \
3956 last = new; \
3957 if (new->arg == 0) \
3958 /* Just a single flag letter: " -x" */ \
3959 flagslen += 3; \
3960 else \
3961 /* " -xfoo", plus space to escape "foo". */ \
3962 flagslen += 1 + 1 + 1 + (3 * (LEN)); \
3963 if (!short_option (cs->c)) \
3964 /* This switch has no single-letter version, so we use the long. */ \
3965 flagslen += 2 + strlen (cs->long_name); \
3966 } while (0)
3967
3968 for (cs = switches; cs->c != '\0'; ++cs)
3969 if (cs->toenv && (!makefile || !cs->no_makefile))
3970 switch (cs->type)
3971 {
3972 case ignore:
3973 break;
3974
3975 case flag:
3976 case flag_off:
3977 if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3978 && (cs->default_value == 0
3979 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3980 ADD_FLAG (0, 0);
3981 break;
3982
3983 case positive_int:
3984 if (all)
3985 {
3986 if ((cs->default_value != 0
3987 && (*(unsigned int *) cs->value_ptr
3988 == *(unsigned int *) cs->default_value)))
3989 break;
3990 else if (cs->noarg_value != 0
3991 && (*(unsigned int *) cs->value_ptr ==
3992 *(unsigned int *) cs->noarg_value))
3993 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3994 else
3995 {
3996 char *buf = alloca (30);
3997 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3998 ADD_FLAG (buf, strlen (buf));
3999 }
4000 }
4001 break;
4002
4003#ifndef NO_FLOAT
4004 case floating:
4005 if (all)
4006 {
4007 if (cs->default_value != 0
4008 && (*(double *) cs->value_ptr
4009 == *(double *) cs->default_value))
4010 break;
4011 else if (cs->noarg_value != 0
4012 && (*(double *) cs->value_ptr
4013 == *(double *) cs->noarg_value))
4014 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
4015 else
4016 {
4017 char *buf = alloca (100);
4018 sprintf (buf, "%g", *(double *) cs->value_ptr);
4019 ADD_FLAG (buf, strlen (buf));
4020 }
4021 }
4022 break;
4023#endif
4024
4025 case string:
4026 if (all)
4027 {
4028 p = *((char **)cs->value_ptr);
4029 if (p)
4030 ADD_FLAG (p, strlen (p));
4031 }
4032 break;
4033
4034 case filename:
4035 case strlist:
4036 if (all)
4037 {
4038 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
4039 if (sl != 0)
4040 {
4041 unsigned int i;
4042 for (i = 0; i < sl->idx; ++i)
4043 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
4044 }
4045 }
4046 break;
4047
4048 default:
4049 abort ();
4050 }
4051
4052#undef ADD_FLAG
4053
4054 /* Four more for the possible " -- ", plus variable references. */
4055 flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
4056
4057 /* Construct the value in FLAGSTRING.
4058 We allocate enough space for a preceding dash and trailing null. */
4059 flagstring = alloca (1 + flagslen + 1);
4060 memset (flagstring, '\0', 1 + flagslen + 1);
4061 p = flagstring;
4062
4063 /* Start with a dash, for MFLAGS. */
4064 *p++ = '-';
4065
4066 /* Add simple options as a group. */
4067 while (flags != 0 && !flags->arg && short_option (flags->cs->c))
4068 {
4069 *p++ = flags->cs->c;
4070 flags = flags->next;
4071 }
4072
4073 /* Now add more complex flags: ones with options and/or long names. */
4074 while (flags)
4075 {
4076 *p++ = ' ';
4077 *p++ = '-';
4078
4079 /* Add the flag letter or name to the string. */
4080 if (short_option (flags->cs->c))
4081 *p++ = flags->cs->c;
4082 else
4083 {
4084 /* Long options require a double-dash. */
4085 *p++ = '-';
4086 strcpy (p, flags->cs->long_name);
4087 p += strlen (p);
4088 }
4089 /* An omitted optional argument has an ARG of "". */
4090 if (flags->arg && flags->arg[0] != '\0')
4091 {
4092 if (!short_option (flags->cs->c))
4093 /* Long options require '='. */
4094 *p++ = '=';
4095 p = quote_for_env (p, flags->arg);
4096 }
4097 flags = flags->next;
4098 }
4099
4100 /* If no flags at all, get rid of the initial dash. */
4101 if (p == &flagstring[1])
4102 {
4103 flagstring[0] = '\0';
4104 p = flagstring;
4105 }
4106
4107#ifdef KMK
4108 /* Define MFLAGS before appending variable definitions. Omit an initial
4109 empty dash. Since MFLAGS is not parsed for flags, there is no reason to
4110 override any makefile redefinition. */
4111 define_variable_cname ("MFLAGS",
4112 flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
4113 o_env, 1);
4114#endif /* !KMK */
4115
4116 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
4117 flag options. */
4118 if (eval_strings)
4119 {
4120 *p++ = ' ';
4121 memcpy (p, evalref, CSTRLEN (evalref));
4122 p += CSTRLEN (evalref);
4123 }
4124
4125 if (all && command_variables)
4126 {
4127 /* Write a reference to $(MAKEOVERRIDES), which contains all the
4128 command-line variable definitions. Separate the variables from the
4129 switches with a "--" arg. */
4130
4131 strcpy (p, " -- ");
4132 p += 4;
4133
4134 /* Copy in the string. */
4135 if (posix_pedantic)
4136 {
4137 memcpy (p, posixref, CSTRLEN (posixref));
4138 p += CSTRLEN (posixref);
4139 }
4140 else
4141 {
4142 memcpy (p, ref, CSTRLEN (ref));
4143 p += CSTRLEN (ref);
4144 }
4145 }
4146
4147 /* If there is a leading dash, omit it. */
4148 if (flagstring[0] == '-')
4149 ++flagstring;
4150
4151#ifdef KMK
4152 /* Provide simple access to some of the options. */
4153 {
4154 char val[32];
4155 sprintf (val, "%u", job_slots ? job_slots : master_job_slots);
4156 define_variable_cname ("KMK_OPTS_JOBS", val, o_default, 1);
4157 sprintf (val, "%u", default_job_slots);
4158 define_variable_cname ("KMK_OPTS_JOBS_DEFAULT", val, o_default, 1);
4159 define_variable_cname ("KMK_OPTS_KEEP_GOING", keep_going_flag ? "1" : "0", o_default, 1);
4160 define_variable_cname ("KMK_OPTS_JUST_PRINT", just_print_flag ? "1" : "0", o_default, 1);
4161 define_variable_cname ("KMK_OPTS_PRETTY_COMMAND_PRINTING",
4162 pretty_command_printing ? "1" : "0", o_default, 1);
4163 sprintf (val, "%u", process_priority);
4164 define_variable_cname ("KMK_OPTS_PRORITY", val, o_default, 1);
4165 sprintf (val, "%u", process_affinity);
4166 define_variable_cname ("KMK_OPTS_AFFINITY", val, o_default, 1);
4167# if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
4168 define_variable_cname ("KMK_OPTS_STATISTICS", make_expensive_statistics ? "1" : "0",
4169 o_default, 1);
4170# endif
4171# ifdef CONFIG_WITH_PRINT_TIME_SWITCH
4172 sprintf (val, "%u", print_time_min);
4173 define_variable_cname ("KMK_OPTS_PRINT_TIME", val, o_default, 1);
4174# endif
4175 }
4176#endif
4177
4178 /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
4179 Makefiles set MAKEFLAGS to add switches, but we still want to redefine
4180 its value with the full set of switches. Then we used o_file, but that
4181 lost when users added -e, causing a previous MAKEFLAGS env. var. to take
4182 precedence over the new one. Of course, an override or command
4183 definition will still take precedence. */
4184#ifdef KMK
4185 return define_variable_cname ("KMK_FLAGS", flagstring,
4186 env_overrides ? o_env_override : o_file, 1);
4187#else
4188 return define_variable_cname ("MAKEFLAGS", flagstring,
4189 env_overrides ? o_env_override : o_file, 1);
4190#endif
4191}
4192
4193
4194/* Print version information. */
4195
4196static void
4197print_version (void)
4198{
4199 static int printed_version = 0;
4200
4201 const char *precede = print_data_base_flag ? "# " : "";
4202
4203 if (printed_version)
4204 /* Do it only once. */
4205 return;
4206
4207#ifdef KMK
4208 printf ("%skmk - kBuild version %d.%d.%d (r%u)\n\
4209\n",
4210 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR,
4211 KBUILD_VERSION_PATCH, KBUILD_SVN_REV);
4212
4213 printf("%sBased on GNU Make %s:\n", precede, version_string);
4214
4215#else /* !KMK */
4216 printf ("%sGNU Make %s\n", precede, version_string);
4217
4218 if (!remote_description || *remote_description == '\0')
4219 printf (_("%sBuilt for %s\n"), precede, make_host);
4220 else
4221 printf (_("%sBuilt for %s (%s)\n"),
4222 precede, make_host, remote_description);
4223#endif /* !KMK */
4224
4225 /* Print this untranslated. The coding standards recommend translating the
4226 (C) to the copyright symbol, but this string is going to change every
4227 year, and none of the rest of it should be translated (including the
4228 word "Copyright"), so it hardly seems worth it. */
4229
4230 printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
4231 precede);
4232
4233 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
4234%sThis is free software: you are free to change and redistribute it.\n\
4235%sThere is NO WARRANTY, to the extent permitted by law.\n"),
4236 precede, precede, precede);
4237
4238#ifdef KMK
4239 printf ("\n\
4240%skBuild modifications:\n\
4241%s Copyright (c) 2005-2018 knut st. osmundsen.\n\
4242\n\
4243%skmkbuiltin commands derived from *BSD sources:\n\
4244%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
4245%s The Regents of the University of California. All rights reserved.\n\
4246%s Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>\n",
4247 precede, precede, precede, precede, precede, precede);
4248
4249# ifdef KBUILD_PATH
4250 printf (_("\n\
4251%sKBUILD_PATH: '%s' (default '%s')\n\
4252%sKBUILD_BIN_PATH: '%s' (default '%s')\n\
4253\n"),
4254 precede, get_kbuild_path(), KBUILD_PATH,
4255 precede, get_kbuild_bin_path(), KBUILD_BIN_PATH);
4256# else /* !KBUILD_PATH */
4257 printf ("\n\
4258%sKBUILD_PATH: '%s'\n\
4259%sKBUILD_BIN_PATH: '%s'\n\
4260\n",
4261 precede, get_kbuild_path(),
4262 precede, get_kbuild_bin_path());
4263# endif /* !KBUILD_PATH */
4264
4265 if (!remote_description || *remote_description == '\0')
4266 printf (_("%sThis program is a %s build, built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n\n"),
4267 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
4268 else
4269 printf (_("%sThis program is a %s build, built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n\n"),
4270 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
4271
4272#endif /* KMK */
4273
4274 printed_version = 1;
4275
4276 /* Flush stdout so the user doesn't have to wait to see the
4277 version information while make thinks about things. */
4278 fflush (stdout);
4279}
4280
4281/* Print a bunch of information about this and that. */
4282
4283static void
4284print_data_base (void)
4285{
4286 time_t when = time ((time_t *) 0);
4287
4288 print_version ();
4289
4290 printf (_("\n# Make data base, printed on %s"), ctime (&when));
4291
4292 print_variable_data_base ();
4293 print_dir_data_base ();
4294 print_rule_data_base ();
4295 print_file_data_base ();
4296 print_vpath_data_base ();
4297#ifdef KMK
4298 print_kbuild_data_base ();
4299#endif
4300#ifndef CONFIG_WITH_STRCACHE2
4301 strcache_print_stats ("#");
4302#else
4303 strcache2_print_stats_all ("#");
4304#endif
4305#ifdef CONFIG_WITH_ALLOC_CACHES
4306 alloccache_print_all ();
4307#endif
4308#ifdef CONFIG_WITH_COMPILER
4309 kmk_cc_print_stats ();
4310#endif
4311
4312 when = time ((time_t *) 0);
4313 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
4314}
4315#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
4316
4317static void
4318print_stats ()
4319{
4320 time_t when;
4321
4322 when = time ((time_t *) 0);
4323 printf (_("\n# Make statistics, printed on %s"), ctime (&when));
4324
4325 /* Allocators: */
4326# ifdef CONFIG_WITH_COMPILER
4327 kmk_cc_print_stats ();
4328# endif
4329# ifndef CONFIG_WITH_STRCACHE2
4330 strcache_print_stats ("#");
4331# else
4332 strcache2_print_stats_all ("#");
4333# endif
4334# ifdef CONFIG_WITH_ALLOC_CACHES
4335 alloccache_print_all ();
4336# endif
4337 print_heap_stats ();
4338
4339 /* Make stuff: */
4340 print_variable_stats ();
4341 print_file_stats ();
4342 print_dir_stats ();
4343# ifdef KMK
4344 print_kbuild_define_stats ();
4345# endif
4346# ifdef CONFIG_WITH_KMK_BUILTIN_STATS
4347 kmk_builtin_print_stats (stdout, "# ");
4348# endif
4349# ifdef CONFIG_WITH_COMPILER
4350 kmk_cc_print_stats ();
4351# endif
4352
4353 when = time ((time_t *) 0);
4354 printf (_("\n# Finished Make statistics on %s\n"), ctime (&when));
4355}
4356#endif /* CONFIG_WITH_PRINT_STATS_SWITCH */
4357
4358static void
4359clean_jobserver (int status)
4360{
4361 /* Sanity: have we written all our jobserver tokens back? If our
4362 exit status is 2 that means some kind of syntax error; we might not
4363 have written all our tokens so do that now. If tokens are left
4364 after any other error code, that's bad. */
4365
4366 if (jobserver_enabled() && jobserver_tokens)
4367 {
4368 if (status != 2)
4369 ON (error, NILF,
4370 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
4371 jobserver_tokens);
4372 else
4373 /* Don't write back the "free" token */
4374 while (--jobserver_tokens)
4375 jobserver_release (0);
4376 }
4377
4378
4379 /* Sanity: If we're the master, were all the tokens written back? */
4380
4381 if (master_job_slots)
4382 {
4383 /* We didn't write one for ourself, so start at 1. */
4384 unsigned int tokens = 1 + jobserver_acquire_all ();
4385
4386 if (tokens != master_job_slots)
4387 ONN (error, NILF,
4388 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
4389 tokens, master_job_slots);
4390
4391 reset_jobserver ();
4392 }
4393}
4394
4395
4396/* Exit with STATUS, cleaning up as necessary. */
4397
4398void
4399#ifdef KMK
4400die_with_job_output (int status, struct output *out)
4401#else
4402die (int status)
4403#endif
4404{
4405 static char dying = 0;
4406#ifdef KMK
4407 static char need_2nd_error = 0;
4408 static char need_2nd_error_output = 0;
4409#endif
4410
4411 if (!dying)
4412 {
4413 int err;
4414
4415 dying = 1;
4416
4417 if (print_version_flag)
4418 print_version ();
4419
4420#ifdef KMK
4421 /* Flag 2nd error message. */
4422 if (status != 0
4423 && ( job_slots_used > 0
4424 || print_data_base_flag
4425 || print_stats_flag))
4426 {
4427 need_2nd_error = 1;
4428 need_2nd_error_output = job_slots_used >= 2
4429 && out != NULL
4430 && out != &make_sync;
4431 if (need_2nd_error_output)
4432 output_metered = 0;
4433 }
4434#endif /* KMK */
4435
4436 /* Wait for children to die. */
4437 err = (status != 0);
4438 while (job_slots_used > 0)
4439 reap_children (1, err);
4440
4441 /* Let the remote job module clean up its state. */
4442 remote_cleanup ();
4443
4444 /* Remove the intermediate files. */
4445 remove_intermediates (0);
4446
4447 if (print_data_base_flag)
4448 print_data_base ();
4449
4450#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
4451 if (print_stats_flag)
4452 print_stats ();
4453#endif
4454 if (verify_flag)
4455 verify_file_data_base ();
4456
4457#ifdef NDEBUG /* bird: Don't waste time on debug sanity checks. */
4458 if (print_data_base_flag || db_level)
4459#endif
4460 verify_file_data_base ();
4461
4462 clean_jobserver (status);
4463
4464 if (output_context)
4465 {
4466 /* die() might be called in a recipe output context due to an
4467 $(error ...) function. */
4468 output_close (output_context);
4469
4470 if (output_context != &make_sync)
4471 output_close (&make_sync);
4472
4473 OUTPUT_UNSET ();
4474 }
4475
4476 output_close (NULL);
4477
4478 /* Try to move back to the original directory. This is essential on
4479 MS-DOS (where there is really only one process), and on Unix it
4480 puts core files in the original directory instead of the -C
4481 directory. Must wait until after remove_intermediates(), or unlinks
4482 of relative pathnames fail. */
4483 if (directory_before_chdir != 0)
4484 {
4485 /* If it fails we don't care: shut up GCC. */
4486 int _x UNUSED;
4487 _x = chdir (directory_before_chdir);
4488 }
4489
4490#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
4491 if (print_time_min != -1)
4492 {
4493 big_int elapsed = nano_timestamp () - make_start_ts;
4494 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
4495 {
4496 char buf[64];
4497 format_elapsed_nano (buf, sizeof (buf), elapsed);
4498 message (1, strlen (buf), _("%*s"), print_time_width, buf);
4499 }
4500 }
4501#endif
4502 }
4503
4504#ifdef KMK
4505 /* The failure might be lost in a -j <lots> run, so mention the
4506 failure again before exiting. */
4507 if (need_2nd_error != 0)
4508 ON (error, NILF, _("*** Exiting with status %d"), status);
4509 if (out)
4510 {
4511 out->dont_truncate = 0;
4512 if (need_2nd_error_output && output_metered > 20)
4513 output_dump (out);
4514 else
4515 output_reset (out);
4516 output_close (out);
4517 }
4518#endif
4519
4520 exit (status);
4521}
4522
4523#ifdef KMK
4524void die (int status)
4525{
4526 die_with_job_output (status, NULL);
4527}
4528#endif
Note: See TracBrowser for help on using the repository browser.