source: trunk/src/kmk/main.c@ 2916

Last change on this file since 2916 was 2916, checked in by bird, 9 years ago

fixes

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