VirtualBox

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

Last change on this file since 2102 was 2102, checked in by bird, 17 years ago

kmk: --print-time fix.

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

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