source: trunk/src/gmake/main.c@ 782

Last change on this file since 782 was 778, checked in by bird, 19 years ago

Attempt at dealing with deadlocked kmk on Ctrl-C by dispatching the SIGINT/SIGBREAK on the main thread instead of the ctrl-event thread (Windows).

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