source: trunk/src/kmk/main.c@ 1864

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

kmk: use alloc caches for variables, variable sets and varaible set lists.

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