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

Last change on this file since 3039 was 2981, checked in by bird, 9 years ago

kmk: Use GetActiveProcessorCount instead of GetSystemInfo when possible. Good for systems with lots of CPUs. However, limit it to 64 so we don't run into trouble with child waiting in subproc.

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