Fix some Savannah bugs.
[make.git] / read.c
blob15455b872574a1f02a1a2d3f63845ddc5389ba4b
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 interepreting? */
82 char *seen_else; /* Have we already seen an `else'? */
85 static struct conditionals toplevel_conditionals;
86 static struct conditionals *conditionals = &toplevel_conditionals;
89 /* Default directories to search for include files in */
91 static char *default_include_directories[] =
93 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
95 * This completely up to the user when they install MSVC or other packages.
96 * This is defined as a placeholder.
98 #define INCLUDEDIR "."
99 #endif
100 INCLUDEDIR,
101 #ifndef _AMIGA
102 "/usr/gnu/include",
103 "/usr/local/include",
104 "/usr/include",
105 #endif
109 /* List of directories to search for include files in */
111 static char **include_directories;
113 /* Maximum length of an element of the above. */
115 static unsigned int max_incl_len;
117 /* The filename and pointer to line number of the
118 makefile currently being read in. */
120 const struct floc *reading_file = 0;
122 /* The chain of makefiles read by read_makefile. */
124 static struct dep *read_makefiles = 0;
126 static int eval_makefile PARAMS ((char *filename, int flags));
127 static int eval PARAMS ((struct ebuffer *buffer, int flags));
129 static long readline PARAMS ((struct ebuffer *ebuf));
130 static void do_define PARAMS ((char *name, unsigned int namelen,
131 enum variable_origin origin,
132 struct ebuffer *ebuf));
133 static int conditional_line PARAMS ((char *line, const struct floc *flocp));
134 static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
135 struct dep *deps, unsigned int cmds_started, char *commands,
136 unsigned int commands_idx, int two_colon,
137 const struct floc *flocp));
138 static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
139 enum variable_origin origin,
140 int enabled,
141 const struct floc *flocp));
142 static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
143 char **startp, unsigned int *length));
145 /* Read in all the makefiles and return the chain of their names. */
147 struct dep *
148 read_all_makefiles (char **makefiles)
150 unsigned int num_makefiles = 0;
152 /* Create *_LIST variables, to hold the makefiles, targets, and variables
153 we will be reading. */
155 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
157 DB (DB_BASIC, (_("Reading makefiles...\n")));
159 /* If there's a non-null variable MAKEFILES, its value is a list of
160 files to read first thing. But don't let it prevent reading the
161 default makefiles and don't let the default goal come from there. */
164 char *value;
165 char *name, *p;
166 unsigned int length;
169 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
170 int save = warn_undefined_variables_flag;
171 warn_undefined_variables_flag = 0;
173 value = allocated_variable_expand ("$(MAKEFILES)");
175 warn_undefined_variables_flag = save;
178 /* Set NAME to the start of next token and LENGTH to its length.
179 MAKEFILES is updated for finding remaining tokens. */
180 p = value;
182 while ((name = find_next_token (&p, &length)) != 0)
184 if (*p != '\0')
185 *p++ = '\0';
186 name = xstrdup (name);
187 if (eval_makefile (name,
188 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
189 free (name);
192 free (value);
195 /* Read makefiles specified with -f switches. */
197 if (makefiles != 0)
198 while (*makefiles != 0)
200 struct dep *tail = read_makefiles;
201 register struct dep *d;
203 if (! eval_makefile (*makefiles, 0))
204 perror_with_name ("", *makefiles);
206 /* Find the right element of read_makefiles. */
207 d = read_makefiles;
208 while (d->next != tail)
209 d = d->next;
211 /* Use the storage read_makefile allocates. */
212 *makefiles = dep_name (d);
213 ++num_makefiles;
214 ++makefiles;
217 /* If there were no -f switches, try the default names. */
219 if (num_makefiles == 0)
221 static char *default_makefiles[] =
222 #ifdef VMS
223 /* all lower case since readdir() (the vms version) 'lowercasifies' */
224 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
225 #else
226 #ifdef _AMIGA
227 { "GNUmakefile", "Makefile", "SMakefile", 0 };
228 #else /* !Amiga && !VMS */
229 { "GNUmakefile", "makefile", "Makefile", 0 };
230 #endif /* AMIGA */
231 #endif /* VMS */
232 register char **p = default_makefiles;
233 while (*p != 0 && !file_exists_p (*p))
234 ++p;
236 if (*p != 0)
238 if (! eval_makefile (*p, 0))
239 perror_with_name ("", *p);
241 else
243 /* No default makefile was found. Add the default makefiles to the
244 `read_makefiles' chain so they will be updated if possible. */
245 struct dep *tail = read_makefiles;
246 /* Add them to the tail, after any MAKEFILES variable makefiles. */
247 while (tail != 0 && tail->next != 0)
248 tail = tail->next;
249 for (p = default_makefiles; *p != 0; ++p)
251 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
252 d->name = 0;
253 d->file = enter_file (*p);
254 d->file->dontcare = 1;
255 d->ignore_mtime = 0;
256 /* Tell update_goal_chain to bail out as soon as this file is
257 made, and main not to die if we can't make this file. */
258 d->changed = RM_DONTCARE;
259 if (tail == 0)
260 read_makefiles = d;
261 else
262 tail->next = d;
263 tail = d;
265 if (tail != 0)
266 tail->next = 0;
270 return read_makefiles;
273 /* Install a new conditional and return the previous one. */
275 static struct conditionals *
276 install_conditionals (struct conditionals *new)
278 struct conditionals *save = conditionals;
280 bzero ((char *) new, sizeof (*new));
281 conditionals = new;
283 return save;
286 /* Free the current conditionals and reinstate a saved one. */
288 static void
289 restore_conditionals (struct conditionals *saved)
291 /* Free any space allocated by conditional_line. */
292 if (conditionals->ignoring)
293 free (conditionals->ignoring);
294 if (conditionals->seen_else)
295 free (conditionals->seen_else);
297 /* Restore state. */
298 conditionals = saved;
301 static int
302 eval_makefile (char *filename, int flags)
304 struct dep *deps;
305 struct ebuffer ebuf;
306 const struct floc *curfile;
307 int makefile_errno;
308 int r;
310 ebuf.floc.filenm = filename;
311 ebuf.floc.lineno = 1;
313 if (ISDB (DB_VERBOSE))
315 printf (_("Reading makefile `%s'"), filename);
316 if (flags & RM_NO_DEFAULT_GOAL)
317 printf (_(" (no default goal)"));
318 if (flags & RM_INCLUDED)
319 printf (_(" (search path)"));
320 if (flags & RM_DONTCARE)
321 printf (_(" (don't care)"));
322 if (flags & RM_NO_TILDE)
323 printf (_(" (no ~ expansion)"));
324 puts ("...");
327 /* First, get a stream to read. */
329 /* Expand ~ in FILENAME unless it came from `include',
330 in which case it was already done. */
331 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
333 char *expanded = tilde_expand (filename);
334 if (expanded != 0)
335 filename = expanded;
338 ebuf.fp = fopen (filename, "r");
339 /* Save the error code so we print the right message later. */
340 makefile_errno = errno;
342 /* If the makefile wasn't found and it's either a makefile from
343 the `MAKEFILES' variable or an included makefile,
344 search the included makefile search path for this makefile. */
345 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
347 register unsigned int i;
348 for (i = 0; include_directories[i] != 0; ++i)
350 char *name = concat (include_directories[i], "/", filename);
351 ebuf.fp = fopen (name, "r");
352 if (ebuf.fp == 0)
353 free (name);
354 else
356 filename = name;
357 break;
362 /* Add FILENAME to the chain of read makefiles. */
363 deps = (struct dep *) xmalloc (sizeof (struct dep));
364 deps->next = read_makefiles;
365 read_makefiles = deps;
366 deps->name = 0;
367 deps->file = lookup_file (filename);
368 if (deps->file == 0)
369 deps->file = enter_file (xstrdup (filename));
370 if (filename != ebuf.floc.filenm)
371 free (filename);
372 filename = deps->file->name;
373 deps->changed = flags;
374 deps->ignore_mtime = 0;
375 if (flags & RM_DONTCARE)
376 deps->file->dontcare = 1;
378 /* If the makefile can't be found at all, give up entirely. */
380 if (ebuf.fp == 0)
382 /* If we did some searching, errno has the error from the last
383 attempt, rather from FILENAME itself. Restore it in case the
384 caller wants to use it in a message. */
385 errno = makefile_errno;
386 return 0;
389 /* Add this makefile to the list. */
390 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
391 f_append, 0);
393 /* Evaluate the makefile */
395 ebuf.size = 200;
396 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
398 curfile = reading_file;
399 reading_file = &ebuf.floc;
401 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
403 reading_file = curfile;
405 fclose (ebuf.fp);
407 free (ebuf.bufstart);
408 alloca (0);
409 return r;
413 eval_buffer (char *buffer)
415 struct ebuffer ebuf;
416 struct conditionals *saved;
417 struct conditionals new;
418 const struct floc *curfile;
419 int r;
421 /* Evaluate the buffer */
423 ebuf.size = strlen (buffer);
424 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
425 ebuf.fp = NULL;
427 ebuf.floc = *reading_file;
429 curfile = reading_file;
430 reading_file = &ebuf.floc;
432 saved = install_conditionals (&new);
434 r = eval (&ebuf, 1);
436 restore_conditionals (saved);
438 reading_file = curfile;
440 alloca (0);
441 return r;
445 /* Read file FILENAME as a makefile and add its contents to the data base.
447 SET_DEFAULT is true if we are allowed to set the default goal. */
450 static int
451 eval (struct ebuffer *ebuf, int set_default)
453 char *collapsed = 0;
454 unsigned int collapsed_length = 0;
455 unsigned int commands_len = 200;
456 char *commands;
457 unsigned int commands_idx = 0;
458 unsigned int cmds_started, tgts_started;
459 int ignoring = 0, in_ignored_define = 0;
460 int no_targets = 0; /* Set when reading a rule without targets. */
461 struct nameseq *filenames = 0;
462 struct dep *deps = 0;
463 long nlines = 0;
464 int two_colon = 0;
465 char *pattern = 0, *pattern_percent;
466 struct floc *fstart;
467 struct floc fi;
469 #define record_waiting_files() \
470 do \
472 if (filenames != 0) \
474 fi.lineno = tgts_started; \
475 record_files (filenames, pattern, pattern_percent, deps, \
476 cmds_started, commands, commands_idx, two_colon, \
477 &fi); \
479 filenames = 0; \
480 commands_idx = 0; \
481 no_targets = 0; \
482 if (pattern) { free(pattern); pattern = 0; } \
483 } while (0)
485 pattern_percent = 0;
486 cmds_started = tgts_started = 1;
488 fstart = &ebuf->floc;
489 fi.filenm = ebuf->floc.filenm;
491 /* Loop over lines in the file.
492 The strategy is to accumulate target names in FILENAMES, dependencies
493 in DEPS and commands in COMMANDS. These are used to define a rule
494 when the start of the next rule (or eof) is encountered.
496 When you see a "continue" in the loop below, that means we are moving on
497 to the next line _without_ ending any rule that we happen to be working
498 with at the moment. If you see a "goto rule_complete", then the
499 statement we just parsed also finishes the previous rule. */
501 commands = xmalloc (200);
503 while (1)
505 unsigned int linelen;
506 char *line;
507 int len;
508 char *p;
509 char *p2;
511 /* Grab the next line to be evaluated */
512 ebuf->floc.lineno += nlines;
513 nlines = readline (ebuf);
515 /* If there is nothing left to eval, we're done. */
516 if (nlines < 0)
517 break;
519 /* If this line is empty, skip it. */
520 line = ebuf->buffer;
521 if (line[0] == '\0')
522 continue;
524 linelen = strlen (line);
526 /* Check for a shell command line first.
527 If it is not one, we can stop treating tab specially. */
528 if (line[0] == '\t')
530 if (no_targets)
531 /* Ignore the commands in a rule with no targets. */
532 continue;
534 /* If there is no preceding rule line, don't treat this line
535 as a command, even though it begins with a tab character.
536 SunOS 4 make appears to behave this way. */
538 if (filenames != 0)
540 if (ignoring)
541 /* Yep, this is a shell command, and we don't care. */
542 continue;
544 /* Append this command line to the line being accumulated. */
545 if (commands_idx == 0)
546 cmds_started = ebuf->floc.lineno;
548 if (linelen + 1 + commands_idx > commands_len)
550 commands_len = (linelen + 1 + commands_idx) * 2;
551 commands = xrealloc (commands, commands_len);
553 bcopy (line, &commands[commands_idx], linelen);
554 commands_idx += linelen;
555 commands[commands_idx++] = '\n';
557 continue;
561 /* This line is not a shell command line. Don't worry about tabs.
562 Get more space if we need it; we don't need to preserve the current
563 contents of the buffer. */
565 if (collapsed_length < linelen+1)
567 collapsed_length = linelen+1;
568 if (collapsed)
569 free ((char *)collapsed);
570 collapsed = (char *) xmalloc (collapsed_length);
572 strcpy (collapsed, line);
573 /* Collapse continuation lines. */
574 collapse_continuations (collapsed);
575 remove_comments (collapsed);
577 /* Compare a word, both length and contents. */
578 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
579 p = collapsed;
580 while (isspace ((unsigned char)*p))
581 ++p;
583 if (*p == '\0')
584 /* This line is completely empty--ignore it. */
585 continue;
587 /* Find the end of the first token. Note we don't need to worry about
588 * ":" here since we compare tokens by length (so "export" will never
589 * be equal to "export:").
591 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
593 len = p2 - p;
595 /* Find the start of the second token. If it looks like a target or
596 variable definition it can't be a preprocessor token so skip
597 them--this allows variables/targets named `ifdef', `export', etc. */
598 while (isspace ((unsigned char)*p2))
599 ++p2;
601 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
603 /* It can't be a preprocessor token so skip it if we're ignoring */
604 if (ignoring)
605 continue;
607 goto skip_conditionals;
610 /* We must first check for conditional and `define' directives before
611 ignoring anything, since they control what we will do with
612 following lines. */
614 if (!in_ignored_define
615 && (word1eq ("ifdef") || word1eq ("ifndef")
616 || word1eq ("ifeq") || word1eq ("ifneq")
617 || word1eq ("else") || word1eq ("endif")))
619 int i = conditional_line (p, fstart);
620 if (i < 0)
621 fatal (fstart, _("invalid syntax in conditional"));
623 ignoring = i;
624 continue;
627 if (word1eq ("endef"))
629 if (!in_ignored_define)
630 fatal (fstart, _("extraneous `endef'"));
631 in_ignored_define = 0;
632 continue;
635 if (word1eq ("define"))
637 if (ignoring)
638 in_ignored_define = 1;
639 else
641 if (*p2 == '\0')
642 fatal (fstart, _("empty variable name"));
644 /* Let the variable name be the whole rest of the line,
645 with trailing blanks stripped (comments have already been
646 removed), so it could be a complex variable/function
647 reference that might contain blanks. */
648 p = strchr (p2, '\0');
649 while (isblank ((unsigned char)p[-1]))
650 --p;
651 do_define (p2, p - p2, o_file, ebuf);
653 continue;
656 if (word1eq ("override"))
658 if (*p2 == '\0')
659 error (fstart, _("empty `override' directive"));
661 if (strneq (p2, "define", 6)
662 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
664 if (ignoring)
665 in_ignored_define = 1;
666 else
668 p2 = next_token (p2 + 6);
669 if (*p2 == '\0')
670 fatal (fstart, _("empty variable name"));
672 /* Let the variable name be the whole rest of the line,
673 with trailing blanks stripped (comments have already been
674 removed), so it could be a complex variable/function
675 reference that might contain blanks. */
676 p = strchr (p2, '\0');
677 while (isblank ((unsigned char)p[-1]))
678 --p;
679 do_define (p2, p - p2, o_override, ebuf);
682 else if (!ignoring
683 && !try_variable_definition (fstart, p2, o_override, 0))
684 error (fstart, _("invalid `override' directive"));
686 continue;
689 if (ignoring)
690 /* Ignore the line. We continue here so conditionals
691 can appear in the middle of a rule. */
692 continue;
694 if (word1eq ("export"))
696 /* 'export' by itself causes everything to be exported. */
697 if (*p2 == '\0')
698 export_all_variables = 1;
699 else
701 struct variable *v;
703 v = try_variable_definition (fstart, p2, o_file, 0);
704 if (v != 0)
705 v->export = v_export;
706 else
708 unsigned int len;
709 char *ap;
711 /* Expand the line so we can use indirect and constructed
712 variable names in an export command. */
713 p2 = ap = allocated_variable_expand (p2);
715 for (p = find_next_token (&p2, &len); p != 0;
716 p = find_next_token (&p2, &len))
718 v = lookup_variable (p, len);
719 if (v == 0)
720 v = define_variable_loc (p, len, "", o_file, 0,
721 fstart);
722 v->export = v_export;
725 free (ap);
728 goto rule_complete;
731 if (word1eq ("unexport"))
733 if (*p2 == '\0')
734 export_all_variables = 0;
735 else
737 unsigned int len;
738 struct variable *v;
739 char *ap;
741 /* Expand the line so we can use indirect and constructed
742 variable names in an unexport command. */
743 p2 = ap = allocated_variable_expand (p2);
745 for (p = find_next_token (&p2, &len); p != 0;
746 p = find_next_token (&p2, &len))
748 v = lookup_variable (p, len);
749 if (v == 0)
750 v = define_variable_loc (p, len, "", o_file, 0, fstart);
752 v->export = v_noexport;
755 free (ap);
757 goto rule_complete;
760 skip_conditionals:
761 if (word1eq ("vpath"))
763 char *pattern;
764 unsigned int len;
765 p2 = variable_expand (p2);
766 p = find_next_token (&p2, &len);
767 if (p != 0)
769 pattern = savestring (p, len);
770 p = find_next_token (&p2, &len);
771 /* No searchpath means remove all previous
772 selective VPATH's with the same pattern. */
774 else
775 /* No pattern means remove all previous selective VPATH's. */
776 pattern = 0;
777 construct_vpath_list (pattern, p);
778 if (pattern != 0)
779 free (pattern);
781 goto rule_complete;
784 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
786 /* We have found an `include' line specifying a nested
787 makefile to be read at this point. */
788 struct conditionals *save;
789 struct conditionals new_conditionals;
790 struct nameseq *files;
791 /* "-include" (vs "include") says no error if the file does not
792 exist. "sinclude" is an alias for this from SGI. */
793 int noerror = (p[0] != 'i');
795 p = allocated_variable_expand (p2);
796 if (*p == '\0')
798 error (fstart,
799 _("no file name for `%sinclude'"), noerror ? "-" : "");
800 continue;
803 /* Parse the list of file names. */
804 p2 = p;
805 files = multi_glob (parse_file_seq (&p2, '\0',
806 sizeof (struct nameseq),
808 sizeof (struct nameseq));
809 free (p);
811 /* Save the state of conditionals and start
812 the included makefile with a clean slate. */
813 save = install_conditionals (&new_conditionals);
815 /* Record the rules that are waiting so they will determine
816 the default goal before those in the included makefile. */
817 record_waiting_files ();
819 /* Read each included makefile. */
820 while (files != 0)
822 struct nameseq *next = files->next;
823 char *name = files->name;
824 int r;
826 free ((char *)files);
827 files = next;
829 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
830 | (noerror ? RM_DONTCARE : 0)));
831 if (!r)
833 if (!noerror)
834 error (fstart, "%s: %s", name, strerror (errno));
835 free (name);
839 /* Restore conditional state. */
840 restore_conditionals (save);
842 goto rule_complete;
845 if (try_variable_definition (fstart, p, o_file, 0))
846 /* This line has been dealt with. */
847 goto rule_complete;
849 /* This line starts with a tab but was not caught above because there
850 was no preceding target, and the line might have been usable as a
851 variable definition. But now we know it is definitely lossage. */
852 if (line[0] == '\t')
853 fatal(fstart, _("commands commence before first target"));
855 /* This line describes some target files. This is complicated by
856 the existence of target-specific variables, because we can't
857 expand the entire line until we know if we have one or not. So
858 we expand the line word by word until we find the first `:',
859 then check to see if it's a target-specific variable.
861 In this algorithm, `lb_next' will point to the beginning of the
862 unexpanded parts of the input buffer, while `p2' points to the
863 parts of the expanded buffer we haven't searched yet. */
866 enum make_word_type wtype;
867 enum variable_origin v_origin;
868 int exported;
869 char *cmdleft, *semip, *lb_next;
870 unsigned int len, plen = 0;
871 char *colonp;
872 const char *end, *beg; /* Helpers for whitespace stripping. */
874 /* Record the previous rule. */
876 record_waiting_files ();
877 tgts_started = fstart->lineno;
879 /* Search the line for an unquoted ; that is not after an
880 unquoted #. */
881 cmdleft = find_char_unquote (line, ';', '#', 0);
882 if (cmdleft != 0 && *cmdleft == '#')
884 /* We found a comment before a semicolon. */
885 *cmdleft = '\0';
886 cmdleft = 0;
888 else if (cmdleft != 0)
889 /* Found one. Cut the line short there before expanding it. */
890 *(cmdleft++) = '\0';
891 semip = cmdleft;
893 collapse_continuations (line);
895 /* We can't expand the entire line, since if it's a per-target
896 variable we don't want to expand it. So, walk from the
897 beginning, expanding as we go, and looking for "interesting"
898 chars. The first word is always expandable. */
899 wtype = get_next_mword(line, NULL, &lb_next, &len);
900 switch (wtype)
902 case w_eol:
903 if (cmdleft != 0)
904 fatal(fstart, _("missing rule before commands"));
905 /* This line contained something but turned out to be nothing
906 but whitespace (a comment?). */
907 continue;
909 case w_colon:
910 case w_dcolon:
911 /* We accept and ignore rules without targets for
912 compatibility with SunOS 4 make. */
913 no_targets = 1;
914 continue;
916 default:
917 break;
920 p2 = variable_expand_string(NULL, lb_next, len);
922 while (1)
924 lb_next += len;
925 if (cmdleft == 0)
927 /* Look for a semicolon in the expanded line. */
928 cmdleft = find_char_unquote (p2, ';', 0, 0);
930 if (cmdleft != 0)
932 unsigned long p2_off = p2 - variable_buffer;
933 unsigned long cmd_off = cmdleft - variable_buffer;
934 char *pend = p2 + strlen(p2);
936 /* Append any remnants of lb, then cut the line short
937 at the semicolon. */
938 *cmdleft = '\0';
940 /* One school of thought says that you shouldn't expand
941 here, but merely copy, since now you're beyond a ";"
942 and into a command script. However, the old parser
943 expanded the whole line, so we continue that for
944 backwards-compatiblity. Also, it wouldn't be
945 entirely consistent, since we do an unconditional
946 expand below once we know we don't have a
947 target-specific variable. */
948 (void)variable_expand_string(pend, lb_next, (long)-1);
949 lb_next += strlen(lb_next);
950 p2 = variable_buffer + p2_off;
951 cmdleft = variable_buffer + cmd_off + 1;
955 colonp = find_char_unquote(p2, ':', 0, 0);
956 #ifdef HAVE_DOS_PATHS
957 /* The drive spec brain-damage strikes again... */
958 /* Note that the only separators of targets in this context
959 are whitespace and a left paren. If others are possible,
960 they should be added to the string in the call to index. */
961 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
962 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
963 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
964 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
965 #endif
966 if (colonp != 0)
967 break;
969 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
970 if (wtype == w_eol)
971 break;
973 p2 += strlen(p2);
974 *(p2++) = ' ';
975 p2 = variable_expand_string(p2, lb_next, len);
976 /* We don't need to worry about cmdleft here, because if it was
977 found in the variable_buffer the entire buffer has already
978 been expanded... we'll never get here. */
981 p2 = next_token (variable_buffer);
983 /* If the word we're looking at is EOL, see if there's _anything_
984 on the line. If not, a variable expanded to nothing, so ignore
985 it. If so, we can't parse this line so punt. */
986 if (wtype == w_eol)
988 if (*p2 != '\0')
989 /* There's no need to be ivory-tower about this: check for
990 one of the most common bugs found in makefiles... */
991 fatal (fstart, _("missing separator%s"),
992 !strneq(line, " ", 8) ? ""
993 : _(" (did you mean TAB instead of 8 spaces?)"));
994 continue;
997 /* Make the colon the end-of-string so we know where to stop
998 looking for targets. */
999 *colonp = '\0';
1000 filenames = multi_glob (parse_file_seq (&p2, '\0',
1001 sizeof (struct nameseq),
1003 sizeof (struct nameseq));
1004 *p2 = ':';
1006 if (!filenames)
1008 /* We accept and ignore rules without targets for
1009 compatibility with SunOS 4 make. */
1010 no_targets = 1;
1011 continue;
1013 /* This should never be possible; we handled it above. */
1014 assert (*p2 != '\0');
1015 ++p2;
1017 /* Is this a one-colon or two-colon entry? */
1018 two_colon = *p2 == ':';
1019 if (two_colon)
1020 p2++;
1022 /* Test to see if it's a target-specific variable. Copy the rest
1023 of the buffer over, possibly temporarily (we'll expand it later
1024 if it's not a target-specific variable). PLEN saves the length
1025 of the unparsed section of p2, for later. */
1026 if (*lb_next != '\0')
1028 unsigned int l = p2 - variable_buffer;
1029 plen = strlen (p2);
1030 (void) variable_buffer_output (p2+plen,
1031 lb_next, strlen (lb_next)+1);
1032 p2 = variable_buffer + l;
1035 /* See if it's an "override" or "export" keyword; if so see if what
1036 comes after it looks like a variable definition. */
1038 wtype = get_next_mword (p2, NULL, &p, &len);
1040 v_origin = o_file;
1041 exported = 0;
1042 if (wtype == w_static)
1044 if (word1eq ("override"))
1046 v_origin = o_override;
1047 wtype = get_next_mword (p+len, NULL, &p, &len);
1049 else if (word1eq ("export"))
1051 exported = 1;
1052 wtype = get_next_mword (p+len, NULL, &p, &len);
1056 if (wtype != w_eol)
1057 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1059 if (wtype == w_varassign)
1061 /* If there was a semicolon found, add it back, plus anything
1062 after it. */
1063 if (semip)
1065 unsigned int l = p - variable_buffer;
1066 *(--semip) = ';';
1067 variable_buffer_output (p2 + strlen (p2),
1068 semip, strlen (semip)+1);
1069 p = variable_buffer + l;
1071 record_target_var (filenames, p, v_origin, exported, fstart);
1072 filenames = 0;
1073 continue;
1076 /* This is a normal target, _not_ a target-specific variable.
1077 Unquote any = in the dependency list. */
1078 find_char_unquote (lb_next, '=', 0, 0);
1080 /* We have some targets, so don't ignore the following commands. */
1081 no_targets = 0;
1083 /* Expand the dependencies, etc. */
1084 if (*lb_next != '\0')
1086 unsigned int l = p2 - variable_buffer;
1087 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1088 p2 = variable_buffer + l;
1090 /* Look for a semicolon in the expanded line. */
1091 if (cmdleft == 0)
1093 cmdleft = find_char_unquote (p2, ';', 0, 0);
1094 if (cmdleft != 0)
1095 *(cmdleft++) = '\0';
1099 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1100 p = strchr (p2, ':');
1101 while (p != 0 && p[-1] == '\\')
1103 register char *q = &p[-1];
1104 register int backslash = 0;
1105 while (*q-- == '\\')
1106 backslash = !backslash;
1107 if (backslash)
1108 p = strchr (p + 1, ':');
1109 else
1110 break;
1112 #ifdef _AMIGA
1113 /* Here, the situation is quite complicated. Let's have a look
1114 at a couple of targets:
1116 install: dev:make
1118 dev:make: make
1120 dev:make:: xyz
1122 The rule is that it's only a target, if there are TWO :'s
1123 OR a space around the :.
1125 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1126 || isspace ((unsigned char)p[-1])))
1127 p = 0;
1128 #endif
1129 #ifdef HAVE_DOS_PATHS
1131 int check_again;
1133 do {
1134 check_again = 0;
1135 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1136 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1137 isalpha ((unsigned char)p[-1]) &&
1138 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1139 p = strchr (p + 1, ':');
1140 check_again = 1;
1142 } while (check_again);
1144 #endif
1145 if (p != 0)
1147 struct nameseq *target;
1148 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1149 ++p2;
1150 if (target == 0)
1151 fatal (fstart, _("missing target pattern"));
1152 else if (target->next != 0)
1153 fatal (fstart, _("multiple target patterns"));
1154 pattern = target->name;
1155 pattern_percent = find_percent (pattern);
1156 if (pattern_percent == 0)
1157 fatal (fstart, _("target pattern contains no `%%'"));
1158 free((char *)target);
1160 else
1161 pattern = 0;
1163 /* Strip leading and trailing whitespaces. */
1164 beg = p2;
1165 end = beg + strlen (beg) - 1;
1166 strip_whitespace (&beg, &end);
1168 if (beg <= end && *beg != '\0')
1170 deps = (struct dep*) xmalloc (sizeof (struct dep));
1171 deps->next = 0;
1172 deps->name = savestring (beg, end - beg + 1);
1173 deps->file = 0;
1175 else
1176 deps = 0;
1178 commands_idx = 0;
1179 if (cmdleft != 0)
1181 /* Semicolon means rest of line is a command. */
1182 unsigned int len = strlen (cmdleft);
1184 cmds_started = fstart->lineno;
1186 /* Add this command line to the buffer. */
1187 if (len + 2 > commands_len)
1189 commands_len = (len + 2) * 2;
1190 commands = (char *) xrealloc (commands, commands_len);
1192 bcopy (cmdleft, commands, len);
1193 commands_idx += len;
1194 commands[commands_idx++] = '\n';
1197 /* Determine if this target should be made default. We used
1198 to do this in record_files() but because of the delayed
1199 target recording and because preprocessor directives are
1200 legal in target's commands it is too late. Consider this
1201 fragment for example:
1203 foo:
1205 ifeq ($(.DEFAULT_TARGET),foo)
1207 endif
1209 Because the target is not recorded until after ifeq
1210 directive is evaluated the .DEFAULT_TARGET does not
1211 contain foo yet as one would expect. Because of this
1212 we have to move some of the logic here. */
1214 if (**default_target_name == '\0' && set_default)
1216 char* name;
1217 struct dep *d;
1218 struct nameseq *t = filenames;
1220 for (; t != 0; t = t->next)
1222 int reject = 0;
1223 name = t->name;
1225 /* We have nothing to do if this is an implicit rule. */
1226 if (strchr (name, '%') != 0)
1227 break;
1229 /* See if this target's name does not start with a `.',
1230 unless it contains a slash. */
1231 if (*name == '.' && strchr (name, '/') == 0
1232 #ifdef HAVE_DOS_PATHS
1233 && strchr (name, '\\') == 0
1234 #endif
1236 continue;
1239 /* If this file is a suffix, don't let it be
1240 the default goal file. */
1241 for (d = suffix_file->deps; d != 0; d = d->next)
1243 register struct dep *d2;
1244 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1246 reject = 1;
1247 break;
1249 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1251 register unsigned int len = strlen (dep_name (d2));
1252 if (!strneq (name, dep_name (d2), len))
1253 continue;
1254 if (streq (name + len, dep_name (d)))
1256 reject = 1;
1257 break;
1261 if (reject)
1262 break;
1265 if (!reject)
1267 (void) define_variable_global (
1268 ".DEFAULT_TARGET", 15, t->name, o_file, 0, NILF);
1269 break;
1274 continue;
1277 /* We get here except in the case that we just read a rule line.
1278 Record now the last rule we read, so following spurious
1279 commands are properly diagnosed. */
1280 rule_complete:
1281 record_waiting_files ();
1284 #undef word1eq
1286 if (conditionals->if_cmds)
1287 fatal (fstart, _("missing `endif'"));
1289 /* At eof, record the last rule. */
1290 record_waiting_files ();
1292 if (collapsed)
1293 free ((char *) collapsed);
1294 free ((char *) commands);
1296 return 1;
1300 /* Execute a `define' directive.
1301 The first line has already been read, and NAME is the name of
1302 the variable to be defined. The following lines remain to be read. */
1304 static void
1305 do_define (char *name, unsigned int namelen,
1306 enum variable_origin origin, struct ebuffer *ebuf)
1308 struct floc defstart;
1309 long nlines = 0;
1310 int nlevels = 1;
1311 unsigned int length = 100;
1312 char *definition = (char *) xmalloc (length);
1313 unsigned int idx = 0;
1314 char *p;
1316 /* Expand the variable name. */
1317 char *var = (char *) alloca (namelen + 1);
1318 bcopy (name, var, namelen);
1319 var[namelen] = '\0';
1320 var = variable_expand (var);
1322 defstart = ebuf->floc;
1324 while (1)
1326 unsigned int len;
1327 char *line;
1329 nlines = readline (ebuf);
1330 ebuf->floc.lineno += nlines;
1332 /* If there is nothing left to eval, we're done. */
1333 if (nlines < 0)
1334 break;
1336 line = ebuf->buffer;
1338 collapse_continuations (line);
1340 /* If the line doesn't begin with a tab, test to see if it introduces
1341 another define, or ends one. */
1343 /* Stop if we find an 'endef' */
1344 if (line[0] != '\t')
1346 p = next_token (line);
1347 len = strlen (p);
1349 /* If this is another 'define', increment the level count. */
1350 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1351 && strneq (p, "define", 6))
1352 ++nlevels;
1354 /* If this is an 'endef', decrement the count. If it's now 0,
1355 we've found the last one. */
1356 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1357 && strneq (p, "endef", 5))
1359 p += 5;
1360 remove_comments (p);
1361 if (*next_token (p) != '\0')
1362 error (&ebuf->floc,
1363 _("Extraneous text after `endef' directive"));
1365 if (--nlevels == 0)
1367 /* Define the variable. */
1368 if (idx == 0)
1369 definition[0] = '\0';
1370 else
1371 definition[idx - 1] = '\0';
1373 /* Always define these variables in the global set. */
1374 define_variable_global (var, strlen (var), definition,
1375 origin, 1, &defstart);
1376 free (definition);
1377 return;
1382 /* Otherwise add this line to the variable definition. */
1383 len = strlen (line);
1384 if (idx + len + 1 > length)
1386 length = (idx + len) * 2;
1387 definition = (char *) xrealloc (definition, length + 1);
1390 bcopy (line, &definition[idx], len);
1391 idx += len;
1392 /* Separate lines with a newline. */
1393 definition[idx++] = '\n';
1396 /* No `endef'!! */
1397 fatal (&defstart, _("missing `endef', unterminated `define'"));
1399 /* NOTREACHED */
1400 return;
1403 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1404 "ifneq", "else" and "endif".
1405 LINE is the input line, with the command as its first word.
1407 FILENAME and LINENO are the filename and line number in the
1408 current makefile. They are used for error messages.
1410 Value is -1 if the line is invalid,
1411 0 if following text should be interpreted,
1412 1 if following text should be ignored. */
1414 static int
1415 conditional_line (char *line, const struct floc *flocp)
1417 int notdef;
1418 char *cmdname;
1419 register unsigned int i;
1421 if (*line == 'i')
1423 /* It's an "if..." command. */
1424 notdef = line[2] == 'n';
1425 if (notdef)
1427 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1428 line += cmdname[3] == 'd' ? 7 : 6;
1430 else
1432 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1433 line += cmdname[2] == 'd' ? 6 : 5;
1436 else
1438 /* It's an "else" or "endif" command. */
1439 notdef = line[1] == 'n';
1440 cmdname = notdef ? "endif" : "else";
1441 line += notdef ? 5 : 4;
1444 line = next_token (line);
1446 if (*cmdname == 'e')
1448 if (*line != '\0')
1449 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1450 /* "Else" or "endif". */
1451 if (conditionals->if_cmds == 0)
1452 fatal (flocp, _("extraneous `%s'"), cmdname);
1453 /* NOTDEF indicates an `endif' command. */
1454 if (notdef)
1455 --conditionals->if_cmds;
1456 else if (conditionals->seen_else[conditionals->if_cmds - 1])
1457 fatal (flocp, _("only one `else' per conditional"));
1458 else
1460 /* Toggle the state of ignorance. */
1461 conditionals->ignoring[conditionals->if_cmds - 1]
1462 = !conditionals->ignoring[conditionals->if_cmds - 1];
1463 /* Record that we have seen an `else' in this conditional.
1464 A second `else' will be erroneous. */
1465 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1467 for (i = 0; i < conditionals->if_cmds; ++i)
1468 if (conditionals->ignoring[i])
1469 return 1;
1470 return 0;
1473 if (conditionals->allocated == 0)
1475 conditionals->allocated = 5;
1476 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1477 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1480 ++conditionals->if_cmds;
1481 if (conditionals->if_cmds > conditionals->allocated)
1483 conditionals->allocated += 5;
1484 conditionals->ignoring = (char *)
1485 xrealloc (conditionals->ignoring, conditionals->allocated);
1486 conditionals->seen_else = (char *)
1487 xrealloc (conditionals->seen_else, conditionals->allocated);
1490 /* Record that we have seen an `if...' but no `else' so far. */
1491 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1493 /* Search through the stack to see if we're already ignoring. */
1494 for (i = 0; i < conditionals->if_cmds - 1; ++i)
1495 if (conditionals->ignoring[i])
1497 /* We are already ignoring, so just push a level
1498 to match the next "else" or "endif", and keep ignoring.
1499 We don't want to expand variables in the condition. */
1500 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1501 return 1;
1504 if (cmdname[notdef ? 3 : 2] == 'd')
1506 /* "Ifdef" or "ifndef". */
1507 char *var;
1508 struct variable *v;
1509 register char *p;
1511 /* Expand the thing we're looking up, so we can use indirect and
1512 constructed variable names. */
1513 var = allocated_variable_expand (line);
1515 /* Make sure there's only one variable name to test. */
1516 p = end_of_token (var);
1517 i = p - var;
1518 p = next_token (p);
1519 if (*p != '\0')
1520 return -1;
1522 var[i] = '\0';
1523 v = lookup_variable (var, strlen (var));
1524 conditionals->ignoring[conditionals->if_cmds - 1]
1525 = (v != 0 && *v->value != '\0') == notdef;
1527 free (var);
1529 else
1531 /* "Ifeq" or "ifneq". */
1532 char *s1, *s2;
1533 unsigned int len;
1534 char termin = *line == '(' ? ',' : *line;
1536 if (termin != ',' && termin != '"' && termin != '\'')
1537 return -1;
1539 s1 = ++line;
1540 /* Find the end of the first string. */
1541 if (termin == ',')
1543 register int count = 0;
1544 for (; *line != '\0'; ++line)
1545 if (*line == '(')
1546 ++count;
1547 else if (*line == ')')
1548 --count;
1549 else if (*line == ',' && count <= 0)
1550 break;
1552 else
1553 while (*line != '\0' && *line != termin)
1554 ++line;
1556 if (*line == '\0')
1557 return -1;
1559 if (termin == ',')
1561 /* Strip blanks after the first string. */
1562 char *p = line++;
1563 while (isblank ((unsigned char)p[-1]))
1564 --p;
1565 *p = '\0';
1567 else
1568 *line++ = '\0';
1570 s2 = variable_expand (s1);
1571 /* We must allocate a new copy of the expanded string because
1572 variable_expand re-uses the same buffer. */
1573 len = strlen (s2);
1574 s1 = (char *) alloca (len + 1);
1575 bcopy (s2, s1, len + 1);
1577 if (termin != ',')
1578 /* Find the start of the second string. */
1579 line = next_token (line);
1581 termin = termin == ',' ? ')' : *line;
1582 if (termin != ')' && termin != '"' && termin != '\'')
1583 return -1;
1585 /* Find the end of the second string. */
1586 if (termin == ')')
1588 register int count = 0;
1589 s2 = next_token (line);
1590 for (line = s2; *line != '\0'; ++line)
1592 if (*line == '(')
1593 ++count;
1594 else if (*line == ')')
1596 if (count <= 0)
1597 break;
1598 else
1599 --count;
1603 else
1605 ++line;
1606 s2 = line;
1607 while (*line != '\0' && *line != termin)
1608 ++line;
1611 if (*line == '\0')
1612 return -1;
1614 *line = '\0';
1615 line = next_token (++line);
1616 if (*line != '\0')
1617 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1619 s2 = variable_expand (s2);
1620 conditionals->ignoring[conditionals->if_cmds - 1]
1621 = streq (s1, s2) == notdef;
1624 /* Search through the stack to see if we're ignoring. */
1625 for (i = 0; i < conditionals->if_cmds; ++i)
1626 if (conditionals->ignoring[i])
1627 return 1;
1628 return 0;
1631 /* Remove duplicate dependencies in CHAIN. */
1633 static unsigned long
1634 dep_hash_1 (const void *key)
1636 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1639 static unsigned long
1640 dep_hash_2 (const void *key)
1642 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1645 static int
1646 dep_hash_cmp (const void *x, const void *y)
1648 struct dep *dx = (struct dep *) x;
1649 struct dep *dy = (struct dep *) y;
1650 int cmp = strcmp (dep_name (dx), dep_name (dy));
1652 /* If the names are the same but ignore_mtimes are not equal, one of these
1653 is an order-only prerequisite and one isn't. That means that we should
1654 remove the one that isn't and keep the one that is. */
1656 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1657 dx->ignore_mtime = dy->ignore_mtime = 0;
1659 return cmp;
1663 void
1664 uniquize_deps (struct dep *chain)
1666 struct hash_table deps;
1667 register struct dep **depp;
1669 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1671 /* Make sure that no dependencies are repeated. This does not
1672 really matter for the purpose of updating targets, but it
1673 might make some names be listed twice for $^ and $?. */
1675 depp = &chain;
1676 while (*depp)
1678 struct dep *dep = *depp;
1679 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1680 if (HASH_VACANT (*dep_slot))
1682 hash_insert_at (&deps, dep, dep_slot);
1683 depp = &dep->next;
1685 else
1687 /* Don't bother freeing duplicates.
1688 It's dangerous and little benefit accrues. */
1689 *depp = dep->next;
1693 hash_free (&deps, 0);
1696 /* Record target-specific variable values for files FILENAMES.
1697 TWO_COLON is nonzero if a double colon was used.
1699 The links of FILENAMES are freed, and so are any names in it
1700 that are not incorporated into other data structures.
1702 If the target is a pattern, add the variable to the pattern-specific
1703 variable value list. */
1705 static void
1706 record_target_var (struct nameseq *filenames, char *defn,
1707 enum variable_origin origin, int exported,
1708 const struct floc *flocp)
1710 struct nameseq *nextf;
1711 struct variable_set_list *global;
1713 global = current_variable_set_list;
1715 /* If the variable is an append version, store that but treat it as a
1716 normal recursive variable. */
1718 for (; filenames != 0; filenames = nextf)
1720 struct variable *v;
1721 register char *name = filenames->name;
1722 char *fname;
1723 char *percent;
1724 struct pattern_var *p;
1726 nextf = filenames->next;
1727 free ((char *) filenames);
1729 /* If it's a pattern target, then add it to the pattern-specific
1730 variable list. */
1731 percent = find_percent (name);
1732 if (percent)
1734 /* Get a reference for this pattern-specific variable struct. */
1735 p = create_pattern_var (name, percent);
1736 p->variable.fileinfo = *flocp;
1737 /* I don't think this can fail since we already determined it was a
1738 variable definition. */
1739 v = parse_variable_definition (&p->variable, defn);
1740 assert (v != 0);
1742 if (v->flavor == f_simple)
1743 v->value = allocated_variable_expand (v->value);
1744 else
1745 v->value = xstrdup (v->value);
1747 fname = p->target;
1749 else
1751 struct file *f;
1753 /* Get a file reference for this file, and initialize it.
1754 We don't want to just call enter_file() because that allocates a
1755 new entry if the file is a double-colon, which we don't want in
1756 this situation. */
1757 f = lookup_file (name);
1758 if (!f)
1759 f = enter_file (name);
1760 else if (f->double_colon)
1761 f = f->double_colon;
1763 initialize_file_variables (f, 1);
1764 fname = f->name;
1766 current_variable_set_list = f->variables;
1767 v = try_variable_definition (flocp, defn, origin, 1);
1768 if (!v)
1769 error (flocp, _("Malformed target-specific variable definition"));
1770 current_variable_set_list = global;
1773 /* Set up the variable to be *-specific. */
1774 v->origin = origin;
1775 v->per_target = 1;
1776 if (exported)
1777 v->export = v_export;
1779 /* If it's not an override, check to see if there was a command-line
1780 setting. If so, reset the value. */
1781 if (origin != o_override)
1783 struct variable *gv;
1784 int len = strlen(v->name);
1786 gv = lookup_variable (v->name, len);
1787 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1789 if (v->value != 0)
1790 free (v->value);
1791 v->value = xstrdup (gv->value);
1792 v->origin = gv->origin;
1793 v->recursive = gv->recursive;
1794 v->append = 0;
1798 /* Free name if not needed further. */
1799 if (name != fname && (name < fname || name > fname + strlen (fname)))
1800 free (name);
1804 /* Record a description line for files FILENAMES,
1805 with dependencies DEPS, commands to execute described
1806 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1807 TWO_COLON is nonzero if a double colon was used.
1808 If not nil, PATTERN is the `%' pattern to make this
1809 a static pattern rule, and PATTERN_PERCENT is a pointer
1810 to the `%' within it.
1812 The links of FILENAMES are freed, and so are any names in it
1813 that are not incorporated into other data structures. */
1815 static void
1816 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1817 struct dep *deps, unsigned int cmds_started, char *commands,
1818 unsigned int commands_idx, int two_colon,
1819 const struct floc *flocp)
1821 struct nameseq *nextf;
1822 int implicit = 0;
1823 unsigned int max_targets = 0, target_idx = 0;
1824 char **targets = 0, **target_percents = 0;
1825 struct commands *cmds;
1827 /* If we've already snapped deps, that means we're in an eval being
1828 resolved after the makefiles have been read in. We can't add more rules
1829 at this time, since they won't get snapped and we'll get core dumps.
1830 See Savannah bug # 12124. */
1831 if (snapped_deps)
1832 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1834 if (commands_idx > 0)
1836 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1837 cmds->fileinfo.filenm = flocp->filenm;
1838 cmds->fileinfo.lineno = cmds_started;
1839 cmds->commands = savestring (commands, commands_idx);
1840 cmds->command_lines = 0;
1842 else
1843 cmds = 0;
1845 for (; filenames != 0; filenames = nextf)
1847 char *name = filenames->name;
1848 struct file *f;
1849 struct dep *d;
1850 struct dep *this;
1851 char *implicit_percent;
1853 nextf = filenames->next;
1854 free (filenames);
1856 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1857 good enough: it doesn't happen until after the makefile is read,
1858 which means we cannot use its value during parsing. */
1860 if (streq (name, ".POSIX"))
1861 posix_pedantic = 1;
1863 implicit_percent = find_percent (name);
1864 implicit |= implicit_percent != 0;
1866 if (implicit && pattern != 0)
1867 fatal (flocp, _("mixed implicit and static pattern rules"));
1869 if (implicit && implicit_percent == 0)
1870 fatal (flocp, _("mixed implicit and normal rules"));
1872 if (implicit)
1874 if (targets == 0)
1876 max_targets = 5;
1877 targets = (char **) xmalloc (5 * sizeof (char *));
1878 target_percents = (char **) xmalloc (5 * sizeof (char *));
1879 target_idx = 0;
1881 else if (target_idx == max_targets - 1)
1883 max_targets += 5;
1884 targets = (char **) xrealloc ((char *) targets,
1885 max_targets * sizeof (char *));
1886 target_percents
1887 = (char **) xrealloc ((char *) target_percents,
1888 max_targets * sizeof (char *));
1890 targets[target_idx] = name;
1891 target_percents[target_idx] = implicit_percent;
1892 ++target_idx;
1893 continue;
1896 /* If there are multiple filenames, copy the chain DEPS
1897 for all but the last one. It is not safe for the same deps
1898 to go in more than one place in the data base. */
1899 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1901 if (pattern != 0)
1903 /* If this is an extended static rule:
1904 `targets: target%pattern: dep%pattern; cmds',
1905 translate each dependency pattern into a plain filename
1906 using the target pattern and this target's name. */
1907 if (!pattern_matches (pattern, pattern_percent, name))
1909 /* Give a warning if the rule is meaningless. */
1910 error (flocp,
1911 _("target `%s' doesn't match the target pattern"), name);
1912 this = 0;
1914 else
1916 /* We use subst_expand to do the work of translating
1917 % to $* in the dependency line. */
1919 if (this != 0 && find_percent (this->name) != 0)
1921 char *o;
1922 char *buffer = variable_expand ("");
1924 o = subst_expand (buffer, this->name, "%", "$*",
1925 1, 2, 0);
1927 free (this->name);
1928 this->name = savestring (buffer, o - buffer);
1933 if (!two_colon)
1935 /* Single-colon. Combine these dependencies
1936 with others in file's existing record, if any. */
1937 f = enter_file (name);
1939 if (f->double_colon)
1940 fatal (flocp,
1941 _("target file `%s' has both : and :: entries"), f->name);
1943 /* If CMDS == F->CMDS, this target was listed in this rule
1944 more than once. Just give a warning since this is harmless. */
1945 if (cmds != 0 && cmds == f->cmds)
1946 error (flocp,
1947 _("target `%s' given more than once in the same rule."),
1948 f->name);
1950 /* Check for two single-colon entries both with commands.
1951 Check is_target so that we don't lose on files such as .c.o
1952 whose commands were preinitialized. */
1953 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1955 error (&cmds->fileinfo,
1956 _("warning: overriding commands for target `%s'"),
1957 f->name);
1958 error (&f->cmds->fileinfo,
1959 _("warning: ignoring old commands for target `%s'"),
1960 f->name);
1963 f->is_target = 1;
1965 /* Defining .DEFAULT with no deps or cmds clears it. */
1966 if (f == default_file && this == 0 && cmds == 0)
1967 f->cmds = 0;
1968 if (cmds != 0)
1969 f->cmds = cmds;
1971 /* Defining .SUFFIXES with no dependencies
1972 clears out the list of suffixes. */
1973 if (f == suffix_file && this == 0)
1975 d = f->deps;
1976 while (d != 0)
1978 struct dep *nextd = d->next;
1979 free (d->name);
1980 free ((char *)d);
1981 d = nextd;
1983 f->deps = 0;
1985 else if (this != 0)
1987 /* Add the file's old deps and the new ones in THIS together. */
1989 if (f->deps != 0)
1991 struct dep **d_ptr = &f->deps;
1993 while ((*d_ptr)->next != 0)
1994 d_ptr = &(*d_ptr)->next;
1996 if (cmds != 0)
1998 /* This is the rule with commands, so put its deps
1999 last. The rationale behind this is that $< expands
2000 to the first dep in the chain, and commands use $<
2001 expecting to get the dep that rule specifies.
2002 However the second expansion algorithm reverses
2003 the order thus we need to make it last here. */
2005 (*d_ptr)->next = this;
2007 else
2009 /* This is the rule without commands. Put its
2010 dependencies at the end but before dependencies
2011 from the rule with commands (if any). This way
2012 everyhting appears in makefile order. */
2014 if (f->cmds != 0)
2016 this->next = *d_ptr;
2017 *d_ptr = this;
2019 else
2020 (*d_ptr)->next = this;
2023 else
2024 f->deps = this;
2026 /* This is a hack. I need a way to communicate to snap_deps()
2027 that the last dependency line in this file came with commands
2028 (so that logic in snap_deps() can put it in front and all
2029 this $< -logic works). I cannot's simply rely oon file->cmds
2030 being not 0 because of the cases like the following:
2032 foo: bar
2033 foo:
2036 I am going to temporarily "borrow" UPDATING member in
2037 `struct file' for this. */
2039 if (cmds != 0)
2040 f->updating = 1;
2043 /* If this is a static pattern rule, set the file's stem to
2044 the part of its name that matched the `%' in the pattern,
2045 so you can use $* in the commands. */
2046 if (pattern != 0)
2048 static char *percent = "%";
2049 char *buffer = variable_expand ("");
2050 char *o = patsubst_expand (buffer, name, pattern, percent,
2051 pattern_percent+1, percent+1);
2052 f->stem = savestring (buffer, o - buffer);
2055 else
2057 /* Double-colon. Make a new record
2058 even if the file already has one. */
2059 f = lookup_file (name);
2060 /* Check for both : and :: rules. Check is_target so
2061 we don't lose on default suffix rules or makefiles. */
2062 if (f != 0 && f->is_target && !f->double_colon)
2063 fatal (flocp,
2064 _("target file `%s' has both : and :: entries"), f->name);
2065 f = enter_file (name);
2066 /* If there was an existing entry and it was a double-colon
2067 entry, enter_file will have returned a new one, making it the
2068 prev pointer of the old one, and setting its double_colon
2069 pointer to the first one. */
2070 if (f->double_colon == 0)
2071 /* This is the first entry for this name, so we must
2072 set its double_colon pointer to itself. */
2073 f->double_colon = f;
2074 f->is_target = 1;
2075 f->deps = this;
2076 f->cmds = cmds;
2079 /* Free name if not needed further. */
2080 if (f != 0 && name != f->name
2081 && (name < f->name || name > f->name + strlen (f->name)))
2083 free (name);
2084 name = f->name;
2087 /* See if this target is a default target and update
2088 DEFAULT_GOAL_FILE if necessary. */
2089 if (strcmp (*default_target_name, name) == 0 &&
2090 (default_goal_file == 0 ||
2091 strcmp (default_goal_file->name, name) != 0))
2093 default_goal_file = f;
2097 if (implicit)
2099 targets[target_idx] = 0;
2100 target_percents[target_idx] = 0;
2101 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2102 free ((char *) target_percents);
2106 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2107 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2108 Quoting backslashes are removed from STRING by compacting it into
2109 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2110 one, or nil if there are none. */
2112 char *
2113 find_char_unquote (char *string, int stop1, int stop2, int blank)
2115 unsigned int string_len = 0;
2116 register char *p = string;
2118 while (1)
2120 if (stop2 && blank)
2121 while (*p != '\0' && *p != stop1 && *p != stop2
2122 && ! isblank ((unsigned char) *p))
2123 ++p;
2124 else if (stop2)
2125 while (*p != '\0' && *p != stop1 && *p != stop2)
2126 ++p;
2127 else if (blank)
2128 while (*p != '\0' && *p != stop1
2129 && ! isblank ((unsigned char) *p))
2130 ++p;
2131 else
2132 while (*p != '\0' && *p != stop1)
2133 ++p;
2135 if (*p == '\0')
2136 break;
2138 if (p > string && p[-1] == '\\')
2140 /* Search for more backslashes. */
2141 register int i = -2;
2142 while (&p[i] >= string && p[i] == '\\')
2143 --i;
2144 ++i;
2145 /* Only compute the length if really needed. */
2146 if (string_len == 0)
2147 string_len = strlen (string);
2148 /* The number of backslashes is now -I.
2149 Copy P over itself to swallow half of them. */
2150 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2151 p += i / 2;
2152 if (i % 2 == 0)
2153 /* All the backslashes quoted each other; the STOPCHAR was
2154 unquoted. */
2155 return p;
2157 /* The STOPCHAR was quoted by a backslash. Look for another. */
2159 else
2160 /* No backslash in sight. */
2161 return p;
2164 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2165 return 0;
2168 /* Search PATTERN for an unquoted %. */
2170 char *
2171 find_percent (char *pattern)
2173 return find_char_unquote (pattern, '%', 0, 0);
2176 /* Parse a string into a sequence of filenames represented as a
2177 chain of struct nameseq's in reverse order and return that chain.
2179 The string is passed as STRINGP, the address of a string pointer.
2180 The string pointer is updated to point at the first character
2181 not parsed, which either is a null char or equals STOPCHAR.
2183 SIZE is how big to construct chain elements.
2184 This is useful if we want them actually to be other structures
2185 that have room for additional info.
2187 If STRIP is nonzero, strip `./'s off the beginning. */
2189 struct nameseq *
2190 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2192 register struct nameseq *new = 0;
2193 register struct nameseq *new1, *lastnew1;
2194 register char *p = *stringp;
2195 char *q;
2196 char *name;
2198 #ifdef VMS
2199 # define VMS_COMMA ','
2200 #else
2201 # define VMS_COMMA 0
2202 #endif
2204 while (1)
2206 /* Skip whitespace; see if any more names are left. */
2207 p = next_token (p);
2208 if (*p == '\0')
2209 break;
2210 if (*p == stopchar)
2211 break;
2213 /* Yes, find end of next name. */
2214 q = p;
2215 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2216 #ifdef VMS
2217 /* convert comma separated list to space separated */
2218 if (p && *p == ',')
2219 *p =' ';
2220 #endif
2221 #ifdef _AMIGA
2222 if (stopchar == ':' && p && *p == ':'
2223 && !(isspace ((unsigned char)p[1]) || !p[1]
2224 || isspace ((unsigned char)p[-1])))
2226 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2228 #endif
2229 #ifdef HAVE_DOS_PATHS
2230 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2231 first colon which isn't followed by a slash or a backslash.
2232 Note that tokens separated by spaces should be treated as separate
2233 tokens since make doesn't allow path names with spaces */
2234 if (stopchar == ':')
2235 while (p != 0 && !isspace ((unsigned char)*p) &&
2236 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2237 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2238 #endif
2239 if (p == 0)
2240 p = q + strlen (q);
2242 if (strip)
2243 #ifdef VMS
2244 /* Skip leading `[]'s. */
2245 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2246 #else
2247 /* Skip leading `./'s. */
2248 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2249 #endif
2251 q += 2; /* Skip "./". */
2252 while (q < p && *q == '/')
2253 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2254 ++q;
2257 /* Extract the filename just found, and skip it. */
2259 if (q == p)
2260 /* ".///" was stripped to "". */
2261 #ifdef VMS
2262 continue;
2263 #else
2264 #ifdef _AMIGA
2265 name = savestring ("", 0);
2266 #else
2267 name = savestring ("./", 2);
2268 #endif
2269 #endif
2270 else
2271 #ifdef VMS
2272 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2273 * to remove this '\' before we can use the filename.
2274 * Savestring called because q may be read-only string constant.
2277 char *qbase = xstrdup (q);
2278 char *pbase = qbase + (p-q);
2279 char *q1 = qbase;
2280 char *q2 = q1;
2281 char *p1 = pbase;
2283 while (q1 != pbase)
2285 if (*q1 == '\\' && *(q1+1) == ':')
2287 q1++;
2288 p1--;
2290 *q2++ = *q1++;
2292 name = savestring (qbase, p1 - qbase);
2293 free (qbase);
2295 #else
2296 name = savestring (q, p - q);
2297 #endif
2299 /* Add it to the front of the chain. */
2300 new1 = (struct nameseq *) xmalloc (size);
2301 new1->name = name;
2302 new1->next = new;
2303 new = new1;
2306 #ifndef NO_ARCHIVES
2308 /* Look for multi-word archive references.
2309 They are indicated by a elt ending with an unmatched `)' and
2310 an elt further down the chain (i.e., previous in the file list)
2311 with an unmatched `(' (e.g., "lib(mem"). */
2313 new1 = new;
2314 lastnew1 = 0;
2315 while (new1 != 0)
2316 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2317 && new1->name[strlen (new1->name) - 1] == ')'
2318 && strchr (new1->name, '(') == 0)
2320 /* NEW1 ends with a `)' but does not contain a `('.
2321 Look back for an elt with an opening `(' but no closing `)'. */
2323 struct nameseq *n = new1->next, *lastn = new1;
2324 char *paren = 0;
2325 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2327 lastn = n;
2328 n = n->next;
2330 if (n != 0
2331 /* Ignore something starting with `(', as that cannot actually
2332 be an archive-member reference (and treating it as such
2333 results in an empty file name, which causes much lossage). */
2334 && n->name[0] != '(')
2336 /* N is the first element in the archive group.
2337 Its name looks like "lib(mem" (with no closing `)'). */
2339 char *libname;
2341 /* Copy "lib(" into LIBNAME. */
2342 ++paren;
2343 libname = (char *) alloca (paren - n->name + 1);
2344 bcopy (n->name, libname, paren - n->name);
2345 libname[paren - n->name] = '\0';
2347 if (*paren == '\0')
2349 /* N was just "lib(", part of something like "lib( a b)".
2350 Edit it out of the chain and free its storage. */
2351 lastn->next = n->next;
2352 free (n->name);
2353 free ((char *) n);
2354 /* LASTN->next is the new stopping elt for the loop below. */
2355 n = lastn->next;
2357 else
2359 /* Replace N's name with the full archive reference. */
2360 name = concat (libname, paren, ")");
2361 free (n->name);
2362 n->name = name;
2365 if (new1->name[1] == '\0')
2367 /* NEW1 is just ")", part of something like "lib(a b )".
2368 Omit it from the chain and free its storage. */
2369 if (lastnew1 == 0)
2370 new = new1->next;
2371 else
2372 lastnew1->next = new1->next;
2373 lastn = new1;
2374 new1 = new1->next;
2375 free (lastn->name);
2376 free ((char *) lastn);
2378 else
2380 /* Replace also NEW1->name, which already has closing `)'. */
2381 name = concat (libname, new1->name, "");
2382 free (new1->name);
2383 new1->name = name;
2384 new1 = new1->next;
2387 /* Trace back from NEW1 (the end of the list) until N
2388 (the beginning of the list), rewriting each name
2389 with the full archive reference. */
2391 while (new1 != n)
2393 name = concat (libname, new1->name, ")");
2394 free (new1->name);
2395 new1->name = name;
2396 lastnew1 = new1;
2397 new1 = new1->next;
2400 else
2402 /* No frobnication happening. Just step down the list. */
2403 lastnew1 = new1;
2404 new1 = new1->next;
2407 else
2409 lastnew1 = new1;
2410 new1 = new1->next;
2413 #endif
2415 *stringp = p;
2416 return new;
2419 /* Find the next line of text in an eval buffer, combining continuation lines
2420 into one line.
2421 Return the number of actual lines read (> 1 if continuation lines).
2422 Returns -1 if there's nothing left in the buffer.
2424 After this function, ebuf->buffer points to the first character of the
2425 line we just found.
2428 /* Read a line of text from a STRING.
2429 Since we aren't really reading from a file, don't bother with linenumbers.
2432 static unsigned long
2433 readstring (struct ebuffer *ebuf)
2435 char *eol;
2437 /* If there is nothing left in this buffer, return 0. */
2438 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2439 return -1;
2441 /* Set up a new starting point for the buffer, and find the end of the
2442 next logical line (taking into account backslash/newline pairs). */
2444 eol = ebuf->buffer = ebuf->bufnext;
2446 while (1)
2448 int backslash = 0;
2449 char *bol = eol;
2450 char *p;
2452 /* Find the next newline. At EOS, stop. */
2453 eol = p = strchr (eol , '\n');
2454 if (!eol)
2456 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2457 return 0;
2460 /* Found a newline; if it's escaped continue; else we're done. */
2461 while (p > bol && *(--p) == '\\')
2462 backslash = !backslash;
2463 if (!backslash)
2464 break;
2465 ++eol;
2468 /* Overwrite the newline char. */
2469 *eol = '\0';
2470 ebuf->bufnext = eol+1;
2472 return 0;
2475 static long
2476 readline (struct ebuffer *ebuf)
2478 char *p;
2479 char *end;
2480 char *start;
2481 long nlines = 0;
2483 /* The behaviors between string and stream buffers are different enough to
2484 warrant different functions. Do the Right Thing. */
2486 if (!ebuf->fp)
2487 return readstring (ebuf);
2489 /* When reading from a file, we always start over at the beginning of the
2490 buffer for each new line. */
2492 p = start = ebuf->bufstart;
2493 end = p + ebuf->size;
2494 *p = '\0';
2496 while (fgets (p, end - p, ebuf->fp) != 0)
2498 char *p2;
2499 unsigned long len;
2500 int backslash;
2502 len = strlen (p);
2503 if (len == 0)
2505 /* This only happens when the first thing on the line is a '\0'.
2506 It is a pretty hopeless case, but (wonder of wonders) Athena
2507 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2508 There is nothing really to be done; we synthesize a newline so
2509 the following line doesn't appear to be part of this line. */
2510 error (&ebuf->floc,
2511 _("warning: NUL character seen; rest of line ignored"));
2512 p[0] = '\n';
2513 len = 1;
2516 /* Jump past the text we just read. */
2517 p += len;
2519 /* If the last char isn't a newline, the whole line didn't fit into the
2520 buffer. Get some more buffer and try again. */
2521 if (p[-1] != '\n')
2522 goto more_buffer;
2524 /* We got a newline, so add one to the count of lines. */
2525 ++nlines;
2527 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2528 /* Check to see if the line was really ended with CRLF; if so ignore
2529 the CR. */
2530 if ((p - start) > 1 && p[-2] == '\r')
2532 --p;
2533 p[-1] = '\n';
2535 #endif
2537 backslash = 0;
2538 for (p2 = p - 2; p2 >= start; --p2)
2540 if (*p2 != '\\')
2541 break;
2542 backslash = !backslash;
2545 if (!backslash)
2547 p[-1] = '\0';
2548 break;
2551 /* It was a backslash/newline combo. If we have more space, read
2552 another line. */
2553 if (end - p >= 80)
2554 continue;
2556 /* We need more space at the end of our buffer, so realloc it.
2557 Make sure to preserve the current offset of p. */
2558 more_buffer:
2560 unsigned long off = p - start;
2561 ebuf->size *= 2;
2562 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2563 ebuf->size);
2564 p = start + off;
2565 end = start + ebuf->size;
2566 *p = '\0';
2570 if (ferror (ebuf->fp))
2571 pfatal_with_name (ebuf->floc.filenm);
2573 /* If we found some lines, return how many.
2574 If we didn't, but we did find _something_, that indicates we read the last
2575 line of a file with no final newline; return 1.
2576 If we read nothing, we're at EOF; return -1. */
2578 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2581 /* Parse the next "makefile word" from the input buffer, and return info
2582 about it.
2584 A "makefile word" is one of:
2586 w_bogus Should never happen
2587 w_eol End of input
2588 w_static A static word; cannot be expanded
2589 w_variable A word containing one or more variables/functions
2590 w_colon A colon
2591 w_dcolon A double-colon
2592 w_semicolon A semicolon
2593 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2595 Note that this function is only used when reading certain parts of the
2596 makefile. Don't use it where special rules hold sway (RHS of a variable,
2597 in a command list, etc.) */
2599 static enum make_word_type
2600 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2602 enum make_word_type wtype = w_bogus;
2603 char *p = buffer, *beg;
2604 char c;
2606 /* Skip any leading whitespace. */
2607 while (isblank ((unsigned char)*p))
2608 ++p;
2610 beg = p;
2611 c = *(p++);
2612 switch (c)
2614 case '\0':
2615 wtype = w_eol;
2616 break;
2618 case ';':
2619 wtype = w_semicolon;
2620 break;
2622 case '=':
2623 wtype = w_varassign;
2624 break;
2626 case ':':
2627 wtype = w_colon;
2628 switch (*p)
2630 case ':':
2631 ++p;
2632 wtype = w_dcolon;
2633 break;
2635 case '=':
2636 ++p;
2637 wtype = w_varassign;
2638 break;
2640 break;
2642 case '+':
2643 case '?':
2644 if (*p == '=')
2646 ++p;
2647 wtype = w_varassign;
2648 break;
2651 default:
2652 if (delim && strchr (delim, c))
2653 wtype = w_static;
2654 break;
2657 /* Did we find something? If so, return now. */
2658 if (wtype != w_bogus)
2659 goto done;
2661 /* This is some non-operator word. A word consists of the longest
2662 string of characters that doesn't contain whitespace, one of [:=#],
2663 or [?+]=, or one of the chars in the DELIM string. */
2665 /* We start out assuming a static word; if we see a variable we'll
2666 adjust our assumptions then. */
2667 wtype = w_static;
2669 /* We already found the first value of "c", above. */
2670 while (1)
2672 char closeparen;
2673 int count;
2675 switch (c)
2677 case '\0':
2678 case ' ':
2679 case '\t':
2680 case '=':
2681 goto done_word;
2683 case ':':
2684 #ifdef HAVE_DOS_PATHS
2685 /* A word CAN include a colon in its drive spec. The drive
2686 spec is allowed either at the beginning of a word, or as part
2687 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2688 if (!(p - beg >= 2
2689 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2690 && (p - beg == 2 || p[-3] == '(')))
2691 #endif
2692 goto done_word;
2694 case '$':
2695 c = *(p++);
2696 if (c == '$')
2697 break;
2699 /* This is a variable reference, so note that it's expandable.
2700 Then read it to the matching close paren. */
2701 wtype = w_variable;
2703 if (c == '(')
2704 closeparen = ')';
2705 else if (c == '{')
2706 closeparen = '}';
2707 else
2708 /* This is a single-letter variable reference. */
2709 break;
2711 for (count=0; *p != '\0'; ++p)
2713 if (*p == c)
2714 ++count;
2715 else if (*p == closeparen && --count < 0)
2717 ++p;
2718 break;
2721 break;
2723 case '?':
2724 case '+':
2725 if (*p == '=')
2726 goto done_word;
2727 break;
2729 case '\\':
2730 switch (*p)
2732 case ':':
2733 case ';':
2734 case '=':
2735 case '\\':
2736 ++p;
2737 break;
2739 break;
2741 default:
2742 if (delim && strchr (delim, c))
2743 goto done_word;
2744 break;
2747 c = *(p++);
2749 done_word:
2750 --p;
2752 done:
2753 if (startp)
2754 *startp = beg;
2755 if (length)
2756 *length = p - beg;
2757 return wtype;
2760 /* Construct the list of include directories
2761 from the arguments and the default list. */
2763 void
2764 construct_include_path (char **arg_dirs)
2766 register unsigned int i;
2767 #ifdef VAXC /* just don't ask ... */
2768 stat_t stbuf;
2769 #else
2770 struct stat stbuf;
2771 #endif
2772 /* Table to hold the dirs. */
2774 register unsigned int defsize = (sizeof (default_include_directories)
2775 / sizeof (default_include_directories[0]));
2776 register unsigned int max = 5;
2777 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2778 register unsigned int idx = 0;
2780 #ifdef __MSDOS__
2781 defsize++;
2782 #endif
2784 /* First consider any dirs specified with -I switches.
2785 Ignore dirs that don't exist. */
2787 if (arg_dirs != 0)
2788 while (*arg_dirs != 0)
2790 char *dir = *arg_dirs++;
2791 int e;
2793 if (dir[0] == '~')
2795 char *expanded = tilde_expand (dir);
2796 if (expanded != 0)
2797 dir = expanded;
2800 EINTRLOOP (e, stat (dir, &stbuf));
2801 if (e == 0 && S_ISDIR (stbuf.st_mode))
2803 if (idx == max - 1)
2805 max += 5;
2806 dirs = (char **)
2807 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2809 dirs[idx++] = dir;
2811 else if (dir != arg_dirs[-1])
2812 free (dir);
2815 /* Now add at the end the standard default dirs. */
2817 #ifdef __MSDOS__
2819 /* The environment variable $DJDIR holds the root of the
2820 DJGPP directory tree; add ${DJDIR}/include. */
2821 struct variable *djdir = lookup_variable ("DJDIR", 5);
2823 if (djdir)
2825 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2827 strcat (strcpy (defdir, djdir->value), "/include");
2828 dirs[idx++] = defdir;
2831 #endif
2833 for (i = 0; default_include_directories[i] != 0; ++i)
2835 int e;
2837 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2838 if (e == 0 && S_ISDIR (stbuf.st_mode))
2839 dirs[idx++] = default_include_directories[i];
2842 dirs[idx] = 0;
2844 /* Now compute the maximum length of any name in it. */
2846 max_incl_len = 0;
2847 for (i = 0; i < idx; ++i)
2849 unsigned int len = strlen (dirs[i]);
2850 /* If dir name is written with a trailing slash, discard it. */
2851 if (dirs[i][len - 1] == '/')
2852 /* We can't just clobber a null in because it may have come from
2853 a literal string and literal strings may not be writable. */
2854 dirs[i] = savestring (dirs[i], len - 1);
2855 if (len > max_incl_len)
2856 max_incl_len = len;
2859 include_directories = dirs;
2862 /* Expand ~ or ~USER at the beginning of NAME.
2863 Return a newly malloc'd string or 0. */
2865 char *
2866 tilde_expand (char *name)
2868 #ifndef VMS
2869 if (name[1] == '/' || name[1] == '\0')
2871 extern char *getenv ();
2872 char *home_dir;
2873 int is_variable;
2876 /* Turn off --warn-undefined-variables while we expand HOME. */
2877 int save = warn_undefined_variables_flag;
2878 warn_undefined_variables_flag = 0;
2880 home_dir = allocated_variable_expand ("$(HOME)");
2882 warn_undefined_variables_flag = save;
2885 is_variable = home_dir[0] != '\0';
2886 if (!is_variable)
2888 free (home_dir);
2889 home_dir = getenv ("HOME");
2891 #if !defined(_AMIGA) && !defined(WINDOWS32)
2892 if (home_dir == 0 || home_dir[0] == '\0')
2894 extern char *getlogin ();
2895 char *logname = getlogin ();
2896 home_dir = 0;
2897 if (logname != 0)
2899 struct passwd *p = getpwnam (logname);
2900 if (p != 0)
2901 home_dir = p->pw_dir;
2904 #endif /* !AMIGA && !WINDOWS32 */
2905 if (home_dir != 0)
2907 char *new = concat (home_dir, "", name + 1);
2908 if (is_variable)
2909 free (home_dir);
2910 return new;
2913 #if !defined(_AMIGA) && !defined(WINDOWS32)
2914 else
2916 struct passwd *pwent;
2917 char *userend = strchr (name + 1, '/');
2918 if (userend != 0)
2919 *userend = '\0';
2920 pwent = getpwnam (name + 1);
2921 if (pwent != 0)
2923 if (userend == 0)
2924 return xstrdup (pwent->pw_dir);
2925 else
2926 return concat (pwent->pw_dir, "/", userend + 1);
2928 else if (userend != 0)
2929 *userend = '/';
2931 #endif /* !AMIGA && !WINDOWS32 */
2932 #endif /* !VMS */
2933 return 0;
2936 /* Given a chain of struct nameseq's describing a sequence of filenames,
2937 in reverse of the intended order, return a new chain describing the
2938 result of globbing the filenames. The new chain is in forward order.
2939 The links of the old chain are freed or used in the new chain.
2940 Likewise for the names in the old chain.
2942 SIZE is how big to construct chain elements.
2943 This is useful if we want them actually to be other structures
2944 that have room for additional info. */
2946 struct nameseq *
2947 multi_glob (struct nameseq *chain, unsigned int size)
2949 extern void dir_setup_glob ();
2950 register struct nameseq *new = 0;
2951 register struct nameseq *old;
2952 struct nameseq *nexto;
2953 glob_t gl;
2955 dir_setup_glob (&gl);
2957 for (old = chain; old != 0; old = nexto)
2959 #ifndef NO_ARCHIVES
2960 char *memname;
2961 #endif
2963 nexto = old->next;
2965 if (old->name[0] == '~')
2967 char *newname = tilde_expand (old->name);
2968 if (newname != 0)
2970 free (old->name);
2971 old->name = newname;
2975 #ifndef NO_ARCHIVES
2976 if (ar_name (old->name))
2978 /* OLD->name is an archive member reference.
2979 Replace it with the archive file name,
2980 and save the member name in MEMNAME.
2981 We will glob on the archive name and then
2982 reattach MEMNAME later. */
2983 char *arname;
2984 ar_parse_name (old->name, &arname, &memname);
2985 free (old->name);
2986 old->name = arname;
2988 else
2989 memname = 0;
2990 #endif /* !NO_ARCHIVES */
2992 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
2994 case 0: /* Success. */
2996 register int i = gl.gl_pathc;
2997 while (i-- > 0)
2999 #ifndef NO_ARCHIVES
3000 if (memname != 0)
3002 /* Try to glob on MEMNAME within the archive. */
3003 struct nameseq *found
3004 = ar_glob (gl.gl_pathv[i], memname, size);
3005 if (found == 0)
3007 /* No matches. Use MEMNAME as-is. */
3008 unsigned int alen = strlen (gl.gl_pathv[i]);
3009 unsigned int mlen = strlen (memname);
3010 struct nameseq *elt
3011 = (struct nameseq *) xmalloc (size);
3012 if (size > sizeof (struct nameseq))
3013 bzero (((char *) elt) + sizeof (struct nameseq),
3014 size - sizeof (struct nameseq));
3015 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3016 bcopy (gl.gl_pathv[i], elt->name, alen);
3017 elt->name[alen] = '(';
3018 bcopy (memname, &elt->name[alen + 1], mlen);
3019 elt->name[alen + 1 + mlen] = ')';
3020 elt->name[alen + 1 + mlen + 1] = '\0';
3021 elt->next = new;
3022 new = elt;
3024 else
3026 /* Find the end of the FOUND chain. */
3027 struct nameseq *f = found;
3028 while (f->next != 0)
3029 f = f->next;
3031 /* Attach the chain being built to the end of the FOUND
3032 chain, and make FOUND the new NEW chain. */
3033 f->next = new;
3034 new = found;
3037 free (memname);
3039 else
3040 #endif /* !NO_ARCHIVES */
3042 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3043 if (size > sizeof (struct nameseq))
3044 bzero (((char *) elt) + sizeof (struct nameseq),
3045 size - sizeof (struct nameseq));
3046 elt->name = xstrdup (gl.gl_pathv[i]);
3047 elt->next = new;
3048 new = elt;
3051 globfree (&gl);
3052 free (old->name);
3053 free ((char *)old);
3054 break;
3057 case GLOB_NOSPACE:
3058 fatal (NILF, _("virtual memory exhausted"));
3059 break;
3061 default:
3062 old->next = new;
3063 new = old;
3064 break;
3068 return new;