VirtualBox

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

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

kmk: show the build type.

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