Fix Savannah bug #19348: if the user specified
[make.git] / read.c
blobe50a76c9d3089a54c960f624ba75c7690b17c298
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 2, or (at your option) any later version.
11 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along with
16 GNU Make; see the file COPYING. If not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
19 #include "make.h"
21 #include <assert.h>
23 #include <glob.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
35 #ifndef WINDOWS32
36 #ifndef _AMIGA
37 #ifndef VMS
38 #include <pwd.h>
39 #else
40 struct passwd *getpwnam (char *name);
41 #endif
42 #endif
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46 eval'ing.
49 struct ebuffer
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 unsigned int size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 struct floc floc; /* Info on the file in fp (if any). */
59 /* Types of "words" that can be read in a makefile. */
60 enum make_word_type
62 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
63 w_varassign
67 /* A `struct conditionals' contains the information describing
68 all the active conditionals in a makefile.
70 The global variable `conditionals' contains the conditionals
71 information for the current makefile. It is initialized from
72 the static structure `toplevel_conditionals' and is later changed
73 to new structures for included makefiles. */
75 struct conditionals
77 unsigned int if_cmds; /* Depth of conditional nesting. */
78 unsigned int allocated; /* Elts allocated in following arrays. */
79 char *ignoring; /* Are we ignoring or interpreting?
80 0=interpreting, 1=not yet interpreted,
81 2=already interpreted */
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 const char *default_include_directories[] =
93 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
94 /* This completely up to the user when they install MSVC or other packages.
95 This is defined as a placeholder. */
96 # define INCLUDEDIR "."
97 #endif
98 INCLUDEDIR,
99 #ifndef _AMIGA
100 "/usr/gnu/include",
101 "/usr/local/include",
102 "/usr/include",
103 #endif
107 /* List of directories to search for include files in */
109 static const char **include_directories;
111 /* Maximum length of an element of the above. */
113 static unsigned int max_incl_len;
115 /* The filename and pointer to line number of the
116 makefile currently being read in. */
118 const struct floc *reading_file = 0;
120 /* The chain of makefiles read by read_makefile. */
122 static struct dep *read_makefiles = 0;
124 static int eval_makefile (const char *filename, int flags);
125 static int eval (struct ebuffer *buffer, int flags);
127 static long readline (struct ebuffer *ebuf);
128 static void do_define (char *name, unsigned int namelen,
129 enum variable_origin origin, struct ebuffer *ebuf);
130 static int conditional_line (char *line, int len, const struct floc *flocp);
131 static void record_files (struct nameseq *filenames, const char *pattern,
132 const char *pattern_percent, struct dep *deps,
133 unsigned int cmds_started, char *commands,
134 unsigned int commands_idx, int two_colon,
135 const struct floc *flocp);
136 static void record_target_var (struct nameseq *filenames, char *defn,
137 enum variable_origin origin, int enabled,
138 const struct floc *flocp);
139 static enum make_word_type get_next_mword (char *buffer, char *delim,
140 char **startp, unsigned int *length);
141 static void remove_comments (char *line);
142 static char *find_char_unquote (char *string, int stop1, int stop2,
143 int blank, int ignorevars);
145 /* Read in all the makefiles and return the chain of their names. */
147 struct dep *
148 read_all_makefiles (const 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 ((const char **)&p, &length)) != 0)
184 if (*p != '\0')
185 *p++ = '\0';
186 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
189 free (value);
192 /* Read makefiles specified with -f switches. */
194 if (makefiles != 0)
195 while (*makefiles != 0)
197 struct dep *tail = read_makefiles;
198 register struct dep *d;
200 if (! eval_makefile (*makefiles, 0))
201 perror_with_name ("", *makefiles);
203 /* Find the right element of read_makefiles. */
204 d = read_makefiles;
205 while (d->next != tail)
206 d = d->next;
208 /* Use the storage read_makefile allocates. */
209 *makefiles = dep_name (d);
210 ++num_makefiles;
211 ++makefiles;
214 /* If there were no -f switches, try the default names. */
216 if (num_makefiles == 0)
218 static char *default_makefiles[] =
219 #ifdef VMS
220 /* all lower case since readdir() (the vms version) 'lowercasifies' */
221 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
222 #else
223 #ifdef _AMIGA
224 { "GNUmakefile", "Makefile", "SMakefile", 0 };
225 #else /* !Amiga && !VMS */
226 { "GNUmakefile", "makefile", "Makefile", 0 };
227 #endif /* AMIGA */
228 #endif /* VMS */
229 register char **p = default_makefiles;
230 while (*p != 0 && !file_exists_p (*p))
231 ++p;
233 if (*p != 0)
235 if (! eval_makefile (*p, 0))
236 perror_with_name ("", *p);
238 else
240 /* No default makefile was found. Add the default makefiles to the
241 `read_makefiles' chain so they will be updated if possible. */
242 struct dep *tail = read_makefiles;
243 /* Add them to the tail, after any MAKEFILES variable makefiles. */
244 while (tail != 0 && tail->next != 0)
245 tail = tail->next;
246 for (p = default_makefiles; *p != 0; ++p)
248 struct dep *d = alloc_dep ();
249 d->file = enter_file (strcache_add (*p));
250 d->file->dontcare = 1;
251 /* Tell update_goal_chain to bail out as soon as this file is
252 made, and main not to die if we can't make this file. */
253 d->changed = RM_DONTCARE;
254 if (tail == 0)
255 read_makefiles = d;
256 else
257 tail->next = d;
258 tail = d;
260 if (tail != 0)
261 tail->next = 0;
265 return read_makefiles;
268 /* Install a new conditional and return the previous one. */
270 static struct conditionals *
271 install_conditionals (struct conditionals *new)
273 struct conditionals *save = conditionals;
275 memset (new, '\0', sizeof (*new));
276 conditionals = new;
278 return save;
281 /* Free the current conditionals and reinstate a saved one. */
283 static void
284 restore_conditionals (struct conditionals *saved)
286 /* Free any space allocated by conditional_line. */
287 if (conditionals->ignoring)
288 free (conditionals->ignoring);
289 if (conditionals->seen_else)
290 free (conditionals->seen_else);
292 /* Restore state. */
293 conditionals = saved;
296 static int
297 eval_makefile (const char *filename, int flags)
299 struct dep *deps;
300 struct ebuffer ebuf;
301 const struct floc *curfile;
302 char *expanded = 0;
303 int makefile_errno;
304 int r;
306 filename = strcache_add (filename);
307 ebuf.floc.filenm = filename;
308 ebuf.floc.lineno = 1;
310 if (ISDB (DB_VERBOSE))
312 printf (_("Reading makefile `%s'"), filename);
313 if (flags & RM_NO_DEFAULT_GOAL)
314 printf (_(" (no default goal)"));
315 if (flags & RM_INCLUDED)
316 printf (_(" (search path)"));
317 if (flags & RM_DONTCARE)
318 printf (_(" (don't care)"));
319 if (flags & RM_NO_TILDE)
320 printf (_(" (no ~ expansion)"));
321 puts ("...");
324 /* First, get a stream to read. */
326 /* Expand ~ in FILENAME unless it came from `include',
327 in which case it was already done. */
328 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
330 expanded = tilde_expand (filename);
331 if (expanded != 0)
332 filename = expanded;
335 ebuf.fp = fopen (filename, "r");
336 /* Save the error code so we print the right message later. */
337 makefile_errno = errno;
339 /* If the makefile wasn't found and it's either a makefile from
340 the `MAKEFILES' variable or an included makefile,
341 search the included makefile search path for this makefile. */
342 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
344 unsigned int i;
345 for (i = 0; include_directories[i] != 0; ++i)
347 const char *included = concat (include_directories[i], "/", filename);
348 ebuf.fp = fopen (included, "r");
349 if (ebuf.fp)
351 filename = strcache_add (included);
352 break;
357 /* Add FILENAME to the chain of read makefiles. */
358 deps = alloc_dep ();
359 deps->next = read_makefiles;
360 read_makefiles = deps;
361 deps->file = lookup_file (filename);
362 if (deps->file == 0)
363 deps->file = enter_file (filename);
364 filename = deps->file->name;
365 deps->changed = flags;
366 if (flags & RM_DONTCARE)
367 deps->file->dontcare = 1;
369 if (expanded)
370 free (expanded);
372 /* If the makefile can't be found at all, give up entirely. */
374 if (ebuf.fp == 0)
376 /* If we did some searching, errno has the error from the last
377 attempt, rather from FILENAME itself. Restore it in case the
378 caller wants to use it in a message. */
379 errno = makefile_errno;
380 return 0;
383 /* Add this makefile to the list. */
384 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
385 f_append, 0);
387 /* Evaluate the makefile */
389 ebuf.size = 200;
390 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
392 curfile = reading_file;
393 reading_file = &ebuf.floc;
395 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
397 reading_file = curfile;
399 fclose (ebuf.fp);
401 free (ebuf.bufstart);
402 alloca (0);
403 return r;
407 eval_buffer (char *buffer)
409 struct ebuffer ebuf;
410 struct conditionals *saved;
411 struct conditionals new;
412 const struct floc *curfile;
413 int r;
415 /* Evaluate the buffer */
417 ebuf.size = strlen (buffer);
418 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
419 ebuf.fp = NULL;
421 ebuf.floc = *reading_file;
423 curfile = reading_file;
424 reading_file = &ebuf.floc;
426 saved = install_conditionals (&new);
428 r = eval (&ebuf, 1);
430 restore_conditionals (saved);
432 reading_file = curfile;
434 alloca (0);
435 return r;
439 /* Read file FILENAME as a makefile and add its contents to the data base.
441 SET_DEFAULT is true if we are allowed to set the default goal. */
444 static int
445 eval (struct ebuffer *ebuf, int set_default)
447 char *collapsed = 0;
448 unsigned int collapsed_length = 0;
449 unsigned int commands_len = 200;
450 char *commands;
451 unsigned int commands_idx = 0;
452 unsigned int cmds_started, tgts_started;
453 int ignoring = 0, in_ignored_define = 0;
454 int no_targets = 0; /* Set when reading a rule without targets. */
455 struct nameseq *filenames = 0;
456 struct dep *deps = 0;
457 long nlines = 0;
458 int two_colon = 0;
459 const char *pattern = 0;
460 const char *pattern_percent;
461 struct floc *fstart;
462 struct floc fi;
464 #define record_waiting_files() \
465 do \
467 if (filenames != 0) \
469 fi.lineno = tgts_started; \
470 record_files (filenames, pattern, pattern_percent, deps, \
471 cmds_started, commands, commands_idx, two_colon, \
472 &fi); \
474 filenames = 0; \
475 commands_idx = 0; \
476 no_targets = 0; \
477 pattern = 0; \
478 } while (0)
480 pattern_percent = 0;
481 cmds_started = tgts_started = 1;
483 fstart = &ebuf->floc;
484 fi.filenm = ebuf->floc.filenm;
486 /* Loop over lines in the file.
487 The strategy is to accumulate target names in FILENAMES, dependencies
488 in DEPS and commands in COMMANDS. These are used to define a rule
489 when the start of the next rule (or eof) is encountered.
491 When you see a "continue" in the loop below, that means we are moving on
492 to the next line _without_ ending any rule that we happen to be working
493 with at the moment. If you see a "goto rule_complete", then the
494 statement we just parsed also finishes the previous rule. */
496 commands = xmalloc (200);
498 while (1)
500 unsigned int linelen;
501 char *line;
502 unsigned int wlen;
503 char *p;
504 char *p2;
506 /* Grab the next line to be evaluated */
507 ebuf->floc.lineno += nlines;
508 nlines = readline (ebuf);
510 /* If there is nothing left to eval, we're done. */
511 if (nlines < 0)
512 break;
514 /* If this line is empty, skip it. */
515 line = ebuf->buffer;
516 if (line[0] == '\0')
517 continue;
519 linelen = strlen (line);
521 /* Check for a shell command line first.
522 If it is not one, we can stop treating tab specially. */
523 if (line[0] == cmd_prefix)
525 if (no_targets)
526 /* Ignore the commands in a rule with no targets. */
527 continue;
529 /* If there is no preceding rule line, don't treat this line
530 as a command, even though it begins with a tab character.
531 SunOS 4 make appears to behave this way. */
533 if (filenames != 0)
535 if (ignoring)
536 /* Yep, this is a shell command, and we don't care. */
537 continue;
539 /* Append this command line to the line being accumulated. */
540 if (commands_idx == 0)
541 cmds_started = ebuf->floc.lineno;
543 if (linelen + 1 + commands_idx > commands_len)
545 commands_len = (linelen + 1 + commands_idx) * 2;
546 commands = xrealloc (commands, commands_len);
548 memcpy (&commands[commands_idx], line, linelen);
549 commands_idx += linelen;
550 commands[commands_idx++] = '\n';
552 continue;
556 /* This line is not a shell command line. Don't worry about tabs.
557 Get more space if we need it; we don't need to preserve the current
558 contents of the buffer. */
560 if (collapsed_length < linelen+1)
562 collapsed_length = linelen+1;
563 if (collapsed)
564 free (collapsed);
565 collapsed = xmalloc (collapsed_length);
567 strcpy (collapsed, line);
568 /* Collapse continuation lines. */
569 collapse_continuations (collapsed);
570 remove_comments (collapsed);
572 /* Compare a word, both length and contents. */
573 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
574 p = collapsed;
575 while (isspace ((unsigned char)*p))
576 ++p;
578 if (*p == '\0')
579 /* This line is completely empty--ignore it. */
580 continue;
582 /* Find the end of the first token. Note we don't need to worry about
583 * ":" here since we compare tokens by length (so "export" will never
584 * be equal to "export:").
586 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
588 wlen = p2 - p;
590 /* Find the start of the second token. If it looks like a target or
591 variable definition it can't be a preprocessor token so skip
592 them--this allows variables/targets named `ifdef', `export', etc. */
593 while (isspace ((unsigned char)*p2))
594 ++p2;
596 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
598 /* It can't be a preprocessor token so skip it if we're ignoring */
599 if (ignoring)
600 continue;
602 goto skip_conditionals;
605 /* We must first check for conditional and `define' directives before
606 ignoring anything, since they control what we will do with
607 following lines. */
609 if (!in_ignored_define)
611 int i = conditional_line (p, wlen, fstart);
612 if (i != -2)
614 if (i == -1)
615 fatal (fstart, _("invalid syntax in conditional"));
617 ignoring = i;
618 continue;
622 if (word1eq ("endef"))
624 if (!in_ignored_define)
625 fatal (fstart, _("extraneous `endef'"));
626 in_ignored_define = 0;
627 continue;
630 if (word1eq ("define"))
632 if (ignoring)
633 in_ignored_define = 1;
634 else
636 if (*p2 == '\0')
637 fatal (fstart, _("empty variable name"));
639 /* Let the variable name be the whole rest of the line,
640 with trailing blanks stripped (comments have already been
641 removed), so it could be a complex variable/function
642 reference that might contain blanks. */
643 p = strchr (p2, '\0');
644 while (isblank ((unsigned char)p[-1]))
645 --p;
646 do_define (p2, p - p2, o_file, ebuf);
648 continue;
651 if (word1eq ("override"))
653 if (*p2 == '\0')
654 error (fstart, _("empty `override' directive"));
656 if (strneq (p2, "define", 6)
657 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
659 if (ignoring)
660 in_ignored_define = 1;
661 else
663 p2 = next_token (p2 + 6);
664 if (*p2 == '\0')
665 fatal (fstart, _("empty variable name"));
667 /* Let the variable name be the whole rest of the line,
668 with trailing blanks stripped (comments have already been
669 removed), so it could be a complex variable/function
670 reference that might contain blanks. */
671 p = strchr (p2, '\0');
672 while (isblank ((unsigned char)p[-1]))
673 --p;
674 do_define (p2, p - p2, o_override, ebuf);
677 else if (!ignoring
678 && !try_variable_definition (fstart, p2, o_override, 0))
679 error (fstart, _("invalid `override' directive"));
681 continue;
684 if (ignoring)
685 /* Ignore the line. We continue here so conditionals
686 can appear in the middle of a rule. */
687 continue;
689 if (word1eq ("export"))
691 /* 'export' by itself causes everything to be exported. */
692 if (*p2 == '\0')
693 export_all_variables = 1;
694 else
696 struct variable *v;
698 v = try_variable_definition (fstart, p2, o_file, 0);
699 if (v != 0)
700 v->export = v_export;
701 else
703 unsigned int l;
704 const char *cp;
705 char *ap;
707 /* Expand the line so we can use indirect and constructed
708 variable names in an export command. */
709 cp = ap = allocated_variable_expand (p2);
711 for (p = find_next_token (&cp, &l); p != 0;
712 p = find_next_token (&cp, &l))
714 v = lookup_variable (p, l);
715 if (v == 0)
716 v = define_variable_loc (p, l, "", o_file, 0, fstart);
717 v->export = v_export;
720 free (ap);
723 goto rule_complete;
726 if (word1eq ("unexport"))
728 if (*p2 == '\0')
729 export_all_variables = 0;
730 else
732 unsigned int l;
733 struct variable *v;
734 const char *cp;
735 char *ap;
737 /* Expand the line so we can use indirect and constructed
738 variable names in an unexport command. */
739 cp = ap = allocated_variable_expand (p2);
741 for (p = find_next_token (&cp, &l); p != 0;
742 p = find_next_token (&cp, &l))
744 v = lookup_variable (p, l);
745 if (v == 0)
746 v = define_variable_loc (p, l, "", o_file, 0, fstart);
748 v->export = v_noexport;
751 free (ap);
753 goto rule_complete;
756 skip_conditionals:
757 if (word1eq ("vpath"))
759 const char *cp;
760 char *vpat;
761 unsigned int l;
762 cp = variable_expand (p2);
763 p = find_next_token (&cp, &l);
764 if (p != 0)
766 vpat = savestring (p, l);
767 p = find_next_token (&cp, &l);
768 /* No searchpath means remove all previous
769 selective VPATH's with the same pattern. */
771 else
772 /* No pattern means remove all previous selective VPATH's. */
773 vpat = 0;
774 construct_vpath_list (vpat, p);
775 if (vpat != 0)
776 free (vpat);
778 goto rule_complete;
781 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
783 /* We have found an `include' line specifying a nested
784 makefile to be read at this point. */
785 struct conditionals *save;
786 struct conditionals new_conditionals;
787 struct nameseq *files;
788 /* "-include" (vs "include") says no error if the file does not
789 exist. "sinclude" is an alias for this from SGI. */
790 int noerror = (p[0] != 'i');
792 p = allocated_variable_expand (p2);
794 /* If no filenames, it's a no-op. */
795 if (*p == '\0')
797 free (p);
798 continue;
801 /* Parse the list of file names. */
802 p2 = p;
803 files = multi_glob (parse_file_seq (&p2, '\0',
804 sizeof (struct nameseq),
806 sizeof (struct nameseq));
807 free (p);
809 /* Save the state of conditionals and start
810 the included makefile with a clean slate. */
811 save = install_conditionals (&new_conditionals);
813 /* Record the rules that are waiting so they will determine
814 the default goal before those in the included makefile. */
815 record_waiting_files ();
817 /* Read each included makefile. */
818 while (files != 0)
820 struct nameseq *next = files->next;
821 const char *name = files->name;
822 int r;
824 free (files);
825 files = next;
827 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
828 | (noerror ? RM_DONTCARE : 0)));
829 if (!r && !noerror)
830 error (fstart, "%s: %s", name, strerror (errno));
833 /* Restore conditional state. */
834 restore_conditionals (save);
836 goto rule_complete;
839 if (try_variable_definition (fstart, p, o_file, 0))
840 /* This line has been dealt with. */
841 goto rule_complete;
843 /* This line starts with a tab but was not caught above because there
844 was no preceding target, and the line might have been usable as a
845 variable definition. But now we know it is definitely lossage. */
846 if (line[0] == cmd_prefix)
847 fatal(fstart, _("commands commence before first target"));
849 /* This line describes some target files. This is complicated by
850 the existence of target-specific variables, because we can't
851 expand the entire line until we know if we have one or not. So
852 we expand the line word by word until we find the first `:',
853 then check to see if it's a target-specific variable.
855 In this algorithm, `lb_next' will point to the beginning of the
856 unexpanded parts of the input buffer, while `p2' points to the
857 parts of the expanded buffer we haven't searched yet. */
860 enum make_word_type wtype;
861 enum variable_origin v_origin;
862 int exported;
863 char *cmdleft, *semip, *lb_next;
864 unsigned int plen = 0;
865 char *colonp;
866 const char *end, *beg; /* Helpers for whitespace stripping. */
868 /* Record the previous rule. */
870 record_waiting_files ();
871 tgts_started = fstart->lineno;
873 /* Search the line for an unquoted ; that is not after an
874 unquoted #. */
875 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
876 if (cmdleft != 0 && *cmdleft == '#')
878 /* We found a comment before a semicolon. */
879 *cmdleft = '\0';
880 cmdleft = 0;
882 else if (cmdleft != 0)
883 /* Found one. Cut the line short there before expanding it. */
884 *(cmdleft++) = '\0';
885 semip = cmdleft;
887 collapse_continuations (line);
889 /* We can't expand the entire line, since if it's a per-target
890 variable we don't want to expand it. So, walk from the
891 beginning, expanding as we go, and looking for "interesting"
892 chars. The first word is always expandable. */
893 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
894 switch (wtype)
896 case w_eol:
897 if (cmdleft != 0)
898 fatal(fstart, _("missing rule before commands"));
899 /* This line contained something but turned out to be nothing
900 but whitespace (a comment?). */
901 continue;
903 case w_colon:
904 case w_dcolon:
905 /* We accept and ignore rules without targets for
906 compatibility with SunOS 4 make. */
907 no_targets = 1;
908 continue;
910 default:
911 break;
914 p2 = variable_expand_string(NULL, lb_next, wlen);
916 while (1)
918 lb_next += wlen;
919 if (cmdleft == 0)
921 /* Look for a semicolon in the expanded line. */
922 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
924 if (cmdleft != 0)
926 unsigned long p2_off = p2 - variable_buffer;
927 unsigned long cmd_off = cmdleft - variable_buffer;
928 char *pend = p2 + strlen(p2);
930 /* Append any remnants of lb, then cut the line short
931 at the semicolon. */
932 *cmdleft = '\0';
934 /* One school of thought says that you shouldn't expand
935 here, but merely copy, since now you're beyond a ";"
936 and into a command script. However, the old parser
937 expanded the whole line, so we continue that for
938 backwards-compatiblity. Also, it wouldn't be
939 entirely consistent, since we do an unconditional
940 expand below once we know we don't have a
941 target-specific variable. */
942 (void)variable_expand_string(pend, lb_next, (long)-1);
943 lb_next += strlen(lb_next);
944 p2 = variable_buffer + p2_off;
945 cmdleft = variable_buffer + cmd_off + 1;
949 colonp = find_char_unquote(p2, ':', 0, 0, 0);
950 #ifdef HAVE_DOS_PATHS
951 /* The drive spec brain-damage strikes again... */
952 /* Note that the only separators of targets in this context
953 are whitespace and a left paren. If others are possible,
954 they should be added to the string in the call to index. */
955 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
956 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
957 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
958 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
959 #endif
960 if (colonp != 0)
961 break;
963 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
964 if (wtype == w_eol)
965 break;
967 p2 += strlen(p2);
968 *(p2++) = ' ';
969 p2 = variable_expand_string(p2, lb_next, wlen);
970 /* We don't need to worry about cmdleft here, because if it was
971 found in the variable_buffer the entire buffer has already
972 been expanded... we'll never get here. */
975 p2 = next_token (variable_buffer);
977 /* If the word we're looking at is EOL, see if there's _anything_
978 on the line. If not, a variable expanded to nothing, so ignore
979 it. If so, we can't parse this line so punt. */
980 if (wtype == w_eol)
982 if (*p2 != '\0')
983 /* There's no need to be ivory-tower about this: check for
984 one of the most common bugs found in makefiles... */
985 fatal (fstart, _("missing separator%s"),
986 !strneq(line, " ", 8) ? ""
987 : _(" (did you mean TAB instead of 8 spaces?)"));
988 continue;
991 /* Make the colon the end-of-string so we know where to stop
992 looking for targets. */
993 *colonp = '\0';
994 filenames = multi_glob (parse_file_seq (&p2, '\0',
995 sizeof (struct nameseq),
997 sizeof (struct nameseq));
998 *p2 = ':';
1000 if (!filenames)
1002 /* We accept and ignore rules without targets for
1003 compatibility with SunOS 4 make. */
1004 no_targets = 1;
1005 continue;
1007 /* This should never be possible; we handled it above. */
1008 assert (*p2 != '\0');
1009 ++p2;
1011 /* Is this a one-colon or two-colon entry? */
1012 two_colon = *p2 == ':';
1013 if (two_colon)
1014 p2++;
1016 /* Test to see if it's a target-specific variable. Copy the rest
1017 of the buffer over, possibly temporarily (we'll expand it later
1018 if it's not a target-specific variable). PLEN saves the length
1019 of the unparsed section of p2, for later. */
1020 if (*lb_next != '\0')
1022 unsigned int l = p2 - variable_buffer;
1023 plen = strlen (p2);
1024 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1025 p2 = variable_buffer + l;
1028 /* See if it's an "override" or "export" keyword; if so see if what
1029 comes after it looks like a variable definition. */
1031 wtype = get_next_mword (p2, NULL, &p, &wlen);
1033 v_origin = o_file;
1034 exported = 0;
1035 if (wtype == w_static)
1037 if (word1eq ("override"))
1039 v_origin = o_override;
1040 wtype = get_next_mword (p+wlen, NULL, &p, &wlen);
1042 else if (word1eq ("export"))
1044 exported = 1;
1045 wtype = get_next_mword (p+wlen, NULL, &p, &wlen);
1049 if (wtype != w_eol)
1050 wtype = get_next_mword (p+wlen, NULL, NULL, NULL);
1052 if (wtype == w_varassign)
1054 /* If there was a semicolon found, add it back, plus anything
1055 after it. */
1056 if (semip)
1058 unsigned int l = p - variable_buffer;
1059 *(--semip) = ';';
1060 variable_buffer_output (p2 + strlen (p2),
1061 semip, strlen (semip)+1);
1062 p = variable_buffer + l;
1064 record_target_var (filenames, p, v_origin, exported, fstart);
1065 filenames = 0;
1066 continue;
1069 /* This is a normal target, _not_ a target-specific variable.
1070 Unquote any = in the dependency list. */
1071 find_char_unquote (lb_next, '=', 0, 0, 0);
1073 /* We have some targets, so don't ignore the following commands. */
1074 no_targets = 0;
1076 /* Expand the dependencies, etc. */
1077 if (*lb_next != '\0')
1079 unsigned int l = p2 - variable_buffer;
1080 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1081 p2 = variable_buffer + l;
1083 /* Look for a semicolon in the expanded line. */
1084 if (cmdleft == 0)
1086 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1087 if (cmdleft != 0)
1088 *(cmdleft++) = '\0';
1092 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1093 p = strchr (p2, ':');
1094 while (p != 0 && p[-1] == '\\')
1096 register char *q = &p[-1];
1097 register int backslash = 0;
1098 while (*q-- == '\\')
1099 backslash = !backslash;
1100 if (backslash)
1101 p = strchr (p + 1, ':');
1102 else
1103 break;
1105 #ifdef _AMIGA
1106 /* Here, the situation is quite complicated. Let's have a look
1107 at a couple of targets:
1109 install: dev:make
1111 dev:make: make
1113 dev:make:: xyz
1115 The rule is that it's only a target, if there are TWO :'s
1116 OR a space around the :.
1118 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1119 || isspace ((unsigned char)p[-1])))
1120 p = 0;
1121 #endif
1122 #ifdef HAVE_DOS_PATHS
1124 int check_again;
1125 do {
1126 check_again = 0;
1127 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1128 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1129 isalpha ((unsigned char)p[-1]) &&
1130 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1131 p = strchr (p + 1, ':');
1132 check_again = 1;
1134 } while (check_again);
1136 #endif
1137 if (p != 0)
1139 struct nameseq *target;
1140 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1141 ++p2;
1142 if (target == 0)
1143 fatal (fstart, _("missing target pattern"));
1144 else if (target->next != 0)
1145 fatal (fstart, _("multiple target patterns"));
1146 pattern_percent = find_percent_cached (&target->name);
1147 pattern = target->name;
1148 if (pattern_percent == 0)
1149 fatal (fstart, _("target pattern contains no `%%'"));
1150 free (target);
1152 else
1153 pattern = 0;
1155 /* Strip leading and trailing whitespaces. */
1156 beg = p2;
1157 end = beg + strlen (beg) - 1;
1158 strip_whitespace (&beg, &end);
1160 if (beg <= end && *beg != '\0')
1162 /* Put all the prerequisites here; they'll be parsed later. */
1163 deps = alloc_dep ();
1164 deps->name = strcache_add_len (beg, end - beg + 1);
1166 else
1167 deps = 0;
1169 commands_idx = 0;
1170 if (cmdleft != 0)
1172 /* Semicolon means rest of line is a command. */
1173 unsigned int l = strlen (cmdleft);
1175 cmds_started = fstart->lineno;
1177 /* Add this command line to the buffer. */
1178 if (l + 2 > commands_len)
1180 commands_len = (l + 2) * 2;
1181 commands = xrealloc (commands, commands_len);
1183 memcpy (commands, cmdleft, l);
1184 commands_idx += l;
1185 commands[commands_idx++] = '\n';
1188 /* Determine if this target should be made default. We used to do
1189 this in record_files() but because of the delayed target recording
1190 and because preprocessor directives are legal in target's commands
1191 it is too late. Consider this fragment for example:
1193 foo:
1195 ifeq ($(.DEFAULT_GOAL),foo)
1197 endif
1199 Because the target is not recorded until after ifeq directive is
1200 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1201 would expect. Because of this we have to move some of the logic
1202 here. */
1204 if (**default_goal_name == '\0' && set_default)
1206 const char *name;
1207 struct dep *d;
1208 struct nameseq *t = filenames;
1210 for (; t != 0; t = t->next)
1212 int reject = 0;
1213 name = t->name;
1215 /* We have nothing to do if this is an implicit rule. */
1216 if (strchr (name, '%') != 0)
1217 break;
1219 /* See if this target's name does not start with a `.',
1220 unless it contains a slash. */
1221 if (*name == '.' && strchr (name, '/') == 0
1222 #ifdef HAVE_DOS_PATHS
1223 && strchr (name, '\\') == 0
1224 #endif
1226 continue;
1229 /* If this file is a suffix, don't let it be
1230 the default goal file. */
1231 for (d = suffix_file->deps; d != 0; d = d->next)
1233 register struct dep *d2;
1234 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1236 reject = 1;
1237 break;
1239 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1241 unsigned int l = strlen (dep_name (d2));
1242 if (!strneq (name, dep_name (d2), l))
1243 continue;
1244 if (streq (name + l, dep_name (d)))
1246 reject = 1;
1247 break;
1251 if (reject)
1252 break;
1255 if (!reject)
1257 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1258 o_file, 0, NILF);
1259 break;
1264 continue;
1267 /* We get here except in the case that we just read a rule line.
1268 Record now the last rule we read, so following spurious
1269 commands are properly diagnosed. */
1270 rule_complete:
1271 record_waiting_files ();
1274 #undef word1eq
1276 if (conditionals->if_cmds)
1277 fatal (fstart, _("missing `endif'"));
1279 /* At eof, record the last rule. */
1280 record_waiting_files ();
1282 if (collapsed)
1283 free (collapsed);
1284 free (commands);
1286 return 1;
1290 /* Remove comments from LINE.
1291 This is done by copying the text at LINE onto itself. */
1293 static void
1294 remove_comments (char *line)
1296 char *comment;
1298 comment = find_char_unquote (line, '#', 0, 0, 0);
1300 if (comment != 0)
1301 /* Cut off the line at the #. */
1302 *comment = '\0';
1305 /* Execute a `define' directive.
1306 The first line has already been read, and NAME is the name of
1307 the variable to be defined. The following lines remain to be read. */
1309 static void
1310 do_define (char *name, unsigned int namelen,
1311 enum variable_origin origin, struct ebuffer *ebuf)
1313 struct floc defstart;
1314 long nlines = 0;
1315 int nlevels = 1;
1316 unsigned int length = 100;
1317 char *definition = xmalloc (length);
1318 unsigned int idx = 0;
1319 char *p;
1321 /* Expand the variable name. */
1322 char *var = alloca (namelen + 1);
1323 memcpy (var, name, namelen);
1324 var[namelen] = '\0';
1325 var = variable_expand (var);
1327 defstart = ebuf->floc;
1329 while (1)
1331 unsigned int len;
1332 char *line;
1334 nlines = readline (ebuf);
1335 ebuf->floc.lineno += nlines;
1337 /* If there is nothing left to eval, we're done. */
1338 if (nlines < 0)
1339 break;
1341 line = ebuf->buffer;
1343 collapse_continuations (line);
1345 /* If the line doesn't begin with a tab, test to see if it introduces
1346 another define, or ends one. */
1348 /* Stop if we find an 'endef' */
1349 if (line[0] != cmd_prefix)
1351 p = next_token (line);
1352 len = strlen (p);
1354 /* If this is another 'define', increment the level count. */
1355 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1356 && strneq (p, "define", 6))
1357 ++nlevels;
1359 /* If this is an 'endef', decrement the count. If it's now 0,
1360 we've found the last one. */
1361 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1362 && strneq (p, "endef", 5))
1364 p += 5;
1365 remove_comments (p);
1366 if (*next_token (p) != '\0')
1367 error (&ebuf->floc,
1368 _("Extraneous text after `endef' directive"));
1370 if (--nlevels == 0)
1372 /* Define the variable. */
1373 if (idx == 0)
1374 definition[0] = '\0';
1375 else
1376 definition[idx - 1] = '\0';
1378 /* Always define these variables in the global set. */
1379 define_variable_global (var, strlen (var), definition,
1380 origin, 1, &defstart);
1381 free (definition);
1382 return;
1387 /* Otherwise add this line to the variable definition. */
1388 len = strlen (line);
1389 if (idx + len + 1 > length)
1391 length = (idx + len) * 2;
1392 definition = xrealloc (definition, length + 1);
1395 memcpy (&definition[idx], line, len);
1396 idx += len;
1397 /* Separate lines with a newline. */
1398 definition[idx++] = '\n';
1401 /* No `endef'!! */
1402 fatal (&defstart, _("missing `endef', unterminated `define'"));
1404 /* NOTREACHED */
1405 return;
1408 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1409 "ifneq", "else" and "endif".
1410 LINE is the input line, with the command as its first word.
1412 FILENAME and LINENO are the filename and line number in the
1413 current makefile. They are used for error messages.
1415 Value is -2 if the line is not a conditional at all,
1416 -1 if the line is an invalid conditional,
1417 0 if following text should be interpreted,
1418 1 if following text should be ignored. */
1420 static int
1421 conditional_line (char *line, int len, const struct floc *flocp)
1423 char *cmdname;
1424 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1425 unsigned int i;
1426 unsigned int o;
1428 /* Compare a word, both length and contents. */
1429 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1430 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1432 /* Make sure this line is a conditional. */
1433 chkword ("ifdef", c_ifdef)
1434 else chkword ("ifndef", c_ifndef)
1435 else chkword ("ifeq", c_ifeq)
1436 else chkword ("ifneq", c_ifneq)
1437 else chkword ("else", c_else)
1438 else chkword ("endif", c_endif)
1439 else
1440 return -2;
1442 /* Found one: skip past it and any whitespace after it. */
1443 line = next_token (line + len);
1445 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1447 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1448 if (cmdtype == c_endif)
1450 if (*line != '\0')
1451 EXTRANEOUS ();
1453 if (!conditionals->if_cmds)
1454 fatal (flocp, _("extraneous `%s'"), cmdname);
1456 --conditionals->if_cmds;
1458 goto DONE;
1461 /* An 'else' statement can either be simple, or it can have another
1462 conditional after it. */
1463 if (cmdtype == c_else)
1465 const char *p;
1467 if (!conditionals->if_cmds)
1468 fatal (flocp, _("extraneous `%s'"), cmdname);
1470 o = conditionals->if_cmds - 1;
1472 if (conditionals->seen_else[o])
1473 fatal (flocp, _("only one `else' per conditional"));
1475 /* Change the state of ignorance. */
1476 switch (conditionals->ignoring[o])
1478 case 0:
1479 /* We've just been interpreting. Never do it again. */
1480 conditionals->ignoring[o] = 2;
1481 break;
1482 case 1:
1483 /* We've never interpreted yet. Maybe this time! */
1484 conditionals->ignoring[o] = 0;
1485 break;
1488 /* It's a simple 'else'. */
1489 if (*line == '\0')
1491 conditionals->seen_else[o] = 1;
1492 goto DONE;
1495 /* The 'else' has extra text. That text must be another conditional
1496 and cannot be an 'else' or 'endif'. */
1498 /* Find the length of the next word. */
1499 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1501 len = p - line;
1503 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1504 if (word1eq("else") || word1eq("endif")
1505 || conditional_line (line, len, flocp) < 0)
1506 EXTRANEOUS ();
1507 else
1509 /* conditional_line() created a new level of conditional.
1510 Raise it back to this level. */
1511 if (conditionals->ignoring[o] < 2)
1512 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1513 --conditionals->if_cmds;
1516 goto DONE;
1519 if (conditionals->allocated == 0)
1521 conditionals->allocated = 5;
1522 conditionals->ignoring = xmalloc (conditionals->allocated);
1523 conditionals->seen_else = xmalloc (conditionals->allocated);
1526 o = conditionals->if_cmds++;
1527 if (conditionals->if_cmds > conditionals->allocated)
1529 conditionals->allocated += 5;
1530 conditionals->ignoring = xrealloc (conditionals->ignoring,
1531 conditionals->allocated);
1532 conditionals->seen_else = xrealloc (conditionals->seen_else,
1533 conditionals->allocated);
1536 /* Record that we have seen an `if...' but no `else' so far. */
1537 conditionals->seen_else[o] = 0;
1539 /* Search through the stack to see if we're already ignoring. */
1540 for (i = 0; i < o; ++i)
1541 if (conditionals->ignoring[i])
1543 /* We are already ignoring, so just push a level to match the next
1544 "else" or "endif", and keep ignoring. We don't want to expand
1545 variables in the condition. */
1546 conditionals->ignoring[o] = 1;
1547 return 1;
1550 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1552 char *var;
1553 struct variable *v;
1554 char *p;
1556 /* Expand the thing we're looking up, so we can use indirect and
1557 constructed variable names. */
1558 var = allocated_variable_expand (line);
1560 /* Make sure there's only one variable name to test. */
1561 p = end_of_token (var);
1562 i = p - var;
1563 p = next_token (p);
1564 if (*p != '\0')
1565 return -1;
1567 var[i] = '\0';
1568 v = lookup_variable (var, i);
1570 conditionals->ignoring[o] =
1571 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1573 free (var);
1575 else
1577 /* "ifeq" or "ifneq". */
1578 char *s1, *s2;
1579 unsigned int l;
1580 char termin = *line == '(' ? ',' : *line;
1582 if (termin != ',' && termin != '"' && termin != '\'')
1583 return -1;
1585 s1 = ++line;
1586 /* Find the end of the first string. */
1587 if (termin == ',')
1589 int count = 0;
1590 for (; *line != '\0'; ++line)
1591 if (*line == '(')
1592 ++count;
1593 else if (*line == ')')
1594 --count;
1595 else if (*line == ',' && count <= 0)
1596 break;
1598 else
1599 while (*line != '\0' && *line != termin)
1600 ++line;
1602 if (*line == '\0')
1603 return -1;
1605 if (termin == ',')
1607 /* Strip blanks after the first string. */
1608 char *p = line++;
1609 while (isblank ((unsigned char)p[-1]))
1610 --p;
1611 *p = '\0';
1613 else
1614 *line++ = '\0';
1616 s2 = variable_expand (s1);
1617 /* We must allocate a new copy of the expanded string because
1618 variable_expand re-uses the same buffer. */
1619 l = strlen (s2);
1620 s1 = alloca (l + 1);
1621 memcpy (s1, s2, l + 1);
1623 if (termin != ',')
1624 /* Find the start of the second string. */
1625 line = next_token (line);
1627 termin = termin == ',' ? ')' : *line;
1628 if (termin != ')' && termin != '"' && termin != '\'')
1629 return -1;
1631 /* Find the end of the second string. */
1632 if (termin == ')')
1634 int count = 0;
1635 s2 = next_token (line);
1636 for (line = s2; *line != '\0'; ++line)
1638 if (*line == '(')
1639 ++count;
1640 else if (*line == ')')
1642 if (count <= 0)
1643 break;
1644 else
1645 --count;
1649 else
1651 ++line;
1652 s2 = line;
1653 while (*line != '\0' && *line != termin)
1654 ++line;
1657 if (*line == '\0')
1658 return -1;
1660 *line = '\0';
1661 line = next_token (++line);
1662 if (*line != '\0')
1663 EXTRANEOUS ();
1665 s2 = variable_expand (s2);
1666 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1669 DONE:
1670 /* Search through the stack to see if we're ignoring. */
1671 for (i = 0; i < conditionals->if_cmds; ++i)
1672 if (conditionals->ignoring[i])
1673 return 1;
1674 return 0;
1677 /* Remove duplicate dependencies in CHAIN. */
1679 static unsigned long
1680 dep_hash_1 (const void *key)
1682 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1685 static unsigned long
1686 dep_hash_2 (const void *key)
1688 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1691 static int
1692 dep_hash_cmp (const void *x, const void *y)
1694 struct dep *dx = (struct dep *) x;
1695 struct dep *dy = (struct dep *) y;
1696 int cmp = strcmp (dep_name (dx), dep_name (dy));
1698 /* If the names are the same but ignore_mtimes are not equal, one of these
1699 is an order-only prerequisite and one isn't. That means that we should
1700 remove the one that isn't and keep the one that is. */
1702 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1703 dx->ignore_mtime = dy->ignore_mtime = 0;
1705 return cmp;
1709 void
1710 uniquize_deps (struct dep *chain)
1712 struct hash_table deps;
1713 register struct dep **depp;
1715 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1717 /* Make sure that no dependencies are repeated. This does not
1718 really matter for the purpose of updating targets, but it
1719 might make some names be listed twice for $^ and $?. */
1721 depp = &chain;
1722 while (*depp)
1724 struct dep *dep = *depp;
1725 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1726 if (HASH_VACANT (*dep_slot))
1728 hash_insert_at (&deps, dep, dep_slot);
1729 depp = &dep->next;
1731 else
1733 /* Don't bother freeing duplicates.
1734 It's dangerous and little benefit accrues. */
1735 *depp = dep->next;
1739 hash_free (&deps, 0);
1742 /* Record target-specific variable values for files FILENAMES.
1743 TWO_COLON is nonzero if a double colon was used.
1745 The links of FILENAMES are freed, and so are any names in it
1746 that are not incorporated into other data structures.
1748 If the target is a pattern, add the variable to the pattern-specific
1749 variable value list. */
1751 static void
1752 record_target_var (struct nameseq *filenames, char *defn,
1753 enum variable_origin origin, int exported,
1754 const struct floc *flocp)
1756 struct nameseq *nextf;
1757 struct variable_set_list *global;
1759 global = current_variable_set_list;
1761 /* If the variable is an append version, store that but treat it as a
1762 normal recursive variable. */
1764 for (; filenames != 0; filenames = nextf)
1766 struct variable *v;
1767 const char *name = filenames->name;
1768 const char *fname;
1769 const char *percent;
1770 struct pattern_var *p;
1772 nextf = filenames->next;
1773 free (filenames);
1775 /* If it's a pattern target, then add it to the pattern-specific
1776 variable list. */
1777 percent = find_percent_cached (&name);
1778 if (percent)
1780 /* Get a reference for this pattern-specific variable struct. */
1781 p = create_pattern_var (name, percent);
1782 p->variable.fileinfo = *flocp;
1783 /* I don't think this can fail since we already determined it was a
1784 variable definition. */
1785 v = parse_variable_definition (&p->variable, defn);
1786 assert (v != 0);
1788 if (v->flavor == f_simple)
1789 v->value = allocated_variable_expand (v->value);
1790 else
1791 v->value = xstrdup (v->value);
1793 fname = p->target;
1795 else
1797 struct file *f;
1799 /* Get a file reference for this file, and initialize it.
1800 We don't want to just call enter_file() because that allocates a
1801 new entry if the file is a double-colon, which we don't want in
1802 this situation. */
1803 f = lookup_file (name);
1804 if (!f)
1805 f = enter_file (strcache_add (name));
1806 else if (f->double_colon)
1807 f = f->double_colon;
1809 initialize_file_variables (f, 1);
1810 fname = f->name;
1812 current_variable_set_list = f->variables;
1813 v = try_variable_definition (flocp, defn, origin, 1);
1814 if (!v)
1815 error (flocp, _("Malformed target-specific variable definition"));
1816 current_variable_set_list = global;
1819 /* Set up the variable to be *-specific. */
1820 v->origin = origin;
1821 v->per_target = 1;
1822 v->export = exported ? v_export : v_default;
1824 /* If it's not an override, check to see if there was a command-line
1825 setting. If so, reset the value. */
1826 if (origin != o_override)
1828 struct variable *gv;
1829 int len = strlen(v->name);
1831 gv = lookup_variable (v->name, len);
1832 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1834 if (v->value != 0)
1835 free (v->value);
1836 v->value = xstrdup (gv->value);
1837 v->origin = gv->origin;
1838 v->recursive = gv->recursive;
1839 v->append = 0;
1845 /* Record a description line for files FILENAMES,
1846 with dependencies DEPS, commands to execute described
1847 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1848 TWO_COLON is nonzero if a double colon was used.
1849 If not nil, PATTERN is the `%' pattern to make this
1850 a static pattern rule, and PATTERN_PERCENT is a pointer
1851 to the `%' within it.
1853 The links of FILENAMES are freed, and so are any names in it
1854 that are not incorporated into other data structures. */
1856 static void
1857 record_files (struct nameseq *filenames, const char *pattern,
1858 const char *pattern_percent, struct dep *deps,
1859 unsigned int cmds_started, char *commands,
1860 unsigned int commands_idx, int two_colon,
1861 const struct floc *flocp)
1863 struct nameseq *nextf;
1864 int implicit = 0;
1865 unsigned int max_targets = 0, target_idx = 0;
1866 const char **targets = 0, **target_percents = 0;
1867 struct commands *cmds;
1869 /* If we've already snapped deps, that means we're in an eval being
1870 resolved after the makefiles have been read in. We can't add more rules
1871 at this time, since they won't get snapped and we'll get core dumps.
1872 See Savannah bug # 12124. */
1873 if (snapped_deps)
1874 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1876 if (commands_idx > 0)
1878 cmds = xmalloc (sizeof (struct commands));
1879 cmds->fileinfo.filenm = flocp->filenm;
1880 cmds->fileinfo.lineno = cmds_started;
1881 cmds->commands = savestring (commands, commands_idx);
1882 cmds->command_lines = 0;
1884 else
1885 cmds = 0;
1887 for (; filenames != 0; filenames = nextf)
1889 const char *name = filenames->name;
1890 struct file *f;
1891 struct dep *this = 0;
1892 const char *implicit_percent;
1894 nextf = filenames->next;
1895 free (filenames);
1897 /* Check for special targets. Do it here instead of, say, snap_deps()
1898 so that we can immediately use the value. */
1900 if (streq (name, ".POSIX"))
1901 posix_pedantic = 1;
1902 else if (streq (name, ".SECONDEXPANSION"))
1903 second_expansion = 1;
1905 implicit_percent = find_percent_cached (&name);
1906 implicit |= implicit_percent != 0;
1908 if (implicit)
1910 if (pattern != 0)
1911 fatal (flocp, _("mixed implicit and static pattern rules"));
1913 if (implicit_percent == 0)
1914 fatal (flocp, _("mixed implicit and normal rules"));
1916 if (targets == 0)
1918 max_targets = 5;
1919 targets = xmalloc (5 * sizeof (char *));
1920 target_percents = xmalloc (5 * sizeof (char *));
1921 target_idx = 0;
1923 else if (target_idx == max_targets - 1)
1925 max_targets += 5;
1926 targets = xrealloc (targets, max_targets * sizeof (char *));
1927 target_percents = xrealloc (target_percents,
1928 max_targets * sizeof (char *));
1930 targets[target_idx] = name;
1931 target_percents[target_idx] = implicit_percent;
1932 ++target_idx;
1933 continue;
1936 /* If this is a static pattern rule:
1937 `targets: target%pattern: dep%pattern; cmds',
1938 make sure the pattern matches this target name. */
1939 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1940 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1941 else if (deps)
1943 /* If there are multiple filenames, copy the chain DEPS for all but
1944 the last one. It is not safe for the same deps to go in more
1945 than one place in the database. */
1946 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1947 this->need_2nd_expansion = (second_expansion
1948 && strchr (this->name, '$'));
1951 if (!two_colon)
1953 /* Single-colon. Combine these dependencies
1954 with others in file's existing record, if any. */
1955 f = enter_file (strcache_add (name));
1957 if (f->double_colon)
1958 fatal (flocp,
1959 _("target file `%s' has both : and :: entries"), f->name);
1961 /* If CMDS == F->CMDS, this target was listed in this rule
1962 more than once. Just give a warning since this is harmless. */
1963 if (cmds != 0 && cmds == f->cmds)
1964 error (flocp,
1965 _("target `%s' given more than once in the same rule."),
1966 f->name);
1968 /* Check for two single-colon entries both with commands.
1969 Check is_target so that we don't lose on files such as .c.o
1970 whose commands were preinitialized. */
1971 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1973 error (&cmds->fileinfo,
1974 _("warning: overriding commands for target `%s'"),
1975 f->name);
1976 error (&f->cmds->fileinfo,
1977 _("warning: ignoring old commands for target `%s'"),
1978 f->name);
1981 f->is_target = 1;
1983 /* Defining .DEFAULT with no deps or cmds clears it. */
1984 if (f == default_file && this == 0 && cmds == 0)
1985 f->cmds = 0;
1986 if (cmds != 0)
1987 f->cmds = cmds;
1989 /* Defining .SUFFIXES with no dependencies clears out the list of
1990 suffixes. */
1991 if (f == suffix_file && this == 0)
1993 free_dep_chain (f->deps);
1994 f->deps = 0;
1996 else if (this != 0)
1998 /* Add the file's old deps and the new ones in THIS together. */
2000 if (f->deps != 0)
2002 struct dep **d_ptr = &f->deps;
2004 while ((*d_ptr)->next != 0)
2005 d_ptr = &(*d_ptr)->next;
2007 if (cmds != 0)
2008 /* This is the rule with commands, so put its deps
2009 last. The rationale behind this is that $< expands to
2010 the first dep in the chain, and commands use $<
2011 expecting to get the dep that rule specifies. However
2012 the second expansion algorithm reverses the order thus
2013 we need to make it last here. */
2014 (*d_ptr)->next = this;
2015 else
2017 /* This is the rule without commands. Put its
2018 dependencies at the end but before dependencies from
2019 the rule with commands (if any). This way everything
2020 appears in makefile order. */
2022 if (f->cmds != 0)
2024 this->next = *d_ptr;
2025 *d_ptr = this;
2027 else
2028 (*d_ptr)->next = this;
2031 else
2032 f->deps = this;
2034 /* This is a hack. I need a way to communicate to snap_deps()
2035 that the last dependency line in this file came with commands
2036 (so that logic in snap_deps() can put it in front and all
2037 this $< -logic works). I cannot simply rely on file->cmds
2038 being not 0 because of the cases like the following:
2040 foo: bar
2041 foo:
2044 I am going to temporarily "borrow" UPDATING member in
2045 `struct file' for this. */
2047 if (cmds != 0)
2048 f->updating = 1;
2051 else
2053 /* Double-colon. Make a new record even if there already is one. */
2054 f = lookup_file (name);
2056 /* Check for both : and :: rules. Check is_target so
2057 we don't lose on default suffix rules or makefiles. */
2058 if (f != 0 && f->is_target && !f->double_colon)
2059 fatal (flocp,
2060 _("target file `%s' has both : and :: entries"), f->name);
2061 f = enter_file (strcache_add (name));
2062 /* If there was an existing entry and it was a double-colon entry,
2063 enter_file will have returned a new one, making it the prev
2064 pointer of the old one, and setting its double_colon pointer to
2065 the first one. */
2066 if (f->double_colon == 0)
2067 /* This is the first entry for this name, so we must set its
2068 double_colon pointer to itself. */
2069 f->double_colon = f;
2070 f->is_target = 1;
2071 f->deps = this;
2072 f->cmds = cmds;
2075 /* If this is a static pattern rule, set the stem to the part of its
2076 name that matched the `%' in the pattern, so you can use $* in the
2077 commands. */
2078 if (pattern)
2080 static const char *percent = "%";
2081 char *buffer = variable_expand ("");
2082 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2083 pattern_percent+1, percent+1);
2084 f->stem = strcache_add_len (buffer, o - buffer);
2085 if (this)
2087 this->staticpattern = 1;
2088 this->stem = f->stem;
2092 name = f->name;
2094 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2095 if (streq (*default_goal_name, name)
2096 && (default_goal_file == 0
2097 || ! streq (default_goal_file->name, name)))
2098 default_goal_file = f;
2101 if (implicit)
2103 if (deps)
2104 deps->need_2nd_expansion = second_expansion;
2105 create_pattern_rule (targets, target_percents, target_idx,
2106 two_colon, deps, cmds, 1);
2110 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2111 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2112 Quoting backslashes are removed from STRING by compacting it into
2113 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2114 one, or nil if there are none. STOPCHARs inside variable references are
2115 ignored if IGNOREVARS is true.
2117 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2119 static char *
2120 find_char_unquote (char *string, int stop1, int stop2, int blank,
2121 int ignorevars)
2123 unsigned int string_len = 0;
2124 char *p = string;
2126 if (ignorevars)
2127 ignorevars = '$';
2129 while (1)
2131 if (stop2 && blank)
2132 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2133 && ! isblank ((unsigned char) *p))
2134 ++p;
2135 else if (stop2)
2136 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2137 ++p;
2138 else if (blank)
2139 while (*p != '\0' && *p != ignorevars && *p != stop1
2140 && ! isblank ((unsigned char) *p))
2141 ++p;
2142 else
2143 while (*p != '\0' && *p != ignorevars && *p != stop1)
2144 ++p;
2146 if (*p == '\0')
2147 break;
2149 /* If we stopped due to a variable reference, skip over its contents. */
2150 if (*p == ignorevars)
2152 char openparen = p[1];
2154 p += 2;
2156 /* Skip the contents of a non-quoted, multi-char variable ref. */
2157 if (openparen == '(' || openparen == '{')
2159 unsigned int pcount = 1;
2160 char closeparen = (openparen == '(' ? ')' : '}');
2162 while (*p)
2164 if (*p == openparen)
2165 ++pcount;
2166 else if (*p == closeparen)
2167 if (--pcount == 0)
2169 ++p;
2170 break;
2172 ++p;
2176 /* Skipped the variable reference: look for STOPCHARS again. */
2177 continue;
2180 if (p > string && p[-1] == '\\')
2182 /* Search for more backslashes. */
2183 int i = -2;
2184 while (&p[i] >= string && p[i] == '\\')
2185 --i;
2186 ++i;
2187 /* Only compute the length if really needed. */
2188 if (string_len == 0)
2189 string_len = strlen (string);
2190 /* The number of backslashes is now -I.
2191 Copy P over itself to swallow half of them. */
2192 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2193 p += i/2;
2194 if (i % 2 == 0)
2195 /* All the backslashes quoted each other; the STOPCHAR was
2196 unquoted. */
2197 return p;
2199 /* The STOPCHAR was quoted by a backslash. Look for another. */
2201 else
2202 /* No backslash in sight. */
2203 return p;
2206 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2207 return 0;
2210 /* Search PATTERN for an unquoted % and handle quoting. */
2212 char *
2213 find_percent (char *pattern)
2215 return find_char_unquote (pattern, '%', 0, 0, 0);
2218 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2219 the % or NULL if no % was found.
2220 This version is used with strings in the string cache: if there's a need to
2221 modify the string a new version will be added to the string cache and
2222 *STRING will be set to that. */
2224 const char *
2225 find_percent_cached (const char **string)
2227 const char *p = *string;
2228 char *new = 0;
2229 int slen;
2231 /* If the first char is a % return now. This lets us avoid extra tests
2232 inside the loop. */
2233 if (*p == '%')
2234 return p;
2236 while (1)
2238 while (*p != '\0' && *p != '%')
2239 ++p;
2241 if (*p == '\0')
2242 break;
2244 /* See if this % is escaped with a backslash; if not we're done. */
2245 if (p[-1] != '\\')
2246 break;
2249 /* Search for more backslashes. */
2250 char *pv;
2251 int i = -2;
2253 while (&p[i] >= *string && p[i] == '\\')
2254 --i;
2255 ++i;
2257 /* At this point we know we'll need to allocate a new string.
2258 Make a copy if we haven't yet done so. */
2259 if (! new)
2261 slen = strlen (*string);
2262 new = alloca (slen + 1);
2263 memcpy (new, *string, slen + 1);
2264 p = new + (p - *string);
2265 *string = new;
2268 /* At this point *string, p, and new all point into the same string.
2269 Get a non-const version of p so we can modify new. */
2270 pv = new + (p - *string);
2272 /* The number of backslashes is now -I.
2273 Copy P over itself to swallow half of them. */
2274 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2275 p += i/2;
2277 /* If the backslashes quoted each other; the % was unquoted. */
2278 if (i % 2 == 0)
2279 break;
2283 /* If we had to change STRING, add it to the strcache. */
2284 if (new)
2286 *string = strcache_add (*string);
2287 p = *string + (p - new);
2290 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2291 return (*p == '\0') ? NULL : p;
2294 /* Parse a string into a sequence of filenames represented as a
2295 chain of struct nameseq's in reverse order and return that chain.
2297 The string is passed as STRINGP, the address of a string pointer.
2298 The string pointer is updated to point at the first character
2299 not parsed, which either is a null char or equals STOPCHAR.
2301 SIZE is how big to construct chain elements.
2302 This is useful if we want them actually to be other structures
2303 that have room for additional info.
2305 If STRIP is nonzero, strip `./'s off the beginning. */
2307 struct nameseq *
2308 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2310 struct nameseq *new = 0;
2311 struct nameseq *new1, *lastnew1;
2312 char *p = *stringp;
2314 #ifdef VMS
2315 # define VMS_COMMA ','
2316 #else
2317 # define VMS_COMMA 0
2318 #endif
2320 while (1)
2322 const char *name;
2323 char *q;
2325 /* Skip whitespace; see if any more names are left. */
2326 p = next_token (p);
2327 if (*p == '\0')
2328 break;
2329 if (*p == stopchar)
2330 break;
2332 /* There are, so find the end of the next name. */
2333 q = p;
2334 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2335 #ifdef VMS
2336 /* convert comma separated list to space separated */
2337 if (p && *p == ',')
2338 *p =' ';
2339 #endif
2340 #ifdef _AMIGA
2341 if (stopchar == ':' && p && *p == ':'
2342 && !(isspace ((unsigned char)p[1]) || !p[1]
2343 || isspace ((unsigned char)p[-1])))
2344 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2345 #endif
2346 #ifdef HAVE_DOS_PATHS
2347 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2348 first colon which isn't followed by a slash or a backslash.
2349 Note that tokens separated by spaces should be treated as separate
2350 tokens since make doesn't allow path names with spaces */
2351 if (stopchar == ':')
2352 while (p != 0 && !isspace ((unsigned char)*p) &&
2353 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2354 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2355 #endif
2356 if (p == 0)
2357 p = q + strlen (q);
2359 if (strip)
2360 #ifdef VMS
2361 /* Skip leading `[]'s. */
2362 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2363 #else
2364 /* Skip leading `./'s. */
2365 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2366 #endif
2368 q += 2; /* Skip "./". */
2369 while (q < p && *q == '/')
2370 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2371 ++q;
2374 /* Extract the filename just found, and skip it. */
2376 if (q == p)
2377 /* ".///" was stripped to "". */
2378 #if defined(VMS)
2379 continue;
2380 #elif defined(_AMIGA)
2381 name = "";
2382 #else
2383 name = "./";
2384 #endif
2385 else
2386 #ifdef VMS
2387 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2388 * to remove this '\' before we can use the filename.
2389 * Savestring called because q may be read-only string constant.
2392 char *qbase = xstrdup (q);
2393 char *pbase = qbase + (p-q);
2394 char *q1 = qbase;
2395 char *q2 = q1;
2396 char *p1 = pbase;
2398 while (q1 != pbase)
2400 if (*q1 == '\\' && *(q1+1) == ':')
2402 q1++;
2403 p1--;
2405 *q2++ = *q1++;
2407 name = strcache_add_len (qbase, p1 - qbase);
2408 free (qbase);
2410 #else
2411 name = strcache_add_len (q, p - q);
2412 #endif
2414 /* Add it to the front of the chain. */
2415 new1 = xmalloc (size);
2416 new1->name = name;
2417 new1->next = new;
2418 new = new1;
2421 #ifndef NO_ARCHIVES
2423 /* Look for multi-word archive references.
2424 They are indicated by a elt ending with an unmatched `)' and
2425 an elt further down the chain (i.e., previous in the file list)
2426 with an unmatched `(' (e.g., "lib(mem"). */
2428 new1 = new;
2429 lastnew1 = 0;
2430 while (new1 != 0)
2431 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2432 && new1->name[strlen (new1->name) - 1] == ')'
2433 && strchr (new1->name, '(') == 0)
2435 /* NEW1 ends with a `)' but does not contain a `('.
2436 Look back for an elt with an opening `(' but no closing `)'. */
2438 struct nameseq *n = new1->next, *lastn = new1;
2439 char *paren = 0;
2440 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2442 lastn = n;
2443 n = n->next;
2445 if (n != 0
2446 /* Ignore something starting with `(', as that cannot actually
2447 be an archive-member reference (and treating it as such
2448 results in an empty file name, which causes much lossage). */
2449 && n->name[0] != '(')
2451 /* N is the first element in the archive group.
2452 Its name looks like "lib(mem" (with no closing `)'). */
2454 char *libname;
2456 /* Copy "lib(" into LIBNAME. */
2457 ++paren;
2458 libname = alloca (paren - n->name + 1);
2459 memcpy (libname, n->name, paren - n->name);
2460 libname[paren - n->name] = '\0';
2462 if (*paren == '\0')
2464 /* N was just "lib(", part of something like "lib( a b)".
2465 Edit it out of the chain and free its storage. */
2466 lastn->next = n->next;
2467 free (n);
2468 /* LASTN->next is the new stopping elt for the loop below. */
2469 n = lastn->next;
2471 else
2473 /* Replace N's name with the full archive reference. */
2474 n->name = strcache_add (concat (libname, paren, ")"));
2477 if (new1->name[1] == '\0')
2479 /* NEW1 is just ")", part of something like "lib(a b )".
2480 Omit it from the chain and free its storage. */
2481 if (lastnew1 == 0)
2482 new = new1->next;
2483 else
2484 lastnew1->next = new1->next;
2485 lastn = new1;
2486 new1 = new1->next;
2487 free (lastn);
2489 else
2491 /* Replace also NEW1->name, which already has closing `)'. */
2492 new1->name = strcache_add (concat (libname, new1->name, ""));
2493 new1 = new1->next;
2496 /* Trace back from NEW1 (the end of the list) until N
2497 (the beginning of the list), rewriting each name
2498 with the full archive reference. */
2500 while (new1 != n)
2502 new1->name = strcache_add (concat (libname, new1->name, ")"));
2503 lastnew1 = new1;
2504 new1 = new1->next;
2507 else
2509 /* No frobnication happening. Just step down the list. */
2510 lastnew1 = new1;
2511 new1 = new1->next;
2514 else
2516 lastnew1 = new1;
2517 new1 = new1->next;
2520 #endif
2522 *stringp = p;
2523 return new;
2526 /* Find the next line of text in an eval buffer, combining continuation lines
2527 into one line.
2528 Return the number of actual lines read (> 1 if continuation lines).
2529 Returns -1 if there's nothing left in the buffer.
2531 After this function, ebuf->buffer points to the first character of the
2532 line we just found.
2535 /* Read a line of text from a STRING.
2536 Since we aren't really reading from a file, don't bother with linenumbers.
2539 static unsigned long
2540 readstring (struct ebuffer *ebuf)
2542 char *eol;
2544 /* If there is nothing left in this buffer, return 0. */
2545 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2546 return -1;
2548 /* Set up a new starting point for the buffer, and find the end of the
2549 next logical line (taking into account backslash/newline pairs). */
2551 eol = ebuf->buffer = ebuf->bufnext;
2553 while (1)
2555 int backslash = 0;
2556 char *bol = eol;
2557 char *p;
2559 /* Find the next newline. At EOS, stop. */
2560 eol = p = strchr (eol , '\n');
2561 if (!eol)
2563 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2564 return 0;
2567 /* Found a newline; if it's escaped continue; else we're done. */
2568 while (p > bol && *(--p) == '\\')
2569 backslash = !backslash;
2570 if (!backslash)
2571 break;
2572 ++eol;
2575 /* Overwrite the newline char. */
2576 *eol = '\0';
2577 ebuf->bufnext = eol+1;
2579 return 0;
2582 static long
2583 readline (struct ebuffer *ebuf)
2585 char *p;
2586 char *end;
2587 char *start;
2588 long nlines = 0;
2590 /* The behaviors between string and stream buffers are different enough to
2591 warrant different functions. Do the Right Thing. */
2593 if (!ebuf->fp)
2594 return readstring (ebuf);
2596 /* When reading from a file, we always start over at the beginning of the
2597 buffer for each new line. */
2599 p = start = ebuf->bufstart;
2600 end = p + ebuf->size;
2601 *p = '\0';
2603 while (fgets (p, end - p, ebuf->fp) != 0)
2605 char *p2;
2606 unsigned long len;
2607 int backslash;
2609 len = strlen (p);
2610 if (len == 0)
2612 /* This only happens when the first thing on the line is a '\0'.
2613 It is a pretty hopeless case, but (wonder of wonders) Athena
2614 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2615 There is nothing really to be done; we synthesize a newline so
2616 the following line doesn't appear to be part of this line. */
2617 error (&ebuf->floc,
2618 _("warning: NUL character seen; rest of line ignored"));
2619 p[0] = '\n';
2620 len = 1;
2623 /* Jump past the text we just read. */
2624 p += len;
2626 /* If the last char isn't a newline, the whole line didn't fit into the
2627 buffer. Get some more buffer and try again. */
2628 if (p[-1] != '\n')
2629 goto more_buffer;
2631 /* We got a newline, so add one to the count of lines. */
2632 ++nlines;
2634 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2635 /* Check to see if the line was really ended with CRLF; if so ignore
2636 the CR. */
2637 if ((p - start) > 1 && p[-2] == '\r')
2639 --p;
2640 p[-1] = '\n';
2642 #endif
2644 backslash = 0;
2645 for (p2 = p - 2; p2 >= start; --p2)
2647 if (*p2 != '\\')
2648 break;
2649 backslash = !backslash;
2652 if (!backslash)
2654 p[-1] = '\0';
2655 break;
2658 /* It was a backslash/newline combo. If we have more space, read
2659 another line. */
2660 if (end - p >= 80)
2661 continue;
2663 /* We need more space at the end of our buffer, so realloc it.
2664 Make sure to preserve the current offset of p. */
2665 more_buffer:
2667 unsigned long off = p - start;
2668 ebuf->size *= 2;
2669 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2670 p = start + off;
2671 end = start + ebuf->size;
2672 *p = '\0';
2676 if (ferror (ebuf->fp))
2677 pfatal_with_name (ebuf->floc.filenm);
2679 /* If we found some lines, return how many.
2680 If we didn't, but we did find _something_, that indicates we read the last
2681 line of a file with no final newline; return 1.
2682 If we read nothing, we're at EOF; return -1. */
2684 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2687 /* Parse the next "makefile word" from the input buffer, and return info
2688 about it.
2690 A "makefile word" is one of:
2692 w_bogus Should never happen
2693 w_eol End of input
2694 w_static A static word; cannot be expanded
2695 w_variable A word containing one or more variables/functions
2696 w_colon A colon
2697 w_dcolon A double-colon
2698 w_semicolon A semicolon
2699 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2701 Note that this function is only used when reading certain parts of the
2702 makefile. Don't use it where special rules hold sway (RHS of a variable,
2703 in a command list, etc.) */
2705 static enum make_word_type
2706 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2708 enum make_word_type wtype = w_bogus;
2709 char *p = buffer, *beg;
2710 char c;
2712 /* Skip any leading whitespace. */
2713 while (isblank ((unsigned char)*p))
2714 ++p;
2716 beg = p;
2717 c = *(p++);
2718 switch (c)
2720 case '\0':
2721 wtype = w_eol;
2722 break;
2724 case ';':
2725 wtype = w_semicolon;
2726 break;
2728 case '=':
2729 wtype = w_varassign;
2730 break;
2732 case ':':
2733 wtype = w_colon;
2734 switch (*p)
2736 case ':':
2737 ++p;
2738 wtype = w_dcolon;
2739 break;
2741 case '=':
2742 ++p;
2743 wtype = w_varassign;
2744 break;
2746 break;
2748 case '+':
2749 case '?':
2750 if (*p == '=')
2752 ++p;
2753 wtype = w_varassign;
2754 break;
2757 default:
2758 if (delim && strchr (delim, c))
2759 wtype = w_static;
2760 break;
2763 /* Did we find something? If so, return now. */
2764 if (wtype != w_bogus)
2765 goto done;
2767 /* This is some non-operator word. A word consists of the longest
2768 string of characters that doesn't contain whitespace, one of [:=#],
2769 or [?+]=, or one of the chars in the DELIM string. */
2771 /* We start out assuming a static word; if we see a variable we'll
2772 adjust our assumptions then. */
2773 wtype = w_static;
2775 /* We already found the first value of "c", above. */
2776 while (1)
2778 char closeparen;
2779 int count;
2781 switch (c)
2783 case '\0':
2784 case ' ':
2785 case '\t':
2786 case '=':
2787 goto done_word;
2789 case ':':
2790 #ifdef HAVE_DOS_PATHS
2791 /* A word CAN include a colon in its drive spec. The drive
2792 spec is allowed either at the beginning of a word, or as part
2793 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2794 if (!(p - beg >= 2
2795 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2796 && (p - beg == 2 || p[-3] == '(')))
2797 #endif
2798 goto done_word;
2800 case '$':
2801 c = *(p++);
2802 if (c == '$')
2803 break;
2805 /* This is a variable reference, so note that it's expandable.
2806 Then read it to the matching close paren. */
2807 wtype = w_variable;
2809 if (c == '(')
2810 closeparen = ')';
2811 else if (c == '{')
2812 closeparen = '}';
2813 else
2814 /* This is a single-letter variable reference. */
2815 break;
2817 for (count=0; *p != '\0'; ++p)
2819 if (*p == c)
2820 ++count;
2821 else if (*p == closeparen && --count < 0)
2823 ++p;
2824 break;
2827 break;
2829 case '?':
2830 case '+':
2831 if (*p == '=')
2832 goto done_word;
2833 break;
2835 case '\\':
2836 switch (*p)
2838 case ':':
2839 case ';':
2840 case '=':
2841 case '\\':
2842 ++p;
2843 break;
2845 break;
2847 default:
2848 if (delim && strchr (delim, c))
2849 goto done_word;
2850 break;
2853 c = *(p++);
2855 done_word:
2856 --p;
2858 done:
2859 if (startp)
2860 *startp = beg;
2861 if (length)
2862 *length = p - beg;
2863 return wtype;
2866 /* Construct the list of include directories
2867 from the arguments and the default list. */
2869 void
2870 construct_include_path (const char **arg_dirs)
2872 #ifdef VAXC /* just don't ask ... */
2873 stat_t stbuf;
2874 #else
2875 struct stat stbuf;
2876 #endif
2877 const char **dirs;
2878 const char **cpp;
2879 unsigned int idx;
2881 /* Compute the number of pointers we need in the table. */
2882 idx = sizeof (default_include_directories) / sizeof (const char *);
2883 if (arg_dirs)
2884 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2885 ++idx;
2887 #ifdef __MSDOS__
2888 /* Add one for $DJDIR. */
2889 ++idx;
2890 #endif
2892 dirs = xmalloc (idx * sizeof (const char *));
2894 idx = 0;
2895 max_incl_len = 0;
2897 /* First consider any dirs specified with -I switches.
2898 Ignore any that don't exist. Remember the maximum string length. */
2900 if (arg_dirs)
2901 while (*arg_dirs != 0)
2903 const char *dir = *(arg_dirs++);
2904 char *expanded = 0;
2905 int e;
2907 if (dir[0] == '~')
2909 expanded = tilde_expand (dir);
2910 if (expanded != 0)
2911 dir = expanded;
2914 EINTRLOOP (e, stat (dir, &stbuf));
2915 if (e == 0 && S_ISDIR (stbuf.st_mode))
2917 unsigned int len = strlen (dir);
2918 /* If dir name is written with trailing slashes, discard them. */
2919 while (len > 1 && dir[len - 1] == '/')
2920 --len;
2921 if (len > max_incl_len)
2922 max_incl_len = len;
2923 dirs[idx++] = strcache_add_len (dir, len);
2926 if (expanded)
2927 free (expanded);
2930 /* Now add the standard default dirs at the end. */
2932 #ifdef __MSDOS__
2934 /* The environment variable $DJDIR holds the root of the DJGPP directory
2935 tree; add ${DJDIR}/include. */
2936 struct variable *djdir = lookup_variable ("DJDIR", 5);
2938 if (djdir)
2940 unsigned int len = strlen (djdir->value) + 8;
2941 char *defdir = alloca (len + 1);
2943 strcat (strcpy (defdir, djdir->value), "/include");
2944 dirs[idx++] = strcache_add (defdir);
2946 if (len > max_incl_len)
2947 max_incl_len = len;
2950 #endif
2952 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2954 int e;
2956 EINTRLOOP (e, stat (*cpp, &stbuf));
2957 if (e == 0 && S_ISDIR (stbuf.st_mode))
2959 unsigned int len = strlen (*cpp);
2960 /* If dir name is written with trailing slashes, discard them. */
2961 while (len > 1 && (*cpp)[len - 1] == '/')
2962 --len;
2963 if (len > max_incl_len)
2964 max_incl_len = len;
2965 dirs[idx++] = strcache_add_len (*cpp, len - 1);
2969 dirs[idx] = 0;
2971 /* Now add each dir to the .INCLUDE_DIRS variable. */
2973 for (cpp = dirs; *cpp != 0; ++cpp)
2974 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2975 o_default, f_append, 0);
2977 include_directories = dirs;
2980 /* Expand ~ or ~USER at the beginning of NAME.
2981 Return a newly malloc'd string or 0. */
2983 char *
2984 tilde_expand (const char *name)
2986 #ifndef VMS
2987 if (name[1] == '/' || name[1] == '\0')
2989 extern char *getenv ();
2990 char *home_dir;
2991 int is_variable;
2994 /* Turn off --warn-undefined-variables while we expand HOME. */
2995 int save = warn_undefined_variables_flag;
2996 warn_undefined_variables_flag = 0;
2998 home_dir = allocated_variable_expand ("$(HOME)");
3000 warn_undefined_variables_flag = save;
3003 is_variable = home_dir[0] != '\0';
3004 if (!is_variable)
3006 free (home_dir);
3007 home_dir = getenv ("HOME");
3009 # if !defined(_AMIGA) && !defined(WINDOWS32)
3010 if (home_dir == 0 || home_dir[0] == '\0')
3012 extern char *getlogin ();
3013 char *logname = getlogin ();
3014 home_dir = 0;
3015 if (logname != 0)
3017 struct passwd *p = getpwnam (logname);
3018 if (p != 0)
3019 home_dir = p->pw_dir;
3022 # endif /* !AMIGA && !WINDOWS32 */
3023 if (home_dir != 0)
3025 char *new = xstrdup (concat (home_dir, "", name + 1));
3026 if (is_variable)
3027 free (home_dir);
3028 return new;
3031 # if !defined(_AMIGA) && !defined(WINDOWS32)
3032 else
3034 struct passwd *pwent;
3035 char *userend = strchr (name + 1, '/');
3036 if (userend != 0)
3037 *userend = '\0';
3038 pwent = getpwnam (name + 1);
3039 if (pwent != 0)
3041 if (userend == 0)
3042 return xstrdup (pwent->pw_dir);
3043 else
3044 return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
3046 else if (userend != 0)
3047 *userend = '/';
3049 # endif /* !AMIGA && !WINDOWS32 */
3050 #endif /* !VMS */
3051 return 0;
3054 /* Given a chain of struct nameseq's describing a sequence of filenames,
3055 in reverse of the intended order, return a new chain describing the
3056 result of globbing the filenames. The new chain is in forward order.
3057 The links of the old chain are freed or used in the new chain.
3058 Likewise for the names in the old chain.
3060 SIZE is how big to construct chain elements.
3061 This is useful if we want them actually to be other structures
3062 that have room for additional info. */
3064 struct nameseq *
3065 multi_glob (struct nameseq *chain, unsigned int size)
3067 void dir_setup_glob (glob_t *);
3068 struct nameseq *new = 0;
3069 struct nameseq *old;
3070 struct nameseq *nexto;
3071 glob_t gl;
3073 dir_setup_glob (&gl);
3075 for (old = chain; old != 0; old = nexto)
3077 const char *gname;
3078 #ifndef NO_ARCHIVES
3079 char *arname = 0;
3080 char *memname = 0;
3081 #endif
3082 nexto = old->next;
3083 gname = old->name;
3085 if (gname[0] == '~')
3087 char *newname = tilde_expand (old->name);
3088 if (newname != 0)
3089 gname = newname;
3092 #ifndef NO_ARCHIVES
3093 if (ar_name (gname))
3095 /* OLD->name is an archive member reference. Replace it with the
3096 archive file name, and save the member name in MEMNAME. We will
3097 glob on the archive name and then reattach MEMNAME later. */
3098 ar_parse_name (gname, &arname, &memname);
3099 gname = arname;
3101 #endif /* !NO_ARCHIVES */
3103 switch (glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3105 case 0: /* Success. */
3107 int i = gl.gl_pathc;
3108 while (i-- > 0)
3110 #ifndef NO_ARCHIVES
3111 if (memname != 0)
3113 /* Try to glob on MEMNAME within the archive. */
3114 struct nameseq *found
3115 = ar_glob (gl.gl_pathv[i], memname, size);
3116 if (! found)
3118 /* No matches. Use MEMNAME as-is. */
3119 unsigned int alen = strlen (gl.gl_pathv[i]);
3120 unsigned int mlen = strlen (memname);
3121 char *name;
3122 struct nameseq *elt = xmalloc (size);
3123 memset (elt, '\0', size);
3125 name = alloca (alen + 1 + mlen + 2);
3126 memcpy (name, gl.gl_pathv[i], alen);
3127 name[alen] = '(';
3128 memcpy (name+alen+1, memname, mlen);
3129 name[alen + 1 + mlen] = ')';
3130 name[alen + 1 + mlen + 1] = '\0';
3131 elt->name = strcache_add (name);
3132 elt->next = new;
3133 new = elt;
3135 else
3137 /* Find the end of the FOUND chain. */
3138 struct nameseq *f = found;
3139 while (f->next != 0)
3140 f = f->next;
3142 /* Attach the chain being built to the end of the FOUND
3143 chain, and make FOUND the new NEW chain. */
3144 f->next = new;
3145 new = found;
3148 else
3149 #endif /* !NO_ARCHIVES */
3151 struct nameseq *elt = xmalloc (size);
3152 memset (elt, '\0', size);
3153 elt->name = strcache_add (gl.gl_pathv[i]);
3154 elt->next = new;
3155 new = elt;
3158 globfree (&gl);
3159 free (old);
3160 break;
3163 case GLOB_NOSPACE:
3164 fatal (NILF, _("virtual memory exhausted"));
3165 break;
3167 default:
3168 old->next = new;
3169 new = old;
3170 break;
3173 #ifndef NO_ARCHIVES
3174 if (arname)
3175 free (arname);
3176 #endif
3179 return new;