VirtualBox

source: kBuild/trunk/src/gmakenew/main.c@ 917

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

PATH_KBUILD and PATH_KBUILD_BIN improvements. Avoid LOCALEDIR, ALIASDIR, LIBDIR and INCLUDEDIR.

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

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