VirtualBox

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

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

kmk: main.c, variable.c: shell_var must have a valid name length or we'll get duplicates in target_environment(). fixed strcache issue with it as well.

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