Add a new variable: MAKE_RESTARTS, to count how many times make has re-exec'd.
[make.git] / read.c
blob40ff986bbba8961f79c12b0d8f5b551c40606c3a
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
23 #include <assert.h>
25 #include <glob.h>
27 #include "dep.h"
28 #include "filedef.h"
29 #include "job.h"
30 #include "commands.h"
31 #include "variable.h"
32 #include "rule.h"
33 #include "debug.h"
34 #include "hash.h"
37 #ifndef WINDOWS32
38 #ifndef _AMIGA
39 #ifndef VMS
40 #include <pwd.h>
41 #else
42 struct passwd *getpwnam PARAMS ((char *name));
43 #endif
44 #endif
45 #endif /* !WINDOWS32 */
47 /* A 'struct ebuffer' controls the origin of the makefile we are currently
48 eval'ing.
51 struct ebuffer
53 char *buffer; /* Start of the current line in the buffer. */
54 char *bufnext; /* Start of the next line in the buffer. */
55 char *bufstart; /* Start of the entire buffer. */
56 unsigned int size; /* Malloc'd size of buffer. */
57 FILE *fp; /* File, or NULL if this is an internal buffer. */
58 struct floc floc; /* Info on the file in fp (if any). */
61 /* Types of "words" that can be read in a makefile. */
62 enum make_word_type
64 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
65 w_varassign
69 /* A `struct conditionals' contains the information describing
70 all the active conditionals in a makefile.
72 The global variable `conditionals' contains the conditionals
73 information for the current makefile. It is initialized from
74 the static structure `toplevel_conditionals' and is later changed
75 to new structures for included makefiles. */
77 struct conditionals
79 unsigned int if_cmds; /* Depth of conditional nesting. */
80 unsigned int allocated; /* Elts allocated in following arrays. */
81 char *ignoring; /* Are we ignoring or interpreting?
82 0=interpreting, 1=not yet interpreted,
83 2=already interpreted */
84 char *seen_else; /* Have we already seen an `else'? */
87 static struct conditionals toplevel_conditionals;
88 static struct conditionals *conditionals = &toplevel_conditionals;
91 /* Default directories to search for include files in */
93 static char *default_include_directories[] =
95 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
97 * This completely up to the user when they install MSVC or other packages.
98 * This is defined as a placeholder.
100 #define INCLUDEDIR "."
101 #endif
102 INCLUDEDIR,
103 #ifndef _AMIGA
104 "/usr/gnu/include",
105 "/usr/local/include",
106 "/usr/include",
107 #endif
111 /* List of directories to search for include files in */
113 static char **include_directories;
115 /* Maximum length of an element of the above. */
117 static unsigned int max_incl_len;
119 /* The filename and pointer to line number of the
120 makefile currently being read in. */
122 const struct floc *reading_file = 0;
124 /* The chain of makefiles read by read_makefile. */
126 static struct dep *read_makefiles = 0;
128 static int eval_makefile PARAMS ((char *filename, int flags));
129 static int eval PARAMS ((struct ebuffer *buffer, int flags));
131 static long readline PARAMS ((struct ebuffer *ebuf));
132 static void do_define PARAMS ((char *name, unsigned int namelen,
133 enum variable_origin origin,
134 struct ebuffer *ebuf));
135 static int conditional_line PARAMS ((char *line, int len, const struct floc *flocp));
136 static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
137 struct dep *deps, unsigned int cmds_started, char *commands,
138 unsigned int commands_idx, int two_colon,
139 const struct floc *flocp));
140 static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
141 enum variable_origin origin,
142 int enabled,
143 const struct floc *flocp));
144 static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
145 char **startp, unsigned int *length));
147 /* Read in all the makefiles and return the chain of their names. */
149 struct dep *
150 read_all_makefiles (char **makefiles)
152 unsigned int num_makefiles = 0;
154 /* Create *_LIST variables, to hold the makefiles, targets, and variables
155 we will be reading. */
157 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
159 DB (DB_BASIC, (_("Reading makefiles...\n")));
161 /* If there's a non-null variable MAKEFILES, its value is a list of
162 files to read first thing. But don't let it prevent reading the
163 default makefiles and don't let the default goal come from there. */
166 char *value;
167 char *name, *p;
168 unsigned int length;
171 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
172 int save = warn_undefined_variables_flag;
173 warn_undefined_variables_flag = 0;
175 value = allocated_variable_expand ("$(MAKEFILES)");
177 warn_undefined_variables_flag = save;
180 /* Set NAME to the start of next token and LENGTH to its length.
181 MAKEFILES is updated for finding remaining tokens. */
182 p = value;
184 while ((name = find_next_token (&p, &length)) != 0)
186 if (*p != '\0')
187 *p++ = '\0';
188 name = xstrdup (name);
189 if (eval_makefile (name,
190 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
191 free (name);
194 free (value);
197 /* Read makefiles specified with -f switches. */
199 if (makefiles != 0)
200 while (*makefiles != 0)
202 struct dep *tail = read_makefiles;
203 register struct dep *d;
205 if (! eval_makefile (*makefiles, 0))
206 perror_with_name ("", *makefiles);
208 /* Find the right element of read_makefiles. */
209 d = read_makefiles;
210 while (d->next != tail)
211 d = d->next;
213 /* Use the storage read_makefile allocates. */
214 *makefiles = dep_name (d);
215 ++num_makefiles;
216 ++makefiles;
219 /* If there were no -f switches, try the default names. */
221 if (num_makefiles == 0)
223 static char *default_makefiles[] =
224 #ifdef VMS
225 /* all lower case since readdir() (the vms version) 'lowercasifies' */
226 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
227 #else
228 #ifdef _AMIGA
229 { "GNUmakefile", "Makefile", "SMakefile", 0 };
230 #else /* !Amiga && !VMS */
231 { "GNUmakefile", "makefile", "Makefile", 0 };
232 #endif /* AMIGA */
233 #endif /* VMS */
234 register char **p = default_makefiles;
235 while (*p != 0 && !file_exists_p (*p))
236 ++p;
238 if (*p != 0)
240 if (! eval_makefile (*p, 0))
241 perror_with_name ("", *p);
243 else
245 /* No default makefile was found. Add the default makefiles to the
246 `read_makefiles' chain so they will be updated if possible. */
247 struct dep *tail = read_makefiles;
248 /* Add them to the tail, after any MAKEFILES variable makefiles. */
249 while (tail != 0 && tail->next != 0)
250 tail = tail->next;
251 for (p = default_makefiles; *p != 0; ++p)
253 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
254 d->name = 0;
255 d->file = enter_file (*p);
256 d->file->dontcare = 1;
257 d->ignore_mtime = 0;
258 d->need_2nd_expansion = 0;
259 /* Tell update_goal_chain to bail out as soon as this file is
260 made, and main not to die if we can't make this file. */
261 d->changed = RM_DONTCARE;
262 if (tail == 0)
263 read_makefiles = d;
264 else
265 tail->next = d;
266 tail = d;
268 if (tail != 0)
269 tail->next = 0;
273 return read_makefiles;
276 /* Install a new conditional and return the previous one. */
278 static struct conditionals *
279 install_conditionals (struct conditionals *new)
281 struct conditionals *save = conditionals;
283 bzero ((char *) new, sizeof (*new));
284 conditionals = new;
286 return save;
289 /* Free the current conditionals and reinstate a saved one. */
291 static void
292 restore_conditionals (struct conditionals *saved)
294 /* Free any space allocated by conditional_line. */
295 if (conditionals->ignoring)
296 free (conditionals->ignoring);
297 if (conditionals->seen_else)
298 free (conditionals->seen_else);
300 /* Restore state. */
301 conditionals = saved;
304 static int
305 eval_makefile (char *filename, int flags)
307 struct dep *deps;
308 struct ebuffer ebuf;
309 const struct floc *curfile;
310 int makefile_errno;
311 int r;
313 ebuf.floc.filenm = filename;
314 ebuf.floc.lineno = 1;
316 if (ISDB (DB_VERBOSE))
318 printf (_("Reading makefile `%s'"), filename);
319 if (flags & RM_NO_DEFAULT_GOAL)
320 printf (_(" (no default goal)"));
321 if (flags & RM_INCLUDED)
322 printf (_(" (search path)"));
323 if (flags & RM_DONTCARE)
324 printf (_(" (don't care)"));
325 if (flags & RM_NO_TILDE)
326 printf (_(" (no ~ expansion)"));
327 puts ("...");
330 /* First, get a stream to read. */
332 /* Expand ~ in FILENAME unless it came from `include',
333 in which case it was already done. */
334 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
336 char *expanded = tilde_expand (filename);
337 if (expanded != 0)
338 filename = expanded;
341 ebuf.fp = fopen (filename, "r");
342 /* Save the error code so we print the right message later. */
343 makefile_errno = errno;
345 /* If the makefile wasn't found and it's either a makefile from
346 the `MAKEFILES' variable or an included makefile,
347 search the included makefile search path for this makefile. */
348 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
350 register unsigned int i;
351 for (i = 0; include_directories[i] != 0; ++i)
353 char *name = concat (include_directories[i], "/", filename);
354 ebuf.fp = fopen (name, "r");
355 if (ebuf.fp == 0)
356 free (name);
357 else
359 filename = name;
360 break;
365 /* Add FILENAME to the chain of read makefiles. */
366 deps = (struct dep *) xmalloc (sizeof (struct dep));
367 deps->next = read_makefiles;
368 read_makefiles = deps;
369 deps->name = 0;
370 deps->file = lookup_file (filename);
371 if (deps->file == 0)
372 deps->file = enter_file (xstrdup (filename));
373 if (filename != ebuf.floc.filenm)
374 free (filename);
375 filename = deps->file->name;
376 deps->changed = flags;
377 deps->ignore_mtime = 0;
378 deps->need_2nd_expansion = 0;
379 if (flags & RM_DONTCARE)
380 deps->file->dontcare = 1;
382 /* If the makefile can't be found at all, give up entirely. */
384 if (ebuf.fp == 0)
386 /* If we did some searching, errno has the error from the last
387 attempt, rather from FILENAME itself. Restore it in case the
388 caller wants to use it in a message. */
389 errno = makefile_errno;
390 return 0;
393 /* Add this makefile to the list. */
394 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
395 f_append, 0);
397 /* Evaluate the makefile */
399 ebuf.size = 200;
400 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
402 curfile = reading_file;
403 reading_file = &ebuf.floc;
405 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
407 reading_file = curfile;
409 fclose (ebuf.fp);
411 free (ebuf.bufstart);
412 alloca (0);
413 return r;
417 eval_buffer (char *buffer)
419 struct ebuffer ebuf;
420 struct conditionals *saved;
421 struct conditionals new;
422 const struct floc *curfile;
423 int r;
425 /* Evaluate the buffer */
427 ebuf.size = strlen (buffer);
428 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
429 ebuf.fp = NULL;
431 ebuf.floc = *reading_file;
433 curfile = reading_file;
434 reading_file = &ebuf.floc;
436 saved = install_conditionals (&new);
438 r = eval (&ebuf, 1);
440 restore_conditionals (saved);
442 reading_file = curfile;
444 alloca (0);
445 return r;
449 /* Read file FILENAME as a makefile and add its contents to the data base.
451 SET_DEFAULT is true if we are allowed to set the default goal. */
454 static int
455 eval (struct ebuffer *ebuf, int set_default)
457 char *collapsed = 0;
458 unsigned int collapsed_length = 0;
459 unsigned int commands_len = 200;
460 char *commands;
461 unsigned int commands_idx = 0;
462 unsigned int cmds_started, tgts_started;
463 int ignoring = 0, in_ignored_define = 0;
464 int no_targets = 0; /* Set when reading a rule without targets. */
465 struct nameseq *filenames = 0;
466 struct dep *deps = 0;
467 long nlines = 0;
468 int two_colon = 0;
469 char *pattern = 0, *pattern_percent;
470 struct floc *fstart;
471 struct floc fi;
473 #define record_waiting_files() \
474 do \
476 if (filenames != 0) \
478 fi.lineno = tgts_started; \
479 record_files (filenames, pattern, pattern_percent, deps, \
480 cmds_started, commands, commands_idx, two_colon, \
481 &fi); \
483 filenames = 0; \
484 commands_idx = 0; \
485 no_targets = 0; \
486 if (pattern) { free(pattern); pattern = 0; } \
487 } while (0)
489 pattern_percent = 0;
490 cmds_started = tgts_started = 1;
492 fstart = &ebuf->floc;
493 fi.filenm = ebuf->floc.filenm;
495 /* Loop over lines in the file.
496 The strategy is to accumulate target names in FILENAMES, dependencies
497 in DEPS and commands in COMMANDS. These are used to define a rule
498 when the start of the next rule (or eof) is encountered.
500 When you see a "continue" in the loop below, that means we are moving on
501 to the next line _without_ ending any rule that we happen to be working
502 with at the moment. If you see a "goto rule_complete", then the
503 statement we just parsed also finishes the previous rule. */
505 commands = xmalloc (200);
507 while (1)
509 unsigned int linelen;
510 char *line;
511 int len;
512 char *p;
513 char *p2;
515 /* Grab the next line to be evaluated */
516 ebuf->floc.lineno += nlines;
517 nlines = readline (ebuf);
519 /* If there is nothing left to eval, we're done. */
520 if (nlines < 0)
521 break;
523 /* If this line is empty, skip it. */
524 line = ebuf->buffer;
525 if (line[0] == '\0')
526 continue;
528 linelen = strlen (line);
530 /* Check for a shell command line first.
531 If it is not one, we can stop treating tab specially. */
532 if (line[0] == '\t')
534 if (no_targets)
535 /* Ignore the commands in a rule with no targets. */
536 continue;
538 /* If there is no preceding rule line, don't treat this line
539 as a command, even though it begins with a tab character.
540 SunOS 4 make appears to behave this way. */
542 if (filenames != 0)
544 if (ignoring)
545 /* Yep, this is a shell command, and we don't care. */
546 continue;
548 /* Append this command line to the line being accumulated. */
549 if (commands_idx == 0)
550 cmds_started = ebuf->floc.lineno;
552 if (linelen + 1 + commands_idx > commands_len)
554 commands_len = (linelen + 1 + commands_idx) * 2;
555 commands = xrealloc (commands, commands_len);
557 bcopy (line, &commands[commands_idx], linelen);
558 commands_idx += linelen;
559 commands[commands_idx++] = '\n';
561 continue;
565 /* This line is not a shell command line. Don't worry about tabs.
566 Get more space if we need it; we don't need to preserve the current
567 contents of the buffer. */
569 if (collapsed_length < linelen+1)
571 collapsed_length = linelen+1;
572 if (collapsed)
573 free ((char *)collapsed);
574 collapsed = (char *) xmalloc (collapsed_length);
576 strcpy (collapsed, line);
577 /* Collapse continuation lines. */
578 collapse_continuations (collapsed);
579 remove_comments (collapsed);
581 /* Compare a word, both length and contents. */
582 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
583 p = collapsed;
584 while (isspace ((unsigned char)*p))
585 ++p;
587 if (*p == '\0')
588 /* This line is completely empty--ignore it. */
589 continue;
591 /* Find the end of the first token. Note we don't need to worry about
592 * ":" here since we compare tokens by length (so "export" will never
593 * be equal to "export:").
595 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
597 len = p2 - p;
599 /* Find the start of the second token. If it looks like a target or
600 variable definition it can't be a preprocessor token so skip
601 them--this allows variables/targets named `ifdef', `export', etc. */
602 while (isspace ((unsigned char)*p2))
603 ++p2;
605 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
607 /* It can't be a preprocessor token so skip it if we're ignoring */
608 if (ignoring)
609 continue;
611 goto skip_conditionals;
614 /* We must first check for conditional and `define' directives before
615 ignoring anything, since they control what we will do with
616 following lines. */
618 if (!in_ignored_define)
620 int i = conditional_line (p, len, fstart);
621 if (i != -2)
623 if (i == -1)
624 fatal (fstart, _("invalid syntax in conditional"));
626 ignoring = i;
627 continue;
631 if (word1eq ("endef"))
633 if (!in_ignored_define)
634 fatal (fstart, _("extraneous `endef'"));
635 in_ignored_define = 0;
636 continue;
639 if (word1eq ("define"))
641 if (ignoring)
642 in_ignored_define = 1;
643 else
645 if (*p2 == '\0')
646 fatal (fstart, _("empty variable name"));
648 /* Let the variable name be the whole rest of the line,
649 with trailing blanks stripped (comments have already been
650 removed), so it could be a complex variable/function
651 reference that might contain blanks. */
652 p = strchr (p2, '\0');
653 while (isblank ((unsigned char)p[-1]))
654 --p;
655 do_define (p2, p - p2, o_file, ebuf);
657 continue;
660 if (word1eq ("override"))
662 if (*p2 == '\0')
663 error (fstart, _("empty `override' directive"));
665 if (strneq (p2, "define", 6)
666 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
668 if (ignoring)
669 in_ignored_define = 1;
670 else
672 p2 = next_token (p2 + 6);
673 if (*p2 == '\0')
674 fatal (fstart, _("empty variable name"));
676 /* Let the variable name be the whole rest of the line,
677 with trailing blanks stripped (comments have already been
678 removed), so it could be a complex variable/function
679 reference that might contain blanks. */
680 p = strchr (p2, '\0');
681 while (isblank ((unsigned char)p[-1]))
682 --p;
683 do_define (p2, p - p2, o_override, ebuf);
686 else if (!ignoring
687 && !try_variable_definition (fstart, p2, o_override, 0))
688 error (fstart, _("invalid `override' directive"));
690 continue;
693 if (ignoring)
694 /* Ignore the line. We continue here so conditionals
695 can appear in the middle of a rule. */
696 continue;
698 if (word1eq ("export"))
700 /* 'export' by itself causes everything to be exported. */
701 if (*p2 == '\0')
702 export_all_variables = 1;
703 else
705 struct variable *v;
707 v = try_variable_definition (fstart, p2, o_file, 0);
708 if (v != 0)
709 v->export = v_export;
710 else
712 unsigned int len;
713 char *ap;
715 /* Expand the line so we can use indirect and constructed
716 variable names in an export command. */
717 p2 = ap = allocated_variable_expand (p2);
719 for (p = find_next_token (&p2, &len); p != 0;
720 p = find_next_token (&p2, &len))
722 v = lookup_variable (p, len);
723 if (v == 0)
724 v = define_variable_loc (p, len, "", o_file, 0,
725 fstart);
726 v->export = v_export;
729 free (ap);
732 goto rule_complete;
735 if (word1eq ("unexport"))
737 if (*p2 == '\0')
738 export_all_variables = 0;
739 else
741 unsigned int len;
742 struct variable *v;
743 char *ap;
745 /* Expand the line so we can use indirect and constructed
746 variable names in an unexport command. */
747 p2 = ap = allocated_variable_expand (p2);
749 for (p = find_next_token (&p2, &len); p != 0;
750 p = find_next_token (&p2, &len))
752 v = lookup_variable (p, len);
753 if (v == 0)
754 v = define_variable_loc (p, len, "", o_file, 0, fstart);
756 v->export = v_noexport;
759 free (ap);
761 goto rule_complete;
764 skip_conditionals:
765 if (word1eq ("vpath"))
767 char *pattern;
768 unsigned int len;
769 p2 = variable_expand (p2);
770 p = find_next_token (&p2, &len);
771 if (p != 0)
773 pattern = savestring (p, len);
774 p = find_next_token (&p2, &len);
775 /* No searchpath means remove all previous
776 selective VPATH's with the same pattern. */
778 else
779 /* No pattern means remove all previous selective VPATH's. */
780 pattern = 0;
781 construct_vpath_list (pattern, p);
782 if (pattern != 0)
783 free (pattern);
785 goto rule_complete;
788 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
790 /* We have found an `include' line specifying a nested
791 makefile to be read at this point. */
792 struct conditionals *save;
793 struct conditionals new_conditionals;
794 struct nameseq *files;
795 /* "-include" (vs "include") says no error if the file does not
796 exist. "sinclude" is an alias for this from SGI. */
797 int noerror = (p[0] != 'i');
799 p = allocated_variable_expand (p2);
800 if (*p == '\0')
802 error (fstart,
803 _("no file name for `%sinclude'"), noerror ? "-" : "");
804 continue;
807 /* Parse the list of file names. */
808 p2 = p;
809 files = multi_glob (parse_file_seq (&p2, '\0',
810 sizeof (struct nameseq),
812 sizeof (struct nameseq));
813 free (p);
815 /* Save the state of conditionals and start
816 the included makefile with a clean slate. */
817 save = install_conditionals (&new_conditionals);
819 /* Record the rules that are waiting so they will determine
820 the default goal before those in the included makefile. */
821 record_waiting_files ();
823 /* Read each included makefile. */
824 while (files != 0)
826 struct nameseq *next = files->next;
827 char *name = files->name;
828 int r;
830 free ((char *)files);
831 files = next;
833 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
834 | (noerror ? RM_DONTCARE : 0)));
835 if (!r)
837 if (!noerror)
838 error (fstart, "%s: %s", name, strerror (errno));
839 free (name);
843 /* Restore conditional state. */
844 restore_conditionals (save);
846 goto rule_complete;
849 if (try_variable_definition (fstart, p, o_file, 0))
850 /* This line has been dealt with. */
851 goto rule_complete;
853 /* This line starts with a tab but was not caught above because there
854 was no preceding target, and the line might have been usable as a
855 variable definition. But now we know it is definitely lossage. */
856 if (line[0] == '\t')
857 fatal(fstart, _("commands commence before first target"));
859 /* This line describes some target files. This is complicated by
860 the existence of target-specific variables, because we can't
861 expand the entire line until we know if we have one or not. So
862 we expand the line word by word until we find the first `:',
863 then check to see if it's a target-specific variable.
865 In this algorithm, `lb_next' will point to the beginning of the
866 unexpanded parts of the input buffer, while `p2' points to the
867 parts of the expanded buffer we haven't searched yet. */
870 enum make_word_type wtype;
871 enum variable_origin v_origin;
872 int exported;
873 char *cmdleft, *semip, *lb_next;
874 unsigned int len, plen = 0;
875 char *colonp;
876 const char *end, *beg; /* Helpers for whitespace stripping. */
878 /* Record the previous rule. */
880 record_waiting_files ();
881 tgts_started = fstart->lineno;
883 /* Search the line for an unquoted ; that is not after an
884 unquoted #. */
885 cmdleft = find_char_unquote (line, ';', '#', 0);
886 if (cmdleft != 0 && *cmdleft == '#')
888 /* We found a comment before a semicolon. */
889 *cmdleft = '\0';
890 cmdleft = 0;
892 else if (cmdleft != 0)
893 /* Found one. Cut the line short there before expanding it. */
894 *(cmdleft++) = '\0';
895 semip = cmdleft;
897 collapse_continuations (line);
899 /* We can't expand the entire line, since if it's a per-target
900 variable we don't want to expand it. So, walk from the
901 beginning, expanding as we go, and looking for "interesting"
902 chars. The first word is always expandable. */
903 wtype = get_next_mword(line, NULL, &lb_next, &len);
904 switch (wtype)
906 case w_eol:
907 if (cmdleft != 0)
908 fatal(fstart, _("missing rule before commands"));
909 /* This line contained something but turned out to be nothing
910 but whitespace (a comment?). */
911 continue;
913 case w_colon:
914 case w_dcolon:
915 /* We accept and ignore rules without targets for
916 compatibility with SunOS 4 make. */
917 no_targets = 1;
918 continue;
920 default:
921 break;
924 p2 = variable_expand_string(NULL, lb_next, len);
926 while (1)
928 lb_next += len;
929 if (cmdleft == 0)
931 /* Look for a semicolon in the expanded line. */
932 cmdleft = find_char_unquote (p2, ';', 0, 0);
934 if (cmdleft != 0)
936 unsigned long p2_off = p2 - variable_buffer;
937 unsigned long cmd_off = cmdleft - variable_buffer;
938 char *pend = p2 + strlen(p2);
940 /* Append any remnants of lb, then cut the line short
941 at the semicolon. */
942 *cmdleft = '\0';
944 /* One school of thought says that you shouldn't expand
945 here, but merely copy, since now you're beyond a ";"
946 and into a command script. However, the old parser
947 expanded the whole line, so we continue that for
948 backwards-compatiblity. Also, it wouldn't be
949 entirely consistent, since we do an unconditional
950 expand below once we know we don't have a
951 target-specific variable. */
952 (void)variable_expand_string(pend, lb_next, (long)-1);
953 lb_next += strlen(lb_next);
954 p2 = variable_buffer + p2_off;
955 cmdleft = variable_buffer + cmd_off + 1;
959 colonp = find_char_unquote(p2, ':', 0, 0);
960 #ifdef HAVE_DOS_PATHS
961 /* The drive spec brain-damage strikes again... */
962 /* Note that the only separators of targets in this context
963 are whitespace and a left paren. If others are possible,
964 they should be added to the string in the call to index. */
965 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
966 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
967 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
968 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
969 #endif
970 if (colonp != 0)
971 break;
973 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
974 if (wtype == w_eol)
975 break;
977 p2 += strlen(p2);
978 *(p2++) = ' ';
979 p2 = variable_expand_string(p2, lb_next, len);
980 /* We don't need to worry about cmdleft here, because if it was
981 found in the variable_buffer the entire buffer has already
982 been expanded... we'll never get here. */
985 p2 = next_token (variable_buffer);
987 /* If the word we're looking at is EOL, see if there's _anything_
988 on the line. If not, a variable expanded to nothing, so ignore
989 it. If so, we can't parse this line so punt. */
990 if (wtype == w_eol)
992 if (*p2 != '\0')
993 /* There's no need to be ivory-tower about this: check for
994 one of the most common bugs found in makefiles... */
995 fatal (fstart, _("missing separator%s"),
996 !strneq(line, " ", 8) ? ""
997 : _(" (did you mean TAB instead of 8 spaces?)"));
998 continue;
1001 /* Make the colon the end-of-string so we know where to stop
1002 looking for targets. */
1003 *colonp = '\0';
1004 filenames = multi_glob (parse_file_seq (&p2, '\0',
1005 sizeof (struct nameseq),
1007 sizeof (struct nameseq));
1008 *p2 = ':';
1010 if (!filenames)
1012 /* We accept and ignore rules without targets for
1013 compatibility with SunOS 4 make. */
1014 no_targets = 1;
1015 continue;
1017 /* This should never be possible; we handled it above. */
1018 assert (*p2 != '\0');
1019 ++p2;
1021 /* Is this a one-colon or two-colon entry? */
1022 two_colon = *p2 == ':';
1023 if (two_colon)
1024 p2++;
1026 /* Test to see if it's a target-specific variable. Copy the rest
1027 of the buffer over, possibly temporarily (we'll expand it later
1028 if it's not a target-specific variable). PLEN saves the length
1029 of the unparsed section of p2, for later. */
1030 if (*lb_next != '\0')
1032 unsigned int l = p2 - variable_buffer;
1033 plen = strlen (p2);
1034 (void) variable_buffer_output (p2+plen,
1035 lb_next, strlen (lb_next)+1);
1036 p2 = variable_buffer + l;
1039 /* See if it's an "override" or "export" keyword; if so see if what
1040 comes after it looks like a variable definition. */
1042 wtype = get_next_mword (p2, NULL, &p, &len);
1044 v_origin = o_file;
1045 exported = 0;
1046 if (wtype == w_static)
1048 if (word1eq ("override"))
1050 v_origin = o_override;
1051 wtype = get_next_mword (p+len, NULL, &p, &len);
1053 else if (word1eq ("export"))
1055 exported = 1;
1056 wtype = get_next_mword (p+len, NULL, &p, &len);
1060 if (wtype != w_eol)
1061 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1063 if (wtype == w_varassign)
1065 /* If there was a semicolon found, add it back, plus anything
1066 after it. */
1067 if (semip)
1069 unsigned int l = p - variable_buffer;
1070 *(--semip) = ';';
1071 variable_buffer_output (p2 + strlen (p2),
1072 semip, strlen (semip)+1);
1073 p = variable_buffer + l;
1075 record_target_var (filenames, p, v_origin, exported, fstart);
1076 filenames = 0;
1077 continue;
1080 /* This is a normal target, _not_ a target-specific variable.
1081 Unquote any = in the dependency list. */
1082 find_char_unquote (lb_next, '=', 0, 0);
1084 /* We have some targets, so don't ignore the following commands. */
1085 no_targets = 0;
1087 /* Expand the dependencies, etc. */
1088 if (*lb_next != '\0')
1090 unsigned int l = p2 - variable_buffer;
1091 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1092 p2 = variable_buffer + l;
1094 /* Look for a semicolon in the expanded line. */
1095 if (cmdleft == 0)
1097 cmdleft = find_char_unquote (p2, ';', 0, 0);
1098 if (cmdleft != 0)
1099 *(cmdleft++) = '\0';
1103 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1104 p = strchr (p2, ':');
1105 while (p != 0 && p[-1] == '\\')
1107 register char *q = &p[-1];
1108 register int backslash = 0;
1109 while (*q-- == '\\')
1110 backslash = !backslash;
1111 if (backslash)
1112 p = strchr (p + 1, ':');
1113 else
1114 break;
1116 #ifdef _AMIGA
1117 /* Here, the situation is quite complicated. Let's have a look
1118 at a couple of targets:
1120 install: dev:make
1122 dev:make: make
1124 dev:make:: xyz
1126 The rule is that it's only a target, if there are TWO :'s
1127 OR a space around the :.
1129 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1130 || isspace ((unsigned char)p[-1])))
1131 p = 0;
1132 #endif
1133 #ifdef HAVE_DOS_PATHS
1135 int check_again;
1137 do {
1138 check_again = 0;
1139 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1140 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1141 isalpha ((unsigned char)p[-1]) &&
1142 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1143 p = strchr (p + 1, ':');
1144 check_again = 1;
1146 } while (check_again);
1148 #endif
1149 if (p != 0)
1151 struct nameseq *target;
1152 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1153 ++p2;
1154 if (target == 0)
1155 fatal (fstart, _("missing target pattern"));
1156 else if (target->next != 0)
1157 fatal (fstart, _("multiple target patterns"));
1158 pattern = target->name;
1159 pattern_percent = find_percent (pattern);
1160 if (pattern_percent == 0)
1161 fatal (fstart, _("target pattern contains no `%%'"));
1162 free((char *)target);
1164 else
1165 pattern = 0;
1167 /* Strip leading and trailing whitespaces. */
1168 beg = p2;
1169 end = beg + strlen (beg) - 1;
1170 strip_whitespace (&beg, &end);
1172 if (beg <= end && *beg != '\0')
1174 char *top;
1175 const char *fromp = beg;
1177 /* Make a copy of the dependency string. Note if we find '$'. */
1178 deps = (struct dep*) xmalloc (sizeof (struct dep));
1179 deps->next = 0;
1180 deps->name = top = (char *) xmalloc (end - beg + 2);
1181 deps->need_2nd_expansion = 0;
1182 while (fromp <= end)
1184 if (*fromp == '$')
1185 deps->need_2nd_expansion = 1;
1186 *(top++) = *(fromp++);
1188 *top = '\0';
1189 deps->file = 0;
1191 else
1192 deps = 0;
1194 commands_idx = 0;
1195 if (cmdleft != 0)
1197 /* Semicolon means rest of line is a command. */
1198 unsigned int len = strlen (cmdleft);
1200 cmds_started = fstart->lineno;
1202 /* Add this command line to the buffer. */
1203 if (len + 2 > commands_len)
1205 commands_len = (len + 2) * 2;
1206 commands = (char *) xrealloc (commands, commands_len);
1208 bcopy (cmdleft, commands, len);
1209 commands_idx += len;
1210 commands[commands_idx++] = '\n';
1213 /* Determine if this target should be made default. We used to do
1214 this in record_files() but because of the delayed target recording
1215 and because preprocessor directives are legal in target's commands
1216 it is too late. Consider this fragment for example:
1218 foo:
1220 ifeq ($(.DEFAULT_GOAL),foo)
1222 endif
1224 Because the target is not recorded until after ifeq directive is
1225 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1226 would expect. Because of this we have to move some of the logic
1227 here. */
1229 if (**default_goal_name == '\0' && set_default)
1231 char* name;
1232 struct dep *d;
1233 struct nameseq *t = filenames;
1235 for (; t != 0; t = t->next)
1237 int reject = 0;
1238 name = t->name;
1240 /* We have nothing to do if this is an implicit rule. */
1241 if (strchr (name, '%') != 0)
1242 break;
1244 /* See if this target's name does not start with a `.',
1245 unless it contains a slash. */
1246 if (*name == '.' && strchr (name, '/') == 0
1247 #ifdef HAVE_DOS_PATHS
1248 && strchr (name, '\\') == 0
1249 #endif
1251 continue;
1254 /* If this file is a suffix, don't let it be
1255 the default goal file. */
1256 for (d = suffix_file->deps; d != 0; d = d->next)
1258 register struct dep *d2;
1259 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1261 reject = 1;
1262 break;
1264 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1266 register unsigned int len = strlen (dep_name (d2));
1267 if (!strneq (name, dep_name (d2), len))
1268 continue;
1269 if (streq (name + len, dep_name (d)))
1271 reject = 1;
1272 break;
1276 if (reject)
1277 break;
1280 if (!reject)
1282 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1283 o_file, 0, NILF);
1284 break;
1289 continue;
1292 /* We get here except in the case that we just read a rule line.
1293 Record now the last rule we read, so following spurious
1294 commands are properly diagnosed. */
1295 rule_complete:
1296 record_waiting_files ();
1299 #undef word1eq
1301 if (conditionals->if_cmds)
1302 fatal (fstart, _("missing `endif'"));
1304 /* At eof, record the last rule. */
1305 record_waiting_files ();
1307 if (collapsed)
1308 free ((char *) collapsed);
1309 free ((char *) commands);
1311 return 1;
1315 /* Execute a `define' directive.
1316 The first line has already been read, and NAME is the name of
1317 the variable to be defined. The following lines remain to be read. */
1319 static void
1320 do_define (char *name, unsigned int namelen,
1321 enum variable_origin origin, struct ebuffer *ebuf)
1323 struct floc defstart;
1324 long nlines = 0;
1325 int nlevels = 1;
1326 unsigned int length = 100;
1327 char *definition = (char *) xmalloc (length);
1328 unsigned int idx = 0;
1329 char *p;
1331 /* Expand the variable name. */
1332 char *var = (char *) alloca (namelen + 1);
1333 bcopy (name, var, namelen);
1334 var[namelen] = '\0';
1335 var = variable_expand (var);
1337 defstart = ebuf->floc;
1339 while (1)
1341 unsigned int len;
1342 char *line;
1344 nlines = readline (ebuf);
1345 ebuf->floc.lineno += nlines;
1347 /* If there is nothing left to eval, we're done. */
1348 if (nlines < 0)
1349 break;
1351 line = ebuf->buffer;
1353 collapse_continuations (line);
1355 /* If the line doesn't begin with a tab, test to see if it introduces
1356 another define, or ends one. */
1358 /* Stop if we find an 'endef' */
1359 if (line[0] != '\t')
1361 p = next_token (line);
1362 len = strlen (p);
1364 /* If this is another 'define', increment the level count. */
1365 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1366 && strneq (p, "define", 6))
1367 ++nlevels;
1369 /* If this is an 'endef', decrement the count. If it's now 0,
1370 we've found the last one. */
1371 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1372 && strneq (p, "endef", 5))
1374 p += 5;
1375 remove_comments (p);
1376 if (*next_token (p) != '\0')
1377 error (&ebuf->floc,
1378 _("Extraneous text after `endef' directive"));
1380 if (--nlevels == 0)
1382 /* Define the variable. */
1383 if (idx == 0)
1384 definition[0] = '\0';
1385 else
1386 definition[idx - 1] = '\0';
1388 /* Always define these variables in the global set. */
1389 define_variable_global (var, strlen (var), definition,
1390 origin, 1, &defstart);
1391 free (definition);
1392 return;
1397 /* Otherwise add this line to the variable definition. */
1398 len = strlen (line);
1399 if (idx + len + 1 > length)
1401 length = (idx + len) * 2;
1402 definition = (char *) xrealloc (definition, length + 1);
1405 bcopy (line, &definition[idx], len);
1406 idx += len;
1407 /* Separate lines with a newline. */
1408 definition[idx++] = '\n';
1411 /* No `endef'!! */
1412 fatal (&defstart, _("missing `endef', unterminated `define'"));
1414 /* NOTREACHED */
1415 return;
1418 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1419 "ifneq", "else" and "endif".
1420 LINE is the input line, with the command as its first word.
1422 FILENAME and LINENO are the filename and line number in the
1423 current makefile. They are used for error messages.
1425 Value is -2 if the line is not a conditional at all,
1426 -1 if the line is an invalid conditional,
1427 0 if following text should be interpreted,
1428 1 if following text should be ignored. */
1430 static int
1431 conditional_line (char *line, int len, const struct floc *flocp)
1433 char *cmdname;
1434 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1435 unsigned int i;
1436 unsigned int o;
1438 /* Compare a word, both length and contents. */
1439 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1440 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1442 /* Make sure this line is a conditional. */
1443 chkword ("ifdef", c_ifdef)
1444 else chkword ("ifndef", c_ifndef)
1445 else chkword ("ifeq", c_ifeq)
1446 else chkword ("ifneq", c_ifneq)
1447 else chkword ("else", c_else)
1448 else chkword ("endif", c_endif)
1449 else
1450 return -2;
1452 /* Found one: skip past it and any whitespace after it. */
1453 line = next_token (line + len);
1455 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1457 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1458 if (cmdtype == c_endif)
1460 if (*line != '\0')
1461 EXTRANEOUS ();
1463 if (!conditionals->if_cmds)
1464 fatal (flocp, _("extraneous `%s'"), cmdname);
1466 --conditionals->if_cmds;
1468 goto DONE;
1471 /* An 'else' statement can either be simple, or it can have another
1472 conditional after it. */
1473 if (cmdtype == c_else)
1475 const char *p;
1477 if (!conditionals->if_cmds)
1478 fatal (flocp, _("extraneous `%s'"), cmdname);
1480 o = conditionals->if_cmds - 1;
1482 if (conditionals->seen_else[o])
1483 fatal (flocp, _("only one `else' per conditional"));
1485 /* Change the state of ignorance. */
1486 switch (conditionals->ignoring[o])
1488 case 0:
1489 /* We've just been interpreting. Never do it again. */
1490 conditionals->ignoring[o] = 2;
1491 break;
1492 case 1:
1493 /* We've never interpreted yet. Maybe this time! */
1494 conditionals->ignoring[o] = 0;
1495 break;
1498 /* It's a simple 'else'. */
1499 if (*line == '\0')
1501 conditionals->seen_else[o] = 1;
1502 goto DONE;
1505 /* The 'else' has extra text. That text must be another conditional
1506 and cannot be an 'else' or 'endif'. */
1508 /* Find the length of the next word. */
1509 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1511 len = p - line;
1513 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1514 if (word1eq("else") || word1eq("endif")
1515 || conditional_line (line, len, flocp) < 0)
1516 EXTRANEOUS ();
1517 else
1519 /* conditional_line() created a new level of conditional.
1520 Raise it back to this level. */
1521 if (conditionals->ignoring[o] < 2)
1522 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1523 --conditionals->if_cmds;
1526 goto DONE;
1529 if (conditionals->allocated == 0)
1531 conditionals->allocated = 5;
1532 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1533 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1536 o = conditionals->if_cmds++;
1537 if (conditionals->if_cmds > conditionals->allocated)
1539 conditionals->allocated += 5;
1540 conditionals->ignoring = (char *)
1541 xrealloc (conditionals->ignoring, conditionals->allocated);
1542 conditionals->seen_else = (char *)
1543 xrealloc (conditionals->seen_else, conditionals->allocated);
1546 /* Record that we have seen an `if...' but no `else' so far. */
1547 conditionals->seen_else[o] = 0;
1549 /* Search through the stack to see if we're already ignoring. */
1550 for (i = 0; i < o; ++i)
1551 if (conditionals->ignoring[i])
1553 /* We are already ignoring, so just push a level to match the next
1554 "else" or "endif", and keep ignoring. We don't want to expand
1555 variables in the condition. */
1556 conditionals->ignoring[o] = 1;
1557 return 1;
1560 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1562 char *var;
1563 struct variable *v;
1564 char *p;
1566 /* Expand the thing we're looking up, so we can use indirect and
1567 constructed variable names. */
1568 var = allocated_variable_expand (line);
1570 /* Make sure there's only one variable name to test. */
1571 p = end_of_token (var);
1572 i = p - var;
1573 p = next_token (p);
1574 if (*p != '\0')
1575 return -1;
1577 var[i] = '\0';
1578 v = lookup_variable (var, i);
1580 conditionals->ignoring[o] =
1581 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1583 free (var);
1585 else
1587 /* "Ifeq" or "ifneq". */
1588 char *s1, *s2;
1589 unsigned int len;
1590 char termin = *line == '(' ? ',' : *line;
1592 if (termin != ',' && termin != '"' && termin != '\'')
1593 return -1;
1595 s1 = ++line;
1596 /* Find the end of the first string. */
1597 if (termin == ',')
1599 int count = 0;
1600 for (; *line != '\0'; ++line)
1601 if (*line == '(')
1602 ++count;
1603 else if (*line == ')')
1604 --count;
1605 else if (*line == ',' && count <= 0)
1606 break;
1608 else
1609 while (*line != '\0' && *line != termin)
1610 ++line;
1612 if (*line == '\0')
1613 return -1;
1615 if (termin == ',')
1617 /* Strip blanks after the first string. */
1618 char *p = line++;
1619 while (isblank ((unsigned char)p[-1]))
1620 --p;
1621 *p = '\0';
1623 else
1624 *line++ = '\0';
1626 s2 = variable_expand (s1);
1627 /* We must allocate a new copy of the expanded string because
1628 variable_expand re-uses the same buffer. */
1629 len = strlen (s2);
1630 s1 = (char *) alloca (len + 1);
1631 bcopy (s2, s1, len + 1);
1633 if (termin != ',')
1634 /* Find the start of the second string. */
1635 line = next_token (line);
1637 termin = termin == ',' ? ')' : *line;
1638 if (termin != ')' && termin != '"' && termin != '\'')
1639 return -1;
1641 /* Find the end of the second string. */
1642 if (termin == ')')
1644 register int count = 0;
1645 s2 = next_token (line);
1646 for (line = s2; *line != '\0'; ++line)
1648 if (*line == '(')
1649 ++count;
1650 else if (*line == ')')
1652 if (count <= 0)
1653 break;
1654 else
1655 --count;
1659 else
1661 ++line;
1662 s2 = line;
1663 while (*line != '\0' && *line != termin)
1664 ++line;
1667 if (*line == '\0')
1668 return -1;
1670 *line = '\0';
1671 line = next_token (++line);
1672 if (*line != '\0')
1673 EXTRANEOUS ();
1675 s2 = variable_expand (s2);
1676 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1679 DONE:
1680 /* Search through the stack to see if we're ignoring. */
1681 for (i = 0; i < conditionals->if_cmds; ++i)
1682 if (conditionals->ignoring[i])
1683 return 1;
1684 return 0;
1687 /* Remove duplicate dependencies in CHAIN. */
1689 static unsigned long
1690 dep_hash_1 (const void *key)
1692 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1695 static unsigned long
1696 dep_hash_2 (const void *key)
1698 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1701 static int
1702 dep_hash_cmp (const void *x, const void *y)
1704 struct dep *dx = (struct dep *) x;
1705 struct dep *dy = (struct dep *) y;
1706 int cmp = strcmp (dep_name (dx), dep_name (dy));
1708 /* If the names are the same but ignore_mtimes are not equal, one of these
1709 is an order-only prerequisite and one isn't. That means that we should
1710 remove the one that isn't and keep the one that is. */
1712 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1713 dx->ignore_mtime = dy->ignore_mtime = 0;
1715 return cmp;
1719 void
1720 uniquize_deps (struct dep *chain)
1722 struct hash_table deps;
1723 register struct dep **depp;
1725 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1727 /* Make sure that no dependencies are repeated. This does not
1728 really matter for the purpose of updating targets, but it
1729 might make some names be listed twice for $^ and $?. */
1731 depp = &chain;
1732 while (*depp)
1734 struct dep *dep = *depp;
1735 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1736 if (HASH_VACANT (*dep_slot))
1738 hash_insert_at (&deps, dep, dep_slot);
1739 depp = &dep->next;
1741 else
1743 /* Don't bother freeing duplicates.
1744 It's dangerous and little benefit accrues. */
1745 *depp = dep->next;
1749 hash_free (&deps, 0);
1752 /* Record target-specific variable values for files FILENAMES.
1753 TWO_COLON is nonzero if a double colon was used.
1755 The links of FILENAMES are freed, and so are any names in it
1756 that are not incorporated into other data structures.
1758 If the target is a pattern, add the variable to the pattern-specific
1759 variable value list. */
1761 static void
1762 record_target_var (struct nameseq *filenames, char *defn,
1763 enum variable_origin origin, int exported,
1764 const struct floc *flocp)
1766 struct nameseq *nextf;
1767 struct variable_set_list *global;
1769 global = current_variable_set_list;
1771 /* If the variable is an append version, store that but treat it as a
1772 normal recursive variable. */
1774 for (; filenames != 0; filenames = nextf)
1776 struct variable *v;
1777 register char *name = filenames->name;
1778 char *fname;
1779 char *percent;
1780 struct pattern_var *p;
1782 nextf = filenames->next;
1783 free ((char *) filenames);
1785 /* If it's a pattern target, then add it to the pattern-specific
1786 variable list. */
1787 percent = find_percent (name);
1788 if (percent)
1790 /* Get a reference for this pattern-specific variable struct. */
1791 p = create_pattern_var (name, percent);
1792 p->variable.fileinfo = *flocp;
1793 /* I don't think this can fail since we already determined it was a
1794 variable definition. */
1795 v = parse_variable_definition (&p->variable, defn);
1796 assert (v != 0);
1798 if (v->flavor == f_simple)
1799 v->value = allocated_variable_expand (v->value);
1800 else
1801 v->value = xstrdup (v->value);
1803 fname = p->target;
1805 else
1807 struct file *f;
1809 /* Get a file reference for this file, and initialize it.
1810 We don't want to just call enter_file() because that allocates a
1811 new entry if the file is a double-colon, which we don't want in
1812 this situation. */
1813 f = lookup_file (name);
1814 if (!f)
1815 f = enter_file (name);
1816 else if (f->double_colon)
1817 f = f->double_colon;
1819 initialize_file_variables (f, 1);
1820 fname = f->name;
1822 current_variable_set_list = f->variables;
1823 v = try_variable_definition (flocp, defn, origin, 1);
1824 if (!v)
1825 error (flocp, _("Malformed target-specific variable definition"));
1826 current_variable_set_list = global;
1829 /* Set up the variable to be *-specific. */
1830 v->origin = origin;
1831 v->per_target = 1;
1832 if (exported)
1833 v->export = v_export;
1835 /* If it's not an override, check to see if there was a command-line
1836 setting. If so, reset the value. */
1837 if (origin != o_override)
1839 struct variable *gv;
1840 int len = strlen(v->name);
1842 gv = lookup_variable (v->name, len);
1843 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1845 if (v->value != 0)
1846 free (v->value);
1847 v->value = xstrdup (gv->value);
1848 v->origin = gv->origin;
1849 v->recursive = gv->recursive;
1850 v->append = 0;
1854 /* Free name if not needed further. */
1855 if (name != fname && (name < fname || name > fname + strlen (fname)))
1856 free (name);
1860 /* Record a description line for files FILENAMES,
1861 with dependencies DEPS, commands to execute described
1862 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1863 TWO_COLON is nonzero if a double colon was used.
1864 If not nil, PATTERN is the `%' pattern to make this
1865 a static pattern rule, and PATTERN_PERCENT is a pointer
1866 to the `%' within it.
1868 The links of FILENAMES are freed, and so are any names in it
1869 that are not incorporated into other data structures. */
1871 static void
1872 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1873 struct dep *deps, unsigned int cmds_started, char *commands,
1874 unsigned int commands_idx, int two_colon,
1875 const struct floc *flocp)
1877 struct nameseq *nextf;
1878 int implicit = 0;
1879 unsigned int max_targets = 0, target_idx = 0;
1880 char **targets = 0, **target_percents = 0;
1881 struct commands *cmds;
1883 /* If we've already snapped deps, that means we're in an eval being
1884 resolved after the makefiles have been read in. We can't add more rules
1885 at this time, since they won't get snapped and we'll get core dumps.
1886 See Savannah bug # 12124. */
1887 if (snapped_deps)
1888 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1890 if (commands_idx > 0)
1892 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1893 cmds->fileinfo.filenm = flocp->filenm;
1894 cmds->fileinfo.lineno = cmds_started;
1895 cmds->commands = savestring (commands, commands_idx);
1896 cmds->command_lines = 0;
1898 else
1899 cmds = 0;
1901 for (; filenames != 0; filenames = nextf)
1903 char *name = filenames->name;
1904 struct file *f;
1905 struct dep *d;
1906 struct dep *this;
1907 char *implicit_percent;
1909 nextf = filenames->next;
1910 free (filenames);
1912 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1913 good enough: it doesn't happen until after the makefile is read,
1914 which means we cannot use its value during parsing. */
1916 if (streq (name, ".POSIX"))
1917 posix_pedantic = 1;
1919 implicit_percent = find_percent (name);
1920 implicit |= implicit_percent != 0;
1922 if (implicit && pattern != 0)
1923 fatal (flocp, _("mixed implicit and static pattern rules"));
1925 if (implicit && implicit_percent == 0)
1926 fatal (flocp, _("mixed implicit and normal rules"));
1928 if (implicit)
1930 if (targets == 0)
1932 max_targets = 5;
1933 targets = (char **) xmalloc (5 * sizeof (char *));
1934 target_percents = (char **) xmalloc (5 * sizeof (char *));
1935 target_idx = 0;
1937 else if (target_idx == max_targets - 1)
1939 max_targets += 5;
1940 targets = (char **) xrealloc ((char *) targets,
1941 max_targets * sizeof (char *));
1942 target_percents
1943 = (char **) xrealloc ((char *) target_percents,
1944 max_targets * sizeof (char *));
1946 targets[target_idx] = name;
1947 target_percents[target_idx] = implicit_percent;
1948 ++target_idx;
1949 continue;
1952 /* If there are multiple filenames, copy the chain DEPS
1953 for all but the last one. It is not safe for the same deps
1954 to go in more than one place in the database. */
1955 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1957 if (pattern != 0)
1959 /* If this is an extended static rule:
1960 `targets: target%pattern: dep%pattern; cmds',
1961 translate each dependency pattern into a plain filename
1962 using the target pattern and this target's name. */
1963 if (!pattern_matches (pattern, pattern_percent, name))
1965 /* Give a warning if the rule is meaningless. */
1966 error (flocp,
1967 _("target `%s' doesn't match the target pattern"), name);
1968 this = 0;
1970 else
1971 /* We use subst_expand to do the work of translating % to $* in
1972 the dependency line. */
1974 if (this != 0 && find_percent (this->name) != 0)
1976 char *o;
1977 char *buffer = variable_expand ("");
1979 o = subst_expand (buffer, this->name, "%", "$*", 1, 2, 0);
1981 free (this->name);
1982 this->name = savestring (buffer, o - buffer);
1983 this->need_2nd_expansion = 1;
1987 if (!two_colon)
1989 /* Single-colon. Combine these dependencies
1990 with others in file's existing record, if any. */
1991 f = enter_file (name);
1993 if (f->double_colon)
1994 fatal (flocp,
1995 _("target file `%s' has both : and :: entries"), f->name);
1997 /* If CMDS == F->CMDS, this target was listed in this rule
1998 more than once. Just give a warning since this is harmless. */
1999 if (cmds != 0 && cmds == f->cmds)
2000 error (flocp,
2001 _("target `%s' given more than once in the same rule."),
2002 f->name);
2004 /* Check for two single-colon entries both with commands.
2005 Check is_target so that we don't lose on files such as .c.o
2006 whose commands were preinitialized. */
2007 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2009 error (&cmds->fileinfo,
2010 _("warning: overriding commands for target `%s'"),
2011 f->name);
2012 error (&f->cmds->fileinfo,
2013 _("warning: ignoring old commands for target `%s'"),
2014 f->name);
2017 f->is_target = 1;
2019 /* Defining .DEFAULT with no deps or cmds clears it. */
2020 if (f == default_file && this == 0 && cmds == 0)
2021 f->cmds = 0;
2022 if (cmds != 0)
2023 f->cmds = cmds;
2025 /* Defining .SUFFIXES with no dependencies
2026 clears out the list of suffixes. */
2027 if (f == suffix_file && this == 0)
2029 d = f->deps;
2030 while (d != 0)
2032 struct dep *nextd = d->next;
2033 free (d->name);
2034 free ((char *)d);
2035 d = nextd;
2037 f->deps = 0;
2039 else if (this != 0)
2041 /* Add the file's old deps and the new ones in THIS together. */
2043 if (f->deps != 0)
2045 struct dep **d_ptr = &f->deps;
2047 while ((*d_ptr)->next != 0)
2048 d_ptr = &(*d_ptr)->next;
2050 if (cmds != 0)
2052 /* This is the rule with commands, so put its deps
2053 last. The rationale behind this is that $< expands
2054 to the first dep in the chain, and commands use $<
2055 expecting to get the dep that rule specifies.
2056 However the second expansion algorithm reverses
2057 the order thus we need to make it last here. */
2059 (*d_ptr)->next = this;
2061 else
2063 /* This is the rule without commands. Put its
2064 dependencies at the end but before dependencies
2065 from the rule with commands (if any). This way
2066 everything appears in makefile order. */
2068 if (f->cmds != 0)
2070 this->next = *d_ptr;
2071 *d_ptr = this;
2073 else
2074 (*d_ptr)->next = this;
2077 else
2078 f->deps = this;
2080 /* This is a hack. I need a way to communicate to snap_deps()
2081 that the last dependency line in this file came with commands
2082 (so that logic in snap_deps() can put it in front and all
2083 this $< -logic works). I cannot simply rely on file->cmds
2084 being not 0 because of the cases like the following:
2086 foo: bar
2087 foo:
2090 I am going to temporarily "borrow" UPDATING member in
2091 `struct file' for this. */
2093 if (cmds != 0)
2094 f->updating = 1;
2097 /* If this is a static pattern rule, set the file's stem to
2098 the part of its name that matched the `%' in the pattern,
2099 so you can use $* in the commands. */
2100 if (pattern != 0)
2102 static char *percent = "%";
2103 char *buffer = variable_expand ("");
2104 char *o = patsubst_expand (buffer, name, pattern, percent,
2105 pattern_percent+1, percent+1);
2106 f->stem = savestring (buffer, o - buffer);
2109 else
2111 /* Double-colon. Make a new record
2112 even if the file already has one. */
2113 f = lookup_file (name);
2114 /* Check for both : and :: rules. Check is_target so
2115 we don't lose on default suffix rules or makefiles. */
2116 if (f != 0 && f->is_target && !f->double_colon)
2117 fatal (flocp,
2118 _("target file `%s' has both : and :: entries"), f->name);
2119 f = enter_file (name);
2120 /* If there was an existing entry and it was a double-colon
2121 entry, enter_file will have returned a new one, making it the
2122 prev pointer of the old one, and setting its double_colon
2123 pointer to the first one. */
2124 if (f->double_colon == 0)
2125 /* This is the first entry for this name, so we must
2126 set its double_colon pointer to itself. */
2127 f->double_colon = f;
2128 f->is_target = 1;
2129 f->deps = this;
2130 f->cmds = cmds;
2133 /* Free name if not needed further. */
2134 if (f != 0 && name != f->name
2135 && (name < f->name || name > f->name + strlen (f->name)))
2137 free (name);
2138 name = f->name;
2141 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2142 if (strcmp (*default_goal_name, name) == 0
2143 && (default_goal_file == 0
2144 || strcmp (default_goal_file->name, name) != 0))
2145 default_goal_file = f;
2148 if (implicit)
2150 targets[target_idx] = 0;
2151 target_percents[target_idx] = 0;
2152 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2153 free ((char *) target_percents);
2157 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2158 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2159 Quoting backslashes are removed from STRING by compacting it into
2160 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2161 one, or nil if there are none. */
2163 char *
2164 find_char_unquote (char *string, int stop1, int stop2, int blank)
2166 unsigned int string_len = 0;
2167 register char *p = string;
2169 while (1)
2171 if (stop2 && blank)
2172 while (*p != '\0' && *p != stop1 && *p != stop2
2173 && ! isblank ((unsigned char) *p))
2174 ++p;
2175 else if (stop2)
2176 while (*p != '\0' && *p != stop1 && *p != stop2)
2177 ++p;
2178 else if (blank)
2179 while (*p != '\0' && *p != stop1
2180 && ! isblank ((unsigned char) *p))
2181 ++p;
2182 else
2183 while (*p != '\0' && *p != stop1)
2184 ++p;
2186 if (*p == '\0')
2187 break;
2189 if (p > string && p[-1] == '\\')
2191 /* Search for more backslashes. */
2192 register int i = -2;
2193 while (&p[i] >= string && p[i] == '\\')
2194 --i;
2195 ++i;
2196 /* Only compute the length if really needed. */
2197 if (string_len == 0)
2198 string_len = strlen (string);
2199 /* The number of backslashes is now -I.
2200 Copy P over itself to swallow half of them. */
2201 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2202 p += i / 2;
2203 if (i % 2 == 0)
2204 /* All the backslashes quoted each other; the STOPCHAR was
2205 unquoted. */
2206 return p;
2208 /* The STOPCHAR was quoted by a backslash. Look for another. */
2210 else
2211 /* No backslash in sight. */
2212 return p;
2215 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2216 return 0;
2219 /* Search PATTERN for an unquoted %. */
2221 char *
2222 find_percent (char *pattern)
2224 return find_char_unquote (pattern, '%', 0, 0);
2227 /* Parse a string into a sequence of filenames represented as a
2228 chain of struct nameseq's in reverse order and return that chain.
2230 The string is passed as STRINGP, the address of a string pointer.
2231 The string pointer is updated to point at the first character
2232 not parsed, which either is a null char or equals STOPCHAR.
2234 SIZE is how big to construct chain elements.
2235 This is useful if we want them actually to be other structures
2236 that have room for additional info.
2238 If STRIP is nonzero, strip `./'s off the beginning. */
2240 struct nameseq *
2241 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2243 register struct nameseq *new = 0;
2244 register struct nameseq *new1, *lastnew1;
2245 register char *p = *stringp;
2246 char *q;
2247 char *name;
2249 #ifdef VMS
2250 # define VMS_COMMA ','
2251 #else
2252 # define VMS_COMMA 0
2253 #endif
2255 while (1)
2257 /* Skip whitespace; see if any more names are left. */
2258 p = next_token (p);
2259 if (*p == '\0')
2260 break;
2261 if (*p == stopchar)
2262 break;
2264 /* Yes, find end of next name. */
2265 q = p;
2266 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2267 #ifdef VMS
2268 /* convert comma separated list to space separated */
2269 if (p && *p == ',')
2270 *p =' ';
2271 #endif
2272 #ifdef _AMIGA
2273 if (stopchar == ':' && p && *p == ':'
2274 && !(isspace ((unsigned char)p[1]) || !p[1]
2275 || isspace ((unsigned char)p[-1])))
2277 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2279 #endif
2280 #ifdef HAVE_DOS_PATHS
2281 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2282 first colon which isn't followed by a slash or a backslash.
2283 Note that tokens separated by spaces should be treated as separate
2284 tokens since make doesn't allow path names with spaces */
2285 if (stopchar == ':')
2286 while (p != 0 && !isspace ((unsigned char)*p) &&
2287 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2288 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2289 #endif
2290 if (p == 0)
2291 p = q + strlen (q);
2293 if (strip)
2294 #ifdef VMS
2295 /* Skip leading `[]'s. */
2296 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2297 #else
2298 /* Skip leading `./'s. */
2299 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2300 #endif
2302 q += 2; /* Skip "./". */
2303 while (q < p && *q == '/')
2304 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2305 ++q;
2308 /* Extract the filename just found, and skip it. */
2310 if (q == p)
2311 /* ".///" was stripped to "". */
2312 #ifdef VMS
2313 continue;
2314 #else
2315 #ifdef _AMIGA
2316 name = savestring ("", 0);
2317 #else
2318 name = savestring ("./", 2);
2319 #endif
2320 #endif
2321 else
2322 #ifdef VMS
2323 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2324 * to remove this '\' before we can use the filename.
2325 * Savestring called because q may be read-only string constant.
2328 char *qbase = xstrdup (q);
2329 char *pbase = qbase + (p-q);
2330 char *q1 = qbase;
2331 char *q2 = q1;
2332 char *p1 = pbase;
2334 while (q1 != pbase)
2336 if (*q1 == '\\' && *(q1+1) == ':')
2338 q1++;
2339 p1--;
2341 *q2++ = *q1++;
2343 name = savestring (qbase, p1 - qbase);
2344 free (qbase);
2346 #else
2347 name = savestring (q, p - q);
2348 #endif
2350 /* Add it to the front of the chain. */
2351 new1 = (struct nameseq *) xmalloc (size);
2352 new1->name = name;
2353 new1->next = new;
2354 new = new1;
2357 #ifndef NO_ARCHIVES
2359 /* Look for multi-word archive references.
2360 They are indicated by a elt ending with an unmatched `)' and
2361 an elt further down the chain (i.e., previous in the file list)
2362 with an unmatched `(' (e.g., "lib(mem"). */
2364 new1 = new;
2365 lastnew1 = 0;
2366 while (new1 != 0)
2367 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2368 && new1->name[strlen (new1->name) - 1] == ')'
2369 && strchr (new1->name, '(') == 0)
2371 /* NEW1 ends with a `)' but does not contain a `('.
2372 Look back for an elt with an opening `(' but no closing `)'. */
2374 struct nameseq *n = new1->next, *lastn = new1;
2375 char *paren = 0;
2376 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2378 lastn = n;
2379 n = n->next;
2381 if (n != 0
2382 /* Ignore something starting with `(', as that cannot actually
2383 be an archive-member reference (and treating it as such
2384 results in an empty file name, which causes much lossage). */
2385 && n->name[0] != '(')
2387 /* N is the first element in the archive group.
2388 Its name looks like "lib(mem" (with no closing `)'). */
2390 char *libname;
2392 /* Copy "lib(" into LIBNAME. */
2393 ++paren;
2394 libname = (char *) alloca (paren - n->name + 1);
2395 bcopy (n->name, libname, paren - n->name);
2396 libname[paren - n->name] = '\0';
2398 if (*paren == '\0')
2400 /* N was just "lib(", part of something like "lib( a b)".
2401 Edit it out of the chain and free its storage. */
2402 lastn->next = n->next;
2403 free (n->name);
2404 free ((char *) n);
2405 /* LASTN->next is the new stopping elt for the loop below. */
2406 n = lastn->next;
2408 else
2410 /* Replace N's name with the full archive reference. */
2411 name = concat (libname, paren, ")");
2412 free (n->name);
2413 n->name = name;
2416 if (new1->name[1] == '\0')
2418 /* NEW1 is just ")", part of something like "lib(a b )".
2419 Omit it from the chain and free its storage. */
2420 if (lastnew1 == 0)
2421 new = new1->next;
2422 else
2423 lastnew1->next = new1->next;
2424 lastn = new1;
2425 new1 = new1->next;
2426 free (lastn->name);
2427 free ((char *) lastn);
2429 else
2431 /* Replace also NEW1->name, which already has closing `)'. */
2432 name = concat (libname, new1->name, "");
2433 free (new1->name);
2434 new1->name = name;
2435 new1 = new1->next;
2438 /* Trace back from NEW1 (the end of the list) until N
2439 (the beginning of the list), rewriting each name
2440 with the full archive reference. */
2442 while (new1 != n)
2444 name = concat (libname, new1->name, ")");
2445 free (new1->name);
2446 new1->name = name;
2447 lastnew1 = new1;
2448 new1 = new1->next;
2451 else
2453 /* No frobnication happening. Just step down the list. */
2454 lastnew1 = new1;
2455 new1 = new1->next;
2458 else
2460 lastnew1 = new1;
2461 new1 = new1->next;
2464 #endif
2466 *stringp = p;
2467 return new;
2470 /* Find the next line of text in an eval buffer, combining continuation lines
2471 into one line.
2472 Return the number of actual lines read (> 1 if continuation lines).
2473 Returns -1 if there's nothing left in the buffer.
2475 After this function, ebuf->buffer points to the first character of the
2476 line we just found.
2479 /* Read a line of text from a STRING.
2480 Since we aren't really reading from a file, don't bother with linenumbers.
2483 static unsigned long
2484 readstring (struct ebuffer *ebuf)
2486 char *eol;
2488 /* If there is nothing left in this buffer, return 0. */
2489 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2490 return -1;
2492 /* Set up a new starting point for the buffer, and find the end of the
2493 next logical line (taking into account backslash/newline pairs). */
2495 eol = ebuf->buffer = ebuf->bufnext;
2497 while (1)
2499 int backslash = 0;
2500 char *bol = eol;
2501 char *p;
2503 /* Find the next newline. At EOS, stop. */
2504 eol = p = strchr (eol , '\n');
2505 if (!eol)
2507 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2508 return 0;
2511 /* Found a newline; if it's escaped continue; else we're done. */
2512 while (p > bol && *(--p) == '\\')
2513 backslash = !backslash;
2514 if (!backslash)
2515 break;
2516 ++eol;
2519 /* Overwrite the newline char. */
2520 *eol = '\0';
2521 ebuf->bufnext = eol+1;
2523 return 0;
2526 static long
2527 readline (struct ebuffer *ebuf)
2529 char *p;
2530 char *end;
2531 char *start;
2532 long nlines = 0;
2534 /* The behaviors between string and stream buffers are different enough to
2535 warrant different functions. Do the Right Thing. */
2537 if (!ebuf->fp)
2538 return readstring (ebuf);
2540 /* When reading from a file, we always start over at the beginning of the
2541 buffer for each new line. */
2543 p = start = ebuf->bufstart;
2544 end = p + ebuf->size;
2545 *p = '\0';
2547 while (fgets (p, end - p, ebuf->fp) != 0)
2549 char *p2;
2550 unsigned long len;
2551 int backslash;
2553 len = strlen (p);
2554 if (len == 0)
2556 /* This only happens when the first thing on the line is a '\0'.
2557 It is a pretty hopeless case, but (wonder of wonders) Athena
2558 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2559 There is nothing really to be done; we synthesize a newline so
2560 the following line doesn't appear to be part of this line. */
2561 error (&ebuf->floc,
2562 _("warning: NUL character seen; rest of line ignored"));
2563 p[0] = '\n';
2564 len = 1;
2567 /* Jump past the text we just read. */
2568 p += len;
2570 /* If the last char isn't a newline, the whole line didn't fit into the
2571 buffer. Get some more buffer and try again. */
2572 if (p[-1] != '\n')
2573 goto more_buffer;
2575 /* We got a newline, so add one to the count of lines. */
2576 ++nlines;
2578 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2579 /* Check to see if the line was really ended with CRLF; if so ignore
2580 the CR. */
2581 if ((p - start) > 1 && p[-2] == '\r')
2583 --p;
2584 p[-1] = '\n';
2586 #endif
2588 backslash = 0;
2589 for (p2 = p - 2; p2 >= start; --p2)
2591 if (*p2 != '\\')
2592 break;
2593 backslash = !backslash;
2596 if (!backslash)
2598 p[-1] = '\0';
2599 break;
2602 /* It was a backslash/newline combo. If we have more space, read
2603 another line. */
2604 if (end - p >= 80)
2605 continue;
2607 /* We need more space at the end of our buffer, so realloc it.
2608 Make sure to preserve the current offset of p. */
2609 more_buffer:
2611 unsigned long off = p - start;
2612 ebuf->size *= 2;
2613 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2614 ebuf->size);
2615 p = start + off;
2616 end = start + ebuf->size;
2617 *p = '\0';
2621 if (ferror (ebuf->fp))
2622 pfatal_with_name (ebuf->floc.filenm);
2624 /* If we found some lines, return how many.
2625 If we didn't, but we did find _something_, that indicates we read the last
2626 line of a file with no final newline; return 1.
2627 If we read nothing, we're at EOF; return -1. */
2629 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2632 /* Parse the next "makefile word" from the input buffer, and return info
2633 about it.
2635 A "makefile word" is one of:
2637 w_bogus Should never happen
2638 w_eol End of input
2639 w_static A static word; cannot be expanded
2640 w_variable A word containing one or more variables/functions
2641 w_colon A colon
2642 w_dcolon A double-colon
2643 w_semicolon A semicolon
2644 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2646 Note that this function is only used when reading certain parts of the
2647 makefile. Don't use it where special rules hold sway (RHS of a variable,
2648 in a command list, etc.) */
2650 static enum make_word_type
2651 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2653 enum make_word_type wtype = w_bogus;
2654 char *p = buffer, *beg;
2655 char c;
2657 /* Skip any leading whitespace. */
2658 while (isblank ((unsigned char)*p))
2659 ++p;
2661 beg = p;
2662 c = *(p++);
2663 switch (c)
2665 case '\0':
2666 wtype = w_eol;
2667 break;
2669 case ';':
2670 wtype = w_semicolon;
2671 break;
2673 case '=':
2674 wtype = w_varassign;
2675 break;
2677 case ':':
2678 wtype = w_colon;
2679 switch (*p)
2681 case ':':
2682 ++p;
2683 wtype = w_dcolon;
2684 break;
2686 case '=':
2687 ++p;
2688 wtype = w_varassign;
2689 break;
2691 break;
2693 case '+':
2694 case '?':
2695 if (*p == '=')
2697 ++p;
2698 wtype = w_varassign;
2699 break;
2702 default:
2703 if (delim && strchr (delim, c))
2704 wtype = w_static;
2705 break;
2708 /* Did we find something? If so, return now. */
2709 if (wtype != w_bogus)
2710 goto done;
2712 /* This is some non-operator word. A word consists of the longest
2713 string of characters that doesn't contain whitespace, one of [:=#],
2714 or [?+]=, or one of the chars in the DELIM string. */
2716 /* We start out assuming a static word; if we see a variable we'll
2717 adjust our assumptions then. */
2718 wtype = w_static;
2720 /* We already found the first value of "c", above. */
2721 while (1)
2723 char closeparen;
2724 int count;
2726 switch (c)
2728 case '\0':
2729 case ' ':
2730 case '\t':
2731 case '=':
2732 goto done_word;
2734 case ':':
2735 #ifdef HAVE_DOS_PATHS
2736 /* A word CAN include a colon in its drive spec. The drive
2737 spec is allowed either at the beginning of a word, or as part
2738 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2739 if (!(p - beg >= 2
2740 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2741 && (p - beg == 2 || p[-3] == '(')))
2742 #endif
2743 goto done_word;
2745 case '$':
2746 c = *(p++);
2747 if (c == '$')
2748 break;
2750 /* This is a variable reference, so note that it's expandable.
2751 Then read it to the matching close paren. */
2752 wtype = w_variable;
2754 if (c == '(')
2755 closeparen = ')';
2756 else if (c == '{')
2757 closeparen = '}';
2758 else
2759 /* This is a single-letter variable reference. */
2760 break;
2762 for (count=0; *p != '\0'; ++p)
2764 if (*p == c)
2765 ++count;
2766 else if (*p == closeparen && --count < 0)
2768 ++p;
2769 break;
2772 break;
2774 case '?':
2775 case '+':
2776 if (*p == '=')
2777 goto done_word;
2778 break;
2780 case '\\':
2781 switch (*p)
2783 case ':':
2784 case ';':
2785 case '=':
2786 case '\\':
2787 ++p;
2788 break;
2790 break;
2792 default:
2793 if (delim && strchr (delim, c))
2794 goto done_word;
2795 break;
2798 c = *(p++);
2800 done_word:
2801 --p;
2803 done:
2804 if (startp)
2805 *startp = beg;
2806 if (length)
2807 *length = p - beg;
2808 return wtype;
2811 /* Construct the list of include directories
2812 from the arguments and the default list. */
2814 void
2815 construct_include_path (char **arg_dirs)
2817 register unsigned int i;
2818 #ifdef VAXC /* just don't ask ... */
2819 stat_t stbuf;
2820 #else
2821 struct stat stbuf;
2822 #endif
2823 /* Table to hold the dirs. */
2825 register unsigned int defsize = (sizeof (default_include_directories)
2826 / sizeof (default_include_directories[0]));
2827 register unsigned int max = 5;
2828 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2829 register unsigned int idx = 0;
2831 #ifdef __MSDOS__
2832 defsize++;
2833 #endif
2835 /* First consider any dirs specified with -I switches.
2836 Ignore dirs that don't exist. */
2838 if (arg_dirs != 0)
2839 while (*arg_dirs != 0)
2841 char *dir = *arg_dirs++;
2842 int e;
2844 if (dir[0] == '~')
2846 char *expanded = tilde_expand (dir);
2847 if (expanded != 0)
2848 dir = expanded;
2851 EINTRLOOP (e, stat (dir, &stbuf));
2852 if (e == 0 && S_ISDIR (stbuf.st_mode))
2854 if (idx == max - 1)
2856 max += 5;
2857 dirs = (char **)
2858 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2860 dirs[idx++] = dir;
2862 else if (dir != arg_dirs[-1])
2863 free (dir);
2866 /* Now add at the end the standard default dirs. */
2868 #ifdef __MSDOS__
2870 /* The environment variable $DJDIR holds the root of the
2871 DJGPP directory tree; add ${DJDIR}/include. */
2872 struct variable *djdir = lookup_variable ("DJDIR", 5);
2874 if (djdir)
2876 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2878 strcat (strcpy (defdir, djdir->value), "/include");
2879 dirs[idx++] = defdir;
2882 #endif
2884 for (i = 0; default_include_directories[i] != 0; ++i)
2886 int e;
2888 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2889 if (e == 0 && S_ISDIR (stbuf.st_mode))
2890 dirs[idx++] = default_include_directories[i];
2893 dirs[idx] = 0;
2895 /* Now compute the maximum length of any name in it. */
2897 max_incl_len = 0;
2898 for (i = 0; i < idx; ++i)
2900 unsigned int len = strlen (dirs[i]);
2901 /* If dir name is written with a trailing slash, discard it. */
2902 if (dirs[i][len - 1] == '/')
2903 /* We can't just clobber a null in because it may have come from
2904 a literal string and literal strings may not be writable. */
2905 dirs[i] = savestring (dirs[i], len - 1);
2906 if (len > max_incl_len)
2907 max_incl_len = len;
2910 include_directories = dirs;
2913 /* Expand ~ or ~USER at the beginning of NAME.
2914 Return a newly malloc'd string or 0. */
2916 char *
2917 tilde_expand (char *name)
2919 #ifndef VMS
2920 if (name[1] == '/' || name[1] == '\0')
2922 extern char *getenv ();
2923 char *home_dir;
2924 int is_variable;
2927 /* Turn off --warn-undefined-variables while we expand HOME. */
2928 int save = warn_undefined_variables_flag;
2929 warn_undefined_variables_flag = 0;
2931 home_dir = allocated_variable_expand ("$(HOME)");
2933 warn_undefined_variables_flag = save;
2936 is_variable = home_dir[0] != '\0';
2937 if (!is_variable)
2939 free (home_dir);
2940 home_dir = getenv ("HOME");
2942 #if !defined(_AMIGA) && !defined(WINDOWS32)
2943 if (home_dir == 0 || home_dir[0] == '\0')
2945 extern char *getlogin ();
2946 char *logname = getlogin ();
2947 home_dir = 0;
2948 if (logname != 0)
2950 struct passwd *p = getpwnam (logname);
2951 if (p != 0)
2952 home_dir = p->pw_dir;
2955 #endif /* !AMIGA && !WINDOWS32 */
2956 if (home_dir != 0)
2958 char *new = concat (home_dir, "", name + 1);
2959 if (is_variable)
2960 free (home_dir);
2961 return new;
2964 #if !defined(_AMIGA) && !defined(WINDOWS32)
2965 else
2967 struct passwd *pwent;
2968 char *userend = strchr (name + 1, '/');
2969 if (userend != 0)
2970 *userend = '\0';
2971 pwent = getpwnam (name + 1);
2972 if (pwent != 0)
2974 if (userend == 0)
2975 return xstrdup (pwent->pw_dir);
2976 else
2977 return concat (pwent->pw_dir, "/", userend + 1);
2979 else if (userend != 0)
2980 *userend = '/';
2982 #endif /* !AMIGA && !WINDOWS32 */
2983 #endif /* !VMS */
2984 return 0;
2987 /* Given a chain of struct nameseq's describing a sequence of filenames,
2988 in reverse of the intended order, return a new chain describing the
2989 result of globbing the filenames. The new chain is in forward order.
2990 The links of the old chain are freed or used in the new chain.
2991 Likewise for the names in the old chain.
2993 SIZE is how big to construct chain elements.
2994 This is useful if we want them actually to be other structures
2995 that have room for additional info. */
2997 struct nameseq *
2998 multi_glob (struct nameseq *chain, unsigned int size)
3000 extern void dir_setup_glob ();
3001 register struct nameseq *new = 0;
3002 register struct nameseq *old;
3003 struct nameseq *nexto;
3004 glob_t gl;
3006 dir_setup_glob (&gl);
3008 for (old = chain; old != 0; old = nexto)
3010 #ifndef NO_ARCHIVES
3011 char *memname;
3012 #endif
3014 nexto = old->next;
3016 if (old->name[0] == '~')
3018 char *newname = tilde_expand (old->name);
3019 if (newname != 0)
3021 free (old->name);
3022 old->name = newname;
3026 #ifndef NO_ARCHIVES
3027 if (ar_name (old->name))
3029 /* OLD->name is an archive member reference.
3030 Replace it with the archive file name,
3031 and save the member name in MEMNAME.
3032 We will glob on the archive name and then
3033 reattach MEMNAME later. */
3034 char *arname;
3035 ar_parse_name (old->name, &arname, &memname);
3036 free (old->name);
3037 old->name = arname;
3039 else
3040 memname = 0;
3041 #endif /* !NO_ARCHIVES */
3043 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3045 case 0: /* Success. */
3047 register int i = gl.gl_pathc;
3048 while (i-- > 0)
3050 #ifndef NO_ARCHIVES
3051 if (memname != 0)
3053 /* Try to glob on MEMNAME within the archive. */
3054 struct nameseq *found
3055 = ar_glob (gl.gl_pathv[i], memname, size);
3056 if (found == 0)
3058 /* No matches. Use MEMNAME as-is. */
3059 unsigned int alen = strlen (gl.gl_pathv[i]);
3060 unsigned int mlen = strlen (memname);
3061 struct nameseq *elt
3062 = (struct nameseq *) xmalloc (size);
3063 if (size > sizeof (struct nameseq))
3064 bzero (((char *) elt) + sizeof (struct nameseq),
3065 size - sizeof (struct nameseq));
3066 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3067 bcopy (gl.gl_pathv[i], elt->name, alen);
3068 elt->name[alen] = '(';
3069 bcopy (memname, &elt->name[alen + 1], mlen);
3070 elt->name[alen + 1 + mlen] = ')';
3071 elt->name[alen + 1 + mlen + 1] = '\0';
3072 elt->next = new;
3073 new = elt;
3075 else
3077 /* Find the end of the FOUND chain. */
3078 struct nameseq *f = found;
3079 while (f->next != 0)
3080 f = f->next;
3082 /* Attach the chain being built to the end of the FOUND
3083 chain, and make FOUND the new NEW chain. */
3084 f->next = new;
3085 new = found;
3088 free (memname);
3090 else
3091 #endif /* !NO_ARCHIVES */
3093 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3094 if (size > sizeof (struct nameseq))
3095 bzero (((char *) elt) + sizeof (struct nameseq),
3096 size - sizeof (struct nameseq));
3097 elt->name = xstrdup (gl.gl_pathv[i]);
3098 elt->next = new;
3099 new = elt;
3102 globfree (&gl);
3103 free (old->name);
3104 free ((char *)old);
3105 break;
3108 case GLOB_NOSPACE:
3109 fatal (NILF, _("virtual memory exhausted"));
3110 break;
3112 default:
3113 old->next = new;
3114 new = old;
3115 break;
3119 return new;