VirtualBox

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

Last change on this file since 765 was 765, checked in by bird, 18 years ago

New predefined variable 'KMK', similar to 'MAKE' only less likely to be defined in the environment.

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