VirtualBox

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

Last change on this file since 1302 was 1280, checked in by bird, 17 years ago

print_version fix.

  • Property svn:eol-style set to native
File size: 100.1 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#ifdef KMK
1471 decode_env_switches (STRING_SIZE_TUPLE ("KMKFLAGS"));
1472#endif
1473 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1474#if 0
1475 /* People write things like:
1476 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1477 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1478 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1479#endif
1480 decode_switches (argc, argv, 0);
1481#ifdef WINDOWS32
1482 if (suspend_flag) {
1483 fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
1484 fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1485 Sleep(30 * 1000);
1486 fprintf(stderr, _("done sleep(30). Continuing.\n"));
1487 }
1488#endif
1489
1490 decode_debug_flags ();
1491
1492#ifdef KMK
1493 set_make_priority ();
1494#endif
1495
1496 /* Set always_make_flag if -B was given and we've not restarted already. */
1497 always_make_flag = always_make_set && (restarts == 0);
1498
1499 /* Print version information. */
1500 if (print_version_flag || print_data_base_flag || db_level)
1501 {
1502 print_version ();
1503
1504 /* `make --version' is supposed to just print the version and exit. */
1505 if (print_version_flag)
1506 die (0);
1507 }
1508
1509#ifndef VMS
1510 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1511 (If it is a relative pathname with a slash, prepend our directory name
1512 so the result will run the same program regardless of the current dir.
1513 If it is a name with no slash, we can only hope that PATH did not
1514 find it in the current directory.) */
1515#ifdef WINDOWS32
1516 /*
1517 * Convert from backslashes to forward slashes for
1518 * programs like sh which don't like them. Shouldn't
1519 * matter if the path is one way or the other for
1520 * CreateProcess().
1521 */
1522 if (strpbrk(argv[0], "/:\\") ||
1523 strstr(argv[0], "..") ||
1524 strneq(argv[0], "//", 2))
1525 argv[0] = xstrdup(w32ify(argv[0],1));
1526#else /* WINDOWS32 */
1527#if defined (__MSDOS__) || defined (__EMX__)
1528 if (strchr (argv[0], '\\'))
1529 {
1530 char *p;
1531
1532 argv[0] = xstrdup (argv[0]);
1533 for (p = argv[0]; *p; p++)
1534 if (*p == '\\')
1535 *p = '/';
1536 }
1537 /* If argv[0] is not in absolute form, prepend the current
1538 directory. This can happen when Make is invoked by another DJGPP
1539 program that uses a non-absolute name. */
1540 if (current_directory[0] != '\0'
1541 && argv[0] != 0
1542 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1543# ifdef __EMX__
1544 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1545 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1546# endif
1547 )
1548 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1549#else /* !__MSDOS__ */
1550 if (current_directory[0] != '\0'
1551 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1552#ifdef HAVE_DOS_PATHS
1553 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1554 && strchr (argv[0], '\\') != 0
1555#endif
1556 )
1557 argv[0] = xstrdup (concat (current_directory, "/", argv[0]));
1558#endif /* !__MSDOS__ */
1559#endif /* WINDOWS32 */
1560#endif
1561
1562 /* The extra indirection through $(MAKE_COMMAND) is done
1563 for hysterical raisins. */
1564 (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
1565 (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
1566#ifdef KMK
1567 (void) define_variable ("KMK", 3, argv[0], o_default, 1);
1568#endif
1569
1570 if (command_variables != 0)
1571 {
1572 struct command_variable *cv;
1573 struct variable *v;
1574 unsigned int len = 0;
1575 char *value, *p;
1576
1577 /* Figure out how much space will be taken up by the command-line
1578 variable definitions. */
1579 for (cv = command_variables; cv != 0; cv = cv->next)
1580 {
1581 v = cv->variable;
1582 len += 2 * strlen (v->name);
1583 if (! v->recursive)
1584 ++len;
1585 ++len;
1586 len += 2 * strlen (v->value);
1587 ++len;
1588 }
1589
1590 /* Now allocate a buffer big enough and fill it. */
1591 p = value = alloca (len);
1592 for (cv = command_variables; cv != 0; cv = cv->next)
1593 {
1594 v = cv->variable;
1595 p = quote_for_env (p, v->name);
1596 if (! v->recursive)
1597 *p++ = ':';
1598 *p++ = '=';
1599 p = quote_for_env (p, v->value);
1600 *p++ = ' ';
1601 }
1602 p[-1] = '\0'; /* Kill the final space and terminate. */
1603
1604 /* Define an unchangeable variable with a name that no POSIX.2
1605 makefile could validly use for its own variable. */
1606 (void) define_variable ("-*-command-variables-*-", 23,
1607 value, o_automatic, 0);
1608
1609 /* Define the variable; this will not override any user definition.
1610 Normally a reference to this variable is written into the value of
1611 MAKEFLAGS, allowing the user to override this value to affect the
1612 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1613 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1614 a reference to this hidden variable is written instead. */
1615 (void) define_variable ("MAKEOVERRIDES", 13,
1616 "${-*-command-variables-*-}", o_env, 1);
1617 }
1618
1619 /* If there were -C flags, move ourselves about. */
1620 if (directories != 0)
1621 {
1622 unsigned int i;
1623 for (i = 0; directories->list[i] != 0; ++i)
1624 {
1625 const char *dir = directories->list[i];
1626#ifdef WINDOWS32
1627 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1628 But allow -C/ just in case someone wants that. */
1629 {
1630 char *p = (char *)dir + strlen (dir) - 1;
1631 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1632 --p;
1633 p[1] = '\0';
1634 }
1635#endif
1636 if (chdir (dir) < 0)
1637 pfatal_with_name (dir);
1638 }
1639 }
1640
1641#ifdef KMK
1642 /* Check for [Mm]akefile.kup and change directory when found.
1643 Makefile.kmk overrides Makefile.kup but not plain Makefile.
1644 If no -C arguments were given, fake one to indicate chdir. */
1645 if (makefiles == 0)
1646 {
1647 struct stat st;
1648 if (( stat ("Makefile.kup", &st) == 0
1649 && S_ISREG (st.st_mode) )
1650 || ( stat ("makefile.kup", &st) == 0
1651 && S_ISREG (st.st_mode) )
1652 && stat ("Makefile.kmk", &st) < 0
1653 && stat ("makefile.kmk", &st) < 0)
1654 {
1655 static char fake_path[3*16 + 32] = "..";
1656 char *cur = &fake_path[2];
1657 int up_levels = 1;
1658 while (up_levels < 16)
1659 {
1660 /* File with higher precedence.s */
1661 strcpy (cur, "/Makefile.kmk");
1662 if (stat (fake_path, &st) == 0)
1663 break;
1664 strcpy (cur, "/makefile.kmk");
1665 if (stat (fake_path, &st) == 0)
1666 break;
1667
1668 /* the .kup files */
1669 strcpy (cur, "/Makefile.kup");
1670 if ( stat (fake_path, &st) != 0
1671 || !S_ISREG (st.st_mode))
1672 {
1673 strcpy (cur, "/makefile.kup");
1674 if ( stat (fake_path, &st) != 0
1675 || !S_ISREG (st.st_mode))
1676 break;
1677 }
1678
1679 /* ok */
1680 strcpy (cur, "/..");
1681 cur += 3;
1682 up_levels++;
1683 }
1684
1685 if (up_levels >= 16)
1686 fatal (NILF, _("Makefile.kup recursion is too deep."));
1687
1688 /* attempt to change to the directory. */
1689 *cur = '\0';
1690 if (chdir (fake_path) < 0)
1691 pfatal_with_name (fake_path);
1692
1693 /* add the string to the directories. */
1694 if (!directories)
1695 {
1696 directories = xmalloc (sizeof(*directories));
1697 directories->list = xmalloc (5 * sizeof (char *));
1698 directories->max = 5;
1699 directories->idx = 0;
1700 }
1701 else if (directories->idx == directories->max - 1)
1702 {
1703 directories->max += 5;
1704 directories->list = xrealloc ((void *)directories->list,
1705 directories->max * sizeof (char *));
1706 }
1707 directories->list[directories->idx++] = fake_path;
1708 }
1709 }
1710#endif /* KMK */
1711
1712#ifdef WINDOWS32
1713 /*
1714 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1715 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1716 *
1717 * The functions in dir.c can incorrectly cache information for "."
1718 * before we have changed directory and this can cause file
1719 * lookups to fail because the current directory (.) was pointing
1720 * at the wrong place when it was first evaluated.
1721 */
1722#ifdef KMK /* this is really a candidate for all platforms... */
1723 {
1724 extern char *default_shell;
1725 char *bin = get_path_kbuild_bin();
1726 size_t len = strlen (bin);
1727 default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
1728 memcpy (default_shell, bin, len);
1729 strcpy (default_shell + len, "/kmk_ash.exe");
1730 no_default_sh_exe = 0;
1731 batch_mode_shell = 1;
1732 }
1733#else /* !KMK */
1734 no_default_sh_exe = !find_and_set_default_shell(NULL);
1735#endif /* !KMK */
1736#endif /* WINDOWS32 */
1737 /* Figure out the level of recursion. */
1738 {
1739 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1740 if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
1741 makelevel = (unsigned int) atoi (v->value);
1742 else
1743 makelevel = 0;
1744 }
1745
1746 /* Except under -s, always do -w in sub-makes and under -C. */
1747 if (!silent_flag && (directories != 0 || makelevel > 0))
1748 print_directory_flag = 1;
1749
1750 /* Let the user disable that with --no-print-directory. */
1751 if (inhibit_print_directory_flag)
1752 print_directory_flag = 0;
1753
1754 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1755 if (no_builtin_variables_flag)
1756 no_builtin_rules_flag = 1;
1757
1758 /* Construct the list of include directories to search. */
1759
1760 construct_include_path (include_directories == 0
1761 ? 0 : include_directories->list);
1762
1763 /* Figure out where we are now, after chdir'ing. */
1764 if (directories == 0)
1765 /* We didn't move, so we're still in the same place. */
1766 starting_directory = current_directory;
1767 else
1768 {
1769#ifdef WINDOWS32
1770 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1771#else
1772 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1773#endif
1774 {
1775#ifdef HAVE_GETCWD
1776 perror_with_name ("getcwd", "");
1777#else
1778 error (NILF, "getwd: %s", current_directory);
1779#endif
1780 starting_directory = 0;
1781 }
1782 else
1783 starting_directory = current_directory;
1784 }
1785
1786 (void) define_variable ("CURDIR", 6, current_directory, o_file, 0);
1787
1788 /* Read any stdin makefiles into temporary files. */
1789
1790 if (makefiles != 0)
1791 {
1792 unsigned int i;
1793 for (i = 0; i < makefiles->idx; ++i)
1794 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1795 {
1796 /* This makefile is standard input. Since we may re-exec
1797 and thus re-read the makefiles, we read standard input
1798 into a temporary file and read from that. */
1799 FILE *outfile;
1800 char *template, *tmpdir;
1801
1802 if (stdin_nm)
1803 fatal (NILF, _("Makefile from standard input specified twice."));
1804
1805#ifdef VMS
1806# define DEFAULT_TMPDIR "sys$scratch:"
1807#else
1808# ifdef P_tmpdir
1809# define DEFAULT_TMPDIR P_tmpdir
1810# else
1811# define DEFAULT_TMPDIR "/tmp"
1812# endif
1813#endif
1814#define DEFAULT_TMPFILE "GmXXXXXX"
1815
1816 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1817#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1818 /* These are also used commonly on these platforms. */
1819 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1820 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1821#endif
1822 )
1823 tmpdir = DEFAULT_TMPDIR;
1824
1825 template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
1826 strcpy (template, tmpdir);
1827
1828#ifdef HAVE_DOS_PATHS
1829 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1830 strcat (template, "/");
1831#else
1832# ifndef VMS
1833 if (template[strlen (template) - 1] != '/')
1834 strcat (template, "/");
1835# endif /* !VMS */
1836#endif /* !HAVE_DOS_PATHS */
1837
1838 strcat (template, DEFAULT_TMPFILE);
1839 outfile = open_tmpfile (&stdin_nm, template);
1840 if (outfile == 0)
1841 pfatal_with_name (_("fopen (temporary file)"));
1842 while (!feof (stdin) && ! ferror (stdin))
1843 {
1844 char buf[2048];
1845 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1846 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1847 pfatal_with_name (_("fwrite (temporary file)"));
1848 }
1849 fclose (outfile);
1850
1851 /* Replace the name that read_all_makefiles will
1852 see with the name of the temporary file. */
1853 makefiles->list[i] = strcache_add (stdin_nm);
1854
1855 /* Make sure the temporary file will not be remade. */
1856 {
1857 struct file *f = enter_file (strcache_add (stdin_nm));
1858 f->updated = 1;
1859 f->update_status = 0;
1860 f->command_state = cs_finished;
1861 /* Can't be intermediate, or it'll be removed too early for
1862 make re-exec. */
1863 f->intermediate = 0;
1864 f->dontcare = 0;
1865 }
1866 }
1867 }
1868
1869#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
1870#if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1871 /* Set up to handle children dying. This must be done before
1872 reading in the makefiles so that `shell' function calls will work.
1873
1874 If we don't have a hanging wait we have to fall back to old, broken
1875 functionality here and rely on the signal handler and counting
1876 children.
1877
1878 If we're using the jobs pipe we need a signal handler so that
1879 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1880 jobserver pipe in job.c if we're waiting for a token.
1881
1882 If none of these are true, we don't need a signal handler at all. */
1883 {
1884 RETSIGTYPE child_handler (int sig);
1885# if defined SIGCHLD
1886 bsd_signal (SIGCHLD, child_handler);
1887# endif
1888# if defined SIGCLD && SIGCLD != SIGCHLD
1889 bsd_signal (SIGCLD, child_handler);
1890# endif
1891 }
1892#endif
1893#endif
1894
1895 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1896#ifdef SIGUSR1
1897 bsd_signal (SIGUSR1, debug_signal_handler);
1898#endif
1899
1900 /* Define the initial list of suffixes for old-style rules. */
1901
1902 set_default_suffixes ();
1903
1904 /* Define the file rules for the built-in suffix rules. These will later
1905 be converted into pattern rules. We used to do this in
1906 install_default_implicit_rules, but since that happens after reading
1907 makefiles, it results in the built-in pattern rules taking precedence
1908 over makefile-specified suffix rules, which is wrong. */
1909
1910 install_default_suffix_rules ();
1911
1912 /* Define some internal and special variables. */
1913
1914 define_automatic_variables ();
1915
1916 /* Set up the MAKEFLAGS and MFLAGS variables
1917 so makefiles can look at them. */
1918
1919 define_makeflags (0, 0);
1920
1921 /* Define the default variables. */
1922 define_default_variables ();
1923
1924 default_file = enter_file (strcache_add (".DEFAULT"));
1925
1926 {
1927 struct variable *v = define_variable (".DEFAULT_GOAL", 13, "", o_file, 0);
1928 default_goal_name = &v->value;
1929 }
1930
1931 /* Read all the makefiles. */
1932
1933 read_makefiles
1934 = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1935
1936#ifdef WINDOWS32
1937 /* look one last time after reading all Makefiles */
1938 if (no_default_sh_exe)
1939 no_default_sh_exe = !find_and_set_default_shell(NULL);
1940#endif /* WINDOWS32 */
1941
1942#if defined (__MSDOS__) || defined (__EMX__)
1943 /* We need to know what kind of shell we will be using. */
1944 {
1945 extern int _is_unixy_shell (const char *_path);
1946 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1947 extern int unixy_shell;
1948 extern char *default_shell;
1949
1950 if (shv && *shv->value)
1951 {
1952 char *shell_path = recursively_expand(shv);
1953
1954 if (shell_path && _is_unixy_shell (shell_path))
1955 unixy_shell = 1;
1956 else
1957 unixy_shell = 0;
1958 if (shell_path)
1959 default_shell = shell_path;
1960 }
1961 }
1962#endif /* __MSDOS__ || __EMX__ */
1963
1964 /* Decode switches again, in case the variables were set by the makefile. */
1965 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1966#if 0
1967 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1968#endif
1969
1970#if defined (__MSDOS__) || defined (__EMX__)
1971 if (job_slots != 1
1972# ifdef __EMX__
1973 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1974# endif
1975 )
1976 {
1977 error (NILF,
1978 _("Parallel jobs (-j) are not supported on this platform."));
1979 error (NILF, _("Resetting to single job (-j1) mode."));
1980 job_slots = 1;
1981 }
1982#endif
1983
1984#ifdef MAKE_JOBSERVER
1985 /* If the jobserver-fds option is seen, make sure that -j is reasonable. */
1986
1987 if (jobserver_fds)
1988 {
1989 const char *cp;
1990 unsigned int ui;
1991
1992 for (ui=1; ui < jobserver_fds->idx; ++ui)
1993 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1994 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1995
1996 /* Now parse the fds string and make sure it has the proper format. */
1997
1998 cp = jobserver_fds->list[0];
1999
2000 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
2001 fatal (NILF,
2002 _("internal error: invalid --jobserver-fds string `%s'"), cp);
2003
2004 DB (DB_JOBS,
2005 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
2006
2007 /* The combination of a pipe + !job_slots means we're using the
2008 jobserver. If !job_slots and we don't have a pipe, we can start
2009 infinite jobs. If we see both a pipe and job_slots >0 that means the
2010 user set -j explicitly. This is broken; in this case obey the user
2011 (ignore the jobserver pipe for this make) but print a message. */
2012
2013 if (job_slots > 0)
2014 error (NILF,
2015 _("warning: -jN forced in submake: disabling jobserver mode."));
2016
2017 /* Create a duplicate pipe, that will be closed in the SIGCHLD
2018 handler. If this fails with EBADF, the parent has closed the pipe
2019 on us because it didn't think we were a submake. If so, print a
2020 warning then default to -j1. */
2021
2022 else if ((job_rfd = dup (job_fds[0])) < 0)
2023 {
2024 if (errno != EBADF)
2025 pfatal_with_name (_("dup jobserver"));
2026
2027 error (NILF,
2028 _("warning: jobserver unavailable: using -j1. Add `+' to parent make rule."));
2029 job_slots = 1;
2030 }
2031
2032 if (job_slots > 0)
2033 {
2034 close (job_fds[0]);
2035 close (job_fds[1]);
2036 job_fds[0] = job_fds[1] = -1;
2037 free (jobserver_fds->list);
2038 free (jobserver_fds);
2039 jobserver_fds = 0;
2040 }
2041 }
2042
2043 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
2044 Set up the pipe and install the fds option for our children. */
2045
2046 if (job_slots > 1)
2047 {
2048 char *cp;
2049 char c = '+';
2050
2051 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
2052 pfatal_with_name (_("creating jobs pipe"));
2053
2054 /* Every make assumes that it always has one job it can run. For the
2055 submakes it's the token they were given by their parent. For the
2056 top make, we just subtract one from the number the user wants. We
2057 want job_slots to be 0 to indicate we're using the jobserver. */
2058
2059 master_job_slots = job_slots;
2060
2061 while (--job_slots)
2062 {
2063 int r;
2064
2065 EINTRLOOP (r, write (job_fds[1], &c, 1));
2066 if (r != 1)
2067 pfatal_with_name (_("init jobserver pipe"));
2068 }
2069
2070 /* Fill in the jobserver_fds struct for our children. */
2071
2072 cp = xmalloc ((sizeof ("1024")*2)+1);
2073 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2074
2075 jobserver_fds = (struct stringlist *)
2076 xmalloc (sizeof (struct stringlist));
2077 jobserver_fds->list = xmalloc (sizeof (char *));
2078 jobserver_fds->list[0] = cp;
2079 jobserver_fds->idx = 1;
2080 jobserver_fds->max = 1;
2081 }
2082#endif
2083
2084#ifndef MAKE_SYMLINKS
2085 if (check_symlink_flag)
2086 {
2087 error (NILF, _("Symbolic links not supported: disabling -L."));
2088 check_symlink_flag = 0;
2089 }
2090#endif
2091
2092 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2093
2094 define_makeflags (1, 0);
2095
2096 /* Make each `struct dep' point at the `struct file' for the file
2097 depended on. Also do magic for special targets. */
2098
2099 snap_deps ();
2100
2101 /* Convert old-style suffix rules to pattern rules. It is important to
2102 do this before installing the built-in pattern rules below, so that
2103 makefile-specified suffix rules take precedence over built-in pattern
2104 rules. */
2105
2106 convert_to_pattern ();
2107
2108 /* Install the default implicit pattern rules.
2109 This used to be done before reading the makefiles.
2110 But in that case, built-in pattern rules were in the chain
2111 before user-defined ones, so they matched first. */
2112
2113 install_default_implicit_rules ();
2114
2115 /* Compute implicit rule limits. */
2116
2117 count_implicit_rule_limits ();
2118
2119 /* Construct the listings of directories in VPATH lists. */
2120
2121 build_vpath_lists ();
2122
2123 /* Mark files given with -o flags as very old and as having been updated
2124 already, and files given with -W flags as brand new (time-stamp as far
2125 as possible into the future). If restarts is set we'll do -W later. */
2126
2127 if (old_files != 0)
2128 {
2129 const char **p;
2130 for (p = old_files->list; *p != 0; ++p)
2131 {
2132 struct file *f = enter_file (*p);
2133 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2134 f->updated = 1;
2135 f->update_status = 0;
2136 f->command_state = cs_finished;
2137 }
2138 }
2139
2140 if (!restarts && new_files != 0)
2141 {
2142 const char **p;
2143 for (p = new_files->list; *p != 0; ++p)
2144 {
2145 struct file *f = enter_file (*p);
2146 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2147 }
2148 }
2149
2150 /* Initialize the remote job module. */
2151 remote_setup ();
2152
2153 if (read_makefiles != 0)
2154 {
2155 /* Update any makefiles if necessary. */
2156
2157 FILE_TIMESTAMP *makefile_mtimes = 0;
2158 unsigned int mm_idx = 0;
2159 char **nargv = argv;
2160 int nargc = argc;
2161 int orig_db_level = db_level;
2162 int status;
2163
2164 if (! ISDB (DB_MAKEFILES))
2165 db_level = DB_NONE;
2166
2167 DB (DB_BASIC, (_("Updating makefiles....\n")));
2168
2169 /* Remove any makefiles we don't want to try to update.
2170 Also record the current modtimes so we can compare them later. */
2171 {
2172 register struct dep *d, *last;
2173 last = 0;
2174 d = read_makefiles;
2175 while (d != 0)
2176 {
2177 struct file *f = d->file;
2178 if (f->double_colon)
2179 for (f = f->double_colon; f != NULL; f = f->prev)
2180 {
2181 if (f->deps == 0 && f->cmds != 0)
2182 {
2183 /* This makefile is a :: target with commands, but
2184 no dependencies. So, it will always be remade.
2185 This might well cause an infinite loop, so don't
2186 try to remake it. (This will only happen if
2187 your makefiles are written exceptionally
2188 stupidly; but if you work for Athena, that's how
2189 you write your makefiles.) */
2190
2191 DB (DB_VERBOSE,
2192 (_("Makefile `%s' might loop; not remaking it.\n"),
2193 f->name));
2194
2195 if (last == 0)
2196 read_makefiles = d->next;
2197 else
2198 last->next = d->next;
2199
2200 /* Free the storage. */
2201 free_dep (d);
2202
2203 d = last == 0 ? read_makefiles : last->next;
2204
2205 break;
2206 }
2207 }
2208 if (f == NULL || !f->double_colon)
2209 {
2210 makefile_mtimes = xrealloc (makefile_mtimes,
2211 (mm_idx+1)
2212 * sizeof (FILE_TIMESTAMP));
2213 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2214 last = d;
2215 d = d->next;
2216 }
2217 }
2218 }
2219
2220 /* Set up `MAKEFLAGS' specially while remaking makefiles. */
2221 define_makeflags (1, 1);
2222
2223 rebuilding_makefiles = 1;
2224 status = update_goal_chain (read_makefiles);
2225 rebuilding_makefiles = 0;
2226
2227 switch (status)
2228 {
2229 case 1:
2230 /* The only way this can happen is if the user specified -q and asked
2231 * for one of the makefiles to be remade as a target on the command
2232 * line. Since we're not actually updating anything with -q we can
2233 * treat this as "did nothing".
2234 */
2235
2236 case -1:
2237 /* Did nothing. */
2238 break;
2239
2240 case 2:
2241 /* Failed to update. Figure out if we care. */
2242 {
2243 /* Nonzero if any makefile was successfully remade. */
2244 int any_remade = 0;
2245 /* Nonzero if any makefile we care about failed
2246 in updating or could not be found at all. */
2247 int any_failed = 0;
2248 unsigned int i;
2249 struct dep *d;
2250
2251 for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
2252 {
2253 /* Reset the considered flag; we may need to look at the file
2254 again to print an error. */
2255 d->file->considered = 0;
2256
2257 if (d->file->updated)
2258 {
2259 /* This makefile was updated. */
2260 if (d->file->update_status == 0)
2261 {
2262 /* It was successfully updated. */
2263 any_remade |= (file_mtime_no_search (d->file)
2264 != makefile_mtimes[i]);
2265 }
2266 else if (! (d->changed & RM_DONTCARE))
2267 {
2268 FILE_TIMESTAMP mtime;
2269 /* The update failed and this makefile was not
2270 from the MAKEFILES variable, so we care. */
2271 error (NILF, _("Failed to remake makefile `%s'."),
2272 d->file->name);
2273 mtime = file_mtime_no_search (d->file);
2274 any_remade |= (mtime != NONEXISTENT_MTIME
2275 && mtime != makefile_mtimes[i]);
2276 makefile_status = MAKE_FAILURE;
2277 }
2278 }
2279 else
2280 /* This makefile was not found at all. */
2281 if (! (d->changed & RM_DONTCARE))
2282 {
2283 /* This is a makefile we care about. See how much. */
2284 if (d->changed & RM_INCLUDED)
2285 /* An included makefile. We don't need
2286 to die, but we do want to complain. */
2287 error (NILF,
2288 _("Included makefile `%s' was not found."),
2289 dep_name (d));
2290 else
2291 {
2292 /* A normal makefile. We must die later. */
2293 error (NILF, _("Makefile `%s' was not found"),
2294 dep_name (d));
2295 any_failed = 1;
2296 }
2297 }
2298 }
2299 /* Reset this to empty so we get the right error message below. */
2300 read_makefiles = 0;
2301
2302 if (any_remade)
2303 goto re_exec;
2304 if (any_failed)
2305 die (2);
2306 break;
2307 }
2308
2309 case 0:
2310 re_exec:
2311 /* Updated successfully. Re-exec ourselves. */
2312
2313 remove_intermediates (0);
2314
2315 if (print_data_base_flag)
2316 print_data_base ();
2317
2318 log_working_directory (0);
2319
2320 clean_jobserver (0);
2321
2322 if (makefiles != 0)
2323 {
2324 /* These names might have changed. */
2325 int i, j = 0;
2326 for (i = 1; i < argc; ++i)
2327 if (strneq (argv[i], "-f", 2)) /* XXX */
2328 {
2329 char *p = &argv[i][2];
2330 if (*p == '\0')
2331 /* This cast is OK since we never modify argv. */
2332 argv[++i] = (char *) makefiles->list[j];
2333 else
2334 argv[i] = xstrdup (concat ("-f", makefiles->list[j], ""));
2335 ++j;
2336 }
2337 }
2338
2339 /* Add -o option for the stdin temporary file, if necessary. */
2340 if (stdin_nm)
2341 {
2342 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2343 memcpy (nargv, argv, argc * sizeof (char *));
2344 nargv[nargc++] = xstrdup (concat ("-o", stdin_nm, ""));
2345 nargv[nargc] = 0;
2346 }
2347
2348 if (directories != 0 && directories->idx > 0)
2349 {
2350 int bad = 1;
2351 if (directory_before_chdir != 0)
2352 {
2353 if (chdir (directory_before_chdir) < 0)
2354 perror_with_name ("chdir", "");
2355 else
2356 bad = 0;
2357 }
2358 if (bad)
2359 fatal (NILF, _("Couldn't change back to original directory."));
2360 }
2361
2362 ++restarts;
2363
2364 if (ISDB (DB_BASIC))
2365 {
2366 char **p;
2367 printf (_("Re-executing[%u]:"), restarts);
2368 for (p = nargv; *p != 0; ++p)
2369 printf (" %s", *p);
2370 putchar ('\n');
2371 }
2372
2373#ifndef _AMIGA
2374 {
2375 char **p;
2376 for (p = environ; *p != 0; ++p)
2377 {
2378 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
2379 && (*p)[MAKELEVEL_LENGTH] == '=')
2380 {
2381 *p = alloca (40);
2382 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2383 }
2384 if (strneq (*p, "MAKE_RESTARTS=", 14))
2385 {
2386 *p = alloca (40);
2387 sprintf (*p, "MAKE_RESTARTS=%u", restarts);
2388 restarts = 0;
2389 }
2390 }
2391 }
2392#else /* AMIGA */
2393 {
2394 char buffer[256];
2395
2396 sprintf (buffer, "%u", makelevel);
2397 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2398
2399 sprintf (buffer, "%u", restarts);
2400 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2401 restarts = 0;
2402 }
2403#endif
2404
2405 /* If we didn't set the restarts variable yet, add it. */
2406 if (restarts)
2407 {
2408 char *b = alloca (40);
2409 sprintf (b, "MAKE_RESTARTS=%u", restarts);
2410 putenv (b);
2411 }
2412
2413 fflush (stdout);
2414 fflush (stderr);
2415
2416 /* Close the dup'd jobserver pipe if we opened one. */
2417 if (job_rfd >= 0)
2418 close (job_rfd);
2419
2420#ifdef _AMIGA
2421 exec_command (nargv);
2422 exit (0);
2423#elif defined (__EMX__)
2424 {
2425 /* It is not possible to use execve() here because this
2426 would cause the parent process to be terminated with
2427 exit code 0 before the child process has been terminated.
2428 Therefore it may be the best solution simply to spawn the
2429 child process including all file handles and to wait for its
2430 termination. */
2431 int pid;
2432 int status;
2433 pid = child_execute_job (0, 1, nargv, environ);
2434
2435 /* is this loop really necessary? */
2436 do {
2437 pid = wait (&status);
2438 } while (pid <= 0);
2439 /* use the exit code of the child process */
2440 exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
2441 }
2442#else
2443 exec_command (nargv, environ);
2444#endif
2445 /* NOTREACHED */
2446
2447 default:
2448#define BOGUS_UPDATE_STATUS 0
2449 assert (BOGUS_UPDATE_STATUS);
2450 break;
2451 }
2452
2453 db_level = orig_db_level;
2454
2455 /* Free the makefile mtimes (if we allocated any). */
2456 if (makefile_mtimes)
2457 free (makefile_mtimes);
2458 }
2459
2460 /* Set up `MAKEFLAGS' again for the normal targets. */
2461 define_makeflags (1, 0);
2462
2463 /* Set always_make_flag if -B was given. */
2464 always_make_flag = always_make_set;
2465
2466 /* If restarts is set we haven't set up -W files yet, so do that now. */
2467 if (restarts && new_files != 0)
2468 {
2469 const char **p;
2470 for (p = new_files->list; *p != 0; ++p)
2471 {
2472 struct file *f = enter_file (*p);
2473 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2474 }
2475 }
2476
2477 /* If there is a temp file from reading a makefile from stdin, get rid of
2478 it now. */
2479 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2480 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2481
2482 {
2483 int status;
2484
2485 /* If there were no command-line goals, use the default. */
2486 if (goals == 0)
2487 {
2488 if (**default_goal_name != '\0')
2489 {
2490 if (default_goal_file == 0 ||
2491 strcmp (*default_goal_name, default_goal_file->name) != 0)
2492 {
2493 default_goal_file = lookup_file (*default_goal_name);
2494
2495 /* In case user set .DEFAULT_GOAL to a non-existent target
2496 name let's just enter this name into the table and let
2497 the standard logic sort it out. */
2498 if (default_goal_file == 0)
2499 {
2500 struct nameseq *ns;
2501 char *p = *default_goal_name;
2502
2503 ns = multi_glob (
2504 parse_file_seq (&p, '\0', sizeof (struct nameseq), 1),
2505 sizeof (struct nameseq));
2506
2507 /* .DEFAULT_GOAL should contain one target. */
2508 if (ns->next != 0)
2509 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2510
2511 default_goal_file = enter_file (strcache_add (ns->name));
2512
2513 ns->name = 0; /* It was reused by enter_file(). */
2514 free_ns_chain (ns);
2515 }
2516 }
2517
2518 goals = alloc_dep ();
2519 goals->file = default_goal_file;
2520 }
2521 }
2522 else
2523 lastgoal->next = 0;
2524
2525
2526 if (!goals)
2527 {
2528 if (read_makefiles == 0)
2529 fatal (NILF, _("No targets specified and no makefile found"));
2530
2531 fatal (NILF, _("No targets"));
2532 }
2533
2534 /* Update the goals. */
2535
2536 DB (DB_BASIC, (_("Updating goal targets....\n")));
2537
2538 switch (update_goal_chain (goals))
2539 {
2540 case -1:
2541 /* Nothing happened. */
2542 case 0:
2543 /* Updated successfully. */
2544 status = makefile_status;
2545 break;
2546 case 1:
2547 /* We are under -q and would run some commands. */
2548 status = MAKE_TROUBLE;
2549 break;
2550 case 2:
2551 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2552 but in VMS, there is only success and failure. */
2553 status = MAKE_FAILURE;
2554 break;
2555 default:
2556 abort ();
2557 }
2558
2559 /* If we detected some clock skew, generate one last warning */
2560 if (clock_skew_detected)
2561 error (NILF,
2562 _("warning: Clock skew detected. Your build may be incomplete."));
2563
2564 /* Exit. */
2565 die (status);
2566 }
2567
2568 /* NOTREACHED */
2569 return 0;
2570}
2571
2572
2573/* Parsing of arguments, decoding of switches. */
2574
2575static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2576static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2577 (sizeof (long_option_aliases) /
2578 sizeof (long_option_aliases[0]))];
2579
2580/* Fill in the string and vector for getopt. */
2581static void
2582init_switches (void)
2583{
2584 char *p;
2585 unsigned int c;
2586 unsigned int i;
2587
2588 if (options[0] != '\0')
2589 /* Already done. */
2590 return;
2591
2592 p = options;
2593
2594 /* Return switch and non-switch args in order, regardless of
2595 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2596 *p++ = '-';
2597
2598 for (i = 0; switches[i].c != '\0'; ++i)
2599 {
2600 long_options[i].name = (switches[i].long_name == 0 ? "" :
2601 switches[i].long_name);
2602 long_options[i].flag = 0;
2603 long_options[i].val = switches[i].c;
2604 if (short_option (switches[i].c))
2605 *p++ = switches[i].c;
2606 switch (switches[i].type)
2607 {
2608 case flag:
2609 case flag_off:
2610 case ignore:
2611 long_options[i].has_arg = no_argument;
2612 break;
2613
2614 case string:
2615 case filename:
2616 case positive_int:
2617 case floating:
2618 if (short_option (switches[i].c))
2619 *p++ = ':';
2620 if (switches[i].noarg_value != 0)
2621 {
2622 if (short_option (switches[i].c))
2623 *p++ = ':';
2624 long_options[i].has_arg = optional_argument;
2625 }
2626 else
2627 long_options[i].has_arg = required_argument;
2628 break;
2629 }
2630 }
2631 *p = '\0';
2632 for (c = 0; c < (sizeof (long_option_aliases) /
2633 sizeof (long_option_aliases[0]));
2634 ++c)
2635 long_options[i++] = long_option_aliases[c];
2636 long_options[i].name = 0;
2637}
2638
2639static void
2640handle_non_switch_argument (char *arg, int env)
2641{
2642 /* Non-option argument. It might be a variable definition. */
2643 struct variable *v;
2644 if (arg[0] == '-' && arg[1] == '\0')
2645 /* Ignore plain `-' for compatibility. */
2646 return;
2647 v = try_variable_definition (0, arg, o_command, 0);
2648 if (v != 0)
2649 {
2650 /* It is indeed a variable definition. If we don't already have this
2651 one, record a pointer to the variable for later use in
2652 define_makeflags. */
2653 struct command_variable *cv;
2654
2655 for (cv = command_variables; cv != 0; cv = cv->next)
2656 if (cv->variable == v)
2657 break;
2658
2659 if (! cv) {
2660 cv = xmalloc (sizeof (*cv));
2661 cv->variable = v;
2662 cv->next = command_variables;
2663 command_variables = cv;
2664 }
2665 }
2666 else if (! env)
2667 {
2668 /* Not an option or variable definition; it must be a goal
2669 target! Enter it as a file and add it to the dep chain of
2670 goals. */
2671 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2672 f->cmd_target = 1;
2673
2674 if (goals == 0)
2675 {
2676 goals = alloc_dep ();
2677 lastgoal = goals;
2678 }
2679 else
2680 {
2681 lastgoal->next = alloc_dep ();
2682 lastgoal = lastgoal->next;
2683 }
2684
2685 lastgoal->file = f;
2686
2687 {
2688 /* Add this target name to the MAKECMDGOALS variable. */
2689 struct variable *gv;
2690 const char *value;
2691
2692 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2693 if (gv == 0)
2694 value = f->name;
2695 else
2696 {
2697 /* Paste the old and new values together */
2698 unsigned int oldlen, newlen;
2699 char *vp;
2700
2701 oldlen = strlen (gv->value);
2702 newlen = strlen (f->name);
2703 vp = alloca (oldlen + 1 + newlen + 1);
2704 memcpy (vp, gv->value, oldlen);
2705 vp[oldlen] = ' ';
2706 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2707 value = vp;
2708 }
2709 define_variable ("MAKECMDGOALS", 12, value, o_default, 0);
2710 }
2711 }
2712}
2713
2714/* Print a nice usage method. */
2715
2716static void
2717print_usage (int bad)
2718{
2719 const char *const *cpp;
2720 FILE *usageto;
2721
2722 if (print_version_flag)
2723 print_version ();
2724
2725 usageto = bad ? stderr : stdout;
2726
2727 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2728
2729 for (cpp = usage; *cpp; ++cpp)
2730 fputs (_(*cpp), usageto);
2731
2732#ifdef KMK
2733 if (!remote_description || *remote_description == '\0')
2734 printf (_("\nThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
2735 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2736 else
2737 printf (_("\nThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
2738 BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
2739#else /* !KMK */
2740 if (!remote_description || *remote_description == '\0')
2741 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2742 else
2743 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2744 make_host, remote_description);
2745#endif /* !KMK */
2746
2747 fprintf (usageto, _("Report bugs to <[email protected]>\n"));
2748}
2749
2750/* Decode switches from ARGC and ARGV.
2751 They came from the environment if ENV is nonzero. */
2752
2753static void
2754decode_switches (int argc, char **argv, int env)
2755{
2756 int bad = 0;
2757 register const struct command_switch *cs;
2758 register struct stringlist *sl;
2759 register int c;
2760
2761 /* getopt does most of the parsing for us.
2762 First, get its vectors set up. */
2763
2764 init_switches ();
2765
2766 /* Let getopt produce error messages for the command line,
2767 but not for options from the environment. */
2768 opterr = !env;
2769 /* Reset getopt's state. */
2770 optind = 0;
2771
2772 while (optind < argc)
2773 {
2774 /* Parse the next argument. */
2775 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2776 if (c == EOF)
2777 /* End of arguments, or "--" marker seen. */
2778 break;
2779 else if (c == 1)
2780 /* An argument not starting with a dash. */
2781 handle_non_switch_argument (optarg, env);
2782 else if (c == '?')
2783 /* Bad option. We will print a usage message and die later.
2784 But continue to parse the other options so the user can
2785 see all he did wrong. */
2786 bad = 1;
2787 else
2788 for (cs = switches; cs->c != '\0'; ++cs)
2789 if (cs->c == c)
2790 {
2791 /* Whether or not we will actually do anything with
2792 this switch. We test this individually inside the
2793 switch below rather than just once outside it, so that
2794 options which are to be ignored still consume args. */
2795 int doit = !env || cs->env;
2796
2797 switch (cs->type)
2798 {
2799 default:
2800 abort ();
2801
2802 case ignore:
2803 break;
2804
2805 case flag:
2806 case flag_off:
2807 if (doit)
2808 *(int *) cs->value_ptr = cs->type == flag;
2809 break;
2810
2811 case string:
2812 case filename:
2813 if (!doit)
2814 break;
2815
2816 if (optarg == 0)
2817 optarg = xstrdup (cs->noarg_value);
2818 else if (*optarg == '\0')
2819 {
2820 error (NILF, _("the `-%c' option requires a non-empty string argument"),
2821 cs->c);
2822 bad = 1;
2823 }
2824
2825 sl = *(struct stringlist **) cs->value_ptr;
2826 if (sl == 0)
2827 {
2828 sl = (struct stringlist *)
2829 xmalloc (sizeof (struct stringlist));
2830 sl->max = 5;
2831 sl->idx = 0;
2832 sl->list = xmalloc (5 * sizeof (char *));
2833 *(struct stringlist **) cs->value_ptr = sl;
2834 }
2835 else if (sl->idx == sl->max - 1)
2836 {
2837 sl->max += 5;
2838 sl->list = xrealloc ((void *)sl->list, /* bird */
2839 sl->max * sizeof (char *));
2840 }
2841 if (cs->type == filename)
2842 sl->list[sl->idx++] = expand_command_line_file (optarg);
2843 else
2844 sl->list[sl->idx++] = optarg;
2845 sl->list[sl->idx] = 0;
2846 break;
2847
2848 case positive_int:
2849 /* See if we have an option argument; if we do require that
2850 it's all digits, not something like "10foo". */
2851 if (optarg == 0 && argc > optind)
2852 {
2853 const char *cp;
2854 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2855 ;
2856 if (cp[0] == '\0')
2857 optarg = argv[optind++];
2858 }
2859
2860 if (!doit)
2861 break;
2862
2863 if (optarg != 0)
2864 {
2865 int i = atoi (optarg);
2866 const char *cp;
2867
2868 /* Yes, I realize we're repeating this in some cases. */
2869 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2870 ;
2871
2872 if (i < 1 || cp[0] != '\0')
2873 {
2874 error (NILF, _("the `-%c' option requires a positive integral argument"),
2875 cs->c);
2876 bad = 1;
2877 }
2878 else
2879 *(unsigned int *) cs->value_ptr = i;
2880 }
2881 else
2882 *(unsigned int *) cs->value_ptr
2883 = *(unsigned int *) cs->noarg_value;
2884 break;
2885
2886#ifndef NO_FLOAT
2887 case floating:
2888 if (optarg == 0 && optind < argc
2889 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2890 optarg = argv[optind++];
2891
2892 if (doit)
2893 *(double *) cs->value_ptr
2894 = (optarg != 0 ? atof (optarg)
2895 : *(double *) cs->noarg_value);
2896
2897 break;
2898#endif
2899 }
2900
2901 /* We've found the switch. Stop looking. */
2902 break;
2903 }
2904 }
2905
2906 /* There are no more options according to getting getopt, but there may
2907 be some arguments left. Since we have asked for non-option arguments
2908 to be returned in order, this only happens when there is a "--"
2909 argument to prevent later arguments from being options. */
2910 while (optind < argc)
2911 handle_non_switch_argument (argv[optind++], env);
2912
2913
2914 if (!env && (bad || print_usage_flag))
2915 {
2916 print_usage (bad);
2917 die (bad ? 2 : 0);
2918 }
2919}
2920
2921/* Decode switches from environment variable ENVAR (which is LEN chars long).
2922 We do this by chopping the value into a vector of words, prepending a
2923 dash to the first word if it lacks one, and passing the vector to
2924 decode_switches. */
2925
2926static void
2927decode_env_switches (char *envar, unsigned int len)
2928{
2929 char *varref = alloca (2 + len + 2);
2930 char *value, *p;
2931 int argc;
2932 char **argv;
2933
2934 /* Get the variable's value. */
2935 varref[0] = '$';
2936 varref[1] = '(';
2937 memcpy (&varref[2], envar, len);
2938 varref[2 + len] = ')';
2939 varref[2 + len + 1] = '\0';
2940 value = variable_expand (varref);
2941
2942 /* Skip whitespace, and check for an empty value. */
2943 value = next_token (value);
2944 len = strlen (value);
2945 if (len == 0)
2946 return;
2947
2948 /* Allocate a vector that is definitely big enough. */
2949 argv = alloca ((1 + len + 1) * sizeof (char *));
2950
2951 /* Allocate a buffer to copy the value into while we split it into words
2952 and unquote it. We must use permanent storage for this because
2953 decode_switches may store pointers into the passed argument words. */
2954 p = xmalloc (2 * len);
2955
2956 /* getopt will look at the arguments starting at ARGV[1].
2957 Prepend a spacer word. */
2958 argv[0] = 0;
2959 argc = 1;
2960 argv[argc] = p;
2961 while (*value != '\0')
2962 {
2963 if (*value == '\\' && value[1] != '\0')
2964 ++value; /* Skip the backslash. */
2965 else if (isblank ((unsigned char)*value))
2966 {
2967 /* End of the word. */
2968 *p++ = '\0';
2969 argv[++argc] = p;
2970 do
2971 ++value;
2972 while (isblank ((unsigned char)*value));
2973 continue;
2974 }
2975 *p++ = *value++;
2976 }
2977 *p = '\0';
2978 argv[++argc] = 0;
2979
2980 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2981 /* The first word doesn't start with a dash and isn't a variable
2982 definition. Add a dash and pass it along to decode_switches. We
2983 need permanent storage for this in case decode_switches saves
2984 pointers into the value. */
2985 argv[1] = xstrdup (concat ("-", argv[1], ""));
2986
2987 /* Parse those words. */
2988 decode_switches (argc, argv, 1);
2989}
2990
2991
2992/* Quote the string IN so that it will be interpreted as a single word with
2993 no magic by decode_env_switches; also double dollar signs to avoid
2994 variable expansion in make itself. Write the result into OUT, returning
2995 the address of the next character to be written.
2996 Allocating space for OUT twice the length of IN is always sufficient. */
2997
2998static char *
2999quote_for_env (char *out, const char *in)
3000{
3001 while (*in != '\0')
3002 {
3003 if (*in == '$')
3004 *out++ = '$';
3005 else if (isblank ((unsigned char)*in) || *in == '\\')
3006 *out++ = '\\';
3007 *out++ = *in++;
3008 }
3009
3010 return out;
3011}
3012
3013/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3014 command switches. Include options with args if ALL is nonzero.
3015 Don't include options with the `no_makefile' flag set if MAKEFILE. */
3016
3017static void
3018define_makeflags (int all, int makefile)
3019{
3020 static const char ref[] = "$(MAKEOVERRIDES)";
3021 static const char posixref[] = "$(-*-command-variables-*-)";
3022 register const struct command_switch *cs;
3023 char *flagstring;
3024 register char *p;
3025 unsigned int words;
3026 struct variable *v;
3027
3028 /* We will construct a linked list of `struct flag's describing
3029 all the flags which need to go in MAKEFLAGS. Then, once we
3030 know how many there are and their lengths, we can put them all
3031 together in a string. */
3032
3033 struct flag
3034 {
3035 struct flag *next;
3036 const struct command_switch *cs;
3037 const char *arg;
3038 };
3039 struct flag *flags = 0;
3040 unsigned int flagslen = 0;
3041#define ADD_FLAG(ARG, LEN) \
3042 do { \
3043 struct flag *new = alloca (sizeof (struct flag)); \
3044 new->cs = cs; \
3045 new->arg = (ARG); \
3046 new->next = flags; \
3047 flags = new; \
3048 if (new->arg == 0) \
3049 ++flagslen; /* Just a single flag letter. */ \
3050 else \
3051 flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */ \
3052 if (!short_option (cs->c)) \
3053 /* This switch has no single-letter version, so we use the long. */ \
3054 flagslen += 2 + strlen (cs->long_name); \
3055 } while (0)
3056
3057 for (cs = switches; cs->c != '\0'; ++cs)
3058 if (cs->toenv && (!makefile || !cs->no_makefile))
3059 switch (cs->type)
3060 {
3061 case ignore:
3062 break;
3063
3064 case flag:
3065 case flag_off:
3066 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3067 && (cs->default_value == 0
3068 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3069 ADD_FLAG (0, 0);
3070 break;
3071
3072 case positive_int:
3073 if (all)
3074 {
3075 if ((cs->default_value != 0
3076 && (*(unsigned int *) cs->value_ptr
3077 == *(unsigned int *) cs->default_value)))
3078 break;
3079 else if (cs->noarg_value != 0
3080 && (*(unsigned int *) cs->value_ptr ==
3081 *(unsigned int *) cs->noarg_value))
3082 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3083#if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
3084 else if (cs->c == 'j')
3085 /* Special case for `-j'. */
3086 ADD_FLAG ("1", 1);
3087#endif
3088 else
3089 {
3090 char *buf = alloca (30);
3091 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3092 ADD_FLAG (buf, strlen (buf));
3093 }
3094 }
3095 break;
3096
3097#ifndef NO_FLOAT
3098 case floating:
3099 if (all)
3100 {
3101 if (cs->default_value != 0
3102 && (*(double *) cs->value_ptr
3103 == *(double *) cs->default_value))
3104 break;
3105 else if (cs->noarg_value != 0
3106 && (*(double *) cs->value_ptr
3107 == *(double *) cs->noarg_value))
3108 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3109 else
3110 {
3111 char *buf = alloca (100);
3112 sprintf (buf, "%g", *(double *) cs->value_ptr);
3113 ADD_FLAG (buf, strlen (buf));
3114 }
3115 }
3116 break;
3117#endif
3118
3119 case filename:
3120 case string:
3121 if (all)
3122 {
3123 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3124 if (sl != 0)
3125 {
3126 /* Add the elements in reverse order, because all the flags
3127 get reversed below; and the order matters for some
3128 switches (like -I). */
3129 unsigned int i = sl->idx;
3130 while (i-- > 0)
3131 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3132 }
3133 }
3134 break;
3135
3136 default:
3137 abort ();
3138 }
3139
3140 flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ". */
3141
3142#undef ADD_FLAG
3143
3144 /* Construct the value in FLAGSTRING.
3145 We allocate enough space for a preceding dash and trailing null. */
3146 flagstring = alloca (1 + flagslen + 1);
3147 memset (flagstring, '\0', 1 + flagslen + 1);
3148 p = flagstring;
3149 words = 1;
3150 *p++ = '-';
3151 while (flags != 0)
3152 {
3153 /* Add the flag letter or name to the string. */
3154 if (short_option (flags->cs->c))
3155 *p++ = flags->cs->c;
3156 else
3157 {
3158 if (*p != '-')
3159 {
3160 *p++ = ' ';
3161 *p++ = '-';
3162 }
3163 *p++ = '-';
3164 strcpy (p, flags->cs->long_name);
3165 p += strlen (p);
3166 }
3167 if (flags->arg != 0)
3168 {
3169 /* A flag that takes an optional argument which in this case is
3170 omitted is specified by ARG being "". We must distinguish
3171 because a following flag appended without an intervening " -"
3172 is considered the arg for the first. */
3173 if (flags->arg[0] != '\0')
3174 {
3175 /* Add its argument too. */
3176 *p++ = !short_option (flags->cs->c) ? '=' : ' ';
3177 p = quote_for_env (p, flags->arg);
3178 }
3179 ++words;
3180 /* Write a following space and dash, for the next flag. */
3181 *p++ = ' ';
3182 *p++ = '-';
3183 }
3184 else if (!short_option (flags->cs->c))
3185 {
3186 ++words;
3187 /* Long options must each go in their own word,
3188 so we write the following space and dash. */
3189 *p++ = ' ';
3190 *p++ = '-';
3191 }
3192 flags = flags->next;
3193 }
3194
3195 /* Define MFLAGS before appending variable definitions. */
3196
3197 if (p == &flagstring[1])
3198 /* No flags. */
3199 flagstring[0] = '\0';
3200 else if (p[-1] == '-')
3201 {
3202 /* Kill the final space and dash. */
3203 p -= 2;
3204 *p = '\0';
3205 }
3206 else
3207 /* Terminate the string. */
3208 *p = '\0';
3209
3210 /* Since MFLAGS is not parsed for flags, there is no reason to
3211 override any makefile redefinition. */
3212 (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
3213
3214 if (all && command_variables != 0)
3215 {
3216 /* Now write a reference to $(MAKEOVERRIDES), which contains all the
3217 command-line variable definitions. */
3218
3219 if (p == &flagstring[1])
3220 /* No flags written, so elide the leading dash already written. */
3221 p = flagstring;
3222 else
3223 {
3224 /* Separate the variables from the switches with a "--" arg. */
3225 if (p[-1] != '-')
3226 {
3227 /* We did not already write a trailing " -". */
3228 *p++ = ' ';
3229 *p++ = '-';
3230 }
3231 /* There is a trailing " -"; fill it out to " -- ". */
3232 *p++ = '-';
3233 *p++ = ' ';
3234 }
3235
3236 /* Copy in the string. */
3237 if (posix_pedantic)
3238 {
3239 memcpy (p, posixref, sizeof posixref - 1);
3240 p += sizeof posixref - 1;
3241 }
3242 else
3243 {
3244 memcpy (p, ref, sizeof ref - 1);
3245 p += sizeof ref - 1;
3246 }
3247 }
3248 else if (p == &flagstring[1])
3249 {
3250 words = 0;
3251 --p;
3252 }
3253 else if (p[-1] == '-')
3254 /* Kill the final space and dash. */
3255 p -= 2;
3256 /* Terminate the string. */
3257 *p = '\0';
3258
3259 v = define_variable ("MAKEFLAGS", 9,
3260 /* If there are switches, omit the leading dash
3261 unless it is a single long option with two
3262 leading dashes. */
3263 &flagstring[(flagstring[0] == '-'
3264 && flagstring[1] != '-')
3265 ? 1 : 0],
3266 /* This used to use o_env, but that lost when a
3267 makefile defined MAKEFLAGS. Makefiles set
3268 MAKEFLAGS to add switches, but we still want
3269 to redefine its value with the full set of
3270 switches. Of course, an override or command
3271 definition will still take precedence. */
3272 o_file, 1);
3273 if (! all)
3274 /* The first time we are called, set MAKEFLAGS to always be exported.
3275 We should not do this again on the second call, because that is
3276 after reading makefiles which might have done `unexport MAKEFLAGS'. */
3277 v->export = v_export;
3278}
3279
3280
3281/* Print version information. */
3282
3283static void
3284print_version (void)
3285{
3286 static int printed_version = 0;
3287
3288 char *precede = print_data_base_flag ? "# " : "";
3289
3290 if (printed_version)
3291 /* Do it only once. */
3292 return;
3293
3294 /* Print this untranslated. The coding standards recommend translating the
3295 (C) to the copyright symbol, but this string is going to change every
3296 year, and none of the rest of it should be translated (including the
3297 word "Copyright", so it hardly seems worth it. */
3298
3299#ifdef KMK
3300 printf ("%skmk - kBuild version %d.%d.%d\n\
3301\n\
3302%sBased on GNU Make %s:\n\
3303%s Copyright (C) 2006 Free Software Foundation, Inc.\n\
3304\n\
3305%skBuild modifications:\n\
3306%s Copyright (C) 2005-2007 Knut St. Osmundsen.\n\
3307\n\
3308%skmkbuiltin commands derived from *BSD sources:\n\
3309%s Copyright (c) 1983 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994\n\
3310%s The Regents of the University of California. All rights reserved.\n\
3311%s Copyright (c) 1998 Todd C. Miller <[email protected]>\n\
3312%s\n",
3313 precede, KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR, KBUILD_VERSION_PATCH,
3314 precede, version_string,
3315 precede, precede, precede, precede, precede, precede, precede, precede);
3316#else
3317 printf ("%sGNU Make %s\n\
3318%sCopyright (C) 2006 Free Software Foundation, Inc.\n",
3319 precede, version_string, precede);
3320#endif
3321
3322 printf (_("%sThis is free software; see the source for copying conditions.\n\
3323%sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
3324%sPARTICULAR PURPOSE.\n"),
3325 precede, precede, precede);
3326
3327#ifdef KMK
3328# ifdef PATH_KBUILD
3329 printf (_("%s\n\
3330%sPATH_KBUILD: '%s' (default '%s')\n\
3331%sPATH_KBUILD_BIN: '%s' (default '%s')\n"),
3332 precede,
3333 precede, get_path_kbuild(), PATH_KBUILD,
3334 precede, get_path_kbuild_bin(), PATH_KBUILD_BIN);
3335# else /* !PATH_KBUILD */
3336 printf (_("%s\n\
3337%sPATH_KBUILD: '%s'\n\
3338%sPATH_KBUILD_BIN: '%s'\n"),
3339 precede,
3340 precede, get_path_kbuild(),
3341 precede, get_path_kbuild_bin());
3342# endif /* !PATH_KBUILD */
3343 if (!remote_description || *remote_description == '\0')
3344 printf (_("\n%sThis program is built for %s/%s/%s [" __DATE__ " " __TIME__ "]\n"),
3345 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3346 else
3347 printf (_("\n%sThis program is built for %s/%s/%s (%s) [" __DATE__ " " __TIME__ "]\n"),
3348 precede, BUILD_PLATFORM, BUILD_PLATFORM_ARCH, BUILD_PLATFORM_CPU, remote_description);
3349#else
3350 if (!remote_description || *remote_description == '\0')
3351 printf (_("\n%sThis program built for %s\n"), precede, make_host);
3352 else
3353 printf (_("\n%sThis program built for %s (%s)\n"),
3354 precede, make_host, remote_description);
3355#endif
3356
3357 printed_version = 1;
3358
3359 /* Flush stdout so the user doesn't have to wait to see the
3360 version information while things are thought about. */
3361 fflush (stdout);
3362}
3363
3364/* Print a bunch of information about this and that. */
3365
3366static void
3367print_data_base ()
3368{
3369 time_t when;
3370
3371 when = time ((time_t *) 0);
3372 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3373
3374 print_variable_data_base ();
3375 print_dir_data_base ();
3376 print_rule_data_base ();
3377 print_file_data_base ();
3378 print_vpath_data_base ();
3379 strcache_print_stats ("#");
3380
3381 when = time ((time_t *) 0);
3382 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3383}
3384
3385static void
3386clean_jobserver (int status)
3387{
3388 char token = '+';
3389
3390 /* Sanity: have we written all our jobserver tokens back? If our
3391 exit status is 2 that means some kind of syntax error; we might not
3392 have written all our tokens so do that now. If tokens are left
3393 after any other error code, that's bad. */
3394
3395 if (job_fds[0] != -1 && jobserver_tokens)
3396 {
3397 if (status != 2)
3398 error (NILF,
3399 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3400 jobserver_tokens);
3401 else
3402 while (jobserver_tokens--)
3403 {
3404 int r;
3405
3406 EINTRLOOP (r, write (job_fds[1], &token, 1));
3407 if (r != 1)
3408 perror_with_name ("write", "");
3409 }
3410 }
3411
3412
3413 /* Sanity: If we're the master, were all the tokens written back? */
3414
3415 if (master_job_slots)
3416 {
3417 /* We didn't write one for ourself, so start at 1. */
3418 unsigned int tcnt = 1;
3419
3420 /* Close the write side, so the read() won't hang. */
3421 close (job_fds[1]);
3422
3423 while (read (job_fds[0], &token, 1) == 1)
3424 ++tcnt;
3425
3426 if (tcnt != master_job_slots)
3427 error (NILF,
3428 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3429 tcnt, master_job_slots);
3430
3431 close (job_fds[0]);
3432 }
3433}
3434
3435
3436/* Exit with STATUS, cleaning up as necessary. */
3437
3438void
3439die (int status)
3440{
3441 static char dying = 0;
3442
3443 if (!dying)
3444 {
3445 int err;
3446
3447 dying = 1;
3448
3449 if (print_version_flag)
3450 print_version ();
3451
3452 /* Wait for children to die. */
3453 err = (status != 0);
3454 while (job_slots_used > 0)
3455 reap_children (1, err);
3456
3457 /* Let the remote job module clean up its state. */
3458 remote_cleanup ();
3459
3460 /* Remove the intermediate files. */
3461 remove_intermediates (0);
3462
3463 if (print_data_base_flag)
3464 print_data_base ();
3465
3466 verify_file_data_base ();
3467
3468 clean_jobserver (status);
3469
3470 /* Try to move back to the original directory. This is essential on
3471 MS-DOS (where there is really only one process), and on Unix it
3472 puts core files in the original directory instead of the -C
3473 directory. Must wait until after remove_intermediates(), or unlinks
3474 of relative pathnames fail. */
3475 if (directory_before_chdir != 0)
3476 chdir (directory_before_chdir);
3477
3478 log_working_directory (0);
3479 }
3480
3481 exit (status);
3482}
3483
3484
3485/* Write a message indicating that we've just entered or
3486 left (according to ENTERING) the current directory. */
3487
3488void
3489log_working_directory (int entering)
3490{
3491 static int entered = 0;
3492
3493 /* Print nothing without the flag. Don't print the entering message
3494 again if we already have. Don't print the leaving message if we
3495 haven't printed the entering message. */
3496 if (! print_directory_flag || entering == entered)
3497 return;
3498
3499 entered = entering;
3500
3501 if (print_data_base_flag)
3502 fputs ("# ", stdout);
3503
3504 /* Use entire sentences to give the translators a fighting chance. */
3505
3506 if (makelevel == 0)
3507 if (starting_directory == 0)
3508 if (entering)
3509 printf (_("%s: Entering an unknown directory\n"), program);
3510 else
3511 printf (_("%s: Leaving an unknown directory\n"), program);
3512 else
3513 if (entering)
3514 printf (_("%s: Entering directory `%s'\n"),
3515 program, starting_directory);
3516 else
3517 printf (_("%s: Leaving directory `%s'\n"),
3518 program, starting_directory);
3519 else
3520 if (starting_directory == 0)
3521 if (entering)
3522 printf (_("%s[%u]: Entering an unknown directory\n"),
3523 program, makelevel);
3524 else
3525 printf (_("%s[%u]: Leaving an unknown directory\n"),
3526 program, makelevel);
3527 else
3528 if (entering)
3529 printf (_("%s[%u]: Entering directory `%s'\n"),
3530 program, makelevel, starting_directory);
3531 else
3532 printf (_("%s[%u]: Leaving directory `%s'\n"),
3533 program, makelevel, starting_directory);
3534
3535 /* Flush stdout to be sure this comes before any stderr output. */
3536 fflush (stdout);
3537}
Note: See TracBrowser for help on using the repository browser.

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