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