VirtualBox

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

Last change on this file since 3122 was 3122, checked in by bird, 8 years ago

kmk/main.c: GetErrorMode was missing in windows 2000 thru w2k3, so use SetErrorMode(0) instead.

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

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