source: trunk/src/gmakenew/main.c@ 914

Last change on this file since 914 was 914, checked in by bird, 18 years ago

some more electric heap stuff.

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