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

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

kmk: Jokes.

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