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

Last change on this file since 1509 was 1503, checked in by bird, 17 years ago

Environment / globals cleanup. The new policy is to use KBUILD_ and KMK_ prefixes for things that is put into or/and picked from the environment. This will take a good while to complete.

Renamed (old still valid for some versions):
PATH_KBUILD -> KBUILD_PATH
PATH_KBUILD_BIN -> KBUILD_BIN_PATH
BUILD_PLATFORM -> KBUILD_HOST
BUILD_PLATFORM_ARCH -> KBUILD_HOST_ARCH
BUILD_PLATFORM_CPU -> KBUILD_HOST_CPU

Renamed - old not checked:
MAKELEVEL -> KMK_LEVEL
KMKFLAGS -> KMK_FLAGS
MAKEFLAGS -> KMK_FLAGS
MAKEOVERRIDES -> KMK_OVERRIDES

Removed:
MAKE_VERSION
MFLAGS

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