VirtualBox

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

Last change on this file since 506 was 506, checked in by bird, 19 years ago

kmk version message with correct copyright stuff and build timestamp.

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

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