VirtualBox

source: kBuild/vendor/gnumake/current/main.c@ 3387

Last change on this file since 3387 was 3138, checked in by bird, 6 years ago

Imported make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6) from https://git.savannah.gnu.org/git/make.git.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use