VirtualBox

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

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

two strcache_add optimizations.

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

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