VirtualBox

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

Last change on this file since 2657 was 2656, checked in by bird, 12 years ago

Haiku build fixes.

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