VirtualBox

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

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

kmk: Don't call verify_file_data_base, which only performs assert-like sanity checks, in non-strict builds because it wasts time.

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

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