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

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

kmk,kWorker: More aggressive handling of --nice (and --priority) on windows.

  • Property svn:eol-style set to native
File size: 117.9 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 /* start off assuming we have no shell */
1417 unixy_shell = 0;
1418 no_default_sh_exe = 1;
1419#endif
1420# ifdef CONFIG_WITH_FAST_IS_SPACE /* bird */
1421 memset (space_map, '\0', sizeof(space_map));
1422 set_space_map_entry (' ');
1423 set_space_map_entry ('\f');
1424 set_space_map_entry ('\n');
1425 set_space_map_entry ('\r');
1426 set_space_map_entry ('\t');
1427 set_space_map_entry ('\v');
1428# endif /* CONFIG_WITH_FAST_IS_SPACE */
1429
1430#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1431 make_start_ts = nano_timestamp ();
1432#endif
1433
1434#ifdef SET_STACK_SIZE
1435 /* Get rid of any avoidable limit on stack size. */
1436 {
1437 struct rlimit rlim;
1438
1439 /* Set the stack limit huge so that alloca does not fail. */
1440 if (getrlimit (RLIMIT_STACK, &rlim) == 0
1441 && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
1442 {
1443 stack_limit = rlim;
1444 rlim.rlim_cur = rlim.rlim_max;
1445 setrlimit (RLIMIT_STACK, &rlim);
1446 }
1447 else
1448 stack_limit.rlim_cur = 0;
1449 }
1450#endif
1451
1452#ifdef HAVE_ATEXIT
1453 atexit (close_stdout);
1454#endif
1455
1456 /* Needed for OS/2 */
1457 initialize_main(&argc, &argv);
1458
1459#ifdef KMK
1460 init_kbuild (argc, argv);
1461#endif
1462
1463 reading_file = 0;
1464
1465#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1466 /* Request the most powerful version of `system', to
1467 make up for the dumb default shell. */
1468 __system_flags = (__system_redirect
1469 | __system_use_shell
1470 | __system_allow_multiple_cmds
1471 | __system_allow_long_cmds
1472 | __system_handle_null_commands
1473 | __system_emulate_chdir);
1474
1475#endif
1476
1477 /* Set up gettext/internationalization support. */
1478 setlocale (LC_ALL, "");
1479 /* The cast to void shuts up compiler warnings on systems that
1480 disable NLS. */
1481#ifdef LOCALEDIR /* bird */
1482 (void)bindtextdomain (PACKAGE, LOCALEDIR);
1483 (void)textdomain (PACKAGE);
1484#endif
1485
1486#ifdef POSIX
1487 sigemptyset (&fatal_signal_set);
1488#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1489#else
1490#ifdef HAVE_SIGSETMASK
1491 fatal_signal_mask = 0;
1492#define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1493#else
1494#define ADD_SIG(sig) (void)sig /* Needed to avoid warnings in MSVC. */
1495#endif
1496#endif
1497
1498#define FATAL_SIG(sig) \
1499 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1500 bsd_signal (sig, SIG_IGN); \
1501 else \
1502 ADD_SIG (sig);
1503
1504#ifdef SIGHUP
1505 FATAL_SIG (SIGHUP);
1506#endif
1507#ifdef SIGQUIT
1508 FATAL_SIG (SIGQUIT);
1509#endif
1510 FATAL_SIG (SIGINT);
1511 FATAL_SIG (SIGTERM);
1512
1513#ifdef __MSDOS__
1514 /* Windows 9X delivers FP exceptions in child programs to their
1515 parent! We don't want Make to die when a child divides by zero,
1516 so we work around that lossage by catching SIGFPE. */
1517 FATAL_SIG (SIGFPE);
1518#endif
1519
1520#ifdef SIGDANGER
1521 FATAL_SIG (SIGDANGER);
1522#endif
1523#ifdef SIGXCPU
1524 FATAL_SIG (SIGXCPU);
1525#endif
1526#ifdef SIGXFSZ
1527 FATAL_SIG (SIGXFSZ);
1528#endif
1529
1530#ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1531 /* bird: dispatch signals in our own way to try avoid deadlocks. */
1532 g_tidMainThread = GetCurrentThreadId ();
1533 SetConsoleCtrlHandler (ctrl_event, TRUE);
1534#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1535
1536#undef FATAL_SIG
1537
1538 /* Do not ignore the child-death signal. This must be done before
1539 any children could possibly be created; otherwise, the wait
1540 functions won't work on systems with the SVR4 ECHILD brain
1541 damage, if our invoker is ignoring this signal. */
1542
1543#ifdef HAVE_WAIT_NOHANG
1544# if defined SIGCHLD
1545 (void) bsd_signal (SIGCHLD, SIG_DFL);
1546# endif
1547# if defined SIGCLD && SIGCLD != SIGCHLD
1548 (void) bsd_signal (SIGCLD, SIG_DFL);
1549# endif
1550#endif
1551
1552 /* Make sure stdout is line-buffered. */
1553
1554#ifdef HAVE_SETVBUF
1555# ifdef SETVBUF_REVERSED
1556 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
1557# else /* setvbuf not reversed. */
1558 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
1559 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
1560# endif /* setvbuf reversed. */
1561#elif HAVE_SETLINEBUF
1562 setlinebuf (stdout);
1563#endif /* setlinebuf missing. */
1564
1565 /* Figure out where this program lives. */
1566
1567 if (argv[0] == 0)
1568 argv[0] = "";
1569 if (argv[0][0] == '\0')
1570#ifdef KMK
1571 program = "kmk";
1572#else
1573 program = "make";
1574#endif
1575 else
1576 {
1577#ifdef VMS
1578 program = strrchr (argv[0], ']');
1579#else
1580 program = strrchr (argv[0], '/');
1581#endif
1582#if defined(__MSDOS__) || defined(__EMX__)
1583 if (program == 0)
1584 program = strrchr (argv[0], '\\');
1585 else
1586 {
1587 /* Some weird environments might pass us argv[0] with
1588 both kinds of slashes; we must find the rightmost. */
1589 char *p = strrchr (argv[0], '\\');
1590 if (p && p > program)
1591 program = p;
1592 }
1593 if (program == 0 && argv[0][1] == ':')
1594 program = argv[0] + 1;
1595#endif
1596#ifdef WINDOWS32
1597 if (program == 0)
1598 {
1599 /* Extract program from full path */
1600 int argv0_len;
1601 program = strrchr (argv[0], '\\');
1602 if (program)
1603 {
1604 argv0_len = strlen(program);
1605 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1606 /* Remove .exe extension */
1607 program[argv0_len - 4] = '\0';
1608 }
1609 }
1610#endif
1611 if (program == 0)
1612 program = argv[0];
1613 else
1614 ++program;
1615 }
1616
1617 /* Set up to access user data (files). */
1618 user_access ();
1619
1620# ifdef CONFIG_WITH_COMPILER
1621 kmk_cc_init ();
1622# endif
1623#ifdef CONFIG_WITH_ALLOC_CACHES
1624 initialize_global_alloc_caches ();
1625#endif
1626 initialize_global_hash_tables ();
1627#ifdef KMK
1628 init_kbuild_object ();
1629#endif
1630
1631 /* Figure out where we are. */
1632
1633#ifdef WINDOWS32
1634 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1635#else
1636 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1637#endif
1638 {
1639#ifdef HAVE_GETCWD
1640 perror_with_name ("getcwd", "");
1641#else
1642 error (NILF, "getwd: %s", current_directory);
1643#endif
1644 current_directory[0] = '\0';
1645 directory_before_chdir = 0;
1646 }
1647 else
1648 directory_before_chdir = xstrdup (current_directory);
1649#ifdef __MSDOS__
1650 /* Make sure we will return to the initial directory, come what may. */
1651 atexit (msdos_return_to_initial_directory);
1652#endif
1653
1654 /* Initialize the special variables. */
1655 define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
1656 /* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
1657 define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
1658 define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
1659
1660 /* Set up .FEATURES
1661 We must do this in multiple calls because define_variable_cname() is
1662 a macro and some compilers (MSVC) don't like conditionals in macros. */
1663 {
1664 const char *features = "target-specific order-only second-expansion"
1665 " else-if shortest-stem undefine"
1666#ifndef NO_ARCHIVES
1667 " archives"
1668#endif
1669#ifdef MAKE_JOBSERVER
1670 " jobserver"
1671#endif
1672#ifdef MAKE_SYMLINKS
1673 " check-symlink"
1674#endif
1675#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1676 " explicit-multitarget"
1677#endif
1678#ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
1679 " prepend-assignment"
1680#endif
1681 ;
1682
1683 define_variable_cname (".FEATURES", features, o_default, 0);
1684 }
1685
1686#ifdef KMK
1687 /* Initialize the default number of jobs to the cpu/core/smt count. */
1688 default_job_slots = job_slots = get_online_cpu_count ();
1689#endif /* KMK */
1690
1691 /* Read in variables from the environment. It is important that this be
1692 done before $(MAKE) is figured out so its definitions will not be
1693 from the environment. */
1694
1695#ifndef _AMIGA
1696 {
1697 unsigned int i;
1698
1699 for (i = 0; envp[i] != 0; ++i)
1700 {
1701 int do_not_define = 0;
1702 char *ep = envp[i];
1703
1704 while (*ep != '\0' && *ep != '=')
1705 ++ep;
1706#ifdef WINDOWS32
1707 if (!unix_path && strneq(envp[i], "PATH=", 5))
1708 unix_path = ep+1;
1709 else if (!strnicmp(envp[i], "Path=", 5)) {
1710 do_not_define = 1; /* it gets defined after loop exits */
1711 if (!windows32_path)
1712 windows32_path = ep+1;
1713 }
1714#endif
1715 /* The result of pointer arithmetic is cast to unsigned int for
1716 machines where ptrdiff_t is a different size that doesn't widen
1717 the same. */
1718 if (!do_not_define)
1719 {
1720 struct variable *v;
1721
1722 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1723 ep + 1, o_env, 1);
1724 /* Force exportation of every variable culled from the
1725 environment. We used to rely on target_environment's
1726 v_default code to do this. But that does not work for the
1727 case where an environment variable is redefined in a makefile
1728 with `override'; it should then still be exported, because it
1729 was originally in the environment. */
1730 v->export = v_export;
1731
1732 /* Another wrinkle is that POSIX says the value of SHELL set in
1733 the makefile won't change the value of SHELL given to
1734 subprocesses. */
1735 if (streq (v->name, "SHELL"))
1736 {
1737#ifndef __MSDOS__
1738 v->export = v_noexport;
1739#endif
1740#ifndef CONFIG_WITH_STRCACHE2
1741 shell_var.name = "SHELL";
1742#else
1743 shell_var.name = v->name;
1744#endif
1745 shell_var.length = 5;
1746#ifndef CONFIG_WITH_VALUE_LENGTH
1747 shell_var.value = xstrdup (ep + 1);
1748#else
1749 shell_var.value = xstrndup (v->value, v->value_length);
1750 shell_var.value_length = v->value_length;
1751#endif
1752 }
1753
1754 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1755 if (streq (v->name, "MAKE_RESTARTS"))
1756 {
1757 v->export = v_noexport;
1758 restarts = (unsigned int) atoi (ep + 1);
1759 }
1760 }
1761 }
1762 }
1763#ifdef WINDOWS32
1764 /* If we didn't find a correctly spelled PATH we define PATH as
1765 * either the first mispelled value or an empty string
1766 */
1767 if (!unix_path)
1768 define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1769 o_env, 1)->export = v_export;
1770#endif
1771#else /* For Amiga, read the ENV: device, ignoring all dirs */
1772 {
1773 BPTR env, file, old;
1774 char buffer[1024];
1775 int len;
1776 __aligned struct FileInfoBlock fib;
1777
1778 env = Lock ("ENV:", ACCESS_READ);
1779 if (env)
1780 {
1781 old = CurrentDir (DupLock(env));
1782 Examine (env, &fib);
1783
1784 while (ExNext (env, &fib))
1785 {
1786 if (fib.fib_DirEntryType < 0) /* File */
1787 {
1788 /* Define an empty variable. It will be filled in
1789 variable_lookup(). Makes startup quite a bit
1790 faster. */
1791 define_variable (fib.fib_FileName,
1792 strlen (fib.fib_FileName),
1793 "", o_env, 1)->export = v_export;
1794 }
1795 }
1796 UnLock (env);
1797 UnLock(CurrentDir(old));
1798 }
1799 }
1800#endif
1801
1802 /* Decode the switches. */
1803
1804#ifdef KMK
1805 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
1806#else /* !KMK */
1807 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1808#if 0
1809 /* People write things like:
1810 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1811 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1812 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1813#endif
1814#endif /* !KMK */
1815
1816 decode_switches (argc, argv, 0);
1817
1818#ifdef WINDOWS32
1819 if (suspend_flag) {
1820 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1821 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1822 Sleep(30 * 1000);
1823 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1824 }
1825#endif
1826
1827 decode_debug_flags ();
1828
1829#ifdef KMK
1830 set_make_priority_and_affinity ();
1831#endif
1832
1833 /* Set always_make_flag if -B was given and we've not restarted already. */
1834 always_make_flag = always_make_set && (restarts == 0);
1835
1836 /* Print version information. */
1837 if (print_version_flag || print_data_base_flag || db_level)
1838 {
1839 print_version ();
1840
1841 /* `make --version' is supposed to just print the version and exit. */
1842 if (print_version_flag)
1843 die (0);
1844 }
1845
1846#ifndef VMS
1847 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1848 (If it is a relative pathname with a slash, prepend our directory name
1849 so the result will run the same program regardless of the current dir.
1850 If it is a name with no slash, we can only hope that PATH did not
1851 find it in the current directory.) */
1852#ifdef WINDOWS32
1853 /*
1854 * Convert from backslashes to forward slashes for
1855 * programs like sh which don't like them. Shouldn't
1856 * matter if the path is one way or the other for
1857 * CreateProcess().
1858 */
1859 if (strpbrk(argv[0], "/:\\") ||
1860 strstr(argv[0], "..") ||
1861 strneq(argv[0], "//", 2))
1862 argv[0] = xstrdup(w32ify(argv[0],1));
1863#else /* WINDOWS32 */
1864#if defined (__MSDOS__) || defined (__EMX__)
1865 if (strchr (argv[0], '\\'))
1866 {
1867 char *p;
1868
1869 argv[0] = xstrdup (argv[0]);
1870 for (p = argv[0]; *p; p++)
1871 if (*p == '\\')
1872 *p = '/';
1873 }
1874 /* If argv[0] is not in absolute form, prepend the current
1875 directory. This can happen when Make is invoked by another DJGPP
1876 program that uses a non-absolute name. */
1877 if (current_directory[0] != '\0'
1878 && argv[0] != 0
1879 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1880# ifdef __EMX__
1881 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1882 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1883# endif
1884 )
1885 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1886#else /* !__MSDOS__ */
1887 if (current_directory[0] != '\0'
1888 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1889#ifdef HAVE_DOS_PATHS
1890 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1891 && strchr (argv[0], '\\') != 0
1892#endif
1893 )
1894 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1895#endif /* !__MSDOS__ */
1896#endif /* WINDOWS32 */
1897#endif
1898
1899 /* The extra indirection through $(MAKE_COMMAND) is done
1900 for hysterical raisins. */
1901 define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1902 define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1903#ifdef KMK
1904 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1905#endif
1906
1907 if (command_variables != 0)
1908 {
1909 struct command_variable *cv;
1910 struct variable *v;
1911 unsigned int len = 0;
1912 char *value, *p;
1913
1914 /* Figure out how much space will be taken up by the command-line
1915 variable definitions. */
1916 for (cv = command_variables; cv != 0; cv = cv->next)
1917 {
1918 v = cv->variable;
1919 len += 2 * strlen (v->name);
1920 if (! v->recursive)
1921 ++len;
1922 ++len;
1923 len += 2 * strlen (v->value);
1924 ++len;
1925 }
1926
1927 /* Now allocate a buffer big enough and fill it. */
1928 p = value = alloca (len);
1929 for (cv = command_variables; cv != 0; cv = cv->next)
1930 {
1931 v = cv->variable;
1932 p = quote_for_env (p, v->name);
1933 if (! v->recursive)
1934 *p++ = ':';
1935 *p++ = '=';
1936 p = quote_for_env (p, v->value);
1937 *p++ = ' ';
1938 }
1939 p[-1] = '\0'; /* Kill the final space and terminate. */
1940
1941 /* Define an unchangeable variable with a name that no POSIX.2
1942 makefile could validly use for its own variable. */
1943 define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
1944
1945 /* Define the variable; this will not override any user definition.
1946 Normally a reference to this variable is written into the value of
1947 MAKEFLAGS, allowing the user to override this value to affect the
1948 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1949 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1950 a reference to this hidden variable is written instead. */
1951#ifdef KMK
1952 define_variable_cname ("KMK_OVERRIDES", "${-*-command-variables-*-}",
1953 o_env, 1);
1954#else
1955 define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
1956 o_env, 1);
1957#endif
1958 }
1959
1960 /* If there were -C flags, move ourselves about. */
1961 if (directories != 0)
1962 {
1963 unsigned int i;
1964 for (i = 0; directories->list[i] != 0; ++i)
1965 {
1966 const char *dir = directories->list[i];
1967#ifdef WINDOWS32
1968 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1969 But allow -C/ just in case someone wants that. */
1970 {
1971 char *p = (char *)dir + strlen (dir) - 1;
1972 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1973 --p;
1974 p[1] = '\0';
1975 }
1976#endif
1977 if (chdir (dir) < 0)
1978 pfatal_with_name (dir);
1979 }
1980 }
1981
1982#ifdef KMK
1983 /* Check for [Mm]akefile.kup and change directory when found.
1984 Makefile.kmk overrides Makefile.kup but not plain Makefile.
1985 If no -C arguments were given, fake one to indicate chdir. */
1986 if (makefiles == 0)
1987 {
1988 struct stat st;
1989 if (( ( stat ("Makefile.kup", &st) == 0
1990 && S_ISREG (st.st_mode) )
1991 || ( stat ("makefile.kup", &st) == 0
1992 && S_ISREG (st.st_mode) ) )
1993 && stat ("Makefile.kmk", &st) < 0
1994 && stat ("makefile.kmk", &st) < 0)
1995 {
1996 static char fake_path[3*16 + 32] = "..";
1997 char *cur = &fake_path[2];
1998 int up_levels = 1;
1999 while (up_levels < 16)
2000 {
2001 /* File with higher precedence.s */
2002 strcpy (cur, "/Makefile.kmk");
2003 if (stat (fake_path, &st) == 0)
2004 break;
2005 strcpy (cur, "/makefile.kmk");
2006 if (stat (fake_path, &st) == 0)
2007 break;
2008
2009 /* the .kup files */
2010 strcpy (cur, "/Makefile.kup");
2011 if ( stat (fake_path, &st) != 0
2012 || !S_ISREG (st.st_mode))
2013 {
2014 strcpy (cur, "/makefile.kup");
2015 if ( stat (fake_path, &st) != 0
2016 || !S_ISREG (st.st_mode))
2017 break;
2018 }
2019
2020 /* ok */
2021 strcpy (cur, "/..");
2022 cur += 3;
2023 up_levels++;
2024 }
2025
2026 if (up_levels >= 16)
2027 fatal (NILF, _("Makefile.kup recursion is too deep."));
2028
2029 /* attempt to change to the directory. */
2030 *cur = '\0';
2031 if (chdir (fake_path) < 0)
2032 pfatal_with_name (fake_path);
2033
2034 /* add the string to the directories. */
2035 if (!directories)
2036 {
2037 directories = xmalloc (sizeof(*directories));
2038 directories->list = xmalloc (5 * sizeof (char *));
2039 directories->max = 5;
2040 directories->idx = 0;
2041 }
2042 else if (directories->idx == directories->max - 1)
2043 {
2044 directories->max += 5;
2045 directories->list = xrealloc ((void *)directories->list,
2046 directories->max * sizeof (char *));
2047 }
2048 directories->list[directories->idx++] = fake_path;
2049 }
2050 }
2051#endif /* KMK */
2052
2053#ifdef WINDOWS32
2054 /*
2055 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
2056 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
2057 *
2058 * The functions in dir.c can incorrectly cache information for "."
2059 * before we have changed directory and this can cause file
2060 * lookups to fail because the current directory (.) was pointing
2061 * at the wrong place when it was first evaluated.
2062 */
2063#ifdef KMK /* this is really a candidate for all platforms... */
2064 {
2065 extern char *default_shell;
2066 const char *bin = get_kbuild_bin_path();
2067 size_t len = strlen (bin);
2068 default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
2069 memcpy (default_shell, bin, len);
2070 strcpy (default_shell + len, "/kmk_ash.exe");
2071 no_default_sh_exe = 0;
2072 batch_mode_shell = 1;
2073 }
2074#else /* !KMK */
2075 no_default_sh_exe = !find_and_set_default_shell(NULL);
2076#endif /* !KMK */
2077#endif /* WINDOWS32 */
2078 /* Figure out the level of recursion. */
2079 {
2080 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
2081 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
2082 makelevel = (unsigned int) atoi (v->value);
2083 else
2084 makelevel = 0;
2085 }
2086
2087 /* Except under -s, always do -w in sub-makes and under -C. */
2088 if (!silent_flag && (directories != 0 || makelevel > 0))
2089 print_directory_flag = 1;
2090
2091 /* Let the user disable that with --no-print-directory. */
2092 if (inhibit_print_directory_flag)
2093 print_directory_flag = 0;
2094
2095 /* If -R was given, set -r too (doesn't make sense otherwise!) */
2096 if (no_builtin_variables_flag)
2097 no_builtin_rules_flag = 1;
2098
2099 /* Construct the list of include directories to search. */
2100
2101 construct_include_path (include_directories == 0
2102 ? 0 : include_directories->list);
2103
2104 /* Figure out where we are now, after chdir'ing. */
2105 if (directories == 0)
2106 /* We didn't move, so we're still in the same place. */
2107 starting_directory = current_directory;
2108 else
2109 {
2110#ifdef WINDOWS32
2111 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
2112#else
2113 if (getcwd (current_directory, GET_PATH_MAX) == 0)
2114#endif
2115 {
2116#ifdef HAVE_GETCWD
2117 perror_with_name ("getcwd", "");
2118#else
2119 error (NILF, "getwd: %s", current_directory);
2120#endif
2121 starting_directory = 0;
2122 }
2123 else
2124 starting_directory = current_directory;
2125 }
2126
2127 define_variable_cname ("CURDIR", current_directory, o_file, 0);
2128
2129 /* Read any stdin makefiles into temporary files. */
2130
2131 if (makefiles != 0)
2132 {
2133 unsigned int i;
2134 for (i = 0; i < makefiles->idx; ++i)
2135 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
2136 {
2137 /* This makefile is standard input. Since we may re-exec
2138 and thus re-read the makefiles, we read standard input
2139 into a temporary file and read from that. */
2140 FILE *outfile;
2141 char *template, *tmpdir;
2142
2143 if (stdin_nm)
2144 fatal (NILF, _("Makefile from standard input specified twice."));
2145
2146#ifdef VMS
2147# define DEFAULT_TMPDIR "sys$scratch:"
2148#else
2149# ifdef P_tmpdir
2150# define DEFAULT_TMPDIR P_tmpdir
2151# else
2152# define DEFAULT_TMPDIR "/tmp"
2153# endif
2154#endif
2155#define DEFAULT_TMPFILE "GmXXXXXX"
2156
2157 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
2158#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2159 /* These are also used commonly on these platforms. */
2160 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
2161 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
2162#endif
2163 )
2164 tmpdir = DEFAULT_TMPDIR;
2165
2166 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
2167 strcpy (template, tmpdir);
2168
2169#ifdef HAVE_DOS_PATHS
2170 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
2171 strcat (template, "/");
2172#else
2173# ifndef VMS
2174 if (template[strlen (template) - 1] != '/')
2175 strcat (template, "/");
2176# endif /* !VMS */
2177#endif /* !HAVE_DOS_PATHS */
2178
2179 strcat (template, DEFAULT_TMPFILE);
2180 outfile = open_tmpfile (&stdin_nm, template);
2181 if (outfile == 0)
2182 pfatal_with_name (_("fopen (temporary file)"));
2183 while (!feof (stdin) && ! ferror (stdin))
2184 {
2185 char buf[2048];
2186 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
2187 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2188 pfatal_with_name (_("fwrite (temporary file)"));
2189 }
2190 fclose (outfile);
2191
2192 /* Replace the name that read_all_makefiles will
2193 see with the name of the temporary file. */
2194 makefiles->list[i] = strcache_add (stdin_nm);
2195
2196 /* Make sure the temporary file will not be remade. */
2197 {
2198 struct file *f = enter_file (strcache_add (stdin_nm));
2199 f->updated = 1;
2200 f->update_status = 0;
2201 f->command_state = cs_finished;
2202 /* Can't be intermediate, or it'll be removed too early for
2203 make re-exec. */
2204 f->intermediate = 0;
2205 f->dontcare = 0;
2206 }
2207 }
2208 }
2209
2210#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
2211#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
2212 /* Set up to handle children dying. This must be done before
2213 reading in the makefiles so that `shell' function calls will work.
2214
2215 If we don't have a hanging wait we have to fall back to old, broken
2216 functionality here and rely on the signal handler and counting
2217 children.
2218
2219 If we're using the jobs pipe we need a signal handler so that
2220 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
2221 jobserver pipe in job.c if we're waiting for a token.
2222
2223 If none of these are true, we don't need a signal handler at all. */
2224 {
2225 RETSIGTYPE child_handler (int sig);
2226# if defined SIGCHLD
2227 bsd_signal (SIGCHLD, child_handler);
2228# endif
2229# if defined SIGCLD && SIGCLD != SIGCHLD
2230 bsd_signal (SIGCLD, child_handler);
2231# endif
2232 }
2233#endif
2234#endif
2235
2236 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2237#ifdef SIGUSR1
2238 bsd_signal (SIGUSR1, debug_signal_handler);
2239#endif
2240
2241 /* Define the initial list of suffixes for old-style rules. */
2242
2243 set_default_suffixes ();
2244
2245 /* Define the file rules for the built-in suffix rules. These will later
2246 be converted into pattern rules. We used to do this in
2247 install_default_implicit_rules, but since that happens after reading
2248 makefiles, it results in the built-in pattern rules taking precedence
2249 over makefile-specified suffix rules, which is wrong. */
2250
2251 install_default_suffix_rules ();
2252
2253 /* Define some internal and special variables. */
2254
2255 define_automatic_variables ();
2256
2257 /* Set up the MAKEFLAGS and MFLAGS variables
2258 so makefiles can look at them. */
2259
2260 define_makeflags (0, 0);
2261
2262 /* Define the default variables. */
2263 define_default_variables ();
2264
2265 default_file = enter_file (strcache_add (".DEFAULT"));
2266
2267 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
2268
2269 /* Evaluate all strings provided with --eval.
2270 Also set up the $(-*-eval-flags-*-) variable. */
2271
2272 if (eval_strings)
2273 {
2274 char *p, *value;
2275 unsigned int i;
2276 unsigned int len = sizeof ("--eval=") * eval_strings->idx;
2277
2278 for (i = 0; i < eval_strings->idx; ++i)
2279 {
2280#ifndef CONFIG_WITH_VALUE_LENGTH
2281 p = xstrdup (eval_strings->list[i]);
2282 len += 2 * strlen (p);
2283 eval_buffer (p);
2284#else
2285 unsigned int sub_len = strlen(eval_strings->list[i]);
2286 p = xstrndup (eval_strings->list[i], sub_len);
2287 len += 2 * sub_len;
2288 eval_buffer (p, p + sub_len);
2289#endif
2290 free (p);
2291 }
2292
2293 p = value = alloca (len);
2294 for (i = 0; i < eval_strings->idx; ++i)
2295 {
2296 strcpy (p, "--eval=");
2297 p += strlen (p);
2298 p = quote_for_env (p, eval_strings->list[i]);
2299 *(p++) = ' ';
2300 }
2301 p[-1] = '\0';
2302
2303 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
2304 }
2305
2306 /* Read all the makefiles. */
2307
2308 read_makefiles
2309 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2310
2311#ifdef WINDOWS32
2312 /* look one last time after reading all Makefiles */
2313 if (no_default_sh_exe)
2314 no_default_sh_exe = !find_and_set_default_shell(NULL);
2315#endif /* WINDOWS32 */
2316
2317#if defined (__MSDOS__) || defined (__EMX__)
2318 /* We need to know what kind of shell we will be using. */
2319 {
2320 extern int _is_unixy_shell (const char *_path);
2321 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2322 extern int unixy_shell;
2323 extern char *default_shell;
2324
2325 if (shv && *shv->value)
2326 {
2327 char *shell_path = recursively_expand(shv);
2328
2329 if (shell_path && _is_unixy_shell (shell_path))
2330 unixy_shell = 1;
2331 else
2332 unixy_shell = 0;
2333 if (shell_path)
2334 default_shell = shell_path;
2335 }
2336 }
2337#endif /* __MSDOS__ || __EMX__ */
2338
2339 /* Decode switches again, in case the variables were set by the makefile. */
2340#ifdef KMK
2341 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2342#else /* !KMK */
2343 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2344#if 0
2345 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2346#endif
2347#endif /* !KMK */
2348
2349#if defined (__MSDOS__) || defined (__EMX__)
2350 if (job_slots != 1
2351# ifdef __EMX__
2352 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2353# endif
2354 )
2355 {
2356 error (NILF,
2357 _("Parallel jobs (-j) are not supported on this platform."));
2358 error (NILF, _("Resetting to single job (-j1) mode."));
2359 job_slots = 1;
2360 }
2361#endif
2362
2363#ifdef MAKE_JOBSERVER
2364 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
2365
2366 if (jobserver_fds)
2367 {
2368 const char *cp;
2369 unsigned int ui;
2370
2371 for (ui=1; ui < jobserver_fds->idx; ++ui)
2372 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
2373 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
2374
2375 /* Now parse the fds string and make sure it has the proper format. */
2376
2377 cp = jobserver_fds->list[0];
2378
2379 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
2380 fatal (NILF,
2381 _("internal error: invalid --jobserver-fds string `%s'"), cp);
2382
2383 DB (DB_JOBS,
2384 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
2385
2386 /* The combination of a pipe + !job_slots means we're using the
2387 jobserver. If !job_slots and we don't have a pipe, we can start
2388 infinite jobs. If we see both a pipe and job_slots >0 that means the
2389 user set -j explicitly. This is broken; in this case obey the user
2390 (ignore the jobserver pipe for this make) but print a message. */
2391
2392 if (job_slots > 0)
2393 error (NILF,
2394 _("warning: -jN forced in submake: disabling jobserver mode."));
2395
2396 /* Create a duplicate pipe, that will be closed in the SIGCHLD
2397 handler. If this fails with EBADF, the parent has closed the pipe
2398 on us because it didn't think we were a submake. If so, print a
2399 warning then default to -j1. */
2400
2401 else if ((job_rfd = dup (job_fds[0])) < 0)
2402 {
2403 if (errno != EBADF)
2404 pfatal_with_name (_("dup jobserver"));
2405
2406 error (NILF,
2407 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
2408 job_slots = 1;
2409 }
2410
2411 if (job_slots > 0)
2412 {
2413 close (job_fds[0]);
2414 close (job_fds[1]);
2415 job_fds[0] = job_fds[1] = -1;
2416 free (jobserver_fds->list);
2417 free (jobserver_fds);
2418 jobserver_fds = 0;
2419 }
2420 }
2421
2422 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
2423 Set up the pipe and install the fds option for our children. */
2424
2425 if (job_slots > 1)
2426 {
2427 char *cp;
2428 char c = '+';
2429
2430 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
2431 pfatal_with_name (_("creating jobs pipe"));
2432
2433 /* Every make assumes that it always has one job it can run. For the
2434 submakes it's the token they were given by their parent. For the
2435 top make, we just subtract one from the number the user wants. We
2436 want job_slots to be 0 to indicate we're using the jobserver. */
2437
2438 master_job_slots = job_slots;
2439
2440 while (--job_slots)
2441 {
2442 int r;
2443
2444 EINTRLOOP (r, write (job_fds[1], &c, 1));
2445 if (r != 1)
2446 pfatal_with_name (_("init jobserver pipe"));
2447 }
2448
2449 /* Fill in the jobserver_fds struct for our children. */
2450
2451 cp = xmalloc ((sizeof ("1024")*2)+1);
2452 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2453
2454 jobserver_fds = (struct stringlist *)
2455 xmalloc (sizeof (struct stringlist));
2456 jobserver_fds->list = xmalloc (sizeof (char *));
2457 jobserver_fds->list[0] = cp;
2458 jobserver_fds->idx = 1;
2459 jobserver_fds->max = 1;
2460 }
2461#endif
2462
2463#ifndef MAKE_SYMLINKS
2464 if (check_symlink_flag)
2465 {
2466 error (NILF, _("Symbolic links not supported: disabling -L."));
2467 check_symlink_flag = 0;
2468 }
2469#endif
2470
2471 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2472
2473 define_makeflags (1, 0);
2474
2475 /* Make each `struct dep' point at the `struct file' for the file
2476 depended on. Also do magic for special targets. */
2477
2478 snap_deps ();
2479
2480 /* Convert old-style suffix rules to pattern rules. It is important to
2481 do this before installing the built-in pattern rules below, so that
2482 makefile-specified suffix rules take precedence over built-in pattern
2483 rules. */
2484
2485 convert_to_pattern ();
2486
2487 /* Install the default implicit pattern rules.
2488 This used to be done before reading the makefiles.
2489 But in that case, built-in pattern rules were in the chain
2490 before user-defined ones, so they matched first. */
2491
2492 install_default_implicit_rules ();
2493
2494 /* Compute implicit rule limits. */
2495
2496 count_implicit_rule_limits ();
2497
2498 /* Construct the listings of directories in VPATH lists. */
2499
2500 build_vpath_lists ();
2501
2502 /* Mark files given with -o flags as very old and as having been updated
2503 already, and files given with -W flags as brand new (time-stamp as far
2504 as possible into the future). If restarts is set we'll do -W later. */
2505
2506 if (old_files != 0)
2507 {
2508 const char **p;
2509 for (p = old_files->list; *p != 0; ++p)
2510 {
2511 struct file *f = enter_file (*p);
2512 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2513 f->updated = 1;
2514 f->update_status = 0;
2515 f->command_state = cs_finished;
2516 }
2517 }
2518
2519 if (!restarts && new_files != 0)
2520 {
2521 const char **p;
2522 for (p = new_files->list; *p != 0; ++p)
2523 {
2524 struct file *f = enter_file (*p);
2525 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2526 }
2527 }
2528
2529 /* Initialize the remote job module. */
2530 remote_setup ();
2531
2532 if (read_makefiles != 0)
2533 {
2534 /* Update any makefiles if necessary. */
2535
2536 FILE_TIMESTAMP *makefile_mtimes = 0;
2537 unsigned int mm_idx = 0;
2538 char **nargv;
2539 int nargc;
2540 int orig_db_level = db_level;
2541 int status;
2542
2543 if (! ISDB (DB_MAKEFILES))
2544 db_level = DB_NONE;
2545
2546 DB (DB_BASIC, (_("Updating makefiles....\n")));
2547
2548 /* Remove any makefiles we don't want to try to update.
2549 Also record the current modtimes so we can compare them later. */
2550 {
2551 register struct dep *d, *last;
2552 last = 0;
2553 d = read_makefiles;
2554 while (d != 0)
2555 {
2556 struct file *f = d->file;
2557 if (f->double_colon)
2558 for (f = f->double_colon; f != NULL; f = f->prev)
2559 {
2560 if (f->deps == 0 && f->cmds != 0)
2561 {
2562 /* This makefile is a :: target with commands, but
2563 no dependencies. So, it will always be remade.
2564 This might well cause an infinite loop, so don't
2565 try to remake it. (This will only happen if
2566 your makefiles are written exceptionally
2567 stupidly; but if you work for Athena, that's how
2568 you write your makefiles.) */
2569
2570 DB (DB_VERBOSE,
2571 (_("Makefile `%s' might loop; not remaking it.\n"),
2572 f->name));
2573
2574 if (last == 0)
2575 read_makefiles = d->next;
2576 else
2577 last->next = d->next;
2578
2579 /* Free the storage. */
2580 free_dep (d);
2581
2582 d = last == 0 ? read_makefiles : last->next;
2583
2584 break;
2585 }
2586 }
2587 if (f == NULL || !f->double_colon)
2588 {
2589 makefile_mtimes = xrealloc (makefile_mtimes,
2590 (mm_idx+1)
2591 * sizeof (FILE_TIMESTAMP));
2592 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2593 last = d;
2594 d = d->next;
2595 }
2596 }
2597 }
2598
2599 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2600 define_makeflags (1, 1);
2601
2602 rebuilding_makefiles = 1;
2603 status = update_goal_chain (read_makefiles);
2604 rebuilding_makefiles = 0;
2605
2606 switch (status)
2607 {
2608 case 1:
2609 /* The only way this can happen is if the user specified -q and asked
2610 * for one of the makefiles to be remade as a target on the command
2611 * line. Since we're not actually updating anything with -q we can
2612 * treat this as "did nothing".
2613 */
2614
2615 case -1:
2616 /* Did nothing. */
2617 break;
2618
2619 case 2:
2620 /* Failed to update. Figure out if we care. */
2621 {
2622 /* Nonzero if any makefile was successfully remade. */
2623 int any_remade = 0;
2624 /* Nonzero if any makefile we care about failed
2625 in updating or could not be found at all. */
2626 int any_failed = 0;
2627 unsigned int i;
2628 struct dep *d;
2629
2630 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2631 {
2632 /* Reset the considered flag; we may need to look at the file
2633 again to print an error. */
2634 d->file->considered = 0;
2635
2636 if (d->file->updated)
2637 {
2638 /* This makefile was updated. */
2639 if (d->file->update_status == 0)
2640 {
2641 /* It was successfully updated. */
2642 any_remade |= (file_mtime_no_search (d->file)
2643 != makefile_mtimes[i]);
2644 }
2645 else if (! (d->changed & RM_DONTCARE))
2646 {
2647 FILE_TIMESTAMP mtime;
2648 /* The update failed and this makefile was not
2649 from the MAKEFILES variable, so we care. */
2650 error (NILF, _("Failed to remake makefile `%s'."),
2651 d->file->name);
2652 mtime = file_mtime_no_search (d->file);
2653 any_remade |= (mtime != NONEXISTENT_MTIME
2654 && mtime != makefile_mtimes[i]);
2655 makefile_status = MAKE_FAILURE;
2656 }
2657 }
2658 else
2659 /* This makefile was not found at all. */
2660 if (! (d->changed & RM_DONTCARE))
2661 {
2662 /* This is a makefile we care about. See how much. */
2663 if (d->changed & RM_INCLUDED)
2664 /* An included makefile. We don't need
2665 to die, but we do want to complain. */
2666 error (NILF,
2667 _("Included makefile `%s' was not found."),
2668 dep_name (d));
2669 else
2670 {
2671 /* A normal makefile. We must die later. */
2672 error (NILF, _("Makefile `%s' was not found"),
2673 dep_name (d));
2674 any_failed = 1;
2675 }
2676 }
2677 }
2678 /* Reset this to empty so we get the right error message below. */
2679 read_makefiles = 0;
2680
2681 if (any_remade)
2682 goto re_exec;
2683 if (any_failed)
2684 die (2);
2685 break;
2686 }
2687
2688 case 0:
2689 re_exec:
2690 /* Updated successfully. Re-exec ourselves. */
2691
2692 remove_intermediates (0);
2693
2694 if (print_data_base_flag)
2695 print_data_base ();
2696
2697 log_working_directory (0);
2698
2699 clean_jobserver (0);
2700
2701 if (makefiles != 0)
2702 {
2703 /* These names might have changed. */
2704 int i, j = 0;
2705 for (i = 1; i < argc; ++i)
2706 if (strneq (argv[i], "-f", 2)) /* XXX */
2707 {
2708 if (argv[i][2] == '\0')
2709 /* This cast is OK since we never modify argv. */
2710 argv[++i] = (char *) makefiles->list[j];
2711 else
2712 argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
2713 ++j;
2714 }
2715 }
2716
2717 /* Add -o option for the stdin temporary file, if necessary. */
2718 nargc = argc;
2719 if (stdin_nm)
2720 {
2721 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2722 memcpy (nargv, argv, argc * sizeof (char *));
2723 nargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
2724 nargv[nargc] = 0;
2725 }
2726 else
2727 nargv = argv;
2728
2729 if (directories != 0 && directories->idx > 0)
2730 {
2731 int bad = 1;
2732 if (directory_before_chdir != 0)
2733 {
2734 if (chdir (directory_before_chdir) < 0)
2735 perror_with_name ("chdir", "");
2736 else
2737 bad = 0;
2738 }
2739 if (bad)
2740 fatal (NILF, _("Couldn't change back to original directory."));
2741 }
2742
2743 ++restarts;
2744
2745 /* Reset makeflags in case they were changed. */
2746 {
2747 const char *pv = define_makeflags (1, 1);
2748 char *p = alloca (sizeof ("MAKEFLAGS=") + strlen (pv) + 1);
2749 sprintf (p, "MAKEFLAGS=%s", pv);
2750 putenv (p);
2751 }
2752
2753 if (ISDB (DB_BASIC))
2754 {
2755 char **p;
2756 printf (_("Re-executing[%u]:"), restarts);
2757 for (p = nargv; *p != 0; ++p)
2758 printf (" %s", *p);
2759 putchar ('\n');
2760 }
2761
2762#ifndef _AMIGA
2763 {
2764 char **p;
2765 for (p = environ; *p != 0; ++p)
2766 {
2767 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2768 && (*p)[MAKELEVEL_LENGTH] == '=')
2769 {
2770 *p = alloca (40);
2771 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2772 }
2773 if (strneq (*p, "MAKE_RESTARTS=", 14))
2774 {
2775 *p = alloca (40);
2776 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2777 restarts = 0;
2778 }
2779 }
2780 }
2781#else /* AMIGA */
2782 {
2783 char buffer[256];
2784
2785 sprintf (buffer, "%u", makelevel);
2786 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2787
2788 sprintf (buffer, "%u", restarts);
2789 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2790 restarts = 0;
2791 }
2792#endif
2793
2794 /* If we didn't set the restarts variable yet, add it. */
2795 if (restarts)
2796 {
2797 char *b = alloca (40);
2798 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2799 putenv (b);
2800 }
2801
2802 fflush (stdout);
2803 fflush (stderr);
2804
2805 /* Close the dup'd jobserver pipe if we opened one. */
2806 if (job_rfd >= 0)
2807 close (job_rfd);
2808
2809#ifdef _AMIGA
2810 exec_command (nargv);
2811 exit (0);
2812#elif defined (__EMX__)
2813 {
2814 /* It is not possible to use execve() here because this
2815 would cause the parent process to be terminated with
2816 exit code 0 before the child process has been terminated.
2817 Therefore it may be the best solution simply to spawn the
2818 child process including all file handles and to wait for its
2819 termination. */
2820 int pid;
2821 int status;
2822 pid = child_execute_job (0, 1, nargv, environ);
2823
2824 /* is this loop really necessary? */
2825 do {
2826 pid = wait (&status);
2827 } while (pid <= 0);
2828 /* use the exit code of the child process */
2829 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2830 }
2831#else
2832 exec_command (nargv, environ);
2833#endif
2834 /* NOTREACHED */
2835
2836 default:
2837#define BOGUS_UPDATE_STATUS 0
2838 assert (BOGUS_UPDATE_STATUS);
2839 break;
2840 }
2841
2842 db_level = orig_db_level;
2843
2844 /* Free the makefile mtimes (if we allocated any). */
2845 if (makefile_mtimes)
2846 free (makefile_mtimes);
2847 }
2848
2849 /* Set up `MAKEFLAGS' again for the normal targets. */
2850 define_makeflags (1, 0);
2851
2852 /* Set always_make_flag if -B was given. */
2853 always_make_flag = always_make_set;
2854
2855 /* If restarts is set we haven't set up -W files yet, so do that now. */
2856 if (restarts && new_files != 0)
2857 {
2858 const char **p;
2859 for (p = new_files->list; *p != 0; ++p)
2860 {
2861 struct file *f = enter_file (*p);
2862 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2863 }
2864 }
2865
2866 /* If there is a temp file from reading a makefile from stdin, get rid of
2867 it now. */
2868 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2869 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2870
2871 /* If there were no command-line goals, use the default. */
2872 if (goals == 0)
2873 {
2874 char *p;
2875
2876 if (default_goal_var->recursive)
2877 p = variable_expand (default_goal_var->value);
2878 else
2879 {
2880 p = variable_buffer_output (variable_buffer, default_goal_var->value,
2881 strlen (default_goal_var->value));
2882 *p = '\0';
2883 p = variable_buffer;
2884 }
2885
2886 if (*p != '\0')
2887 {
2888 struct file *f = lookup_file (p);
2889
2890 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2891 table and let the standard logic sort it out. */
2892 if (f == 0)
2893 {
2894 struct nameseq *ns;
2895 ns = PARSE_FILE_SEQ (&p, struct nameseq, '\0', NULL, 0);
2896 if (ns)
2897 {
2898 /* .DEFAULT_GOAL should contain one target. */
2899 if (ns->next != 0)
2900 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2901
2902#ifndef CONFIG_WITH_VALUE_LENGTH
2903 f = enter_file (strcache_add (ns->name));
2904#else
2905 f = enter_file (ns->name);
2906#endif
2907
2908 ns->name = 0; /* It was reused by enter_file(). */
2909 free_ns_chain (ns);
2910 }
2911 }
2912
2913 if (f)
2914 {
2915 goals = alloc_dep ();
2916 goals->file = f;
2917 }
2918 }
2919 }
2920 else
2921 lastgoal->next = 0;
2922
2923
2924 if (!goals)
2925 {
2926 if (read_makefiles == 0)
2927 fatal (NILF, _("No targets specified and no makefile found"));
2928
2929 fatal (NILF, _("No targets"));
2930 }
2931
2932 /* Update the goals. */
2933
2934 DB (DB_BASIC, (_("Updating goal targets....\n")));
2935
2936 {
2937 int status;
2938
2939 switch (update_goal_chain (goals))
2940 {
2941 case -1:
2942 /* Nothing happened. */
2943 case 0:
2944 /* Updated successfully. */
2945 status = makefile_status;
2946 break;
2947 case 1:
2948 /* We are under -q and would run some commands. */
2949 status = MAKE_TROUBLE;
2950 break;
2951 case 2:
2952 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2953 but in VMS, there is only success and failure. */
2954 status = MAKE_FAILURE;
2955 break;
2956 default:
2957 abort ();
2958 }
2959
2960 /* If we detected some clock skew, generate one last warning */
2961 if (clock_skew_detected)
2962 error (NILF,
2963 _("warning: Clock skew detected. Your build may be incomplete."));
2964
2965 MAKE_STATS_2(if (uStartTick) printf("main ticks elapsed: %ull\n", (unsigned long long)(CURRENT_CLOCK_TICK() - uStartTick)) );
2966 /* Exit. */
2967 die (status);
2968 }
2969
2970 /* NOTREACHED */
2971 return 0;
2972}
2973
2974
2975/* Parsing of arguments, decoding of switches. */
2976
2977static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2978static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2979 (sizeof (long_option_aliases) /
2980 sizeof (long_option_aliases[0]))];
2981
2982/* Fill in the string and vector for getopt. */
2983static void
2984init_switches (void)
2985{
2986 char *p;
2987 unsigned int c;
2988 unsigned int i;
2989
2990 if (options[0] != '\0')
2991 /* Already done. */
2992 return;
2993
2994 p = options;
2995
2996 /* Return switch and non-switch args in order, regardless of
2997 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2998 *p++ = '-';
2999
3000 for (i = 0; switches[i].c != '\0'; ++i)
3001 {
3002 long_options[i].name = (switches[i].long_name == 0 ? "" :
3003 switches[i].long_name);
3004 long_options[i].flag = 0;
3005 long_options[i].val = switches[i].c;
3006 if (short_option (switches[i].c))
3007 *p++ = switches[i].c;
3008 switch (switches[i].type)
3009 {
3010 case flag:
3011 case flag_off:
3012 case ignore:
3013 long_options[i].has_arg = no_argument;
3014 break;
3015
3016 case string:
3017 case filename:
3018 case positive_int:
3019 case floating:
3020 if (short_option (switches[i].c))
3021 *p++ = ':';
3022 if (switches[i].noarg_value != 0)
3023 {
3024 if (short_option (switches[i].c))
3025 *p++ = ':';
3026 long_options[i].has_arg = optional_argument;
3027 }
3028 else
3029 long_options[i].has_arg = required_argument;
3030 break;
3031 }
3032 }
3033 *p = '\0';
3034 for (c = 0; c < (sizeof (long_option_aliases) /
3035 sizeof (long_option_aliases[0]));
3036 ++c)
3037 long_options[i++] = long_option_aliases[c];
3038 long_options[i].name = 0;
3039}
3040
3041static void
3042handle_non_switch_argument (char *arg, int env)
3043{
3044 /* Non-option argument. It might be a variable definition. */
3045 struct variable *v;
3046 if (arg[0] == '-' && arg[1] == '\0')
3047 /* Ignore plain `-' for compatibility. */
3048 return;
3049 v = try_variable_definition (0, arg IF_WITH_VALUE_LENGTH_PARAM(NULL), o_command, 0);
3050 if (v != 0)
3051 {
3052 /* It is indeed a variable definition. If we don't already have this
3053 one, record a pointer to the variable for later use in
3054 define_makeflags. */
3055 struct command_variable *cv;
3056
3057 for (cv = command_variables; cv != 0; cv = cv->next)
3058 if (cv->variable == v)
3059 break;
3060
3061 if (! cv) {
3062 cv = xmalloc (sizeof (*cv));
3063 cv->variable = v;
3064 cv->next = command_variables;
3065 command_variables = cv;
3066 }
3067 }
3068 else if (! env)
3069 {
3070 /* Not an option or variable definition; it must be a goal
3071 target! Enter it as a file and add it to the dep chain of
3072 goals. */
3073 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
3074 f->cmd_target = 1;
3075
3076 if (goals == 0)
3077 {
3078 goals = alloc_dep ();
3079 lastgoal = goals;
3080 }
3081 else
3082 {
3083 lastgoal->next = alloc_dep ();
3084 lastgoal = lastgoal->next;
3085 }
3086
3087 lastgoal->file = f;
3088
3089 {
3090 /* Add this target name to the MAKECMDGOALS variable. */
3091 struct variable *gv;
3092 const char *value;
3093
3094 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
3095 if (gv == 0)
3096 value = f->name;
3097 else
3098 {
3099 /* Paste the old and new values together */
3100 unsigned int oldlen, newlen;
3101 char *vp;
3102
3103 oldlen = strlen (gv->value);
3104 newlen = strlen (f->name);
3105 vp = alloca (oldlen + 1 + newlen + 1);
3106 memcpy (vp, gv->value, oldlen);
3107 vp[oldlen] = ' ';
3108 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
3109 value = vp;
3110 }
3111 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
3112 }
3113 }
3114}
3115
3116/* Print a nice usage method. */
3117
3118static void
3119print_usage (int bad)
3120{
3121 const char *const *cpp;
3122 FILE *usageto;
3123
3124 if (print_version_flag)
3125 print_version ();
3126
3127 usageto = bad ? stderr : stdout;
3128
3129 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
3130
3131 for (cpp = usage; *cpp; ++cpp)
3132 fputs (_(*cpp), usageto);
3133
3134#ifdef KMK
3135 if (!remote_description || *remote_description == '\0')
3136 fprintf (usageto, _("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3137 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3138 else
3139 fprintf (usageto, _("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3140 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3141#else /* !KMK */
3142 if (!remote_description || *remote_description == '\0')
3143 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
3144 else
3145 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
3146 make_host, remote_description);
3147#endif /* !KMK */
3148
3149 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
3150}
3151
3152/* Decode switches from ARGC and ARGV.
3153 They came from the environment if ENV is nonzero. */
3154
3155static void
3156decode_switches (int argc, char **argv, int env)
3157{
3158 int bad = 0;
3159 register const struct command_switch *cs;
3160 register struct stringlist *sl;
3161 register int c;
3162
3163 /* getopt does most of the parsing for us.
3164 First, get its vectors set up. */
3165
3166 init_switches ();
3167
3168 /* Let getopt produce error messages for the command line,
3169 but not for options from the environment. */
3170 opterr = !env;
3171 /* Reset getopt's state. */
3172 optind = 0;
3173
3174 while (optind < argc)
3175 {
3176 /* Parse the next argument. */
3177 c = getopt_long (argc, argv, options, long_options, (int *) 0);
3178 if (c == EOF)
3179 /* End of arguments, or "--" marker seen. */
3180 break;
3181 else if (c == 1)
3182 /* An argument not starting with a dash. */
3183 handle_non_switch_argument (optarg, env);
3184 else if (c == '?')
3185 /* Bad option. We will print a usage message and die later.
3186 But continue to parse the other options so the user can
3187 see all he did wrong. */
3188 bad = 1;
3189 else
3190 for (cs = switches; cs->c != '\0'; ++cs)
3191 if (cs->c == c)
3192 {
3193 /* Whether or not we will actually do anything with
3194 this switch. We test this individually inside the
3195 switch below rather than just once outside it, so that
3196 options which are to be ignored still consume args. */
3197 int doit = !env || cs->env;
3198
3199 switch (cs->type)
3200 {
3201 default:
3202 abort ();
3203
3204 case ignore:
3205 break;
3206
3207 case flag:
3208 case flag_off:
3209 if (doit)
3210 *(int *) cs->value_ptr = cs->type == flag;
3211 break;
3212
3213 case string:
3214 case filename:
3215 if (!doit)
3216 break;
3217
3218 if (optarg == 0)
3219 optarg = xstrdup (cs->noarg_value);
3220 else if (*optarg == '\0')
3221 {
3222 char opt[2] = "c";
3223 const char *op = opt;
3224
3225 if (short_option (cs->c))
3226 opt[0] = cs->c;
3227 else
3228 op = cs->long_name;
3229
3230 error (NILF, _("the `%s%s' option requires a non-empty string argument"),
3231 short_option (cs->c) ? "-" : "--", op);
3232 bad = 1;
3233 }
3234
3235 sl = *(struct stringlist **) cs->value_ptr;
3236 if (sl == 0)
3237 {
3238 sl = (struct stringlist *)
3239 xmalloc (sizeof (struct stringlist));
3240 sl->max = 5;
3241 sl->idx = 0;
3242 sl->list = xmalloc (5 * sizeof (char *));
3243 *(struct stringlist **) cs->value_ptr = sl;
3244 }
3245 else if (sl->idx == sl->max - 1)
3246 {
3247 sl->max += 5;
3248 /* MSVC erroneously warns without a cast here. */
3249 sl->list = xrealloc ((void *)sl->list,
3250 sl->max * sizeof (char *));
3251 }
3252 if (cs->type == filename)
3253 sl->list[sl->idx++] = expand_command_line_file (optarg);
3254 else
3255 sl->list[sl->idx++] = optarg;
3256 sl->list[sl->idx] = 0;
3257 break;
3258
3259 case positive_int:
3260 /* See if we have an option argument; if we do require that
3261 it's all digits, not something like "10foo". */
3262 if (optarg == 0 && argc > optind)
3263 {
3264 const char *cp;
3265 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3266 ;
3267 if (cp[0] == '\0')
3268 optarg = argv[optind++];
3269 }
3270
3271 if (!doit)
3272 break;
3273
3274 if (optarg != 0)
3275 {
3276 int i = atoi (optarg);
3277 const char *cp;
3278
3279 /* Yes, I realize we're repeating this in some cases. */
3280 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
3281 ;
3282
3283 if (i < 1 || cp[0] != '\0')
3284 {
3285 error (NILF, _("the `-%c' option requires a positive integral argument"),
3286 cs->c);
3287 bad = 1;
3288 }
3289 else
3290 *(unsigned int *) cs->value_ptr = i;
3291 }
3292 else
3293 *(unsigned int *) cs->value_ptr
3294 = *(unsigned int *) cs->noarg_value;
3295 break;
3296
3297#ifndef NO_FLOAT
3298 case floating:
3299 if (optarg == 0 && optind < argc
3300 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3301 optarg = argv[optind++];
3302
3303 if (doit)
3304 *(double *) cs->value_ptr
3305 = (optarg != 0 ? atof (optarg)
3306 : *(double *) cs->noarg_value);
3307
3308 break;
3309#endif
3310 }
3311
3312 /* We've found the switch. Stop looking. */
3313 break;
3314 }
3315 }
3316
3317 /* There are no more options according to getting getopt, but there may
3318 be some arguments left. Since we have asked for non-option arguments
3319 to be returned in order, this only happens when there is a "--"
3320 argument to prevent later arguments from being options. */
3321 while (optind < argc)
3322 handle_non_switch_argument (argv[optind++], env);
3323
3324
3325 if (!env && (bad || print_usage_flag))
3326 {
3327 print_usage (bad);
3328 die (bad ? 2 : 0);
3329 }
3330}
3331
3332/* Decode switches from environment variable ENVAR (which is LEN chars long).
3333 We do this by chopping the value into a vector of words, prepending a
3334 dash to the first word if it lacks one, and passing the vector to
3335 decode_switches. */
3336
3337static void
3338decode_env_switches (char *envar, unsigned int len)
3339{
3340 char *varref = alloca (2 + len + 2);
3341 char *value, *p;
3342 int argc;
3343 char **argv;
3344
3345 /* Get the variable's value. */
3346 varref[0] = '$';
3347 varref[1] = '(';
3348 memcpy (&varref[2], envar, len);
3349 varref[2 + len] = ')';
3350 varref[2 + len + 1] = '\0';
3351 value = variable_expand (varref);
3352
3353 /* Skip whitespace, and check for an empty value. */
3354 value = next_token (value);
3355 len = strlen (value);
3356 if (len == 0)
3357 return;
3358
3359 /* Allocate a vector that is definitely big enough. */
3360 argv = alloca ((1 + len + 1) * sizeof (char *));
3361
3362 /* Allocate a buffer to copy the value into while we split it into words
3363 and unquote it. We must use permanent storage for this because
3364 decode_switches may store pointers into the passed argument words. */
3365 p = xmalloc (2 * len);
3366
3367 /* getopt will look at the arguments starting at ARGV[1].
3368 Prepend a spacer word. */
3369 argv[0] = 0;
3370 argc = 1;
3371 argv[argc] = p;
3372 while (*value != '\0')
3373 {
3374 if (*value == '\\' && value[1] != '\0')
3375 ++value; /* Skip the backslash. */
3376 else if (isblank ((unsigned char)*value))
3377 {
3378 /* End of the word. */
3379 *p++ = '\0';
3380 argv[++argc] = p;
3381 do
3382 ++value;
3383 while (isblank ((unsigned char)*value));
3384 continue;
3385 }
3386 *p++ = *value++;
3387 }
3388 *p = '\0';
3389 argv[++argc] = 0;
3390
3391 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3392 /* The first word doesn't start with a dash and isn't a variable
3393 definition. Add a dash and pass it along to decode_switches. We
3394 need permanent storage for this in case decode_switches saves
3395 pointers into the value. */
3396 argv[1] = xstrdup (concat (2, "-", argv[1]));
3397
3398 /* Parse those words. */
3399 decode_switches (argc, argv, 1);
3400}
3401
3402
3403/* Quote the string IN so that it will be interpreted as a single word with
3404 no magic by decode_env_switches; also double dollar signs to avoid
3405 variable expansion in make itself. Write the result into OUT, returning
3406 the address of the next character to be written.
3407 Allocating space for OUT twice the length of IN is always sufficient. */
3408
3409static char *
3410quote_for_env (char *out, const char *in)
3411{
3412 while (*in != '\0')
3413 {
3414 if (*in == '$')
3415 *out++ = '$';
3416 else if (isblank ((unsigned char)*in) || *in == '\\')
3417 *out++ = '\\';
3418 *out++ = *in++;
3419 }
3420
3421 return out;
3422}
3423
3424/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3425 command switches. Include options with args if ALL is nonzero.
3426 Don't include options with the `no_makefile' flag set if MAKEFILE. */
3427
3428static const char *
3429define_makeflags (int all, int makefile)
3430{
3431#ifdef KMK
3432 static const char ref[] = "$(KMK_OVERRIDES)";
3433#else
3434 static /*<- bird*/ const char ref[] = "$(MAKEOVERRIDES)";
3435#endif
3436 static /*<- bird*/ const char posixref[] = "$(-*-command-variables-*-)";
3437 static /*<- bird*/ const char evalref[] = "$(-*-eval-flags-*-)";
3438 const struct command_switch *cs;
3439 char *flagstring;
3440 register char *p;
3441 unsigned int words;
3442 struct variable *v;
3443
3444 /* We will construct a linked list of `struct flag's describing
3445 all the flags which need to go in MAKEFLAGS. Then, once we
3446 know how many there are and their lengths, we can put them all
3447 together in a string. */
3448
3449 struct flag
3450 {
3451 struct flag *next;
3452 const struct command_switch *cs;
3453 const char *arg;
3454 };
3455 struct flag *flags = 0;
3456 unsigned int flagslen = 0;
3457#define ADD_FLAG(ARG, LEN) \
3458 do { \
3459 struct flag *new = alloca (sizeof (struct flag)); \
3460 new->cs = cs; \
3461 new->arg = (ARG); \
3462 new->next = flags; \
3463 flags = new; \
3464 if (new->arg == 0) \
3465 ++flagslen; /* Just a single flag letter. */ \
3466 else \
3467 /* " -x foo", plus space to expand "foo". */ \
3468 flagslen += 1 + 1 + 1 + 1 + (3 * (LEN)); \
3469 if (!short_option (cs->c)) \
3470 /* This switch has no single-letter version, so we use the long. */ \
3471 flagslen += 2 + strlen (cs->long_name); \
3472 } while (0)
3473
3474 for (cs = switches; cs->c != '\0'; ++cs)
3475 if (cs->toenv && (!makefile || !cs->no_makefile))
3476 switch (cs->type)
3477 {
3478 case ignore:
3479 break;
3480
3481 case flag:
3482 case flag_off:
3483 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3484 && (cs->default_value == 0
3485 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3486 ADD_FLAG (0, 0);
3487 break;
3488
3489 case positive_int:
3490 if (all)
3491 {
3492 if ((cs->default_value != 0
3493 && (*(unsigned int *) cs->value_ptr
3494 == *(unsigned int *) cs->default_value)))
3495 break;
3496 else if (cs->noarg_value != 0
3497 && (*(unsigned int *) cs->value_ptr ==
3498 *(unsigned int *) cs->noarg_value))
3499 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3500#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
3501 else if (cs->c == 'j')
3502 /* Special case for `-j'. */
3503 ADD_FLAG ("1", 1);
3504#endif
3505 else
3506 {
3507 char *buf = alloca (30);
3508 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3509 ADD_FLAG (buf, strlen (buf));
3510 }
3511 }
3512 break;
3513
3514#ifndef NO_FLOAT
3515 case floating:
3516 if (all)
3517 {
3518 if (cs->default_value != 0
3519 && (*(double *) cs->value_ptr
3520 == *(double *) cs->default_value))
3521 break;
3522 else if (cs->noarg_value != 0
3523 && (*(double *) cs->value_ptr
3524 == *(double *) cs->noarg_value))
3525 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3526 else
3527 {
3528 char *buf = alloca (100);
3529 sprintf (buf, "%g", *(double *) cs->value_ptr);
3530 ADD_FLAG (buf, strlen (buf));
3531 }
3532 }
3533 break;
3534#endif
3535
3536 case filename:
3537 case string:
3538 if (all)
3539 {
3540 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3541 if (sl != 0)
3542 {
3543 /* Add the elements in reverse order, because all the flags
3544 get reversed below; and the order matters for some
3545 switches (like -I). */
3546 unsigned int i = sl->idx;
3547 while (i-- > 0)
3548 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3549 }
3550 }
3551 break;
3552
3553 default:
3554 abort ();
3555 }
3556
3557 /* Four more for the possible " -- ". */
3558 flagslen += 4 + sizeof (posixref) + sizeof (evalref);
3559
3560#undef ADD_FLAG
3561
3562 /* Construct the value in FLAGSTRING.
3563 We allocate enough space for a preceding dash and trailing null. */
3564 flagstring = alloca (1 + flagslen + 1);
3565 memset (flagstring, '\0', 1 + flagslen + 1);
3566 p = flagstring;
3567 words = 1;
3568 *p++ = '-';
3569 while (flags != 0)
3570 {
3571 /* Add the flag letter or name to the string. */
3572 if (short_option (flags->cs->c))
3573 *p++ = flags->cs->c;
3574 else
3575 {
3576 if (*p != '-')
3577 {
3578 *p++ = ' ';
3579 *p++ = '-';
3580 }
3581 *p++ = '-';
3582 strcpy (p, flags->cs->long_name);
3583 p += strlen (p);
3584 }
3585 if (flags->arg != 0)
3586 {
3587 /* A flag that takes an optional argument which in this case is
3588 omitted is specified by ARG being "". We must distinguish
3589 because a following flag appended without an intervening " -"
3590 is considered the arg for the first. */
3591 if (flags->arg[0] != '\0')
3592 {
3593 /* Add its argument too. */
3594 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3595 p = quote_for_env (p, flags->arg);
3596 }
3597 ++words;
3598 /* Write a following space and dash, for the next flag. */
3599 *p++ = ' ';
3600 *p++ = '-';
3601 }
3602 else if (!short_option (flags->cs->c))
3603 {
3604 ++words;
3605 /* Long options must each go in their own word,
3606 so we write the following space and dash. */
3607 *p++ = ' ';
3608 *p++ = '-';
3609 }
3610 flags = flags->next;
3611 }
3612
3613 /* Define MFLAGS before appending variable definitions. */
3614
3615 if (p == &flagstring[1])
3616 /* No flags. */
3617 flagstring[0] = '\0';
3618 else if (p[-1] == '-')
3619 {
3620 /* Kill the final space and dash. */
3621 p -= 2;
3622 *p = '\0';
3623 }
3624 else
3625 /* Terminate the string. */
3626 *p = '\0';
3627
3628#ifdef KMK
3629 /* Since MFLAGS is not parsed for flags, there is no reason to
3630 override any makefile redefinition. */
3631 define_variable_cname ("MFLAGS", flagstring, o_env, 1);
3632#endif /* !KMK */
3633
3634 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3635 flag options. */
3636 if (eval_strings)
3637 {
3638 if (p == &flagstring[1])
3639 /* No flags written, so elide the leading dash already written. */
3640 p = flagstring;
3641 else
3642 *p++ = ' ';
3643 memcpy (p, evalref, sizeof (evalref) - 1);
3644 p += sizeof (evalref) - 1;
3645 }
3646
3647 if (all && command_variables != 0)
3648 {
3649 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3650 command-line variable definitions. */
3651
3652 if (p == &flagstring[1])
3653 /* No flags written, so elide the leading dash already written. */
3654 p = flagstring;
3655 else
3656 {
3657 /* Separate the variables from the switches with a "--" arg. */
3658 if (p[-1] != '-')
3659 {
3660 /* We did not already write a trailing " -". */
3661 *p++ = ' ';
3662 *p++ = '-';
3663 }
3664 /* There is a trailing " -"; fill it out to " -- ". */
3665 *p++ = '-';
3666 *p++ = ' ';
3667 }
3668
3669 /* Copy in the string. */
3670 if (posix_pedantic)
3671 {
3672 memcpy (p, posixref, sizeof (posixref) - 1);
3673 p += sizeof (posixref) - 1;
3674 }
3675 else
3676 {
3677 memcpy (p, ref, sizeof (ref) - 1);
3678 p += sizeof (ref) - 1;
3679 }
3680 }
3681 else if (p == &flagstring[1])
3682 {
3683 words = 0;
3684 --p;
3685 }
3686 else if (p[-1] == '-')
3687 /* Kill the final space and dash. */
3688 p -= 2;
3689 /* Terminate the string. */
3690 *p = '\0';
3691
3692 /* If there are switches, omit the leading dash unless it is a single long
3693 option with two leading dashes. */
3694 if (flagstring[0] == '-' && flagstring[1] != '-')
3695 ++flagstring;
3696
3697#ifdef KMK
3698 v = define_variable_cname ("KMK_FLAGS", flagstring,
3699 /* This used to use o_env, but that lost when a
3700 makefile defined MAKEFLAGS. Makefiles set
3701 MAKEFLAGS to add switches, but we still want
3702 to redefine its value with the full set of
3703 switches. Of course, an override or command
3704 definition will still take precedence. */
3705 o_file, 1);
3706#else
3707 v = define_variable_cname ("MAKEFLAGS", flagstring,
3708 /* This used to use o_env, but that lost when a
3709 makefile defined MAKEFLAGS. Makefiles set
3710 MAKEFLAGS to add switches, but we still want
3711 to redefine its value with the full set of
3712 switches. Of course, an override or command
3713 definition will still take precedence. */
3714 o_file, 1);
3715#endif
3716
3717 if (! all)
3718 /* The first time we are called, set MAKEFLAGS to always be exported.
3719 We should not do this again on the second call, because that is
3720 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3721 v->export = v_export;
3722
3723#ifdef KMK
3724 /* Provide simple access to some of the options. */
3725 {
3726 char val[32];
3727 sprintf (val, "%u", job_slots);
3728 define_variable_cname ("KMK_OPTS_JOBS", val, o_default, 1);
3729 define_variable_cname ("KMK_OPTS_KEEP_GOING", keep_going_flag ? "1" : "0", o_default, 1);
3730 define_variable_cname ("KMK_OPTS_JUST_PRINT", just_print_flag ? "1" : "0", o_default, 1);
3731 define_variable_cname ("KMK_OPTS_PRETTY_COMMAND_PRINTING",
3732 pretty_command_printing ? "1" : "0", o_default, 1);
3733 sprintf (val, "%u", process_priority);
3734 define_variable_cname ("KMK_OPTS_PRORITY", val, o_default, 1);
3735 sprintf (val, "%u", process_affinity);
3736 define_variable_cname ("KMK_OPTS_AFFINITY", val, o_default, 1);
3737# if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
3738 define_variable_cname ("KMK_OPTS_STATISTICS", make_expensive_statistics ? "1" : "0",
3739 o_default, 1);
3740# endif
3741# ifdef CONFIG_WITH_PRINT_TIME_SWITCH
3742 sprintf (val, "%u", print_time_min);
3743 define_variable_cname ("KMK_OPTS_PRINT_TIME", val, o_default, 1);
3744# endif
3745 }
3746#endif
3747
3748 return v->value;
3749}
3750
3751
3752/* Print version information. */
3753
3754static void
3755print_version (void)
3756{
3757 static int printed_version = 0;
3758
3759 char *precede = print_data_base_flag ? "# " : "";
3760
3761 if (printed_version)
3762 /* Do it only once. */
3763 return;
3764
3765#ifdef KMK
3766 printf ("%skmk - kBuild version %d.%d.%d (r%u)\n\
3767\n",
3768 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR,
3769 KBUILD_VERSION_PATCH, KBUILD_SVN_REV);
3770
3771 printf("%sBased on GNU Make %s:\n", precede, version_string);
3772
3773#else /* !KMK */
3774 printf ("%sGNU Make %s\n", precede, version_string);
3775
3776 if (!remote_description || *remote_description == '\0')
3777 printf (_("%sBuilt for %s\n"), precede, make_host);
3778 else
3779 printf (_("%sBuilt for %s (%s)\n"),
3780 precede, make_host, remote_description);
3781#endif /* !KMK */
3782
3783 /* Print this untranslated. The coding standards recommend translating the
3784 (C) to the copyright symbol, but this string is going to change every
3785 year, and none of the rest of it should be translated (including the
3786 word "Copyright", so it hardly seems worth it. */
3787
3788 printf ("%sCopyright (C) 2010 Free Software Foundation, Inc.\n", precede);
3789
3790 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
3791%sThis is free software: you are free to change and redistribute it.\n\
3792%sThere is NO WARRANTY, to the extent permitted by law.\n"),
3793 precede, precede, precede);
3794
3795#ifdef KMK
3796 printf ("\n\
3797%skBuild modifications:\n\
3798%s Copyright (c) 2005-2013 knut st. osmundsen.\n\
3799\n\
3800%skmkbuiltin commands derived from *BSD sources:\n\
3801%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3802%s The Regents of the University of California. All rights reserved.\n\
3803%s Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>\n",
3804 precede, precede, precede, precede, precede, precede);
3805
3806# ifdef KBUILD_PATH
3807 printf (_("\n\
3808%sKBUILD_PATH: '%s' (default '%s')\n\
3809%sKBUILD_BIN_PATH: '%s' (default '%s')\n\
3810\n"),
3811 precede, get_kbuild_path(), KBUILD_PATH,
3812 precede, get_kbuild_bin_path(), KBUILD_BIN_PATH);
3813# else /* !KBUILD_PATH */
3814 printf ("\n\
3815%sKBUILD_PATH: '%s'\n\
3816%sKBUILD_BIN_PATH: '%s'\n\
3817\n",
3818 precede, get_kbuild_path(),
3819 precede, get_kbuild_bin_path());
3820# endif /* !KBUILD_PATH */
3821
3822 if (!remote_description || *remote_description == '\0')
3823 printf (_("%sThis program is a %s build, built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n\n"),
3824 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3825 else
3826 printf (_("%sThis program is a %s build, built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n\n"),
3827 precede, KBUILD_TYPE, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3828
3829#endif /* KMK */
3830
3831 printed_version = 1;
3832
3833 /* Flush stdout so the user doesn't have to wait to see the
3834 version information while things are thought about. */
3835 fflush (stdout);
3836}
3837
3838/* Print a bunch of information about this and that. */
3839
3840static void
3841print_data_base ()
3842{
3843 time_t when;
3844
3845 when = time ((time_t *) 0);
3846 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3847
3848 print_variable_data_base ();
3849 print_dir_data_base ();
3850 print_rule_data_base ();
3851 print_file_data_base ();
3852 print_vpath_data_base ();
3853#ifdef KMK
3854 print_kbuild_data_base ();
3855#endif
3856#ifndef CONFIG_WITH_STRCACHE2
3857 strcache_print_stats ("#");
3858#else
3859 strcache2_print_stats_all ("#");
3860#endif
3861#ifdef CONFIG_WITH_ALLOC_CACHES
3862 alloccache_print_all ();
3863#endif
3864#ifdef CONFIG_WITH_COMPILER
3865 kmk_cc_print_stats ();
3866#endif
3867
3868 when = time ((time_t *) 0);
3869 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3870}
3871#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
3872
3873static void
3874print_stats ()
3875{
3876 time_t when;
3877
3878 when = time ((time_t *) 0);
3879 printf (_("\n# Make statistics, printed on %s"), ctime (&when));
3880
3881 /* Allocators: */
3882#ifdef CONFIG_WITH_COMPILER
3883 kmk_cc_print_stats ();
3884#endif
3885# ifndef CONFIG_WITH_STRCACHE2
3886 strcache_print_stats ("#");
3887# else
3888 strcache2_print_stats_all ("#");
3889# endif
3890# ifdef CONFIG_WITH_ALLOC_CACHES
3891 alloccache_print_all ();
3892# endif
3893 print_heap_stats ();
3894
3895 /* Make stuff: */
3896 print_variable_stats ();
3897 print_file_stats ();
3898 print_dir_stats ();
3899# ifdef KMK
3900 print_kbuild_define_stats ();
3901# endif
3902# ifdef CONFIG_WITH_COMPILER
3903 kmk_cc_print_stats ();
3904# endif
3905
3906 when = time ((time_t *) 0);
3907 printf (_("\n# Finished Make statistics on %s\n"), ctime (&when));
3908}
3909#endif
3910
3911static void
3912clean_jobserver (int status)
3913{
3914 char token = '+';
3915
3916 /* Sanity: have we written all our jobserver tokens back? If our
3917 exit status is 2 that means some kind of syntax error; we might not
3918 have written all our tokens so do that now. If tokens are left
3919 after any other error code, that's bad. */
3920
3921 if (job_fds[0] != -1 && jobserver_tokens)
3922 {
3923 if (status != 2)
3924 error (NILF,
3925 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3926 jobserver_tokens);
3927 else
3928 while (jobserver_tokens--)
3929 {
3930 int r;
3931
3932 EINTRLOOP (r, write (job_fds[1], &token, 1));
3933 if (r != 1)
3934 perror_with_name ("write", "");
3935 }
3936 }
3937
3938
3939 /* Sanity: If we're the master, were all the tokens written back? */
3940
3941 if (master_job_slots)
3942 {
3943 /* We didn't write one for ourself, so start at 1. */
3944 unsigned int tcnt = 1;
3945
3946 /* Close the write side, so the read() won't hang. */
3947 close (job_fds[1]);
3948
3949 while (read (job_fds[0], &token, 1) == 1)
3950 ++tcnt;
3951
3952 if (tcnt != master_job_slots)
3953 error (NILF,
3954 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3955 tcnt, master_job_slots);
3956
3957 close (job_fds[0]);
3958
3959 /* Clean out jobserver_fds so we don't pass this information to any
3960 sub-makes. Also reset job_slots since it will be put on the command
3961 line, not in MAKEFLAGS. */
3962 job_slots = default_job_slots;
3963 if (jobserver_fds)
3964 {
3965 /* MSVC erroneously warns without a cast here. */
3966 free ((void *)jobserver_fds->list);
3967 free (jobserver_fds);
3968 jobserver_fds = 0;
3969 }
3970 }
3971}
3972
3973
3974/* Exit with STATUS, cleaning up as necessary. */
3975
3976void
3977die (int status)
3978{
3979 static char dying = 0;
3980#ifdef KMK
3981 static char need_2nd_error = 0;
3982#endif
3983
3984 if (!dying)
3985 {
3986 int err;
3987
3988 dying = 1;
3989
3990 if (print_version_flag)
3991 print_version ();
3992
3993#ifdef KMK
3994 /* Flag 2nd error message. */
3995 if (status != 0
3996 && ( job_slots_used > 0
3997 || print_data_base_flag
3998 || print_stats_flag))
3999 need_2nd_error = 1;
4000#endif /* KMK */
4001
4002 /* Wait for children to die. */
4003 err = (status != 0);
4004 while (job_slots_used > 0)
4005 reap_children (1, err);
4006
4007 /* Let the remote job module clean up its state. */
4008 remote_cleanup ();
4009
4010 /* Remove the intermediate files. */
4011 remove_intermediates (0);
4012
4013 if (print_data_base_flag)
4014 print_data_base ();
4015
4016#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
4017 if (print_stats_flag)
4018 print_stats ();
4019#endif
4020
4021#ifdef NDEBUG /* bird: Don't waste time on debug sanity checks. */
4022 if (print_data_base_flag || db_level)
4023#endif
4024 verify_file_data_base ();
4025
4026 clean_jobserver (status);
4027
4028 /* Try to move back to the original directory. This is essential on
4029 MS-DOS (where there is really only one process), and on Unix it
4030 puts core files in the original directory instead of the -C
4031 directory. Must wait until after remove_intermediates(), or unlinks
4032 of relative pathnames fail. */
4033 if (directory_before_chdir != 0)
4034 {
4035 /* If it fails we don't care: shut up GCC. */
4036 int _x;
4037 _x = chdir (directory_before_chdir);
4038 }
4039
4040#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
4041 if (print_time_min != -1)
4042 {
4043 big_int elapsed = nano_timestamp () - make_start_ts;
4044 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
4045 {
4046 char buf[64];
4047 format_elapsed_nano (buf, sizeof (buf), elapsed);
4048 message (1, _("%*s"), print_time_width, buf);
4049 }
4050 }
4051#endif
4052
4053 log_working_directory (0);
4054 }
4055
4056#ifdef KMK
4057 /* The failure might be lost in a -j <lots> run, so mention the
4058 failure again before exiting. */
4059 if (need_2nd_error != 0)
4060 error (NILF, _("*** Exiting with status %d"), status);
4061#endif
4062
4063 exit (status);
4064}
4065
4066
4067/* Write a message indicating that we've just entered or
4068 left (according to ENTERING) the current directory. */
4069
4070void
4071log_working_directory (int entering)
4072{
4073 static int entered = 0;
4074
4075 /* Print nothing without the flag. Don't print the entering message
4076 again if we already have. Don't print the leaving message if we
4077 haven't printed the entering message. */
4078 if (! print_directory_flag || entering == entered)
4079 return;
4080
4081 entered = entering;
4082
4083 if (print_data_base_flag)
4084 fputs ("# ", stdout);
4085
4086 /* Use entire sentences to give the translators a fighting chance. */
4087
4088 if (makelevel == 0)
4089 if (starting_directory == 0)
4090 if (entering)
4091 printf (_("%s: Entering an unknown directory\n"), program);
4092 else
4093 printf (_("%s: Leaving an unknown directory\n"), program);
4094 else
4095 if (entering)
4096 printf (_("%s: Entering directory `%s'\n"),
4097 program, starting_directory);
4098 else
4099 printf (_("%s: Leaving directory `%s'\n"),
4100 program, starting_directory);
4101 else
4102 if (starting_directory == 0)
4103 if (entering)
4104 printf (_("%s[%u]: Entering an unknown directory\n"),
4105 program, makelevel);
4106 else
4107 printf (_("%s[%u]: Leaving an unknown directory\n"),
4108 program, makelevel);
4109 else
4110 if (entering)
4111 printf (_("%s[%u]: Entering directory `%s'\n"),
4112 program, makelevel, starting_directory);
4113 else
4114 printf (_("%s[%u]: Leaving directory `%s'\n"),
4115 program, makelevel, starting_directory);
4116
4117 /* Flush stdout to be sure this comes before any stderr output. */
4118 fflush (stdout);
4119}
Note: See TracBrowser for help on using the repository browser.