VirtualBox

source: kBuild/trunk/src/gmake/main.c@ 783

最後變更 在這個檔案從783是 783,由 bird 提交於 18 年 前

Makefile.kup - if found it'll automatically take up you one directory. (Makefile.kmk overrides Makefile.kup.)

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

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