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

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

fixed argument mixup. added help for kmk options.

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