VirtualBox

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

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

main: kmk_ash.exe is a unixy_shell (windows).

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

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