VirtualBox

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

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

msvcrt build.

  • Property svn:eol-style set to native
File size: 96.9 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#if !defined(HAVE_UNISTD_H) && !defined(_MSC_VER)
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
930/* bird: */
931#ifdef CONFIG_NEW_WIN32_CTRL_EVENT
932#include <process.h>
933static UINT g_tidMainThread = 0;
934static int g_sigPending = 0; /* lazy bird */
935
936static __declspec(naked) void dispatch_stub(void)
937{
938 __asm {
939 pushfd
940 pushad
941 cld
942 }
943 fflush(stdout);
944 /*fprintf(stderr, "dbg: raising %s on the main thread (%d)\n", g_sigPending == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());*/
945 raise(g_sigPending);
946 __asm {
947 popad
948 popfd
949 ret
950 }
951}
952
953static BOOL WINAPI ctrl_event(DWORD CtrlType)
954{
955 int sig = (CtrlType == CTRL_C_EVENT) ? SIGINT : SIGBREAK;
956 HANDLE hThread;
957 CONTEXT Ctx;
958
959 /* open the main thread and suspend it. */
960 hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, g_tidMainThread);
961 SuspendThread(hThread);
962
963 /* Get the thread context and */
964 memset(&Ctx, 0, sizeof(Ctx));
965 Ctx.ContextFlags = CONTEXT_FULL;
966 GetThreadContext(hThread, &Ctx);
967
968 /* If we've got a valid Esp, dispatch it on the main thread
969 otherwise raise the signal in the ctrl-event thread (this). */
970 if (Ctx.Esp >= 0x1000)
971 {
972 ((uintptr_t *)Ctx.Esp)[-1] = Ctx.Eip;
973 Ctx.Esp -= sizeof(uintptr_t);
974 Ctx.Eip = (uintptr_t)&dispatch_stub;
975
976 SetThreadContext(hThread, &Ctx);
977 g_sigPending = sig;
978 ResumeThread(hThread);
979 CloseHandle(hThread);
980 }
981 else
982 {
983 fprintf(stderr, "dbg: raising %s on the ctrl-event thread (%d)\n", sig == SIGINT ? "SIGINT" : "SIGBREAK", _getpid());
984 raise(sig);
985 ResumeThread(hThread);
986 CloseHandle(hThread);
987 exit(130);
988 }
989
990 Sleep(1);
991 return TRUE;
992}
993#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
994
995#endif /* WINDOWS32 */
996
997#ifdef __MSDOS__
998
999static void
1000msdos_return_to_initial_directory (void)
1001{
1002 if (directory_before_chdir)
1003 chdir (directory_before_chdir);
1004}
1005#endif
1006
1007#ifndef _MSC_VER
1008extern char *mktemp PARAMS ((char *template));
1009#endif
1010extern int mkstemp PARAMS ((char *template));
1011
1012FILE *
1013open_tmpfile(char **name, const char *template)
1014{
1015#ifdef HAVE_FDOPEN
1016 int fd;
1017#endif
1018
1019#if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
1020# define TEMPLATE_LEN strlen (template)
1021#else
1022# define TEMPLATE_LEN L_tmpnam
1023#endif
1024 *name = xmalloc (TEMPLATE_LEN + 1);
1025 strcpy (*name, template);
1026
1027#if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
1028 /* It's safest to use mkstemp(), if we can. */
1029 fd = mkstemp (*name);
1030 if (fd == -1)
1031 return 0;
1032 return fdopen (fd, "w");
1033#else
1034# ifdef HAVE_MKTEMP
1035 (void) mktemp (*name);
1036# else
1037 (void) tmpnam (*name);
1038# endif
1039
1040# ifdef HAVE_FDOPEN
1041 /* Can't use mkstemp(), but guard against a race condition. */
1042 fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
1043 if (fd == -1)
1044 return 0;
1045 return fdopen (fd, "w");
1046# else
1047 /* Not secure, but what can we do? */
1048 return fopen (*name, "w");
1049# endif
1050#endif
1051}
1052
1053
1054#ifdef _AMIGA
1055int
1056main (int argc, char **argv)
1057#else
1058int
1059main (int argc, char **argv, char **envp)
1060#endif
1061{
1062 static char *stdin_nm = 0;
1063 struct file *f;
1064 int i;
1065 int makefile_status = MAKE_SUCCESS;
1066 char **p;
1067 struct dep *read_makefiles;
1068 PATH_VAR (current_directory);
1069 unsigned int restarts = 0;
1070#ifdef WINDOWS32
1071 char *unix_path = NULL;
1072 char *windows32_path = NULL;
1073
1074 SetUnhandledExceptionFilter(handle_runtime_exceptions);
1075
1076 /* start off assuming we have no shell */
1077 unixy_shell = 0;
1078 no_default_sh_exe = 1;
1079#endif
1080
1081#ifdef SET_STACK_SIZE
1082 /* Get rid of any avoidable limit on stack size. */
1083 {
1084 struct rlimit rlim;
1085
1086 /* Set the stack limit huge so that alloca does not fail. */
1087 if (getrlimit (RLIMIT_STACK, &rlim) == 0)
1088 {
1089 rlim.rlim_cur = rlim.rlim_max;
1090 setrlimit (RLIMIT_STACK, &rlim);
1091 }
1092 }
1093#endif
1094
1095#ifdef HAVE_ATEXIT
1096 atexit (close_stdout);
1097#endif
1098
1099 /* Needed for OS/2 */
1100 initialize_main(&argc, &argv);
1101
1102 default_goal_file = 0;
1103 reading_file = 0;
1104
1105#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1106 /* Request the most powerful version of `system', to
1107 make up for the dumb default shell. */
1108 __system_flags = (__system_redirect
1109 | __system_use_shell
1110 | __system_allow_multiple_cmds
1111 | __system_allow_long_cmds
1112 | __system_handle_null_commands
1113 | __system_emulate_chdir);
1114
1115#endif
1116
1117 /* Set up gettext/internationalization support. */
1118 setlocale (LC_ALL, "");
1119 bindtextdomain (PACKAGE, LOCALEDIR);
1120 textdomain (PACKAGE);
1121
1122#ifdef POSIX
1123 sigemptyset (&fatal_signal_set);
1124#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1125#else
1126#ifdef HAVE_SIGSETMASK
1127 fatal_signal_mask = 0;
1128#define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1129#else
1130#define ADD_SIG(sig)
1131#endif
1132#endif
1133
1134#define FATAL_SIG(sig) \
1135 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1136 bsd_signal (sig, SIG_IGN); \
1137 else \
1138 ADD_SIG (sig);
1139
1140#ifdef SIGHUP
1141 FATAL_SIG (SIGHUP);
1142#endif
1143#ifdef SIGQUIT
1144 FATAL_SIG (SIGQUIT);
1145#endif
1146 FATAL_SIG (SIGINT);
1147 FATAL_SIG (SIGTERM);
1148
1149#ifdef __MSDOS__
1150 /* Windows 9X delivers FP exceptions in child programs to their
1151 parent! We don't want Make to die when a child divides by zero,
1152 so we work around that lossage by catching SIGFPE. */
1153 FATAL_SIG (SIGFPE);
1154#endif
1155
1156#ifdef SIGDANGER
1157 FATAL_SIG (SIGDANGER);
1158#endif
1159#ifdef SIGXCPU
1160 FATAL_SIG (SIGXCPU);
1161#endif
1162#ifdef SIGXFSZ
1163 FATAL_SIG (SIGXFSZ);
1164#endif
1165
1166#ifdef CONFIG_NEW_WIN32_CTRL_EVENT
1167 /* bird: dispatch signals in our own way to try avoid deadlocks. */
1168 g_tidMainThread = GetCurrentThreadId ();
1169 SetConsoleCtrlHandler (ctrl_event, TRUE);
1170#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
1171
1172#undef FATAL_SIG
1173
1174 /* Do not ignore the child-death signal. This must be done before
1175 any children could possibly be created; otherwise, the wait
1176 functions won't work on systems with the SVR4 ECHILD brain
1177 damage, if our invoker is ignoring this signal. */
1178
1179#ifdef HAVE_WAIT_NOHANG
1180# if defined SIGCHLD
1181 (void) bsd_signal (SIGCHLD, SIG_DFL);
1182# endif
1183# if defined SIGCLD && SIGCLD != SIGCHLD
1184 (void) bsd_signal (SIGCLD, SIG_DFL);
1185# endif
1186#endif
1187
1188 /* Make sure stdout is line-buffered. */
1189
1190#ifdef HAVE_SETVBUF
1191# ifdef SETVBUF_REVERSED
1192 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
1193# else /* setvbuf not reversed. */
1194 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
1195 setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
1196# endif /* setvbuf reversed. */
1197#elif HAVE_SETLINEBUF
1198 setlinebuf (stdout);
1199#endif /* setlinebuf missing. */
1200
1201 /* Figure out where this program lives. */
1202
1203 if (argv[0] == 0)
1204 argv[0] = "";
1205 if (argv[0][0] == '\0')
1206 program = "make";
1207 else
1208 {
1209#ifdef VMS
1210 program = strrchr (argv[0], ']');
1211#else
1212 program = strrchr (argv[0], '/');
1213#endif
1214#if defined(__MSDOS__) || defined(__EMX__)
1215 if (program == 0)
1216 program = strrchr (argv[0], '\\');
1217 else
1218 {
1219 /* Some weird environments might pass us argv[0] with
1220 both kinds of slashes; we must find the rightmost. */
1221 char *p = strrchr (argv[0], '\\');
1222 if (p && p > program)
1223 program = p;
1224 }
1225 if (program == 0 && argv[0][1] == ':')
1226 program = argv[0] + 1;
1227#endif
1228#ifdef WINDOWS32
1229 if (program == 0)
1230 {
1231 /* Extract program from full path */
1232 int argv0_len;
1233 program = strrchr (argv[0], '\\');
1234 if (program)
1235 {
1236 argv0_len = strlen(program);
1237 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1238 /* Remove .exe extension */
1239 program[argv0_len - 4] = '\0';
1240 }
1241 }
1242#endif
1243 if (program == 0)
1244 program = argv[0];
1245 else
1246 ++program;
1247 }
1248
1249 /* Set up to access user data (files). */
1250 user_access ();
1251
1252 initialize_global_hash_tables ();
1253
1254 /* Figure out where we are. */
1255
1256#ifdef WINDOWS32
1257 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1258#else
1259 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1260#endif
1261 {
1262#ifdef HAVE_GETCWD
1263 perror_with_name ("getcwd", "");
1264#else
1265 error (NILF, "getwd: %s", current_directory);
1266#endif
1267 current_directory[0] = '\0';
1268 directory_before_chdir = 0;
1269 }
1270 else
1271 directory_before_chdir = xstrdup (current_directory);
1272#ifdef __MSDOS__
1273 /* Make sure we will return to the initial directory, come what may. */
1274 atexit (msdos_return_to_initial_directory);
1275#endif
1276
1277 /* Initialize the special variables. */
1278 define_variable (".VARIABLES", 10, "", o_default, 0)->special = 1;
1279 /* define_variable (".TARGETS", 8, "", o_default, 0)->special = 1; */
1280
1281 /* Set up .FEATURES */
1282 define_variable (".FEATURES", 9,
1283 "target-specific order-only second-expansion else-if",
1284 o_default, 0);
1285#ifndef NO_ARCHIVES
1286 do_variable_definition (NILF, ".FEATURES", "archives",
1287 o_default, f_append, 0);
1288#endif
1289#ifdef MAKE_JOBSERVER
1290 do_variable_definition (NILF, ".FEATURES", "jobserver",
1291 o_default, f_append, 0);
1292#endif
1293#ifdef MAKE_SYMLINKS
1294 do_variable_definition (NILF, ".FEATURES", "check-symlink",
1295 o_default, f_append, 0);
1296#endif
1297
1298 /* Read in variables from the environment. It is important that this be
1299 done before $(MAKE) is figured out so its definitions will not be
1300 from the environment. */
1301
1302#ifndef _AMIGA
1303 for (i = 0; envp[i] != 0; ++i)
1304 {
1305 int do_not_define = 0;
1306 char *ep = envp[i];
1307
1308 while (*ep != '\0' && *ep != '=')
1309 ++ep;
1310#ifdef WINDOWS32
1311 if (!unix_path && strneq(envp[i], "PATH=", 5))
1312 unix_path = ep+1;
1313 else if (!strnicmp(envp[i], "Path=", 5)) {
1314 do_not_define = 1; /* it gets defined after loop exits */
1315 if (!windows32_path)
1316 windows32_path = ep+1;
1317 }
1318#endif
1319 /* The result of pointer arithmetic is cast to unsigned int for
1320 machines where ptrdiff_t is a different size that doesn't widen
1321 the same. */
1322 if (!do_not_define)
1323 {
1324 struct variable *v;
1325
1326 v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
1327 ep + 1, o_env, 1);
1328 /* Force exportation of every variable culled from the environment.
1329 We used to rely on target_environment's v_default code to do this.
1330 But that does not work for the case where an environment variable
1331 is redefined in a makefile with `override'; it should then still
1332 be exported, because it was originally in the environment. */
1333 v->export = v_export;
1334
1335 /* Another wrinkle is that POSIX says the value of SHELL set in the
1336 makefile won't change the value of SHELL given to subprocesses */
1337 if (streq (v->name, "SHELL"))
1338 {
1339#ifndef __MSDOS__
1340 v->export = v_noexport;
1341#endif
1342 shell_var.name = "SHELL";
1343 shell_var.value = xstrdup (ep + 1);
1344 }
1345
1346 /* If MAKE_RESTARTS is set, remember it but don't export it. */
1347 if (streq (v->name, "MAKE_RESTARTS"))
1348 {
1349 v->export = v_noexport;
1350 restarts = (unsigned int) atoi (ep + 1);
1351 }
1352 }
1353 }
1354#ifdef WINDOWS32
1355 /* If we didn't find a correctly spelled PATH we define PATH as
1356 * either the first mispelled value or an empty string
1357 */
1358 if (!unix_path)
1359 define_variable("PATH", 4,
1360 windows32_path ? windows32_path : "",
1361 o_env, 1)->export = v_export;
1362#endif
1363#else /* For Amiga, read the ENV: device, ignoring all dirs */
1364 {
1365 BPTR env, file, old;
1366 char buffer[1024];
1367 int len;
1368 __aligned struct FileInfoBlock fib;
1369
1370 env = Lock ("ENV:", ACCESS_READ);
1371 if (env)
1372 {
1373 old = CurrentDir (DupLock(env));
1374 Examine (env, &fib);
1375
1376 while (ExNext (env, &fib))
1377 {
1378 if (fib.fib_DirEntryType < 0) /* File */
1379 {
1380 /* Define an empty variable. It will be filled in
1381 variable_lookup(). Makes startup quite a bit
1382 faster. */
1383 define_variable (fib.fib_FileName,
1384 strlen (fib.fib_FileName),
1385 "", o_env, 1)->export = v_export;
1386 }
1387 }
1388 UnLock (env);
1389 UnLock(CurrentDir(old));
1390 }
1391 }
1392#endif
1393
1394 /* Decode the switches. */
1395
1396 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1397#if 0
1398 /* People write things like:
1399 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1400 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1401 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1402#endif
1403 decode_switches (argc, argv, 0);
1404#ifdef WINDOWS32
1405 if (suspend_flag) {
1406 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1407 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1408 Sleep(30 * 1000);
1409 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1410 }
1411#endif
1412
1413 decode_debug_flags ();
1414
1415#ifdef KMK
1416 set_make_priority ();
1417#endif
1418
1419 /* Set always_make_flag if -B was given and we've not restarted already. */
1420 always_make_flag = always_make_set && (restarts == 0);
1421
1422 /* Print version information. */
1423 if (print_version_flag || print_data_base_flag || db_level)
1424 {
1425 print_version ();
1426
1427 /* `make --version' is supposed to just print the version and exit. */
1428 if (print_version_flag)
1429 die (0);
1430 }
1431
1432#ifndef VMS
1433 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1434 (If it is a relative pathname with a slash, prepend our directory name
1435 so the result will run the same program regardless of the current dir.
1436 If it is a name with no slash, we can only hope that PATH did not
1437 find it in the current directory.) */
1438#ifdef WINDOWS32
1439 /*
1440 * Convert from backslashes to forward slashes for
1441 * programs like sh which don't like them. Shouldn't
1442 * matter if the path is one way or the other for
1443 * CreateProcess().
1444 */
1445 if (strpbrk(argv[0], "/:\\") ||
1446 strstr(argv[0], "..") ||
1447 strneq(argv[0], "//", 2))
1448 argv[0] = xstrdup(w32ify(argv[0],1));
1449#else /* WINDOWS32 */
1450#if defined (__MSDOS__) || defined (__EMX__)
1451 if (strchr (argv[0], '\\'))
1452 {
1453 char *p;
1454
1455 argv[0] = xstrdup (argv[0]);
1456 for (p = argv[0]; *p; p++)
1457 if (*p == '\\')
1458 *p = '/';
1459 }
1460 /* If argv[0] is not in absolute form, prepend the current
1461 directory. This can happen when Make is invoked by another DJGPP
1462 program that uses a non-absolute name. */
1463 if (current_directory[0] != '\0'
1464 && argv[0] != 0
1465 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1466#ifdef __EMX__
1467 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1468 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1469# endif
1470 )
1471 argv[0] = concat (current_directory, "/", argv[0]);
1472#else /* !__MSDOS__ */
1473 if (current_directory[0] != '\0'
1474 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0)
1475 argv[0] = concat (current_directory, "/", argv[0]);
1476#endif /* !__MSDOS__ */
1477#endif /* WINDOWS32 */
1478#endif
1479
1480 /* The extra indirection through $(MAKE_COMMAND) is done
1481 for hysterical raisins. */
1482 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1483 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1484#ifdef KMK
1485 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1486#endif
1487
1488 if (command_variables != 0)
1489 {
1490 struct command_variable *cv;
1491 struct variable *v;
1492 unsigned int len = 0;
1493 char *value, *p;
1494
1495 /* Figure out how much space will be taken up by the command-line
1496 variable definitions. */
1497 for (cv = command_variables; cv != 0; cv = cv->next)
1498 {
1499 v = cv->variable;
1500 len += 2 * strlen (v->name);
1501 if (! v->recursive)
1502 ++len;
1503 ++len;
1504 len += 2 * strlen (v->value);
1505 ++len;
1506 }
1507
1508 /* Now allocate a buffer big enough and fill it. */
1509 p = value = (char *) alloca (len);
1510 for (cv = command_variables; cv != 0; cv = cv->next)
1511 {
1512 v = cv->variable;
1513 p = quote_for_env (p, v->name);
1514 if (! v->recursive)
1515 *p++ = ':';
1516 *p++ = '=';
1517 p = quote_for_env (p, v->value);
1518 *p++ = ' ';
1519 }
1520 p[-1] = '\0'; /* Kill the final space and terminate. */
1521
1522 /* Define an unchangeable variable with a name that no POSIX.2
1523 makefile could validly use for its own variable. */
1524 (void) define_variable ("-*-command-variables-*-", 23,
1525 value, o_automatic, 0);
1526
1527 /* Define the variable; this will not override any user definition.
1528 Normally a reference to this variable is written into the value of
1529 MAKEFLAGS, allowing the user to override this value to affect the
1530 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1531 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1532 a reference to this hidden variable is written instead. */
1533 (void) define_variable ("MAKEOVERRIDES", 13,
1534 "${-*-command-variables-*-}", o_env, 1);
1535 }
1536
1537#ifdef KMK
1538 /* If there wasn't any -C or -f flags, check for Makefile.kup and
1539 insert a fake -C argument.
1540 Makefile.kmk overrides Makefile.kup but not plain Makefile. */
1541 if (makefiles == 0 && directories == 0)
1542 {
1543 struct stat st;
1544 if (( stat ("Makefile.kup", &st) == 0
1545 && S_ISREG (st.st_mode) )
1546 || ( stat ("makefile.kup", &st) == 0
1547 && S_ISREG (st.st_mode) )
1548 && stat ("Makefile.kmk", &st) < 0
1549 && stat ("makefile.kmk", &st) < 0)
1550 {
1551 static char fake_path[3*16 + 32] = "..";
1552 static char *fake_list[2] = { &fake_path[0], NULL };
1553 struct stringlist fake_directories = { &fake_list[0], 1, 0 };
1554
1555 char *cur = &fake_path[2];
1556 int up_levels = 1;
1557
1558 while (up_levels < 16)
1559 {
1560 /* File with higher precedence.s */
1561 strcpy (cur, "/Makefile.kmk");
1562 if (stat (fake_path, &st) == 0)
1563 break;
1564 strcpy (cur, "/makefile.kmk");
1565 if (stat (fake_path, &st) == 0)
1566 break;
1567
1568 /* the .kup files */
1569 strcpy (cur, "/Makefile.kup");
1570 if ( stat (fake_path, &st) != 0
1571 || !S_ISREG (st.st_mode))
1572 {
1573 strcpy (cur, "/makefile.kup");
1574 if ( stat (fake_path, &st) != 0
1575 || !S_ISREG (st.st_mode))
1576 break;
1577 }
1578
1579 /* ok */
1580 strcpy (cur, "/..");
1581 cur += 3;
1582 up_levels++;
1583 }
1584
1585 if (up_levels >= 16)
1586 fatal (NILF, _("Makefile.kup recursion is too deep."));
1587
1588 *cur = '\0';
1589 directories = &fake_directories;
1590 }
1591 }
1592#endif
1593
1594 /* If there were -C flags, move ourselves about. */
1595 if (directories != 0)
1596 for (i = 0; directories->list[i] != 0; ++i)
1597 {
1598 char *dir = directories->list[i];
1599 char *expanded = 0;
1600 if (dir[0] == '~')
1601 {
1602 expanded = tilde_expand (dir);
1603 if (expanded != 0)
1604 dir = expanded;
1605 }
1606#ifdef WINDOWS32
1607 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1608 But allow -C/ just in case someone wants that. */
1609 {
1610 char *p = dir + strlen (dir) - 1;
1611 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1612 --p;
1613 p[1] = '\0';
1614 }
1615#endif
1616 if (chdir (dir) < 0)
1617 pfatal_with_name (dir);
1618 if (expanded)
1619 free (expanded);
1620 }
1621
1622#ifdef WINDOWS32
1623 /*
1624 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1625 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1626 *
1627 * The functions in dir.c can incorrectly cache information for "."
1628 * before we have changed directory and this can cause file
1629 * lookups to fail because the current directory (.) was pointing
1630 * at the wrong place when it was first evaluated.
1631 */
1632 no_default_sh_exe = !find_and_set_default_shell(NULL);
1633
1634#endif /* WINDOWS32 */
1635 /* Figure out the level of recursion. */
1636 {
1637 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1638 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1639 makelevel = (unsigned int) atoi (v->value);
1640 else
1641 makelevel = 0;
1642 }
1643
1644 /* Except under -s, always do -w in sub-makes and under -C. */
1645 if (!silent_flag && (directories != 0 || makelevel > 0))
1646 print_directory_flag = 1;
1647
1648 /* Let the user disable that with --no-print-directory. */
1649 if (inhibit_print_directory_flag)
1650 print_directory_flag = 0;
1651
1652 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1653 if (no_builtin_variables_flag)
1654 no_builtin_rules_flag = 1;
1655
1656 /* Construct the list of include directories to search. */
1657
1658 construct_include_path (include_directories == 0 ? (char **) 0
1659 : include_directories->list);
1660
1661 /* Figure out where we are now, after chdir'ing. */
1662 if (directories == 0)
1663 /* We didn't move, so we're still in the same place. */
1664 starting_directory = current_directory;
1665 else
1666 {
1667#ifdef WINDOWS32
1668 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1669#else
1670 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1671#endif
1672 {
1673#ifdef HAVE_GETCWD
1674 perror_with_name ("getcwd", "");
1675#else
1676 error (NILF, "getwd: %s", current_directory);
1677#endif
1678 starting_directory = 0;
1679 }
1680 else
1681 starting_directory = current_directory;
1682 }
1683
1684 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1685
1686 /* Read any stdin makefiles into temporary files. */
1687
1688 if (makefiles != 0)
1689 {
1690 register unsigned int i;
1691 for (i = 0; i < makefiles->idx; ++i)
1692 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1693 {
1694 /* This makefile is standard input. Since we may re-exec
1695 and thus re-read the makefiles, we read standard input
1696 into a temporary file and read from that. */
1697 FILE *outfile;
1698 char *template, *tmpdir;
1699
1700 if (stdin_nm)
1701 fatal (NILF, _("Makefile from standard input specified twice."));
1702
1703#ifdef VMS
1704# define DEFAULT_TMPDIR "sys$scratch:"
1705#else
1706# ifdef P_tmpdir
1707# define DEFAULT_TMPDIR P_tmpdir
1708# else
1709# define DEFAULT_TMPDIR "/tmp"
1710# endif
1711#endif
1712#define DEFAULT_TMPFILE "GmXXXXXX"
1713
1714 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1715#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1716 /* These are also used commonly on these platforms. */
1717 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1718 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1719#endif
1720 )
1721 tmpdir = DEFAULT_TMPDIR;
1722
1723 template = (char *) alloca (strlen (tmpdir)
1724 + sizeof (DEFAULT_TMPFILE) + 1);
1725 strcpy (template, tmpdir);
1726
1727#ifdef HAVE_DOS_PATHS
1728 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1729 strcat (template, "/");
1730#else
1731# ifndef VMS
1732 if (template[strlen (template) - 1] != '/')
1733 strcat (template, "/");
1734# endif /* !VMS */
1735#endif /* !HAVE_DOS_PATHS */
1736
1737 strcat (template, DEFAULT_TMPFILE);
1738 outfile = open_tmpfile (&stdin_nm, template);
1739 if (outfile == 0)
1740 pfatal_with_name (_("fopen (temporary file)"));
1741 while (!feof (stdin) && ! ferror (stdin))
1742 {
1743 char buf[2048];
1744 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1745 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1746 pfatal_with_name (_("fwrite (temporary file)"));
1747 }
1748 (void) fclose (outfile);
1749
1750 /* Replace the name that read_all_makefiles will
1751 see with the name of the temporary file. */
1752 makefiles->list[i] = xstrdup (stdin_nm);
1753
1754 /* Make sure the temporary file will not be remade. */
1755 f = enter_file (stdin_nm);
1756 f->updated = 1;
1757 f->update_status = 0;
1758 f->command_state = cs_finished;
1759 /* Can't be intermediate, or it'll be removed too early for
1760 make re-exec. */
1761 f->intermediate = 0;
1762 f->dontcare = 0;
1763 }
1764 }
1765
1766#ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
1767#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1768 /* Set up to handle children dying. This must be done before
1769 reading in the makefiles so that `shell' function calls will work.
1770
1771 If we don't have a hanging wait we have to fall back to old, broken
1772 functionality here and rely on the signal handler and counting
1773 children.
1774
1775 If we're using the jobs pipe we need a signal handler so that
1776 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1777 jobserver pipe in job.c if we're waiting for a token.
1778
1779 If none of these are true, we don't need a signal handler at all. */
1780 {
1781 extern RETSIGTYPE child_handler PARAMS ((int sig));
1782# if defined SIGCHLD
1783 bsd_signal (SIGCHLD, child_handler);
1784# endif
1785# if defined SIGCLD && SIGCLD != SIGCHLD
1786 bsd_signal (SIGCLD, child_handler);
1787# endif
1788 }
1789#endif
1790#endif
1791
1792 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1793#ifdef SIGUSR1
1794 bsd_signal (SIGUSR1, debug_signal_handler);
1795#endif
1796
1797 /* Define the initial list of suffixes for old-style rules. */
1798
1799 set_default_suffixes ();
1800
1801 /* Define the file rules for the built-in suffix rules. These will later
1802 be converted into pattern rules. We used to do this in
1803 install_default_implicit_rules, but since that happens after reading
1804 makefiles, it results in the built-in pattern rules taking precedence
1805 over makefile-specified suffix rules, which is wrong. */
1806
1807 install_default_suffix_rules ();
1808
1809 /* Define some internal and special variables. */
1810
1811 define_automatic_variables ();
1812
1813 /* Set up the MAKEFLAGS and MFLAGS variables
1814 so makefiles can look at them. */
1815
1816 define_makeflags (0, 0);
1817
1818 /* Define the default variables. */
1819 define_default_variables ();
1820
1821 default_file = enter_file (".DEFAULT");
1822
1823 {
1824 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
1825 default_goal_name = &v->value;
1826 }
1827
1828 /* Read all the makefiles. */
1829
1830 read_makefiles
1831 = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
1832
1833#ifdef WINDOWS32
1834 /* look one last time after reading all Makefiles */
1835 if (no_default_sh_exe)
1836 no_default_sh_exe = !find_and_set_default_shell(NULL);
1837#endif /* WINDOWS32 */
1838
1839#if defined (__MSDOS__) || defined (__EMX__)
1840 /* We need to know what kind of shell we will be using. */
1841 {
1842 extern int _is_unixy_shell (const char *_path);
1843 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1844 extern int unixy_shell;
1845 extern char *default_shell;
1846
1847 if (shv && *shv->value)
1848 {
1849 char *shell_path = recursively_expand(shv);
1850
1851 if (shell_path && _is_unixy_shell (shell_path))
1852 unixy_shell = 1;
1853 else
1854 unixy_shell = 0;
1855 if (shell_path)
1856 default_shell = shell_path;
1857 }
1858 }
1859#endif /* __MSDOS__ || __EMX__ */
1860
1861 /* Decode switches again, in case the variables were set by the makefile. */
1862 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1863#if 0
1864 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1865#endif
1866
1867#if defined (__MSDOS__) || defined (__EMX__)
1868 if (job_slots != 1
1869# ifdef __EMX__
1870 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1871# endif
1872 )
1873 {
1874 error (NILF,
1875 _("Parallel jobs (-j) are not supported on this platform."));
1876 error (NILF, _("Resetting to single job (-j1) mode."));
1877 job_slots = 1;
1878 }
1879#endif
1880
1881#ifdef MAKE_JOBSERVER
1882 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
1883
1884 if (jobserver_fds)
1885 {
1886 char *cp;
1887 unsigned int ui;
1888
1889 for (ui=1; ui < jobserver_fds->idx; ++ui)
1890 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1891 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1892
1893 /* Now parse the fds string and make sure it has the proper format. */
1894
1895 cp = jobserver_fds->list[0];
1896
1897 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
1898 fatal (NILF,
1899 _("internal error: invalid --jobserver-fds string `%s'"), cp);
1900
1901 /* The combination of a pipe + !job_slots means we're using the
1902 jobserver. If !job_slots and we don't have a pipe, we can start
1903 infinite jobs. If we see both a pipe and job_slots >0 that means the
1904 user set -j explicitly. This is broken; in this case obey the user
1905 (ignore the jobserver pipe for this make) but print a message. */
1906
1907 if (job_slots > 0)
1908 error (NILF,
1909 _("warning: -jN forced in submake: disabling jobserver mode."));
1910
1911 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1912 handler. If this fails with EBADF, the parent has closed the pipe
1913 on us because it didn't think we were a submake. If so, print a
1914 warning then default to -j1. */
1915
1916 else if ((job_rfd = dup (job_fds[0])) < 0)
1917 {
1918 if (errno != EBADF)
1919 pfatal_with_name (_("dup jobserver"));
1920
1921 error (NILF,
1922 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
1923 job_slots = 1;
1924 }
1925
1926 if (job_slots > 0)
1927 {
1928 close (job_fds[0]);
1929 close (job_fds[1]);
1930 job_fds[0] = job_fds[1] = -1;
1931 free (jobserver_fds->list);
1932 free (jobserver_fds);
1933 jobserver_fds = 0;
1934 }
1935 }
1936
1937 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
1938 Set up the pipe and install the fds option for our children. */
1939
1940 if (job_slots > 1)
1941 {
1942 char c = '+';
1943
1944 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
1945 pfatal_with_name (_("creating jobs pipe"));
1946
1947 /* Every make assumes that it always has one job it can run. For the
1948 submakes it's the token they were given by their parent. For the
1949 top make, we just subtract one from the number the user wants. We
1950 want job_slots to be 0 to indicate we're using the jobserver. */
1951
1952 master_job_slots = job_slots;
1953
1954 while (--job_slots)
1955 {
1956 int r;
1957
1958 EINTRLOOP (r, write (job_fds[1], &c, 1));
1959 if (r != 1)
1960 pfatal_with_name (_("init jobserver pipe"));
1961 }
1962
1963 /* Fill in the jobserver_fds struct for our children. */
1964
1965 jobserver_fds = (struct stringlist *)
1966 xmalloc (sizeof (struct stringlist));
1967 jobserver_fds->list = (char **) xmalloc (sizeof (char *));
1968 jobserver_fds->list[0] = xmalloc ((sizeof ("1024")*2)+1);
1969
1970 sprintf (jobserver_fds->list[0], "%d,%d", job_fds[0], job_fds[1]);
1971 jobserver_fds->idx = 1;
1972 jobserver_fds->max = 1;
1973 }
1974#endif
1975
1976#ifndef MAKE_SYMLINKS
1977 if (check_symlink_flag)
1978 {
1979 error (NILF, _("Symbolic links not supported: disabling -L."));
1980 check_symlink_flag = 0;
1981 }
1982#endif
1983
1984 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
1985
1986 define_makeflags (1, 0);
1987
1988 /* Make each `struct dep' point at the `struct file' for the file
1989 depended on. Also do magic for special targets. */
1990
1991 snap_deps ();
1992
1993 /* Convert old-style suffix rules to pattern rules. It is important to
1994 do this before installing the built-in pattern rules below, so that
1995 makefile-specified suffix rules take precedence over built-in pattern
1996 rules. */
1997
1998 convert_to_pattern ();
1999
2000 /* Install the default implicit pattern rules.
2001 This used to be done before reading the makefiles.
2002 But in that case, built-in pattern rules were in the chain
2003 before user-defined ones, so they matched first. */
2004
2005 install_default_implicit_rules ();
2006
2007 /* Compute implicit rule limits. */
2008
2009 count_implicit_rule_limits ();
2010
2011 /* Construct the listings of directories in VPATH lists. */
2012
2013 build_vpath_lists ();
2014
2015 /* Mark files given with -o flags as very old and as having been updated
2016 already, and files given with -W flags as brand new (time-stamp as far
2017 as possible into the future). If restarts is set we'll do -W later. */
2018
2019 if (old_files != 0)
2020 for (p = old_files->list; *p != 0; ++p)
2021 {
2022 f = enter_command_line_file (*p);
2023 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2024 f->updated = 1;
2025 f->update_status = 0;
2026 f->command_state = cs_finished;
2027 }
2028
2029 if (!restarts && new_files != 0)
2030 {
2031 for (p = new_files->list; *p != 0; ++p)
2032 {
2033 f = enter_command_line_file (*p);
2034 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2035 }
2036 }
2037
2038 /* Initialize the remote job module. */
2039 remote_setup ();
2040
2041 if (read_makefiles != 0)
2042 {
2043 /* Update any makefiles if necessary. */
2044
2045 FILE_TIMESTAMP *makefile_mtimes = 0;
2046 unsigned int mm_idx = 0;
2047 char **nargv = argv;
2048 int nargc = argc;
2049 int orig_db_level = db_level;
2050 int status;
2051
2052 if (! ISDB (DB_MAKEFILES))
2053 db_level = DB_NONE;
2054
2055 DB (DB_BASIC, (_("Updating makefiles....\n")));
2056
2057 /* Remove any makefiles we don't want to try to update.
2058 Also record the current modtimes so we can compare them later. */
2059 {
2060 register struct dep *d, *last;
2061 last = 0;
2062 d = read_makefiles;
2063 while (d != 0)
2064 {
2065 register struct file *f = d->file;
2066 if (f->double_colon)
2067 for (f = f->double_colon; f != NULL; f = f->prev)
2068 {
2069 if (f->deps == 0 && f->cmds != 0)
2070 {
2071 /* This makefile is a :: target with commands, but
2072 no dependencies. So, it will always be remade.
2073 This might well cause an infinite loop, so don't
2074 try to remake it. (This will only happen if
2075 your makefiles are written exceptionally
2076 stupidly; but if you work for Athena, that's how
2077 you write your makefiles.) */
2078
2079 DB (DB_VERBOSE,
2080 (_("Makefile `%s' might loop; not remaking it.\n"),
2081 f->name));
2082
2083 if (last == 0)
2084 read_makefiles = d->next;
2085 else
2086 last->next = d->next;
2087
2088 /* Free the storage. */
2089 free_dep (d);
2090
2091 d = last == 0 ? read_makefiles : last->next;
2092
2093 break;
2094 }
2095 }
2096 if (f == NULL || !f->double_colon)
2097 {
2098 makefile_mtimes = (FILE_TIMESTAMP *)
2099 xrealloc ((char *) makefile_mtimes,
2100 (mm_idx + 1) * sizeof (FILE_TIMESTAMP));
2101 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2102 last = d;
2103 d = d->next;
2104 }
2105 }
2106 }
2107
2108 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2109 define_makeflags (1, 1);
2110
2111 rebuilding_makefiles = 1;
2112 status = update_goal_chain (read_makefiles);
2113 rebuilding_makefiles = 0;
2114
2115 switch (status)
2116 {
2117 case 1:
2118 /* The only way this can happen is if the user specified -q and asked
2119 * for one of the makefiles to be remade as a target on the command
2120 * line. Since we're not actually updating anything with -q we can
2121 * treat this as "did nothing".
2122 */
2123
2124 case -1:
2125 /* Did nothing. */
2126 break;
2127
2128 case 2:
2129 /* Failed to update. Figure out if we care. */
2130 {
2131 /* Nonzero if any makefile was successfully remade. */
2132 int any_remade = 0;
2133 /* Nonzero if any makefile we care about failed
2134 in updating or could not be found at all. */
2135 int any_failed = 0;
2136 unsigned int i;
2137 struct dep *d;
2138
2139 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2140 {
2141 /* Reset the considered flag; we may need to look at the file
2142 again to print an error. */
2143 d->file->considered = 0;
2144
2145 if (d->file->updated)
2146 {
2147 /* This makefile was updated. */
2148 if (d->file->update_status == 0)
2149 {
2150 /* It was successfully updated. */
2151 any_remade |= (file_mtime_no_search (d->file)
2152 != makefile_mtimes[i]);
2153 }
2154 else if (! (d->changed & RM_DONTCARE))
2155 {
2156 FILE_TIMESTAMP mtime;
2157 /* The update failed and this makefile was not
2158 from the MAKEFILES variable, so we care. */
2159 error (NILF, _("Failed to remake makefile `%s'."),
2160 d->file->name);
2161 mtime = file_mtime_no_search (d->file);
2162 any_remade |= (mtime != NONEXISTENT_MTIME
2163 && mtime != makefile_mtimes[i]);
2164 makefile_status = MAKE_FAILURE;
2165 }
2166 }
2167 else
2168 /* This makefile was not found at all. */
2169 if (! (d->changed & RM_DONTCARE))
2170 {
2171 /* This is a makefile we care about. See how much. */
2172 if (d->changed & RM_INCLUDED)
2173 /* An included makefile. We don't need
2174 to die, but we do want to complain. */
2175 error (NILF,
2176 _("Included makefile `%s' was not found."),
2177 dep_name (d));
2178 else
2179 {
2180 /* A normal makefile. We must die later. */
2181 error (NILF, _("Makefile `%s' was not found"),
2182 dep_name (d));
2183 any_failed = 1;
2184 }
2185 }
2186 }
2187 /* Reset this to empty so we get the right error message below. */
2188 read_makefiles = 0;
2189
2190 if (any_remade)
2191 goto re_exec;
2192 if (any_failed)
2193 die (2);
2194 break;
2195 }
2196
2197 case 0:
2198 re_exec:
2199 /* Updated successfully. Re-exec ourselves. */
2200
2201 remove_intermediates (0);
2202
2203 if (print_data_base_flag)
2204 print_data_base ();
2205
2206 log_working_directory (0);
2207
2208 clean_jobserver (0);
2209
2210 if (makefiles != 0)
2211 {
2212 /* These names might have changed. */
2213 int i, j = 0;
2214 for (i = 1; i < argc; ++i)
2215 if (strneq (argv[i], "-f", 2)) /* XXX */
2216 {
2217 char *p = &argv[i][2];
2218 if (*p == '\0')
2219 argv[++i] = makefiles->list[j];
2220 else
2221 argv[i] = concat ("-f", makefiles->list[j], "");
2222 ++j;
2223 }
2224 }
2225
2226 /* Add -o option for the stdin temporary file, if necessary. */
2227 if (stdin_nm)
2228 {
2229 nargv = (char **) xmalloc ((nargc + 2) * sizeof (char *));
2230 bcopy ((char *) argv, (char *) nargv, argc * sizeof (char *));
2231 nargv[nargc++] = concat ("-o", stdin_nm, "");
2232 nargv[nargc] = 0;
2233 }
2234
2235 if (directories != 0 && directories->idx > 0)
2236 {
2237 char bad;
2238 if (directory_before_chdir != 0)
2239 {
2240 if (chdir (directory_before_chdir) < 0)
2241 {
2242 perror_with_name ("chdir", "");
2243 bad = 1;
2244 }
2245 else
2246 bad = 0;
2247 }
2248 else
2249 bad = 1;
2250 if (bad)
2251 fatal (NILF, _("Couldn't change back to original directory."));
2252 }
2253
2254 ++restarts;
2255
2256 if (ISDB (DB_BASIC))
2257 {
2258 char **p;
2259 printf (_("Re-executing[%u]:"), restarts);
2260 for (p = nargv; *p != 0; ++p)
2261 printf (" %s", *p);
2262 putchar ('\n');
2263 }
2264
2265#ifndef _AMIGA
2266 for (p = environ; *p != 0; ++p)
2267 {
2268 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2269 && (*p)[MAKELEVEL_LENGTH] == '=')
2270 {
2271 /* The SGI compiler apparently can't understand
2272 the concept of storing the result of a function
2273 in something other than a local variable. */
2274 char *sgi_loses;
2275 sgi_loses = (char *) alloca (40);
2276 *p = sgi_loses;
2277 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2278 }
2279 if (strneq (*p, "MAKE_RESTARTS=", 14))
2280 {
2281 char *sgi_loses;
2282 sgi_loses = (char *) alloca (40);
2283 *p = sgi_loses;
2284 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2285 restarts = 0;
2286 }
2287 }
2288#else /* AMIGA */
2289 {
2290 char buffer[256];
2291
2292 sprintf (buffer, "%u", makelevel);
2293 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2294
2295 sprintf (buffer, "%u", restarts);
2296 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2297 restarts = 0;
2298 }
2299#endif
2300
2301 /* If we didn't set the restarts variable yet, add it. */
2302 if (restarts)
2303 {
2304 char *b = alloca (40);
2305 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2306 putenv (b);
2307 }
2308
2309 fflush (stdout);
2310 fflush (stderr);
2311
2312 /* Close the dup'd jobserver pipe if we opened one. */
2313 if (job_rfd >= 0)
2314 close (job_rfd);
2315
2316#ifdef _AMIGA
2317 exec_command (nargv);
2318 exit (0);
2319#elif defined (__EMX__)
2320 {
2321 /* It is not possible to use execve() here because this
2322 would cause the parent process to be terminated with
2323 exit code 0 before the child process has been terminated.
2324 Therefore it may be the best solution simply to spawn the
2325 child process including all file handles and to wait for its
2326 termination. */
2327 int pid;
2328 int status;
2329 pid = child_execute_job (0, 1, nargv, environ);
2330
2331 /* is this loop really necessary? */
2332 do {
2333 pid = wait (&status);
2334 } while (pid <= 0);
2335 /* use the exit code of the child process */
2336 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2337 }
2338#else
2339 exec_command (nargv, environ);
2340#endif
2341 /* NOTREACHED */
2342
2343 default:
2344#define BOGUS_UPDATE_STATUS 0
2345 assert (BOGUS_UPDATE_STATUS);
2346 break;
2347 }
2348
2349 db_level = orig_db_level;
2350
2351 /* Free the makefile mtimes (if we allocated any). */
2352 if (makefile_mtimes)
2353 free ((char *) makefile_mtimes);
2354 }
2355
2356 /* Set up `MAKEFLAGS' again for the normal targets. */
2357 define_makeflags (1, 0);
2358
2359 /* Set always_make_flag if -B was given. */
2360 always_make_flag = always_make_set;
2361
2362 /* If restarts is set we haven't set up -W files yet, so do that now. */
2363 if (restarts && new_files != 0)
2364 {
2365 for (p = new_files->list; *p != 0; ++p)
2366 {
2367 f = enter_command_line_file (*p);
2368 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2369 }
2370 }
2371
2372 /* If there is a temp file from reading a makefile from stdin, get rid of
2373 it now. */
2374 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2375 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2376
2377 {
2378 int status;
2379
2380 /* If there were no command-line goals, use the default. */
2381 if (goals == 0)
2382 {
2383 if (**default_goal_name != '\0')
2384 {
2385 if (default_goal_file == 0 ||
2386 strcmp (*default_goal_name, default_goal_file->name) != 0)
2387 {
2388 default_goal_file = lookup_file (*default_goal_name);
2389
2390 /* In case user set .DEFAULT_GOAL to a non-existent target
2391 name let's just enter this name into the table and let
2392 the standard logic sort it out. */
2393 if (default_goal_file == 0)
2394 {
2395 struct nameseq *ns;
2396 char *p = *default_goal_name;
2397
2398 ns = multi_glob (
2399 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2400 sizeof (struct nameseq));
2401
2402 /* .DEFAULT_GOAL should contain one target. */
2403 if (ns->next != 0)
2404 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2405
2406 default_goal_file = enter_file (ns->name);
2407
2408 ns->name = 0; /* It was reused by enter_file(). */
2409 free_ns_chain (ns);
2410 }
2411 }
2412
2413 goals = alloc_dep ();
2414 goals->file = default_goal_file;
2415 }
2416 }
2417 else
2418 lastgoal->next = 0;
2419
2420
2421 if (!goals)
2422 {
2423 if (read_makefiles == 0)
2424 fatal (NILF, _("No targets specified and no makefile found"));
2425
2426 fatal (NILF, _("No targets"));
2427 }
2428
2429 /* Update the goals. */
2430
2431 DB (DB_BASIC, (_("Updating goal targets....\n")));
2432
2433 switch (update_goal_chain (goals))
2434 {
2435 case -1:
2436 /* Nothing happened. */
2437 case 0:
2438 /* Updated successfully. */
2439 status = makefile_status;
2440 break;
2441 case 1:
2442 /* We are under -q and would run some commands. */
2443 status = MAKE_TROUBLE;
2444 break;
2445 case 2:
2446 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2447 but in VMS, there is only success and failure. */
2448 status = MAKE_FAILURE;
2449 break;
2450 default:
2451 abort ();
2452 }
2453
2454 /* If we detected some clock skew, generate one last warning */
2455 if (clock_skew_detected)
2456 error (NILF,
2457 _("warning: Clock skew detected. Your build may be incomplete."));
2458
2459 /* Exit. */
2460 die (status);
2461 }
2462
2463 /* NOTREACHED */
2464 return 0;
2465}
2466
2467
2468/* Parsing of arguments, decoding of switches. */
2469
2470static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2471static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2472 (sizeof (long_option_aliases) /
2473 sizeof (long_option_aliases[0]))];
2474
2475/* Fill in the string and vector for getopt. */
2476static void
2477init_switches (void)
2478{
2479 char *p;
2480 unsigned int c;
2481 unsigned int i;
2482
2483 if (options[0] != '\0')
2484 /* Already done. */
2485 return;
2486
2487 p = options;
2488
2489 /* Return switch and non-switch args in order, regardless of
2490 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2491 *p++ = '-';
2492
2493 for (i = 0; switches[i].c != '\0'; ++i)
2494 {
2495 long_options[i].name = (switches[i].long_name == 0 ? "" :
2496 switches[i].long_name);
2497 long_options[i].flag = 0;
2498 long_options[i].val = switches[i].c;
2499 if (short_option (switches[i].c))
2500 *p++ = switches[i].c;
2501 switch (switches[i].type)
2502 {
2503 case flag:
2504 case flag_off:
2505 case ignore:
2506 long_options[i].has_arg = no_argument;
2507 break;
2508
2509 case string:
2510 case positive_int:
2511 case floating:
2512 if (short_option (switches[i].c))
2513 *p++ = ':';
2514 if (switches[i].noarg_value != 0)
2515 {
2516 if (short_option (switches[i].c))
2517 *p++ = ':';
2518 long_options[i].has_arg = optional_argument;
2519 }
2520 else
2521 long_options[i].has_arg = required_argument;
2522 break;
2523 }
2524 }
2525 *p = '\0';
2526 for (c = 0; c < (sizeof (long_option_aliases) /
2527 sizeof (long_option_aliases[0]));
2528 ++c)
2529 long_options[i++] = long_option_aliases[c];
2530 long_options[i].name = 0;
2531}
2532
2533static void
2534handle_non_switch_argument (char *arg, int env)
2535{
2536 /* Non-option argument. It might be a variable definition. */
2537 struct variable *v;
2538 if (arg[0] == '-' && arg[1] == '\0')
2539 /* Ignore plain `-' for compatibility. */
2540 return;
2541 v = try_variable_definition (0, arg, o_command, 0);
2542 if (v != 0)
2543 {
2544 /* It is indeed a variable definition. If we don't already have this
2545 one, record a pointer to the variable for later use in
2546 define_makeflags. */
2547 struct command_variable *cv;
2548
2549 for (cv = command_variables; cv != 0; cv = cv->next)
2550 if (cv->variable == v)
2551 break;
2552
2553 if (! cv) {
2554 cv = (struct command_variable *) xmalloc (sizeof (*cv));
2555 cv->variable = v;
2556 cv->next = command_variables;
2557 command_variables = cv;
2558 }
2559 }
2560 else if (! env)
2561 {
2562 /* Not an option or variable definition; it must be a goal
2563 target! Enter it as a file and add it to the dep chain of
2564 goals. */
2565 struct file *f = enter_command_line_file (arg);
2566 f->cmd_target = 1;
2567
2568 if (goals == 0)
2569 {
2570 goals = alloc_dep ();
2571 lastgoal = goals;
2572 }
2573 else
2574 {
2575 lastgoal->next = alloc_dep ();
2576 lastgoal = lastgoal->next;
2577 }
2578
2579 lastgoal->file = f;
2580
2581 {
2582 /* Add this target name to the MAKECMDGOALS variable. */
2583 struct variable *v;
2584 char *value;
2585
2586 v = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2587 if (v == 0)
2588 value = f->name;
2589 else
2590 {
2591 /* Paste the old and new values together */
2592 unsigned int oldlen, newlen;
2593
2594 oldlen = strlen (v->value);
2595 newlen = strlen (f->name);
2596 value = (char *) alloca (oldlen + 1 + newlen + 1);
2597 bcopy (v->value, value, oldlen);
2598 value[oldlen] = ' ';
2599 bcopy (f->name, &value[oldlen + 1], newlen + 1);
2600 }
2601 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2602 }
2603 }
2604}
2605
2606/* Print a nice usage method. */
2607
2608static void
2609print_usage (int bad)
2610{
2611 const char *const *cpp;
2612 FILE *usageto;
2613
2614 if (print_version_flag)
2615 print_version ();
2616
2617 usageto = bad ? stderr : stdout;
2618
2619 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2620
2621 for (cpp = usage; *cpp; ++cpp)
2622 fputs (_(*cpp), usageto);
2623
2624#ifdef KMK
2625 if (!remote_description || *remote_description == '\0')
2626 printf (_("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
2627 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2628 else
2629 printf (_("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
2630 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2631#else
2632 if (!remote_description || *remote_description == '\0')
2633 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2634 else
2635 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2636 make_host, remote_description);
2637#endif
2638
2639 fprintf (usageto, _("Report bugs to <[email protected]>\n"));
2640}
2641
2642/* Decode switches from ARGC and ARGV.
2643 They came from the environment if ENV is nonzero. */
2644
2645static void
2646decode_switches (int argc, char **argv, int env)
2647{
2648 int bad = 0;
2649 register const struct command_switch *cs;
2650 register struct stringlist *sl;
2651 register int c;
2652
2653 /* getopt does most of the parsing for us.
2654 First, get its vectors set up. */
2655
2656 init_switches ();
2657
2658 /* Let getopt produce error messages for the command line,
2659 but not for options from the environment. */
2660 opterr = !env;
2661 /* Reset getopt's state. */
2662 optind = 0;
2663
2664 while (optind < argc)
2665 {
2666 /* Parse the next argument. */
2667 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2668 if (c == EOF)
2669 /* End of arguments, or "--" marker seen. */
2670 break;
2671 else if (c == 1)
2672 /* An argument not starting with a dash. */
2673 handle_non_switch_argument (optarg, env);
2674 else if (c == '?')
2675 /* Bad option. We will print a usage message and die later.
2676 But continue to parse the other options so the user can
2677 see all he did wrong. */
2678 bad = 1;
2679 else
2680 for (cs = switches; cs->c != '\0'; ++cs)
2681 if (cs->c == c)
2682 {
2683 /* Whether or not we will actually do anything with
2684 this switch. We test this individually inside the
2685 switch below rather than just once outside it, so that
2686 options which are to be ignored still consume args. */
2687 int doit = !env || cs->env;
2688
2689 switch (cs->type)
2690 {
2691 default:
2692 abort ();
2693
2694 case ignore:
2695 break;
2696
2697 case flag:
2698 case flag_off:
2699 if (doit)
2700 *(int *) cs->value_ptr = cs->type == flag;
2701 break;
2702
2703 case string:
2704 if (!doit)
2705 break;
2706
2707 if (optarg == 0)
2708 optarg = cs->noarg_value;
2709 else if (*optarg == '\0')
2710 {
2711 error (NILF, _("the `-%c' option requires a non-empty string argument"),
2712 cs->c);
2713 bad = 1;
2714 }
2715
2716 sl = *(struct stringlist **) cs->value_ptr;
2717 if (sl == 0)
2718 {
2719 sl = (struct stringlist *)
2720 xmalloc (sizeof (struct stringlist));
2721 sl->max = 5;
2722 sl->idx = 0;
2723 sl->list = (char **) xmalloc (5 * sizeof (char *));
2724 *(struct stringlist **) cs->value_ptr = sl;
2725 }
2726 else if (sl->idx == sl->max - 1)
2727 {
2728 sl->max += 5;
2729 sl->list = (char **)
2730 xrealloc ((char *) sl->list,
2731 sl->max * sizeof (char *));
2732 }
2733 sl->list[sl->idx++] = optarg;
2734 sl->list[sl->idx] = 0;
2735 break;
2736
2737 case positive_int:
2738 /* See if we have an option argument; if we do require that
2739 it's all digits, not something like "10foo". */
2740 if (optarg == 0 && argc > optind)
2741 {
2742 const char *cp;
2743 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2744 ;
2745 if (cp[0] == '\0')
2746 optarg = argv[optind++];
2747 }
2748
2749 if (!doit)
2750 break;
2751
2752 if (optarg != 0)
2753 {
2754 int i = atoi (optarg);
2755 const char *cp;
2756
2757 /* Yes, I realize we're repeating this in some cases. */
2758 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2759 ;
2760
2761 if (i < 1 || cp[0] != '\0')
2762 {
2763 error (NILF, _("the `-%c' option requires a positive integral argument"),
2764 cs->c);
2765 bad = 1;
2766 }
2767 else
2768 *(unsigned int *) cs->value_ptr = i;
2769 }
2770 else
2771 *(unsigned int *) cs->value_ptr
2772 = *(unsigned int *) cs->noarg_value;
2773 break;
2774
2775#ifndef NO_FLOAT
2776 case floating:
2777 if (optarg == 0 && optind < argc
2778 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2779 optarg = argv[optind++];
2780
2781 if (doit)
2782 *(double *) cs->value_ptr
2783 = (optarg != 0 ? atof (optarg)
2784 : *(double *) cs->noarg_value);
2785
2786 break;
2787#endif
2788 }
2789
2790 /* We've found the switch. Stop looking. */
2791 break;
2792 }
2793 }
2794
2795 /* There are no more options according to getting getopt, but there may
2796 be some arguments left. Since we have asked for non-option arguments
2797 to be returned in order, this only happens when there is a "--"
2798 argument to prevent later arguments from being options. */
2799 while (optind < argc)
2800 handle_non_switch_argument (argv[optind++], env);
2801
2802
2803 if (!env && (bad || print_usage_flag))
2804 {
2805 print_usage (bad);
2806 die (bad ? 2 : 0);
2807 }
2808}
2809
2810/* Decode switches from environment variable ENVAR (which is LEN chars long).
2811 We do this by chopping the value into a vector of words, prepending a
2812 dash to the first word if it lacks one, and passing the vector to
2813 decode_switches. */
2814
2815static void
2816decode_env_switches (char *envar, unsigned int len)
2817{
2818 char *varref = (char *) alloca (2 + len + 2);
2819 char *value, *p;
2820 int argc;
2821 char **argv;
2822
2823 /* Get the variable's value. */
2824 varref[0] = '$';
2825 varref[1] = '(';
2826 bcopy (envar, &varref[2], len);
2827 varref[2 + len] = ')';
2828 varref[2 + len + 1] = '\0';
2829 value = variable_expand (varref);
2830
2831 /* Skip whitespace, and check for an empty value. */
2832 value = next_token (value);
2833 len = strlen (value);
2834 if (len == 0)
2835 return;
2836
2837 /* Allocate a vector that is definitely big enough. */
2838 argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
2839
2840 /* Allocate a buffer to copy the value into while we split it into words
2841 and unquote it. We must use permanent storage for this because
2842 decode_switches may store pointers into the passed argument words. */
2843 p = (char *) xmalloc (2 * len);
2844
2845 /* getopt will look at the arguments starting at ARGV[1].
2846 Prepend a spacer word. */
2847 argv[0] = 0;
2848 argc = 1;
2849 argv[argc] = p;
2850 while (*value != '\0')
2851 {
2852 if (*value == '\\' && value[1] != '\0')
2853 ++value; /* Skip the backslash. */
2854 else if (isblank ((unsigned char)*value))
2855 {
2856 /* End of the word. */
2857 *p++ = '\0';
2858 argv[++argc] = p;
2859 do
2860 ++value;
2861 while (isblank ((unsigned char)*value));
2862 continue;
2863 }
2864 *p++ = *value++;
2865 }
2866 *p = '\0';
2867 argv[++argc] = 0;
2868
2869 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2870 /* The first word doesn't start with a dash and isn't a variable
2871 definition. Add a dash and pass it along to decode_switches. We
2872 need permanent storage for this in case decode_switches saves
2873 pointers into the value. */
2874 argv[1] = concat ("-", argv[1], "");
2875
2876 /* Parse those words. */
2877 decode_switches (argc, argv, 1);
2878}
2879
2880
2881/* Quote the string IN so that it will be interpreted as a single word with
2882 no magic by decode_env_switches; also double dollar signs to avoid
2883 variable expansion in make itself. Write the result into OUT, returning
2884 the address of the next character to be written.
2885 Allocating space for OUT twice the length of IN is always sufficient. */
2886
2887static char *
2888quote_for_env (char *out, char *in)
2889{
2890 while (*in != '\0')
2891 {
2892 if (*in == '$')
2893 *out++ = '$';
2894 else if (isblank ((unsigned char)*in) || *in == '\\')
2895 *out++ = '\\';
2896 *out++ = *in++;
2897 }
2898
2899 return out;
2900}
2901
2902/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
2903 command switches. Include options with args if ALL is nonzero.
2904 Don't include options with the `no_makefile' flag set if MAKEFILE. */
2905
2906static void
2907define_makeflags (int all, int makefile)
2908{
2909 static const char ref[] = "$(MAKEOVERRIDES)";
2910 static const char posixref[] = "$(-*-command-variables-*-)";
2911 register const struct command_switch *cs;
2912 char *flagstring;
2913 register char *p;
2914 unsigned int words;
2915 struct variable *v;
2916
2917 /* We will construct a linked list of `struct flag's describing
2918 all the flags which need to go in MAKEFLAGS. Then, once we
2919 know how many there are and their lengths, we can put them all
2920 together in a string. */
2921
2922 struct flag
2923 {
2924 struct flag *next;
2925 const struct command_switch *cs;
2926 char *arg;
2927 };
2928 struct flag *flags = 0;
2929 unsigned int flagslen = 0;
2930#define ADD_FLAG(ARG, LEN) \
2931 do { \
2932 struct flag *new = (struct flag *) alloca (sizeof (struct flag)); \
2933 new->cs = cs; \
2934 new->arg = (ARG); \
2935 new->next = flags; \
2936 flags = new; \
2937 if (new->arg == 0) \
2938 ++flagslen; /* Just a single flag letter. */ \
2939 else \
2940 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
2941 if (!short_option (cs->c)) \
2942 /* This switch has no single-letter version, so we use the long. */ \
2943 flagslen += 2 + strlen (cs->long_name); \
2944 } while (0)
2945
2946 for (cs = switches; cs->c != '\0'; ++cs)
2947 if (cs->toenv && (!makefile || !cs->no_makefile))
2948 switch (cs->type)
2949 {
2950 default:
2951 abort ();
2952
2953 case ignore:
2954 break;
2955
2956 case flag:
2957 case flag_off:
2958 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
2959 && (cs->default_value == 0
2960 || *(int *) cs->value_ptr != *(int *) cs->default_value))
2961 ADD_FLAG (0, 0);
2962 break;
2963
2964 case positive_int:
2965 if (all)
2966 {
2967 if ((cs->default_value != 0
2968 && (*(unsigned int *) cs->value_ptr
2969 == *(unsigned int *) cs->default_value)))
2970 break;
2971 else if (cs->noarg_value != 0
2972 && (*(unsigned int *) cs->value_ptr ==
2973 *(unsigned int *) cs->noarg_value))
2974 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
2975#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
2976 else if (cs->c == 'j')
2977 /* Special case for `-j'. */
2978 ADD_FLAG ("1", 1);
2979#endif
2980 else
2981 {
2982 char *buf = (char *) alloca (30);
2983 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
2984 ADD_FLAG (buf, strlen (buf));
2985 }
2986 }
2987 break;
2988
2989#ifndef NO_FLOAT
2990 case floating:
2991 if (all)
2992 {
2993 if (cs->default_value != 0
2994 && (*(double *) cs->value_ptr
2995 == *(double *) cs->default_value))
2996 break;
2997 else if (cs->noarg_value != 0
2998 && (*(double *) cs->value_ptr
2999 == *(double *) cs->noarg_value))
3000 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3001 else
3002 {
3003 char *buf = (char *) alloca (100);
3004 sprintf (buf, "%g", *(double *) cs->value_ptr);
3005 ADD_FLAG (buf, strlen (buf));
3006 }
3007 }
3008 break;
3009#endif
3010
3011 case string:
3012 if (all)
3013 {
3014 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3015 if (sl != 0)
3016 {
3017 /* Add the elements in reverse order, because
3018 all the flags get reversed below; and the order
3019 matters for some switches (like -I). */
3020 register unsigned int i = sl->idx;
3021 while (i-- > 0)
3022 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3023 }
3024 }
3025 break;
3026 }
3027
3028 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3029
3030#undef ADD_FLAG
3031
3032 /* Construct the value in FLAGSTRING.
3033 We allocate enough space for a preceding dash and trailing null. */
3034 flagstring = (char *) alloca (1 + flagslen + 1);
3035 bzero (flagstring, 1 + flagslen + 1);
3036 p = flagstring;
3037 words = 1;
3038 *p++ = '-';
3039 while (flags != 0)
3040 {
3041 /* Add the flag letter or name to the string. */
3042 if (short_option (flags->cs->c))
3043 *p++ = flags->cs->c;
3044 else
3045 {
3046 if (*p != '-')
3047 {
3048 *p++ = ' ';
3049 *p++ = '-';
3050 }
3051 *p++ = '-';
3052 strcpy (p, flags->cs->long_name);
3053 p += strlen (p);
3054 }
3055 if (flags->arg != 0)
3056 {
3057 /* A flag that takes an optional argument which in this case is
3058 omitted is specified by ARG being "". We must distinguish
3059 because a following flag appended without an intervening " -"
3060 is considered the arg for the first. */
3061 if (flags->arg[0] != '\0')
3062 {
3063 /* Add its argument too. */
3064 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3065 p = quote_for_env (p, flags->arg);
3066 }
3067 ++words;
3068 /* Write a following space and dash, for the next flag. */
3069 *p++ = ' ';
3070 *p++ = '-';
3071 }
3072 else if (!short_option (flags->cs->c))
3073 {
3074 ++words;
3075 /* Long options must each go in their own word,
3076 so we write the following space and dash. */
3077 *p++ = ' ';
3078 *p++ = '-';
3079 }
3080 flags = flags->next;
3081 }
3082
3083 /* Define MFLAGS before appending variable definitions. */
3084
3085 if (p == &flagstring[1])
3086 /* No flags. */
3087 flagstring[0] = '\0';
3088 else if (p[-1] == '-')
3089 {
3090 /* Kill the final space and dash. */
3091 p -= 2;
3092 *p = '\0';
3093 }
3094 else
3095 /* Terminate the string. */
3096 *p = '\0';
3097
3098 /* Since MFLAGS is not parsed for flags, there is no reason to
3099 override any makefile redefinition. */
3100 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3101
3102 if (all && command_variables != 0)
3103 {
3104 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3105 command-line variable definitions. */
3106
3107 if (p == &flagstring[1])
3108 /* No flags written, so elide the leading dash already written. */
3109 p = flagstring;
3110 else
3111 {
3112 /* Separate the variables from the switches with a "--" arg. */
3113 if (p[-1] != '-')
3114 {
3115 /* We did not already write a trailing " -". */
3116 *p++ = ' ';
3117 *p++ = '-';
3118 }
3119 /* There is a trailing " -"; fill it out to " -- ". */
3120 *p++ = '-';
3121 *p++ = ' ';
3122 }
3123
3124 /* Copy in the string. */
3125 if (posix_pedantic)
3126 {
3127 bcopy (posixref, p, sizeof posixref - 1);
3128 p += sizeof posixref - 1;
3129 }
3130 else
3131 {
3132 bcopy (ref, p, sizeof ref - 1);
3133 p += sizeof ref - 1;
3134 }
3135 }
3136 else if (p == &flagstring[1])
3137 {
3138 words = 0;
3139 --p;
3140 }
3141 else if (p[-1] == '-')
3142 /* Kill the final space and dash. */
3143 p -= 2;
3144 /* Terminate the string. */
3145 *p = '\0';
3146
3147 v = define_variable ("MAKEFLAGS", 9,
3148 /* If there are switches, omit the leading dash
3149 unless it is a single long option with two
3150 leading dashes. */
3151 &flagstring[(flagstring[0] == '-'
3152 && flagstring[1] != '-')
3153 ? 1 : 0],
3154 /* This used to use o_env, but that lost when a
3155 makefile defined MAKEFLAGS. Makefiles set
3156 MAKEFLAGS to add switches, but we still want
3157 to redefine its value with the full set of
3158 switches. Of course, an override or command
3159 definition will still take precedence. */
3160 o_file, 1);
3161 if (! all)
3162 /* The first time we are called, set MAKEFLAGS to always be exported.
3163 We should not do this again on the second call, because that is
3164 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3165 v->export = v_export;
3166}
3167
3168
3169/* Print version information. */
3170
3171static void
3172print_version (void)
3173{
3174 static int printed_version = 0;
3175
3176 char *precede = print_data_base_flag ? "# " : "";
3177
3178 if (printed_version)
3179 /* Do it only once. */
3180 return;
3181
3182 /* Print this untranslated. The coding standards recommend translating the
3183 (C) to the copyright symbol, but this string is going to change every
3184 year, and none of the rest of it should be translated (including the
3185 word "Copyright", so it hardly seems worth it. */
3186
3187#ifdef KMK
3188 printf ("%skBuild Make %d.%d.%d\n\
3189\n\
3190%sBased on GNU Make %s:\n\
3191%s Copyright (C) 2006 Free Software Foundation, Inc.\n\
3192\n\
3193%skBuild Modifications:\n\
3194%s Copyright (C) 2005-2006 Knut St. Osmundsen.\n\
3195\n\
3196%skmkbuiltin commands derived from *BSD sources:\n\
3197%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3198%s The Regents of the University of California. All rights reserved.\n\
3199%s Copyright (c) 1998 Todd C. Miller <[email protected]>\n\
3200%s\n",
3201 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR, KBUILD_VERSION_PATCH,
3202 precede, version_string,
3203 precede, precede, precede, precede, precede, precede, precede, precede);
3204#else
3205 printf ("%sGNU Make %s\n\
3206%sCopyright (C) 2006 Free Software Foundation, Inc.\n",
3207 precede, version_string, precede);
3208#endif
3209
3210 printf (_("%sThis is free software; see the source for copying conditions.\n\
3211%sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
3212%sPARTICULAR PURPOSE.\n"),
3213 precede, precede, precede);
3214
3215#ifdef KMK
3216# ifdef PATH_KBUILD
3217 printf (_("%s\n\
3218%sPATH_KBUILD default: '%s'\n\
3219%sPATH_KBUILD_BIN default: '%s'\n"),
3220 precede, precede, PATH_KBUILD, precede, PATH_KBUILD_BIN);
3221# endif /* PATH_KBUILD */
3222 if (!remote_description || *remote_description == '\0')
3223 printf (_("\n%sThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3224 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3225 else
3226 printf (_("\n%sThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3227 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3228#else
3229 if (!remote_description || *remote_description == '\0')
3230 printf (_("\n%sThis program built for %s\n"), precede, make_host);
3231 else
3232 printf (_("\n%sThis program built for %s (%s)\n"),
3233 precede, make_host, remote_description);
3234#endif
3235
3236 printed_version = 1;
3237
3238 /* Flush stdout so the user doesn't have to wait to see the
3239 version information while things are thought about. */
3240 fflush (stdout);
3241}
3242
3243/* Print a bunch of information about this and that. */
3244
3245static void
3246print_data_base ()
3247{
3248 time_t when;
3249
3250 when = time ((time_t *) 0);
3251 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3252
3253 print_variable_data_base ();
3254 print_dir_data_base ();
3255 print_rule_data_base ();
3256 print_file_data_base ();
3257 print_vpath_data_base ();
3258 strcache_print_stats ("#");
3259
3260 when = time ((time_t *) 0);
3261 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3262}
3263
3264static void
3265clean_jobserver (int status)
3266{
3267 char token = '+';
3268
3269 /* Sanity: have we written all our jobserver tokens back? If our
3270 exit status is 2 that means some kind of syntax error; we might not
3271 have written all our tokens so do that now. If tokens are left
3272 after any other error code, that's bad. */
3273
3274 if (job_fds[0] != -1 && jobserver_tokens)
3275 {
3276 if (status != 2)
3277 error (NILF,
3278 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3279 jobserver_tokens);
3280 else
3281 while (jobserver_tokens--)
3282 {
3283 int r;
3284
3285 EINTRLOOP (r, write (job_fds[1], &token, 1));
3286 if (r != 1)
3287 perror_with_name ("write", "");
3288 }
3289 }
3290
3291
3292 /* Sanity: If we're the master, were all the tokens written back? */
3293
3294 if (master_job_slots)
3295 {
3296 /* We didn't write one for ourself, so start at 1. */
3297 unsigned int tcnt = 1;
3298
3299 /* Close the write side, so the read() won't hang. */
3300 close (job_fds[1]);
3301
3302 while (read (job_fds[0], &token, 1) == 1)
3303 ++tcnt;
3304
3305 if (tcnt != master_job_slots)
3306 error (NILF,
3307 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3308 tcnt, master_job_slots);
3309
3310 close (job_fds[0]);
3311 }
3312}
3313
3314
3315/* Exit with STATUS, cleaning up as necessary. */
3316
3317void
3318die (int status)
3319{
3320 static char dying = 0;
3321
3322 if (!dying)
3323 {
3324 int err;
3325
3326 dying = 1;
3327
3328 if (print_version_flag)
3329 print_version ();
3330
3331 /* Wait for children to die. */
3332 err = (status != 0);
3333 while (job_slots_used > 0)
3334 reap_children (1, err);
3335
3336 /* Let the remote job module clean up its state. */
3337 remote_cleanup ();
3338
3339 /* Remove the intermediate files. */
3340 remove_intermediates (0);
3341
3342 if (print_data_base_flag)
3343 print_data_base ();
3344
3345 clean_jobserver (status);
3346
3347 /* Try to move back to the original directory. This is essential on
3348 MS-DOS (where there is really only one process), and on Unix it
3349 puts core files in the original directory instead of the -C
3350 directory. Must wait until after remove_intermediates(), or unlinks
3351 of relative pathnames fail. */
3352 if (directory_before_chdir != 0)
3353 chdir (directory_before_chdir);
3354
3355 log_working_directory (0);
3356 }
3357
3358 exit (status);
3359}
3360
3361
3362/* Write a message indicating that we've just entered or
3363 left (according to ENTERING) the current directory. */
3364
3365void
3366log_working_directory (int entering)
3367{
3368 static int entered = 0;
3369
3370 /* Print nothing without the flag. Don't print the entering message
3371 again if we already have. Don't print the leaving message if we
3372 haven't printed the entering message. */
3373 if (! print_directory_flag || entering == entered)
3374 return;
3375
3376 entered = entering;
3377
3378 if (print_data_base_flag)
3379 fputs ("# ", stdout);
3380
3381 /* Use entire sentences to give the translators a fighting chance. */
3382
3383 if (makelevel == 0)
3384 if (starting_directory == 0)
3385 if (entering)
3386 printf (_("%s: Entering an unknown directory\n"), program);
3387 else
3388 printf (_("%s: Leaving an unknown directory\n"), program);
3389 else
3390 if (entering)
3391 printf (_("%s: Entering directory `%s'\n"),
3392 program, starting_directory);
3393 else
3394 printf (_("%s: Leaving directory `%s'\n"),
3395 program, starting_directory);
3396 else
3397 if (starting_directory == 0)
3398 if (entering)
3399 printf (_("%s[%u]: Entering an unknown directory\n"),
3400 program, makelevel);
3401 else
3402 printf (_("%s[%u]: Leaving an unknown directory\n"),
3403 program, makelevel);
3404 else
3405 if (entering)
3406 printf (_("%s[%u]: Entering directory `%s'\n"),
3407 program, makelevel, starting_directory);
3408 else
3409 printf (_("%s[%u]: Leaving directory `%s'\n"),
3410 program, makelevel, starting_directory);
3411
3412 /* Flush stdout to be sure this comes before any stderr output. */
3413 fflush (stdout);
3414}
Note: See TracBrowser for help on using the repository browser.

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