Make second expansion optional (partial implementation).
[make/kirr.git] / read.c
blobbad07eb863618413856dbe740de843c5b0ea2663
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));
146 static void remove_comments PARAMS ((char *line));
147 static char *find_char_unquote PARAMS ((char *string, int stop1,
148 int stop2, int blank, int ignorevars));
150 /* Read in all the makefiles and return the chain of their names. */
152 struct dep *
153 read_all_makefiles (char **makefiles)
155 unsigned int num_makefiles = 0;
157 /* Create *_LIST variables, to hold the makefiles, targets, and variables
158 we will be reading. */
160 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
162 DB (DB_BASIC, (_("Reading makefiles...\n")));
164 /* If there's a non-null variable MAKEFILES, its value is a list of
165 files to read first thing. But don't let it prevent reading the
166 default makefiles and don't let the default goal come from there. */
169 char *value;
170 char *name, *p;
171 unsigned int length;
174 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
175 int save = warn_undefined_variables_flag;
176 warn_undefined_variables_flag = 0;
178 value = allocated_variable_expand ("$(MAKEFILES)");
180 warn_undefined_variables_flag = save;
183 /* Set NAME to the start of next token and LENGTH to its length.
184 MAKEFILES is updated for finding remaining tokens. */
185 p = value;
187 while ((name = find_next_token (&p, &length)) != 0)
189 if (*p != '\0')
190 *p++ = '\0';
191 name = xstrdup (name);
192 if (eval_makefile (name,
193 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
194 free (name);
197 free (value);
200 /* Read makefiles specified with -f switches. */
202 if (makefiles != 0)
203 while (*makefiles != 0)
205 struct dep *tail = read_makefiles;
206 register struct dep *d;
208 if (! eval_makefile (*makefiles, 0))
209 perror_with_name ("", *makefiles);
211 /* Find the right element of read_makefiles. */
212 d = read_makefiles;
213 while (d->next != tail)
214 d = d->next;
216 /* Use the storage read_makefile allocates. */
217 *makefiles = dep_name (d);
218 ++num_makefiles;
219 ++makefiles;
222 /* If there were no -f switches, try the default names. */
224 if (num_makefiles == 0)
226 static char *default_makefiles[] =
227 #ifdef VMS
228 /* all lower case since readdir() (the vms version) 'lowercasifies' */
229 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
230 #else
231 #ifdef _AMIGA
232 { "GNUmakefile", "Makefile", "SMakefile", 0 };
233 #else /* !Amiga && !VMS */
234 { "GNUmakefile", "makefile", "Makefile", 0 };
235 #endif /* AMIGA */
236 #endif /* VMS */
237 register char **p = default_makefiles;
238 while (*p != 0 && !file_exists_p (*p))
239 ++p;
241 if (*p != 0)
243 if (! eval_makefile (*p, 0))
244 perror_with_name ("", *p);
246 else
248 /* No default makefile was found. Add the default makefiles to the
249 `read_makefiles' chain so they will be updated if possible. */
250 struct dep *tail = read_makefiles;
251 /* Add them to the tail, after any MAKEFILES variable makefiles. */
252 while (tail != 0 && tail->next != 0)
253 tail = tail->next;
254 for (p = default_makefiles; *p != 0; ++p)
256 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
257 d->name = 0;
258 d->file = enter_file (*p);
259 d->file->dontcare = 1;
260 d->ignore_mtime = 0;
261 d->staticpattern = 0;
262 d->need_2nd_expansion = 0;
263 /* Tell update_goal_chain to bail out as soon as this file is
264 made, and main not to die if we can't make this file. */
265 d->changed = RM_DONTCARE;
266 if (tail == 0)
267 read_makefiles = d;
268 else
269 tail->next = d;
270 tail = d;
272 if (tail != 0)
273 tail->next = 0;
277 return read_makefiles;
280 /* Install a new conditional and return the previous one. */
282 static struct conditionals *
283 install_conditionals (struct conditionals *new)
285 struct conditionals *save = conditionals;
287 bzero ((char *) new, sizeof (*new));
288 conditionals = new;
290 return save;
293 /* Free the current conditionals and reinstate a saved one. */
295 static void
296 restore_conditionals (struct conditionals *saved)
298 /* Free any space allocated by conditional_line. */
299 if (conditionals->ignoring)
300 free (conditionals->ignoring);
301 if (conditionals->seen_else)
302 free (conditionals->seen_else);
304 /* Restore state. */
305 conditionals = saved;
308 static int
309 eval_makefile (char *filename, int flags)
311 struct dep *deps;
312 struct ebuffer ebuf;
313 const struct floc *curfile;
314 int makefile_errno;
315 int r;
317 ebuf.floc.filenm = filename;
318 ebuf.floc.lineno = 1;
320 if (ISDB (DB_VERBOSE))
322 printf (_("Reading makefile `%s'"), filename);
323 if (flags & RM_NO_DEFAULT_GOAL)
324 printf (_(" (no default goal)"));
325 if (flags & RM_INCLUDED)
326 printf (_(" (search path)"));
327 if (flags & RM_DONTCARE)
328 printf (_(" (don't care)"));
329 if (flags & RM_NO_TILDE)
330 printf (_(" (no ~ expansion)"));
331 puts ("...");
334 /* First, get a stream to read. */
336 /* Expand ~ in FILENAME unless it came from `include',
337 in which case it was already done. */
338 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
340 char *expanded = tilde_expand (filename);
341 if (expanded != 0)
342 filename = expanded;
345 ebuf.fp = fopen (filename, "r");
346 /* Save the error code so we print the right message later. */
347 makefile_errno = errno;
349 /* If the makefile wasn't found and it's either a makefile from
350 the `MAKEFILES' variable or an included makefile,
351 search the included makefile search path for this makefile. */
352 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
354 register unsigned int i;
355 for (i = 0; include_directories[i] != 0; ++i)
357 char *name = concat (include_directories[i], "/", filename);
358 ebuf.fp = fopen (name, "r");
359 if (ebuf.fp == 0)
360 free (name);
361 else
363 filename = name;
364 break;
369 /* Add FILENAME to the chain of read makefiles. */
370 deps = (struct dep *) xmalloc (sizeof (struct dep));
371 deps->next = read_makefiles;
372 read_makefiles = deps;
373 deps->name = 0;
374 deps->file = lookup_file (filename);
375 if (deps->file == 0)
376 deps->file = enter_file (xstrdup (filename));
377 if (filename != ebuf.floc.filenm)
378 free (filename);
379 filename = deps->file->name;
380 deps->changed = flags;
381 deps->ignore_mtime = 0;
382 deps->staticpattern = 0;
383 deps->need_2nd_expansion = 0;
384 if (flags & RM_DONTCARE)
385 deps->file->dontcare = 1;
387 /* If the makefile can't be found at all, give up entirely. */
389 if (ebuf.fp == 0)
391 /* If we did some searching, errno has the error from the last
392 attempt, rather from FILENAME itself. Restore it in case the
393 caller wants to use it in a message. */
394 errno = makefile_errno;
395 return 0;
398 /* Add this makefile to the list. */
399 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
400 f_append, 0);
402 /* Evaluate the makefile */
404 ebuf.size = 200;
405 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
407 curfile = reading_file;
408 reading_file = &ebuf.floc;
410 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
412 reading_file = curfile;
414 fclose (ebuf.fp);
416 free (ebuf.bufstart);
417 alloca (0);
418 return r;
422 eval_buffer (char *buffer)
424 struct ebuffer ebuf;
425 struct conditionals *saved;
426 struct conditionals new;
427 const struct floc *curfile;
428 int r;
430 /* Evaluate the buffer */
432 ebuf.size = strlen (buffer);
433 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
434 ebuf.fp = NULL;
436 ebuf.floc = *reading_file;
438 curfile = reading_file;
439 reading_file = &ebuf.floc;
441 saved = install_conditionals (&new);
443 r = eval (&ebuf, 1);
445 restore_conditionals (saved);
447 reading_file = curfile;
449 alloca (0);
450 return r;
454 /* Read file FILENAME as a makefile and add its contents to the data base.
456 SET_DEFAULT is true if we are allowed to set the default goal. */
459 static int
460 eval (struct ebuffer *ebuf, int set_default)
462 char *collapsed = 0;
463 unsigned int collapsed_length = 0;
464 unsigned int commands_len = 200;
465 char *commands;
466 unsigned int commands_idx = 0;
467 unsigned int cmds_started, tgts_started;
468 int ignoring = 0, in_ignored_define = 0;
469 int no_targets = 0; /* Set when reading a rule without targets. */
470 struct nameseq *filenames = 0;
471 struct dep *deps = 0;
472 long nlines = 0;
473 int two_colon = 0;
474 char *pattern = 0, *pattern_percent;
475 struct floc *fstart;
476 struct floc fi;
478 #define record_waiting_files() \
479 do \
481 if (filenames != 0) \
483 fi.lineno = tgts_started; \
484 record_files (filenames, pattern, pattern_percent, deps, \
485 cmds_started, commands, commands_idx, two_colon, \
486 &fi); \
488 filenames = 0; \
489 commands_idx = 0; \
490 no_targets = 0; \
491 if (pattern) { free(pattern); pattern = 0; } \
492 } while (0)
494 pattern_percent = 0;
495 cmds_started = tgts_started = 1;
497 fstart = &ebuf->floc;
498 fi.filenm = ebuf->floc.filenm;
500 /* Loop over lines in the file.
501 The strategy is to accumulate target names in FILENAMES, dependencies
502 in DEPS and commands in COMMANDS. These are used to define a rule
503 when the start of the next rule (or eof) is encountered.
505 When you see a "continue" in the loop below, that means we are moving on
506 to the next line _without_ ending any rule that we happen to be working
507 with at the moment. If you see a "goto rule_complete", then the
508 statement we just parsed also finishes the previous rule. */
510 commands = xmalloc (200);
512 while (1)
514 unsigned int linelen;
515 char *line;
516 int len;
517 char *p;
518 char *p2;
520 /* Grab the next line to be evaluated */
521 ebuf->floc.lineno += nlines;
522 nlines = readline (ebuf);
524 /* If there is nothing left to eval, we're done. */
525 if (nlines < 0)
526 break;
528 /* If this line is empty, skip it. */
529 line = ebuf->buffer;
530 if (line[0] == '\0')
531 continue;
533 linelen = strlen (line);
535 /* Check for a shell command line first.
536 If it is not one, we can stop treating tab specially. */
537 if (line[0] == '\t')
539 if (no_targets)
540 /* Ignore the commands in a rule with no targets. */
541 continue;
543 /* If there is no preceding rule line, don't treat this line
544 as a command, even though it begins with a tab character.
545 SunOS 4 make appears to behave this way. */
547 if (filenames != 0)
549 if (ignoring)
550 /* Yep, this is a shell command, and we don't care. */
551 continue;
553 /* Append this command line to the line being accumulated. */
554 if (commands_idx == 0)
555 cmds_started = ebuf->floc.lineno;
557 if (linelen + 1 + commands_idx > commands_len)
559 commands_len = (linelen + 1 + commands_idx) * 2;
560 commands = xrealloc (commands, commands_len);
562 bcopy (line, &commands[commands_idx], linelen);
563 commands_idx += linelen;
564 commands[commands_idx++] = '\n';
566 continue;
570 /* This line is not a shell command line. Don't worry about tabs.
571 Get more space if we need it; we don't need to preserve the current
572 contents of the buffer. */
574 if (collapsed_length < linelen+1)
576 collapsed_length = linelen+1;
577 if (collapsed)
578 free ((char *)collapsed);
579 collapsed = (char *) xmalloc (collapsed_length);
581 strcpy (collapsed, line);
582 /* Collapse continuation lines. */
583 collapse_continuations (collapsed);
584 remove_comments (collapsed);
586 /* Compare a word, both length and contents. */
587 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
588 p = collapsed;
589 while (isspace ((unsigned char)*p))
590 ++p;
592 if (*p == '\0')
593 /* This line is completely empty--ignore it. */
594 continue;
596 /* Find the end of the first token. Note we don't need to worry about
597 * ":" here since we compare tokens by length (so "export" will never
598 * be equal to "export:").
600 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
602 len = p2 - p;
604 /* Find the start of the second token. If it looks like a target or
605 variable definition it can't be a preprocessor token so skip
606 them--this allows variables/targets named `ifdef', `export', etc. */
607 while (isspace ((unsigned char)*p2))
608 ++p2;
610 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
612 /* It can't be a preprocessor token so skip it if we're ignoring */
613 if (ignoring)
614 continue;
616 goto skip_conditionals;
619 /* We must first check for conditional and `define' directives before
620 ignoring anything, since they control what we will do with
621 following lines. */
623 if (!in_ignored_define)
625 int i = conditional_line (p, len, fstart);
626 if (i != -2)
628 if (i == -1)
629 fatal (fstart, _("invalid syntax in conditional"));
631 ignoring = i;
632 continue;
636 if (word1eq ("endef"))
638 if (!in_ignored_define)
639 fatal (fstart, _("extraneous `endef'"));
640 in_ignored_define = 0;
641 continue;
644 if (word1eq ("define"))
646 if (ignoring)
647 in_ignored_define = 1;
648 else
650 if (*p2 == '\0')
651 fatal (fstart, _("empty variable name"));
653 /* Let the variable name be the whole rest of the line,
654 with trailing blanks stripped (comments have already been
655 removed), so it could be a complex variable/function
656 reference that might contain blanks. */
657 p = strchr (p2, '\0');
658 while (isblank ((unsigned char)p[-1]))
659 --p;
660 do_define (p2, p - p2, o_file, ebuf);
662 continue;
665 if (word1eq ("override"))
667 if (*p2 == '\0')
668 error (fstart, _("empty `override' directive"));
670 if (strneq (p2, "define", 6)
671 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
673 if (ignoring)
674 in_ignored_define = 1;
675 else
677 p2 = next_token (p2 + 6);
678 if (*p2 == '\0')
679 fatal (fstart, _("empty variable name"));
681 /* Let the variable name be the whole rest of the line,
682 with trailing blanks stripped (comments have already been
683 removed), so it could be a complex variable/function
684 reference that might contain blanks. */
685 p = strchr (p2, '\0');
686 while (isblank ((unsigned char)p[-1]))
687 --p;
688 do_define (p2, p - p2, o_override, ebuf);
691 else if (!ignoring
692 && !try_variable_definition (fstart, p2, o_override, 0))
693 error (fstart, _("invalid `override' directive"));
695 continue;
698 if (ignoring)
699 /* Ignore the line. We continue here so conditionals
700 can appear in the middle of a rule. */
701 continue;
703 if (word1eq ("export"))
705 /* 'export' by itself causes everything to be exported. */
706 if (*p2 == '\0')
707 export_all_variables = 1;
708 else
710 struct variable *v;
712 v = try_variable_definition (fstart, p2, o_file, 0);
713 if (v != 0)
714 v->export = v_export;
715 else
717 unsigned int len;
718 char *ap;
720 /* Expand the line so we can use indirect and constructed
721 variable names in an export command. */
722 p2 = ap = allocated_variable_expand (p2);
724 for (p = find_next_token (&p2, &len); p != 0;
725 p = find_next_token (&p2, &len))
727 v = lookup_variable (p, len);
728 if (v == 0)
729 v = define_variable_loc (p, len, "", o_file, 0,
730 fstart);
731 v->export = v_export;
734 free (ap);
737 goto rule_complete;
740 if (word1eq ("unexport"))
742 if (*p2 == '\0')
743 export_all_variables = 0;
744 else
746 unsigned int len;
747 struct variable *v;
748 char *ap;
750 /* Expand the line so we can use indirect and constructed
751 variable names in an unexport command. */
752 p2 = ap = allocated_variable_expand (p2);
754 for (p = find_next_token (&p2, &len); p != 0;
755 p = find_next_token (&p2, &len))
757 v = lookup_variable (p, len);
758 if (v == 0)
759 v = define_variable_loc (p, len, "", o_file, 0, fstart);
761 v->export = v_noexport;
764 free (ap);
766 goto rule_complete;
769 skip_conditionals:
770 if (word1eq ("vpath"))
772 char *pattern;
773 unsigned int len;
774 p2 = variable_expand (p2);
775 p = find_next_token (&p2, &len);
776 if (p != 0)
778 pattern = savestring (p, len);
779 p = find_next_token (&p2, &len);
780 /* No searchpath means remove all previous
781 selective VPATH's with the same pattern. */
783 else
784 /* No pattern means remove all previous selective VPATH's. */
785 pattern = 0;
786 construct_vpath_list (pattern, p);
787 if (pattern != 0)
788 free (pattern);
790 goto rule_complete;
793 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
795 /* We have found an `include' line specifying a nested
796 makefile to be read at this point. */
797 struct conditionals *save;
798 struct conditionals new_conditionals;
799 struct nameseq *files;
800 /* "-include" (vs "include") says no error if the file does not
801 exist. "sinclude" is an alias for this from SGI. */
802 int noerror = (p[0] != 'i');
804 p = allocated_variable_expand (p2);
806 /* If no filenames, it's a no-op. */
807 if (*p == '\0')
808 continue;
810 /* Parse the list of file names. */
811 p2 = p;
812 files = multi_glob (parse_file_seq (&p2, '\0',
813 sizeof (struct nameseq),
815 sizeof (struct nameseq));
816 free (p);
818 /* Save the state of conditionals and start
819 the included makefile with a clean slate. */
820 save = install_conditionals (&new_conditionals);
822 /* Record the rules that are waiting so they will determine
823 the default goal before those in the included makefile. */
824 record_waiting_files ();
826 /* Read each included makefile. */
827 while (files != 0)
829 struct nameseq *next = files->next;
830 char *name = files->name;
831 int r;
833 free ((char *)files);
834 files = next;
836 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
837 | (noerror ? RM_DONTCARE : 0)));
838 if (!r)
840 if (!noerror)
841 error (fstart, "%s: %s", name, strerror (errno));
842 free (name);
846 /* Restore conditional state. */
847 restore_conditionals (save);
849 goto rule_complete;
852 if (try_variable_definition (fstart, p, o_file, 0))
853 /* This line has been dealt with. */
854 goto rule_complete;
856 /* This line starts with a tab but was not caught above because there
857 was no preceding target, and the line might have been usable as a
858 variable definition. But now we know it is definitely lossage. */
859 if (line[0] == '\t')
860 fatal(fstart, _("commands commence before first target"));
862 /* This line describes some target files. This is complicated by
863 the existence of target-specific variables, because we can't
864 expand the entire line until we know if we have one or not. So
865 we expand the line word by word until we find the first `:',
866 then check to see if it's a target-specific variable.
868 In this algorithm, `lb_next' will point to the beginning of the
869 unexpanded parts of the input buffer, while `p2' points to the
870 parts of the expanded buffer we haven't searched yet. */
873 enum make_word_type wtype;
874 enum variable_origin v_origin;
875 int exported;
876 char *cmdleft, *semip, *lb_next;
877 unsigned int len, plen = 0;
878 char *colonp;
879 const char *end, *beg; /* Helpers for whitespace stripping. */
881 /* Record the previous rule. */
883 record_waiting_files ();
884 tgts_started = fstart->lineno;
886 /* Search the line for an unquoted ; that is not after an
887 unquoted #. */
888 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
889 if (cmdleft != 0 && *cmdleft == '#')
891 /* We found a comment before a semicolon. */
892 *cmdleft = '\0';
893 cmdleft = 0;
895 else if (cmdleft != 0)
896 /* Found one. Cut the line short there before expanding it. */
897 *(cmdleft++) = '\0';
898 semip = cmdleft;
900 collapse_continuations (line);
902 /* We can't expand the entire line, since if it's a per-target
903 variable we don't want to expand it. So, walk from the
904 beginning, expanding as we go, and looking for "interesting"
905 chars. The first word is always expandable. */
906 wtype = get_next_mword(line, NULL, &lb_next, &len);
907 switch (wtype)
909 case w_eol:
910 if (cmdleft != 0)
911 fatal(fstart, _("missing rule before commands"));
912 /* This line contained something but turned out to be nothing
913 but whitespace (a comment?). */
914 continue;
916 case w_colon:
917 case w_dcolon:
918 /* We accept and ignore rules without targets for
919 compatibility with SunOS 4 make. */
920 no_targets = 1;
921 continue;
923 default:
924 break;
927 p2 = variable_expand_string(NULL, lb_next, len);
929 while (1)
931 lb_next += len;
932 if (cmdleft == 0)
934 /* Look for a semicolon in the expanded line. */
935 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
937 if (cmdleft != 0)
939 unsigned long p2_off = p2 - variable_buffer;
940 unsigned long cmd_off = cmdleft - variable_buffer;
941 char *pend = p2 + strlen(p2);
943 /* Append any remnants of lb, then cut the line short
944 at the semicolon. */
945 *cmdleft = '\0';
947 /* One school of thought says that you shouldn't expand
948 here, but merely copy, since now you're beyond a ";"
949 and into a command script. However, the old parser
950 expanded the whole line, so we continue that for
951 backwards-compatiblity. Also, it wouldn't be
952 entirely consistent, since we do an unconditional
953 expand below once we know we don't have a
954 target-specific variable. */
955 (void)variable_expand_string(pend, lb_next, (long)-1);
956 lb_next += strlen(lb_next);
957 p2 = variable_buffer + p2_off;
958 cmdleft = variable_buffer + cmd_off + 1;
962 colonp = find_char_unquote(p2, ':', 0, 0, 0);
963 #ifdef HAVE_DOS_PATHS
964 /* The drive spec brain-damage strikes again... */
965 /* Note that the only separators of targets in this context
966 are whitespace and a left paren. If others are possible,
967 they should be added to the string in the call to index. */
968 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
969 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
970 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
971 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
972 #endif
973 if (colonp != 0)
974 break;
976 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
977 if (wtype == w_eol)
978 break;
980 p2 += strlen(p2);
981 *(p2++) = ' ';
982 p2 = variable_expand_string(p2, lb_next, len);
983 /* We don't need to worry about cmdleft here, because if it was
984 found in the variable_buffer the entire buffer has already
985 been expanded... we'll never get here. */
988 p2 = next_token (variable_buffer);
990 /* If the word we're looking at is EOL, see if there's _anything_
991 on the line. If not, a variable expanded to nothing, so ignore
992 it. If so, we can't parse this line so punt. */
993 if (wtype == w_eol)
995 if (*p2 != '\0')
996 /* There's no need to be ivory-tower about this: check for
997 one of the most common bugs found in makefiles... */
998 fatal (fstart, _("missing separator%s"),
999 !strneq(line, " ", 8) ? ""
1000 : _(" (did you mean TAB instead of 8 spaces?)"));
1001 continue;
1004 /* Make the colon the end-of-string so we know where to stop
1005 looking for targets. */
1006 *colonp = '\0';
1007 filenames = multi_glob (parse_file_seq (&p2, '\0',
1008 sizeof (struct nameseq),
1010 sizeof (struct nameseq));
1011 *p2 = ':';
1013 if (!filenames)
1015 /* We accept and ignore rules without targets for
1016 compatibility with SunOS 4 make. */
1017 no_targets = 1;
1018 continue;
1020 /* This should never be possible; we handled it above. */
1021 assert (*p2 != '\0');
1022 ++p2;
1024 /* Is this a one-colon or two-colon entry? */
1025 two_colon = *p2 == ':';
1026 if (two_colon)
1027 p2++;
1029 /* Test to see if it's a target-specific variable. Copy the rest
1030 of the buffer over, possibly temporarily (we'll expand it later
1031 if it's not a target-specific variable). PLEN saves the length
1032 of the unparsed section of p2, for later. */
1033 if (*lb_next != '\0')
1035 unsigned int l = p2 - variable_buffer;
1036 plen = strlen (p2);
1037 (void) variable_buffer_output (p2+plen,
1038 lb_next, strlen (lb_next)+1);
1039 p2 = variable_buffer + l;
1042 /* See if it's an "override" or "export" keyword; if so see if what
1043 comes after it looks like a variable definition. */
1045 wtype = get_next_mword (p2, NULL, &p, &len);
1047 v_origin = o_file;
1048 exported = 0;
1049 if (wtype == w_static)
1051 if (word1eq ("override"))
1053 v_origin = o_override;
1054 wtype = get_next_mword (p+len, NULL, &p, &len);
1056 else if (word1eq ("export"))
1058 exported = 1;
1059 wtype = get_next_mword (p+len, NULL, &p, &len);
1063 if (wtype != w_eol)
1064 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1066 if (wtype == w_varassign)
1068 /* If there was a semicolon found, add it back, plus anything
1069 after it. */
1070 if (semip)
1072 unsigned int l = p - variable_buffer;
1073 *(--semip) = ';';
1074 variable_buffer_output (p2 + strlen (p2),
1075 semip, strlen (semip)+1);
1076 p = variable_buffer + l;
1078 record_target_var (filenames, p, v_origin, exported, fstart);
1079 filenames = 0;
1080 continue;
1083 /* This is a normal target, _not_ a target-specific variable.
1084 Unquote any = in the dependency list. */
1085 find_char_unquote (lb_next, '=', 0, 0, 0);
1087 /* We have some targets, so don't ignore the following commands. */
1088 no_targets = 0;
1090 /* Expand the dependencies, etc. */
1091 if (*lb_next != '\0')
1093 unsigned int l = p2 - variable_buffer;
1094 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1095 p2 = variable_buffer + l;
1097 /* Look for a semicolon in the expanded line. */
1098 if (cmdleft == 0)
1100 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1101 if (cmdleft != 0)
1102 *(cmdleft++) = '\0';
1106 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1107 p = strchr (p2, ':');
1108 while (p != 0 && p[-1] == '\\')
1110 register char *q = &p[-1];
1111 register int backslash = 0;
1112 while (*q-- == '\\')
1113 backslash = !backslash;
1114 if (backslash)
1115 p = strchr (p + 1, ':');
1116 else
1117 break;
1119 #ifdef _AMIGA
1120 /* Here, the situation is quite complicated. Let's have a look
1121 at a couple of targets:
1123 install: dev:make
1125 dev:make: make
1127 dev:make:: xyz
1129 The rule is that it's only a target, if there are TWO :'s
1130 OR a space around the :.
1132 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1133 || isspace ((unsigned char)p[-1])))
1134 p = 0;
1135 #endif
1136 #ifdef HAVE_DOS_PATHS
1138 int check_again;
1140 do {
1141 check_again = 0;
1142 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1143 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1144 isalpha ((unsigned char)p[-1]) &&
1145 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1146 p = strchr (p + 1, ':');
1147 check_again = 1;
1149 } while (check_again);
1151 #endif
1152 if (p != 0)
1154 struct nameseq *target;
1155 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1156 ++p2;
1157 if (target == 0)
1158 fatal (fstart, _("missing target pattern"));
1159 else if (target->next != 0)
1160 fatal (fstart, _("multiple target patterns"));
1161 pattern = target->name;
1162 pattern_percent = find_percent (pattern);
1163 if (pattern_percent == 0)
1164 fatal (fstart, _("target pattern contains no `%%'"));
1165 free ((char *)target);
1167 else
1168 pattern = 0;
1170 /* Strip leading and trailing whitespaces. */
1171 beg = p2;
1172 end = beg + strlen (beg) - 1;
1173 strip_whitespace (&beg, &end);
1175 if (beg <= end && *beg != '\0')
1177 /* Put all the prerequisites here; they'll be parsed later. */
1178 deps = (struct dep *) xmalloc (sizeof (struct dep));
1179 deps->next = 0;
1180 deps->name = xstrdup (beg);
1181 deps->staticpattern = 0;
1182 deps->need_2nd_expansion = 0;
1183 deps->file = 0;
1185 else
1186 deps = 0;
1188 commands_idx = 0;
1189 if (cmdleft != 0)
1191 /* Semicolon means rest of line is a command. */
1192 unsigned int len = strlen (cmdleft);
1194 cmds_started = fstart->lineno;
1196 /* Add this command line to the buffer. */
1197 if (len + 2 > commands_len)
1199 commands_len = (len + 2) * 2;
1200 commands = (char *) xrealloc (commands, commands_len);
1202 bcopy (cmdleft, commands, len);
1203 commands_idx += len;
1204 commands[commands_idx++] = '\n';
1207 /* Determine if this target should be made default. We used to do
1208 this in record_files() but because of the delayed target recording
1209 and because preprocessor directives are legal in target's commands
1210 it is too late. Consider this fragment for example:
1212 foo:
1214 ifeq ($(.DEFAULT_GOAL),foo)
1216 endif
1218 Because the target is not recorded until after ifeq directive is
1219 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1220 would expect. Because of this we have to move some of the logic
1221 here. */
1223 if (**default_goal_name == '\0' && set_default)
1225 char* name;
1226 struct dep *d;
1227 struct nameseq *t = filenames;
1229 for (; t != 0; t = t->next)
1231 int reject = 0;
1232 name = t->name;
1234 /* We have nothing to do if this is an implicit rule. */
1235 if (strchr (name, '%') != 0)
1236 break;
1238 /* See if this target's name does not start with a `.',
1239 unless it contains a slash. */
1240 if (*name == '.' && strchr (name, '/') == 0
1241 #ifdef HAVE_DOS_PATHS
1242 && strchr (name, '\\') == 0
1243 #endif
1245 continue;
1248 /* If this file is a suffix, don't let it be
1249 the default goal file. */
1250 for (d = suffix_file->deps; d != 0; d = d->next)
1252 register struct dep *d2;
1253 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1255 reject = 1;
1256 break;
1258 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1260 register unsigned int len = strlen (dep_name (d2));
1261 if (!strneq (name, dep_name (d2), len))
1262 continue;
1263 if (streq (name + len, dep_name (d)))
1265 reject = 1;
1266 break;
1270 if (reject)
1271 break;
1274 if (!reject)
1276 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1277 o_file, 0, NILF);
1278 break;
1283 continue;
1286 /* We get here except in the case that we just read a rule line.
1287 Record now the last rule we read, so following spurious
1288 commands are properly diagnosed. */
1289 rule_complete:
1290 record_waiting_files ();
1293 #undef word1eq
1295 if (conditionals->if_cmds)
1296 fatal (fstart, _("missing `endif'"));
1298 /* At eof, record the last rule. */
1299 record_waiting_files ();
1301 if (collapsed)
1302 free ((char *) collapsed);
1303 free ((char *) commands);
1305 return 1;
1309 /* Remove comments from LINE.
1310 This is done by copying the text at LINE onto itself. */
1312 static void
1313 remove_comments (char *line)
1315 char *comment;
1317 comment = find_char_unquote (line, '#', 0, 0, 0);
1319 if (comment != 0)
1320 /* Cut off the line at the #. */
1321 *comment = '\0';
1324 /* Execute a `define' directive.
1325 The first line has already been read, and NAME is the name of
1326 the variable to be defined. The following lines remain to be read. */
1328 static void
1329 do_define (char *name, unsigned int namelen,
1330 enum variable_origin origin, struct ebuffer *ebuf)
1332 struct floc defstart;
1333 long nlines = 0;
1334 int nlevels = 1;
1335 unsigned int length = 100;
1336 char *definition = (char *) xmalloc (length);
1337 unsigned int idx = 0;
1338 char *p;
1340 /* Expand the variable name. */
1341 char *var = (char *) alloca (namelen + 1);
1342 bcopy (name, var, namelen);
1343 var[namelen] = '\0';
1344 var = variable_expand (var);
1346 defstart = ebuf->floc;
1348 while (1)
1350 unsigned int len;
1351 char *line;
1353 nlines = readline (ebuf);
1354 ebuf->floc.lineno += nlines;
1356 /* If there is nothing left to eval, we're done. */
1357 if (nlines < 0)
1358 break;
1360 line = ebuf->buffer;
1362 collapse_continuations (line);
1364 /* If the line doesn't begin with a tab, test to see if it introduces
1365 another define, or ends one. */
1367 /* Stop if we find an 'endef' */
1368 if (line[0] != '\t')
1370 p = next_token (line);
1371 len = strlen (p);
1373 /* If this is another 'define', increment the level count. */
1374 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1375 && strneq (p, "define", 6))
1376 ++nlevels;
1378 /* If this is an 'endef', decrement the count. If it's now 0,
1379 we've found the last one. */
1380 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1381 && strneq (p, "endef", 5))
1383 p += 5;
1384 remove_comments (p);
1385 if (*next_token (p) != '\0')
1386 error (&ebuf->floc,
1387 _("Extraneous text after `endef' directive"));
1389 if (--nlevels == 0)
1391 /* Define the variable. */
1392 if (idx == 0)
1393 definition[0] = '\0';
1394 else
1395 definition[idx - 1] = '\0';
1397 /* Always define these variables in the global set. */
1398 define_variable_global (var, strlen (var), definition,
1399 origin, 1, &defstart);
1400 free (definition);
1401 return;
1406 /* Otherwise add this line to the variable definition. */
1407 len = strlen (line);
1408 if (idx + len + 1 > length)
1410 length = (idx + len) * 2;
1411 definition = (char *) xrealloc (definition, length + 1);
1414 bcopy (line, &definition[idx], len);
1415 idx += len;
1416 /* Separate lines with a newline. */
1417 definition[idx++] = '\n';
1420 /* No `endef'!! */
1421 fatal (&defstart, _("missing `endef', unterminated `define'"));
1423 /* NOTREACHED */
1424 return;
1427 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1428 "ifneq", "else" and "endif".
1429 LINE is the input line, with the command as its first word.
1431 FILENAME and LINENO are the filename and line number in the
1432 current makefile. They are used for error messages.
1434 Value is -2 if the line is not a conditional at all,
1435 -1 if the line is an invalid conditional,
1436 0 if following text should be interpreted,
1437 1 if following text should be ignored. */
1439 static int
1440 conditional_line (char *line, int len, const struct floc *flocp)
1442 char *cmdname;
1443 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1444 unsigned int i;
1445 unsigned int o;
1447 /* Compare a word, both length and contents. */
1448 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1449 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1451 /* Make sure this line is a conditional. */
1452 chkword ("ifdef", c_ifdef)
1453 else chkword ("ifndef", c_ifndef)
1454 else chkword ("ifeq", c_ifeq)
1455 else chkword ("ifneq", c_ifneq)
1456 else chkword ("else", c_else)
1457 else chkword ("endif", c_endif)
1458 else
1459 return -2;
1461 /* Found one: skip past it and any whitespace after it. */
1462 line = next_token (line + len);
1464 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1466 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1467 if (cmdtype == c_endif)
1469 if (*line != '\0')
1470 EXTRANEOUS ();
1472 if (!conditionals->if_cmds)
1473 fatal (flocp, _("extraneous `%s'"), cmdname);
1475 --conditionals->if_cmds;
1477 goto DONE;
1480 /* An 'else' statement can either be simple, or it can have another
1481 conditional after it. */
1482 if (cmdtype == c_else)
1484 const char *p;
1486 if (!conditionals->if_cmds)
1487 fatal (flocp, _("extraneous `%s'"), cmdname);
1489 o = conditionals->if_cmds - 1;
1491 if (conditionals->seen_else[o])
1492 fatal (flocp, _("only one `else' per conditional"));
1494 /* Change the state of ignorance. */
1495 switch (conditionals->ignoring[o])
1497 case 0:
1498 /* We've just been interpreting. Never do it again. */
1499 conditionals->ignoring[o] = 2;
1500 break;
1501 case 1:
1502 /* We've never interpreted yet. Maybe this time! */
1503 conditionals->ignoring[o] = 0;
1504 break;
1507 /* It's a simple 'else'. */
1508 if (*line == '\0')
1510 conditionals->seen_else[o] = 1;
1511 goto DONE;
1514 /* The 'else' has extra text. That text must be another conditional
1515 and cannot be an 'else' or 'endif'. */
1517 /* Find the length of the next word. */
1518 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1520 len = p - line;
1522 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1523 if (word1eq("else") || word1eq("endif")
1524 || conditional_line (line, len, flocp) < 0)
1525 EXTRANEOUS ();
1526 else
1528 /* conditional_line() created a new level of conditional.
1529 Raise it back to this level. */
1530 if (conditionals->ignoring[o] < 2)
1531 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1532 --conditionals->if_cmds;
1535 goto DONE;
1538 if (conditionals->allocated == 0)
1540 conditionals->allocated = 5;
1541 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1542 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1545 o = conditionals->if_cmds++;
1546 if (conditionals->if_cmds > conditionals->allocated)
1548 conditionals->allocated += 5;
1549 conditionals->ignoring = (char *)
1550 xrealloc (conditionals->ignoring, conditionals->allocated);
1551 conditionals->seen_else = (char *)
1552 xrealloc (conditionals->seen_else, conditionals->allocated);
1555 /* Record that we have seen an `if...' but no `else' so far. */
1556 conditionals->seen_else[o] = 0;
1558 /* Search through the stack to see if we're already ignoring. */
1559 for (i = 0; i < o; ++i)
1560 if (conditionals->ignoring[i])
1562 /* We are already ignoring, so just push a level to match the next
1563 "else" or "endif", and keep ignoring. We don't want to expand
1564 variables in the condition. */
1565 conditionals->ignoring[o] = 1;
1566 return 1;
1569 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1571 char *var;
1572 struct variable *v;
1573 char *p;
1575 /* Expand the thing we're looking up, so we can use indirect and
1576 constructed variable names. */
1577 var = allocated_variable_expand (line);
1579 /* Make sure there's only one variable name to test. */
1580 p = end_of_token (var);
1581 i = p - var;
1582 p = next_token (p);
1583 if (*p != '\0')
1584 return -1;
1586 var[i] = '\0';
1587 v = lookup_variable (var, i);
1589 conditionals->ignoring[o] =
1590 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1592 free (var);
1594 else
1596 /* "Ifeq" or "ifneq". */
1597 char *s1, *s2;
1598 unsigned int len;
1599 char termin = *line == '(' ? ',' : *line;
1601 if (termin != ',' && termin != '"' && termin != '\'')
1602 return -1;
1604 s1 = ++line;
1605 /* Find the end of the first string. */
1606 if (termin == ',')
1608 int count = 0;
1609 for (; *line != '\0'; ++line)
1610 if (*line == '(')
1611 ++count;
1612 else if (*line == ')')
1613 --count;
1614 else if (*line == ',' && count <= 0)
1615 break;
1617 else
1618 while (*line != '\0' && *line != termin)
1619 ++line;
1621 if (*line == '\0')
1622 return -1;
1624 if (termin == ',')
1626 /* Strip blanks after the first string. */
1627 char *p = line++;
1628 while (isblank ((unsigned char)p[-1]))
1629 --p;
1630 *p = '\0';
1632 else
1633 *line++ = '\0';
1635 s2 = variable_expand (s1);
1636 /* We must allocate a new copy of the expanded string because
1637 variable_expand re-uses the same buffer. */
1638 len = strlen (s2);
1639 s1 = (char *) alloca (len + 1);
1640 bcopy (s2, s1, len + 1);
1642 if (termin != ',')
1643 /* Find the start of the second string. */
1644 line = next_token (line);
1646 termin = termin == ',' ? ')' : *line;
1647 if (termin != ')' && termin != '"' && termin != '\'')
1648 return -1;
1650 /* Find the end of the second string. */
1651 if (termin == ')')
1653 register int count = 0;
1654 s2 = next_token (line);
1655 for (line = s2; *line != '\0'; ++line)
1657 if (*line == '(')
1658 ++count;
1659 else if (*line == ')')
1661 if (count <= 0)
1662 break;
1663 else
1664 --count;
1668 else
1670 ++line;
1671 s2 = line;
1672 while (*line != '\0' && *line != termin)
1673 ++line;
1676 if (*line == '\0')
1677 return -1;
1679 *line = '\0';
1680 line = next_token (++line);
1681 if (*line != '\0')
1682 EXTRANEOUS ();
1684 s2 = variable_expand (s2);
1685 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1688 DONE:
1689 /* Search through the stack to see if we're ignoring. */
1690 for (i = 0; i < conditionals->if_cmds; ++i)
1691 if (conditionals->ignoring[i])
1692 return 1;
1693 return 0;
1696 /* Remove duplicate dependencies in CHAIN. */
1698 static unsigned long
1699 dep_hash_1 (const void *key)
1701 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1704 static unsigned long
1705 dep_hash_2 (const void *key)
1707 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1710 static int
1711 dep_hash_cmp (const void *x, const void *y)
1713 struct dep *dx = (struct dep *) x;
1714 struct dep *dy = (struct dep *) y;
1715 int cmp = strcmp (dep_name (dx), dep_name (dy));
1717 /* If the names are the same but ignore_mtimes are not equal, one of these
1718 is an order-only prerequisite and one isn't. That means that we should
1719 remove the one that isn't and keep the one that is. */
1721 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1722 dx->ignore_mtime = dy->ignore_mtime = 0;
1724 return cmp;
1728 void
1729 uniquize_deps (struct dep *chain)
1731 struct hash_table deps;
1732 register struct dep **depp;
1734 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1736 /* Make sure that no dependencies are repeated. This does not
1737 really matter for the purpose of updating targets, but it
1738 might make some names be listed twice for $^ and $?. */
1740 depp = &chain;
1741 while (*depp)
1743 struct dep *dep = *depp;
1744 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1745 if (HASH_VACANT (*dep_slot))
1747 hash_insert_at (&deps, dep, dep_slot);
1748 depp = &dep->next;
1750 else
1752 /* Don't bother freeing duplicates.
1753 It's dangerous and little benefit accrues. */
1754 *depp = dep->next;
1758 hash_free (&deps, 0);
1761 /* Record target-specific variable values for files FILENAMES.
1762 TWO_COLON is nonzero if a double colon was used.
1764 The links of FILENAMES are freed, and so are any names in it
1765 that are not incorporated into other data structures.
1767 If the target is a pattern, add the variable to the pattern-specific
1768 variable value list. */
1770 static void
1771 record_target_var (struct nameseq *filenames, char *defn,
1772 enum variable_origin origin, int exported,
1773 const struct floc *flocp)
1775 struct nameseq *nextf;
1776 struct variable_set_list *global;
1778 global = current_variable_set_list;
1780 /* If the variable is an append version, store that but treat it as a
1781 normal recursive variable. */
1783 for (; filenames != 0; filenames = nextf)
1785 struct variable *v;
1786 register char *name = filenames->name;
1787 char *fname;
1788 char *percent;
1789 struct pattern_var *p;
1791 nextf = filenames->next;
1792 free ((char *) filenames);
1794 /* If it's a pattern target, then add it to the pattern-specific
1795 variable list. */
1796 percent = find_percent (name);
1797 if (percent)
1799 /* Get a reference for this pattern-specific variable struct. */
1800 p = create_pattern_var (name, percent);
1801 p->variable.fileinfo = *flocp;
1802 /* I don't think this can fail since we already determined it was a
1803 variable definition. */
1804 v = parse_variable_definition (&p->variable, defn);
1805 assert (v != 0);
1807 if (v->flavor == f_simple)
1808 v->value = allocated_variable_expand (v->value);
1809 else
1810 v->value = xstrdup (v->value);
1812 fname = p->target;
1814 else
1816 struct file *f;
1818 /* Get a file reference for this file, and initialize it.
1819 We don't want to just call enter_file() because that allocates a
1820 new entry if the file is a double-colon, which we don't want in
1821 this situation. */
1822 f = lookup_file (name);
1823 if (!f)
1824 f = enter_file (name);
1825 else if (f->double_colon)
1826 f = f->double_colon;
1828 initialize_file_variables (f, 1);
1829 fname = f->name;
1831 current_variable_set_list = f->variables;
1832 v = try_variable_definition (flocp, defn, origin, 1);
1833 if (!v)
1834 error (flocp, _("Malformed target-specific variable definition"));
1835 current_variable_set_list = global;
1838 /* Set up the variable to be *-specific. */
1839 v->origin = origin;
1840 v->per_target = 1;
1841 if (exported)
1842 v->export = v_export;
1844 /* If it's not an override, check to see if there was a command-line
1845 setting. If so, reset the value. */
1846 if (origin != o_override)
1848 struct variable *gv;
1849 int len = strlen(v->name);
1851 gv = lookup_variable (v->name, len);
1852 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1854 if (v->value != 0)
1855 free (v->value);
1856 v->value = xstrdup (gv->value);
1857 v->origin = gv->origin;
1858 v->recursive = gv->recursive;
1859 v->append = 0;
1863 /* Free name if not needed further. */
1864 if (name != fname && (name < fname || name > fname + strlen (fname)))
1865 free (name);
1869 /* Record a description line for files FILENAMES,
1870 with dependencies DEPS, commands to execute described
1871 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1872 TWO_COLON is nonzero if a double colon was used.
1873 If not nil, PATTERN is the `%' pattern to make this
1874 a static pattern rule, and PATTERN_PERCENT is a pointer
1875 to the `%' within it.
1877 The links of FILENAMES are freed, and so are any names in it
1878 that are not incorporated into other data structures. */
1880 static void
1881 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1882 struct dep *deps, unsigned int cmds_started, char *commands,
1883 unsigned int commands_idx, int two_colon,
1884 const struct floc *flocp)
1886 struct nameseq *nextf;
1887 int implicit = 0;
1888 unsigned int max_targets = 0, target_idx = 0;
1889 char **targets = 0, **target_percents = 0;
1890 struct commands *cmds;
1892 /* If we've already snapped deps, that means we're in an eval being
1893 resolved after the makefiles have been read in. We can't add more rules
1894 at this time, since they won't get snapped and we'll get core dumps.
1895 See Savannah bug # 12124. */
1896 if (snapped_deps)
1897 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1899 if (commands_idx > 0)
1901 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1902 cmds->fileinfo.filenm = flocp->filenm;
1903 cmds->fileinfo.lineno = cmds_started;
1904 cmds->commands = savestring (commands, commands_idx);
1905 cmds->command_lines = 0;
1907 else
1908 cmds = 0;
1910 for (; filenames != 0; filenames = nextf)
1912 char *name = filenames->name;
1913 struct file *f;
1914 struct dep *this = 0;
1915 char *implicit_percent;
1917 nextf = filenames->next;
1918 free (filenames);
1920 /* Check for special targets. Do it here instead of, say, snap_deps()
1921 so that we can immediately use the value. */
1923 if (streq (name, ".POSIX"))
1924 posix_pedantic = 1;
1925 else if (streq (name, ".SECONDEXPANSION"))
1926 second_expansion = 1;
1928 implicit_percent = find_percent (name);
1929 implicit |= implicit_percent != 0;
1931 if (implicit && pattern != 0)
1932 fatal (flocp, _("mixed implicit and static pattern rules"));
1934 if (implicit && implicit_percent == 0)
1935 fatal (flocp, _("mixed implicit and normal rules"));
1937 if (implicit)
1939 if (targets == 0)
1941 max_targets = 5;
1942 targets = (char **) xmalloc (5 * sizeof (char *));
1943 target_percents = (char **) xmalloc (5 * sizeof (char *));
1944 target_idx = 0;
1946 else if (target_idx == max_targets - 1)
1948 max_targets += 5;
1949 targets = (char **) xrealloc ((char *) targets,
1950 max_targets * sizeof (char *));
1951 target_percents
1952 = (char **) xrealloc ((char *) target_percents,
1953 max_targets * sizeof (char *));
1955 targets[target_idx] = name;
1956 target_percents[target_idx] = implicit_percent;
1957 ++target_idx;
1958 continue;
1961 /* If this is a static pattern rule:
1962 `targets: target%pattern: dep%pattern; cmds',
1963 make sure the pattern matches this target name. */
1964 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1965 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1966 else if (deps)
1968 /* If there are multiple filenames, copy the chain DEPS for all but
1969 the last one. It is not safe for the same deps to go in more
1970 than one place in the database. */
1971 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1972 this->need_2nd_expansion = second_expansion;
1975 if (!two_colon)
1977 /* Single-colon. Combine these dependencies
1978 with others in file's existing record, if any. */
1979 f = enter_file (name);
1981 if (f->double_colon)
1982 fatal (flocp,
1983 _("target file `%s' has both : and :: entries"), f->name);
1985 /* If CMDS == F->CMDS, this target was listed in this rule
1986 more than once. Just give a warning since this is harmless. */
1987 if (cmds != 0 && cmds == f->cmds)
1988 error (flocp,
1989 _("target `%s' given more than once in the same rule."),
1990 f->name);
1992 /* Check for two single-colon entries both with commands.
1993 Check is_target so that we don't lose on files such as .c.o
1994 whose commands were preinitialized. */
1995 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1997 error (&cmds->fileinfo,
1998 _("warning: overriding commands for target `%s'"),
1999 f->name);
2000 error (&f->cmds->fileinfo,
2001 _("warning: ignoring old commands for target `%s'"),
2002 f->name);
2005 f->is_target = 1;
2007 /* Defining .DEFAULT with no deps or cmds clears it. */
2008 if (f == default_file && this == 0 && cmds == 0)
2009 f->cmds = 0;
2010 if (cmds != 0)
2011 f->cmds = cmds;
2013 /* Defining .SUFFIXES with no dependencies clears out the list of
2014 suffixes. */
2015 if (f == suffix_file && this == 0)
2017 free_dep_chain (f->deps);
2018 f->deps = 0;
2020 else if (this != 0)
2022 /* Add the file's old deps and the new ones in THIS together. */
2024 if (f->deps != 0)
2026 struct dep **d_ptr = &f->deps;
2028 while ((*d_ptr)->next != 0)
2029 d_ptr = &(*d_ptr)->next;
2031 if (cmds != 0)
2032 /* This is the rule with commands, so put its deps
2033 last. The rationale behind this is that $< expands to
2034 the first dep in the chain, and commands use $<
2035 expecting to get the dep that rule specifies. However
2036 the second expansion algorithm reverses the order thus
2037 we need to make it last here. */
2038 (*d_ptr)->next = this;
2039 else
2041 /* This is the rule without commands. Put its
2042 dependencies at the end but before dependencies from
2043 the rule with commands (if any). This way everything
2044 appears in makefile order. */
2046 if (f->cmds != 0)
2048 this->next = *d_ptr;
2049 *d_ptr = this;
2051 else
2052 (*d_ptr)->next = this;
2055 else
2056 f->deps = this;
2058 /* This is a hack. I need a way to communicate to snap_deps()
2059 that the last dependency line in this file came with commands
2060 (so that logic in snap_deps() can put it in front and all
2061 this $< -logic works). I cannot simply rely on file->cmds
2062 being not 0 because of the cases like the following:
2064 foo: bar
2065 foo:
2068 I am going to temporarily "borrow" UPDATING member in
2069 `struct file' for this. */
2071 if (cmds != 0)
2072 f->updating = 1;
2075 else
2077 /* Double-colon. Make a new record even if there already is one. */
2078 f = lookup_file (name);
2080 /* Check for both : and :: rules. Check is_target so
2081 we don't lose on default suffix rules or makefiles. */
2082 if (f != 0 && f->is_target && !f->double_colon)
2083 fatal (flocp,
2084 _("target file `%s' has both : and :: entries"), f->name);
2085 f = enter_file (name);
2086 /* If there was an existing entry and it was a double-colon entry,
2087 enter_file will have returned a new one, making it the prev
2088 pointer of the old one, and setting its double_colon pointer to
2089 the first one. */
2090 if (f->double_colon == 0)
2091 /* This is the first entry for this name, so we must set its
2092 double_colon pointer to itself. */
2093 f->double_colon = f;
2094 f->is_target = 1;
2095 f->deps = this;
2096 f->cmds = cmds;
2099 /* If this is a static pattern rule, set the stem to the part of its
2100 name that matched the `%' in the pattern, so you can use $* in the
2101 commands. */
2102 if (pattern)
2104 static char *percent = "%";
2105 char *buffer = variable_expand ("");
2106 char *o = patsubst_expand (buffer, name, pattern, percent,
2107 pattern_percent+1, percent+1);
2108 f->stem = savestring (buffer, o - buffer);
2109 if (this)
2110 this->staticpattern = 1;
2113 /* Free name if not needed further. */
2114 if (f != 0 && name != f->name
2115 && (name < f->name || name > f->name + strlen (f->name)))
2117 free (name);
2118 name = f->name;
2121 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2122 if (streq (*default_goal_name, name)
2123 && (default_goal_file == 0
2124 || ! streq (default_goal_file->name, name)))
2125 default_goal_file = f;
2128 if (implicit)
2130 targets[target_idx] = 0;
2131 target_percents[target_idx] = 0;
2132 deps->need_2nd_expansion = second_expansion;
2133 /* We set this to indicate we've not yet parsed the prereq string. */
2134 deps->staticpattern = 1;
2135 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2136 free ((char *) target_percents);
2140 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2141 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2142 Quoting backslashes are removed from STRING by compacting it into
2143 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2144 one, or nil if there are none. STOPCHARs inside variable references are
2145 ignored if IGNOREVARS is true.
2147 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2149 static char *
2150 find_char_unquote (char *string, int stop1, int stop2, int blank,
2151 int ignorevars)
2153 unsigned int string_len = 0;
2154 register char *p = string;
2156 if (ignorevars)
2157 ignorevars = '$';
2159 while (1)
2161 if (stop2 && blank)
2162 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2163 && ! isblank ((unsigned char) *p))
2164 ++p;
2165 else if (stop2)
2166 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2167 ++p;
2168 else if (blank)
2169 while (*p != '\0' && *p != ignorevars && *p != stop1
2170 && ! isblank ((unsigned char) *p))
2171 ++p;
2172 else
2173 while (*p != '\0' && *p != ignorevars && *p != stop1)
2174 ++p;
2176 if (*p == '\0')
2177 break;
2179 /* If we stopped due to a variable reference, skip over its contents. */
2180 if (*p == ignorevars)
2182 char openparen = p[1];
2184 p += 2;
2186 /* Skip the contents of a non-quoted, multi-char variable ref. */
2187 if (openparen == '(' || openparen == '{')
2189 unsigned int pcount = 1;
2190 char closeparen = (openparen == '(' ? ')' : '}');
2192 while (*p)
2194 if (*p == openparen)
2195 ++pcount;
2196 else if (*p == closeparen)
2197 if (--pcount == 0)
2199 ++p;
2200 break;
2202 ++p;
2206 /* Skipped the variable reference: look for STOPCHARS again. */
2207 continue;
2210 if (p > string && p[-1] == '\\')
2212 /* Search for more backslashes. */
2213 register int i = -2;
2214 while (&p[i] >= string && p[i] == '\\')
2215 --i;
2216 ++i;
2217 /* Only compute the length if really needed. */
2218 if (string_len == 0)
2219 string_len = strlen (string);
2220 /* The number of backslashes is now -I.
2221 Copy P over itself to swallow half of them. */
2222 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2223 p += i / 2;
2224 if (i % 2 == 0)
2225 /* All the backslashes quoted each other; the STOPCHAR was
2226 unquoted. */
2227 return p;
2229 /* The STOPCHAR was quoted by a backslash. Look for another. */
2231 else
2232 /* No backslash in sight. */
2233 return p;
2236 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2237 return 0;
2240 /* Search PATTERN for an unquoted %. */
2242 char *
2243 find_percent (char *pattern)
2245 return find_char_unquote (pattern, '%', 0, 0, 0);
2248 /* Parse a string into a sequence of filenames represented as a
2249 chain of struct nameseq's in reverse order and return that chain.
2251 The string is passed as STRINGP, the address of a string pointer.
2252 The string pointer is updated to point at the first character
2253 not parsed, which either is a null char or equals STOPCHAR.
2255 SIZE is how big to construct chain elements.
2256 This is useful if we want them actually to be other structures
2257 that have room for additional info.
2259 If STRIP is nonzero, strip `./'s off the beginning. */
2261 struct nameseq *
2262 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2264 struct nameseq *new = 0;
2265 struct nameseq *new1, *lastnew1;
2266 char *p = *stringp;
2267 char *q;
2268 char *name;
2270 #ifdef VMS
2271 # define VMS_COMMA ','
2272 #else
2273 # define VMS_COMMA 0
2274 #endif
2276 while (1)
2278 /* Skip whitespace; see if any more names are left. */
2279 p = next_token (p);
2280 if (*p == '\0')
2281 break;
2282 if (*p == stopchar)
2283 break;
2285 /* Yes, find end of next name. */
2286 q = p;
2287 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2288 #ifdef VMS
2289 /* convert comma separated list to space separated */
2290 if (p && *p == ',')
2291 *p =' ';
2292 #endif
2293 #ifdef _AMIGA
2294 if (stopchar == ':' && p && *p == ':'
2295 && !(isspace ((unsigned char)p[1]) || !p[1]
2296 || isspace ((unsigned char)p[-1])))
2298 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2300 #endif
2301 #ifdef HAVE_DOS_PATHS
2302 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2303 first colon which isn't followed by a slash or a backslash.
2304 Note that tokens separated by spaces should be treated as separate
2305 tokens since make doesn't allow path names with spaces */
2306 if (stopchar == ':')
2307 while (p != 0 && !isspace ((unsigned char)*p) &&
2308 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2309 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2310 #endif
2311 if (p == 0)
2312 p = q + strlen (q);
2314 if (strip)
2315 #ifdef VMS
2316 /* Skip leading `[]'s. */
2317 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2318 #else
2319 /* Skip leading `./'s. */
2320 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2321 #endif
2323 q += 2; /* Skip "./". */
2324 while (q < p && *q == '/')
2325 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2326 ++q;
2329 /* Extract the filename just found, and skip it. */
2331 if (q == p)
2332 /* ".///" was stripped to "". */
2333 #ifdef VMS
2334 continue;
2335 #else
2336 #ifdef _AMIGA
2337 name = savestring ("", 0);
2338 #else
2339 name = savestring ("./", 2);
2340 #endif
2341 #endif
2342 else
2343 #ifdef VMS
2344 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2345 * to remove this '\' before we can use the filename.
2346 * Savestring called because q may be read-only string constant.
2349 char *qbase = xstrdup (q);
2350 char *pbase = qbase + (p-q);
2351 char *q1 = qbase;
2352 char *q2 = q1;
2353 char *p1 = pbase;
2355 while (q1 != pbase)
2357 if (*q1 == '\\' && *(q1+1) == ':')
2359 q1++;
2360 p1--;
2362 *q2++ = *q1++;
2364 name = savestring (qbase, p1 - qbase);
2365 free (qbase);
2367 #else
2368 name = savestring (q, p - q);
2369 #endif
2371 /* Add it to the front of the chain. */
2372 new1 = (struct nameseq *) xmalloc (size);
2373 new1->name = name;
2374 new1->next = new;
2375 new = new1;
2378 #ifndef NO_ARCHIVES
2380 /* Look for multi-word archive references.
2381 They are indicated by a elt ending with an unmatched `)' and
2382 an elt further down the chain (i.e., previous in the file list)
2383 with an unmatched `(' (e.g., "lib(mem"). */
2385 new1 = new;
2386 lastnew1 = 0;
2387 while (new1 != 0)
2388 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2389 && new1->name[strlen (new1->name) - 1] == ')'
2390 && strchr (new1->name, '(') == 0)
2392 /* NEW1 ends with a `)' but does not contain a `('.
2393 Look back for an elt with an opening `(' but no closing `)'. */
2395 struct nameseq *n = new1->next, *lastn = new1;
2396 char *paren = 0;
2397 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2399 lastn = n;
2400 n = n->next;
2402 if (n != 0
2403 /* Ignore something starting with `(', as that cannot actually
2404 be an archive-member reference (and treating it as such
2405 results in an empty file name, which causes much lossage). */
2406 && n->name[0] != '(')
2408 /* N is the first element in the archive group.
2409 Its name looks like "lib(mem" (with no closing `)'). */
2411 char *libname;
2413 /* Copy "lib(" into LIBNAME. */
2414 ++paren;
2415 libname = (char *) alloca (paren - n->name + 1);
2416 bcopy (n->name, libname, paren - n->name);
2417 libname[paren - n->name] = '\0';
2419 if (*paren == '\0')
2421 /* N was just "lib(", part of something like "lib( a b)".
2422 Edit it out of the chain and free its storage. */
2423 lastn->next = n->next;
2424 free (n->name);
2425 free ((char *) n);
2426 /* LASTN->next is the new stopping elt for the loop below. */
2427 n = lastn->next;
2429 else
2431 /* Replace N's name with the full archive reference. */
2432 name = concat (libname, paren, ")");
2433 free (n->name);
2434 n->name = name;
2437 if (new1->name[1] == '\0')
2439 /* NEW1 is just ")", part of something like "lib(a b )".
2440 Omit it from the chain and free its storage. */
2441 if (lastnew1 == 0)
2442 new = new1->next;
2443 else
2444 lastnew1->next = new1->next;
2445 lastn = new1;
2446 new1 = new1->next;
2447 free (lastn->name);
2448 free ((char *) lastn);
2450 else
2452 /* Replace also NEW1->name, which already has closing `)'. */
2453 name = concat (libname, new1->name, "");
2454 free (new1->name);
2455 new1->name = name;
2456 new1 = new1->next;
2459 /* Trace back from NEW1 (the end of the list) until N
2460 (the beginning of the list), rewriting each name
2461 with the full archive reference. */
2463 while (new1 != n)
2465 name = concat (libname, new1->name, ")");
2466 free (new1->name);
2467 new1->name = name;
2468 lastnew1 = new1;
2469 new1 = new1->next;
2472 else
2474 /* No frobnication happening. Just step down the list. */
2475 lastnew1 = new1;
2476 new1 = new1->next;
2479 else
2481 lastnew1 = new1;
2482 new1 = new1->next;
2485 #endif
2487 *stringp = p;
2488 return new;
2491 /* Find the next line of text in an eval buffer, combining continuation lines
2492 into one line.
2493 Return the number of actual lines read (> 1 if continuation lines).
2494 Returns -1 if there's nothing left in the buffer.
2496 After this function, ebuf->buffer points to the first character of the
2497 line we just found.
2500 /* Read a line of text from a STRING.
2501 Since we aren't really reading from a file, don't bother with linenumbers.
2504 static unsigned long
2505 readstring (struct ebuffer *ebuf)
2507 char *eol;
2509 /* If there is nothing left in this buffer, return 0. */
2510 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2511 return -1;
2513 /* Set up a new starting point for the buffer, and find the end of the
2514 next logical line (taking into account backslash/newline pairs). */
2516 eol = ebuf->buffer = ebuf->bufnext;
2518 while (1)
2520 int backslash = 0;
2521 char *bol = eol;
2522 char *p;
2524 /* Find the next newline. At EOS, stop. */
2525 eol = p = strchr (eol , '\n');
2526 if (!eol)
2528 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2529 return 0;
2532 /* Found a newline; if it's escaped continue; else we're done. */
2533 while (p > bol && *(--p) == '\\')
2534 backslash = !backslash;
2535 if (!backslash)
2536 break;
2537 ++eol;
2540 /* Overwrite the newline char. */
2541 *eol = '\0';
2542 ebuf->bufnext = eol+1;
2544 return 0;
2547 static long
2548 readline (struct ebuffer *ebuf)
2550 char *p;
2551 char *end;
2552 char *start;
2553 long nlines = 0;
2555 /* The behaviors between string and stream buffers are different enough to
2556 warrant different functions. Do the Right Thing. */
2558 if (!ebuf->fp)
2559 return readstring (ebuf);
2561 /* When reading from a file, we always start over at the beginning of the
2562 buffer for each new line. */
2564 p = start = ebuf->bufstart;
2565 end = p + ebuf->size;
2566 *p = '\0';
2568 while (fgets (p, end - p, ebuf->fp) != 0)
2570 char *p2;
2571 unsigned long len;
2572 int backslash;
2574 len = strlen (p);
2575 if (len == 0)
2577 /* This only happens when the first thing on the line is a '\0'.
2578 It is a pretty hopeless case, but (wonder of wonders) Athena
2579 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2580 There is nothing really to be done; we synthesize a newline so
2581 the following line doesn't appear to be part of this line. */
2582 error (&ebuf->floc,
2583 _("warning: NUL character seen; rest of line ignored"));
2584 p[0] = '\n';
2585 len = 1;
2588 /* Jump past the text we just read. */
2589 p += len;
2591 /* If the last char isn't a newline, the whole line didn't fit into the
2592 buffer. Get some more buffer and try again. */
2593 if (p[-1] != '\n')
2594 goto more_buffer;
2596 /* We got a newline, so add one to the count of lines. */
2597 ++nlines;
2599 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2600 /* Check to see if the line was really ended with CRLF; if so ignore
2601 the CR. */
2602 if ((p - start) > 1 && p[-2] == '\r')
2604 --p;
2605 p[-1] = '\n';
2607 #endif
2609 backslash = 0;
2610 for (p2 = p - 2; p2 >= start; --p2)
2612 if (*p2 != '\\')
2613 break;
2614 backslash = !backslash;
2617 if (!backslash)
2619 p[-1] = '\0';
2620 break;
2623 /* It was a backslash/newline combo. If we have more space, read
2624 another line. */
2625 if (end - p >= 80)
2626 continue;
2628 /* We need more space at the end of our buffer, so realloc it.
2629 Make sure to preserve the current offset of p. */
2630 more_buffer:
2632 unsigned long off = p - start;
2633 ebuf->size *= 2;
2634 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2635 ebuf->size);
2636 p = start + off;
2637 end = start + ebuf->size;
2638 *p = '\0';
2642 if (ferror (ebuf->fp))
2643 pfatal_with_name (ebuf->floc.filenm);
2645 /* If we found some lines, return how many.
2646 If we didn't, but we did find _something_, that indicates we read the last
2647 line of a file with no final newline; return 1.
2648 If we read nothing, we're at EOF; return -1. */
2650 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2653 /* Parse the next "makefile word" from the input buffer, and return info
2654 about it.
2656 A "makefile word" is one of:
2658 w_bogus Should never happen
2659 w_eol End of input
2660 w_static A static word; cannot be expanded
2661 w_variable A word containing one or more variables/functions
2662 w_colon A colon
2663 w_dcolon A double-colon
2664 w_semicolon A semicolon
2665 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2667 Note that this function is only used when reading certain parts of the
2668 makefile. Don't use it where special rules hold sway (RHS of a variable,
2669 in a command list, etc.) */
2671 static enum make_word_type
2672 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2674 enum make_word_type wtype = w_bogus;
2675 char *p = buffer, *beg;
2676 char c;
2678 /* Skip any leading whitespace. */
2679 while (isblank ((unsigned char)*p))
2680 ++p;
2682 beg = p;
2683 c = *(p++);
2684 switch (c)
2686 case '\0':
2687 wtype = w_eol;
2688 break;
2690 case ';':
2691 wtype = w_semicolon;
2692 break;
2694 case '=':
2695 wtype = w_varassign;
2696 break;
2698 case ':':
2699 wtype = w_colon;
2700 switch (*p)
2702 case ':':
2703 ++p;
2704 wtype = w_dcolon;
2705 break;
2707 case '=':
2708 ++p;
2709 wtype = w_varassign;
2710 break;
2712 break;
2714 case '+':
2715 case '?':
2716 if (*p == '=')
2718 ++p;
2719 wtype = w_varassign;
2720 break;
2723 default:
2724 if (delim && strchr (delim, c))
2725 wtype = w_static;
2726 break;
2729 /* Did we find something? If so, return now. */
2730 if (wtype != w_bogus)
2731 goto done;
2733 /* This is some non-operator word. A word consists of the longest
2734 string of characters that doesn't contain whitespace, one of [:=#],
2735 or [?+]=, or one of the chars in the DELIM string. */
2737 /* We start out assuming a static word; if we see a variable we'll
2738 adjust our assumptions then. */
2739 wtype = w_static;
2741 /* We already found the first value of "c", above. */
2742 while (1)
2744 char closeparen;
2745 int count;
2747 switch (c)
2749 case '\0':
2750 case ' ':
2751 case '\t':
2752 case '=':
2753 goto done_word;
2755 case ':':
2756 #ifdef HAVE_DOS_PATHS
2757 /* A word CAN include a colon in its drive spec. The drive
2758 spec is allowed either at the beginning of a word, or as part
2759 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2760 if (!(p - beg >= 2
2761 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2762 && (p - beg == 2 || p[-3] == '(')))
2763 #endif
2764 goto done_word;
2766 case '$':
2767 c = *(p++);
2768 if (c == '$')
2769 break;
2771 /* This is a variable reference, so note that it's expandable.
2772 Then read it to the matching close paren. */
2773 wtype = w_variable;
2775 if (c == '(')
2776 closeparen = ')';
2777 else if (c == '{')
2778 closeparen = '}';
2779 else
2780 /* This is a single-letter variable reference. */
2781 break;
2783 for (count=0; *p != '\0'; ++p)
2785 if (*p == c)
2786 ++count;
2787 else if (*p == closeparen && --count < 0)
2789 ++p;
2790 break;
2793 break;
2795 case '?':
2796 case '+':
2797 if (*p == '=')
2798 goto done_word;
2799 break;
2801 case '\\':
2802 switch (*p)
2804 case ':':
2805 case ';':
2806 case '=':
2807 case '\\':
2808 ++p;
2809 break;
2811 break;
2813 default:
2814 if (delim && strchr (delim, c))
2815 goto done_word;
2816 break;
2819 c = *(p++);
2821 done_word:
2822 --p;
2824 done:
2825 if (startp)
2826 *startp = beg;
2827 if (length)
2828 *length = p - beg;
2829 return wtype;
2832 /* Construct the list of include directories
2833 from the arguments and the default list. */
2835 void
2836 construct_include_path (char **arg_dirs)
2838 register unsigned int i;
2839 #ifdef VAXC /* just don't ask ... */
2840 stat_t stbuf;
2841 #else
2842 struct stat stbuf;
2843 #endif
2844 /* Table to hold the dirs. */
2846 register unsigned int defsize = (sizeof (default_include_directories)
2847 / sizeof (default_include_directories[0]));
2848 register unsigned int max = 5;
2849 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2850 register unsigned int idx = 0;
2852 #ifdef __MSDOS__
2853 defsize++;
2854 #endif
2856 /* First consider any dirs specified with -I switches.
2857 Ignore dirs that don't exist. */
2859 if (arg_dirs != 0)
2860 while (*arg_dirs != 0)
2862 char *dir = *arg_dirs++;
2863 int e;
2865 if (dir[0] == '~')
2867 char *expanded = tilde_expand (dir);
2868 if (expanded != 0)
2869 dir = expanded;
2872 EINTRLOOP (e, stat (dir, &stbuf));
2873 if (e == 0 && S_ISDIR (stbuf.st_mode))
2875 if (idx == max - 1)
2877 max += 5;
2878 dirs = (char **)
2879 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2881 dirs[idx++] = dir;
2883 else if (dir != arg_dirs[-1])
2884 free (dir);
2887 /* Now add at the end the standard default dirs. */
2889 #ifdef __MSDOS__
2891 /* The environment variable $DJDIR holds the root of the
2892 DJGPP directory tree; add ${DJDIR}/include. */
2893 struct variable *djdir = lookup_variable ("DJDIR", 5);
2895 if (djdir)
2897 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2899 strcat (strcpy (defdir, djdir->value), "/include");
2900 dirs[idx++] = defdir;
2903 #endif
2905 for (i = 0; default_include_directories[i] != 0; ++i)
2907 int e;
2909 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2910 if (e == 0 && S_ISDIR (stbuf.st_mode))
2911 dirs[idx++] = default_include_directories[i];
2914 dirs[idx] = 0;
2916 /* Now compute the maximum length of any name in it. */
2918 max_incl_len = 0;
2919 for (i = 0; i < idx; ++i)
2921 unsigned int len = strlen (dirs[i]);
2922 /* If dir name is written with a trailing slash, discard it. */
2923 if (dirs[i][len - 1] == '/')
2924 /* We can't just clobber a null in because it may have come from
2925 a literal string and literal strings may not be writable. */
2926 dirs[i] = savestring (dirs[i], len - 1);
2927 if (len > max_incl_len)
2928 max_incl_len = len;
2931 include_directories = dirs;
2934 /* Expand ~ or ~USER at the beginning of NAME.
2935 Return a newly malloc'd string or 0. */
2937 char *
2938 tilde_expand (char *name)
2940 #ifndef VMS
2941 if (name[1] == '/' || name[1] == '\0')
2943 extern char *getenv ();
2944 char *home_dir;
2945 int is_variable;
2948 /* Turn off --warn-undefined-variables while we expand HOME. */
2949 int save = warn_undefined_variables_flag;
2950 warn_undefined_variables_flag = 0;
2952 home_dir = allocated_variable_expand ("$(HOME)");
2954 warn_undefined_variables_flag = save;
2957 is_variable = home_dir[0] != '\0';
2958 if (!is_variable)
2960 free (home_dir);
2961 home_dir = getenv ("HOME");
2963 #if !defined(_AMIGA) && !defined(WINDOWS32)
2964 if (home_dir == 0 || home_dir[0] == '\0')
2966 extern char *getlogin ();
2967 char *logname = getlogin ();
2968 home_dir = 0;
2969 if (logname != 0)
2971 struct passwd *p = getpwnam (logname);
2972 if (p != 0)
2973 home_dir = p->pw_dir;
2976 #endif /* !AMIGA && !WINDOWS32 */
2977 if (home_dir != 0)
2979 char *new = concat (home_dir, "", name + 1);
2980 if (is_variable)
2981 free (home_dir);
2982 return new;
2985 #if !defined(_AMIGA) && !defined(WINDOWS32)
2986 else
2988 struct passwd *pwent;
2989 char *userend = strchr (name + 1, '/');
2990 if (userend != 0)
2991 *userend = '\0';
2992 pwent = getpwnam (name + 1);
2993 if (pwent != 0)
2995 if (userend == 0)
2996 return xstrdup (pwent->pw_dir);
2997 else
2998 return concat (pwent->pw_dir, "/", userend + 1);
3000 else if (userend != 0)
3001 *userend = '/';
3003 #endif /* !AMIGA && !WINDOWS32 */
3004 #endif /* !VMS */
3005 return 0;
3008 /* Given a chain of struct nameseq's describing a sequence of filenames,
3009 in reverse of the intended order, return a new chain describing the
3010 result of globbing the filenames. The new chain is in forward order.
3011 The links of the old chain are freed or used in the new chain.
3012 Likewise for the names in the old chain.
3014 SIZE is how big to construct chain elements.
3015 This is useful if we want them actually to be other structures
3016 that have room for additional info. */
3018 struct nameseq *
3019 multi_glob (struct nameseq *chain, unsigned int size)
3021 extern void dir_setup_glob ();
3022 register struct nameseq *new = 0;
3023 register struct nameseq *old;
3024 struct nameseq *nexto;
3025 glob_t gl;
3027 dir_setup_glob (&gl);
3029 for (old = chain; old != 0; old = nexto)
3031 #ifndef NO_ARCHIVES
3032 char *memname;
3033 #endif
3035 nexto = old->next;
3037 if (old->name[0] == '~')
3039 char *newname = tilde_expand (old->name);
3040 if (newname != 0)
3042 free (old->name);
3043 old->name = newname;
3047 #ifndef NO_ARCHIVES
3048 if (ar_name (old->name))
3050 /* OLD->name is an archive member reference.
3051 Replace it with the archive file name,
3052 and save the member name in MEMNAME.
3053 We will glob on the archive name and then
3054 reattach MEMNAME later. */
3055 char *arname;
3056 ar_parse_name (old->name, &arname, &memname);
3057 free (old->name);
3058 old->name = arname;
3060 else
3061 memname = 0;
3062 #endif /* !NO_ARCHIVES */
3064 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3066 case 0: /* Success. */
3068 register int i = gl.gl_pathc;
3069 while (i-- > 0)
3071 #ifndef NO_ARCHIVES
3072 if (memname != 0)
3074 /* Try to glob on MEMNAME within the archive. */
3075 struct nameseq *found
3076 = ar_glob (gl.gl_pathv[i], memname, size);
3077 if (found == 0)
3079 /* No matches. Use MEMNAME as-is. */
3080 unsigned int alen = strlen (gl.gl_pathv[i]);
3081 unsigned int mlen = strlen (memname);
3082 struct nameseq *elt
3083 = (struct nameseq *) xmalloc (size);
3084 if (size > sizeof (struct nameseq))
3085 bzero (((char *) elt) + sizeof (struct nameseq),
3086 size - sizeof (struct nameseq));
3087 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3088 bcopy (gl.gl_pathv[i], elt->name, alen);
3089 elt->name[alen] = '(';
3090 bcopy (memname, &elt->name[alen + 1], mlen);
3091 elt->name[alen + 1 + mlen] = ')';
3092 elt->name[alen + 1 + mlen + 1] = '\0';
3093 elt->next = new;
3094 new = elt;
3096 else
3098 /* Find the end of the FOUND chain. */
3099 struct nameseq *f = found;
3100 while (f->next != 0)
3101 f = f->next;
3103 /* Attach the chain being built to the end of the FOUND
3104 chain, and make FOUND the new NEW chain. */
3105 f->next = new;
3106 new = found;
3109 free (memname);
3111 else
3112 #endif /* !NO_ARCHIVES */
3114 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3115 if (size > sizeof (struct nameseq))
3116 bzero (((char *) elt) + sizeof (struct nameseq),
3117 size - sizeof (struct nameseq));
3118 elt->name = xstrdup (gl.gl_pathv[i]);
3119 elt->next = new;
3120 new = elt;
3123 globfree (&gl);
3124 free (old->name);
3125 free ((char *)old);
3126 break;
3129 case GLOB_NOSPACE:
3130 fatal (NILF, _("virtual memory exhausted"));
3131 break;
3133 default:
3134 old->next = new;
3135 new = old;
3136 break;
3140 return new;