VirtualBox

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

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

Added --pretty-command-printing for simplifying makefile debugging.

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

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