VirtualBox

source: kBuild/trunk/src/gmakenew/main.c@ 944

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

Some more warnings.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette