VirtualBox

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

Last change on this file since 2744 was 2717, checked in by bird, 11 years ago

kmk: Hacking kBuild-define-*.

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

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