VirtualBox

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

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

kmk/winchildren: Use windows job objects to terminate all orphaned children when the topmost kmk process terminates. There are a couple of command line options to disable/tweak this behaviour.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use