VirtualBox

source: kBuild/trunk/src/kmk/main.c@ 1134

Last change on this file since 1134 was 1126, checked in by bird, 17 years ago

Need to check for Makefile.kup *after* processing -C arguments.

  • Property svn:eol-style set to native
File size: 98.8 KB
Line 
1/* Argument parsing and main program of GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4Foundation, Inc.
5This file is part of GNU Make.
6
7GNU Make is free software; you can redistribute it and/or modify it under the
8terms of the GNU General Public License as published by the Free Software
9Foundation; either version 2, or (at your option) any later version.
10
11GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License along with
16GNU Make; see the file COPYING. If not, write to the Free Software
17Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
18
19#include "make.h"
20#include "dep.h"
21#include "filedef.h"
22#include "variable.h"
23#include "job.h"
24#include "commands.h"
25#include "rule.h"
26#include "debug.h"
27#include "getopt.h"
28#ifdef KMK
29# include "kbuild.h"
30#endif
31
32#include <assert.h>
33#ifdef _AMIGA
34# include <dos/dos.h>
35# include <proto/dos.h>
36#endif
37#ifdef WINDOWS32
38#include <windows.h>
39#include <io.h>
40#include "pathstuff.h"
41#endif
42#ifdef __EMX__
43# include <sys/types.h>
44# include <sys/wait.h>
45#endif
46#ifdef HAVE_FCNTL_H
47# include <fcntl.h>
48#endif
49
50#if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
51# define SET_STACK_SIZE
52#endif
53
54#ifdef SET_STACK_SIZE
55# include <sys/resource.h>
56#endif
57
58#ifdef _AMIGA
59int __stack = 20000; /* Make sure we have 20K of stack space */
60#endif
61
62void init_dir (void);
63void remote_setup (void);
64void remote_cleanup (void);
65RETSIGTYPE fatal_error_signal (int sig);
66
67void print_variable_data_base (void);
68void print_dir_data_base (void);
69void print_rule_data_base (void);
70void print_file_data_base (void);
71void print_vpath_data_base (void);
72
73void verify_file_data_base (void);
74
75#if defined HAVE_WAITPID || defined HAVE_WAIT3
76# define HAVE_WAIT_NOHANG
77#endif
78
79#if !defined(HAVE_UNISTD_H) && !defined(_MSC_VER) /* bird */
80int chdir ();
81#endif
82#ifndef STDC_HEADERS
83# ifndef sun /* Sun has an incorrect decl in a header. */
84void exit (int) __attribute__ ((noreturn));
85# endif
86double atof ();
87#endif
88
89static void clean_jobserver (int status);
90static void print_data_base (void);
91static void print_version (void);
92static void decode_switches (int argc, char **argv, int env);
93static void decode_env_switches (char *envar, unsigned int len);
94static void define_makeflags (int all, int makefile);
95static char *quote_for_env (char *out, const char *in);
96static void initialize_global_hash_tables (void);
97
98
99
100/* The structure that describes an accepted command switch. */
101
102struct command_switch
103 {
104 int c; /* The switch character. */
105
106 enum /* Type of the value. */
107 {
108 flag, /* Turn int flag on. */
109 flag_off, /* Turn int flag off. */
110 string, /* One string per switch. */
111 filename, /* A string containing a file name. */
112 positive_int, /* A positive integer. */
113 floating, /* A floating-point number (double). */
114 ignore /* Ignored. */
115 } type;
116
117 void *value_ptr; /* Pointer to the value-holding variable. */
118
119 unsigned int env:1; /* Can come from MAKEFLAGS. */
120 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
121 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
122
123 const void *noarg_value; /* Pointer to value used if no arg given. */
124 const void *default_value; /* Pointer to default value. */
125
126 char *long_name; /* Long option name. */
127 };
128
129/* True if C is a switch value that corresponds to a short option. */
130
131#define short_option(c) ((c) <= CHAR_MAX)
132
133/* The structure used to hold the list of strings given
134 in command switches of a type that takes string arguments. */
135
136struct stringlist
137 {
138 const char **list; /* Nil-terminated list of strings. */
139 unsigned int idx; /* Index into above. */
140 unsigned int max; /* Number of pointers allocated. */
141 };
142
143
144/* The recognized command switches. */
145
146/* Nonzero means do not print commands to be executed (-s). */
147
148int silent_flag;
149
150/* Nonzero means just touch the files
151 that would appear to need remaking (-t) */
152
153int touch_flag;
154
155/* Nonzero means just print what commands would need to be executed,
156 don't actually execute them (-n). */
157
158int just_print_flag;
159
160#ifdef CONFIG_PRETTY_COMMAND_PRINTING
161/* Nonzero means to print commands argument for argument skipping blanks. */
162
163int pretty_command_printing;
164#endif
165
166/* Print debugging info (--debug). */
167
168static struct stringlist *db_flags;
169static int debug_flag = 0;
170
171int db_level = 0;
172
173/* Output level (--verbosity). */
174
175static struct stringlist *verbosity_flags;
176
177#ifdef WINDOWS32
178/* Suspend make in main for a short time to allow debugger to attach */
179
180int suspend_flag = 0;
181#endif
182
183/* Environment variables override makefile definitions. */
184
185int env_overrides = 0;
186
187/* Nonzero means ignore status codes returned by commands
188 executed to remake files. Just treat them all as successful (-i). */
189
190int ignore_errors_flag = 0;
191
192/* Nonzero means don't remake anything, just print the data base
193 that results from reading the makefile (-p). */
194
195int print_data_base_flag = 0;
196
197/* Nonzero means don't remake anything; just return a nonzero status
198 if the specified targets are not up to date (-q). */
199
200int question_flag = 0;
201
202/* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
203
204int no_builtin_rules_flag = 0;
205int no_builtin_variables_flag = 0;
206
207/* Nonzero means keep going even if remaking some file fails (-k). */
208
209int keep_going_flag;
210int default_keep_going_flag = 0;
211
212/* Nonzero means check symlink mtimes. */
213
214int check_symlink_flag = 0;
215
216/* Nonzero means print directory before starting and when done (-w). */
217
218int print_directory_flag = 0;
219
220/* Nonzero means ignore print_directory_flag and never print the directory.
221 This is necessary because print_directory_flag is set implicitly. */
222
223int inhibit_print_directory_flag = 0;
224
225/* Nonzero means print version information. */
226
227int print_version_flag = 0;
228
229/* List of makefiles given with -f switches. */
230
231static struct stringlist *makefiles = 0;
232
233/* Number of job slots (commands that can be run at once). */
234
235unsigned int job_slots = 1;
236unsigned int default_job_slots = 1;
237static unsigned int master_job_slots = 0;
238
239/* Value of job_slots that means no limit. */
240
241static unsigned int inf_jobs = 0;
242
243/* File descriptors for the jobs pipe. */
244
245static struct stringlist *jobserver_fds = 0;
246
247int job_fds[2] = { -1, -1 };
248int job_rfd = -1;
249
250/* Maximum load average at which multiple jobs will be run.
251 Negative values mean unlimited, while zero means limit to
252 zero load (which could be useful to start infinite jobs remotely
253 but one at a time locally). */
254#ifndef NO_FLOAT
255double max_load_average = -1.0;
256double default_load_average = -1.0;
257#else
258int max_load_average = -1;
259int default_load_average = -1;
260#endif
261
262/* List of directories given with -C switches. */
263
264static struct stringlist *directories = 0;
265
266/* List of include directories given with -I switches. */
267
268static struct stringlist *include_directories = 0;
269
270/* List of files given with -o switches. */
271
272static struct stringlist *old_files = 0;
273
274/* List of files given with -W switches. */
275
276static struct stringlist *new_files = 0;
277
278/* If nonzero, we should just print usage and exit. */
279
280static int print_usage_flag = 0;
281
282/* If nonzero, we should print a warning message
283 for each reference to an undefined variable. */
284
285int warn_undefined_variables_flag;
286
287/* If nonzero, always build all targets, regardless of whether
288 they appear out of date or not. */
289
290static int always_make_set = 0;
291int always_make_flag = 0;
292
293/* If nonzero, we're in the "try to rebuild makefiles" phase. */
294
295int rebuilding_makefiles = 0;
296
297/* Remember the original value of the SHELL variable, from the environment. */
298
299struct variable shell_var;
300
301/* This character introduces a command: it's the first char on the line. */
302
303char cmd_prefix = '\t';
304
305#ifdef KMK
306/* Process priority.
307 0 = no change;
308 1 = idle / max nice;
309 2 = below normal / nice 10;
310 3 = normal / nice 0;
311 4 = high / nice -10;
312 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 /* If there were -C flags, move ourselves about. */
1579 if (directories != 0)
1580 {
1581 unsigned int i;
1582 for (i = 0; directories->list[i] != 0; ++i)
1583 {
1584 const char *dir = directories->list[i];
1585#ifdef WINDOWS32
1586 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1587 But allow -C/ just in case someone wants that. */
1588 {
1589 char *p = (char *)dir + strlen (dir) - 1;
1590 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1591 --p;
1592 p[1] = '\0';
1593 }
1594#endif
1595 if (chdir (dir) < 0)
1596 pfatal_with_name (dir);
1597 }
1598 }
1599
1600#ifdef KMK
1601 /* Check for [Mm]akefile.kup and change directory when found.
1602 Makefile.kmk overrides Makefile.kup but not plain Makefile.
1603 If no -C arguments were given, fake one to indicate chdir. */
1604 if (makefiles == 0)
1605 {
1606 struct stat st;
1607 if (( stat ("Makefile.kup", &st) == 0
1608 && S_ISREG (st.st_mode) )
1609 || ( stat ("makefile.kup", &st) == 0
1610 && S_ISREG (st.st_mode) )
1611 && stat ("Makefile.kmk", &st) < 0
1612 && stat ("makefile.kmk", &st) < 0)
1613 {
1614 static char fake_path[3*16 + 32] = "..";
1615 char *cur = &fake_path[2];
1616 int up_levels = 1;
1617 while (up_levels < 16)
1618 {
1619 /* File with higher precedence.s */
1620 strcpy (cur, "/Makefile.kmk");
1621 if (stat (fake_path, &st) == 0)
1622 break;
1623 strcpy (cur, "/makefile.kmk");
1624 if (stat (fake_path, &st) == 0)
1625 break;
1626
1627 /* the .kup files */
1628 strcpy (cur, "/Makefile.kup");
1629 if ( stat (fake_path, &st) != 0
1630 || !S_ISREG (st.st_mode))
1631 {
1632 strcpy (cur, "/makefile.kup");
1633 if ( stat (fake_path, &st) != 0
1634 || !S_ISREG (st.st_mode))
1635 break;
1636 }
1637
1638 /* ok */
1639 strcpy (cur, "/..");
1640 cur += 3;
1641 up_levels++;
1642 }
1643
1644 if (up_levels >= 16)
1645 fatal (NILF, _("Makefile.kup recursion is too deep."));
1646
1647 /* attempt to change to the directory. */
1648 *cur = '\0';
1649 if (chdir (fake_path) < 0)
1650 pfatal_with_name (fake_path);
1651
1652 /* add the string to the directories. */
1653 if (!directories)
1654 {
1655 directories = xmalloc (sizeof(*directories));
1656 directories->list = xmalloc (5 * sizeof (char *));
1657 directories->max = 5;
1658 directories->idx = 0;
1659 }
1660 else if (directories->idx == directories->max - 1)
1661 {
1662 directories->max += 5;
1663 directories->list = xrealloc ((void *)directories->list,
1664 directories->max * sizeof (char *));
1665 }
1666 directories->list[directories->idx++] = fake_path;
1667 }
1668 }
1669#endif /* KMK */
1670
1671#ifdef WINDOWS32
1672 /*
1673 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1674 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1675 *
1676 * The functions in dir.c can incorrectly cache information for "."
1677 * before we have changed directory and this can cause file
1678 * lookups to fail because the current directory (.) was pointing
1679 * at the wrong place when it was first evaluated.
1680 */
1681 no_default_sh_exe = !find_and_set_default_shell(NULL);
1682
1683#endif /* WINDOWS32 */
1684 /* Figure out the level of recursion. */
1685 {
1686 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1687 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1688 makelevel = (unsigned int) atoi (v->value);
1689 else
1690 makelevel = 0;
1691 }
1692
1693 /* Except under -s, always do -w in sub-makes and under -C. */
1694 if (!silent_flag && (directories != 0 || makelevel > 0))
1695 print_directory_flag = 1;
1696
1697 /* Let the user disable that with --no-print-directory. */
1698 if (inhibit_print_directory_flag)
1699 print_directory_flag = 0;
1700
1701 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1702 if (no_builtin_variables_flag)
1703 no_builtin_rules_flag = 1;
1704
1705 /* Construct the list of include directories to search. */
1706
1707 construct_include_path (include_directories == 0
1708 ? 0 : include_directories->list);
1709
1710 /* Figure out where we are now, after chdir'ing. */
1711 if (directories == 0)
1712 /* We didn't move, so we're still in the same place. */
1713 starting_directory = current_directory;
1714 else
1715 {
1716#ifdef WINDOWS32
1717 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1718#else
1719 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1720#endif
1721 {
1722#ifdef HAVE_GETCWD
1723 perror_with_name ("getcwd", "");
1724#else
1725 error (NILF, "getwd: %s", current_directory);
1726#endif
1727 starting_directory = 0;
1728 }
1729 else
1730 starting_directory = current_directory;
1731 }
1732
1733 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1734
1735 /* Read any stdin makefiles into temporary files. */
1736
1737 if (makefiles != 0)
1738 {
1739 unsigned int i;
1740 for (i = 0; i < makefiles->idx; ++i)
1741 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1742 {
1743 /* This makefile is standard input. Since we may re-exec
1744 and thus re-read the makefiles, we read standard input
1745 into a temporary file and read from that. */
1746 FILE *outfile;
1747 char *template, *tmpdir;
1748
1749 if (stdin_nm)
1750 fatal (NILF, _("Makefile from standard input specified twice."));
1751
1752#ifdef VMS
1753# define DEFAULT_TMPDIR "sys$scratch:"
1754#else
1755# ifdef P_tmpdir
1756# define DEFAULT_TMPDIR P_tmpdir
1757# else
1758# define DEFAULT_TMPDIR "/tmp"
1759# endif
1760#endif
1761#define DEFAULT_TMPFILE "GmXXXXXX"
1762
1763 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1764#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1765 /* These are also used commonly on these platforms. */
1766 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1767 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1768#endif
1769 )
1770 tmpdir = DEFAULT_TMPDIR;
1771
1772 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
1773 strcpy (template, tmpdir);
1774
1775#ifdef HAVE_DOS_PATHS
1776 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1777 strcat (template, "/");
1778#else
1779# ifndef VMS
1780 if (template[strlen (template) - 1] != '/')
1781 strcat (template, "/");
1782# endif /* !VMS */
1783#endif /* !HAVE_DOS_PATHS */
1784
1785 strcat (template, DEFAULT_TMPFILE);
1786 outfile = open_tmpfile (&stdin_nm, template);
1787 if (outfile == 0)
1788 pfatal_with_name (_("fopen (temporary file)"));
1789 while (!feof (stdin) && ! ferror (stdin))
1790 {
1791 char buf[2048];
1792 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1793 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1794 pfatal_with_name (_("fwrite (temporary file)"));
1795 }
1796 fclose (outfile);
1797
1798 /* Replace the name that read_all_makefiles will
1799 see with the name of the temporary file. */
1800 makefiles->list[i] = strcache_add (stdin_nm);
1801
1802 /* Make sure the temporary file will not be remade. */
1803 {
1804 struct file *f = enter_file (strcache_add (stdin_nm));
1805 f->updated = 1;
1806 f->update_status = 0;
1807 f->command_state = cs_finished;
1808 /* Can't be intermediate, or it'll be removed too early for
1809 make re-exec. */
1810 f->intermediate = 0;
1811 f->dontcare = 0;
1812 }
1813 }
1814 }
1815
1816#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
1817#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1818 /* Set up to handle children dying. This must be done before
1819 reading in the makefiles so that `shell' function calls will work.
1820
1821 If we don't have a hanging wait we have to fall back to old, broken
1822 functionality here and rely on the signal handler and counting
1823 children.
1824
1825 If we're using the jobs pipe we need a signal handler so that
1826 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1827 jobserver pipe in job.c if we're waiting for a token.
1828
1829 If none of these are true, we don't need a signal handler at all. */
1830 {
1831 RETSIGTYPE child_handler (int sig);
1832# if defined SIGCHLD
1833 bsd_signal (SIGCHLD, child_handler);
1834# endif
1835# if defined SIGCLD && SIGCLD != SIGCHLD
1836 bsd_signal (SIGCLD, child_handler);
1837# endif
1838 }
1839#endif
1840#endif
1841
1842 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1843#ifdef SIGUSR1
1844 bsd_signal (SIGUSR1, debug_signal_handler);
1845#endif
1846
1847 /* Define the initial list of suffixes for old-style rules. */
1848
1849 set_default_suffixes ();
1850
1851 /* Define the file rules for the built-in suffix rules. These will later
1852 be converted into pattern rules. We used to do this in
1853 install_default_implicit_rules, but since that happens after reading
1854 makefiles, it results in the built-in pattern rules taking precedence
1855 over makefile-specified suffix rules, which is wrong. */
1856
1857 install_default_suffix_rules ();
1858
1859 /* Define some internal and special variables. */
1860
1861 define_automatic_variables ();
1862
1863 /* Set up the MAKEFLAGS and MFLAGS variables
1864 so makefiles can look at them. */
1865
1866 define_makeflags (0, 0);
1867
1868 /* Define the default variables. */
1869 define_default_variables ();
1870
1871 default_file = enter_file (strcache_add (".DEFAULT"));
1872
1873 {
1874 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
1875 default_goal_name = &v->value;
1876 }
1877
1878 /* Read all the makefiles. */
1879
1880 read_makefiles
1881 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1882
1883#ifdef WINDOWS32
1884 /* look one last time after reading all Makefiles */
1885 if (no_default_sh_exe)
1886 no_default_sh_exe = !find_and_set_default_shell(NULL);
1887#endif /* WINDOWS32 */
1888
1889#if defined (__MSDOS__) || defined (__EMX__)
1890 /* We need to know what kind of shell we will be using. */
1891 {
1892 extern int _is_unixy_shell (const char *_path);
1893 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1894 extern int unixy_shell;
1895 extern char *default_shell;
1896
1897 if (shv && *shv->value)
1898 {
1899 char *shell_path = recursively_expand(shv);
1900
1901 if (shell_path && _is_unixy_shell (shell_path))
1902 unixy_shell = 1;
1903 else
1904 unixy_shell = 0;
1905 if (shell_path)
1906 default_shell = shell_path;
1907 }
1908 }
1909#endif /* __MSDOS__ || __EMX__ */
1910
1911 /* Decode switches again, in case the variables were set by the makefile. */
1912 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1913#if 0
1914 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1915#endif
1916
1917#if defined (__MSDOS__) || defined (__EMX__)
1918 if (job_slots != 1
1919# ifdef __EMX__
1920 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1921# endif
1922 )
1923 {
1924 error (NILF,
1925 _("Parallel jobs (-j) are not supported on this platform."));
1926 error (NILF, _("Resetting to single job (-j1) mode."));
1927 job_slots = 1;
1928 }
1929#endif
1930
1931#ifdef MAKE_JOBSERVER
1932 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
1933
1934 if (jobserver_fds)
1935 {
1936 const char *cp;
1937 unsigned int ui;
1938
1939 for (ui=1; ui < jobserver_fds->idx; ++ui)
1940 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1941 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1942
1943 /* Now parse the fds string and make sure it has the proper format. */
1944
1945 cp = jobserver_fds->list[0];
1946
1947 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
1948 fatal (NILF,
1949 _("internal error: invalid --jobserver-fds string `%s'"), cp);
1950
1951 DB (DB_JOBS,
1952 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
1953
1954 /* The combination of a pipe + !job_slots means we're using the
1955 jobserver. If !job_slots and we don't have a pipe, we can start
1956 infinite jobs. If we see both a pipe and job_slots >0 that means the
1957 user set -j explicitly. This is broken; in this case obey the user
1958 (ignore the jobserver pipe for this make) but print a message. */
1959
1960 if (job_slots > 0)
1961 error (NILF,
1962 _("warning: -jN forced in submake: disabling jobserver mode."));
1963
1964 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1965 handler. If this fails with EBADF, the parent has closed the pipe
1966 on us because it didn't think we were a submake. If so, print a
1967 warning then default to -j1. */
1968
1969 else if ((job_rfd = dup (job_fds[0])) < 0)
1970 {
1971 if (errno != EBADF)
1972 pfatal_with_name (_("dup jobserver"));
1973
1974 error (NILF,
1975 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
1976 job_slots = 1;
1977 }
1978
1979 if (job_slots > 0)
1980 {
1981 close (job_fds[0]);
1982 close (job_fds[1]);
1983 job_fds[0] = job_fds[1] = -1;
1984 free (jobserver_fds->list);
1985 free (jobserver_fds);
1986 jobserver_fds = 0;
1987 }
1988 }
1989
1990 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
1991 Set up the pipe and install the fds option for our children. */
1992
1993 if (job_slots > 1)
1994 {
1995 char *cp;
1996 char c = '+';
1997
1998 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
1999 pfatal_with_name (_("creating jobs pipe"));
2000
2001 /* Every make assumes that it always has one job it can run. For the
2002 submakes it's the token they were given by their parent. For the
2003 top make, we just subtract one from the number the user wants. We
2004 want job_slots to be 0 to indicate we're using the jobserver. */
2005
2006 master_job_slots = job_slots;
2007
2008 while (--job_slots)
2009 {
2010 int r;
2011
2012 EINTRLOOP (r, write (job_fds[1], &c, 1));
2013 if (r != 1)
2014 pfatal_with_name (_("init jobserver pipe"));
2015 }
2016
2017 /* Fill in the jobserver_fds struct for our children. */
2018
2019 cp = xmalloc ((sizeof ("1024")*2)+1);
2020 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2021
2022 jobserver_fds = (struct stringlist *)
2023 xmalloc (sizeof (struct stringlist));
2024 jobserver_fds->list = xmalloc (sizeof (char *));
2025 jobserver_fds->list[0] = cp;
2026 jobserver_fds->idx = 1;
2027 jobserver_fds->max = 1;
2028 }
2029#endif
2030
2031#ifndef MAKE_SYMLINKS
2032 if (check_symlink_flag)
2033 {
2034 error (NILF, _("Symbolic links not supported: disabling -L."));
2035 check_symlink_flag = 0;
2036 }
2037#endif
2038
2039 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2040
2041 define_makeflags (1, 0);
2042
2043 /* Make each `struct dep' point at the `struct file' for the file
2044 depended on. Also do magic for special targets. */
2045
2046 snap_deps ();
2047
2048 /* Convert old-style suffix rules to pattern rules. It is important to
2049 do this before installing the built-in pattern rules below, so that
2050 makefile-specified suffix rules take precedence over built-in pattern
2051 rules. */
2052
2053 convert_to_pattern ();
2054
2055 /* Install the default implicit pattern rules.
2056 This used to be done before reading the makefiles.
2057 But in that case, built-in pattern rules were in the chain
2058 before user-defined ones, so they matched first. */
2059
2060 install_default_implicit_rules ();
2061
2062 /* Compute implicit rule limits. */
2063
2064 count_implicit_rule_limits ();
2065
2066 /* Construct the listings of directories in VPATH lists. */
2067
2068 build_vpath_lists ();
2069
2070 /* Mark files given with -o flags as very old and as having been updated
2071 already, and files given with -W flags as brand new (time-stamp as far
2072 as possible into the future). If restarts is set we'll do -W later. */
2073
2074 if (old_files != 0)
2075 {
2076 const char **p;
2077 for (p = old_files->list; *p != 0; ++p)
2078 {
2079 struct file *f = enter_file (*p);
2080 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2081 f->updated = 1;
2082 f->update_status = 0;
2083 f->command_state = cs_finished;
2084 }
2085 }
2086
2087 if (!restarts && new_files != 0)
2088 {
2089 const char **p;
2090 for (p = new_files->list; *p != 0; ++p)
2091 {
2092 struct file *f = enter_file (*p);
2093 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2094 }
2095 }
2096
2097 /* Initialize the remote job module. */
2098 remote_setup ();
2099
2100 if (read_makefiles != 0)
2101 {
2102 /* Update any makefiles if necessary. */
2103
2104 FILE_TIMESTAMP *makefile_mtimes = 0;
2105 unsigned int mm_idx = 0;
2106 char **nargv = argv;
2107 int nargc = argc;
2108 int orig_db_level = db_level;
2109 int status;
2110
2111 if (! ISDB (DB_MAKEFILES))
2112 db_level = DB_NONE;
2113
2114 DB (DB_BASIC, (_("Updating makefiles....\n")));
2115
2116 /* Remove any makefiles we don't want to try to update.
2117 Also record the current modtimes so we can compare them later. */
2118 {
2119 register struct dep *d, *last;
2120 last = 0;
2121 d = read_makefiles;
2122 while (d != 0)
2123 {
2124 struct file *f = d->file;
2125 if (f->double_colon)
2126 for (f = f->double_colon; f != NULL; f = f->prev)
2127 {
2128 if (f->deps == 0 && f->cmds != 0)
2129 {
2130 /* This makefile is a :: target with commands, but
2131 no dependencies. So, it will always be remade.
2132 This might well cause an infinite loop, so don't
2133 try to remake it. (This will only happen if
2134 your makefiles are written exceptionally
2135 stupidly; but if you work for Athena, that's how
2136 you write your makefiles.) */
2137
2138 DB (DB_VERBOSE,
2139 (_("Makefile `%s' might loop; not remaking it.\n"),
2140 f->name));
2141
2142 if (last == 0)
2143 read_makefiles = d->next;
2144 else
2145 last->next = d->next;
2146
2147 /* Free the storage. */
2148 free_dep (d);
2149
2150 d = last == 0 ? read_makefiles : last->next;
2151
2152 break;
2153 }
2154 }
2155 if (f == NULL || !f->double_colon)
2156 {
2157 makefile_mtimes = xrealloc (makefile_mtimes,
2158 (mm_idx+1)
2159 * sizeof (FILE_TIMESTAMP));
2160 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2161 last = d;
2162 d = d->next;
2163 }
2164 }
2165 }
2166
2167 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2168 define_makeflags (1, 1);
2169
2170 rebuilding_makefiles = 1;
2171 status = update_goal_chain (read_makefiles);
2172 rebuilding_makefiles = 0;
2173
2174 switch (status)
2175 {
2176 case 1:
2177 /* The only way this can happen is if the user specified -q and asked
2178 * for one of the makefiles to be remade as a target on the command
2179 * line. Since we're not actually updating anything with -q we can
2180 * treat this as "did nothing".
2181 */
2182
2183 case -1:
2184 /* Did nothing. */
2185 break;
2186
2187 case 2:
2188 /* Failed to update. Figure out if we care. */
2189 {
2190 /* Nonzero if any makefile was successfully remade. */
2191 int any_remade = 0;
2192 /* Nonzero if any makefile we care about failed
2193 in updating or could not be found at all. */
2194 int any_failed = 0;
2195 unsigned int i;
2196 struct dep *d;
2197
2198 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2199 {
2200 /* Reset the considered flag; we may need to look at the file
2201 again to print an error. */
2202 d->file->considered = 0;
2203
2204 if (d->file->updated)
2205 {
2206 /* This makefile was updated. */
2207 if (d->file->update_status == 0)
2208 {
2209 /* It was successfully updated. */
2210 any_remade |= (file_mtime_no_search (d->file)
2211 != makefile_mtimes[i]);
2212 }
2213 else if (! (d->changed & RM_DONTCARE))
2214 {
2215 FILE_TIMESTAMP mtime;
2216 /* The update failed and this makefile was not
2217 from the MAKEFILES variable, so we care. */
2218 error (NILF, _("Failed to remake makefile `%s'."),
2219 d->file->name);
2220 mtime = file_mtime_no_search (d->file);
2221 any_remade |= (mtime != NONEXISTENT_MTIME
2222 && mtime != makefile_mtimes[i]);
2223 makefile_status = MAKE_FAILURE;
2224 }
2225 }
2226 else
2227 /* This makefile was not found at all. */
2228 if (! (d->changed & RM_DONTCARE))
2229 {
2230 /* This is a makefile we care about. See how much. */
2231 if (d->changed & RM_INCLUDED)
2232 /* An included makefile. We don't need
2233 to die, but we do want to complain. */
2234 error (NILF,
2235 _("Included makefile `%s' was not found."),
2236 dep_name (d));
2237 else
2238 {
2239 /* A normal makefile. We must die later. */
2240 error (NILF, _("Makefile `%s' was not found"),
2241 dep_name (d));
2242 any_failed = 1;
2243 }
2244 }
2245 }
2246 /* Reset this to empty so we get the right error message below. */
2247 read_makefiles = 0;
2248
2249 if (any_remade)
2250 goto re_exec;
2251 if (any_failed)
2252 die (2);
2253 break;
2254 }
2255
2256 case 0:
2257 re_exec:
2258 /* Updated successfully. Re-exec ourselves. */
2259
2260 remove_intermediates (0);
2261
2262 if (print_data_base_flag)
2263 print_data_base ();
2264
2265 log_working_directory (0);
2266
2267 clean_jobserver (0);
2268
2269 if (makefiles != 0)
2270 {
2271 /* These names might have changed. */
2272 int i, j = 0;
2273 for (i = 1; i < argc; ++i)
2274 if (strneq (argv[i], "-f", 2)) /* XXX */
2275 {
2276 char *p = &argv[i][2];
2277 if (*p == '\0')
2278 /* This cast is OK since we never modify argv. */
2279 argv[++i] = (char *) makefiles->list[j];
2280 else
2281 argv[i] = xstrdup (concat ("-f", makefiles->list[j], ""));
2282 ++j;
2283 }
2284 }
2285
2286 /* Add -o option for the stdin temporary file, if necessary. */
2287 if (stdin_nm)
2288 {
2289 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2290 memcpy (nargv, argv, argc * sizeof (char *));
2291 nargv[nargc++] = xstrdup (concat ("-o", stdin_nm, ""));
2292 nargv[nargc] = 0;
2293 }
2294
2295 if (directories != 0 && directories->idx > 0)
2296 {
2297 int bad = 1;
2298 if (directory_before_chdir != 0)
2299 {
2300 if (chdir (directory_before_chdir) < 0)
2301 perror_with_name ("chdir", "");
2302 else
2303 bad = 0;
2304 }
2305 if (bad)
2306 fatal (NILF, _("Couldn't change back to original directory."));
2307 }
2308
2309 ++restarts;
2310
2311 if (ISDB (DB_BASIC))
2312 {
2313 char **p;
2314 printf (_("Re-executing[%u]:"), restarts);
2315 for (p = nargv; *p != 0; ++p)
2316 printf (" %s", *p);
2317 putchar ('\n');
2318 }
2319
2320#ifndef _AMIGA
2321 {
2322 char **p;
2323 for (p = environ; *p != 0; ++p)
2324 {
2325 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2326 && (*p)[MAKELEVEL_LENGTH] == '=')
2327 {
2328 *p = alloca (40);
2329 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2330 }
2331 if (strneq (*p, "MAKE_RESTARTS=", 14))
2332 {
2333 *p = alloca (40);
2334 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2335 restarts = 0;
2336 }
2337 }
2338 }
2339#else /* AMIGA */
2340 {
2341 char buffer[256];
2342
2343 sprintf (buffer, "%u", makelevel);
2344 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2345
2346 sprintf (buffer, "%u", restarts);
2347 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2348 restarts = 0;
2349 }
2350#endif
2351
2352 /* If we didn't set the restarts variable yet, add it. */
2353 if (restarts)
2354 {
2355 char *b = alloca (40);
2356 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2357 putenv (b);
2358 }
2359
2360 fflush (stdout);
2361 fflush (stderr);
2362
2363 /* Close the dup'd jobserver pipe if we opened one. */
2364 if (job_rfd >= 0)
2365 close (job_rfd);
2366
2367#ifdef _AMIGA
2368 exec_command (nargv);
2369 exit (0);
2370#elif defined (__EMX__)
2371 {
2372 /* It is not possible to use execve() here because this
2373 would cause the parent process to be terminated with
2374 exit code 0 before the child process has been terminated.
2375 Therefore it may be the best solution simply to spawn the
2376 child process including all file handles and to wait for its
2377 termination. */
2378 int pid;
2379 int status;
2380 pid = child_execute_job (0, 1, nargv, environ);
2381
2382 /* is this loop really necessary? */
2383 do {
2384 pid = wait (&status);
2385 } while (pid <= 0);
2386 /* use the exit code of the child process */
2387 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2388 }
2389#else
2390 exec_command (nargv, environ);
2391#endif
2392 /* NOTREACHED */
2393
2394 default:
2395#define BOGUS_UPDATE_STATUS 0
2396 assert (BOGUS_UPDATE_STATUS);
2397 break;
2398 }
2399
2400 db_level = orig_db_level;
2401
2402 /* Free the makefile mtimes (if we allocated any). */
2403 if (makefile_mtimes)
2404 free (makefile_mtimes);
2405 }
2406
2407 /* Set up `MAKEFLAGS' again for the normal targets. */
2408 define_makeflags (1, 0);
2409
2410 /* Set always_make_flag if -B was given. */
2411 always_make_flag = always_make_set;
2412
2413 /* If restarts is set we haven't set up -W files yet, so do that now. */
2414 if (restarts && new_files != 0)
2415 {
2416 const char **p;
2417 for (p = new_files->list; *p != 0; ++p)
2418 {
2419 struct file *f = enter_file (*p);
2420 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2421 }
2422 }
2423
2424 /* If there is a temp file from reading a makefile from stdin, get rid of
2425 it now. */
2426 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2427 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2428
2429 {
2430 int status;
2431
2432 /* If there were no command-line goals, use the default. */
2433 if (goals == 0)
2434 {
2435 if (**default_goal_name != '\0')
2436 {
2437 if (default_goal_file == 0 ||
2438 strcmp (*default_goal_name, default_goal_file->name) != 0)
2439 {
2440 default_goal_file = lookup_file (*default_goal_name);
2441
2442 /* In case user set .DEFAULT_GOAL to a non-existent target
2443 name let's just enter this name into the table and let
2444 the standard logic sort it out. */
2445 if (default_goal_file == 0)
2446 {
2447 struct nameseq *ns;
2448 char *p = *default_goal_name;
2449
2450 ns = multi_glob (
2451 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2452 sizeof (struct nameseq));
2453
2454 /* .DEFAULT_GOAL should contain one target. */
2455 if (ns->next != 0)
2456 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2457
2458 default_goal_file = enter_file (strcache_add (ns->name));
2459
2460 ns->name = 0; /* It was reused by enter_file(). */
2461 free_ns_chain (ns);
2462 }
2463 }
2464
2465 goals = alloc_dep ();
2466 goals->file = default_goal_file;
2467 }
2468 }
2469 else
2470 lastgoal->next = 0;
2471
2472
2473 if (!goals)
2474 {
2475 if (read_makefiles == 0)
2476 fatal (NILF, _("No targets specified and no makefile found"));
2477
2478 fatal (NILF, _("No targets"));
2479 }
2480
2481 /* Update the goals. */
2482
2483 DB (DB_BASIC, (_("Updating goal targets....\n")));
2484
2485 switch (update_goal_chain (goals))
2486 {
2487 case -1:
2488 /* Nothing happened. */
2489 case 0:
2490 /* Updated successfully. */
2491 status = makefile_status;
2492 break;
2493 case 1:
2494 /* We are under -q and would run some commands. */
2495 status = MAKE_TROUBLE;
2496 break;
2497 case 2:
2498 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2499 but in VMS, there is only success and failure. */
2500 status = MAKE_FAILURE;
2501 break;
2502 default:
2503 abort ();
2504 }
2505
2506 /* If we detected some clock skew, generate one last warning */
2507 if (clock_skew_detected)
2508 error (NILF,
2509 _("warning: Clock skew detected. Your build may be incomplete."));
2510
2511 /* Exit. */
2512 die (status);
2513 }
2514
2515 /* NOTREACHED */
2516 return 0;
2517}
2518
2519
2520/* Parsing of arguments, decoding of switches. */
2521
2522static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2523static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2524 (sizeof (long_option_aliases) /
2525 sizeof (long_option_aliases[0]))];
2526
2527/* Fill in the string and vector for getopt. */
2528static void
2529init_switches (void)
2530{
2531 char *p;
2532 unsigned int c;
2533 unsigned int i;
2534
2535 if (options[0] != '\0')
2536 /* Already done. */
2537 return;
2538
2539 p = options;
2540
2541 /* Return switch and non-switch args in order, regardless of
2542 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2543 *p++ = '-';
2544
2545 for (i = 0; switches[i].c != '\0'; ++i)
2546 {
2547 long_options[i].name = (switches[i].long_name == 0 ? "" :
2548 switches[i].long_name);
2549 long_options[i].flag = 0;
2550 long_options[i].val = switches[i].c;
2551 if (short_option (switches[i].c))
2552 *p++ = switches[i].c;
2553 switch (switches[i].type)
2554 {
2555 case flag:
2556 case flag_off:
2557 case ignore:
2558 long_options[i].has_arg = no_argument;
2559 break;
2560
2561 case string:
2562 case filename:
2563 case positive_int:
2564 case floating:
2565 if (short_option (switches[i].c))
2566 *p++ = ':';
2567 if (switches[i].noarg_value != 0)
2568 {
2569 if (short_option (switches[i].c))
2570 *p++ = ':';
2571 long_options[i].has_arg = optional_argument;
2572 }
2573 else
2574 long_options[i].has_arg = required_argument;
2575 break;
2576 }
2577 }
2578 *p = '\0';
2579 for (c = 0; c < (sizeof (long_option_aliases) /
2580 sizeof (long_option_aliases[0]));
2581 ++c)
2582 long_options[i++] = long_option_aliases[c];
2583 long_options[i].name = 0;
2584}
2585
2586static void
2587handle_non_switch_argument (char *arg, int env)
2588{
2589 /* Non-option argument. It might be a variable definition. */
2590 struct variable *v;
2591 if (arg[0] == '-' && arg[1] == '\0')
2592 /* Ignore plain `-' for compatibility. */
2593 return;
2594 v = try_variable_definition (0, arg, o_command, 0);
2595 if (v != 0)
2596 {
2597 /* It is indeed a variable definition. If we don't already have this
2598 one, record a pointer to the variable for later use in
2599 define_makeflags. */
2600 struct command_variable *cv;
2601
2602 for (cv = command_variables; cv != 0; cv = cv->next)
2603 if (cv->variable == v)
2604 break;
2605
2606 if (! cv) {
2607 cv = xmalloc (sizeof (*cv));
2608 cv->variable = v;
2609 cv->next = command_variables;
2610 command_variables = cv;
2611 }
2612 }
2613 else if (! env)
2614 {
2615 /* Not an option or variable definition; it must be a goal
2616 target! Enter it as a file and add it to the dep chain of
2617 goals. */
2618 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2619 f->cmd_target = 1;
2620
2621 if (goals == 0)
2622 {
2623 goals = alloc_dep ();
2624 lastgoal = goals;
2625 }
2626 else
2627 {
2628 lastgoal->next = alloc_dep ();
2629 lastgoal = lastgoal->next;
2630 }
2631
2632 lastgoal->file = f;
2633
2634 {
2635 /* Add this target name to the MAKECMDGOALS variable. */
2636 struct variable *gv;
2637 const char *value;
2638
2639 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2640 if (gv == 0)
2641 value = f->name;
2642 else
2643 {
2644 /* Paste the old and new values together */
2645 unsigned int oldlen, newlen;
2646 char *vp;
2647
2648 oldlen = strlen (gv->value);
2649 newlen = strlen (f->name);
2650 vp = alloca (oldlen + 1 + newlen + 1);
2651 memcpy (vp, gv->value, oldlen);
2652 vp[oldlen] = ' ';
2653 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2654 value = vp;
2655 }
2656 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2657 }
2658 }
2659}
2660
2661/* Print a nice usage method. */
2662
2663static void
2664print_usage (int bad)
2665{
2666 const char *const *cpp;
2667 FILE *usageto;
2668
2669 if (print_version_flag)
2670 print_version ();
2671
2672 usageto = bad ? stderr : stdout;
2673
2674 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2675
2676 for (cpp = usage; *cpp; ++cpp)
2677 fputs (_(*cpp), usageto);
2678
2679#ifdef KMK
2680 if (!remote_description || *remote_description == '\0')
2681 printf (_("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
2682 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2683 else
2684 printf (_("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
2685 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2686#else /* !KMK */
2687 if (!remote_description || *remote_description == '\0')
2688 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2689 else
2690 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2691 make_host, remote_description);
2692#endif /* !KMK */
2693
2694 fprintf (usageto, _("Report bugs to <[email protected]>\n"));
2695}
2696
2697/* Decode switches from ARGC and ARGV.
2698 They came from the environment if ENV is nonzero. */
2699
2700static void
2701decode_switches (int argc, char **argv, int env)
2702{
2703 int bad = 0;
2704 register const struct command_switch *cs;
2705 register struct stringlist *sl;
2706 register int c;
2707
2708 /* getopt does most of the parsing for us.
2709 First, get its vectors set up. */
2710
2711 init_switches ();
2712
2713 /* Let getopt produce error messages for the command line,
2714 but not for options from the environment. */
2715 opterr = !env;
2716 /* Reset getopt's state. */
2717 optind = 0;
2718
2719 while (optind < argc)
2720 {
2721 /* Parse the next argument. */
2722 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2723 if (c == EOF)
2724 /* End of arguments, or "--" marker seen. */
2725 break;
2726 else if (c == 1)
2727 /* An argument not starting with a dash. */
2728 handle_non_switch_argument (optarg, env);
2729 else if (c == '?')
2730 /* Bad option. We will print a usage message and die later.
2731 But continue to parse the other options so the user can
2732 see all he did wrong. */
2733 bad = 1;
2734 else
2735 for (cs = switches; cs->c != '\0'; ++cs)
2736 if (cs->c == c)
2737 {
2738 /* Whether or not we will actually do anything with
2739 this switch. We test this individually inside the
2740 switch below rather than just once outside it, so that
2741 options which are to be ignored still consume args. */
2742 int doit = !env || cs->env;
2743
2744 switch (cs->type)
2745 {
2746 default:
2747 abort ();
2748
2749 case ignore:
2750 break;
2751
2752 case flag:
2753 case flag_off:
2754 if (doit)
2755 *(int *) cs->value_ptr = cs->type == flag;
2756 break;
2757
2758 case string:
2759 case filename:
2760 if (!doit)
2761 break;
2762
2763 if (optarg == 0)
2764 optarg = xstrdup (cs->noarg_value);
2765 else if (*optarg == '\0')
2766 {
2767 error (NILF, _("the `-%c' option requires a non-empty string argument"),
2768 cs->c);
2769 bad = 1;
2770 }
2771
2772 sl = *(struct stringlist **) cs->value_ptr;
2773 if (sl == 0)
2774 {
2775 sl = (struct stringlist *)
2776 xmalloc (sizeof (struct stringlist));
2777 sl->max = 5;
2778 sl->idx = 0;
2779 sl->list = xmalloc (5 * sizeof (char *));
2780 *(struct stringlist **) cs->value_ptr = sl;
2781 }
2782 else if (sl->idx == sl->max - 1)
2783 {
2784 sl->max += 5;
2785 sl->list = xrealloc ((void *)sl->list, /* bird */
2786 sl->max * sizeof (char *));
2787 }
2788 if (cs->type == filename)
2789 sl->list[sl->idx++] = expand_command_line_file (optarg);
2790 else
2791 sl->list[sl->idx++] = optarg;
2792 sl->list[sl->idx] = 0;
2793 break;
2794
2795 case positive_int:
2796 /* See if we have an option argument; if we do require that
2797 it's all digits, not something like "10foo". */
2798 if (optarg == 0 && argc > optind)
2799 {
2800 const char *cp;
2801 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2802 ;
2803 if (cp[0] == '\0')
2804 optarg = argv[optind++];
2805 }
2806
2807 if (!doit)
2808 break;
2809
2810 if (optarg != 0)
2811 {
2812 int i = atoi (optarg);
2813 const char *cp;
2814
2815 /* Yes, I realize we're repeating this in some cases. */
2816 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2817 ;
2818
2819 if (i < 1 || cp[0] != '\0')
2820 {
2821 error (NILF, _("the `-%c' option requires a positive integral argument"),
2822 cs->c);
2823 bad = 1;
2824 }
2825 else
2826 *(unsigned int *) cs->value_ptr = i;
2827 }
2828 else
2829 *(unsigned int *) cs->value_ptr
2830 = *(unsigned int *) cs->noarg_value;
2831 break;
2832
2833#ifndef NO_FLOAT
2834 case floating:
2835 if (optarg == 0 && optind < argc
2836 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2837 optarg = argv[optind++];
2838
2839 if (doit)
2840 *(double *) cs->value_ptr
2841 = (optarg != 0 ? atof (optarg)
2842 : *(double *) cs->noarg_value);
2843
2844 break;
2845#endif
2846 }
2847
2848 /* We've found the switch. Stop looking. */
2849 break;
2850 }
2851 }
2852
2853 /* There are no more options according to getting getopt, but there may
2854 be some arguments left. Since we have asked for non-option arguments
2855 to be returned in order, this only happens when there is a "--"
2856 argument to prevent later arguments from being options. */
2857 while (optind < argc)
2858 handle_non_switch_argument (argv[optind++], env);
2859
2860
2861 if (!env && (bad || print_usage_flag))
2862 {
2863 print_usage (bad);
2864 die (bad ? 2 : 0);
2865 }
2866}
2867
2868/* Decode switches from environment variable ENVAR (which is LEN chars long).
2869 We do this by chopping the value into a vector of words, prepending a
2870 dash to the first word if it lacks one, and passing the vector to
2871 decode_switches. */
2872
2873static void
2874decode_env_switches (char *envar, unsigned int len)
2875{
2876 char *varref = alloca (2 + len + 2);
2877 char *value, *p;
2878 int argc;
2879 char **argv;
2880
2881 /* Get the variable's value. */
2882 varref[0] = '$';
2883 varref[1] = '(';
2884 memcpy (&varref[2], envar, len);
2885 varref[2 + len] = ')';
2886 varref[2 + len + 1] = '\0';
2887 value = variable_expand (varref);
2888
2889 /* Skip whitespace, and check for an empty value. */
2890 value = next_token (value);
2891 len = strlen (value);
2892 if (len == 0)
2893 return;
2894
2895 /* Allocate a vector that is definitely big enough. */
2896 argv = alloca ((1 + len + 1) * sizeof (char *));
2897
2898 /* Allocate a buffer to copy the value into while we split it into words
2899 and unquote it. We must use permanent storage for this because
2900 decode_switches may store pointers into the passed argument words. */
2901 p = xmalloc (2 * len);
2902
2903 /* getopt will look at the arguments starting at ARGV[1].
2904 Prepend a spacer word. */
2905 argv[0] = 0;
2906 argc = 1;
2907 argv[argc] = p;
2908 while (*value != '\0')
2909 {
2910 if (*value == '\\' && value[1] != '\0')
2911 ++value; /* Skip the backslash. */
2912 else if (isblank ((unsigned char)*value))
2913 {
2914 /* End of the word. */
2915 *p++ = '\0';
2916 argv[++argc] = p;
2917 do
2918 ++value;
2919 while (isblank ((unsigned char)*value));
2920 continue;
2921 }
2922 *p++ = *value++;
2923 }
2924 *p = '\0';
2925 argv[++argc] = 0;
2926
2927 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2928 /* The first word doesn't start with a dash and isn't a variable
2929 definition. Add a dash and pass it along to decode_switches. We
2930 need permanent storage for this in case decode_switches saves
2931 pointers into the value. */
2932 argv[1] = xstrdup (concat ("-", argv[1], ""));
2933
2934 /* Parse those words. */
2935 decode_switches (argc, argv, 1);
2936}
2937
2938
2939/* Quote the string IN so that it will be interpreted as a single word with
2940 no magic by decode_env_switches; also double dollar signs to avoid
2941 variable expansion in make itself. Write the result into OUT, returning
2942 the address of the next character to be written.
2943 Allocating space for OUT twice the length of IN is always sufficient. */
2944
2945static char *
2946quote_for_env (char *out, const char *in)
2947{
2948 while (*in != '\0')
2949 {
2950 if (*in == '$')
2951 *out++ = '$';
2952 else if (isblank ((unsigned char)*in) || *in == '\\')
2953 *out++ = '\\';
2954 *out++ = *in++;
2955 }
2956
2957 return out;
2958}
2959
2960/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2961 command switches. Include options with args if ALL is nonzero.
2962 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2963
2964static void
2965define_makeflags (int all, int makefile)
2966{
2967 static const char ref[] = "$(MAKEOVERRIDES)";
2968 static const char posixref[] = "$(-*-command-variables-*-)";
2969 register const struct command_switch *cs;
2970 char *flagstring;
2971 register char *p;
2972 unsigned int words;
2973 struct variable *v;
2974
2975 /* We will construct a linked list of `struct flag's describing
2976 all the flags which need to go in MAKEFLAGS. Then, once we
2977 know how many there are and their lengths, we can put them all
2978 together in a string. */
2979
2980 struct flag
2981 {
2982 struct flag *next;
2983 const struct command_switch *cs;
2984 const char *arg;
2985 };
2986 struct flag *flags = 0;
2987 unsigned int flagslen = 0;
2988#define ADD_FLAG(ARG, LEN) \
2989 do { \
2990 struct flag *new = alloca (sizeof (struct flag)); \
2991 new->cs = cs; \
2992 new->arg = (ARG); \
2993 new->next = flags; \
2994 flags = new; \
2995 if (new->arg == 0) \
2996 ++flagslen; /* Just a single flag letter. */ \
2997 else \
2998 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2999 if (!short_option (cs->c)) \
3000 /* This switch has no single-letter version, so we use the long. */ \
3001 flagslen += 2 + strlen (cs->long_name); \
3002 } while (0)
3003
3004 for (cs = switches; cs->c != '\0'; ++cs)
3005 if (cs->toenv && (!makefile || !cs->no_makefile))
3006 switch (cs->type)
3007 {
3008 case ignore:
3009 break;
3010
3011 case flag:
3012 case flag_off:
3013 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3014 && (cs->default_value == 0
3015 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3016 ADD_FLAG (0, 0);
3017 break;
3018
3019 case positive_int:
3020 if (all)
3021 {
3022 if ((cs->default_value != 0
3023 && (*(unsigned int *) cs->value_ptr
3024 == *(unsigned int *) cs->default_value)))
3025 break;
3026 else if (cs->noarg_value != 0
3027 && (*(unsigned int *) cs->value_ptr ==
3028 *(unsigned int *) cs->noarg_value))
3029 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3030#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
3031 else if (cs->c == 'j')
3032 /* Special case for `-j'. */
3033 ADD_FLAG ("1", 1);
3034#endif
3035 else
3036 {
3037 char *buf = alloca (30);
3038 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3039 ADD_FLAG (buf, strlen (buf));
3040 }
3041 }
3042 break;
3043
3044#ifndef NO_FLOAT
3045 case floating:
3046 if (all)
3047 {
3048 if (cs->default_value != 0
3049 && (*(double *) cs->value_ptr
3050 == *(double *) cs->default_value))
3051 break;
3052 else if (cs->noarg_value != 0
3053 && (*(double *) cs->value_ptr
3054 == *(double *) cs->noarg_value))
3055 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3056 else
3057 {
3058 char *buf = alloca (100);
3059 sprintf (buf, "%g", *(double *) cs->value_ptr);
3060 ADD_FLAG (buf, strlen (buf));
3061 }
3062 }
3063 break;
3064#endif
3065
3066 case filename:
3067 case string:
3068 if (all)
3069 {
3070 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3071 if (sl != 0)
3072 {
3073 /* Add the elements in reverse order, because all the flags
3074 get reversed below; and the order matters for some
3075 switches (like -I). */
3076 unsigned int i = sl->idx;
3077 while (i-- > 0)
3078 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3079 }
3080 }
3081 break;
3082
3083 default:
3084 abort ();
3085 }
3086
3087 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3088
3089#undef ADD_FLAG
3090
3091 /* Construct the value in FLAGSTRING.
3092 We allocate enough space for a preceding dash and trailing null. */
3093 flagstring = alloca (1 + flagslen + 1);
3094 memset (flagstring, '\0', 1 + flagslen + 1);
3095 p = flagstring;
3096 words = 1;
3097 *p++ = '-';
3098 while (flags != 0)
3099 {
3100 /* Add the flag letter or name to the string. */
3101 if (short_option (flags->cs->c))
3102 *p++ = flags->cs->c;
3103 else
3104 {
3105 if (*p != '-')
3106 {
3107 *p++ = ' ';
3108 *p++ = '-';
3109 }
3110 *p++ = '-';
3111 strcpy (p, flags->cs->long_name);
3112 p += strlen (p);
3113 }
3114 if (flags->arg != 0)
3115 {
3116 /* A flag that takes an optional argument which in this case is
3117 omitted is specified by ARG being "". We must distinguish
3118 because a following flag appended without an intervening " -"
3119 is considered the arg for the first. */
3120 if (flags->arg[0] != '\0')
3121 {
3122 /* Add its argument too. */
3123 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3124 p = quote_for_env (p, flags->arg);
3125 }
3126 ++words;
3127 /* Write a following space and dash, for the next flag. */
3128 *p++ = ' ';
3129 *p++ = '-';
3130 }
3131 else if (!short_option (flags->cs->c))
3132 {
3133 ++words;
3134 /* Long options must each go in their own word,
3135 so we write the following space and dash. */
3136 *p++ = ' ';
3137 *p++ = '-';
3138 }
3139 flags = flags->next;
3140 }
3141
3142 /* Define MFLAGS before appending variable definitions. */
3143
3144 if (p == &flagstring[1])
3145 /* No flags. */
3146 flagstring[0] = '\0';
3147 else if (p[-1] == '-')
3148 {
3149 /* Kill the final space and dash. */
3150 p -= 2;
3151 *p = '\0';
3152 }
3153 else
3154 /* Terminate the string. */
3155 *p = '\0';
3156
3157 /* Since MFLAGS is not parsed for flags, there is no reason to
3158 override any makefile redefinition. */
3159 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3160
3161 if (all && command_variables != 0)
3162 {
3163 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3164 command-line variable definitions. */
3165
3166 if (p == &flagstring[1])
3167 /* No flags written, so elide the leading dash already written. */
3168 p = flagstring;
3169 else
3170 {
3171 /* Separate the variables from the switches with a "--" arg. */
3172 if (p[-1] != '-')
3173 {
3174 /* We did not already write a trailing " -". */
3175 *p++ = ' ';
3176 *p++ = '-';
3177 }
3178 /* There is a trailing " -"; fill it out to " -- ". */
3179 *p++ = '-';
3180 *p++ = ' ';
3181 }
3182
3183 /* Copy in the string. */
3184 if (posix_pedantic)
3185 {
3186 memcpy (p, posixref, sizeof posixref - 1);
3187 p += sizeof posixref - 1;
3188 }
3189 else
3190 {
3191 memcpy (p, ref, sizeof ref - 1);
3192 p += sizeof ref - 1;
3193 }
3194 }
3195 else if (p == &flagstring[1])
3196 {
3197 words = 0;
3198 --p;
3199 }
3200 else if (p[-1] == '-')
3201 /* Kill the final space and dash. */
3202 p -= 2;
3203 /* Terminate the string. */
3204 *p = '\0';
3205
3206 v = define_variable ("MAKEFLAGS", 9,
3207 /* If there are switches, omit the leading dash
3208 unless it is a single long option with two
3209 leading dashes. */
3210 &flagstring[(flagstring[0] == '-'
3211 && flagstring[1] != '-')
3212 ? 1 : 0],
3213 /* This used to use o_env, but that lost when a
3214 makefile defined MAKEFLAGS. Makefiles set
3215 MAKEFLAGS to add switches, but we still want
3216 to redefine its value with the full set of
3217 switches. Of course, an override or command
3218 definition will still take precedence. */
3219 o_file, 1);
3220 if (! all)
3221 /* The first time we are called, set MAKEFLAGS to always be exported.
3222 We should not do this again on the second call, because that is
3223 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3224 v->export = v_export;
3225}
3226
3227
3228/* Print version information. */
3229
3230static void
3231print_version (void)
3232{
3233 static int printed_version = 0;
3234
3235 char *precede = print_data_base_flag ? "# " : "";
3236
3237 if (printed_version)
3238 /* Do it only once. */
3239 return;
3240
3241 /* Print this untranslated. The coding standards recommend translating the
3242 (C) to the copyright symbol, but this string is going to change every
3243 year, and none of the rest of it should be translated (including the
3244 word "Copyright", so it hardly seems worth it. */
3245
3246#ifdef KMK
3247 printf ("%skBuild Make %d.%d.%d\n\
3248\n\
3249%sBased on GNU Make %s:\n\
3250%s Copyright (C) 2006 Free Software Foundation, Inc.\n\
3251\n\
3252%skBuild Modifications:\n\
3253%s Copyright (C) 2005-2006 Knut St. Osmundsen.\n\
3254\n\
3255%skmkbuiltin commands derived from *BSD sources:\n\
3256%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3257%s The Regents of the University of California. All rights reserved.\n\
3258%s Copyright (c) 1998 Todd C. Miller <[email protected]>\n\
3259%s\n",
3260 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR, KBUILD_VERSION_PATCH,
3261 precede, version_string,
3262 precede, precede, precede, precede, precede, precede, precede, precede);
3263#else
3264 printf ("%sGNU Make %s\n\
3265%sCopyright (C) 2006 Free Software Foundation, Inc.\n",
3266 precede, version_string, precede);
3267#endif
3268
3269 printf (_("%sThis is free software; see the source for copying conditions.\n\
3270%sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
3271%sPARTICULAR PURPOSE.\n"),
3272 precede, precede, precede);
3273
3274#ifdef KMK
3275# ifdef PATH_KBUILD
3276 printf (_("%s\n\
3277%sPATH_KBUILD: '%s' (default '%s')\n\
3278%sPATH_KBUILD_BIN: '%s' (default '%s')\n"),
3279 precede,
3280 precede, get_path_kbuild(), PATH_KBUILD
3281 precede, get_path_kbuild_bin(), PATH_KBUILD_BIN);
3282# else /* !PATH_KBUILD */
3283 printf (_("%s\n\
3284%sPATH_KBUILD: '%s'\n\
3285%sPATH_KBUILD_BIN: '%s'\n"),
3286 precede,
3287 precede, get_path_kbuild(),
3288 precede, get_path_kbuild_bin());
3289# endif /* !PATH_KBUILD */
3290 if (!remote_description || *remote_description == '\0')
3291 printf (_("\n%sThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3292 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3293 else
3294 printf (_("\n%sThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3295 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3296#else
3297 if (!remote_description || *remote_description == '\0')
3298 printf (_("\n%sThis program built for %s\n"), precede, make_host);
3299 else
3300 printf (_("\n%sThis program built for %s (%s)\n"),
3301 precede, make_host, remote_description);
3302#endif
3303
3304 printed_version = 1;
3305
3306 /* Flush stdout so the user doesn't have to wait to see the
3307 version information while things are thought about. */
3308 fflush (stdout);
3309}
3310
3311/* Print a bunch of information about this and that. */
3312
3313static void
3314print_data_base ()
3315{
3316 time_t when;
3317
3318 when = time ((time_t *) 0);
3319 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3320
3321 print_variable_data_base ();
3322 print_dir_data_base ();
3323 print_rule_data_base ();
3324 print_file_data_base ();
3325 print_vpath_data_base ();
3326 strcache_print_stats ("#");
3327
3328 when = time ((time_t *) 0);
3329 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3330}
3331
3332static void
3333clean_jobserver (int status)
3334{
3335 char token = '+';
3336
3337 /* Sanity: have we written all our jobserver tokens back? If our
3338 exit status is 2 that means some kind of syntax error; we might not
3339 have written all our tokens so do that now. If tokens are left
3340 after any other error code, that's bad. */
3341
3342 if (job_fds[0] != -1 && jobserver_tokens)
3343 {
3344 if (status != 2)
3345 error (NILF,
3346 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3347 jobserver_tokens);
3348 else
3349 while (jobserver_tokens--)
3350 {
3351 int r;
3352
3353 EINTRLOOP (r, write (job_fds[1], &token, 1));
3354 if (r != 1)
3355 perror_with_name ("write", "");
3356 }
3357 }
3358
3359
3360 /* Sanity: If we're the master, were all the tokens written back? */
3361
3362 if (master_job_slots)
3363 {
3364 /* We didn't write one for ourself, so start at 1. */
3365 unsigned int tcnt = 1;
3366
3367 /* Close the write side, so the read() won't hang. */
3368 close (job_fds[1]);
3369
3370 while (read (job_fds[0], &token, 1) == 1)
3371 ++tcnt;
3372
3373 if (tcnt != master_job_slots)
3374 error (NILF,
3375 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3376 tcnt, master_job_slots);
3377
3378 close (job_fds[0]);
3379 }
3380}
3381
3382
3383/* Exit with STATUS, cleaning up as necessary. */
3384
3385void
3386die (int status)
3387{
3388 static char dying = 0;
3389
3390 if (!dying)
3391 {
3392 int err;
3393
3394 dying = 1;
3395
3396 if (print_version_flag)
3397 print_version ();
3398
3399 /* Wait for children to die. */
3400 err = (status != 0);
3401 while (job_slots_used > 0)
3402 reap_children (1, err);
3403
3404 /* Let the remote job module clean up its state. */
3405 remote_cleanup ();
3406
3407 /* Remove the intermediate files. */
3408 remove_intermediates (0);
3409
3410 if (print_data_base_flag)
3411 print_data_base ();
3412
3413 verify_file_data_base ();
3414
3415 clean_jobserver (status);
3416
3417 /* Try to move back to the original directory. This is essential on
3418 MS-DOS (where there is really only one process), and on Unix it
3419 puts core files in the original directory instead of the -C
3420 directory. Must wait until after remove_intermediates(), or unlinks
3421 of relative pathnames fail. */
3422 if (directory_before_chdir != 0)
3423 chdir (directory_before_chdir);
3424
3425 log_working_directory (0);
3426 }
3427
3428 exit (status);
3429}
3430
3431
3432/* Write a message indicating that we've just entered or
3433 left (according to ENTERING) the current directory. */
3434
3435void
3436log_working_directory (int entering)
3437{
3438 static int entered = 0;
3439
3440 /* Print nothing without the flag. Don't print the entering message
3441 again if we already have. Don't print the leaving message if we
3442 haven't printed the entering message. */
3443 if (! print_directory_flag || entering == entered)
3444 return;
3445
3446 entered = entering;
3447
3448 if (print_data_base_flag)
3449 fputs ("# ", stdout);
3450
3451 /* Use entire sentences to give the translators a fighting chance. */
3452
3453 if (makelevel == 0)
3454 if (starting_directory == 0)
3455 if (entering)
3456 printf (_("%s: Entering an unknown directory\n"), program);
3457 else
3458 printf (_("%s: Leaving an unknown directory\n"), program);
3459 else
3460 if (entering)
3461 printf (_("%s: Entering directory `%s'\n"),
3462 program, starting_directory);
3463 else
3464 printf (_("%s: Leaving directory `%s'\n"),
3465 program, starting_directory);
3466 else
3467 if (starting_directory == 0)
3468 if (entering)
3469 printf (_("%s[%u]: Entering an unknown directory\n"),
3470 program, makelevel);
3471 else
3472 printf (_("%s[%u]: Leaving an unknown directory\n"),
3473 program, makelevel);
3474 else
3475 if (entering)
3476 printf (_("%s[%u]: Entering directory `%s'\n"),
3477 program, makelevel, starting_directory);
3478 else
3479 printf (_("%s[%u]: Leaving directory `%s'\n"),
3480 program, makelevel, starting_directory);
3481
3482 /* Flush stdout to be sure this comes before any stderr output. */
3483 fflush (stdout);
3484}
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