Numerous updates to tests for issues found on Cygwin and Windows.
[make.git] / read.c
blob0c78c7f482946bbe36bcd3f948c7cbc46da1667b
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 PARAMS ((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 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, int len, 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));
144 static void remove_comments PARAMS ((char *line));
145 static char *find_char_unquote PARAMS ((char *string, int stop1,
146 int stop2, int blank, int ignorevars));
148 /* Read in all the makefiles and return the chain of their names. */
150 struct dep *
151 read_all_makefiles (char **makefiles)
153 unsigned int num_makefiles = 0;
155 /* Create *_LIST variables, to hold the makefiles, targets, and variables
156 we will be reading. */
158 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
160 DB (DB_BASIC, (_("Reading makefiles...\n")));
162 /* If there's a non-null variable MAKEFILES, its value is a list of
163 files to read first thing. But don't let it prevent reading the
164 default makefiles and don't let the default goal come from there. */
167 char *value;
168 char *name, *p;
169 unsigned int length;
172 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
173 int save = warn_undefined_variables_flag;
174 warn_undefined_variables_flag = 0;
176 value = allocated_variable_expand ("$(MAKEFILES)");
178 warn_undefined_variables_flag = save;
181 /* Set NAME to the start of next token and LENGTH to its length.
182 MAKEFILES is updated for finding remaining tokens. */
183 p = value;
185 while ((name = find_next_token (&p, &length)) != 0)
187 if (*p != '\0')
188 *p++ = '\0';
189 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
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 d->staticpattern = 0;
257 d->need_2nd_expansion = 0;
258 /* Tell update_goal_chain to bail out as soon as this file is
259 made, and main not to die if we can't make this file. */
260 d->changed = RM_DONTCARE;
261 if (tail == 0)
262 read_makefiles = d;
263 else
264 tail->next = d;
265 tail = d;
267 if (tail != 0)
268 tail->next = 0;
272 return read_makefiles;
275 /* Install a new conditional and return the previous one. */
277 static struct conditionals *
278 install_conditionals (struct conditionals *new)
280 struct conditionals *save = conditionals;
282 bzero ((char *) new, sizeof (*new));
283 conditionals = new;
285 return save;
288 /* Free the current conditionals and reinstate a saved one. */
290 static void
291 restore_conditionals (struct conditionals *saved)
293 /* Free any space allocated by conditional_line. */
294 if (conditionals->ignoring)
295 free (conditionals->ignoring);
296 if (conditionals->seen_else)
297 free (conditionals->seen_else);
299 /* Restore state. */
300 conditionals = saved;
303 static int
304 eval_makefile (char *filename, int flags)
306 struct dep *deps;
307 struct ebuffer ebuf;
308 const struct floc *curfile;
309 char *expanded = 0;
310 char *included = 0;
311 int makefile_errno;
312 int r;
314 ebuf.floc.filenm = strcache_add (filename);
315 ebuf.floc.lineno = 1;
317 if (ISDB (DB_VERBOSE))
319 printf (_("Reading makefile `%s'"), filename);
320 if (flags & RM_NO_DEFAULT_GOAL)
321 printf (_(" (no default goal)"));
322 if (flags & RM_INCLUDED)
323 printf (_(" (search path)"));
324 if (flags & RM_DONTCARE)
325 printf (_(" (don't care)"));
326 if (flags & RM_NO_TILDE)
327 printf (_(" (no ~ expansion)"));
328 puts ("...");
331 /* First, get a stream to read. */
333 /* Expand ~ in FILENAME unless it came from `include',
334 in which case it was already done. */
335 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
337 expanded = tilde_expand (filename);
338 if (expanded != 0)
339 filename = expanded;
342 ebuf.fp = fopen (filename, "r");
343 /* Save the error code so we print the right message later. */
344 makefile_errno = errno;
346 /* If the makefile wasn't found and it's either a makefile from
347 the `MAKEFILES' variable or an included makefile,
348 search the included makefile search path for this makefile. */
349 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
351 register unsigned int i;
352 for (i = 0; include_directories[i] != 0; ++i)
354 included = concat (include_directories[i], "/", filename);
355 ebuf.fp = fopen (included, "r");
356 if (ebuf.fp)
358 filename = included;
359 break;
361 free (included);
363 /* If we're not using it, we already freed it above. */
364 if (filename != included)
365 included = 0;
368 /* Add FILENAME to the chain of read makefiles. */
369 deps = (struct dep *) xmalloc (sizeof (struct dep));
370 deps->next = read_makefiles;
371 read_makefiles = deps;
372 deps->name = 0;
373 deps->file = lookup_file (filename);
374 if (deps->file == 0)
375 deps->file = enter_file (xstrdup (filename));
376 filename = deps->file->name;
377 deps->changed = flags;
378 deps->ignore_mtime = 0;
379 deps->staticpattern = 0;
380 deps->need_2nd_expansion = 0;
381 if (flags & RM_DONTCARE)
382 deps->file->dontcare = 1;
384 if (expanded)
385 free (expanded);
386 if (included)
387 free (included);
389 /* If the makefile can't be found at all, give up entirely. */
391 if (ebuf.fp == 0)
393 /* If we did some searching, errno has the error from the last
394 attempt, rather from FILENAME itself. Restore it in case the
395 caller wants to use it in a message. */
396 errno = makefile_errno;
397 return 0;
400 /* Add this makefile to the list. */
401 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
402 f_append, 0);
404 /* Evaluate the makefile */
406 ebuf.size = 200;
407 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
409 curfile = reading_file;
410 reading_file = &ebuf.floc;
412 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
414 reading_file = curfile;
416 fclose (ebuf.fp);
418 free (ebuf.bufstart);
419 alloca (0);
420 return r;
424 eval_buffer (char *buffer)
426 struct ebuffer ebuf;
427 struct conditionals *saved;
428 struct conditionals new;
429 const struct floc *curfile;
430 int r;
432 /* Evaluate the buffer */
434 ebuf.size = strlen (buffer);
435 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
436 ebuf.fp = NULL;
438 ebuf.floc = *reading_file;
440 curfile = reading_file;
441 reading_file = &ebuf.floc;
443 saved = install_conditionals (&new);
445 r = eval (&ebuf, 1);
447 restore_conditionals (saved);
449 reading_file = curfile;
451 alloca (0);
452 return r;
456 /* Read file FILENAME as a makefile and add its contents to the data base.
458 SET_DEFAULT is true if we are allowed to set the default goal. */
461 static int
462 eval (struct ebuffer *ebuf, int set_default)
464 char *collapsed = 0;
465 unsigned int collapsed_length = 0;
466 unsigned int commands_len = 200;
467 char *commands;
468 unsigned int commands_idx = 0;
469 unsigned int cmds_started, tgts_started;
470 int ignoring = 0, in_ignored_define = 0;
471 int no_targets = 0; /* Set when reading a rule without targets. */
472 struct nameseq *filenames = 0;
473 struct dep *deps = 0;
474 long nlines = 0;
475 int two_colon = 0;
476 char *pattern = 0, *pattern_percent;
477 struct floc *fstart;
478 struct floc fi;
480 #define record_waiting_files() \
481 do \
483 if (filenames != 0) \
485 fi.lineno = tgts_started; \
486 record_files (filenames, pattern, pattern_percent, deps, \
487 cmds_started, commands, commands_idx, two_colon, \
488 &fi); \
490 filenames = 0; \
491 commands_idx = 0; \
492 no_targets = 0; \
493 if (pattern) { free(pattern); pattern = 0; } \
494 } while (0)
496 pattern_percent = 0;
497 cmds_started = tgts_started = 1;
499 fstart = &ebuf->floc;
500 fi.filenm = ebuf->floc.filenm;
502 /* Loop over lines in the file.
503 The strategy is to accumulate target names in FILENAMES, dependencies
504 in DEPS and commands in COMMANDS. These are used to define a rule
505 when the start of the next rule (or eof) is encountered.
507 When you see a "continue" in the loop below, that means we are moving on
508 to the next line _without_ ending any rule that we happen to be working
509 with at the moment. If you see a "goto rule_complete", then the
510 statement we just parsed also finishes the previous rule. */
512 commands = xmalloc (200);
514 while (1)
516 unsigned int linelen;
517 char *line;
518 int len;
519 char *p;
520 char *p2;
522 /* Grab the next line to be evaluated */
523 ebuf->floc.lineno += nlines;
524 nlines = readline (ebuf);
526 /* If there is nothing left to eval, we're done. */
527 if (nlines < 0)
528 break;
530 /* If this line is empty, skip it. */
531 line = ebuf->buffer;
532 if (line[0] == '\0')
533 continue;
535 linelen = strlen (line);
537 /* Check for a shell command line first.
538 If it is not one, we can stop treating tab specially. */
539 if (line[0] == '\t')
541 if (no_targets)
542 /* Ignore the commands in a rule with no targets. */
543 continue;
545 /* If there is no preceding rule line, don't treat this line
546 as a command, even though it begins with a tab character.
547 SunOS 4 make appears to behave this way. */
549 if (filenames != 0)
551 if (ignoring)
552 /* Yep, this is a shell command, and we don't care. */
553 continue;
555 /* Append this command line to the line being accumulated. */
556 if (commands_idx == 0)
557 cmds_started = ebuf->floc.lineno;
559 if (linelen + 1 + commands_idx > commands_len)
561 commands_len = (linelen + 1 + commands_idx) * 2;
562 commands = xrealloc (commands, commands_len);
564 bcopy (line, &commands[commands_idx], linelen);
565 commands_idx += linelen;
566 commands[commands_idx++] = '\n';
568 continue;
572 /* This line is not a shell command line. Don't worry about tabs.
573 Get more space if we need it; we don't need to preserve the current
574 contents of the buffer. */
576 if (collapsed_length < linelen+1)
578 collapsed_length = linelen+1;
579 if (collapsed)
580 free ((char *)collapsed);
581 collapsed = (char *) xmalloc (collapsed_length);
583 strcpy (collapsed, line);
584 /* Collapse continuation lines. */
585 collapse_continuations (collapsed);
586 remove_comments (collapsed);
588 /* Compare a word, both length and contents. */
589 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
590 p = collapsed;
591 while (isspace ((unsigned char)*p))
592 ++p;
594 if (*p == '\0')
595 /* This line is completely empty--ignore it. */
596 continue;
598 /* Find the end of the first token. Note we don't need to worry about
599 * ":" here since we compare tokens by length (so "export" will never
600 * be equal to "export:").
602 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
604 len = p2 - p;
606 /* Find the start of the second token. If it looks like a target or
607 variable definition it can't be a preprocessor token so skip
608 them--this allows variables/targets named `ifdef', `export', etc. */
609 while (isspace ((unsigned char)*p2))
610 ++p2;
612 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
614 /* It can't be a preprocessor token so skip it if we're ignoring */
615 if (ignoring)
616 continue;
618 goto skip_conditionals;
621 /* We must first check for conditional and `define' directives before
622 ignoring anything, since they control what we will do with
623 following lines. */
625 if (!in_ignored_define)
627 int i = conditional_line (p, len, fstart);
628 if (i != -2)
630 if (i == -1)
631 fatal (fstart, _("invalid syntax in conditional"));
633 ignoring = i;
634 continue;
638 if (word1eq ("endef"))
640 if (!in_ignored_define)
641 fatal (fstart, _("extraneous `endef'"));
642 in_ignored_define = 0;
643 continue;
646 if (word1eq ("define"))
648 if (ignoring)
649 in_ignored_define = 1;
650 else
652 if (*p2 == '\0')
653 fatal (fstart, _("empty variable name"));
655 /* Let the variable name be the whole rest of the line,
656 with trailing blanks stripped (comments have already been
657 removed), so it could be a complex variable/function
658 reference that might contain blanks. */
659 p = strchr (p2, '\0');
660 while (isblank ((unsigned char)p[-1]))
661 --p;
662 do_define (p2, p - p2, o_file, ebuf);
664 continue;
667 if (word1eq ("override"))
669 if (*p2 == '\0')
670 error (fstart, _("empty `override' directive"));
672 if (strneq (p2, "define", 6)
673 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
675 if (ignoring)
676 in_ignored_define = 1;
677 else
679 p2 = next_token (p2 + 6);
680 if (*p2 == '\0')
681 fatal (fstart, _("empty variable name"));
683 /* Let the variable name be the whole rest of the line,
684 with trailing blanks stripped (comments have already been
685 removed), so it could be a complex variable/function
686 reference that might contain blanks. */
687 p = strchr (p2, '\0');
688 while (isblank ((unsigned char)p[-1]))
689 --p;
690 do_define (p2, p - p2, o_override, ebuf);
693 else if (!ignoring
694 && !try_variable_definition (fstart, p2, o_override, 0))
695 error (fstart, _("invalid `override' directive"));
697 continue;
700 if (ignoring)
701 /* Ignore the line. We continue here so conditionals
702 can appear in the middle of a rule. */
703 continue;
705 if (word1eq ("export"))
707 /* 'export' by itself causes everything to be exported. */
708 if (*p2 == '\0')
709 export_all_variables = 1;
710 else
712 struct variable *v;
714 v = try_variable_definition (fstart, p2, o_file, 0);
715 if (v != 0)
716 v->export = v_export;
717 else
719 unsigned int len;
720 char *ap;
722 /* Expand the line so we can use indirect and constructed
723 variable names in an export command. */
724 p2 = ap = allocated_variable_expand (p2);
726 for (p = find_next_token (&p2, &len); p != 0;
727 p = find_next_token (&p2, &len))
729 v = lookup_variable (p, len);
730 if (v == 0)
731 v = define_variable_loc (p, len, "", o_file, 0,
732 fstart);
733 v->export = v_export;
736 free (ap);
739 goto rule_complete;
742 if (word1eq ("unexport"))
744 if (*p2 == '\0')
745 export_all_variables = 0;
746 else
748 unsigned int len;
749 struct variable *v;
750 char *ap;
752 /* Expand the line so we can use indirect and constructed
753 variable names in an unexport command. */
754 p2 = ap = allocated_variable_expand (p2);
756 for (p = find_next_token (&p2, &len); p != 0;
757 p = find_next_token (&p2, &len))
759 v = lookup_variable (p, len);
760 if (v == 0)
761 v = define_variable_loc (p, len, "", o_file, 0, fstart);
763 v->export = v_noexport;
766 free (ap);
768 goto rule_complete;
771 skip_conditionals:
772 if (word1eq ("vpath"))
774 char *pattern;
775 unsigned int len;
776 p2 = variable_expand (p2);
777 p = find_next_token (&p2, &len);
778 if (p != 0)
780 pattern = savestring (p, len);
781 p = find_next_token (&p2, &len);
782 /* No searchpath means remove all previous
783 selective VPATH's with the same pattern. */
785 else
786 /* No pattern means remove all previous selective VPATH's. */
787 pattern = 0;
788 construct_vpath_list (pattern, p);
789 if (pattern != 0)
790 free (pattern);
792 goto rule_complete;
795 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
797 /* We have found an `include' line specifying a nested
798 makefile to be read at this point. */
799 struct conditionals *save;
800 struct conditionals new_conditionals;
801 struct nameseq *files;
802 /* "-include" (vs "include") says no error if the file does not
803 exist. "sinclude" is an alias for this from SGI. */
804 int noerror = (p[0] != 'i');
806 p = allocated_variable_expand (p2);
808 /* If no filenames, it's a no-op. */
809 if (*p == '\0')
811 free (p);
812 continue;
815 /* Parse the list of file names. */
816 p2 = p;
817 files = multi_glob (parse_file_seq (&p2, '\0',
818 sizeof (struct nameseq),
820 sizeof (struct nameseq));
821 free (p);
823 /* Save the state of conditionals and start
824 the included makefile with a clean slate. */
825 save = install_conditionals (&new_conditionals);
827 /* Record the rules that are waiting so they will determine
828 the default goal before those in the included makefile. */
829 record_waiting_files ();
831 /* Read each included makefile. */
832 while (files != 0)
834 struct nameseq *next = files->next;
835 char *name = files->name;
836 int r;
838 free ((char *)files);
839 files = next;
841 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
842 | (noerror ? RM_DONTCARE : 0)));
843 if (!r && !noerror)
844 error (fstart, "%s: %s", name, strerror (errno));
845 free (name);
848 /* Restore conditional state. */
849 restore_conditionals (save);
851 goto rule_complete;
854 if (try_variable_definition (fstart, p, o_file, 0))
855 /* This line has been dealt with. */
856 goto rule_complete;
858 /* This line starts with a tab but was not caught above because there
859 was no preceding target, and the line might have been usable as a
860 variable definition. But now we know it is definitely lossage. */
861 if (line[0] == '\t')
862 fatal(fstart, _("commands commence before first target"));
864 /* This line describes some target files. This is complicated by
865 the existence of target-specific variables, because we can't
866 expand the entire line until we know if we have one or not. So
867 we expand the line word by word until we find the first `:',
868 then check to see if it's a target-specific variable.
870 In this algorithm, `lb_next' will point to the beginning of the
871 unexpanded parts of the input buffer, while `p2' points to the
872 parts of the expanded buffer we haven't searched yet. */
875 enum make_word_type wtype;
876 enum variable_origin v_origin;
877 int exported;
878 char *cmdleft, *semip, *lb_next;
879 unsigned int len, plen = 0;
880 char *colonp;
881 const char *end, *beg; /* Helpers for whitespace stripping. */
883 /* Record the previous rule. */
885 record_waiting_files ();
886 tgts_started = fstart->lineno;
888 /* Search the line for an unquoted ; that is not after an
889 unquoted #. */
890 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
891 if (cmdleft != 0 && *cmdleft == '#')
893 /* We found a comment before a semicolon. */
894 *cmdleft = '\0';
895 cmdleft = 0;
897 else if (cmdleft != 0)
898 /* Found one. Cut the line short there before expanding it. */
899 *(cmdleft++) = '\0';
900 semip = cmdleft;
902 collapse_continuations (line);
904 /* We can't expand the entire line, since if it's a per-target
905 variable we don't want to expand it. So, walk from the
906 beginning, expanding as we go, and looking for "interesting"
907 chars. The first word is always expandable. */
908 wtype = get_next_mword(line, NULL, &lb_next, &len);
909 switch (wtype)
911 case w_eol:
912 if (cmdleft != 0)
913 fatal(fstart, _("missing rule before commands"));
914 /* This line contained something but turned out to be nothing
915 but whitespace (a comment?). */
916 continue;
918 case w_colon:
919 case w_dcolon:
920 /* We accept and ignore rules without targets for
921 compatibility with SunOS 4 make. */
922 no_targets = 1;
923 continue;
925 default:
926 break;
929 p2 = variable_expand_string(NULL, lb_next, len);
931 while (1)
933 lb_next += len;
934 if (cmdleft == 0)
936 /* Look for a semicolon in the expanded line. */
937 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
939 if (cmdleft != 0)
941 unsigned long p2_off = p2 - variable_buffer;
942 unsigned long cmd_off = cmdleft - variable_buffer;
943 char *pend = p2 + strlen(p2);
945 /* Append any remnants of lb, then cut the line short
946 at the semicolon. */
947 *cmdleft = '\0';
949 /* One school of thought says that you shouldn't expand
950 here, but merely copy, since now you're beyond a ";"
951 and into a command script. However, the old parser
952 expanded the whole line, so we continue that for
953 backwards-compatiblity. Also, it wouldn't be
954 entirely consistent, since we do an unconditional
955 expand below once we know we don't have a
956 target-specific variable. */
957 (void)variable_expand_string(pend, lb_next, (long)-1);
958 lb_next += strlen(lb_next);
959 p2 = variable_buffer + p2_off;
960 cmdleft = variable_buffer + cmd_off + 1;
964 colonp = find_char_unquote(p2, ':', 0, 0, 0);
965 #ifdef HAVE_DOS_PATHS
966 /* The drive spec brain-damage strikes again... */
967 /* Note that the only separators of targets in this context
968 are whitespace and a left paren. If others are possible,
969 they should be added to the string in the call to index. */
970 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
971 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
972 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
973 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
974 #endif
975 if (colonp != 0)
976 break;
978 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
979 if (wtype == w_eol)
980 break;
982 p2 += strlen(p2);
983 *(p2++) = ' ';
984 p2 = variable_expand_string(p2, lb_next, len);
985 /* We don't need to worry about cmdleft here, because if it was
986 found in the variable_buffer the entire buffer has already
987 been expanded... we'll never get here. */
990 p2 = next_token (variable_buffer);
992 /* If the word we're looking at is EOL, see if there's _anything_
993 on the line. If not, a variable expanded to nothing, so ignore
994 it. If so, we can't parse this line so punt. */
995 if (wtype == w_eol)
997 if (*p2 != '\0')
998 /* There's no need to be ivory-tower about this: check for
999 one of the most common bugs found in makefiles... */
1000 fatal (fstart, _("missing separator%s"),
1001 !strneq(line, " ", 8) ? ""
1002 : _(" (did you mean TAB instead of 8 spaces?)"));
1003 continue;
1006 /* Make the colon the end-of-string so we know where to stop
1007 looking for targets. */
1008 *colonp = '\0';
1009 filenames = multi_glob (parse_file_seq (&p2, '\0',
1010 sizeof (struct nameseq),
1012 sizeof (struct nameseq));
1013 *p2 = ':';
1015 if (!filenames)
1017 /* We accept and ignore rules without targets for
1018 compatibility with SunOS 4 make. */
1019 no_targets = 1;
1020 continue;
1022 /* This should never be possible; we handled it above. */
1023 assert (*p2 != '\0');
1024 ++p2;
1026 /* Is this a one-colon or two-colon entry? */
1027 two_colon = *p2 == ':';
1028 if (two_colon)
1029 p2++;
1031 /* Test to see if it's a target-specific variable. Copy the rest
1032 of the buffer over, possibly temporarily (we'll expand it later
1033 if it's not a target-specific variable). PLEN saves the length
1034 of the unparsed section of p2, for later. */
1035 if (*lb_next != '\0')
1037 unsigned int l = p2 - variable_buffer;
1038 plen = strlen (p2);
1039 (void) variable_buffer_output (p2+plen,
1040 lb_next, strlen (lb_next)+1);
1041 p2 = variable_buffer + l;
1044 /* See if it's an "override" or "export" keyword; if so see if what
1045 comes after it looks like a variable definition. */
1047 wtype = get_next_mword (p2, NULL, &p, &len);
1049 v_origin = o_file;
1050 exported = 0;
1051 if (wtype == w_static)
1053 if (word1eq ("override"))
1055 v_origin = o_override;
1056 wtype = get_next_mword (p+len, NULL, &p, &len);
1058 else if (word1eq ("export"))
1060 exported = 1;
1061 wtype = get_next_mword (p+len, NULL, &p, &len);
1065 if (wtype != w_eol)
1066 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1068 if (wtype == w_varassign)
1070 /* If there was a semicolon found, add it back, plus anything
1071 after it. */
1072 if (semip)
1074 unsigned int l = p - variable_buffer;
1075 *(--semip) = ';';
1076 variable_buffer_output (p2 + strlen (p2),
1077 semip, strlen (semip)+1);
1078 p = variable_buffer + l;
1080 record_target_var (filenames, p, v_origin, exported, fstart);
1081 filenames = 0;
1082 continue;
1085 /* This is a normal target, _not_ a target-specific variable.
1086 Unquote any = in the dependency list. */
1087 find_char_unquote (lb_next, '=', 0, 0, 0);
1089 /* We have some targets, so don't ignore the following commands. */
1090 no_targets = 0;
1092 /* Expand the dependencies, etc. */
1093 if (*lb_next != '\0')
1095 unsigned int l = p2 - variable_buffer;
1096 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1097 p2 = variable_buffer + l;
1099 /* Look for a semicolon in the expanded line. */
1100 if (cmdleft == 0)
1102 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1103 if (cmdleft != 0)
1104 *(cmdleft++) = '\0';
1108 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1109 p = strchr (p2, ':');
1110 while (p != 0 && p[-1] == '\\')
1112 register char *q = &p[-1];
1113 register int backslash = 0;
1114 while (*q-- == '\\')
1115 backslash = !backslash;
1116 if (backslash)
1117 p = strchr (p + 1, ':');
1118 else
1119 break;
1121 #ifdef _AMIGA
1122 /* Here, the situation is quite complicated. Let's have a look
1123 at a couple of targets:
1125 install: dev:make
1127 dev:make: make
1129 dev:make:: xyz
1131 The rule is that it's only a target, if there are TWO :'s
1132 OR a space around the :.
1134 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1135 || isspace ((unsigned char)p[-1])))
1136 p = 0;
1137 #endif
1138 #ifdef HAVE_DOS_PATHS
1140 int check_again;
1142 do {
1143 check_again = 0;
1144 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1145 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1146 isalpha ((unsigned char)p[-1]) &&
1147 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1148 p = strchr (p + 1, ':');
1149 check_again = 1;
1151 } while (check_again);
1153 #endif
1154 if (p != 0)
1156 struct nameseq *target;
1157 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1158 ++p2;
1159 if (target == 0)
1160 fatal (fstart, _("missing target pattern"));
1161 else if (target->next != 0)
1162 fatal (fstart, _("multiple target patterns"));
1163 pattern = target->name;
1164 pattern_percent = find_percent (pattern);
1165 if (pattern_percent == 0)
1166 fatal (fstart, _("target pattern contains no `%%'"));
1167 free ((char *)target);
1169 else
1170 pattern = 0;
1172 /* Strip leading and trailing whitespaces. */
1173 beg = p2;
1174 end = beg + strlen (beg) - 1;
1175 strip_whitespace (&beg, &end);
1177 if (beg <= end && *beg != '\0')
1179 /* Put all the prerequisites here; they'll be parsed later. */
1180 deps = (struct dep *) xmalloc (sizeof (struct dep));
1181 deps->next = 0;
1182 deps->name = savestring (beg, end - beg + 1);
1183 deps->file = 0;
1184 deps->changed = 0;
1185 deps->ignore_mtime = 0;
1186 deps->staticpattern = 0;
1187 deps->need_2nd_expansion = 0;
1189 else
1190 deps = 0;
1192 commands_idx = 0;
1193 if (cmdleft != 0)
1195 /* Semicolon means rest of line is a command. */
1196 unsigned int len = strlen (cmdleft);
1198 cmds_started = fstart->lineno;
1200 /* Add this command line to the buffer. */
1201 if (len + 2 > commands_len)
1203 commands_len = (len + 2) * 2;
1204 commands = (char *) xrealloc (commands, commands_len);
1206 bcopy (cmdleft, commands, len);
1207 commands_idx += len;
1208 commands[commands_idx++] = '\n';
1211 /* Determine if this target should be made default. We used to do
1212 this in record_files() but because of the delayed target recording
1213 and because preprocessor directives are legal in target's commands
1214 it is too late. Consider this fragment for example:
1216 foo:
1218 ifeq ($(.DEFAULT_GOAL),foo)
1220 endif
1222 Because the target is not recorded until after ifeq directive is
1223 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1224 would expect. Because of this we have to move some of the logic
1225 here. */
1227 if (**default_goal_name == '\0' && set_default)
1229 char* name;
1230 struct dep *d;
1231 struct nameseq *t = filenames;
1233 for (; t != 0; t = t->next)
1235 int reject = 0;
1236 name = t->name;
1238 /* We have nothing to do if this is an implicit rule. */
1239 if (strchr (name, '%') != 0)
1240 break;
1242 /* See if this target's name does not start with a `.',
1243 unless it contains a slash. */
1244 if (*name == '.' && strchr (name, '/') == 0
1245 #ifdef HAVE_DOS_PATHS
1246 && strchr (name, '\\') == 0
1247 #endif
1249 continue;
1252 /* If this file is a suffix, don't let it be
1253 the default goal file. */
1254 for (d = suffix_file->deps; d != 0; d = d->next)
1256 register struct dep *d2;
1257 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1259 reject = 1;
1260 break;
1262 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1264 register unsigned int len = strlen (dep_name (d2));
1265 if (!strneq (name, dep_name (d2), len))
1266 continue;
1267 if (streq (name + len, dep_name (d)))
1269 reject = 1;
1270 break;
1274 if (reject)
1275 break;
1278 if (!reject)
1280 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1281 o_file, 0, NILF);
1282 break;
1287 continue;
1290 /* We get here except in the case that we just read a rule line.
1291 Record now the last rule we read, so following spurious
1292 commands are properly diagnosed. */
1293 rule_complete:
1294 record_waiting_files ();
1297 #undef word1eq
1299 if (conditionals->if_cmds)
1300 fatal (fstart, _("missing `endif'"));
1302 /* At eof, record the last rule. */
1303 record_waiting_files ();
1305 if (collapsed)
1306 free ((char *) collapsed);
1307 free ((char *) commands);
1309 return 1;
1313 /* Remove comments from LINE.
1314 This is done by copying the text at LINE onto itself. */
1316 static void
1317 remove_comments (char *line)
1319 char *comment;
1321 comment = find_char_unquote (line, '#', 0, 0, 0);
1323 if (comment != 0)
1324 /* Cut off the line at the #. */
1325 *comment = '\0';
1328 /* Execute a `define' directive.
1329 The first line has already been read, and NAME is the name of
1330 the variable to be defined. The following lines remain to be read. */
1332 static void
1333 do_define (char *name, unsigned int namelen,
1334 enum variable_origin origin, struct ebuffer *ebuf)
1336 struct floc defstart;
1337 long nlines = 0;
1338 int nlevels = 1;
1339 unsigned int length = 100;
1340 char *definition = (char *) xmalloc (length);
1341 unsigned int idx = 0;
1342 char *p;
1344 /* Expand the variable name. */
1345 char *var = (char *) alloca (namelen + 1);
1346 bcopy (name, var, namelen);
1347 var[namelen] = '\0';
1348 var = variable_expand (var);
1350 defstart = ebuf->floc;
1352 while (1)
1354 unsigned int len;
1355 char *line;
1357 nlines = readline (ebuf);
1358 ebuf->floc.lineno += nlines;
1360 /* If there is nothing left to eval, we're done. */
1361 if (nlines < 0)
1362 break;
1364 line = ebuf->buffer;
1366 collapse_continuations (line);
1368 /* If the line doesn't begin with a tab, test to see if it introduces
1369 another define, or ends one. */
1371 /* Stop if we find an 'endef' */
1372 if (line[0] != '\t')
1374 p = next_token (line);
1375 len = strlen (p);
1377 /* If this is another 'define', increment the level count. */
1378 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1379 && strneq (p, "define", 6))
1380 ++nlevels;
1382 /* If this is an 'endef', decrement the count. If it's now 0,
1383 we've found the last one. */
1384 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1385 && strneq (p, "endef", 5))
1387 p += 5;
1388 remove_comments (p);
1389 if (*next_token (p) != '\0')
1390 error (&ebuf->floc,
1391 _("Extraneous text after `endef' directive"));
1393 if (--nlevels == 0)
1395 /* Define the variable. */
1396 if (idx == 0)
1397 definition[0] = '\0';
1398 else
1399 definition[idx - 1] = '\0';
1401 /* Always define these variables in the global set. */
1402 define_variable_global (var, strlen (var), definition,
1403 origin, 1, &defstart);
1404 free (definition);
1405 return;
1410 /* Otherwise add this line to the variable definition. */
1411 len = strlen (line);
1412 if (idx + len + 1 > length)
1414 length = (idx + len) * 2;
1415 definition = (char *) xrealloc (definition, length + 1);
1418 bcopy (line, &definition[idx], len);
1419 idx += len;
1420 /* Separate lines with a newline. */
1421 definition[idx++] = '\n';
1424 /* No `endef'!! */
1425 fatal (&defstart, _("missing `endef', unterminated `define'"));
1427 /* NOTREACHED */
1428 return;
1431 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1432 "ifneq", "else" and "endif".
1433 LINE is the input line, with the command as its first word.
1435 FILENAME and LINENO are the filename and line number in the
1436 current makefile. They are used for error messages.
1438 Value is -2 if the line is not a conditional at all,
1439 -1 if the line is an invalid conditional,
1440 0 if following text should be interpreted,
1441 1 if following text should be ignored. */
1443 static int
1444 conditional_line (char *line, int len, const struct floc *flocp)
1446 char *cmdname;
1447 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1448 unsigned int i;
1449 unsigned int o;
1451 /* Compare a word, both length and contents. */
1452 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1453 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1455 /* Make sure this line is a conditional. */
1456 chkword ("ifdef", c_ifdef)
1457 else chkword ("ifndef", c_ifndef)
1458 else chkword ("ifeq", c_ifeq)
1459 else chkword ("ifneq", c_ifneq)
1460 else chkword ("else", c_else)
1461 else chkword ("endif", c_endif)
1462 else
1463 return -2;
1465 /* Found one: skip past it and any whitespace after it. */
1466 line = next_token (line + len);
1468 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1470 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1471 if (cmdtype == c_endif)
1473 if (*line != '\0')
1474 EXTRANEOUS ();
1476 if (!conditionals->if_cmds)
1477 fatal (flocp, _("extraneous `%s'"), cmdname);
1479 --conditionals->if_cmds;
1481 goto DONE;
1484 /* An 'else' statement can either be simple, or it can have another
1485 conditional after it. */
1486 if (cmdtype == c_else)
1488 const char *p;
1490 if (!conditionals->if_cmds)
1491 fatal (flocp, _("extraneous `%s'"), cmdname);
1493 o = conditionals->if_cmds - 1;
1495 if (conditionals->seen_else[o])
1496 fatal (flocp, _("only one `else' per conditional"));
1498 /* Change the state of ignorance. */
1499 switch (conditionals->ignoring[o])
1501 case 0:
1502 /* We've just been interpreting. Never do it again. */
1503 conditionals->ignoring[o] = 2;
1504 break;
1505 case 1:
1506 /* We've never interpreted yet. Maybe this time! */
1507 conditionals->ignoring[o] = 0;
1508 break;
1511 /* It's a simple 'else'. */
1512 if (*line == '\0')
1514 conditionals->seen_else[o] = 1;
1515 goto DONE;
1518 /* The 'else' has extra text. That text must be another conditional
1519 and cannot be an 'else' or 'endif'. */
1521 /* Find the length of the next word. */
1522 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1524 len = p - line;
1526 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1527 if (word1eq("else") || word1eq("endif")
1528 || conditional_line (line, len, flocp) < 0)
1529 EXTRANEOUS ();
1530 else
1532 /* conditional_line() created a new level of conditional.
1533 Raise it back to this level. */
1534 if (conditionals->ignoring[o] < 2)
1535 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1536 --conditionals->if_cmds;
1539 goto DONE;
1542 if (conditionals->allocated == 0)
1544 conditionals->allocated = 5;
1545 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1546 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1549 o = conditionals->if_cmds++;
1550 if (conditionals->if_cmds > conditionals->allocated)
1552 conditionals->allocated += 5;
1553 conditionals->ignoring = (char *)
1554 xrealloc (conditionals->ignoring, conditionals->allocated);
1555 conditionals->seen_else = (char *)
1556 xrealloc (conditionals->seen_else, conditionals->allocated);
1559 /* Record that we have seen an `if...' but no `else' so far. */
1560 conditionals->seen_else[o] = 0;
1562 /* Search through the stack to see if we're already ignoring. */
1563 for (i = 0; i < o; ++i)
1564 if (conditionals->ignoring[i])
1566 /* We are already ignoring, so just push a level to match the next
1567 "else" or "endif", and keep ignoring. We don't want to expand
1568 variables in the condition. */
1569 conditionals->ignoring[o] = 1;
1570 return 1;
1573 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1575 char *var;
1576 struct variable *v;
1577 char *p;
1579 /* Expand the thing we're looking up, so we can use indirect and
1580 constructed variable names. */
1581 var = allocated_variable_expand (line);
1583 /* Make sure there's only one variable name to test. */
1584 p = end_of_token (var);
1585 i = p - var;
1586 p = next_token (p);
1587 if (*p != '\0')
1588 return -1;
1590 var[i] = '\0';
1591 v = lookup_variable (var, i);
1593 conditionals->ignoring[o] =
1594 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1596 free (var);
1598 else
1600 /* "Ifeq" or "ifneq". */
1601 char *s1, *s2;
1602 unsigned int len;
1603 char termin = *line == '(' ? ',' : *line;
1605 if (termin != ',' && termin != '"' && termin != '\'')
1606 return -1;
1608 s1 = ++line;
1609 /* Find the end of the first string. */
1610 if (termin == ',')
1612 int count = 0;
1613 for (; *line != '\0'; ++line)
1614 if (*line == '(')
1615 ++count;
1616 else if (*line == ')')
1617 --count;
1618 else if (*line == ',' && count <= 0)
1619 break;
1621 else
1622 while (*line != '\0' && *line != termin)
1623 ++line;
1625 if (*line == '\0')
1626 return -1;
1628 if (termin == ',')
1630 /* Strip blanks after the first string. */
1631 char *p = line++;
1632 while (isblank ((unsigned char)p[-1]))
1633 --p;
1634 *p = '\0';
1636 else
1637 *line++ = '\0';
1639 s2 = variable_expand (s1);
1640 /* We must allocate a new copy of the expanded string because
1641 variable_expand re-uses the same buffer. */
1642 len = strlen (s2);
1643 s1 = (char *) alloca (len + 1);
1644 bcopy (s2, s1, len + 1);
1646 if (termin != ',')
1647 /* Find the start of the second string. */
1648 line = next_token (line);
1650 termin = termin == ',' ? ')' : *line;
1651 if (termin != ')' && termin != '"' && termin != '\'')
1652 return -1;
1654 /* Find the end of the second string. */
1655 if (termin == ')')
1657 register int count = 0;
1658 s2 = next_token (line);
1659 for (line = s2; *line != '\0'; ++line)
1661 if (*line == '(')
1662 ++count;
1663 else if (*line == ')')
1665 if (count <= 0)
1666 break;
1667 else
1668 --count;
1672 else
1674 ++line;
1675 s2 = line;
1676 while (*line != '\0' && *line != termin)
1677 ++line;
1680 if (*line == '\0')
1681 return -1;
1683 *line = '\0';
1684 line = next_token (++line);
1685 if (*line != '\0')
1686 EXTRANEOUS ();
1688 s2 = variable_expand (s2);
1689 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1692 DONE:
1693 /* Search through the stack to see if we're ignoring. */
1694 for (i = 0; i < conditionals->if_cmds; ++i)
1695 if (conditionals->ignoring[i])
1696 return 1;
1697 return 0;
1700 /* Remove duplicate dependencies in CHAIN. */
1702 static unsigned long
1703 dep_hash_1 (const void *key)
1705 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1708 static unsigned long
1709 dep_hash_2 (const void *key)
1711 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1714 static int
1715 dep_hash_cmp (const void *x, const void *y)
1717 struct dep *dx = (struct dep *) x;
1718 struct dep *dy = (struct dep *) y;
1719 int cmp = strcmp (dep_name (dx), dep_name (dy));
1721 /* If the names are the same but ignore_mtimes are not equal, one of these
1722 is an order-only prerequisite and one isn't. That means that we should
1723 remove the one that isn't and keep the one that is. */
1725 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1726 dx->ignore_mtime = dy->ignore_mtime = 0;
1728 return cmp;
1732 void
1733 uniquize_deps (struct dep *chain)
1735 struct hash_table deps;
1736 register struct dep **depp;
1738 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1740 /* Make sure that no dependencies are repeated. This does not
1741 really matter for the purpose of updating targets, but it
1742 might make some names be listed twice for $^ and $?. */
1744 depp = &chain;
1745 while (*depp)
1747 struct dep *dep = *depp;
1748 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1749 if (HASH_VACANT (*dep_slot))
1751 hash_insert_at (&deps, dep, dep_slot);
1752 depp = &dep->next;
1754 else
1756 /* Don't bother freeing duplicates.
1757 It's dangerous and little benefit accrues. */
1758 *depp = dep->next;
1762 hash_free (&deps, 0);
1765 /* Record target-specific variable values for files FILENAMES.
1766 TWO_COLON is nonzero if a double colon was used.
1768 The links of FILENAMES are freed, and so are any names in it
1769 that are not incorporated into other data structures.
1771 If the target is a pattern, add the variable to the pattern-specific
1772 variable value list. */
1774 static void
1775 record_target_var (struct nameseq *filenames, char *defn,
1776 enum variable_origin origin, int exported,
1777 const struct floc *flocp)
1779 struct nameseq *nextf;
1780 struct variable_set_list *global;
1782 global = current_variable_set_list;
1784 /* If the variable is an append version, store that but treat it as a
1785 normal recursive variable. */
1787 for (; filenames != 0; filenames = nextf)
1789 struct variable *v;
1790 register char *name = filenames->name;
1791 char *fname;
1792 char *percent;
1793 struct pattern_var *p;
1795 nextf = filenames->next;
1796 free ((char *) filenames);
1798 /* If it's a pattern target, then add it to the pattern-specific
1799 variable list. */
1800 percent = find_percent (name);
1801 if (percent)
1803 /* Get a reference for this pattern-specific variable struct. */
1804 p = create_pattern_var (name, percent);
1805 p->variable.fileinfo = *flocp;
1806 /* I don't think this can fail since we already determined it was a
1807 variable definition. */
1808 v = parse_variable_definition (&p->variable, defn);
1809 assert (v != 0);
1811 if (v->flavor == f_simple)
1812 v->value = allocated_variable_expand (v->value);
1813 else
1814 v->value = xstrdup (v->value);
1816 fname = p->target;
1818 else
1820 struct file *f;
1822 /* Get a file reference for this file, and initialize it.
1823 We don't want to just call enter_file() because that allocates a
1824 new entry if the file is a double-colon, which we don't want in
1825 this situation. */
1826 f = lookup_file (name);
1827 if (!f)
1828 f = enter_file (name);
1829 else if (f->double_colon)
1830 f = f->double_colon;
1832 initialize_file_variables (f, 1);
1833 fname = f->name;
1835 current_variable_set_list = f->variables;
1836 v = try_variable_definition (flocp, defn, origin, 1);
1837 if (!v)
1838 error (flocp, _("Malformed target-specific variable definition"));
1839 current_variable_set_list = global;
1842 /* Set up the variable to be *-specific. */
1843 v->origin = origin;
1844 v->per_target = 1;
1845 v->export = exported ? v_export : v_default;
1847 /* If it's not an override, check to see if there was a command-line
1848 setting. If so, reset the value. */
1849 if (origin != o_override)
1851 struct variable *gv;
1852 int len = strlen(v->name);
1854 gv = lookup_variable (v->name, len);
1855 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1857 if (v->value != 0)
1858 free (v->value);
1859 v->value = xstrdup (gv->value);
1860 v->origin = gv->origin;
1861 v->recursive = gv->recursive;
1862 v->append = 0;
1866 /* Free name if not needed further. */
1867 if (name != fname && (name < fname || name > fname + strlen (fname)))
1868 free (name);
1872 /* Record a description line for files FILENAMES,
1873 with dependencies DEPS, commands to execute described
1874 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1875 TWO_COLON is nonzero if a double colon was used.
1876 If not nil, PATTERN is the `%' pattern to make this
1877 a static pattern rule, and PATTERN_PERCENT is a pointer
1878 to the `%' within it.
1880 The links of FILENAMES are freed, and so are any names in it
1881 that are not incorporated into other data structures. */
1883 static void
1884 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1885 struct dep *deps, unsigned int cmds_started, char *commands,
1886 unsigned int commands_idx, int two_colon,
1887 const struct floc *flocp)
1889 struct nameseq *nextf;
1890 int implicit = 0;
1891 unsigned int max_targets = 0, target_idx = 0;
1892 char **targets = 0, **target_percents = 0;
1893 struct commands *cmds;
1895 /* If we've already snapped deps, that means we're in an eval being
1896 resolved after the makefiles have been read in. We can't add more rules
1897 at this time, since they won't get snapped and we'll get core dumps.
1898 See Savannah bug # 12124. */
1899 if (snapped_deps)
1900 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1902 if (commands_idx > 0)
1904 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1905 cmds->fileinfo.filenm = flocp->filenm;
1906 cmds->fileinfo.lineno = cmds_started;
1907 cmds->commands = savestring (commands, commands_idx);
1908 cmds->command_lines = 0;
1910 else
1911 cmds = 0;
1913 for (; filenames != 0; filenames = nextf)
1915 char *name = filenames->name;
1916 struct file *f;
1917 struct dep *this = 0;
1918 char *implicit_percent;
1920 nextf = filenames->next;
1921 free (filenames);
1923 /* Check for special targets. Do it here instead of, say, snap_deps()
1924 so that we can immediately use the value. */
1926 if (streq (name, ".POSIX"))
1927 posix_pedantic = 1;
1928 else if (streq (name, ".SECONDEXPANSION"))
1929 second_expansion = 1;
1931 implicit_percent = find_percent (name);
1932 implicit |= implicit_percent != 0;
1934 if (implicit && pattern != 0)
1935 fatal (flocp, _("mixed implicit and static pattern rules"));
1937 if (implicit && implicit_percent == 0)
1938 fatal (flocp, _("mixed implicit and normal rules"));
1940 if (implicit)
1942 if (targets == 0)
1944 max_targets = 5;
1945 targets = (char **) xmalloc (5 * sizeof (char *));
1946 target_percents = (char **) xmalloc (5 * sizeof (char *));
1947 target_idx = 0;
1949 else if (target_idx == max_targets - 1)
1951 max_targets += 5;
1952 targets = (char **) xrealloc ((char *) targets,
1953 max_targets * sizeof (char *));
1954 target_percents
1955 = (char **) xrealloc ((char *) target_percents,
1956 max_targets * sizeof (char *));
1958 targets[target_idx] = name;
1959 target_percents[target_idx] = implicit_percent;
1960 ++target_idx;
1961 continue;
1964 /* If this is a static pattern rule:
1965 `targets: target%pattern: dep%pattern; cmds',
1966 make sure the pattern matches this target name. */
1967 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1968 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1969 else if (deps)
1971 /* If there are multiple filenames, copy the chain DEPS for all but
1972 the last one. It is not safe for the same deps to go in more
1973 than one place in the database. */
1974 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1975 this->need_2nd_expansion = (second_expansion
1976 && strchr (this->name, '$'));
1979 if (!two_colon)
1981 /* Single-colon. Combine these dependencies
1982 with others in file's existing record, if any. */
1983 f = enter_file (name);
1985 if (f->double_colon)
1986 fatal (flocp,
1987 _("target file `%s' has both : and :: entries"), f->name);
1989 /* If CMDS == F->CMDS, this target was listed in this rule
1990 more than once. Just give a warning since this is harmless. */
1991 if (cmds != 0 && cmds == f->cmds)
1992 error (flocp,
1993 _("target `%s' given more than once in the same rule."),
1994 f->name);
1996 /* Check for two single-colon entries both with commands.
1997 Check is_target so that we don't lose on files such as .c.o
1998 whose commands were preinitialized. */
1999 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2001 error (&cmds->fileinfo,
2002 _("warning: overriding commands for target `%s'"),
2003 f->name);
2004 error (&f->cmds->fileinfo,
2005 _("warning: ignoring old commands for target `%s'"),
2006 f->name);
2009 f->is_target = 1;
2011 /* Defining .DEFAULT with no deps or cmds clears it. */
2012 if (f == default_file && this == 0 && cmds == 0)
2013 f->cmds = 0;
2014 if (cmds != 0)
2015 f->cmds = cmds;
2017 /* Defining .SUFFIXES with no dependencies clears out the list of
2018 suffixes. */
2019 if (f == suffix_file && this == 0)
2021 free_dep_chain (f->deps);
2022 f->deps = 0;
2024 else if (this != 0)
2026 /* Add the file's old deps and the new ones in THIS together. */
2028 if (f->deps != 0)
2030 struct dep **d_ptr = &f->deps;
2032 while ((*d_ptr)->next != 0)
2033 d_ptr = &(*d_ptr)->next;
2035 if (cmds != 0)
2036 /* This is the rule with commands, so put its deps
2037 last. The rationale behind this is that $< expands to
2038 the first dep in the chain, and commands use $<
2039 expecting to get the dep that rule specifies. However
2040 the second expansion algorithm reverses the order thus
2041 we need to make it last here. */
2042 (*d_ptr)->next = this;
2043 else
2045 /* This is the rule without commands. Put its
2046 dependencies at the end but before dependencies from
2047 the rule with commands (if any). This way everything
2048 appears in makefile order. */
2050 if (f->cmds != 0)
2052 this->next = *d_ptr;
2053 *d_ptr = this;
2055 else
2056 (*d_ptr)->next = this;
2059 else
2060 f->deps = this;
2062 /* This is a hack. I need a way to communicate to snap_deps()
2063 that the last dependency line in this file came with commands
2064 (so that logic in snap_deps() can put it in front and all
2065 this $< -logic works). I cannot simply rely on file->cmds
2066 being not 0 because of the cases like the following:
2068 foo: bar
2069 foo:
2072 I am going to temporarily "borrow" UPDATING member in
2073 `struct file' for this. */
2075 if (cmds != 0)
2076 f->updating = 1;
2079 else
2081 /* Double-colon. Make a new record even if there already is one. */
2082 f = lookup_file (name);
2084 /* Check for both : and :: rules. Check is_target so
2085 we don't lose on default suffix rules or makefiles. */
2086 if (f != 0 && f->is_target && !f->double_colon)
2087 fatal (flocp,
2088 _("target file `%s' has both : and :: entries"), f->name);
2089 f = enter_file (name);
2090 /* If there was an existing entry and it was a double-colon entry,
2091 enter_file will have returned a new one, making it the prev
2092 pointer of the old one, and setting its double_colon pointer to
2093 the first one. */
2094 if (f->double_colon == 0)
2095 /* This is the first entry for this name, so we must set its
2096 double_colon pointer to itself. */
2097 f->double_colon = f;
2098 f->is_target = 1;
2099 f->deps = this;
2100 f->cmds = cmds;
2103 /* If this is a static pattern rule, set the stem to the part of its
2104 name that matched the `%' in the pattern, so you can use $* in the
2105 commands. */
2106 if (pattern)
2108 static char *percent = "%";
2109 char *buffer = variable_expand ("");
2110 char *o = patsubst_expand (buffer, name, pattern, percent,
2111 pattern_percent+1, percent+1);
2112 f->stem = savestring (buffer, o - buffer);
2113 if (this)
2114 this->staticpattern = 1;
2117 /* Free name if not needed further. */
2118 if (f != 0 && name != f->name
2119 && (name < f->name || name > f->name + strlen (f->name)))
2121 free (name);
2122 name = f->name;
2125 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2126 if (streq (*default_goal_name, name)
2127 && (default_goal_file == 0
2128 || ! streq (default_goal_file->name, name)))
2129 default_goal_file = f;
2132 if (implicit)
2134 targets[target_idx] = 0;
2135 target_percents[target_idx] = 0;
2136 if (deps)
2137 deps->need_2nd_expansion = second_expansion;
2138 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2139 free ((char *) target_percents);
2143 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2144 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2145 Quoting backslashes are removed from STRING by compacting it into
2146 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2147 one, or nil if there are none. STOPCHARs inside variable references are
2148 ignored if IGNOREVARS is true.
2150 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2152 static char *
2153 find_char_unquote (char *string, int stop1, int stop2, int blank,
2154 int ignorevars)
2156 unsigned int string_len = 0;
2157 register char *p = string;
2159 if (ignorevars)
2160 ignorevars = '$';
2162 while (1)
2164 if (stop2 && blank)
2165 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2166 && ! isblank ((unsigned char) *p))
2167 ++p;
2168 else if (stop2)
2169 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2170 ++p;
2171 else if (blank)
2172 while (*p != '\0' && *p != ignorevars && *p != stop1
2173 && ! isblank ((unsigned char) *p))
2174 ++p;
2175 else
2176 while (*p != '\0' && *p != ignorevars && *p != stop1)
2177 ++p;
2179 if (*p == '\0')
2180 break;
2182 /* If we stopped due to a variable reference, skip over its contents. */
2183 if (*p == ignorevars)
2185 char openparen = p[1];
2187 p += 2;
2189 /* Skip the contents of a non-quoted, multi-char variable ref. */
2190 if (openparen == '(' || openparen == '{')
2192 unsigned int pcount = 1;
2193 char closeparen = (openparen == '(' ? ')' : '}');
2195 while (*p)
2197 if (*p == openparen)
2198 ++pcount;
2199 else if (*p == closeparen)
2200 if (--pcount == 0)
2202 ++p;
2203 break;
2205 ++p;
2209 /* Skipped the variable reference: look for STOPCHARS again. */
2210 continue;
2213 if (p > string && p[-1] == '\\')
2215 /* Search for more backslashes. */
2216 register int i = -2;
2217 while (&p[i] >= string && p[i] == '\\')
2218 --i;
2219 ++i;
2220 /* Only compute the length if really needed. */
2221 if (string_len == 0)
2222 string_len = strlen (string);
2223 /* The number of backslashes is now -I.
2224 Copy P over itself to swallow half of them. */
2225 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2226 p += i / 2;
2227 if (i % 2 == 0)
2228 /* All the backslashes quoted each other; the STOPCHAR was
2229 unquoted. */
2230 return p;
2232 /* The STOPCHAR was quoted by a backslash. Look for another. */
2234 else
2235 /* No backslash in sight. */
2236 return p;
2239 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2240 return 0;
2243 /* Search PATTERN for an unquoted %. */
2245 char *
2246 find_percent (char *pattern)
2248 return find_char_unquote (pattern, '%', 0, 0, 0);
2251 /* Parse a string into a sequence of filenames represented as a
2252 chain of struct nameseq's in reverse order and return that chain.
2254 The string is passed as STRINGP, the address of a string pointer.
2255 The string pointer is updated to point at the first character
2256 not parsed, which either is a null char or equals STOPCHAR.
2258 SIZE is how big to construct chain elements.
2259 This is useful if we want them actually to be other structures
2260 that have room for additional info.
2262 If STRIP is nonzero, strip `./'s off the beginning. */
2264 struct nameseq *
2265 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2267 struct nameseq *new = 0;
2268 struct nameseq *new1, *lastnew1;
2269 char *p = *stringp;
2270 char *q;
2271 char *name;
2273 #ifdef VMS
2274 # define VMS_COMMA ','
2275 #else
2276 # define VMS_COMMA 0
2277 #endif
2279 while (1)
2281 /* Skip whitespace; see if any more names are left. */
2282 p = next_token (p);
2283 if (*p == '\0')
2284 break;
2285 if (*p == stopchar)
2286 break;
2288 /* Yes, find end of next name. */
2289 q = p;
2290 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2291 #ifdef VMS
2292 /* convert comma separated list to space separated */
2293 if (p && *p == ',')
2294 *p =' ';
2295 #endif
2296 #ifdef _AMIGA
2297 if (stopchar == ':' && p && *p == ':'
2298 && !(isspace ((unsigned char)p[1]) || !p[1]
2299 || isspace ((unsigned char)p[-1])))
2301 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2303 #endif
2304 #ifdef HAVE_DOS_PATHS
2305 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2306 first colon which isn't followed by a slash or a backslash.
2307 Note that tokens separated by spaces should be treated as separate
2308 tokens since make doesn't allow path names with spaces */
2309 if (stopchar == ':')
2310 while (p != 0 && !isspace ((unsigned char)*p) &&
2311 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2312 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2313 #endif
2314 if (p == 0)
2315 p = q + strlen (q);
2317 if (strip)
2318 #ifdef VMS
2319 /* Skip leading `[]'s. */
2320 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2321 #else
2322 /* Skip leading `./'s. */
2323 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2324 #endif
2326 q += 2; /* Skip "./". */
2327 while (q < p && *q == '/')
2328 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2329 ++q;
2332 /* Extract the filename just found, and skip it. */
2334 if (q == p)
2335 /* ".///" was stripped to "". */
2336 #ifdef VMS
2337 continue;
2338 #else
2339 #ifdef _AMIGA
2340 name = savestring ("", 0);
2341 #else
2342 name = savestring ("./", 2);
2343 #endif
2344 #endif
2345 else
2346 #ifdef VMS
2347 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2348 * to remove this '\' before we can use the filename.
2349 * Savestring called because q may be read-only string constant.
2352 char *qbase = xstrdup (q);
2353 char *pbase = qbase + (p-q);
2354 char *q1 = qbase;
2355 char *q2 = q1;
2356 char *p1 = pbase;
2358 while (q1 != pbase)
2360 if (*q1 == '\\' && *(q1+1) == ':')
2362 q1++;
2363 p1--;
2365 *q2++ = *q1++;
2367 name = savestring (qbase, p1 - qbase);
2368 free (qbase);
2370 #else
2371 name = savestring (q, p - q);
2372 #endif
2374 /* Add it to the front of the chain. */
2375 new1 = (struct nameseq *) xmalloc (size);
2376 new1->name = name;
2377 new1->next = new;
2378 new = new1;
2381 #ifndef NO_ARCHIVES
2383 /* Look for multi-word archive references.
2384 They are indicated by a elt ending with an unmatched `)' and
2385 an elt further down the chain (i.e., previous in the file list)
2386 with an unmatched `(' (e.g., "lib(mem"). */
2388 new1 = new;
2389 lastnew1 = 0;
2390 while (new1 != 0)
2391 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2392 && new1->name[strlen (new1->name) - 1] == ')'
2393 && strchr (new1->name, '(') == 0)
2395 /* NEW1 ends with a `)' but does not contain a `('.
2396 Look back for an elt with an opening `(' but no closing `)'. */
2398 struct nameseq *n = new1->next, *lastn = new1;
2399 char *paren = 0;
2400 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2402 lastn = n;
2403 n = n->next;
2405 if (n != 0
2406 /* Ignore something starting with `(', as that cannot actually
2407 be an archive-member reference (and treating it as such
2408 results in an empty file name, which causes much lossage). */
2409 && n->name[0] != '(')
2411 /* N is the first element in the archive group.
2412 Its name looks like "lib(mem" (with no closing `)'). */
2414 char *libname;
2416 /* Copy "lib(" into LIBNAME. */
2417 ++paren;
2418 libname = (char *) alloca (paren - n->name + 1);
2419 bcopy (n->name, libname, paren - n->name);
2420 libname[paren - n->name] = '\0';
2422 if (*paren == '\0')
2424 /* N was just "lib(", part of something like "lib( a b)".
2425 Edit it out of the chain and free its storage. */
2426 lastn->next = n->next;
2427 free (n->name);
2428 free ((char *) n);
2429 /* LASTN->next is the new stopping elt for the loop below. */
2430 n = lastn->next;
2432 else
2434 /* Replace N's name with the full archive reference. */
2435 name = concat (libname, paren, ")");
2436 free (n->name);
2437 n->name = name;
2440 if (new1->name[1] == '\0')
2442 /* NEW1 is just ")", part of something like "lib(a b )".
2443 Omit it from the chain and free its storage. */
2444 if (lastnew1 == 0)
2445 new = new1->next;
2446 else
2447 lastnew1->next = new1->next;
2448 lastn = new1;
2449 new1 = new1->next;
2450 free (lastn->name);
2451 free ((char *) lastn);
2453 else
2455 /* Replace also NEW1->name, which already has closing `)'. */
2456 name = concat (libname, new1->name, "");
2457 free (new1->name);
2458 new1->name = name;
2459 new1 = new1->next;
2462 /* Trace back from NEW1 (the end of the list) until N
2463 (the beginning of the list), rewriting each name
2464 with the full archive reference. */
2466 while (new1 != n)
2468 name = concat (libname, new1->name, ")");
2469 free (new1->name);
2470 new1->name = name;
2471 lastnew1 = new1;
2472 new1 = new1->next;
2475 else
2477 /* No frobnication happening. Just step down the list. */
2478 lastnew1 = new1;
2479 new1 = new1->next;
2482 else
2484 lastnew1 = new1;
2485 new1 = new1->next;
2488 #endif
2490 *stringp = p;
2491 return new;
2494 /* Find the next line of text in an eval buffer, combining continuation lines
2495 into one line.
2496 Return the number of actual lines read (> 1 if continuation lines).
2497 Returns -1 if there's nothing left in the buffer.
2499 After this function, ebuf->buffer points to the first character of the
2500 line we just found.
2503 /* Read a line of text from a STRING.
2504 Since we aren't really reading from a file, don't bother with linenumbers.
2507 static unsigned long
2508 readstring (struct ebuffer *ebuf)
2510 char *eol;
2512 /* If there is nothing left in this buffer, return 0. */
2513 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2514 return -1;
2516 /* Set up a new starting point for the buffer, and find the end of the
2517 next logical line (taking into account backslash/newline pairs). */
2519 eol = ebuf->buffer = ebuf->bufnext;
2521 while (1)
2523 int backslash = 0;
2524 char *bol = eol;
2525 char *p;
2527 /* Find the next newline. At EOS, stop. */
2528 eol = p = strchr (eol , '\n');
2529 if (!eol)
2531 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2532 return 0;
2535 /* Found a newline; if it's escaped continue; else we're done. */
2536 while (p > bol && *(--p) == '\\')
2537 backslash = !backslash;
2538 if (!backslash)
2539 break;
2540 ++eol;
2543 /* Overwrite the newline char. */
2544 *eol = '\0';
2545 ebuf->bufnext = eol+1;
2547 return 0;
2550 static long
2551 readline (struct ebuffer *ebuf)
2553 char *p;
2554 char *end;
2555 char *start;
2556 long nlines = 0;
2558 /* The behaviors between string and stream buffers are different enough to
2559 warrant different functions. Do the Right Thing. */
2561 if (!ebuf->fp)
2562 return readstring (ebuf);
2564 /* When reading from a file, we always start over at the beginning of the
2565 buffer for each new line. */
2567 p = start = ebuf->bufstart;
2568 end = p + ebuf->size;
2569 *p = '\0';
2571 while (fgets (p, end - p, ebuf->fp) != 0)
2573 char *p2;
2574 unsigned long len;
2575 int backslash;
2577 len = strlen (p);
2578 if (len == 0)
2580 /* This only happens when the first thing on the line is a '\0'.
2581 It is a pretty hopeless case, but (wonder of wonders) Athena
2582 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2583 There is nothing really to be done; we synthesize a newline so
2584 the following line doesn't appear to be part of this line. */
2585 error (&ebuf->floc,
2586 _("warning: NUL character seen; rest of line ignored"));
2587 p[0] = '\n';
2588 len = 1;
2591 /* Jump past the text we just read. */
2592 p += len;
2594 /* If the last char isn't a newline, the whole line didn't fit into the
2595 buffer. Get some more buffer and try again. */
2596 if (p[-1] != '\n')
2597 goto more_buffer;
2599 /* We got a newline, so add one to the count of lines. */
2600 ++nlines;
2602 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2603 /* Check to see if the line was really ended with CRLF; if so ignore
2604 the CR. */
2605 if ((p - start) > 1 && p[-2] == '\r')
2607 --p;
2608 p[-1] = '\n';
2610 #endif
2612 backslash = 0;
2613 for (p2 = p - 2; p2 >= start; --p2)
2615 if (*p2 != '\\')
2616 break;
2617 backslash = !backslash;
2620 if (!backslash)
2622 p[-1] = '\0';
2623 break;
2626 /* It was a backslash/newline combo. If we have more space, read
2627 another line. */
2628 if (end - p >= 80)
2629 continue;
2631 /* We need more space at the end of our buffer, so realloc it.
2632 Make sure to preserve the current offset of p. */
2633 more_buffer:
2635 unsigned long off = p - start;
2636 ebuf->size *= 2;
2637 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2638 ebuf->size);
2639 p = start + off;
2640 end = start + ebuf->size;
2641 *p = '\0';
2645 if (ferror (ebuf->fp))
2646 pfatal_with_name (ebuf->floc.filenm);
2648 /* If we found some lines, return how many.
2649 If we didn't, but we did find _something_, that indicates we read the last
2650 line of a file with no final newline; return 1.
2651 If we read nothing, we're at EOF; return -1. */
2653 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2656 /* Parse the next "makefile word" from the input buffer, and return info
2657 about it.
2659 A "makefile word" is one of:
2661 w_bogus Should never happen
2662 w_eol End of input
2663 w_static A static word; cannot be expanded
2664 w_variable A word containing one or more variables/functions
2665 w_colon A colon
2666 w_dcolon A double-colon
2667 w_semicolon A semicolon
2668 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2670 Note that this function is only used when reading certain parts of the
2671 makefile. Don't use it where special rules hold sway (RHS of a variable,
2672 in a command list, etc.) */
2674 static enum make_word_type
2675 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2677 enum make_word_type wtype = w_bogus;
2678 char *p = buffer, *beg;
2679 char c;
2681 /* Skip any leading whitespace. */
2682 while (isblank ((unsigned char)*p))
2683 ++p;
2685 beg = p;
2686 c = *(p++);
2687 switch (c)
2689 case '\0':
2690 wtype = w_eol;
2691 break;
2693 case ';':
2694 wtype = w_semicolon;
2695 break;
2697 case '=':
2698 wtype = w_varassign;
2699 break;
2701 case ':':
2702 wtype = w_colon;
2703 switch (*p)
2705 case ':':
2706 ++p;
2707 wtype = w_dcolon;
2708 break;
2710 case '=':
2711 ++p;
2712 wtype = w_varassign;
2713 break;
2715 break;
2717 case '+':
2718 case '?':
2719 if (*p == '=')
2721 ++p;
2722 wtype = w_varassign;
2723 break;
2726 default:
2727 if (delim && strchr (delim, c))
2728 wtype = w_static;
2729 break;
2732 /* Did we find something? If so, return now. */
2733 if (wtype != w_bogus)
2734 goto done;
2736 /* This is some non-operator word. A word consists of the longest
2737 string of characters that doesn't contain whitespace, one of [:=#],
2738 or [?+]=, or one of the chars in the DELIM string. */
2740 /* We start out assuming a static word; if we see a variable we'll
2741 adjust our assumptions then. */
2742 wtype = w_static;
2744 /* We already found the first value of "c", above. */
2745 while (1)
2747 char closeparen;
2748 int count;
2750 switch (c)
2752 case '\0':
2753 case ' ':
2754 case '\t':
2755 case '=':
2756 goto done_word;
2758 case ':':
2759 #ifdef HAVE_DOS_PATHS
2760 /* A word CAN include a colon in its drive spec. The drive
2761 spec is allowed either at the beginning of a word, or as part
2762 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2763 if (!(p - beg >= 2
2764 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2765 && (p - beg == 2 || p[-3] == '(')))
2766 #endif
2767 goto done_word;
2769 case '$':
2770 c = *(p++);
2771 if (c == '$')
2772 break;
2774 /* This is a variable reference, so note that it's expandable.
2775 Then read it to the matching close paren. */
2776 wtype = w_variable;
2778 if (c == '(')
2779 closeparen = ')';
2780 else if (c == '{')
2781 closeparen = '}';
2782 else
2783 /* This is a single-letter variable reference. */
2784 break;
2786 for (count=0; *p != '\0'; ++p)
2788 if (*p == c)
2789 ++count;
2790 else if (*p == closeparen && --count < 0)
2792 ++p;
2793 break;
2796 break;
2798 case '?':
2799 case '+':
2800 if (*p == '=')
2801 goto done_word;
2802 break;
2804 case '\\':
2805 switch (*p)
2807 case ':':
2808 case ';':
2809 case '=':
2810 case '\\':
2811 ++p;
2812 break;
2814 break;
2816 default:
2817 if (delim && strchr (delim, c))
2818 goto done_word;
2819 break;
2822 c = *(p++);
2824 done_word:
2825 --p;
2827 done:
2828 if (startp)
2829 *startp = beg;
2830 if (length)
2831 *length = p - beg;
2832 return wtype;
2835 /* Construct the list of include directories
2836 from the arguments and the default list. */
2838 void
2839 construct_include_path (char **arg_dirs)
2841 register unsigned int i;
2842 #ifdef VAXC /* just don't ask ... */
2843 stat_t stbuf;
2844 #else
2845 struct stat stbuf;
2846 #endif
2847 /* Table to hold the dirs. */
2849 register unsigned int defsize = (sizeof (default_include_directories)
2850 / sizeof (default_include_directories[0]));
2851 register unsigned int max = 5;
2852 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2853 register unsigned int idx = 0;
2855 #ifdef __MSDOS__
2856 defsize++;
2857 #endif
2859 /* First consider any dirs specified with -I switches.
2860 Ignore dirs that don't exist. */
2862 if (arg_dirs != 0)
2863 while (*arg_dirs != 0)
2865 char *dir = *arg_dirs++;
2866 int e;
2868 if (dir[0] == '~')
2870 char *expanded = tilde_expand (dir);
2871 if (expanded != 0)
2872 dir = expanded;
2875 EINTRLOOP (e, stat (dir, &stbuf));
2876 if (e == 0 && S_ISDIR (stbuf.st_mode))
2878 if (idx == max - 1)
2880 max += 5;
2881 dirs = (char **)
2882 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2884 dirs[idx++] = dir;
2886 else if (dir != arg_dirs[-1])
2887 free (dir);
2890 /* Now add at the end the standard default dirs. */
2892 #ifdef __MSDOS__
2894 /* The environment variable $DJDIR holds the root of the
2895 DJGPP directory tree; add ${DJDIR}/include. */
2896 struct variable *djdir = lookup_variable ("DJDIR", 5);
2898 if (djdir)
2900 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2902 strcat (strcpy (defdir, djdir->value), "/include");
2903 dirs[idx++] = defdir;
2906 #endif
2908 for (i = 0; default_include_directories[i] != 0; ++i)
2910 int e;
2912 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2913 if (e == 0 && S_ISDIR (stbuf.st_mode))
2914 dirs[idx++] = default_include_directories[i];
2917 dirs[idx] = 0;
2919 /* Now compute the maximum length of any name in it. Also add each
2920 dir to the .INCLUDE_DIRS variable. */
2922 max_incl_len = 0;
2923 for (i = 0; i < idx; ++i)
2925 unsigned int len = strlen (dirs[i]);
2926 /* If dir name is written with a trailing slash, discard it. */
2927 if (dirs[i][len - 1] == '/')
2928 /* We can't just clobber a null in because it may have come from
2929 a literal string and literal strings may not be writable. */
2930 dirs[i] = savestring (dirs[i], len - 1);
2931 if (len > max_incl_len)
2932 max_incl_len = len;
2934 /* Append to .INCLUDE_DIRS. */
2935 do_variable_definition (NILF, ".INCLUDE_DIRS", dirs[i],
2936 o_default, f_append, 0);
2939 include_directories = dirs;
2942 /* Expand ~ or ~USER at the beginning of NAME.
2943 Return a newly malloc'd string or 0. */
2945 char *
2946 tilde_expand (char *name)
2948 #ifndef VMS
2949 if (name[1] == '/' || name[1] == '\0')
2951 extern char *getenv ();
2952 char *home_dir;
2953 int is_variable;
2956 /* Turn off --warn-undefined-variables while we expand HOME. */
2957 int save = warn_undefined_variables_flag;
2958 warn_undefined_variables_flag = 0;
2960 home_dir = allocated_variable_expand ("$(HOME)");
2962 warn_undefined_variables_flag = save;
2965 is_variable = home_dir[0] != '\0';
2966 if (!is_variable)
2968 free (home_dir);
2969 home_dir = getenv ("HOME");
2971 #if !defined(_AMIGA) && !defined(WINDOWS32)
2972 if (home_dir == 0 || home_dir[0] == '\0')
2974 extern char *getlogin ();
2975 char *logname = getlogin ();
2976 home_dir = 0;
2977 if (logname != 0)
2979 struct passwd *p = getpwnam (logname);
2980 if (p != 0)
2981 home_dir = p->pw_dir;
2984 #endif /* !AMIGA && !WINDOWS32 */
2985 if (home_dir != 0)
2987 char *new = concat (home_dir, "", name + 1);
2988 if (is_variable)
2989 free (home_dir);
2990 return new;
2993 #if !defined(_AMIGA) && !defined(WINDOWS32)
2994 else
2996 struct passwd *pwent;
2997 char *userend = strchr (name + 1, '/');
2998 if (userend != 0)
2999 *userend = '\0';
3000 pwent = getpwnam (name + 1);
3001 if (pwent != 0)
3003 if (userend == 0)
3004 return xstrdup (pwent->pw_dir);
3005 else
3006 return concat (pwent->pw_dir, "/", userend + 1);
3008 else if (userend != 0)
3009 *userend = '/';
3011 #endif /* !AMIGA && !WINDOWS32 */
3012 #endif /* !VMS */
3013 return 0;
3016 /* Given a chain of struct nameseq's describing a sequence of filenames,
3017 in reverse of the intended order, return a new chain describing the
3018 result of globbing the filenames. The new chain is in forward order.
3019 The links of the old chain are freed or used in the new chain.
3020 Likewise for the names in the old chain.
3022 SIZE is how big to construct chain elements.
3023 This is useful if we want them actually to be other structures
3024 that have room for additional info. */
3026 struct nameseq *
3027 multi_glob (struct nameseq *chain, unsigned int size)
3029 extern void dir_setup_glob ();
3030 register struct nameseq *new = 0;
3031 register struct nameseq *old;
3032 struct nameseq *nexto;
3033 glob_t gl;
3035 dir_setup_glob (&gl);
3037 for (old = chain; old != 0; old = nexto)
3039 #ifndef NO_ARCHIVES
3040 char *memname;
3041 #endif
3043 nexto = old->next;
3045 if (old->name[0] == '~')
3047 char *newname = tilde_expand (old->name);
3048 if (newname != 0)
3050 free (old->name);
3051 old->name = newname;
3055 #ifndef NO_ARCHIVES
3056 if (ar_name (old->name))
3058 /* OLD->name is an archive member reference.
3059 Replace it with the archive file name,
3060 and save the member name in MEMNAME.
3061 We will glob on the archive name and then
3062 reattach MEMNAME later. */
3063 char *arname;
3064 ar_parse_name (old->name, &arname, &memname);
3065 free (old->name);
3066 old->name = arname;
3068 else
3069 memname = 0;
3070 #endif /* !NO_ARCHIVES */
3072 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3074 case 0: /* Success. */
3076 register int i = gl.gl_pathc;
3077 while (i-- > 0)
3079 #ifndef NO_ARCHIVES
3080 if (memname != 0)
3082 /* Try to glob on MEMNAME within the archive. */
3083 struct nameseq *found
3084 = ar_glob (gl.gl_pathv[i], memname, size);
3085 if (found == 0)
3087 /* No matches. Use MEMNAME as-is. */
3088 unsigned int alen = strlen (gl.gl_pathv[i]);
3089 unsigned int mlen = strlen (memname);
3090 struct nameseq *elt
3091 = (struct nameseq *) xmalloc (size);
3092 if (size > sizeof (struct nameseq))
3093 bzero (((char *) elt) + sizeof (struct nameseq),
3094 size - sizeof (struct nameseq));
3095 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3096 bcopy (gl.gl_pathv[i], elt->name, alen);
3097 elt->name[alen] = '(';
3098 bcopy (memname, &elt->name[alen + 1], mlen);
3099 elt->name[alen + 1 + mlen] = ')';
3100 elt->name[alen + 1 + mlen + 1] = '\0';
3101 elt->next = new;
3102 new = elt;
3104 else
3106 /* Find the end of the FOUND chain. */
3107 struct nameseq *f = found;
3108 while (f->next != 0)
3109 f = f->next;
3111 /* Attach the chain being built to the end of the FOUND
3112 chain, and make FOUND the new NEW chain. */
3113 f->next = new;
3114 new = found;
3117 free (memname);
3119 else
3120 #endif /* !NO_ARCHIVES */
3122 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3123 if (size > sizeof (struct nameseq))
3124 bzero (((char *) elt) + sizeof (struct nameseq),
3125 size - sizeof (struct nameseq));
3126 elt->name = xstrdup (gl.gl_pathv[i]);
3127 elt->next = new;
3128 new = elt;
3131 globfree (&gl);
3132 free (old->name);
3133 free ((char *)old);
3134 break;
3137 case GLOB_NOSPACE:
3138 fatal (NILF, _("virtual memory exhausted"));
3139 break;
3141 default:
3142 old->next = new;
3143 new = old;
3144 break;
3148 return new;