VirtualBox

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

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

kmk: New switch --print-stats which will print variable, file, strcache, allocation and heap statistics.

  • Property svn:eol-style set to native
File size: 110.0 KB
Line 
1/* Argument parsing and main program of GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4Foundation, Inc.
5This file is part of GNU Make.
6
7GNU Make is free software; you can redistribute it and/or modify it under the
8terms of the GNU General Public License as published by the Free Software
9Foundation; either version 2, or (at your option) any later version.
10
11GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License along with
16GNU Make; see the file COPYING. If not, write to the Free Software
17Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
18
19#include "make.h"
20#include "dep.h"
21#include "filedef.h"
22#include "variable.h"
23#include "job.h"
24#include "commands.h"
25#include "rule.h"
26#include "debug.h"
27#include "getopt.h"
28#ifdef KMK
29# include "kbuild.h"
30#endif
31
32#include <assert.h>
33#ifdef _AMIGA
34# include <dos/dos.h>
35# include <proto/dos.h>
36#endif
37#ifdef WINDOWS32
38#include <windows.h>
39#include <io.h>
40#include "pathstuff.h"
41#endif
42#ifdef __EMX__
43# include <sys/types.h>
44# include <sys/wait.h>
45#endif
46#ifdef HAVE_FCNTL_H
47# include <fcntl.h>
48#endif
49
50#ifdef KMK /* for get_online_cpu_count */
51# if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
52# include <sys/sysctl.h>
53# endif
54# ifdef __OS2__
55# define INCL_BASE
56# include <os2.h>
57# endif
58#endif /* KMK*/
59
60#if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
61# define SET_STACK_SIZE
62#endif
63
64#ifdef SET_STACK_SIZE
65# include <sys/resource.h>
66#endif
67
68#ifdef _AMIGA
69int __stack = 20000; /* Make sure we have 20K of stack space */
70#endif
71
72void init_dir (void);
73void remote_setup (void);
74void remote_cleanup (void);
75RETSIGTYPE fatal_error_signal (int sig);
76
77void print_variable_data_base (void);
78void print_dir_data_base (void);
79void print_rule_data_base (void);
80void print_file_data_base (void);
81void print_vpath_data_base (void);
82
83void verify_file_data_base (void);
84
85#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 commands.\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 commands; 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 commands; 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 commands.\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
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
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
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
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 prevent 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
1540 /* Set up .FEATURES */
1541 define_variable (".FEATURES", 9,
1542 "target-specific order-only second-expansion else-if",
1543 o_default, 0);
1544#ifndef NO_ARCHIVES
1545 do_variable_definition (NILF, ".FEATURES", "archives",
1546 o_default, f_append, 0);
1547#endif
1548#ifdef MAKE_JOBSERVER
1549 do_variable_definition (NILF, ".FEATURES", "jobserver",
1550 o_default, f_append, 0);
1551#endif
1552#ifdef MAKE_SYMLINKS
1553 do_variable_definition (NILF, ".FEATURES", "check-symlink",
1554 o_default, f_append, 0);
1555#endif
1556#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1557 do_variable_definition (NILF, ".FEATURES", "explicit-multitarget",
1558 o_default, f_append, 0);
1559#endif
1560#ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
1561 do_variable_definition (NILF, ".FEATURES", "prepend-assignment",
1562 o_default, f_append, 0);
1563#endif
1564
1565#ifdef KMK
1566 /* Initialize the default number of jobs to the cpu/core/smt count. */
1567 default_job_slots = job_slots = get_online_cpu_count ();
1568#endif /* KMK */
1569
1570 /* Read in variables from the environment. It is important that this be
1571 done before $(MAKE) is figured out so its definitions will not be
1572 from the environment. */
1573
1574#ifndef _AMIGA
1575 {
1576 unsigned int i;
1577
1578 for (i = 0; envp[i] != 0; ++i)
1579 {
1580 int do_not_define = 0;
1581 char *ep = envp[i];
1582
1583 while (*ep != '\0' && *ep != '=')
1584 ++ep;
1585#ifdef WINDOWS32
1586 if (!unix_path && strneq(envp[i], "PATH=", 5))
1587 unix_path = ep+1;
1588 else if (!strnicmp(envp[i], "Path=", 5)) {
1589 do_not_define = 1; /* it gets defined after loop exits */
1590 if (!windows32_path)
1591 windows32_path = ep+1;
1592 }
1593#endif
1594 /* The result of pointer arithmetic is cast to unsigned int for
1595 machines where ptrdiff_t is a different size that doesn't widen
1596 the same. */
1597 if (!do_not_define)
1598 {
1599 struct variable *v;
1600
1601 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1602 ep + 1, o_env, 1);
1603 /* Force exportation of every variable culled from the
1604 environment. We used to rely on target_environment's
1605 v_default code to do this. But that does not work for the
1606 case where an environment variable is redefined in a makefile
1607 with `override'; it should then still be exported, because it
1608 was originally in the environment. */
1609 v->export = v_export;
1610
1611 /* Another wrinkle is that POSIX says the value of SHELL set in
1612 the makefile won't change the value of SHELL given to
1613 subprocesses. */
1614 if (streq (v->name, "SHELL"))
1615 {
1616#ifndef __MSDOS__
1617 v->export = v_noexport;
1618#endif
1619 shell_var.name = "SHELL";
1620 shell_var.value = xstrdup (ep + 1);
1621 }
1622
1623 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1624 if (streq (v->name, "MAKE_RESTARTS"))
1625 {
1626 v->export = v_noexport;
1627 restarts = (unsigned int) atoi (ep + 1);
1628 }
1629 }
1630 }
1631 }
1632#ifdef WINDOWS32
1633 /* If we didn't find a correctly spelled PATH we define PATH as
1634 * either the first mispelled value or an empty string
1635 */
1636 if (!unix_path)
1637 define_variable("PATH", 4,
1638 windows32_path ? windows32_path : "",
1639 o_env, 1)->export = v_export;
1640#endif
1641#else /* For Amiga, read the ENV: device, ignoring all dirs */
1642 {
1643 BPTR env, file, old;
1644 char buffer[1024];
1645 int len;
1646 __aligned struct FileInfoBlock fib;
1647
1648 env = Lock ("ENV:", ACCESS_READ);
1649 if (env)
1650 {
1651 old = CurrentDir (DupLock(env));
1652 Examine (env, &fib);
1653
1654 while (ExNext (env, &fib))
1655 {
1656 if (fib.fib_DirEntryType < 0) /* File */
1657 {
1658 /* Define an empty variable. It will be filled in
1659 variable_lookup(). Makes startup quite a bit
1660 faster. */
1661 define_variable (fib.fib_FileName,
1662 strlen (fib.fib_FileName),
1663 "", o_env, 1)->export = v_export;
1664 }
1665 }
1666 UnLock (env);
1667 UnLock(CurrentDir(old));
1668 }
1669 }
1670#endif
1671
1672 /* Decode the switches. */
1673
1674#ifdef KMK
1675 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
1676#else /* !KMK */
1677 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1678#if 0
1679 /* People write things like:
1680 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1681 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1682 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1683#endif
1684#endif /* !KMK */
1685 decode_switches (argc, argv, 0);
1686#ifdef WINDOWS32
1687 if (suspend_flag) {
1688 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1689 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1690 Sleep(30 * 1000);
1691 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1692 }
1693#endif
1694
1695 decode_debug_flags ();
1696
1697#ifdef KMK
1698 set_make_priority_and_affinity ();
1699#endif
1700
1701 /* Set always_make_flag if -B was given and we've not restarted already. */
1702 always_make_flag = always_make_set && (restarts == 0);
1703
1704 /* Print version information. */
1705 if (print_version_flag || print_data_base_flag || db_level)
1706 {
1707 print_version ();
1708
1709 /* `make --version' is supposed to just print the version and exit. */
1710 if (print_version_flag)
1711 die (0);
1712 }
1713
1714#ifndef VMS
1715 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1716 (If it is a relative pathname with a slash, prepend our directory name
1717 so the result will run the same program regardless of the current dir.
1718 If it is a name with no slash, we can only hope that PATH did not
1719 find it in the current directory.) */
1720#ifdef WINDOWS32
1721 /*
1722 * Convert from backslashes to forward slashes for
1723 * programs like sh which don't like them. Shouldn't
1724 * matter if the path is one way or the other for
1725 * CreateProcess().
1726 */
1727 if (strpbrk(argv[0], "/:\\") ||
1728 strstr(argv[0], "..") ||
1729 strneq(argv[0], "//", 2))
1730 argv[0] = xstrdup(w32ify(argv[0],1));
1731#else /* WINDOWS32 */
1732#if defined (__MSDOS__) || defined (__EMX__)
1733 if (strchr (argv[0], '\\'))
1734 {
1735 char *p;
1736
1737 argv[0] = xstrdup (argv[0]);
1738 for (p = argv[0]; *p; p++)
1739 if (*p == '\\')
1740 *p = '/';
1741 }
1742 /* If argv[0] is not in absolute form, prepend the current
1743 directory. This can happen when Make is invoked by another DJGPP
1744 program that uses a non-absolute name. */
1745 if (current_directory[0] != '\0'
1746 && argv[0] != 0
1747 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1748# ifdef __EMX__
1749 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1750 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1751# endif
1752 )
1753 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1754#else /* !__MSDOS__ */
1755 if (current_directory[0] != '\0'
1756 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1757#ifdef HAVE_DOS_PATHS
1758 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1759 && strchr (argv[0], '\\') != 0
1760#endif
1761 )
1762 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1763#endif /* !__MSDOS__ */
1764#endif /* WINDOWS32 */
1765#endif
1766
1767 /* The extra indirection through $(MAKE_COMMAND) is done
1768 for hysterical raisins. */
1769 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1770 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1771#ifdef KMK
1772 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1773#endif
1774
1775 if (command_variables != 0)
1776 {
1777 struct command_variable *cv;
1778 struct variable *v;
1779 unsigned int len = 0;
1780 char *value, *p;
1781
1782 /* Figure out how much space will be taken up by the command-line
1783 variable definitions. */
1784 for (cv = command_variables; cv != 0; cv = cv->next)
1785 {
1786 v = cv->variable;
1787 len += 2 * strlen (v->name);
1788 if (! v->recursive)
1789 ++len;
1790 ++len;
1791 len += 2 * strlen (v->value);
1792 ++len;
1793 }
1794
1795 /* Now allocate a buffer big enough and fill it. */
1796 p = value = alloca (len);
1797 for (cv = command_variables; cv != 0; cv = cv->next)
1798 {
1799 v = cv->variable;
1800 p = quote_for_env (p, v->name);
1801 if (! v->recursive)
1802 *p++ = ':';
1803 *p++ = '=';
1804 p = quote_for_env (p, v->value);
1805 *p++ = ' ';
1806 }
1807 p[-1] = '\0'; /* Kill the final space and terminate. */
1808
1809 /* Define an unchangeable variable with a name that no POSIX.2
1810 makefile could validly use for its own variable. */
1811 (void) define_variable ("-*-command-variables-*-", 23,
1812 value, o_automatic, 0);
1813
1814 /* Define the variable; this will not override any user definition.
1815 Normally a reference to this variable is written into the value of
1816 MAKEFLAGS, allowing the user to override this value to affect the
1817 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1818 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1819 a reference to this hidden variable is written instead. */
1820#ifdef KMK
1821 (void) define_variable ("KMK_OVERRIDES", 13,
1822 "${-*-command-variables-*-}", o_env, 1);
1823#else
1824 (void) define_variable ("MAKEOVERRIDES", 13,
1825 "${-*-command-variables-*-}", o_env, 1);
1826#endif
1827 }
1828
1829 /* If there were -C flags, move ourselves about. */
1830 if (directories != 0)
1831 {
1832 unsigned int i;
1833 for (i = 0; directories->list[i] != 0; ++i)
1834 {
1835 const char *dir = directories->list[i];
1836#ifdef WINDOWS32
1837 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1838 But allow -C/ just in case someone wants that. */
1839 {
1840 char *p = (char *)dir + strlen (dir) - 1;
1841 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1842 --p;
1843 p[1] = '\0';
1844 }
1845#endif
1846 if (chdir (dir) < 0)
1847 pfatal_with_name (dir);
1848 }
1849 }
1850
1851#ifdef KMK
1852 /* Check for [Mm]akefile.kup and change directory when found.
1853 Makefile.kmk overrides Makefile.kup but not plain Makefile.
1854 If no -C arguments were given, fake one to indicate chdir. */
1855 if (makefiles == 0)
1856 {
1857 struct stat st;
1858 if (( ( stat ("Makefile.kup", &st) == 0
1859 && S_ISREG (st.st_mode) )
1860 || ( stat ("makefile.kup", &st) == 0
1861 && S_ISREG (st.st_mode) ) )
1862 && stat ("Makefile.kmk", &st) < 0
1863 && stat ("makefile.kmk", &st) < 0)
1864 {
1865 static char fake_path[3*16 + 32] = "..";
1866 char *cur = &fake_path[2];
1867 int up_levels = 1;
1868 while (up_levels < 16)
1869 {
1870 /* File with higher precedence.s */
1871 strcpy (cur, "/Makefile.kmk");
1872 if (stat (fake_path, &st) == 0)
1873 break;
1874 strcpy (cur, "/makefile.kmk");
1875 if (stat (fake_path, &st) == 0)
1876 break;
1877
1878 /* the .kup files */
1879 strcpy (cur, "/Makefile.kup");
1880 if ( stat (fake_path, &st) != 0
1881 || !S_ISREG (st.st_mode))
1882 {
1883 strcpy (cur, "/makefile.kup");
1884 if ( stat (fake_path, &st) != 0
1885 || !S_ISREG (st.st_mode))
1886 break;
1887 }
1888
1889 /* ok */
1890 strcpy (cur, "/..");
1891 cur += 3;
1892 up_levels++;
1893 }
1894
1895 if (up_levels >= 16)
1896 fatal (NILF, _("Makefile.kup recursion is too deep."));
1897
1898 /* attempt to change to the directory. */
1899 *cur = '\0';
1900 if (chdir (fake_path) < 0)
1901 pfatal_with_name (fake_path);
1902
1903 /* add the string to the directories. */
1904 if (!directories)
1905 {
1906 directories = xmalloc (sizeof(*directories));
1907 directories->list = xmalloc (5 * sizeof (char *));
1908 directories->max = 5;
1909 directories->idx = 0;
1910 }
1911 else if (directories->idx == directories->max - 1)
1912 {
1913 directories->max += 5;
1914 directories->list = xrealloc ((void *)directories->list,
1915 directories->max * sizeof (char *));
1916 }
1917 directories->list[directories->idx++] = fake_path;
1918 }
1919 }
1920#endif /* KMK */
1921
1922#ifdef WINDOWS32
1923 /*
1924 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1925 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1926 *
1927 * The functions in dir.c can incorrectly cache information for "."
1928 * before we have changed directory and this can cause file
1929 * lookups to fail because the current directory (.) was pointing
1930 * at the wrong place when it was first evaluated.
1931 */
1932#ifdef KMK /* this is really a candidate for all platforms... */
1933 {
1934 extern char *default_shell;
1935 const char *bin = get_kbuild_bin_path();
1936 size_t len = strlen (bin);
1937 default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
1938 memcpy (default_shell, bin, len);
1939 strcpy (default_shell + len, "/kmk_ash.exe");
1940 no_default_sh_exe = 0;
1941 batch_mode_shell = 1;
1942 }
1943#else /* !KMK */
1944 no_default_sh_exe = !find_and_set_default_shell(NULL);
1945#endif /* !KMK */
1946#endif /* WINDOWS32 */
1947 /* Figure out the level of recursion. */
1948 {
1949 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1950 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1951 makelevel = (unsigned int) atoi (v->value);
1952 else
1953 makelevel = 0;
1954 }
1955
1956 /* Except under -s, always do -w in sub-makes and under -C. */
1957 if (!silent_flag && (directories != 0 || makelevel > 0))
1958 print_directory_flag = 1;
1959
1960 /* Let the user disable that with --no-print-directory. */
1961 if (inhibit_print_directory_flag)
1962 print_directory_flag = 0;
1963
1964 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1965 if (no_builtin_variables_flag)
1966 no_builtin_rules_flag = 1;
1967
1968 /* Construct the list of include directories to search. */
1969
1970 construct_include_path (include_directories == 0
1971 ? 0 : include_directories->list);
1972
1973 /* Figure out where we are now, after chdir'ing. */
1974 if (directories == 0)
1975 /* We didn't move, so we're still in the same place. */
1976 starting_directory = current_directory;
1977 else
1978 {
1979#ifdef WINDOWS32
1980 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1981#else
1982 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1983#endif
1984 {
1985#ifdef HAVE_GETCWD
1986 perror_with_name ("getcwd", "");
1987#else
1988 error (NILF, "getwd: %s", current_directory);
1989#endif
1990 starting_directory = 0;
1991 }
1992 else
1993 starting_directory = current_directory;
1994 }
1995
1996 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1997
1998 /* Read any stdin makefiles into temporary files. */
1999
2000 if (makefiles != 0)
2001 {
2002 unsigned int i;
2003 for (i = 0; i < makefiles->idx; ++i)
2004 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
2005 {
2006 /* This makefile is standard input. Since we may re-exec
2007 and thus re-read the makefiles, we read standard input
2008 into a temporary file and read from that. */
2009 FILE *outfile;
2010 char *template, *tmpdir;
2011
2012 if (stdin_nm)
2013 fatal (NILF, _("Makefile from standard input specified twice."));
2014
2015#ifdef VMS
2016# define DEFAULT_TMPDIR "sys$scratch:"
2017#else
2018# ifdef P_tmpdir
2019# define DEFAULT_TMPDIR P_tmpdir
2020# else
2021# define DEFAULT_TMPDIR "/tmp"
2022# endif
2023#endif
2024#define DEFAULT_TMPFILE "GmXXXXXX"
2025
2026 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
2027#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2028 /* These are also used commonly on these platforms. */
2029 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
2030 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
2031#endif
2032 )
2033 tmpdir = DEFAULT_TMPDIR;
2034
2035 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
2036 strcpy (template, tmpdir);
2037
2038#ifdef HAVE_DOS_PATHS
2039 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
2040 strcat (template, "/");
2041#else
2042# ifndef VMS
2043 if (template[strlen (template) - 1] != '/')
2044 strcat (template, "/");
2045# endif /* !VMS */
2046#endif /* !HAVE_DOS_PATHS */
2047
2048 strcat (template, DEFAULT_TMPFILE);
2049 outfile = open_tmpfile (&stdin_nm, template);
2050 if (outfile == 0)
2051 pfatal_with_name (_("fopen (temporary file)"));
2052 while (!feof (stdin) && ! ferror (stdin))
2053 {
2054 char buf[2048];
2055 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
2056 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2057 pfatal_with_name (_("fwrite (temporary file)"));
2058 }
2059 fclose (outfile);
2060
2061 /* Replace the name that read_all_makefiles will
2062 see with the name of the temporary file. */
2063 makefiles->list[i] = strcache_add (stdin_nm);
2064
2065 /* Make sure the temporary file will not be remade. */
2066 {
2067 struct file *f = enter_file (strcache_add (stdin_nm));
2068 f->updated = 1;
2069 f->update_status = 0;
2070 f->command_state = cs_finished;
2071 /* Can't be intermediate, or it'll be removed too early for
2072 make re-exec. */
2073 f->intermediate = 0;
2074 f->dontcare = 0;
2075 }
2076 }
2077 }
2078
2079#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
2080#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
2081 /* Set up to handle children dying. This must be done before
2082 reading in the makefiles so that `shell' function calls will work.
2083
2084 If we don't have a hanging wait we have to fall back to old, broken
2085 functionality here and rely on the signal handler and counting
2086 children.
2087
2088 If we're using the jobs pipe we need a signal handler so that
2089 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
2090 jobserver pipe in job.c if we're waiting for a token.
2091
2092 If none of these are true, we don't need a signal handler at all. */
2093 {
2094 RETSIGTYPE child_handler (int sig);
2095# if defined SIGCHLD
2096 bsd_signal (SIGCHLD, child_handler);
2097# endif
2098# if defined SIGCLD && SIGCLD != SIGCHLD
2099 bsd_signal (SIGCLD, child_handler);
2100# endif
2101 }
2102#endif
2103#endif
2104
2105 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2106#ifdef SIGUSR1
2107 bsd_signal (SIGUSR1, debug_signal_handler);
2108#endif
2109
2110 /* Define the initial list of suffixes for old-style rules. */
2111
2112 set_default_suffixes ();
2113
2114 /* Define the file rules for the built-in suffix rules. These will later
2115 be converted into pattern rules. We used to do this in
2116 install_default_implicit_rules, but since that happens after reading
2117 makefiles, it results in the built-in pattern rules taking precedence
2118 over makefile-specified suffix rules, which is wrong. */
2119
2120 install_default_suffix_rules ();
2121
2122 /* Define some internal and special variables. */
2123
2124 define_automatic_variables ();
2125
2126 /* Set up the MAKEFLAGS and MFLAGS variables
2127 so makefiles can look at them. */
2128
2129 define_makeflags (0, 0);
2130
2131 /* Define the default variables. */
2132 define_default_variables ();
2133
2134 default_file = enter_file (strcache_add (".DEFAULT"));
2135
2136 {
2137 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
2138 default_goal_name = &v->value;
2139 }
2140
2141 /* Read all the makefiles. */
2142
2143 read_makefiles
2144 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2145
2146#ifdef WINDOWS32
2147 /* look one last time after reading all Makefiles */
2148 if (no_default_sh_exe)
2149 no_default_sh_exe = !find_and_set_default_shell(NULL);
2150#endif /* WINDOWS32 */
2151
2152#if defined (__MSDOS__) || defined (__EMX__)
2153 /* We need to know what kind of shell we will be using. */
2154 {
2155 extern int _is_unixy_shell (const char *_path);
2156 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2157 extern int unixy_shell;
2158 extern char *default_shell;
2159
2160 if (shv && *shv->value)
2161 {
2162 char *shell_path = recursively_expand(shv);
2163
2164 if (shell_path && _is_unixy_shell (shell_path))
2165 unixy_shell = 1;
2166 else
2167 unixy_shell = 0;
2168 if (shell_path)
2169 default_shell = shell_path;
2170 }
2171 }
2172#endif /* __MSDOS__ || __EMX__ */
2173
2174 /* Decode switches again, in case the variables were set by the makefile. */
2175#ifdef KMK
2176 decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
2177#else /* !KMK */
2178 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2179#if 0
2180 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2181#endif
2182#endif /* !KMK */
2183
2184#if defined (__MSDOS__) || defined (__EMX__)
2185 if (job_slots != 1
2186# ifdef __EMX__
2187 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2188# endif
2189 )
2190 {
2191 error (NILF,
2192 _("Parallel jobs (-j) are not supported on this platform."));
2193 error (NILF, _("Resetting to single job (-j1) mode."));
2194 job_slots = 1;
2195 }
2196#endif
2197
2198#ifdef MAKE_JOBSERVER
2199 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
2200
2201 if (jobserver_fds)
2202 {
2203 const char *cp;
2204 unsigned int ui;
2205
2206 for (ui=1; ui < jobserver_fds->idx; ++ui)
2207 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
2208 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
2209
2210 /* Now parse the fds string and make sure it has the proper format. */
2211
2212 cp = jobserver_fds->list[0];
2213
2214 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
2215 fatal (NILF,
2216 _("internal error: invalid --jobserver-fds string `%s'"), cp);
2217
2218 DB (DB_JOBS,
2219 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
2220
2221 /* The combination of a pipe + !job_slots means we're using the
2222 jobserver. If !job_slots and we don't have a pipe, we can start
2223 infinite jobs. If we see both a pipe and job_slots >0 that means the
2224 user set -j explicitly. This is broken; in this case obey the user
2225 (ignore the jobserver pipe for this make) but print a message. */
2226
2227 if (job_slots > 0)
2228 error (NILF,
2229 _("warning: -jN forced in submake: disabling jobserver mode."));
2230
2231 /* Create a duplicate pipe, that will be closed in the SIGCHLD
2232 handler. If this fails with EBADF, the parent has closed the pipe
2233 on us because it didn't think we were a submake. If so, print a
2234 warning then default to -j1. */
2235
2236 else if ((job_rfd = dup (job_fds[0])) < 0)
2237 {
2238 if (errno != EBADF)
2239 pfatal_with_name (_("dup jobserver"));
2240
2241 error (NILF,
2242 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
2243 job_slots = 1;
2244 }
2245
2246 if (job_slots > 0)
2247 {
2248 close (job_fds[0]);
2249 close (job_fds[1]);
2250 job_fds[0] = job_fds[1] = -1;
2251 free (jobserver_fds->list);
2252 free (jobserver_fds);
2253 jobserver_fds = 0;
2254 }
2255 }
2256
2257 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
2258 Set up the pipe and install the fds option for our children. */
2259
2260 if (job_slots > 1)
2261 {
2262 char *cp;
2263 char c = '+';
2264
2265 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
2266 pfatal_with_name (_("creating jobs pipe"));
2267
2268 /* Every make assumes that it always has one job it can run. For the
2269 submakes it's the token they were given by their parent. For the
2270 top make, we just subtract one from the number the user wants. We
2271 want job_slots to be 0 to indicate we're using the jobserver. */
2272
2273 master_job_slots = job_slots;
2274
2275 while (--job_slots)
2276 {
2277 int r;
2278
2279 EINTRLOOP (r, write (job_fds[1], &c, 1));
2280 if (r != 1)
2281 pfatal_with_name (_("init jobserver pipe"));
2282 }
2283
2284 /* Fill in the jobserver_fds struct for our children. */
2285
2286 cp = xmalloc ((sizeof ("1024")*2)+1);
2287 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2288
2289 jobserver_fds = (struct stringlist *)
2290 xmalloc (sizeof (struct stringlist));
2291 jobserver_fds->list = xmalloc (sizeof (char *));
2292 jobserver_fds->list[0] = cp;
2293 jobserver_fds->idx = 1;
2294 jobserver_fds->max = 1;
2295 }
2296#endif
2297
2298#ifndef MAKE_SYMLINKS
2299 if (check_symlink_flag)
2300 {
2301 error (NILF, _("Symbolic links not supported: disabling -L."));
2302 check_symlink_flag = 0;
2303 }
2304#endif
2305
2306 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2307
2308 define_makeflags (1, 0);
2309
2310 /* Make each `struct dep' point at the `struct file' for the file
2311 depended on. Also do magic for special targets. */
2312
2313 snap_deps ();
2314
2315 /* Convert old-style suffix rules to pattern rules. It is important to
2316 do this before installing the built-in pattern rules below, so that
2317 makefile-specified suffix rules take precedence over built-in pattern
2318 rules. */
2319
2320 convert_to_pattern ();
2321
2322 /* Install the default implicit pattern rules.
2323 This used to be done before reading the makefiles.
2324 But in that case, built-in pattern rules were in the chain
2325 before user-defined ones, so they matched first. */
2326
2327 install_default_implicit_rules ();
2328
2329 /* Compute implicit rule limits. */
2330
2331 count_implicit_rule_limits ();
2332
2333 /* Construct the listings of directories in VPATH lists. */
2334
2335 build_vpath_lists ();
2336
2337 /* Mark files given with -o flags as very old and as having been updated
2338 already, and files given with -W flags as brand new (time-stamp as far
2339 as possible into the future). If restarts is set we'll do -W later. */
2340
2341 if (old_files != 0)
2342 {
2343 const char **p;
2344 for (p = old_files->list; *p != 0; ++p)
2345 {
2346 struct file *f = enter_file (*p);
2347 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2348 f->updated = 1;
2349 f->update_status = 0;
2350 f->command_state = cs_finished;
2351 }
2352 }
2353
2354 if (!restarts && new_files != 0)
2355 {
2356 const char **p;
2357 for (p = new_files->list; *p != 0; ++p)
2358 {
2359 struct file *f = enter_file (*p);
2360 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2361 }
2362 }
2363
2364 /* Initialize the remote job module. */
2365 remote_setup ();
2366
2367 if (read_makefiles != 0)
2368 {
2369 /* Update any makefiles if necessary. */
2370
2371 FILE_TIMESTAMP *makefile_mtimes = 0;
2372 unsigned int mm_idx = 0;
2373 char **nargv = argv;
2374 int nargc = argc;
2375 int orig_db_level = db_level;
2376 int status;
2377
2378 if (! ISDB (DB_MAKEFILES))
2379 db_level = DB_NONE;
2380
2381 DB (DB_BASIC, (_("Updating makefiles....\n")));
2382
2383 /* Remove any makefiles we don't want to try to update.
2384 Also record the current modtimes so we can compare them later. */
2385 {
2386 register struct dep *d, *last;
2387 last = 0;
2388 d = read_makefiles;
2389 while (d != 0)
2390 {
2391 struct file *f = d->file;
2392 if (f->double_colon)
2393 for (f = f->double_colon; f != NULL; f = f->prev)
2394 {
2395 if (f->deps == 0 && f->cmds != 0)
2396 {
2397 /* This makefile is a :: target with commands, but
2398 no dependencies. So, it will always be remade.
2399 This might well cause an infinite loop, so don't
2400 try to remake it. (This will only happen if
2401 your makefiles are written exceptionally
2402 stupidly; but if you work for Athena, that's how
2403 you write your makefiles.) */
2404
2405 DB (DB_VERBOSE,
2406 (_("Makefile `%s' might loop; not remaking it.\n"),
2407 f->name));
2408
2409 if (last == 0)
2410 read_makefiles = d->next;
2411 else
2412 last->next = d->next;
2413
2414 /* Free the storage. */
2415 free_dep (d);
2416
2417 d = last == 0 ? read_makefiles : last->next;
2418
2419 break;
2420 }
2421 }
2422 if (f == NULL || !f->double_colon)
2423 {
2424 makefile_mtimes = xrealloc (makefile_mtimes,
2425 (mm_idx+1)
2426 * sizeof (FILE_TIMESTAMP));
2427 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2428 last = d;
2429 d = d->next;
2430 }
2431 }
2432 }
2433
2434 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2435 define_makeflags (1, 1);
2436
2437 rebuilding_makefiles = 1;
2438 status = update_goal_chain (read_makefiles);
2439 rebuilding_makefiles = 0;
2440
2441 switch (status)
2442 {
2443 case 1:
2444 /* The only way this can happen is if the user specified -q and asked
2445 * for one of the makefiles to be remade as a target on the command
2446 * line. Since we're not actually updating anything with -q we can
2447 * treat this as "did nothing".
2448 */
2449
2450 case -1:
2451 /* Did nothing. */
2452 break;
2453
2454 case 2:
2455 /* Failed to update. Figure out if we care. */
2456 {
2457 /* Nonzero if any makefile was successfully remade. */
2458 int any_remade = 0;
2459 /* Nonzero if any makefile we care about failed
2460 in updating or could not be found at all. */
2461 int any_failed = 0;
2462 unsigned int i;
2463 struct dep *d;
2464
2465 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2466 {
2467 /* Reset the considered flag; we may need to look at the file
2468 again to print an error. */
2469 d->file->considered = 0;
2470
2471 if (d->file->updated)
2472 {
2473 /* This makefile was updated. */
2474 if (d->file->update_status == 0)
2475 {
2476 /* It was successfully updated. */
2477 any_remade |= (file_mtime_no_search (d->file)
2478 != makefile_mtimes[i]);
2479 }
2480 else if (! (d->changed & RM_DONTCARE))
2481 {
2482 FILE_TIMESTAMP mtime;
2483 /* The update failed and this makefile was not
2484 from the MAKEFILES variable, so we care. */
2485 error (NILF, _("Failed to remake makefile `%s'."),
2486 d->file->name);
2487 mtime = file_mtime_no_search (d->file);
2488 any_remade |= (mtime != NONEXISTENT_MTIME
2489 && mtime != makefile_mtimes[i]);
2490 makefile_status = MAKE_FAILURE;
2491 }
2492 }
2493 else
2494 /* This makefile was not found at all. */
2495 if (! (d->changed & RM_DONTCARE))
2496 {
2497 /* This is a makefile we care about. See how much. */
2498 if (d->changed & RM_INCLUDED)
2499 /* An included makefile. We don't need
2500 to die, but we do want to complain. */
2501 error (NILF,
2502 _("Included makefile `%s' was not found."),
2503 dep_name (d));
2504 else
2505 {
2506 /* A normal makefile. We must die later. */
2507 error (NILF, _("Makefile `%s' was not found"),
2508 dep_name (d));
2509 any_failed = 1;
2510 }
2511 }
2512 }
2513 /* Reset this to empty so we get the right error message below. */
2514 read_makefiles = 0;
2515
2516 if (any_remade)
2517 goto re_exec;
2518 if (any_failed)
2519 die (2);
2520 break;
2521 }
2522
2523 case 0:
2524 re_exec:
2525 /* Updated successfully. Re-exec ourselves. */
2526
2527 remove_intermediates (0);
2528
2529 if (print_data_base_flag)
2530 print_data_base ();
2531
2532 log_working_directory (0);
2533
2534 clean_jobserver (0);
2535
2536 if (makefiles != 0)
2537 {
2538 /* These names might have changed. */
2539 int i, j = 0;
2540 for (i = 1; i < argc; ++i)
2541 if (strneq (argv[i], "-f", 2)) /* XXX */
2542 {
2543 char *p = &argv[i][2];
2544 if (*p == '\0')
2545 /* This cast is OK since we never modify argv. */
2546 argv[++i] = (char *) makefiles->list[j];
2547 else
2548 argv[i] = xstrdup (concat ("-f", makefiles->list[j], ""));
2549 ++j;
2550 }
2551 }
2552
2553 /* Add -o option for the stdin temporary file, if necessary. */
2554 if (stdin_nm)
2555 {
2556 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2557 memcpy (nargv, argv, argc * sizeof (char *));
2558 nargv[nargc++] = xstrdup (concat ("-o", stdin_nm, ""));
2559 nargv[nargc] = 0;
2560 }
2561
2562 if (directories != 0 && directories->idx > 0)
2563 {
2564 int bad = 1;
2565 if (directory_before_chdir != 0)
2566 {
2567 if (chdir (directory_before_chdir) < 0)
2568 perror_with_name ("chdir", "");
2569 else
2570 bad = 0;
2571 }
2572 if (bad)
2573 fatal (NILF, _("Couldn't change back to original directory."));
2574 }
2575
2576 ++restarts;
2577
2578 if (ISDB (DB_BASIC))
2579 {
2580 char **p;
2581 printf (_("Re-executing[%u]:"), restarts);
2582 for (p = nargv; *p != 0; ++p)
2583 printf (" %s", *p);
2584 putchar ('\n');
2585 }
2586
2587#ifndef _AMIGA
2588 {
2589 char **p;
2590 for (p = environ; *p != 0; ++p)
2591 {
2592 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2593 && (*p)[MAKELEVEL_LENGTH] == '=')
2594 {
2595 *p = alloca (40);
2596 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2597 }
2598 if (strneq (*p, "MAKE_RESTARTS=", 14))
2599 {
2600 *p = alloca (40);
2601 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2602 restarts = 0;
2603 }
2604 }
2605 }
2606#else /* AMIGA */
2607 {
2608 char buffer[256];
2609
2610 sprintf (buffer, "%u", makelevel);
2611 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2612
2613 sprintf (buffer, "%u", restarts);
2614 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2615 restarts = 0;
2616 }
2617#endif
2618
2619 /* If we didn't set the restarts variable yet, add it. */
2620 if (restarts)
2621 {
2622 char *b = alloca (40);
2623 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2624 putenv (b);
2625 }
2626
2627 fflush (stdout);
2628 fflush (stderr);
2629
2630 /* Close the dup'd jobserver pipe if we opened one. */
2631 if (job_rfd >= 0)
2632 close (job_rfd);
2633
2634#ifdef _AMIGA
2635 exec_command (nargv);
2636 exit (0);
2637#elif defined (__EMX__)
2638 {
2639 /* It is not possible to use execve() here because this
2640 would cause the parent process to be terminated with
2641 exit code 0 before the child process has been terminated.
2642 Therefore it may be the best solution simply to spawn the
2643 child process including all file handles and to wait for its
2644 termination. */
2645 int pid;
2646 int status;
2647 pid = child_execute_job (0, 1, nargv, environ);
2648
2649 /* is this loop really necessary? */
2650 do {
2651 pid = wait (&status);
2652 } while (pid <= 0);
2653 /* use the exit code of the child process */
2654 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2655 }
2656#else
2657 exec_command (nargv, environ);
2658#endif
2659 /* NOTREACHED */
2660
2661 default:
2662#define BOGUS_UPDATE_STATUS 0
2663 assert (BOGUS_UPDATE_STATUS);
2664 break;
2665 }
2666
2667 db_level = orig_db_level;
2668
2669 /* Free the makefile mtimes (if we allocated any). */
2670 if (makefile_mtimes)
2671 free (makefile_mtimes);
2672 }
2673
2674 /* Set up `MAKEFLAGS' again for the normal targets. */
2675 define_makeflags (1, 0);
2676
2677 /* Set always_make_flag if -B was given. */
2678 always_make_flag = always_make_set;
2679
2680 /* If restarts is set we haven't set up -W files yet, so do that now. */
2681 if (restarts && new_files != 0)
2682 {
2683 const char **p;
2684 for (p = new_files->list; *p != 0; ++p)
2685 {
2686 struct file *f = enter_file (*p);
2687 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2688 }
2689 }
2690
2691 /* If there is a temp file from reading a makefile from stdin, get rid of
2692 it now. */
2693 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2694 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2695
2696 {
2697 int status;
2698
2699 /* If there were no command-line goals, use the default. */
2700 if (goals == 0)
2701 {
2702 if (**default_goal_name != '\0')
2703 {
2704 if (default_goal_file == 0 ||
2705 strcmp (*default_goal_name, default_goal_file->name) != 0)
2706 {
2707 default_goal_file = lookup_file (*default_goal_name);
2708
2709 /* In case user set .DEFAULT_GOAL to a non-existent target
2710 name let's just enter this name into the table and let
2711 the standard logic sort it out. */
2712 if (default_goal_file == 0)
2713 {
2714 struct nameseq *ns;
2715 char *p = *default_goal_name;
2716
2717#ifndef CONFIG_WITH_ALLOC_CACHES
2718 ns = multi_glob (
2719 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2720 sizeof (struct nameseq));
2721#else
2722 ns = multi_glob (
2723 parse_file_seq (&p, '\0', &nameseq_cache, 1),
2724 &nameseq_cache);
2725#endif
2726
2727 /* .DEFAULT_GOAL should contain one target. */
2728 if (ns->next != 0)
2729 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2730
2731#ifndef CONFIG_WITH_VALUE_LENGTH
2732 default_goal_file = enter_file (strcache_add (ns->name));
2733#else
2734 default_goal_file = enter_file (ns->name);
2735#endif
2736
2737 ns->name = 0; /* It was reused by enter_file(). */
2738 free_ns_chain (ns);
2739 }
2740 }
2741
2742 goals = alloc_dep ();
2743 goals->file = default_goal_file;
2744 }
2745 }
2746 else
2747 lastgoal->next = 0;
2748
2749
2750 if (!goals)
2751 {
2752 if (read_makefiles == 0)
2753 fatal (NILF, _("No targets specified and no makefile found"));
2754
2755 fatal (NILF, _("No targets"));
2756 }
2757
2758 /* Update the goals. */
2759
2760 DB (DB_BASIC, (_("Updating goal targets....\n")));
2761
2762 switch (update_goal_chain (goals))
2763 {
2764 case -1:
2765 /* Nothing happened. */
2766 case 0:
2767 /* Updated successfully. */
2768 status = makefile_status;
2769 break;
2770 case 1:
2771 /* We are under -q and would run some commands. */
2772 status = MAKE_TROUBLE;
2773 break;
2774 case 2:
2775 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2776 but in VMS, there is only success and failure. */
2777 status = MAKE_FAILURE;
2778 break;
2779 default:
2780 abort ();
2781 }
2782
2783 /* If we detected some clock skew, generate one last warning */
2784 if (clock_skew_detected)
2785 error (NILF,
2786 _("warning: Clock skew detected. Your build may be incomplete."));
2787
2788 /* Exit. */
2789 die (status);
2790 }
2791
2792 /* NOTREACHED */
2793 return 0;
2794}
2795
2796
2797/* Parsing of arguments, decoding of switches. */
2798
2799static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2800static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2801 (sizeof (long_option_aliases) /
2802 sizeof (long_option_aliases[0]))];
2803
2804/* Fill in the string and vector for getopt. */
2805static void
2806init_switches (void)
2807{
2808 char *p;
2809 unsigned int c;
2810 unsigned int i;
2811
2812 if (options[0] != '\0')
2813 /* Already done. */
2814 return;
2815
2816 p = options;
2817
2818 /* Return switch and non-switch args in order, regardless of
2819 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2820 *p++ = '-';
2821
2822 for (i = 0; switches[i].c != '\0'; ++i)
2823 {
2824 long_options[i].name = (switches[i].long_name == 0 ? "" :
2825 switches[i].long_name);
2826 long_options[i].flag = 0;
2827 long_options[i].val = switches[i].c;
2828 if (short_option (switches[i].c))
2829 *p++ = switches[i].c;
2830 switch (switches[i].type)
2831 {
2832 case flag:
2833 case flag_off:
2834 case ignore:
2835 long_options[i].has_arg = no_argument;
2836 break;
2837
2838 case string:
2839 case filename:
2840 case positive_int:
2841 case floating:
2842 if (short_option (switches[i].c))
2843 *p++ = ':';
2844 if (switches[i].noarg_value != 0)
2845 {
2846 if (short_option (switches[i].c))
2847 *p++ = ':';
2848 long_options[i].has_arg = optional_argument;
2849 }
2850 else
2851 long_options[i].has_arg = required_argument;
2852 break;
2853 }
2854 }
2855 *p = '\0';
2856 for (c = 0; c < (sizeof (long_option_aliases) /
2857 sizeof (long_option_aliases[0]));
2858 ++c)
2859 long_options[i++] = long_option_aliases[c];
2860 long_options[i].name = 0;
2861}
2862
2863static void
2864handle_non_switch_argument (char *arg, int env)
2865{
2866 /* Non-option argument. It might be a variable definition. */
2867 struct variable *v;
2868 if (arg[0] == '-' && arg[1] == '\0')
2869 /* Ignore plain `-' for compatibility. */
2870 return;
2871#ifndef CONFIG_WITH_VALUE_LENGTH
2872 v = try_variable_definition (0, arg, o_command, 0);
2873#else
2874 v = try_variable_definition (0, arg, NULL, o_command, 0);
2875#endif
2876 if (v != 0)
2877 {
2878 /* It is indeed a variable definition. If we don't already have this
2879 one, record a pointer to the variable for later use in
2880 define_makeflags. */
2881 struct command_variable *cv;
2882
2883 for (cv = command_variables; cv != 0; cv = cv->next)
2884 if (cv->variable == v)
2885 break;
2886
2887 if (! cv) {
2888 cv = xmalloc (sizeof (*cv));
2889 cv->variable = v;
2890 cv->next = command_variables;
2891 command_variables = cv;
2892 }
2893 }
2894 else if (! env)
2895 {
2896 /* Not an option or variable definition; it must be a goal
2897 target! Enter it as a file and add it to the dep chain of
2898 goals. */
2899 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2900 f->cmd_target = 1;
2901
2902 if (goals == 0)
2903 {
2904 goals = alloc_dep ();
2905 lastgoal = goals;
2906 }
2907 else
2908 {
2909 lastgoal->next = alloc_dep ();
2910 lastgoal = lastgoal->next;
2911 }
2912
2913 lastgoal->file = f;
2914
2915 {
2916 /* Add this target name to the MAKECMDGOALS variable. */
2917 struct variable *gv;
2918 const char *value;
2919
2920 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2921 if (gv == 0)
2922 value = f->name;
2923 else
2924 {
2925 /* Paste the old and new values together */
2926 unsigned int oldlen, newlen;
2927 char *vp;
2928
2929 oldlen = strlen (gv->value);
2930 newlen = strlen (f->name);
2931 vp = alloca (oldlen + 1 + newlen + 1);
2932 memcpy (vp, gv->value, oldlen);
2933 vp[oldlen] = ' ';
2934 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2935 value = vp;
2936 }
2937 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2938 }
2939 }
2940}
2941
2942/* Print a nice usage method. */
2943
2944static void
2945print_usage (int bad)
2946{
2947 const char *const *cpp;
2948 FILE *usageto;
2949
2950 if (print_version_flag)
2951 print_version ();
2952
2953 usageto = bad ? stderr : stdout;
2954
2955 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2956
2957 for (cpp = usage; *cpp; ++cpp)
2958 fputs (_(*cpp), usageto);
2959
2960#ifdef KMK
2961 if (!remote_description || *remote_description == '\0')
2962 printf (_("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
2963 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
2964 else
2965 printf (_("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
2966 KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
2967#else /* !KMK */
2968 if (!remote_description || *remote_description == '\0')
2969 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2970 else
2971 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2972 make_host, remote_description);
2973#endif /* !KMK */
2974
2975 fprintf (usageto, _("Report bugs to <[email protected]>\n"));
2976}
2977
2978/* Decode switches from ARGC and ARGV.
2979 They came from the environment if ENV is nonzero. */
2980
2981static void
2982decode_switches (int argc, char **argv, int env)
2983{
2984 int bad = 0;
2985 register const struct command_switch *cs;
2986 register struct stringlist *sl;
2987 register int c;
2988
2989 /* getopt does most of the parsing for us.
2990 First, get its vectors set up. */
2991
2992 init_switches ();
2993
2994 /* Let getopt produce error messages for the command line,
2995 but not for options from the environment. */
2996 opterr = !env;
2997 /* Reset getopt's state. */
2998 optind = 0;
2999
3000 while (optind < argc)
3001 {
3002 /* Parse the next argument. */
3003 c = getopt_long (argc, argv, options, long_options, (int *) 0);
3004 if (c == EOF)
3005 /* End of arguments, or "--" marker seen. */
3006 break;
3007 else if (c == 1)
3008 /* An argument not starting with a dash. */
3009 handle_non_switch_argument (optarg, env);
3010 else if (c == '?')
3011 /* Bad option. We will print a usage message and die later.
3012 But continue to parse the other options so the user can
3013 see all he did wrong. */
3014 bad = 1;
3015 else
3016 for (cs = switches; cs->c != '\0'; ++cs)
3017 if (cs->c == c)
3018 {
3019 /* Whether or not we will actually do anything with
3020 this switch. We test this individually inside the
3021 switch below rather than just once outside it, so that
3022 options which are to be ignored still consume args. */
3023 int doit = !env || cs->env;
3024
3025 switch (cs->type)
3026 {
3027 default:
3028 abort ();
3029
3030 case ignore:
3031 break;
3032
3033 case flag:
3034 case flag_off:
3035 if (doit)
3036 *(int *) cs->value_ptr = cs->type == flag;
3037 break;
3038
3039 case string:
3040 case filename:
3041 if (!doit)
3042 break;
3043
3044 if (optarg == 0)
3045 optarg = xstrdup (cs->noarg_value);
3046 else if (*optarg == '\0')
3047 {
3048 error (NILF, _("the `-%c' option requires a non-empty string argument"),
3049 cs->c);
3050 bad = 1;
3051 }
3052
3053 sl = *(struct stringlist **) cs->value_ptr;
3054 if (sl == 0)
3055 {
3056 sl = (struct stringlist *)
3057 xmalloc (sizeof (struct stringlist));
3058 sl->max = 5;
3059 sl->idx = 0;
3060 sl->list = xmalloc (5 * sizeof (char *));
3061 *(struct stringlist **) cs->value_ptr = sl;
3062 }
3063 else if (sl->idx == sl->max - 1)
3064 {
3065 sl->max += 5;
3066 sl->list = xrealloc ((void *)sl->list, /* bird */
3067 sl->max * sizeof (char *));
3068 }
3069 if (cs->type == filename)
3070 sl->list[sl->idx++] = expand_command_line_file (optarg);
3071 else
3072 sl->list[sl->idx++] = optarg;
3073 sl->list[sl->idx] = 0;
3074 break;
3075
3076 case positive_int:
3077 /* See if we have an option argument; if we do require that
3078 it's all digits, not something like "10foo". */
3079 if (optarg == 0 && argc > optind)
3080 {
3081 const char *cp;
3082 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3083 ;
3084 if (cp[0] == '\0')
3085 optarg = argv[optind++];
3086 }
3087
3088 if (!doit)
3089 break;
3090
3091 if (optarg != 0)
3092 {
3093 int i = atoi (optarg);
3094 const char *cp;
3095
3096 /* Yes, I realize we're repeating this in some cases. */
3097 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
3098 ;
3099
3100 if (i < 1 || cp[0] != '\0')
3101 {
3102 error (NILF, _("the `-%c' option requires a positive integral argument"),
3103 cs->c);
3104 bad = 1;
3105 }
3106 else
3107 *(unsigned int *) cs->value_ptr = i;
3108 }
3109 else
3110 *(unsigned int *) cs->value_ptr
3111 = *(unsigned int *) cs->noarg_value;
3112 break;
3113
3114#ifndef NO_FLOAT
3115 case floating:
3116 if (optarg == 0 && optind < argc
3117 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3118 optarg = argv[optind++];
3119
3120 if (doit)
3121 *(double *) cs->value_ptr
3122 = (optarg != 0 ? atof (optarg)
3123 : *(double *) cs->noarg_value);
3124
3125 break;
3126#endif
3127 }
3128
3129 /* We've found the switch. Stop looking. */
3130 break;
3131 }
3132 }
3133
3134 /* There are no more options according to getting getopt, but there may
3135 be some arguments left. Since we have asked for non-option arguments
3136 to be returned in order, this only happens when there is a "--"
3137 argument to prevent later arguments from being options. */
3138 while (optind < argc)
3139 handle_non_switch_argument (argv[optind++], env);
3140
3141
3142 if (!env && (bad || print_usage_flag))
3143 {
3144 print_usage (bad);
3145 die (bad ? 2 : 0);
3146 }
3147}
3148
3149/* Decode switches from environment variable ENVAR (which is LEN chars long).
3150 We do this by chopping the value into a vector of words, prepending a
3151 dash to the first word if it lacks one, and passing the vector to
3152 decode_switches. */
3153
3154static void
3155decode_env_switches (char *envar, unsigned int len)
3156{
3157 char *varref = alloca (2 + len + 2);
3158 char *value, *p;
3159 int argc;
3160 char **argv;
3161
3162 /* Get the variable's value. */
3163 varref[0] = '$';
3164 varref[1] = '(';
3165 memcpy (&varref[2], envar, len);
3166 varref[2 + len] = ')';
3167 varref[2 + len + 1] = '\0';
3168 value = variable_expand (varref);
3169
3170 /* Skip whitespace, and check for an empty value. */
3171 value = next_token (value);
3172 len = strlen (value);
3173 if (len == 0)
3174 return;
3175
3176 /* Allocate a vector that is definitely big enough. */
3177 argv = alloca ((1 + len + 1) * sizeof (char *));
3178
3179 /* Allocate a buffer to copy the value into while we split it into words
3180 and unquote it. We must use permanent storage for this because
3181 decode_switches may store pointers into the passed argument words. */
3182 p = xmalloc (2 * len);
3183
3184 /* getopt will look at the arguments starting at ARGV[1].
3185 Prepend a spacer word. */
3186 argv[0] = 0;
3187 argc = 1;
3188 argv[argc] = p;
3189 while (*value != '\0')
3190 {
3191 if (*value == '\\' && value[1] != '\0')
3192 ++value; /* Skip the backslash. */
3193 else if (isblank ((unsigned char)*value))
3194 {
3195 /* End of the word. */
3196 *p++ = '\0';
3197 argv[++argc] = p;
3198 do
3199 ++value;
3200 while (isblank ((unsigned char)*value));
3201 continue;
3202 }
3203 *p++ = *value++;
3204 }
3205 *p = '\0';
3206 argv[++argc] = 0;
3207
3208 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3209 /* The first word doesn't start with a dash and isn't a variable
3210 definition. Add a dash and pass it along to decode_switches. We
3211 need permanent storage for this in case decode_switches saves
3212 pointers into the value. */
3213 argv[1] = xstrdup (concat ("-", argv[1], ""));
3214
3215 /* Parse those words. */
3216 decode_switches (argc, argv, 1);
3217}
3218
3219
3220/* Quote the string IN so that it will be interpreted as a single word with
3221 no magic by decode_env_switches; also double dollar signs to avoid
3222 variable expansion in make itself. Write the result into OUT, returning
3223 the address of the next character to be written.
3224 Allocating space for OUT twice the length of IN is always sufficient. */
3225
3226static char *
3227quote_for_env (char *out, const char *in)
3228{
3229 while (*in != '\0')
3230 {
3231 if (*in == '$')
3232 *out++ = '$';
3233 else if (isblank ((unsigned char)*in) || *in == '\\')
3234 *out++ = '\\';
3235 *out++ = *in++;
3236 }
3237
3238 return out;
3239}
3240
3241/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3242 command switches. Include options with args if ALL is nonzero.
3243 Don't include options with the `no_makefile' flag set if MAKEFILE. */
3244
3245static void
3246define_makeflags (int all, int makefile)
3247{
3248#ifdef KMK
3249 static const char ref[] = "$(KMK_OVERRIDES)";
3250#else
3251 static const char ref[] = "$(MAKEOVERRIDES)";
3252#endif
3253 static const char posixref[] = "$(-*-command-variables-*-)";
3254 register const struct command_switch *cs;
3255 char *flagstring;
3256 register char *p;
3257 unsigned int words;
3258 struct variable *v;
3259
3260 /* We will construct a linked list of `struct flag's describing
3261 all the flags which need to go in MAKEFLAGS. Then, once we
3262 know how many there are and their lengths, we can put them all
3263 together in a string. */
3264
3265 struct flag
3266 {
3267 struct flag *next;
3268 const struct command_switch *cs;
3269 const char *arg;
3270 };
3271 struct flag *flags = 0;
3272 unsigned int flagslen = 0;
3273#define ADD_FLAG(ARG, LEN) \
3274 do { \
3275 struct flag *new = alloca (sizeof (struct flag)); \
3276 new->cs = cs; \
3277 new->arg = (ARG); \
3278 new->next = flags; \
3279 flags = new; \
3280 if (new->arg == 0) \
3281 ++flagslen; /* Just a single flag letter. */ \
3282 else \
3283 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
3284 if (!short_option (cs->c)) \
3285 /* This switch has no single-letter version, so we use the long. */ \
3286 flagslen += 2 + strlen (cs->long_name); \
3287 } while (0)
3288
3289 for (cs = switches; cs->c != '\0'; ++cs)
3290 if (cs->toenv && (!makefile || !cs->no_makefile))
3291 switch (cs->type)
3292 {
3293 case ignore:
3294 break;
3295
3296 case flag:
3297 case flag_off:
3298 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3299 && (cs->default_value == 0
3300 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3301 ADD_FLAG (0, 0);
3302 break;
3303
3304 case positive_int:
3305 if (all)
3306 {
3307 if ((cs->default_value != 0
3308 && (*(unsigned int *) cs->value_ptr
3309 == *(unsigned int *) cs->default_value)))
3310 break;
3311 else if (cs->noarg_value != 0
3312 && (*(unsigned int *) cs->value_ptr ==
3313 *(unsigned int *) cs->noarg_value))
3314 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3315#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
3316 else if (cs->c == 'j')
3317 /* Special case for `-j'. */
3318 ADD_FLAG ("1", 1);
3319#endif
3320 else
3321 {
3322 char *buf = alloca (30);
3323 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3324 ADD_FLAG (buf, strlen (buf));
3325 }
3326 }
3327 break;
3328
3329#ifndef NO_FLOAT
3330 case floating:
3331 if (all)
3332 {
3333 if (cs->default_value != 0
3334 && (*(double *) cs->value_ptr
3335 == *(double *) cs->default_value))
3336 break;
3337 else if (cs->noarg_value != 0
3338 && (*(double *) cs->value_ptr
3339 == *(double *) cs->noarg_value))
3340 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3341 else
3342 {
3343 char *buf = alloca (100);
3344 sprintf (buf, "%g", *(double *) cs->value_ptr);
3345 ADD_FLAG (buf, strlen (buf));
3346 }
3347 }
3348 break;
3349#endif
3350
3351 case filename:
3352 case string:
3353 if (all)
3354 {
3355 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3356 if (sl != 0)
3357 {
3358 /* Add the elements in reverse order, because all the flags
3359 get reversed below; and the order matters for some
3360 switches (like -I). */
3361 unsigned int i = sl->idx;
3362 while (i-- > 0)
3363 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3364 }
3365 }
3366 break;
3367
3368 default:
3369 abort ();
3370 }
3371
3372 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3373
3374#undef ADD_FLAG
3375
3376 /* Construct the value in FLAGSTRING.
3377 We allocate enough space for a preceding dash and trailing null. */
3378 flagstring = alloca (1 + flagslen + 1);
3379 memset (flagstring, '\0', 1 + flagslen + 1);
3380 p = flagstring;
3381 words = 1;
3382 *p++ = '-';
3383 while (flags != 0)
3384 {
3385 /* Add the flag letter or name to the string. */
3386 if (short_option (flags->cs->c))
3387 *p++ = flags->cs->c;
3388 else
3389 {
3390 if (*p != '-')
3391 {
3392 *p++ = ' ';
3393 *p++ = '-';
3394 }
3395 *p++ = '-';
3396 strcpy (p, flags->cs->long_name);
3397 p += strlen (p);
3398 }
3399 if (flags->arg != 0)
3400 {
3401 /* A flag that takes an optional argument which in this case is
3402 omitted is specified by ARG being "". We must distinguish
3403 because a following flag appended without an intervening " -"
3404 is considered the arg for the first. */
3405 if (flags->arg[0] != '\0')
3406 {
3407 /* Add its argument too. */
3408 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3409 p = quote_for_env (p, flags->arg);
3410 }
3411 ++words;
3412 /* Write a following space and dash, for the next flag. */
3413 *p++ = ' ';
3414 *p++ = '-';
3415 }
3416 else if (!short_option (flags->cs->c))
3417 {
3418 ++words;
3419 /* Long options must each go in their own word,
3420 so we write the following space and dash. */
3421 *p++ = ' ';
3422 *p++ = '-';
3423 }
3424 flags = flags->next;
3425 }
3426
3427 /* Define MFLAGS before appending variable definitions. */
3428
3429 if (p == &flagstring[1])
3430 /* No flags. */
3431 flagstring[0] = '\0';
3432 else if (p[-1] == '-')
3433 {
3434 /* Kill the final space and dash. */
3435 p -= 2;
3436 *p = '\0';
3437 }
3438 else
3439 /* Terminate the string. */
3440 *p = '\0';
3441
3442#ifdef KMK
3443 /* Since MFLAGS is not parsed for flags, there is no reason to
3444 override any makefile redefinition. */
3445 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3446#endif /* !KMK */
3447
3448 if (all && command_variables != 0)
3449 {
3450 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3451 command-line variable definitions. */
3452
3453 if (p == &flagstring[1])
3454 /* No flags written, so elide the leading dash already written. */
3455 p = flagstring;
3456 else
3457 {
3458 /* Separate the variables from the switches with a "--" arg. */
3459 if (p[-1] != '-')
3460 {
3461 /* We did not already write a trailing " -". */
3462 *p++ = ' ';
3463 *p++ = '-';
3464 }
3465 /* There is a trailing " -"; fill it out to " -- ". */
3466 *p++ = '-';
3467 *p++ = ' ';
3468 }
3469
3470 /* Copy in the string. */
3471 if (posix_pedantic)
3472 {
3473 memcpy (p, posixref, sizeof posixref - 1);
3474 p += sizeof posixref - 1;
3475 }
3476 else
3477 {
3478 memcpy (p, ref, sizeof ref - 1);
3479 p += sizeof ref - 1;
3480 }
3481 }
3482 else if (p == &flagstring[1])
3483 {
3484 words = 0;
3485 --p;
3486 }
3487 else if (p[-1] == '-')
3488 /* Kill the final space and dash. */
3489 p -= 2;
3490 /* Terminate the string. */
3491 *p = '\0';
3492
3493#ifdef KMK
3494 v = define_variable ("KMK_FLAGS", 9,
3495 /* If there are switches, omit the leading dash
3496 unless it is a single long option with two
3497 leading dashes. */
3498 &flagstring[(flagstring[0] == '-'
3499 && flagstring[1] != '-')
3500 ? 1 : 0],
3501 /* This used to use o_env, but that lost when a
3502 makefile defined MAKEFLAGS. Makefiles set
3503 MAKEFLAGS to add switches, but we still want
3504 to redefine its value with the full set of
3505 switches. Of course, an override or command
3506 definition will still take precedence. */
3507 o_file, 1);
3508#else
3509 v = define_variable ("MAKEFLAGS", 9,
3510 /* If there are switches, omit the leading dash
3511 unless it is a single long option with two
3512 leading dashes. */
3513 &flagstring[(flagstring[0] == '-'
3514 && flagstring[1] != '-')
3515 ? 1 : 0],
3516 /* This used to use o_env, but that lost when a
3517 makefile defined MAKEFLAGS. Makefiles set
3518 MAKEFLAGS to add switches, but we still want
3519 to redefine its value with the full set of
3520 switches. Of course, an override or command
3521 definition will still take precedence. */
3522 o_file, 1);
3523#endif
3524 if (! all)
3525 /* The first time we are called, set MAKEFLAGS to always be exported.
3526 We should not do this again on the second call, because that is
3527 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3528 v->export = v_export;
3529
3530#ifdef KMK
3531 /* Provide simple access to some of the options. */
3532 {
3533 char val[32];
3534 sprintf (val, "%u", job_slots);
3535 define_variable ("KMK_OPTS_JOBS", sizeof("KMK_OPTS_JOBS") - 1,
3536 val, o_default, 1);
3537 define_variable ("KMK_OPTS_KEEP_GOING", sizeof("KMK_OPTS_KEEP_GOING") - 1,
3538 keep_going_flag ? "1" : "0", o_default, 1);
3539 define_variable ("KMK_OPTS_JUST_PRINT", sizeof("KMK_OPTS_JUST_PRINT") - 1,
3540 just_print_flag ? "1" : "0", o_default, 1);
3541 define_variable ("KMK_OPTS_PRETTY_COMMAND_PRINTING", sizeof("KMK_OPTS_PRETTY_COMMAND_PRINTING") - 1,
3542 pretty_command_printing ? "1" : "0", o_default, 1);
3543 sprintf (val, "%u", process_priority);
3544 define_variable ("KMK_OPTS_PRORITY", sizeof("KMK_OPTS_PRORITY") - 1,
3545 val, o_default, 1);
3546 sprintf (val, "%u", process_affinity);
3547 define_variable ("KMK_OPTS_AFFINITY", sizeof("KMK_OPTS_AFFINITY") - 1,
3548 val, o_default, 1);
3549#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
3550 define_variable ("KMK_OPTS_STATISTICS", sizeof("KMK_OPTS_STATISTICS") - 1,
3551 make_expensive_statistics ? "1" : "0", o_default, 1);
3552# endif
3553 }
3554#endif
3555}
3556
3557
3558/* Print version information. */
3559
3560static void
3561print_version (void)
3562{
3563 static int printed_version = 0;
3564
3565 char *precede = print_data_base_flag ? "# " : "";
3566
3567 if (printed_version)
3568 /* Do it only once. */
3569 return;
3570
3571 /* Print this untranslated. The coding standards recommend translating the
3572 (C) to the copyright symbol, but this string is going to change every
3573 year, and none of the rest of it should be translated (including the
3574 word "Copyright", so it hardly seems worth it. */
3575
3576#ifdef KMK
3577 printf ("%skmk - kBuild version %d.%d.%d (r%u)\n\
3578\n\
3579%sBased on GNU Make %s:\n\
3580%s Copyright (C) 2006 Free Software Foundation, Inc.\n\
3581\n\
3582%skBuild modifications:\n\
3583%s Copyright (C) 2005-2008 Knut St. Osmundsen.\n\
3584\n\
3585%skmkbuiltin commands derived from *BSD sources:\n\
3586%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3587%s The Regents of the University of California. All rights reserved.\n\
3588%s Copyright (c) 1998 Todd C. Miller <[email protected]>\n\
3589%s\n",
3590 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR,
3591 KBUILD_VERSION_PATCH, KBUILD_SVN_REV,
3592 precede, version_string,
3593 precede, precede, precede, precede, precede, precede,
3594 precede, precede);
3595#else
3596 printf ("%sGNU Make %s\n\
3597%sCopyright (C) 2006 Free Software Foundation, Inc.\n",
3598 precede, version_string, precede);
3599#endif
3600
3601 printf (_("%sThis is free software; see the source for copying conditions.\n\
3602%sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
3603%sPARTICULAR PURPOSE.\n"),
3604 precede, precede, precede);
3605
3606#ifdef KMK
3607# ifdef KBUILD_PATH
3608 printf (_("%s\n\
3609%sKBUILD_PATH: '%s' (default '%s')\n\
3610%sKBUILD_BIN_PATH: '%s' (default '%s')\n"),
3611 precede,
3612 precede, get_kbuild_path(), KBUILD_PATH,
3613 precede, get_kbuild_bin_path(), KBUILD_BIN_PATH);
3614# else /* !KBUILD_PATH */
3615 printf (_("%s\n\
3616%sKBUILD_PATH: '%s'\n\
3617%sKBUILD_BIN_PATH: '%s'\n"),
3618 precede,
3619 precede, get_kbuild_path(),
3620 precede, get_kbuild_bin_path());
3621# endif /* !KBUILD_PATH */
3622 if (!remote_description || *remote_description == '\0')
3623 printf (_("\n%sThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3624 precede, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU);
3625 else
3626 printf (_("\n%sThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3627 precede, KBUILD_HOST, KBUILD_HOST_ARCH, KBUILD_HOST_CPU, remote_description);
3628#else
3629 if (!remote_description || *remote_description == '\0')
3630 printf (_("\n%sThis program built for %s\n"), precede, make_host);
3631 else
3632 printf (_("\n%sThis program built for %s (%s)\n"),
3633 precede, make_host, remote_description);
3634#endif
3635
3636 printed_version = 1;
3637
3638 /* Flush stdout so the user doesn't have to wait to see the
3639 version information while things are thought about. */
3640 fflush (stdout);
3641}
3642
3643/* Print a bunch of information about this and that. */
3644
3645static void
3646print_data_base ()
3647{
3648 time_t when;
3649
3650 when = time ((time_t *) 0);
3651 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3652
3653 print_variable_data_base ();
3654 print_dir_data_base ();
3655 print_rule_data_base ();
3656 print_file_data_base ();
3657 print_vpath_data_base ();
3658#ifndef CONFIG_WITH_STRCACHE2
3659 strcache_print_stats ("#");
3660#else
3661 strcache2_print_stats_all ("#");
3662#endif
3663#ifdef CONFIG_WITH_ALLOC_CACHES
3664 alloccache_print_all ();
3665#endif
3666
3667 when = time ((time_t *) 0);
3668 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3669}
3670#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
3671
3672static void
3673print_stats ()
3674{
3675 time_t when;
3676
3677 when = time ((time_t *) 0);
3678 printf (_("\n# Make statistics, printed on %s"), ctime (&when));
3679
3680 print_variable_stats ();
3681 print_file_stats ();
3682# ifndef CONFIG_WITH_STRCACHE2
3683 strcache_print_stats ("#");
3684# else
3685 strcache2_print_stats_all ("#");
3686# endif
3687# ifdef CONFIG_WITH_ALLOC_CACHES
3688 alloccache_print_all ();
3689# endif
3690 print_heap_stats ();
3691
3692 when = time ((time_t *) 0);
3693 printf (_("\n# Finished Make statistics on %s\n"), ctime (&when));
3694}
3695#endif
3696
3697static void
3698clean_jobserver (int status)
3699{
3700 char token = '+';
3701
3702 /* Sanity: have we written all our jobserver tokens back? If our
3703 exit status is 2 that means some kind of syntax error; we might not
3704 have written all our tokens so do that now. If tokens are left
3705 after any other error code, that's bad. */
3706
3707 if (job_fds[0] != -1 && jobserver_tokens)
3708 {
3709 if (status != 2)
3710 error (NILF,
3711 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3712 jobserver_tokens);
3713 else
3714 while (jobserver_tokens--)
3715 {
3716 int r;
3717
3718 EINTRLOOP (r, write (job_fds[1], &token, 1));
3719 if (r != 1)
3720 perror_with_name ("write", "");
3721 }
3722 }
3723
3724
3725 /* Sanity: If we're the master, were all the tokens written back? */
3726
3727 if (master_job_slots)
3728 {
3729 /* We didn't write one for ourself, so start at 1. */
3730 unsigned int tcnt = 1;
3731
3732 /* Close the write side, so the read() won't hang. */
3733 close (job_fds[1]);
3734
3735 while (read (job_fds[0], &token, 1) == 1)
3736 ++tcnt;
3737
3738 if (tcnt != master_job_slots)
3739 error (NILF,
3740 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3741 tcnt, master_job_slots);
3742
3743 close (job_fds[0]);
3744 }
3745}
3746
3747
3748/* Exit with STATUS, cleaning up as necessary. */
3749
3750void
3751die (int status)
3752{
3753 static char dying = 0;
3754
3755 if (!dying)
3756 {
3757 int err;
3758
3759 dying = 1;
3760
3761 if (print_version_flag)
3762 print_version ();
3763
3764 /* Wait for children to die. */
3765 err = (status != 0);
3766 while (job_slots_used > 0)
3767 reap_children (1, err);
3768
3769 /* Let the remote job module clean up its state. */
3770 remote_cleanup ();
3771
3772 /* Remove the intermediate files. */
3773 remove_intermediates (0);
3774
3775 if (print_data_base_flag)
3776 print_data_base ();
3777
3778#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
3779 if (print_stats_flag)
3780 print_stats ();
3781#endif
3782
3783#ifdef NDEBUG /* bird: Don't waste time on debug sanity checks. */
3784 if (print_data_base_flag || db_level)
3785#endif
3786 verify_file_data_base ();
3787
3788 clean_jobserver (status);
3789
3790 /* Try to move back to the original directory. This is essential on
3791 MS-DOS (where there is really only one process), and on Unix it
3792 puts core files in the original directory instead of the -C
3793 directory. Must wait until after remove_intermediates(), or unlinks
3794 of relative pathnames fail. */
3795 if (directory_before_chdir != 0)
3796 chdir (directory_before_chdir);
3797
3798 log_working_directory (0);
3799 }
3800
3801 exit (status);
3802}
3803
3804
3805/* Write a message indicating that we've just entered or
3806 left (according to ENTERING) the current directory. */
3807
3808void
3809log_working_directory (int entering)
3810{
3811 static int entered = 0;
3812
3813 /* Print nothing without the flag. Don't print the entering message
3814 again if we already have. Don't print the leaving message if we
3815 haven't printed the entering message. */
3816 if (! print_directory_flag || entering == entered)
3817 return;
3818
3819 entered = entering;
3820
3821 if (print_data_base_flag)
3822 fputs ("# ", stdout);
3823
3824 /* Use entire sentences to give the translators a fighting chance. */
3825
3826 if (makelevel == 0)
3827 if (starting_directory == 0)
3828 if (entering)
3829 printf (_("%s: Entering an unknown directory\n"), program);
3830 else
3831 printf (_("%s: Leaving an unknown directory\n"), program);
3832 else
3833 if (entering)
3834 printf (_("%s: Entering directory `%s'\n"),
3835 program, starting_directory);
3836 else
3837 printf (_("%s: Leaving directory `%s'\n"),
3838 program, starting_directory);
3839 else
3840 if (starting_directory == 0)
3841 if (entering)
3842 printf (_("%s[%u]: Entering an unknown directory\n"),
3843 program, makelevel);
3844 else
3845 printf (_("%s[%u]: Leaving an unknown directory\n"),
3846 program, makelevel);
3847 else
3848 if (entering)
3849 printf (_("%s[%u]: Entering directory `%s'\n"),
3850 program, makelevel, starting_directory);
3851 else
3852 printf (_("%s[%u]: Leaving directory `%s'\n"),
3853 program, makelevel, starting_directory);
3854
3855 /* Flush stdout to be sure this comes before any stderr output. */
3856 fflush (stdout);
3857}
Note: See TracBrowser for help on using the repository browser.

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