VirtualBox

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

Last change on this file since 2185 was 2185, checked in by bird, 16 years ago

kmk: changed the conditions for showing the final error message a bit to avoid messing up a lot of negative testcases.

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

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