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

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

kmk: Added print_dir_stats and implemented it for the NT directory cache.

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