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