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

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

Merged with the 2007-05-23 CVS. Added rsort and fixed a couple of windows build issues.

  • Property svn:eol-style set to native
File size: 97.3 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 SetUnhandledExceptionFilter(handle_runtime_exceptions);
1086
1087 /* start off assuming we have no shell */
1088 unixy_shell = 0;
1089 no_default_sh_exe = 1;
1090#endif
1091
1092#ifdef SET_STACK_SIZE
1093 /* Get rid of any avoidable limit on stack size. */
1094 {
1095 struct rlimit rlim;
1096
1097 /* Set the stack limit huge so that alloca does not fail. */
1098 if (getrlimit (RLIMIT_STACK, &rlim) == 0)
1099 {
1100 rlim.rlim_cur = rlim.rlim_max;
1101 setrlimit (RLIMIT_STACK, &rlim);
1102 }
1103 }
1104#endif
1105
1106#ifdef HAVE_ATEXIT
1107 atexit (close_stdout);
1108#endif
1109
1110 /* Needed for OS/2 */
1111 initialize_main(&argc, &argv);
1112
1113 default_goal_file = 0;
1114 reading_file = 0;
1115
1116#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1117 /* Request the most powerful version of `system', to
1118 make up for the dumb default shell. */
1119 __system_flags = (__system_redirect
1120 | __system_use_shell
1121 | __system_allow_multiple_cmds
1122 | __system_allow_long_cmds
1123 | __system_handle_null_commands
1124 | __system_emulate_chdir);
1125
1126#endif
1127
1128 /* Set up gettext/internationalization support. */
1129 setlocale (LC_ALL, "");
1130 bindtextdomain (PACKAGE, LOCALEDIR);
1131 textdomain (PACKAGE);
1132
1133#ifdef POSIX
1134 sigemptyset (&fatal_signal_set);
1135#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1136#else
1137#ifdef HAVE_SIGSETMASK
1138 fatal_signal_mask = 0;
1139#define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1140#else
1141#define ADD_SIG(sig)
1142#endif
1143#endif
1144
1145#define FATAL_SIG(sig) \
1146 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1147 bsd_signal (sig, SIG_IGN); \
1148 else \
1149 ADD_SIG (sig);
1150
1151#ifdef SIGHUP
1152 FATAL_SIG (SIGHUP);
1153#endif
1154#ifdef SIGQUIT
1155 FATAL_SIG (SIGQUIT);
1156#endif
1157 FATAL_SIG (SIGINT);
1158 FATAL_SIG (SIGTERM);
1159
1160#ifdef __MSDOS__
1161 /* Windows 9X delivers FP exceptions in child programs to their
1162 parent! We don't want Make to die when a child divides by zero,
1163 so we work around that lossage by catching SIGFPE. */
1164 FATAL_SIG (SIGFPE);
1165#endif
1166
1167#ifdef SIGDANGER
1168 FATAL_SIG (SIGDANGER);
1169#endif
1170#ifdef SIGXCPU
1171 FATAL_SIG (SIGXCPU);
1172#endif
1173#ifdef SIGXFSZ
1174 FATAL_SIG (SIGXFSZ);
1175#endif
1176
1177#ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1178 /* bird: dispatch signals in our own way to try avoid deadlocks. */
1179 g_tidMainThread = GetCurrentThreadId ();
1180 SetConsoleCtrlHandler (ctrl_event, TRUE);
1181#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1182
1183#undef FATAL_SIG
1184
1185 /* Do not ignore the child-death signal. This must be done before
1186 any children could possibly be created; otherwise, the wait
1187 functions won't work on systems with the SVR4 ECHILD brain
1188 damage, if our invoker is ignoring this signal. */
1189
1190#ifdef HAVE_WAIT_NOHANG
1191# if defined SIGCHLD
1192 (void) bsd_signal (SIGCHLD, SIG_DFL);
1193# endif
1194# if defined SIGCLD && SIGCLD != SIGCHLD
1195 (void) bsd_signal (SIGCLD, SIG_DFL);
1196# endif
1197#endif
1198
1199 /* Make sure stdout is line-buffered. */
1200
1201#ifdef HAVE_SETVBUF
1202# ifdef SETVBUF_REVERSED
1203 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
1204# else /* setvbuf not reversed. */
1205 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
1206 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
1207# endif /* setvbuf reversed. */
1208#elif HAVE_SETLINEBUF
1209 setlinebuf (stdout);
1210#endif /* setlinebuf missing. */
1211
1212 /* Figure out where this program lives. */
1213
1214 if (argv[0] == 0)
1215 argv[0] = "";
1216 if (argv[0][0] == '\0')
1217 program = "make";
1218 else
1219 {
1220#ifdef VMS
1221 program = strrchr (argv[0], ']');
1222#else
1223 program = strrchr (argv[0], '/');
1224#endif
1225#if defined(__MSDOS__) || defined(__EMX__)
1226 if (program == 0)
1227 program = strrchr (argv[0], '\\');
1228 else
1229 {
1230 /* Some weird environments might pass us argv[0] with
1231 both kinds of slashes; we must find the rightmost. */
1232 char *p = strrchr (argv[0], '\\');
1233 if (p && p > program)
1234 program = p;
1235 }
1236 if (program == 0 && argv[0][1] == ':')
1237 program = argv[0] + 1;
1238#endif
1239#ifdef WINDOWS32
1240 if (program == 0)
1241 {
1242 /* Extract program from full path */
1243 int argv0_len;
1244 program = strrchr (argv[0], '\\');
1245 if (program)
1246 {
1247 argv0_len = strlen(program);
1248 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1249 /* Remove .exe extension */
1250 program[argv0_len - 4] = '\0';
1251 }
1252 }
1253#endif
1254 if (program == 0)
1255 program = argv[0];
1256 else
1257 ++program;
1258 }
1259
1260 /* Set up to access user data (files). */
1261 user_access ();
1262
1263 initialize_global_hash_tables ();
1264
1265 /* Figure out where we are. */
1266
1267#ifdef WINDOWS32
1268 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1269#else
1270 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1271#endif
1272 {
1273#ifdef HAVE_GETCWD
1274 perror_with_name ("getcwd", "");
1275#else
1276 error (NILF, "getwd: %s", current_directory);
1277#endif
1278 current_directory[0] = '\0';
1279 directory_before_chdir = 0;
1280 }
1281 else
1282 directory_before_chdir = xstrdup (current_directory);
1283#ifdef __MSDOS__
1284 /* Make sure we will return to the initial directory, come what may. */
1285 atexit (msdos_return_to_initial_directory);
1286#endif
1287
1288 /* Initialize the special variables. */
1289 define_variable (".VARIABLES", 10, "", o_default, 0)->special = 1;
1290 /* define_variable (".TARGETS", 8, "", o_default, 0)->special = 1; */
1291
1292 /* Set up .FEATURES */
1293 define_variable (".FEATURES", 9,
1294 "target-specific order-only second-expansion else-if",
1295 o_default, 0);
1296#ifndef NO_ARCHIVES
1297 do_variable_definition (NILF, ".FEATURES", "archives",
1298 o_default, f_append, 0);
1299#endif
1300#ifdef MAKE_JOBSERVER
1301 do_variable_definition (NILF, ".FEATURES", "jobserver",
1302 o_default, f_append, 0);
1303#endif
1304#ifdef MAKE_SYMLINKS
1305 do_variable_definition (NILF, ".FEATURES", "check-symlink",
1306 o_default, f_append, 0);
1307#endif
1308
1309 /* Read in variables from the environment. It is important that this be
1310 done before $(MAKE) is figured out so its definitions will not be
1311 from the environment. */
1312
1313#ifndef _AMIGA
1314 {
1315 unsigned int i;
1316
1317 for (i = 0; envp[i] != 0; ++i)
1318 {
1319 int do_not_define = 0;
1320 char *ep = envp[i];
1321
1322 while (*ep != '\0' && *ep != '=')
1323 ++ep;
1324#ifdef WINDOWS32
1325 if (!unix_path && strneq(envp[i], "PATH=", 5))
1326 unix_path = ep+1;
1327 else if (!strnicmp(envp[i], "Path=", 5)) {
1328 do_not_define = 1; /* it gets defined after loop exits */
1329 if (!windows32_path)
1330 windows32_path = ep+1;
1331 }
1332#endif
1333 /* The result of pointer arithmetic is cast to unsigned int for
1334 machines where ptrdiff_t is a different size that doesn't widen
1335 the same. */
1336 if (!do_not_define)
1337 {
1338 struct variable *v;
1339
1340 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1341 ep + 1, o_env, 1);
1342 /* Force exportation of every variable culled from the
1343 environment. We used to rely on target_environment's
1344 v_default code to do this. But that does not work for the
1345 case where an environment variable is redefined in a makefile
1346 with `override'; it should then still be exported, because it
1347 was originally in the environment. */
1348 v->export = v_export;
1349
1350 /* Another wrinkle is that POSIX says the value of SHELL set in
1351 the makefile won't change the value of SHELL given to
1352 subprocesses. */
1353 if (streq (v->name, "SHELL"))
1354 {
1355#ifndef __MSDOS__
1356 v->export = v_noexport;
1357#endif
1358 shell_var.name = "SHELL";
1359 shell_var.value = xstrdup (ep + 1);
1360 }
1361
1362 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1363 if (streq (v->name, "MAKE_RESTARTS"))
1364 {
1365 v->export = v_noexport;
1366 restarts = (unsigned int) atoi (ep + 1);
1367 }
1368 }
1369 }
1370 }
1371#ifdef WINDOWS32
1372 /* If we didn't find a correctly spelled PATH we define PATH as
1373 * either the first mispelled value or an empty string
1374 */
1375 if (!unix_path)
1376 define_variable("PATH", 4,
1377 windows32_path ? windows32_path : "",
1378 o_env, 1)->export = v_export;
1379#endif
1380#else /* For Amiga, read the ENV: device, ignoring all dirs */
1381 {
1382 BPTR env, file, old;
1383 char buffer[1024];
1384 int len;
1385 __aligned struct FileInfoBlock fib;
1386
1387 env = Lock ("ENV:", ACCESS_READ);
1388 if (env)
1389 {
1390 old = CurrentDir (DupLock(env));
1391 Examine (env, &fib);
1392
1393 while (ExNext (env, &fib))
1394 {
1395 if (fib.fib_DirEntryType < 0) /* File */
1396 {
1397 /* Define an empty variable. It will be filled in
1398 variable_lookup(). Makes startup quite a bit
1399 faster. */
1400 define_variable (fib.fib_FileName,
1401 strlen (fib.fib_FileName),
1402 "", o_env, 1)->export = v_export;
1403 }
1404 }
1405 UnLock (env);
1406 UnLock(CurrentDir(old));
1407 }
1408 }
1409#endif
1410
1411 /* Decode the switches. */
1412
1413 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1414#if 0
1415 /* People write things like:
1416 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1417 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1418 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1419#endif
1420 decode_switches (argc, argv, 0);
1421#ifdef WINDOWS32
1422 if (suspend_flag) {
1423 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1424 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1425 Sleep(30 * 1000);
1426 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1427 }
1428#endif
1429
1430 decode_debug_flags ();
1431
1432#ifdef KMK
1433 set_make_priority ();
1434#endif
1435
1436 /* Set always_make_flag if -B was given and we've not restarted already. */
1437 always_make_flag = always_make_set && (restarts == 0);
1438
1439 /* Print version information. */
1440 if (print_version_flag || print_data_base_flag || db_level)
1441 {
1442 print_version ();
1443
1444 /* `make --version' is supposed to just print the version and exit. */
1445 if (print_version_flag)
1446 die (0);
1447 }
1448
1449#ifndef VMS
1450 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1451 (If it is a relative pathname with a slash, prepend our directory name
1452 so the result will run the same program regardless of the current dir.
1453 If it is a name with no slash, we can only hope that PATH did not
1454 find it in the current directory.) */
1455#ifdef WINDOWS32
1456 /*
1457 * Convert from backslashes to forward slashes for
1458 * programs like sh which don't like them. Shouldn't
1459 * matter if the path is one way or the other for
1460 * CreateProcess().
1461 */
1462 if (strpbrk(argv[0], "/:\\") ||
1463 strstr(argv[0], "..") ||
1464 strneq(argv[0], "//", 2))
1465 argv[0] = xstrdup(w32ify(argv[0],1));
1466#else /* WINDOWS32 */
1467#if defined (__MSDOS__) || defined (__EMX__)
1468 if (strchr (argv[0], '\\'))
1469 {
1470 char *p;
1471
1472 argv[0] = xstrdup (argv[0]);
1473 for (p = argv[0]; *p; p++)
1474 if (*p == '\\')
1475 *p = '/';
1476 }
1477 /* If argv[0] is not in absolute form, prepend the current
1478 directory. This can happen when Make is invoked by another DJGPP
1479 program that uses a non-absolute name. */
1480 if (current_directory[0] != '\0'
1481 && argv[0] != 0
1482 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1483# ifdef __EMX__
1484 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1485 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1486# endif
1487 )
1488 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1489#else /* !__MSDOS__ */
1490 if (current_directory[0] != '\0'
1491 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1492#ifdef HAVE_DOS_PATHS
1493 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1494 && strchr (argv[0], '\\') != 0
1495#endif
1496 )
1497 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1498#endif /* !__MSDOS__ */
1499#endif /* WINDOWS32 */
1500#endif
1501
1502 /* The extra indirection through $(MAKE_COMMAND) is done
1503 for hysterical raisins. */
1504 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1505 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1506#ifdef KMK
1507 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1508#endif
1509
1510 if (command_variables != 0)
1511 {
1512 struct command_variable *cv;
1513 struct variable *v;
1514 unsigned int len = 0;
1515 char *value, *p;
1516
1517 /* Figure out how much space will be taken up by the command-line
1518 variable definitions. */
1519 for (cv = command_variables; cv != 0; cv = cv->next)
1520 {
1521 v = cv->variable;
1522 len += 2 * strlen (v->name);
1523 if (! v->recursive)
1524 ++len;
1525 ++len;
1526 len += 2 * strlen (v->value);
1527 ++len;
1528 }
1529
1530 /* Now allocate a buffer big enough and fill it. */
1531 p = value = alloca (len);
1532 for (cv = command_variables; cv != 0; cv = cv->next)
1533 {
1534 v = cv->variable;
1535 p = quote_for_env (p, v->name);
1536 if (! v->recursive)
1537 *p++ = ':';
1538 *p++ = '=';
1539 p = quote_for_env (p, v->value);
1540 *p++ = ' ';
1541 }
1542 p[-1] = '\0'; /* Kill the final space and terminate. */
1543
1544 /* Define an unchangeable variable with a name that no POSIX.2
1545 makefile could validly use for its own variable. */
1546 (void) define_variable ("-*-command-variables-*-", 23,
1547 value, o_automatic, 0);
1548
1549 /* Define the variable; this will not override any user definition.
1550 Normally a reference to this variable is written into the value of
1551 MAKEFLAGS, allowing the user to override this value to affect the
1552 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1553 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1554 a reference to this hidden variable is written instead. */
1555 (void) define_variable ("MAKEOVERRIDES", 13,
1556 "${-*-command-variables-*-}", o_env, 1);
1557 }
1558
1559#ifdef KMK
1560 /* If there wasn't any -C or -f flags, check for Makefile.kup and
1561 insert a fake -C argument.
1562 Makefile.kmk overrides Makefile.kup but not plain Makefile. */
1563 if (makefiles == 0 && directories == 0)
1564 {
1565 struct stat st;
1566 if (( stat ("Makefile.kup", &st) == 0
1567 && S_ISREG (st.st_mode) )
1568 || ( stat ("makefile.kup", &st) == 0
1569 && S_ISREG (st.st_mode) )
1570 && stat ("Makefile.kmk", &st) < 0
1571 && stat ("makefile.kmk", &st) < 0)
1572 {
1573 static char fake_path[3*16 + 32] = "..";
1574 static char *fake_list[2] = { &fake_path[0], NULL };
1575 struct stringlist fake_directories = { &fake_list[0], 1, 0 };
1576
1577 char *cur = &fake_path[2];
1578 int up_levels = 1;
1579
1580 while (up_levels < 16)
1581 {
1582 /* File with higher precedence.s */
1583 strcpy (cur, "/Makefile.kmk");
1584 if (stat (fake_path, &st) == 0)
1585 break;
1586 strcpy (cur, "/makefile.kmk");
1587 if (stat (fake_path, &st) == 0)
1588 break;
1589
1590 /* the .kup files */
1591 strcpy (cur, "/Makefile.kup");
1592 if ( stat (fake_path, &st) != 0
1593 || !S_ISREG (st.st_mode))
1594 {
1595 strcpy (cur, "/makefile.kup");
1596 if ( stat (fake_path, &st) != 0
1597 || !S_ISREG (st.st_mode))
1598 break;
1599 }
1600
1601 /* ok */
1602 strcpy (cur, "/..");
1603 cur += 3;
1604 up_levels++;
1605 }
1606
1607 if (up_levels >= 16)
1608 fatal (NILF, _("Makefile.kup recursion is too deep."));
1609
1610 *cur = '\0';
1611 directories = &fake_directories;
1612 }
1613 }
1614#endif /* KMK */
1615
1616 /* If there were -C flags, move ourselves about. */
1617 if (directories != 0)
1618 {
1619 unsigned int i;
1620 for (i = 0; directories->list[i] != 0; ++i)
1621 {
1622 const char *dir = directories->list[i];
1623#ifdef WINDOWS32
1624 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1625 But allow -C/ just in case someone wants that. */
1626 {
1627 char *p = (char *)dir + strlen (dir) - 1;
1628 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1629 --p;
1630 p[1] = '\0';
1631 }
1632#endif
1633 if (chdir (dir) < 0)
1634 pfatal_with_name (dir);
1635 }
1636 }
1637
1638#ifdef WINDOWS32
1639 /*
1640 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1641 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1642 *
1643 * The functions in dir.c can incorrectly cache information for "."
1644 * before we have changed directory and this can cause file
1645 * lookups to fail because the current directory (.) was pointing
1646 * at the wrong place when it was first evaluated.
1647 */
1648 no_default_sh_exe = !find_and_set_default_shell(NULL);
1649
1650#endif /* WINDOWS32 */
1651 /* Figure out the level of recursion. */
1652 {
1653 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1654 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1655 makelevel = (unsigned int) atoi (v->value);
1656 else
1657 makelevel = 0;
1658 }
1659
1660 /* Except under -s, always do -w in sub-makes and under -C. */
1661 if (!silent_flag && (directories != 0 || makelevel > 0))
1662 print_directory_flag = 1;
1663
1664 /* Let the user disable that with --no-print-directory. */
1665 if (inhibit_print_directory_flag)
1666 print_directory_flag = 0;
1667
1668 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1669 if (no_builtin_variables_flag)
1670 no_builtin_rules_flag = 1;
1671
1672 /* Construct the list of include directories to search. */
1673
1674 construct_include_path (include_directories == 0
1675 ? 0 : include_directories->list);
1676
1677 /* Figure out where we are now, after chdir'ing. */
1678 if (directories == 0)
1679 /* We didn't move, so we're still in the same place. */
1680 starting_directory = current_directory;
1681 else
1682 {
1683#ifdef WINDOWS32
1684 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1685#else
1686 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1687#endif
1688 {
1689#ifdef HAVE_GETCWD
1690 perror_with_name ("getcwd", "");
1691#else
1692 error (NILF, "getwd: %s", current_directory);
1693#endif
1694 starting_directory = 0;
1695 }
1696 else
1697 starting_directory = current_directory;
1698 }
1699
1700 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1701
1702 /* Read any stdin makefiles into temporary files. */
1703
1704 if (makefiles != 0)
1705 {
1706 unsigned int i;
1707 for (i = 0; i < makefiles->idx; ++i)
1708 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1709 {
1710 /* This makefile is standard input. Since we may re-exec
1711 and thus re-read the makefiles, we read standard input
1712 into a temporary file and read from that. */
1713 FILE *outfile;
1714 char *template, *tmpdir;
1715
1716 if (stdin_nm)
1717 fatal (NILF, _("Makefile from standard input specified twice."));
1718
1719#ifdef VMS
1720# define DEFAULT_TMPDIR "sys$scratch:"
1721#else
1722# ifdef P_tmpdir
1723# define DEFAULT_TMPDIR P_tmpdir
1724# else
1725# define DEFAULT_TMPDIR "/tmp"
1726# endif
1727#endif
1728#define DEFAULT_TMPFILE "GmXXXXXX"
1729
1730 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1731#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1732 /* These are also used commonly on these platforms. */
1733 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1734 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1735#endif
1736 )
1737 tmpdir = DEFAULT_TMPDIR;
1738
1739 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
1740 strcpy (template, tmpdir);
1741
1742#ifdef HAVE_DOS_PATHS
1743 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1744 strcat (template, "/");
1745#else
1746# ifndef VMS
1747 if (template[strlen (template) - 1] != '/')
1748 strcat (template, "/");
1749# endif /* !VMS */
1750#endif /* !HAVE_DOS_PATHS */
1751
1752 strcat (template, DEFAULT_TMPFILE);
1753 outfile = open_tmpfile (&stdin_nm, template);
1754 if (outfile == 0)
1755 pfatal_with_name (_("fopen (temporary file)"));
1756 while (!feof (stdin) && ! ferror (stdin))
1757 {
1758 char buf[2048];
1759 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1760 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1761 pfatal_with_name (_("fwrite (temporary file)"));
1762 }
1763 fclose (outfile);
1764
1765 /* Replace the name that read_all_makefiles will
1766 see with the name of the temporary file. */
1767 makefiles->list[i] = strcache_add (stdin_nm);
1768
1769 /* Make sure the temporary file will not be remade. */
1770 {
1771 struct file *f = enter_file (strcache_add (stdin_nm));
1772 f->updated = 1;
1773 f->update_status = 0;
1774 f->command_state = cs_finished;
1775 /* Can't be intermediate, or it'll be removed too early for
1776 make re-exec. */
1777 f->intermediate = 0;
1778 f->dontcare = 0;
1779 }
1780 }
1781 }
1782
1783#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
1784#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1785 /* Set up to handle children dying. This must be done before
1786 reading in the makefiles so that `shell' function calls will work.
1787
1788 If we don't have a hanging wait we have to fall back to old, broken
1789 functionality here and rely on the signal handler and counting
1790 children.
1791
1792 If we're using the jobs pipe we need a signal handler so that
1793 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1794 jobserver pipe in job.c if we're waiting for a token.
1795
1796 If none of these are true, we don't need a signal handler at all. */
1797 {
1798 RETSIGTYPE child_handler (int sig);
1799# if defined SIGCHLD
1800 bsd_signal (SIGCHLD, child_handler);
1801# endif
1802# if defined SIGCLD && SIGCLD != SIGCHLD
1803 bsd_signal (SIGCLD, child_handler);
1804# endif
1805 }
1806#endif
1807#endif
1808
1809 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1810#ifdef SIGUSR1
1811 bsd_signal (SIGUSR1, debug_signal_handler);
1812#endif
1813
1814 /* Define the initial list of suffixes for old-style rules. */
1815
1816 set_default_suffixes ();
1817
1818 /* Define the file rules for the built-in suffix rules. These will later
1819 be converted into pattern rules. We used to do this in
1820 install_default_implicit_rules, but since that happens after reading
1821 makefiles, it results in the built-in pattern rules taking precedence
1822 over makefile-specified suffix rules, which is wrong. */
1823
1824 install_default_suffix_rules ();
1825
1826 /* Define some internal and special variables. */
1827
1828 define_automatic_variables ();
1829
1830 /* Set up the MAKEFLAGS and MFLAGS variables
1831 so makefiles can look at them. */
1832
1833 define_makeflags (0, 0);
1834
1835 /* Define the default variables. */
1836 define_default_variables ();
1837
1838 default_file = enter_file (strcache_add (".DEFAULT"));
1839
1840 {
1841 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
1842 default_goal_name = &v->value;
1843 }
1844
1845 /* Read all the makefiles. */
1846
1847 read_makefiles
1848 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1849
1850#ifdef WINDOWS32
1851 /* look one last time after reading all Makefiles */
1852 if (no_default_sh_exe)
1853 no_default_sh_exe = !find_and_set_default_shell(NULL);
1854#endif /* WINDOWS32 */
1855
1856#if defined (__MSDOS__) || defined (__EMX__)
1857 /* We need to know what kind of shell we will be using. */
1858 {
1859 extern int _is_unixy_shell (const char *_path);
1860 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1861 extern int unixy_shell;
1862 extern char *default_shell;
1863
1864 if (shv && *shv->value)
1865 {
1866 char *shell_path = recursively_expand(shv);
1867
1868 if (shell_path && _is_unixy_shell (shell_path))
1869 unixy_shell = 1;
1870 else
1871 unixy_shell = 0;
1872 if (shell_path)
1873 default_shell = shell_path;
1874 }
1875 }
1876#endif /* __MSDOS__ || __EMX__ */
1877
1878 /* Decode switches again, in case the variables were set by the makefile. */
1879 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1880#if 0
1881 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1882#endif
1883
1884#if defined (__MSDOS__) || defined (__EMX__)
1885 if (job_slots != 1
1886# ifdef __EMX__
1887 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1888# endif
1889 )
1890 {
1891 error (NILF,
1892 _("Parallel jobs (-j) are not supported on this platform."));
1893 error (NILF, _("Resetting to single job (-j1) mode."));
1894 job_slots = 1;
1895 }
1896#endif
1897
1898#ifdef MAKE_JOBSERVER
1899 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
1900
1901 if (jobserver_fds)
1902 {
1903 const char *cp;
1904 unsigned int ui;
1905
1906 for (ui=1; ui < jobserver_fds->idx; ++ui)
1907 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1908 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1909
1910 /* Now parse the fds string and make sure it has the proper format. */
1911
1912 cp = jobserver_fds->list[0];
1913
1914 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
1915 fatal (NILF,
1916 _("internal error: invalid --jobserver-fds string `%s'"), cp);
1917
1918 DB (DB_JOBS,
1919 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
1920
1921 /* The combination of a pipe + !job_slots means we're using the
1922 jobserver. If !job_slots and we don't have a pipe, we can start
1923 infinite jobs. If we see both a pipe and job_slots >0 that means the
1924 user set -j explicitly. This is broken; in this case obey the user
1925 (ignore the jobserver pipe for this make) but print a message. */
1926
1927 if (job_slots > 0)
1928 error (NILF,
1929 _("warning: -jN forced in submake: disabling jobserver mode."));
1930
1931 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1932 handler. If this fails with EBADF, the parent has closed the pipe
1933 on us because it didn't think we were a submake. If so, print a
1934 warning then default to -j1. */
1935
1936 else if ((job_rfd = dup (job_fds[0])) < 0)
1937 {
1938 if (errno != EBADF)
1939 pfatal_with_name (_("dup jobserver"));
1940
1941 error (NILF,
1942 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
1943 job_slots = 1;
1944 }
1945
1946 if (job_slots > 0)
1947 {
1948 close (job_fds[0]);
1949 close (job_fds[1]);
1950 job_fds[0] = job_fds[1] = -1;
1951 free (jobserver_fds->list);
1952 free (jobserver_fds);
1953 jobserver_fds = 0;
1954 }
1955 }
1956
1957 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
1958 Set up the pipe and install the fds option for our children. */
1959
1960 if (job_slots > 1)
1961 {
1962 char *cp;
1963 char c = '+';
1964
1965 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
1966 pfatal_with_name (_("creating jobs pipe"));
1967
1968 /* Every make assumes that it always has one job it can run. For the
1969 submakes it's the token they were given by their parent. For the
1970 top make, we just subtract one from the number the user wants. We
1971 want job_slots to be 0 to indicate we're using the jobserver. */
1972
1973 master_job_slots = job_slots;
1974
1975 while (--job_slots)
1976 {
1977 int r;
1978
1979 EINTRLOOP (r, write (job_fds[1], &c, 1));
1980 if (r != 1)
1981 pfatal_with_name (_("init jobserver pipe"));
1982 }
1983
1984 /* Fill in the jobserver_fds struct for our children. */
1985
1986 cp = xmalloc ((sizeof ("1024")*2)+1);
1987 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
1988
1989 jobserver_fds = (struct stringlist *)
1990 xmalloc (sizeof (struct stringlist));
1991 jobserver_fds->list = xmalloc (sizeof (char *));
1992 jobserver_fds->list[0] = cp;
1993 jobserver_fds->idx = 1;
1994 jobserver_fds->max = 1;
1995 }
1996#endif
1997
1998#ifndef MAKE_SYMLINKS
1999 if (check_symlink_flag)
2000 {
2001 error (NILF, _("Symbolic links not supported: disabling -L."));
2002 check_symlink_flag = 0;
2003 }
2004#endif
2005
2006 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2007
2008 define_makeflags (1, 0);
2009
2010 /* Make each `struct dep' point at the `struct file' for the file
2011 depended on. Also do magic for special targets. */
2012
2013 snap_deps ();
2014
2015 /* Convert old-style suffix rules to pattern rules. It is important to
2016 do this before installing the built-in pattern rules below, so that
2017 makefile-specified suffix rules take precedence over built-in pattern
2018 rules. */
2019
2020 convert_to_pattern ();
2021
2022 /* Install the default implicit pattern rules.
2023 This used to be done before reading the makefiles.
2024 But in that case, built-in pattern rules were in the chain
2025 before user-defined ones, so they matched first. */
2026
2027 install_default_implicit_rules ();
2028
2029 /* Compute implicit rule limits. */
2030
2031 count_implicit_rule_limits ();
2032
2033 /* Construct the listings of directories in VPATH lists. */
2034
2035 build_vpath_lists ();
2036
2037 /* Mark files given with -o flags as very old and as having been updated
2038 already, and files given with -W flags as brand new (time-stamp as far
2039 as possible into the future). If restarts is set we'll do -W later. */
2040
2041 if (old_files != 0)
2042 {
2043 const char **p;
2044 for (p = old_files->list; *p != 0; ++p)
2045 {
2046 struct file *f = enter_file (*p);
2047 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2048 f->updated = 1;
2049 f->update_status = 0;
2050 f->command_state = cs_finished;
2051 }
2052 }
2053
2054 if (!restarts && new_files != 0)
2055 {
2056 const char **p;
2057 for (p = new_files->list; *p != 0; ++p)
2058 {
2059 struct file *f = enter_file (*p);
2060 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2061 }
2062 }
2063
2064 /* Initialize the remote job module. */
2065 remote_setup ();
2066
2067 if (read_makefiles != 0)
2068 {
2069 /* Update any makefiles if necessary. */
2070
2071 FILE_TIMESTAMP *makefile_mtimes = 0;
2072 unsigned int mm_idx = 0;
2073 char **nargv = argv;
2074 int nargc = argc;
2075 int orig_db_level = db_level;
2076 int status;
2077
2078 if (! ISDB (DB_MAKEFILES))
2079 db_level = DB_NONE;
2080
2081 DB (DB_BASIC, (_("Updating makefiles....\n")));
2082
2083 /* Remove any makefiles we don't want to try to update.
2084 Also record the current modtimes so we can compare them later. */
2085 {
2086 register struct dep *d, *last;
2087 last = 0;
2088 d = read_makefiles;
2089 while (d != 0)
2090 {
2091 struct file *f = d->file;
2092 if (f->double_colon)
2093 for (f = f->double_colon; f != NULL; f = f->prev)
2094 {
2095 if (f->deps == 0 && f->cmds != 0)
2096 {
2097 /* This makefile is a :: target with commands, but
2098 no dependencies. So, it will always be remade.
2099 This might well cause an infinite loop, so don't
2100 try to remake it. (This will only happen if
2101 your makefiles are written exceptionally
2102 stupidly; but if you work for Athena, that's how
2103 you write your makefiles.) */
2104
2105 DB (DB_VERBOSE,
2106 (_("Makefile `%s' might loop; not remaking it.\n"),
2107 f->name));
2108
2109 if (last == 0)
2110 read_makefiles = d->next;
2111 else
2112 last->next = d->next;
2113
2114 /* Free the storage. */
2115 free_dep (d);
2116
2117 d = last == 0 ? read_makefiles : last->next;
2118
2119 break;
2120 }
2121 }
2122 if (f == NULL || !f->double_colon)
2123 {
2124 makefile_mtimes = xrealloc (makefile_mtimes,
2125 (mm_idx+1)
2126 * sizeof (FILE_TIMESTAMP));
2127 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2128 last = d;
2129 d = d->next;
2130 }
2131 }
2132 }
2133
2134 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2135 define_makeflags (1, 1);
2136
2137 rebuilding_makefiles = 1;
2138 status = update_goal_chain (read_makefiles);
2139 rebuilding_makefiles = 0;
2140
2141 switch (status)
2142 {
2143 case 1:
2144 /* The only way this can happen is if the user specified -q and asked
2145 * for one of the makefiles to be remade as a target on the command
2146 * line. Since we're not actually updating anything with -q we can
2147 * treat this as "did nothing".
2148 */
2149
2150 case -1:
2151 /* Did nothing. */
2152 break;
2153
2154 case 2:
2155 /* Failed to update. Figure out if we care. */
2156 {
2157 /* Nonzero if any makefile was successfully remade. */
2158 int any_remade = 0;
2159 /* Nonzero if any makefile we care about failed
2160 in updating or could not be found at all. */
2161 int any_failed = 0;
2162 unsigned int i;
2163 struct dep *d;
2164
2165 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2166 {
2167 /* Reset the considered flag; we may need to look at the file
2168 again to print an error. */
2169 d->file->considered = 0;
2170
2171 if (d->file->updated)
2172 {
2173 /* This makefile was updated. */
2174 if (d->file->update_status == 0)
2175 {
2176 /* It was successfully updated. */
2177 any_remade |= (file_mtime_no_search (d->file)
2178 != makefile_mtimes[i]);
2179 }
2180 else if (! (d->changed & RM_DONTCARE))
2181 {
2182 FILE_TIMESTAMP mtime;
2183 /* The update failed and this makefile was not
2184 from the MAKEFILES variable, so we care. */
2185 error (NILF, _("Failed to remake makefile `%s'."),
2186 d->file->name);
2187 mtime = file_mtime_no_search (d->file);
2188 any_remade |= (mtime != NONEXISTENT_MTIME
2189 && mtime != makefile_mtimes[i]);
2190 makefile_status = MAKE_FAILURE;
2191 }
2192 }
2193 else
2194 /* This makefile was not found at all. */
2195 if (! (d->changed & RM_DONTCARE))
2196 {
2197 /* This is a makefile we care about. See how much. */
2198 if (d->changed & RM_INCLUDED)
2199 /* An included makefile. We don't need
2200 to die, but we do want to complain. */
2201 error (NILF,
2202 _("Included makefile `%s' was not found."),
2203 dep_name (d));
2204 else
2205 {
2206 /* A normal makefile. We must die later. */
2207 error (NILF, _("Makefile `%s' was not found"),
2208 dep_name (d));
2209 any_failed = 1;
2210 }
2211 }
2212 }
2213 /* Reset this to empty so we get the right error message below. */
2214 read_makefiles = 0;
2215
2216 if (any_remade)
2217 goto re_exec;
2218 if (any_failed)
2219 die (2);
2220 break;
2221 }
2222
2223 case 0:
2224 re_exec:
2225 /* Updated successfully. Re-exec ourselves. */
2226
2227 remove_intermediates (0);
2228
2229 if (print_data_base_flag)
2230 print_data_base ();
2231
2232 log_working_directory (0);
2233
2234 clean_jobserver (0);
2235
2236 if (makefiles != 0)
2237 {
2238 /* These names might have changed. */
2239 int i, j = 0;
2240 for (i = 1; i < argc; ++i)
2241 if (strneq (argv[i], "-f", 2)) /* XXX */
2242 {
2243 char *p = &argv[i][2];
2244 if (*p == '\0')
2245 /* This cast is OK since we never modify argv. */
2246 argv[++i] = (char *) makefiles->list[j];
2247 else
2248 argv[i] = xstrdup (concat ("-f", makefiles->list[j], ""));
2249 ++j;
2250 }
2251 }
2252
2253 /* Add -o option for the stdin temporary file, if necessary. */
2254 if (stdin_nm)
2255 {
2256 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2257 memcpy (nargv, argv, argc * sizeof (char *));
2258 nargv[nargc++] = xstrdup (concat ("-o", stdin_nm, ""));
2259 nargv[nargc] = 0;
2260 }
2261
2262 if (directories != 0 && directories->idx > 0)
2263 {
2264 int bad = 1;
2265 if (directory_before_chdir != 0)
2266 {
2267 if (chdir (directory_before_chdir) < 0)
2268 perror_with_name ("chdir", "");
2269 else
2270 bad = 0;
2271 }
2272 if (bad)
2273 fatal (NILF, _("Couldn't change back to original directory."));
2274 }
2275
2276 ++restarts;
2277
2278 if (ISDB (DB_BASIC))
2279 {
2280 char **p;
2281 printf (_("Re-executing[%u]:"), restarts);
2282 for (p = nargv; *p != 0; ++p)
2283 printf (" %s", *p);
2284 putchar ('\n');
2285 }
2286
2287#ifndef _AMIGA
2288 {
2289 char **p;
2290 for (p = environ; *p != 0; ++p)
2291 {
2292 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2293 && (*p)[MAKELEVEL_LENGTH] == '=')
2294 {
2295 *p = alloca (40);
2296 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2297 }
2298 if (strneq (*p, "MAKE_RESTARTS=", 14))
2299 {
2300 *p = alloca (40);
2301 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2302 restarts = 0;
2303 }
2304 }
2305 }
2306#else /* AMIGA */
2307 {
2308 char buffer[256];
2309
2310 sprintf (buffer, "%u", makelevel);
2311 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2312
2313 sprintf (buffer, "%u", restarts);
2314 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2315 restarts = 0;
2316 }
2317#endif
2318
2319 /* If we didn't set the restarts variable yet, add it. */
2320 if (restarts)
2321 {
2322 char *b = alloca (40);
2323 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2324 putenv (b);
2325 }
2326
2327 fflush (stdout);
2328 fflush (stderr);
2329
2330 /* Close the dup'd jobserver pipe if we opened one. */
2331 if (job_rfd >= 0)
2332 close (job_rfd);
2333
2334#ifdef _AMIGA
2335 exec_command (nargv);
2336 exit (0);
2337#elif defined (__EMX__)
2338 {
2339 /* It is not possible to use execve() here because this
2340 would cause the parent process to be terminated with
2341 exit code 0 before the child process has been terminated.
2342 Therefore it may be the best solution simply to spawn the
2343 child process including all file handles and to wait for its
2344 termination. */
2345 int pid;
2346 int status;
2347 pid = child_execute_job (0, 1, nargv, environ);
2348
2349 /* is this loop really necessary? */
2350 do {
2351 pid = wait (&status);
2352 } while (pid <= 0);
2353 /* use the exit code of the child process */
2354 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2355 }
2356#else
2357 exec_command (nargv, environ);
2358#endif
2359 /* NOTREACHED */
2360
2361 default:
2362#define BOGUS_UPDATE_STATUS 0
2363 assert (BOGUS_UPDATE_STATUS);
2364 break;
2365 }
2366
2367 db_level = orig_db_level;
2368
2369 /* Free the makefile mtimes (if we allocated any). */
2370 if (makefile_mtimes)
2371 free (makefile_mtimes);
2372 }
2373
2374 /* Set up `MAKEFLAGS' again for the normal targets. */
2375 define_makeflags (1, 0);
2376
2377 /* Set always_make_flag if -B was given. */
2378 always_make_flag = always_make_set;
2379
2380 /* If restarts is set we haven't set up -W files yet, so do that now. */
2381 if (restarts && new_files != 0)
2382 {
2383 const char **p;
2384 for (p = new_files->list; *p != 0; ++p)
2385 {
2386 struct file *f = enter_file (*p);
2387 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2388 }
2389 }
2390
2391 /* If there is a temp file from reading a makefile from stdin, get rid of
2392 it now. */
2393 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2394 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2395
2396 {
2397 int status;
2398
2399 /* If there were no command-line goals, use the default. */
2400 if (goals == 0)
2401 {
2402 if (**default_goal_name != '\0')
2403 {
2404 if (default_goal_file == 0 ||
2405 strcmp (*default_goal_name, default_goal_file->name) != 0)
2406 {
2407 default_goal_file = lookup_file (*default_goal_name);
2408
2409 /* In case user set .DEFAULT_GOAL to a non-existent target
2410 name let's just enter this name into the table and let
2411 the standard logic sort it out. */
2412 if (default_goal_file == 0)
2413 {
2414 struct nameseq *ns;
2415 char *p = *default_goal_name;
2416
2417 ns = multi_glob (
2418 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2419 sizeof (struct nameseq));
2420
2421 /* .DEFAULT_GOAL should contain one target. */
2422 if (ns->next != 0)
2423 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2424
2425 default_goal_file = enter_file (strcache_add (ns->name));
2426
2427 ns->name = 0; /* It was reused by enter_file(). */
2428 free_ns_chain (ns);
2429 }
2430 }
2431
2432 goals = alloc_dep ();
2433 goals->file = default_goal_file;
2434 }
2435 }
2436 else
2437 lastgoal->next = 0;
2438
2439
2440 if (!goals)
2441 {
2442 if (read_makefiles == 0)
2443 fatal (NILF, _("No targets specified and no makefile found"));
2444
2445 fatal (NILF, _("No targets"));
2446 }
2447
2448 /* Update the goals. */
2449
2450 DB (DB_BASIC, (_("Updating goal targets....\n")));
2451
2452 switch (update_goal_chain (goals))
2453 {
2454 case -1:
2455 /* Nothing happened. */
2456 case 0:
2457 /* Updated successfully. */
2458 status = makefile_status;
2459 break;
2460 case 1:
2461 /* We are under -q and would run some commands. */
2462 status = MAKE_TROUBLE;
2463 break;
2464 case 2:
2465 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2466 but in VMS, there is only success and failure. */
2467 status = MAKE_FAILURE;
2468 break;
2469 default:
2470 abort ();
2471 }
2472
2473 /* If we detected some clock skew, generate one last warning */
2474 if (clock_skew_detected)
2475 error (NILF,
2476 _("warning: Clock skew detected. Your build may be incomplete."));
2477
2478 /* Exit. */
2479 die (status);
2480 }
2481
2482 /* NOTREACHED */
2483 return 0;
2484}
2485
2486
2487/* Parsing of arguments, decoding of switches. */
2488
2489static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2490static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2491 (sizeof (long_option_aliases) /
2492 sizeof (long_option_aliases[0]))];
2493
2494/* Fill in the string and vector for getopt. */
2495static void
2496init_switches (void)
2497{
2498 char *p;
2499 unsigned int c;
2500 unsigned int i;
2501
2502 if (options[0] != '\0')
2503 /* Already done. */
2504 return;
2505
2506 p = options;
2507
2508 /* Return switch and non-switch args in order, regardless of
2509 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2510 *p++ = '-';
2511
2512 for (i = 0; switches[i].c != '\0'; ++i)
2513 {
2514 long_options[i].name = (switches[i].long_name == 0 ? "" :
2515 switches[i].long_name);
2516 long_options[i].flag = 0;
2517 long_options[i].val = switches[i].c;
2518 if (short_option (switches[i].c))
2519 *p++ = switches[i].c;
2520 switch (switches[i].type)
2521 {
2522 case flag:
2523 case flag_off:
2524 case ignore:
2525 long_options[i].has_arg = no_argument;
2526 break;
2527
2528 case string:
2529 case filename:
2530 case positive_int:
2531 case floating:
2532 if (short_option (switches[i].c))
2533 *p++ = ':';
2534 if (switches[i].noarg_value != 0)
2535 {
2536 if (short_option (switches[i].c))
2537 *p++ = ':';
2538 long_options[i].has_arg = optional_argument;
2539 }
2540 else
2541 long_options[i].has_arg = required_argument;
2542 break;
2543 }
2544 }
2545 *p = '\0';
2546 for (c = 0; c < (sizeof (long_option_aliases) /
2547 sizeof (long_option_aliases[0]));
2548 ++c)
2549 long_options[i++] = long_option_aliases[c];
2550 long_options[i].name = 0;
2551}
2552
2553static void
2554handle_non_switch_argument (char *arg, int env)
2555{
2556 /* Non-option argument. It might be a variable definition. */
2557 struct variable *v;
2558 if (arg[0] == '-' && arg[1] == '\0')
2559 /* Ignore plain `-' for compatibility. */
2560 return;
2561 v = try_variable_definition (0, arg, o_command, 0);
2562 if (v != 0)
2563 {
2564 /* It is indeed a variable definition. If we don't already have this
2565 one, record a pointer to the variable for later use in
2566 define_makeflags. */
2567 struct command_variable *cv;
2568
2569 for (cv = command_variables; cv != 0; cv = cv->next)
2570 if (cv->variable == v)
2571 break;
2572
2573 if (! cv) {
2574 cv = xmalloc (sizeof (*cv));
2575 cv->variable = v;
2576 cv->next = command_variables;
2577 command_variables = cv;
2578 }
2579 }
2580 else if (! env)
2581 {
2582 /* Not an option or variable definition; it must be a goal
2583 target! Enter it as a file and add it to the dep chain of
2584 goals. */
2585 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2586 f->cmd_target = 1;
2587
2588 if (goals == 0)
2589 {
2590 goals = alloc_dep ();
2591 lastgoal = goals;
2592 }
2593 else
2594 {
2595 lastgoal->next = alloc_dep ();
2596 lastgoal = lastgoal->next;
2597 }
2598
2599 lastgoal->file = f;
2600
2601 {
2602 /* Add this target name to the MAKECMDGOALS variable. */
2603 struct variable *gv;
2604 const char *value;
2605
2606 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2607 if (gv == 0)
2608 value = f->name;
2609 else
2610 {
2611 /* Paste the old and new values together */
2612 unsigned int oldlen, newlen;
2613 char *vp;
2614
2615 oldlen = strlen (gv->value);
2616 newlen = strlen (f->name);
2617 vp = alloca (oldlen + 1 + newlen + 1);
2618 memcpy (vp, gv->value, oldlen);
2619 vp[oldlen] = ' ';
2620 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2621 value = vp;
2622 }
2623 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2624 }
2625 }
2626}
2627
2628/* Print a nice usage method. */
2629
2630static void
2631print_usage (int bad)
2632{
2633 const char *const *cpp;
2634 FILE *usageto;
2635
2636 if (print_version_flag)
2637 print_version ();
2638
2639 usageto = bad ? stderr : stdout;
2640
2641 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2642
2643 for (cpp = usage; *cpp; ++cpp)
2644 fputs (_(*cpp), usageto);
2645
2646#ifdef KMK
2647 if (!remote_description || *remote_description == '\0')
2648 printf (_("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
2649 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2650 else
2651 printf (_("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
2652 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2653#else /* !KMK */
2654 if (!remote_description || *remote_description == '\0')
2655 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2656 else
2657 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2658 make_host, remote_description);
2659#endif /* !KMK */
2660
2661 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2662}
2663
2664/* Decode switches from ARGC and ARGV.
2665 They came from the environment if ENV is nonzero. */
2666
2667static void
2668decode_switches (int argc, char **argv, int env)
2669{
2670 int bad = 0;
2671 register const struct command_switch *cs;
2672 register struct stringlist *sl;
2673 register int c;
2674
2675 /* getopt does most of the parsing for us.
2676 First, get its vectors set up. */
2677
2678 init_switches ();
2679
2680 /* Let getopt produce error messages for the command line,
2681 but not for options from the environment. */
2682 opterr = !env;
2683 /* Reset getopt's state. */
2684 optind = 0;
2685
2686 while (optind < argc)
2687 {
2688 /* Parse the next argument. */
2689 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2690 if (c == EOF)
2691 /* End of arguments, or "--" marker seen. */
2692 break;
2693 else if (c == 1)
2694 /* An argument not starting with a dash. */
2695 handle_non_switch_argument (optarg, env);
2696 else if (c == '?')
2697 /* Bad option. We will print a usage message and die later.
2698 But continue to parse the other options so the user can
2699 see all he did wrong. */
2700 bad = 1;
2701 else
2702 for (cs = switches; cs->c != '\0'; ++cs)
2703 if (cs->c == c)
2704 {
2705 /* Whether or not we will actually do anything with
2706 this switch. We test this individually inside the
2707 switch below rather than just once outside it, so that
2708 options which are to be ignored still consume args. */
2709 int doit = !env || cs->env;
2710
2711 switch (cs->type)
2712 {
2713 default:
2714 abort ();
2715
2716 case ignore:
2717 break;
2718
2719 case flag:
2720 case flag_off:
2721 if (doit)
2722 *(int *) cs->value_ptr = cs->type == flag;
2723 break;
2724
2725 case string:
2726 case filename:
2727 if (!doit)
2728 break;
2729
2730 if (optarg == 0)
2731 optarg = xstrdup (cs->noarg_value);
2732 else if (*optarg == '\0')
2733 {
2734 error (NILF, _("the `-%c' option requires a non-empty string argument"),
2735 cs->c);
2736 bad = 1;
2737 }
2738
2739 sl = *(struct stringlist **) cs->value_ptr;
2740 if (sl == 0)
2741 {
2742 sl = (struct stringlist *)
2743 xmalloc (sizeof (struct stringlist));
2744 sl->max = 5;
2745 sl->idx = 0;
2746 sl->list = xmalloc (5 * sizeof (char *));
2747 *(struct stringlist **) cs->value_ptr = sl;
2748 }
2749 else if (sl->idx == sl->max - 1)
2750 {
2751 sl->max += 5;
2752 sl->list = xrealloc (sl->list,
2753 sl->max * sizeof (char *));
2754 }
2755 if (cs->type == filename)
2756 sl->list[sl->idx++] = expand_command_line_file (optarg);
2757 else
2758 sl->list[sl->idx++] = optarg;
2759 sl->list[sl->idx] = 0;
2760 break;
2761
2762 case positive_int:
2763 /* See if we have an option argument; if we do require that
2764 it's all digits, not something like "10foo". */
2765 if (optarg == 0 && argc > optind)
2766 {
2767 const char *cp;
2768 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2769 ;
2770 if (cp[0] == '\0')
2771 optarg = argv[optind++];
2772 }
2773
2774 if (!doit)
2775 break;
2776
2777 if (optarg != 0)
2778 {
2779 int i = atoi (optarg);
2780 const char *cp;
2781
2782 /* Yes, I realize we're repeating this in some cases. */
2783 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2784 ;
2785
2786 if (i < 1 || cp[0] != '\0')
2787 {
2788 error (NILF, _("the `-%c' option requires a positive integral argument"),
2789 cs->c);
2790 bad = 1;
2791 }
2792 else
2793 *(unsigned int *) cs->value_ptr = i;
2794 }
2795 else
2796 *(unsigned int *) cs->value_ptr
2797 = *(unsigned int *) cs->noarg_value;
2798 break;
2799
2800#ifndef NO_FLOAT
2801 case floating:
2802 if (optarg == 0 && optind < argc
2803 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2804 optarg = argv[optind++];
2805
2806 if (doit)
2807 *(double *) cs->value_ptr
2808 = (optarg != 0 ? atof (optarg)
2809 : *(double *) cs->noarg_value);
2810
2811 break;
2812#endif
2813 }
2814
2815 /* We've found the switch. Stop looking. */
2816 break;
2817 }
2818 }
2819
2820 /* There are no more options according to getting getopt, but there may
2821 be some arguments left. Since we have asked for non-option arguments
2822 to be returned in order, this only happens when there is a "--"
2823 argument to prevent later arguments from being options. */
2824 while (optind < argc)
2825 handle_non_switch_argument (argv[optind++], env);
2826
2827
2828 if (!env && (bad || print_usage_flag))
2829 {
2830 print_usage (bad);
2831 die (bad ? 2 : 0);
2832 }
2833}
2834
2835/* Decode switches from environment variable ENVAR (which is LEN chars long).
2836 We do this by chopping the value into a vector of words, prepending a
2837 dash to the first word if it lacks one, and passing the vector to
2838 decode_switches. */
2839
2840static void
2841decode_env_switches (char *envar, unsigned int len)
2842{
2843 char *varref = alloca (2 + len + 2);
2844 char *value, *p;
2845 int argc;
2846 char **argv;
2847
2848 /* Get the variable's value. */
2849 varref[0] = '$';
2850 varref[1] = '(';
2851 memcpy (&varref[2], envar, len);
2852 varref[2 + len] = ')';
2853 varref[2 + len + 1] = '\0';
2854 value = variable_expand (varref);
2855
2856 /* Skip whitespace, and check for an empty value. */
2857 value = next_token (value);
2858 len = strlen (value);
2859 if (len == 0)
2860 return;
2861
2862 /* Allocate a vector that is definitely big enough. */
2863 argv = alloca ((1 + len + 1) * sizeof (char *));
2864
2865 /* Allocate a buffer to copy the value into while we split it into words
2866 and unquote it. We must use permanent storage for this because
2867 decode_switches may store pointers into the passed argument words. */
2868 p = xmalloc (2 * len);
2869
2870 /* getopt will look at the arguments starting at ARGV[1].
2871 Prepend a spacer word. */
2872 argv[0] = 0;
2873 argc = 1;
2874 argv[argc] = p;
2875 while (*value != '\0')
2876 {
2877 if (*value == '\\' && value[1] != '\0')
2878 ++value; /* Skip the backslash. */
2879 else if (isblank ((unsigned char)*value))
2880 {
2881 /* End of the word. */
2882 *p++ = '\0';
2883 argv[++argc] = p;
2884 do
2885 ++value;
2886 while (isblank ((unsigned char)*value));
2887 continue;
2888 }
2889 *p++ = *value++;
2890 }
2891 *p = '\0';
2892 argv[++argc] = 0;
2893
2894 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2895 /* The first word doesn't start with a dash and isn't a variable
2896 definition. Add a dash and pass it along to decode_switches. We
2897 need permanent storage for this in case decode_switches saves
2898 pointers into the value. */
2899 argv[1] = xstrdup (concat ("-", argv[1], ""));
2900
2901 /* Parse those words. */
2902 decode_switches (argc, argv, 1);
2903}
2904
2905
2906/* Quote the string IN so that it will be interpreted as a single word with
2907 no magic by decode_env_switches; also double dollar signs to avoid
2908 variable expansion in make itself. Write the result into OUT, returning
2909 the address of the next character to be written.
2910 Allocating space for OUT twice the length of IN is always sufficient. */
2911
2912static char *
2913quote_for_env (char *out, const char *in)
2914{
2915 while (*in != '\0')
2916 {
2917 if (*in == '$')
2918 *out++ = '$';
2919 else if (isblank ((unsigned char)*in) || *in == '\\')
2920 *out++ = '\\';
2921 *out++ = *in++;
2922 }
2923
2924 return out;
2925}
2926
2927/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2928 command switches. Include options with args if ALL is nonzero.
2929 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2930
2931static void
2932define_makeflags (int all, int makefile)
2933{
2934 static const char ref[] = "$(MAKEOVERRIDES)";
2935 static const char posixref[] = "$(-*-command-variables-*-)";
2936 register const struct command_switch *cs;
2937 char *flagstring;
2938 register char *p;
2939 unsigned int words;
2940 struct variable *v;
2941
2942 /* We will construct a linked list of `struct flag's describing
2943 all the flags which need to go in MAKEFLAGS. Then, once we
2944 know how many there are and their lengths, we can put them all
2945 together in a string. */
2946
2947 struct flag
2948 {
2949 struct flag *next;
2950 const struct command_switch *cs;
2951 const char *arg;
2952 };
2953 struct flag *flags = 0;
2954 unsigned int flagslen = 0;
2955#define ADD_FLAG(ARG, LEN) \
2956 do { \
2957 struct flag *new = alloca (sizeof (struct flag)); \
2958 new->cs = cs; \
2959 new->arg = (ARG); \
2960 new->next = flags; \
2961 flags = new; \
2962 if (new->arg == 0) \
2963 ++flagslen; /* Just a single flag letter. */ \
2964 else \
2965 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2966 if (!short_option (cs->c)) \
2967 /* This switch has no single-letter version, so we use the long. */ \
2968 flagslen += 2 + strlen (cs->long_name); \
2969 } while (0)
2970
2971 for (cs = switches; cs->c != '\0'; ++cs)
2972 if (cs->toenv && (!makefile || !cs->no_makefile))
2973 switch (cs->type)
2974 {
2975 case ignore:
2976 break;
2977
2978 case flag:
2979 case flag_off:
2980 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2981 && (cs->default_value == 0
2982 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2983 ADD_FLAG (0, 0);
2984 break;
2985
2986 case positive_int:
2987 if (all)
2988 {
2989 if ((cs->default_value != 0
2990 && (*(unsigned int *) cs->value_ptr
2991 == *(unsigned int *) cs->default_value)))
2992 break;
2993 else if (cs->noarg_value != 0
2994 && (*(unsigned int *) cs->value_ptr ==
2995 *(unsigned int *) cs->noarg_value))
2996 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2997#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
2998 else if (cs->c == 'j')
2999 /* Special case for `-j'. */
3000 ADD_FLAG ("1", 1);
3001#endif
3002 else
3003 {
3004 char *buf = alloca (30);
3005 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3006 ADD_FLAG (buf, strlen (buf));
3007 }
3008 }
3009 break;
3010
3011#ifndef NO_FLOAT
3012 case floating:
3013 if (all)
3014 {
3015 if (cs->default_value != 0
3016 && (*(double *) cs->value_ptr
3017 == *(double *) cs->default_value))
3018 break;
3019 else if (cs->noarg_value != 0
3020 && (*(double *) cs->value_ptr
3021 == *(double *) cs->noarg_value))
3022 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3023 else
3024 {
3025 char *buf = alloca (100);
3026 sprintf (buf, "%g", *(double *) cs->value_ptr);
3027 ADD_FLAG (buf, strlen (buf));
3028 }
3029 }
3030 break;
3031#endif
3032
3033 case filename:
3034 case string:
3035 if (all)
3036 {
3037 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3038 if (sl != 0)
3039 {
3040 /* Add the elements in reverse order, because all the flags
3041 get reversed below; and the order matters for some
3042 switches (like -I). */
3043 unsigned int i = sl->idx;
3044 while (i-- > 0)
3045 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3046 }
3047 }
3048 break;
3049
3050 default:
3051 abort ();
3052 }
3053
3054 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3055
3056#undef ADD_FLAG
3057
3058 /* Construct the value in FLAGSTRING.
3059 We allocate enough space for a preceding dash and trailing null. */
3060 flagstring = alloca (1 + flagslen + 1);
3061 memset (flagstring, '\0', 1 + flagslen + 1);
3062 p = flagstring;
3063 words = 1;
3064 *p++ = '-';
3065 while (flags != 0)
3066 {
3067 /* Add the flag letter or name to the string. */
3068 if (short_option (flags->cs->c))
3069 *p++ = flags->cs->c;
3070 else
3071 {
3072 if (*p != '-')
3073 {
3074 *p++ = ' ';
3075 *p++ = '-';
3076 }
3077 *p++ = '-';
3078 strcpy (p, flags->cs->long_name);
3079 p += strlen (p);
3080 }
3081 if (flags->arg != 0)
3082 {
3083 /* A flag that takes an optional argument which in this case is
3084 omitted is specified by ARG being "". We must distinguish
3085 because a following flag appended without an intervening " -"
3086 is considered the arg for the first. */
3087 if (flags->arg[0] != '\0')
3088 {
3089 /* Add its argument too. */
3090 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3091 p = quote_for_env (p, flags->arg);
3092 }
3093 ++words;
3094 /* Write a following space and dash, for the next flag. */
3095 *p++ = ' ';
3096 *p++ = '-';
3097 }
3098 else if (!short_option (flags->cs->c))
3099 {
3100 ++words;
3101 /* Long options must each go in their own word,
3102 so we write the following space and dash. */
3103 *p++ = ' ';
3104 *p++ = '-';
3105 }
3106 flags = flags->next;
3107 }
3108
3109 /* Define MFLAGS before appending variable definitions. */
3110
3111 if (p == &flagstring[1])
3112 /* No flags. */
3113 flagstring[0] = '\0';
3114 else if (p[-1] == '-')
3115 {
3116 /* Kill the final space and dash. */
3117 p -= 2;
3118 *p = '\0';
3119 }
3120 else
3121 /* Terminate the string. */
3122 *p = '\0';
3123
3124 /* Since MFLAGS is not parsed for flags, there is no reason to
3125 override any makefile redefinition. */
3126 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3127
3128 if (all && command_variables != 0)
3129 {
3130 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3131 command-line variable definitions. */
3132
3133 if (p == &flagstring[1])
3134 /* No flags written, so elide the leading dash already written. */
3135 p = flagstring;
3136 else
3137 {
3138 /* Separate the variables from the switches with a "--" arg. */
3139 if (p[-1] != '-')
3140 {
3141 /* We did not already write a trailing " -". */
3142 *p++ = ' ';
3143 *p++ = '-';
3144 }
3145 /* There is a trailing " -"; fill it out to " -- ". */
3146 *p++ = '-';
3147 *p++ = ' ';
3148 }
3149
3150 /* Copy in the string. */
3151 if (posix_pedantic)
3152 {
3153 memcpy (p, posixref, sizeof posixref - 1);
3154 p += sizeof posixref - 1;
3155 }
3156 else
3157 {
3158 memcpy (p, ref, sizeof ref - 1);
3159 p += sizeof ref - 1;
3160 }
3161 }
3162 else if (p == &flagstring[1])
3163 {
3164 words = 0;
3165 --p;
3166 }
3167 else if (p[-1] == '-')
3168 /* Kill the final space and dash. */
3169 p -= 2;
3170 /* Terminate the string. */
3171 *p = '\0';
3172
3173 v = define_variable ("MAKEFLAGS", 9,
3174 /* If there are switches, omit the leading dash
3175 unless it is a single long option with two
3176 leading dashes. */
3177 &flagstring[(flagstring[0] == '-'
3178 && flagstring[1] != '-')
3179 ? 1 : 0],
3180 /* This used to use o_env, but that lost when a
3181 makefile defined MAKEFLAGS. Makefiles set
3182 MAKEFLAGS to add switches, but we still want
3183 to redefine its value with the full set of
3184 switches. Of course, an override or command
3185 definition will still take precedence. */
3186 o_file, 1);
3187 if (! all)
3188 /* The first time we are called, set MAKEFLAGS to always be exported.
3189 We should not do this again on the second call, because that is
3190 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3191 v->export = v_export;
3192}
3193
3194
3195/* Print version information. */
3196
3197static void
3198print_version (void)
3199{
3200 static int printed_version = 0;
3201
3202 char *precede = print_data_base_flag ? "# " : "";
3203
3204 if (printed_version)
3205 /* Do it only once. */
3206 return;
3207
3208 /* Print this untranslated. The coding standards recommend translating the
3209 (C) to the copyright symbol, but this string is going to change every
3210 year, and none of the rest of it should be translated (including the
3211 word "Copyright", so it hardly seems worth it. */
3212
3213#ifdef KMK
3214 printf ("%skBuild Make %d.%d.%d\n\
3215\n\
3216%sBased on GNU Make %s:\n\
3217%s Copyright (C) 2006 Free Software Foundation, Inc.\n\
3218\n\
3219%skBuild Modifications:\n\
3220%s Copyright (C) 2005-2006 Knut St. Osmundsen.\n\
3221\n\
3222%skmkbuiltin commands derived from *BSD sources:\n\
3223%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3224%s The Regents of the University of California. All rights reserved.\n\
3225%s Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>\n\
3226%s\n",
3227 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR, KBUILD_VERSION_PATCH,
3228 precede, version_string,
3229 precede, precede, precede, precede, precede, precede, precede, precede);
3230#else
3231 printf ("%sGNU Make %s\n\
3232%sCopyright (C) 2006 Free Software Foundation, Inc.\n",
3233 precede, version_string, precede);
3234#endif
3235
3236 printf (_("%sThis is free software; see the source for copying conditions.\n\
3237%sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
3238%sPARTICULAR PURPOSE.\n"),
3239 precede, precede, precede);
3240
3241#ifdef KMK
3242# ifdef PATH_KBUILD
3243 printf (_("%s\n\
3244%sPATH_KBUILD default: '%s'\n\
3245%sPATH_KBUILD_BIN default: '%s'\n"),
3246 precede, precede, PATH_KBUILD, precede, PATH_KBUILD_BIN);
3247# endif /* PATH_KBUILD */
3248 if (!remote_description || *remote_description == '\0')
3249 printf (_("\n%sThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3250 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3251 else
3252 printf (_("\n%sThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3253 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3254#else
3255 if (!remote_description || *remote_description == '\0')
3256 printf (_("\n%sThis program built for %s\n"), precede, make_host);
3257 else
3258 printf (_("\n%sThis program built for %s (%s)\n"),
3259 precede, make_host, remote_description);
3260#endif
3261
3262 printed_version = 1;
3263
3264 /* Flush stdout so the user doesn't have to wait to see the
3265 version information while things are thought about. */
3266 fflush (stdout);
3267}
3268
3269/* Print a bunch of information about this and that. */
3270
3271static void
3272print_data_base ()
3273{
3274 time_t when;
3275
3276 when = time ((time_t *) 0);
3277 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3278
3279 print_variable_data_base ();
3280 print_dir_data_base ();
3281 print_rule_data_base ();
3282 print_file_data_base ();
3283 print_vpath_data_base ();
3284 strcache_print_stats ("#");
3285
3286 when = time ((time_t *) 0);
3287 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3288}
3289
3290static void
3291clean_jobserver (int status)
3292{
3293 char token = '+';
3294
3295 /* Sanity: have we written all our jobserver tokens back? If our
3296 exit status is 2 that means some kind of syntax error; we might not
3297 have written all our tokens so do that now. If tokens are left
3298 after any other error code, that's bad. */
3299
3300 if (job_fds[0] != -1 && jobserver_tokens)
3301 {
3302 if (status != 2)
3303 error (NILF,
3304 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3305 jobserver_tokens);
3306 else
3307 while (jobserver_tokens--)
3308 {
3309 int r;
3310
3311 EINTRLOOP (r, write (job_fds[1], &token, 1));
3312 if (r != 1)
3313 perror_with_name ("write", "");
3314 }
3315 }
3316
3317
3318 /* Sanity: If we're the master, were all the tokens written back? */
3319
3320 if (master_job_slots)
3321 {
3322 /* We didn't write one for ourself, so start at 1. */
3323 unsigned int tcnt = 1;
3324
3325 /* Close the write side, so the read() won't hang. */
3326 close (job_fds[1]);
3327
3328 while (read (job_fds[0], &token, 1) == 1)
3329 ++tcnt;
3330
3331 if (tcnt != master_job_slots)
3332 error (NILF,
3333 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3334 tcnt, master_job_slots);
3335
3336 close (job_fds[0]);
3337 }
3338}
3339
3340
3341/* Exit with STATUS, cleaning up as necessary. */
3342
3343void
3344die (int status)
3345{
3346 static char dying = 0;
3347
3348 if (!dying)
3349 {
3350 int err;
3351
3352 dying = 1;
3353
3354 if (print_version_flag)
3355 print_version ();
3356
3357 /* Wait for children to die. */
3358 err = (status != 0);
3359 while (job_slots_used > 0)
3360 reap_children (1, err);
3361
3362 /* Let the remote job module clean up its state. */
3363 remote_cleanup ();
3364
3365 /* Remove the intermediate files. */
3366 remove_intermediates (0);
3367
3368 if (print_data_base_flag)
3369 print_data_base ();
3370
3371 verify_file_data_base ();
3372
3373 clean_jobserver (status);
3374
3375 /* Try to move back to the original directory. This is essential on
3376 MS-DOS (where there is really only one process), and on Unix it
3377 puts core files in the original directory instead of the -C
3378 directory. Must wait until after remove_intermediates(), or unlinks
3379 of relative pathnames fail. */
3380 if (directory_before_chdir != 0)
3381 chdir (directory_before_chdir);
3382
3383 log_working_directory (0);
3384 }
3385
3386 exit (status);
3387}
3388
3389
3390/* Write a message indicating that we've just entered or
3391 left (according to ENTERING) the current directory. */
3392
3393void
3394log_working_directory (int entering)
3395{
3396 static int entered = 0;
3397
3398 /* Print nothing without the flag. Don't print the entering message
3399 again if we already have. Don't print the leaving message if we
3400 haven't printed the entering message. */
3401 if (! print_directory_flag || entering == entered)
3402 return;
3403
3404 entered = entering;
3405
3406 if (print_data_base_flag)
3407 fputs ("# ", stdout);
3408
3409 /* Use entire sentences to give the translators a fighting chance. */
3410
3411 if (makelevel == 0)
3412 if (starting_directory == 0)
3413 if (entering)
3414 printf (_("%s: Entering an unknown directory\n"), program);
3415 else
3416 printf (_("%s: Leaving an unknown directory\n"), program);
3417 else
3418 if (entering)
3419 printf (_("%s: Entering directory `%s'\n"),
3420 program, starting_directory);
3421 else
3422 printf (_("%s: Leaving directory `%s'\n"),
3423 program, starting_directory);
3424 else
3425 if (starting_directory == 0)
3426 if (entering)
3427 printf (_("%s[%u]: Entering an unknown directory\n"),
3428 program, makelevel);
3429 else
3430 printf (_("%s[%u]: Leaving an unknown directory\n"),
3431 program, makelevel);
3432 else
3433 if (entering)
3434 printf (_("%s[%u]: Entering directory `%s'\n"),
3435 program, makelevel, starting_directory);
3436 else
3437 printf (_("%s[%u]: Leaving directory `%s'\n"),
3438 program, makelevel, starting_directory);
3439
3440 /* Flush stdout to be sure this comes before any stderr output. */
3441 fflush (stdout);
3442}
Note: See TracBrowser for help on using the repository browser.