VirtualBox

source: kBuild/trunk/src/kmk/main.c@ 1223

Last change on this file since 1223 was 1186, checked in by bird, 17 years ago

aligned the version message.

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