Debian Codegraph @

src/main.c

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