VirtualBox

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

Last change on this file since 2758 was 2758, checked in by bird, 10 years ago

Some more variable stats I added the other day (not in release builds).

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