VirtualBox

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

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

Fixed --affinity and corrected --priority help.

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

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