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

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

kmk: Allocation caches for nameseq, dep and idep. next: variable.

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