VirtualBox

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

Last change on this file since 2913 was 2913, checked in by bird, 8 years ago

report STATUS_DELETE_PENDING as ENOENT.

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

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