source: trunk/src/gmake/main.c@ 217

Last change on this file since 217 was 217, checked in by bird, 20 years ago

More proper .NOTPARALLEL.

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