VirtualBox

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

Last change on this file since 2760 was 2760, checked in by bird, 10 years ago

main.c: Fixed stack alignment in the AMD64 specific signal emulation code.

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

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