source: trunk/src/kmk/main.c@ 1707

Last change on this file since 1707 was 1701, checked in by bird, 17 years ago

kmk: Implemented secondary target expansion. Fixes #42.

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