VirtualBox

source: kBuild/vendor/gnumake/2005-05-16/main.c@ 1989

Last change on this file since 1989 was 280, checked in by bird, 20 years ago

Current make snaphot, 2005-05-16.

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

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