VirtualBox

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

Last change on this file since 2546 was 2546, checked in by bird, 13 years ago

Applied modified patches for Haiku support from Mike Smith.

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