VirtualBox

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

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

Added an --affinity option.

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

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