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

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

kmk: added --nice option as an alias for --priority=1

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