- New code capability: a read-only string cache. Start of solution for
[make.git] / read.c
blob5ec87073dc612a2e8fbbf5aa7366f451c495991b
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
23 #include <assert.h>
25 #include <glob.h>
27 #include "dep.h"
28 #include "filedef.h"
29 #include "job.h"
30 #include "commands.h"
31 #include "variable.h"
32 #include "rule.h"
33 #include "debug.h"
34 #include "hash.h"
37 #ifndef WINDOWS32
38 #ifndef _AMIGA
39 #ifndef VMS
40 #include <pwd.h>
41 #else
42 struct passwd *getpwnam PARAMS ((char *name));
43 #endif
44 #endif
45 #endif /* !WINDOWS32 */
47 /* A 'struct ebuffer' controls the origin of the makefile we are currently
48 eval'ing.
51 struct ebuffer
53 char *buffer; /* Start of the current line in the buffer. */
54 char *bufnext; /* Start of the next line in the buffer. */
55 char *bufstart; /* Start of the entire buffer. */
56 unsigned int size; /* Malloc'd size of buffer. */
57 FILE *fp; /* File, or NULL if this is an internal buffer. */
58 struct floc floc; /* Info on the file in fp (if any). */
61 /* Types of "words" that can be read in a makefile. */
62 enum make_word_type
64 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
65 w_varassign
69 /* A `struct conditionals' contains the information describing
70 all the active conditionals in a makefile.
72 The global variable `conditionals' contains the conditionals
73 information for the current makefile. It is initialized from
74 the static structure `toplevel_conditionals' and is later changed
75 to new structures for included makefiles. */
77 struct conditionals
79 unsigned int if_cmds; /* Depth of conditional nesting. */
80 unsigned int allocated; /* Elts allocated in following arrays. */
81 char *ignoring; /* Are we ignoring or interpreting?
82 0=interpreting, 1=not yet interpreted,
83 2=already interpreted */
84 char *seen_else; /* Have we already seen an `else'? */
87 static struct conditionals toplevel_conditionals;
88 static struct conditionals *conditionals = &toplevel_conditionals;
91 /* Default directories to search for include files in */
93 static char *default_include_directories[] =
95 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
97 * This completely up to the user when they install MSVC or other packages.
98 * This is defined as a placeholder.
100 #define INCLUDEDIR "."
101 #endif
102 INCLUDEDIR,
103 #ifndef _AMIGA
104 "/usr/gnu/include",
105 "/usr/local/include",
106 "/usr/include",
107 #endif
111 /* List of directories to search for include files in */
113 static char **include_directories;
115 /* Maximum length of an element of the above. */
117 static unsigned int max_incl_len;
119 /* The filename and pointer to line number of the
120 makefile currently being read in. */
122 const struct floc *reading_file = 0;
124 /* The chain of makefiles read by read_makefile. */
126 static struct dep *read_makefiles = 0;
128 static int eval_makefile PARAMS ((char *filename, int flags));
129 static int eval PARAMS ((struct ebuffer *buffer, int flags));
131 static long readline PARAMS ((struct ebuffer *ebuf));
132 static void do_define PARAMS ((char *name, unsigned int namelen,
133 enum variable_origin origin,
134 struct ebuffer *ebuf));
135 static int conditional_line PARAMS ((char *line, int len, const struct floc *flocp));
136 static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
137 struct dep *deps, unsigned int cmds_started, char *commands,
138 unsigned int commands_idx, int two_colon,
139 const struct floc *flocp));
140 static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
141 enum variable_origin origin,
142 int enabled,
143 const struct floc *flocp));
144 static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
145 char **startp, unsigned int *length));
146 static void remove_comments PARAMS ((char *line));
147 static char *find_char_unquote PARAMS ((char *string, int stop1,
148 int stop2, int blank, int ignorevars));
150 /* Read in all the makefiles and return the chain of their names. */
152 struct dep *
153 read_all_makefiles (char **makefiles)
155 unsigned int num_makefiles = 0;
157 /* Create *_LIST variables, to hold the makefiles, targets, and variables
158 we will be reading. */
160 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
162 DB (DB_BASIC, (_("Reading makefiles...\n")));
164 /* If there's a non-null variable MAKEFILES, its value is a list of
165 files to read first thing. But don't let it prevent reading the
166 default makefiles and don't let the default goal come from there. */
169 char *value;
170 char *name, *p;
171 unsigned int length;
174 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
175 int save = warn_undefined_variables_flag;
176 warn_undefined_variables_flag = 0;
178 value = allocated_variable_expand ("$(MAKEFILES)");
180 warn_undefined_variables_flag = save;
183 /* Set NAME to the start of next token and LENGTH to its length.
184 MAKEFILES is updated for finding remaining tokens. */
185 p = value;
187 while ((name = find_next_token (&p, &length)) != 0)
189 if (*p != '\0')
190 *p++ = '\0';
191 name = xstrdup (name);
192 if (eval_makefile (name,
193 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
194 free (name);
197 free (value);
200 /* Read makefiles specified with -f switches. */
202 if (makefiles != 0)
203 while (*makefiles != 0)
205 struct dep *tail = read_makefiles;
206 register struct dep *d;
208 if (! eval_makefile (*makefiles, 0))
209 perror_with_name ("", *makefiles);
211 /* Find the right element of read_makefiles. */
212 d = read_makefiles;
213 while (d->next != tail)
214 d = d->next;
216 /* Use the storage read_makefile allocates. */
217 *makefiles = dep_name (d);
218 ++num_makefiles;
219 ++makefiles;
222 /* If there were no -f switches, try the default names. */
224 if (num_makefiles == 0)
226 static char *default_makefiles[] =
227 #ifdef VMS
228 /* all lower case since readdir() (the vms version) 'lowercasifies' */
229 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
230 #else
231 #ifdef _AMIGA
232 { "GNUmakefile", "Makefile", "SMakefile", 0 };
233 #else /* !Amiga && !VMS */
234 { "GNUmakefile", "makefile", "Makefile", 0 };
235 #endif /* AMIGA */
236 #endif /* VMS */
237 register char **p = default_makefiles;
238 while (*p != 0 && !file_exists_p (*p))
239 ++p;
241 if (*p != 0)
243 if (! eval_makefile (*p, 0))
244 perror_with_name ("", *p);
246 else
248 /* No default makefile was found. Add the default makefiles to the
249 `read_makefiles' chain so they will be updated if possible. */
250 struct dep *tail = read_makefiles;
251 /* Add them to the tail, after any MAKEFILES variable makefiles. */
252 while (tail != 0 && tail->next != 0)
253 tail = tail->next;
254 for (p = default_makefiles; *p != 0; ++p)
256 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
257 d->name = 0;
258 d->file = enter_file (*p);
259 d->file->dontcare = 1;
260 d->ignore_mtime = 0;
261 d->staticpattern = 0;
262 d->need_2nd_expansion = 0;
263 /* Tell update_goal_chain to bail out as soon as this file is
264 made, and main not to die if we can't make this file. */
265 d->changed = RM_DONTCARE;
266 if (tail == 0)
267 read_makefiles = d;
268 else
269 tail->next = d;
270 tail = d;
272 if (tail != 0)
273 tail->next = 0;
277 return read_makefiles;
280 /* Install a new conditional and return the previous one. */
282 static struct conditionals *
283 install_conditionals (struct conditionals *new)
285 struct conditionals *save = conditionals;
287 bzero ((char *) new, sizeof (*new));
288 conditionals = new;
290 return save;
293 /* Free the current conditionals and reinstate a saved one. */
295 static void
296 restore_conditionals (struct conditionals *saved)
298 /* Free any space allocated by conditional_line. */
299 if (conditionals->ignoring)
300 free (conditionals->ignoring);
301 if (conditionals->seen_else)
302 free (conditionals->seen_else);
304 /* Restore state. */
305 conditionals = saved;
308 static int
309 eval_makefile (char *filename, int flags)
311 struct dep *deps;
312 struct ebuffer ebuf;
313 const struct floc *curfile;
314 char *expanded = 0;
315 char *included = 0;
316 int makefile_errno;
317 int r;
319 ebuf.floc.filenm = strcache_add (filename);
320 ebuf.floc.lineno = 1;
322 if (ISDB (DB_VERBOSE))
324 printf (_("Reading makefile `%s'"), filename);
325 if (flags & RM_NO_DEFAULT_GOAL)
326 printf (_(" (no default goal)"));
327 if (flags & RM_INCLUDED)
328 printf (_(" (search path)"));
329 if (flags & RM_DONTCARE)
330 printf (_(" (don't care)"));
331 if (flags & RM_NO_TILDE)
332 printf (_(" (no ~ expansion)"));
333 puts ("...");
336 /* First, get a stream to read. */
338 /* Expand ~ in FILENAME unless it came from `include',
339 in which case it was already done. */
340 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
342 expanded = tilde_expand (filename);
343 if (expanded != 0)
344 filename = expanded;
347 ebuf.fp = fopen (filename, "r");
348 /* Save the error code so we print the right message later. */
349 makefile_errno = errno;
351 /* If the makefile wasn't found and it's either a makefile from
352 the `MAKEFILES' variable or an included makefile,
353 search the included makefile search path for this makefile. */
354 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
356 register unsigned int i;
357 for (i = 0; include_directories[i] != 0; ++i)
359 included = concat (include_directories[i], "/", filename);
360 ebuf.fp = fopen (included, "r");
361 if (ebuf.fp)
363 filename = included;
364 break;
366 free (included);
368 /* If we're not using it, we already freed it above. */
369 if (filename != included)
370 included = 0;
373 /* Add FILENAME to the chain of read makefiles. */
374 deps = (struct dep *) xmalloc (sizeof (struct dep));
375 deps->next = read_makefiles;
376 read_makefiles = deps;
377 deps->name = 0;
378 deps->file = lookup_file (filename);
379 if (deps->file == 0)
380 deps->file = enter_file (xstrdup (filename));
381 filename = deps->file->name;
382 deps->changed = flags;
383 deps->ignore_mtime = 0;
384 deps->staticpattern = 0;
385 deps->need_2nd_expansion = 0;
386 if (flags & RM_DONTCARE)
387 deps->file->dontcare = 1;
389 if (expanded)
390 free (expanded);
391 if (included)
392 free (included);
394 /* If the makefile can't be found at all, give up entirely. */
396 if (ebuf.fp == 0)
398 /* If we did some searching, errno has the error from the last
399 attempt, rather from FILENAME itself. Restore it in case the
400 caller wants to use it in a message. */
401 errno = makefile_errno;
402 return 0;
405 /* Add this makefile to the list. */
406 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
407 f_append, 0);
409 /* Evaluate the makefile */
411 ebuf.size = 200;
412 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
414 curfile = reading_file;
415 reading_file = &ebuf.floc;
417 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
419 reading_file = curfile;
421 fclose (ebuf.fp);
423 free (ebuf.bufstart);
424 alloca (0);
425 return r;
429 eval_buffer (char *buffer)
431 struct ebuffer ebuf;
432 struct conditionals *saved;
433 struct conditionals new;
434 const struct floc *curfile;
435 int r;
437 /* Evaluate the buffer */
439 ebuf.size = strlen (buffer);
440 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
441 ebuf.fp = NULL;
443 ebuf.floc = *reading_file;
445 curfile = reading_file;
446 reading_file = &ebuf.floc;
448 saved = install_conditionals (&new);
450 r = eval (&ebuf, 1);
452 restore_conditionals (saved);
454 reading_file = curfile;
456 alloca (0);
457 return r;
461 /* Read file FILENAME as a makefile and add its contents to the data base.
463 SET_DEFAULT is true if we are allowed to set the default goal. */
466 static int
467 eval (struct ebuffer *ebuf, int set_default)
469 char *collapsed = 0;
470 unsigned int collapsed_length = 0;
471 unsigned int commands_len = 200;
472 char *commands;
473 unsigned int commands_idx = 0;
474 unsigned int cmds_started, tgts_started;
475 int ignoring = 0, in_ignored_define = 0;
476 int no_targets = 0; /* Set when reading a rule without targets. */
477 struct nameseq *filenames = 0;
478 struct dep *deps = 0;
479 long nlines = 0;
480 int two_colon = 0;
481 char *pattern = 0, *pattern_percent;
482 struct floc *fstart;
483 struct floc fi;
485 #define record_waiting_files() \
486 do \
488 if (filenames != 0) \
490 fi.lineno = tgts_started; \
491 record_files (filenames, pattern, pattern_percent, deps, \
492 cmds_started, commands, commands_idx, two_colon, \
493 &fi); \
495 filenames = 0; \
496 commands_idx = 0; \
497 no_targets = 0; \
498 if (pattern) { free(pattern); pattern = 0; } \
499 } while (0)
501 pattern_percent = 0;
502 cmds_started = tgts_started = 1;
504 fstart = &ebuf->floc;
505 fi.filenm = ebuf->floc.filenm;
507 /* Loop over lines in the file.
508 The strategy is to accumulate target names in FILENAMES, dependencies
509 in DEPS and commands in COMMANDS. These are used to define a rule
510 when the start of the next rule (or eof) is encountered.
512 When you see a "continue" in the loop below, that means we are moving on
513 to the next line _without_ ending any rule that we happen to be working
514 with at the moment. If you see a "goto rule_complete", then the
515 statement we just parsed also finishes the previous rule. */
517 commands = xmalloc (200);
519 while (1)
521 unsigned int linelen;
522 char *line;
523 int len;
524 char *p;
525 char *p2;
527 /* Grab the next line to be evaluated */
528 ebuf->floc.lineno += nlines;
529 nlines = readline (ebuf);
531 /* If there is nothing left to eval, we're done. */
532 if (nlines < 0)
533 break;
535 /* If this line is empty, skip it. */
536 line = ebuf->buffer;
537 if (line[0] == '\0')
538 continue;
540 linelen = strlen (line);
542 /* Check for a shell command line first.
543 If it is not one, we can stop treating tab specially. */
544 if (line[0] == '\t')
546 if (no_targets)
547 /* Ignore the commands in a rule with no targets. */
548 continue;
550 /* If there is no preceding rule line, don't treat this line
551 as a command, even though it begins with a tab character.
552 SunOS 4 make appears to behave this way. */
554 if (filenames != 0)
556 if (ignoring)
557 /* Yep, this is a shell command, and we don't care. */
558 continue;
560 /* Append this command line to the line being accumulated. */
561 if (commands_idx == 0)
562 cmds_started = ebuf->floc.lineno;
564 if (linelen + 1 + commands_idx > commands_len)
566 commands_len = (linelen + 1 + commands_idx) * 2;
567 commands = xrealloc (commands, commands_len);
569 bcopy (line, &commands[commands_idx], linelen);
570 commands_idx += linelen;
571 commands[commands_idx++] = '\n';
573 continue;
577 /* This line is not a shell command line. Don't worry about tabs.
578 Get more space if we need it; we don't need to preserve the current
579 contents of the buffer. */
581 if (collapsed_length < linelen+1)
583 collapsed_length = linelen+1;
584 if (collapsed)
585 free ((char *)collapsed);
586 collapsed = (char *) xmalloc (collapsed_length);
588 strcpy (collapsed, line);
589 /* Collapse continuation lines. */
590 collapse_continuations (collapsed);
591 remove_comments (collapsed);
593 /* Compare a word, both length and contents. */
594 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
595 p = collapsed;
596 while (isspace ((unsigned char)*p))
597 ++p;
599 if (*p == '\0')
600 /* This line is completely empty--ignore it. */
601 continue;
603 /* Find the end of the first token. Note we don't need to worry about
604 * ":" here since we compare tokens by length (so "export" will never
605 * be equal to "export:").
607 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
609 len = p2 - p;
611 /* Find the start of the second token. If it looks like a target or
612 variable definition it can't be a preprocessor token so skip
613 them--this allows variables/targets named `ifdef', `export', etc. */
614 while (isspace ((unsigned char)*p2))
615 ++p2;
617 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
619 /* It can't be a preprocessor token so skip it if we're ignoring */
620 if (ignoring)
621 continue;
623 goto skip_conditionals;
626 /* We must first check for conditional and `define' directives before
627 ignoring anything, since they control what we will do with
628 following lines. */
630 if (!in_ignored_define)
632 int i = conditional_line (p, len, fstart);
633 if (i != -2)
635 if (i == -1)
636 fatal (fstart, _("invalid syntax in conditional"));
638 ignoring = i;
639 continue;
643 if (word1eq ("endef"))
645 if (!in_ignored_define)
646 fatal (fstart, _("extraneous `endef'"));
647 in_ignored_define = 0;
648 continue;
651 if (word1eq ("define"))
653 if (ignoring)
654 in_ignored_define = 1;
655 else
657 if (*p2 == '\0')
658 fatal (fstart, _("empty variable name"));
660 /* Let the variable name be the whole rest of the line,
661 with trailing blanks stripped (comments have already been
662 removed), so it could be a complex variable/function
663 reference that might contain blanks. */
664 p = strchr (p2, '\0');
665 while (isblank ((unsigned char)p[-1]))
666 --p;
667 do_define (p2, p - p2, o_file, ebuf);
669 continue;
672 if (word1eq ("override"))
674 if (*p2 == '\0')
675 error (fstart, _("empty `override' directive"));
677 if (strneq (p2, "define", 6)
678 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
680 if (ignoring)
681 in_ignored_define = 1;
682 else
684 p2 = next_token (p2 + 6);
685 if (*p2 == '\0')
686 fatal (fstart, _("empty variable name"));
688 /* Let the variable name be the whole rest of the line,
689 with trailing blanks stripped (comments have already been
690 removed), so it could be a complex variable/function
691 reference that might contain blanks. */
692 p = strchr (p2, '\0');
693 while (isblank ((unsigned char)p[-1]))
694 --p;
695 do_define (p2, p - p2, o_override, ebuf);
698 else if (!ignoring
699 && !try_variable_definition (fstart, p2, o_override, 0))
700 error (fstart, _("invalid `override' directive"));
702 continue;
705 if (ignoring)
706 /* Ignore the line. We continue here so conditionals
707 can appear in the middle of a rule. */
708 continue;
710 if (word1eq ("export"))
712 /* 'export' by itself causes everything to be exported. */
713 if (*p2 == '\0')
714 export_all_variables = 1;
715 else
717 struct variable *v;
719 v = try_variable_definition (fstart, p2, o_file, 0);
720 if (v != 0)
721 v->export = v_export;
722 else
724 unsigned int len;
725 char *ap;
727 /* Expand the line so we can use indirect and constructed
728 variable names in an export command. */
729 p2 = ap = allocated_variable_expand (p2);
731 for (p = find_next_token (&p2, &len); p != 0;
732 p = find_next_token (&p2, &len))
734 v = lookup_variable (p, len);
735 if (v == 0)
736 v = define_variable_loc (p, len, "", o_file, 0,
737 fstart);
738 v->export = v_export;
741 free (ap);
744 goto rule_complete;
747 if (word1eq ("unexport"))
749 if (*p2 == '\0')
750 export_all_variables = 0;
751 else
753 unsigned int len;
754 struct variable *v;
755 char *ap;
757 /* Expand the line so we can use indirect and constructed
758 variable names in an unexport command. */
759 p2 = ap = allocated_variable_expand (p2);
761 for (p = find_next_token (&p2, &len); p != 0;
762 p = find_next_token (&p2, &len))
764 v = lookup_variable (p, len);
765 if (v == 0)
766 v = define_variable_loc (p, len, "", o_file, 0, fstart);
768 v->export = v_noexport;
771 free (ap);
773 goto rule_complete;
776 skip_conditionals:
777 if (word1eq ("vpath"))
779 char *pattern;
780 unsigned int len;
781 p2 = variable_expand (p2);
782 p = find_next_token (&p2, &len);
783 if (p != 0)
785 pattern = savestring (p, len);
786 p = find_next_token (&p2, &len);
787 /* No searchpath means remove all previous
788 selective VPATH's with the same pattern. */
790 else
791 /* No pattern means remove all previous selective VPATH's. */
792 pattern = 0;
793 construct_vpath_list (pattern, p);
794 if (pattern != 0)
795 free (pattern);
797 goto rule_complete;
800 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
802 /* We have found an `include' line specifying a nested
803 makefile to be read at this point. */
804 struct conditionals *save;
805 struct conditionals new_conditionals;
806 struct nameseq *files;
807 /* "-include" (vs "include") says no error if the file does not
808 exist. "sinclude" is an alias for this from SGI. */
809 int noerror = (p[0] != 'i');
811 p = allocated_variable_expand (p2);
813 /* If no filenames, it's a no-op. */
814 if (*p == '\0')
815 continue;
817 /* Parse the list of file names. */
818 p2 = p;
819 files = multi_glob (parse_file_seq (&p2, '\0',
820 sizeof (struct nameseq),
822 sizeof (struct nameseq));
823 free (p);
825 /* Save the state of conditionals and start
826 the included makefile with a clean slate. */
827 save = install_conditionals (&new_conditionals);
829 /* Record the rules that are waiting so they will determine
830 the default goal before those in the included makefile. */
831 record_waiting_files ();
833 /* Read each included makefile. */
834 while (files != 0)
836 struct nameseq *next = files->next;
837 char *name = files->name;
838 int r;
840 free ((char *)files);
841 files = next;
843 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
844 | (noerror ? RM_DONTCARE : 0)));
845 if (!r)
847 if (!noerror)
848 error (fstart, "%s: %s", name, strerror (errno));
849 free (name);
853 /* Restore conditional state. */
854 restore_conditionals (save);
856 goto rule_complete;
859 if (try_variable_definition (fstart, p, o_file, 0))
860 /* This line has been dealt with. */
861 goto rule_complete;
863 /* This line starts with a tab but was not caught above because there
864 was no preceding target, and the line might have been usable as a
865 variable definition. But now we know it is definitely lossage. */
866 if (line[0] == '\t')
867 fatal(fstart, _("commands commence before first target"));
869 /* This line describes some target files. This is complicated by
870 the existence of target-specific variables, because we can't
871 expand the entire line until we know if we have one or not. So
872 we expand the line word by word until we find the first `:',
873 then check to see if it's a target-specific variable.
875 In this algorithm, `lb_next' will point to the beginning of the
876 unexpanded parts of the input buffer, while `p2' points to the
877 parts of the expanded buffer we haven't searched yet. */
880 enum make_word_type wtype;
881 enum variable_origin v_origin;
882 int exported;
883 char *cmdleft, *semip, *lb_next;
884 unsigned int len, plen = 0;
885 char *colonp;
886 const char *end, *beg; /* Helpers for whitespace stripping. */
888 /* Record the previous rule. */
890 record_waiting_files ();
891 tgts_started = fstart->lineno;
893 /* Search the line for an unquoted ; that is not after an
894 unquoted #. */
895 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
896 if (cmdleft != 0 && *cmdleft == '#')
898 /* We found a comment before a semicolon. */
899 *cmdleft = '\0';
900 cmdleft = 0;
902 else if (cmdleft != 0)
903 /* Found one. Cut the line short there before expanding it. */
904 *(cmdleft++) = '\0';
905 semip = cmdleft;
907 collapse_continuations (line);
909 /* We can't expand the entire line, since if it's a per-target
910 variable we don't want to expand it. So, walk from the
911 beginning, expanding as we go, and looking for "interesting"
912 chars. The first word is always expandable. */
913 wtype = get_next_mword(line, NULL, &lb_next, &len);
914 switch (wtype)
916 case w_eol:
917 if (cmdleft != 0)
918 fatal(fstart, _("missing rule before commands"));
919 /* This line contained something but turned out to be nothing
920 but whitespace (a comment?). */
921 continue;
923 case w_colon:
924 case w_dcolon:
925 /* We accept and ignore rules without targets for
926 compatibility with SunOS 4 make. */
927 no_targets = 1;
928 continue;
930 default:
931 break;
934 p2 = variable_expand_string(NULL, lb_next, len);
936 while (1)
938 lb_next += len;
939 if (cmdleft == 0)
941 /* Look for a semicolon in the expanded line. */
942 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
944 if (cmdleft != 0)
946 unsigned long p2_off = p2 - variable_buffer;
947 unsigned long cmd_off = cmdleft - variable_buffer;
948 char *pend = p2 + strlen(p2);
950 /* Append any remnants of lb, then cut the line short
951 at the semicolon. */
952 *cmdleft = '\0';
954 /* One school of thought says that you shouldn't expand
955 here, but merely copy, since now you're beyond a ";"
956 and into a command script. However, the old parser
957 expanded the whole line, so we continue that for
958 backwards-compatiblity. Also, it wouldn't be
959 entirely consistent, since we do an unconditional
960 expand below once we know we don't have a
961 target-specific variable. */
962 (void)variable_expand_string(pend, lb_next, (long)-1);
963 lb_next += strlen(lb_next);
964 p2 = variable_buffer + p2_off;
965 cmdleft = variable_buffer + cmd_off + 1;
969 colonp = find_char_unquote(p2, ':', 0, 0, 0);
970 #ifdef HAVE_DOS_PATHS
971 /* The drive spec brain-damage strikes again... */
972 /* Note that the only separators of targets in this context
973 are whitespace and a left paren. If others are possible,
974 they should be added to the string in the call to index. */
975 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
976 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
977 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
978 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
979 #endif
980 if (colonp != 0)
981 break;
983 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
984 if (wtype == w_eol)
985 break;
987 p2 += strlen(p2);
988 *(p2++) = ' ';
989 p2 = variable_expand_string(p2, lb_next, len);
990 /* We don't need to worry about cmdleft here, because if it was
991 found in the variable_buffer the entire buffer has already
992 been expanded... we'll never get here. */
995 p2 = next_token (variable_buffer);
997 /* If the word we're looking at is EOL, see if there's _anything_
998 on the line. If not, a variable expanded to nothing, so ignore
999 it. If so, we can't parse this line so punt. */
1000 if (wtype == w_eol)
1002 if (*p2 != '\0')
1003 /* There's no need to be ivory-tower about this: check for
1004 one of the most common bugs found in makefiles... */
1005 fatal (fstart, _("missing separator%s"),
1006 !strneq(line, " ", 8) ? ""
1007 : _(" (did you mean TAB instead of 8 spaces?)"));
1008 continue;
1011 /* Make the colon the end-of-string so we know where to stop
1012 looking for targets. */
1013 *colonp = '\0';
1014 filenames = multi_glob (parse_file_seq (&p2, '\0',
1015 sizeof (struct nameseq),
1017 sizeof (struct nameseq));
1018 *p2 = ':';
1020 if (!filenames)
1022 /* We accept and ignore rules without targets for
1023 compatibility with SunOS 4 make. */
1024 no_targets = 1;
1025 continue;
1027 /* This should never be possible; we handled it above. */
1028 assert (*p2 != '\0');
1029 ++p2;
1031 /* Is this a one-colon or two-colon entry? */
1032 two_colon = *p2 == ':';
1033 if (two_colon)
1034 p2++;
1036 /* Test to see if it's a target-specific variable. Copy the rest
1037 of the buffer over, possibly temporarily (we'll expand it later
1038 if it's not a target-specific variable). PLEN saves the length
1039 of the unparsed section of p2, for later. */
1040 if (*lb_next != '\0')
1042 unsigned int l = p2 - variable_buffer;
1043 plen = strlen (p2);
1044 (void) variable_buffer_output (p2+plen,
1045 lb_next, strlen (lb_next)+1);
1046 p2 = variable_buffer + l;
1049 /* See if it's an "override" or "export" keyword; if so see if what
1050 comes after it looks like a variable definition. */
1052 wtype = get_next_mword (p2, NULL, &p, &len);
1054 v_origin = o_file;
1055 exported = 0;
1056 if (wtype == w_static)
1058 if (word1eq ("override"))
1060 v_origin = o_override;
1061 wtype = get_next_mword (p+len, NULL, &p, &len);
1063 else if (word1eq ("export"))
1065 exported = 1;
1066 wtype = get_next_mword (p+len, NULL, &p, &len);
1070 if (wtype != w_eol)
1071 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1073 if (wtype == w_varassign)
1075 /* If there was a semicolon found, add it back, plus anything
1076 after it. */
1077 if (semip)
1079 unsigned int l = p - variable_buffer;
1080 *(--semip) = ';';
1081 variable_buffer_output (p2 + strlen (p2),
1082 semip, strlen (semip)+1);
1083 p = variable_buffer + l;
1085 record_target_var (filenames, p, v_origin, exported, fstart);
1086 filenames = 0;
1087 continue;
1090 /* This is a normal target, _not_ a target-specific variable.
1091 Unquote any = in the dependency list. */
1092 find_char_unquote (lb_next, '=', 0, 0, 0);
1094 /* We have some targets, so don't ignore the following commands. */
1095 no_targets = 0;
1097 /* Expand the dependencies, etc. */
1098 if (*lb_next != '\0')
1100 unsigned int l = p2 - variable_buffer;
1101 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1102 p2 = variable_buffer + l;
1104 /* Look for a semicolon in the expanded line. */
1105 if (cmdleft == 0)
1107 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1108 if (cmdleft != 0)
1109 *(cmdleft++) = '\0';
1113 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1114 p = strchr (p2, ':');
1115 while (p != 0 && p[-1] == '\\')
1117 register char *q = &p[-1];
1118 register int backslash = 0;
1119 while (*q-- == '\\')
1120 backslash = !backslash;
1121 if (backslash)
1122 p = strchr (p + 1, ':');
1123 else
1124 break;
1126 #ifdef _AMIGA
1127 /* Here, the situation is quite complicated. Let's have a look
1128 at a couple of targets:
1130 install: dev:make
1132 dev:make: make
1134 dev:make:: xyz
1136 The rule is that it's only a target, if there are TWO :'s
1137 OR a space around the :.
1139 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1140 || isspace ((unsigned char)p[-1])))
1141 p = 0;
1142 #endif
1143 #ifdef HAVE_DOS_PATHS
1145 int check_again;
1147 do {
1148 check_again = 0;
1149 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1150 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1151 isalpha ((unsigned char)p[-1]) &&
1152 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1153 p = strchr (p + 1, ':');
1154 check_again = 1;
1156 } while (check_again);
1158 #endif
1159 if (p != 0)
1161 struct nameseq *target;
1162 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1163 ++p2;
1164 if (target == 0)
1165 fatal (fstart, _("missing target pattern"));
1166 else if (target->next != 0)
1167 fatal (fstart, _("multiple target patterns"));
1168 pattern = target->name;
1169 pattern_percent = find_percent (pattern);
1170 if (pattern_percent == 0)
1171 fatal (fstart, _("target pattern contains no `%%'"));
1172 free ((char *)target);
1174 else
1175 pattern = 0;
1177 /* Strip leading and trailing whitespaces. */
1178 beg = p2;
1179 end = beg + strlen (beg) - 1;
1180 strip_whitespace (&beg, &end);
1182 if (beg <= end && *beg != '\0')
1184 /* Put all the prerequisites here; they'll be parsed later. */
1185 deps = (struct dep *) xmalloc (sizeof (struct dep));
1186 deps->next = 0;
1187 deps->name = savestring (beg, end - beg + 1);
1188 deps->file = 0;
1189 deps->changed = 0;
1190 deps->ignore_mtime = 0;
1191 deps->staticpattern = 0;
1192 deps->need_2nd_expansion = 0;
1194 else
1195 deps = 0;
1197 commands_idx = 0;
1198 if (cmdleft != 0)
1200 /* Semicolon means rest of line is a command. */
1201 unsigned int len = strlen (cmdleft);
1203 cmds_started = fstart->lineno;
1205 /* Add this command line to the buffer. */
1206 if (len + 2 > commands_len)
1208 commands_len = (len + 2) * 2;
1209 commands = (char *) xrealloc (commands, commands_len);
1211 bcopy (cmdleft, commands, len);
1212 commands_idx += len;
1213 commands[commands_idx++] = '\n';
1216 /* Determine if this target should be made default. We used to do
1217 this in record_files() but because of the delayed target recording
1218 and because preprocessor directives are legal in target's commands
1219 it is too late. Consider this fragment for example:
1221 foo:
1223 ifeq ($(.DEFAULT_GOAL),foo)
1225 endif
1227 Because the target is not recorded until after ifeq directive is
1228 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1229 would expect. Because of this we have to move some of the logic
1230 here. */
1232 if (**default_goal_name == '\0' && set_default)
1234 char* name;
1235 struct dep *d;
1236 struct nameseq *t = filenames;
1238 for (; t != 0; t = t->next)
1240 int reject = 0;
1241 name = t->name;
1243 /* We have nothing to do if this is an implicit rule. */
1244 if (strchr (name, '%') != 0)
1245 break;
1247 /* See if this target's name does not start with a `.',
1248 unless it contains a slash. */
1249 if (*name == '.' && strchr (name, '/') == 0
1250 #ifdef HAVE_DOS_PATHS
1251 && strchr (name, '\\') == 0
1252 #endif
1254 continue;
1257 /* If this file is a suffix, don't let it be
1258 the default goal file. */
1259 for (d = suffix_file->deps; d != 0; d = d->next)
1261 register struct dep *d2;
1262 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1264 reject = 1;
1265 break;
1267 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1269 register unsigned int len = strlen (dep_name (d2));
1270 if (!strneq (name, dep_name (d2), len))
1271 continue;
1272 if (streq (name + len, dep_name (d)))
1274 reject = 1;
1275 break;
1279 if (reject)
1280 break;
1283 if (!reject)
1285 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1286 o_file, 0, NILF);
1287 break;
1292 continue;
1295 /* We get here except in the case that we just read a rule line.
1296 Record now the last rule we read, so following spurious
1297 commands are properly diagnosed. */
1298 rule_complete:
1299 record_waiting_files ();
1302 #undef word1eq
1304 if (conditionals->if_cmds)
1305 fatal (fstart, _("missing `endif'"));
1307 /* At eof, record the last rule. */
1308 record_waiting_files ();
1310 if (collapsed)
1311 free ((char *) collapsed);
1312 free ((char *) commands);
1314 return 1;
1318 /* Remove comments from LINE.
1319 This is done by copying the text at LINE onto itself. */
1321 static void
1322 remove_comments (char *line)
1324 char *comment;
1326 comment = find_char_unquote (line, '#', 0, 0, 0);
1328 if (comment != 0)
1329 /* Cut off the line at the #. */
1330 *comment = '\0';
1333 /* Execute a `define' directive.
1334 The first line has already been read, and NAME is the name of
1335 the variable to be defined. The following lines remain to be read. */
1337 static void
1338 do_define (char *name, unsigned int namelen,
1339 enum variable_origin origin, struct ebuffer *ebuf)
1341 struct floc defstart;
1342 long nlines = 0;
1343 int nlevels = 1;
1344 unsigned int length = 100;
1345 char *definition = (char *) xmalloc (length);
1346 unsigned int idx = 0;
1347 char *p;
1349 /* Expand the variable name. */
1350 char *var = (char *) alloca (namelen + 1);
1351 bcopy (name, var, namelen);
1352 var[namelen] = '\0';
1353 var = variable_expand (var);
1355 defstart = ebuf->floc;
1357 while (1)
1359 unsigned int len;
1360 char *line;
1362 nlines = readline (ebuf);
1363 ebuf->floc.lineno += nlines;
1365 /* If there is nothing left to eval, we're done. */
1366 if (nlines < 0)
1367 break;
1369 line = ebuf->buffer;
1371 collapse_continuations (line);
1373 /* If the line doesn't begin with a tab, test to see if it introduces
1374 another define, or ends one. */
1376 /* Stop if we find an 'endef' */
1377 if (line[0] != '\t')
1379 p = next_token (line);
1380 len = strlen (p);
1382 /* If this is another 'define', increment the level count. */
1383 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1384 && strneq (p, "define", 6))
1385 ++nlevels;
1387 /* If this is an 'endef', decrement the count. If it's now 0,
1388 we've found the last one. */
1389 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1390 && strneq (p, "endef", 5))
1392 p += 5;
1393 remove_comments (p);
1394 if (*next_token (p) != '\0')
1395 error (&ebuf->floc,
1396 _("Extraneous text after `endef' directive"));
1398 if (--nlevels == 0)
1400 /* Define the variable. */
1401 if (idx == 0)
1402 definition[0] = '\0';
1403 else
1404 definition[idx - 1] = '\0';
1406 /* Always define these variables in the global set. */
1407 define_variable_global (var, strlen (var), definition,
1408 origin, 1, &defstart);
1409 free (definition);
1410 return;
1415 /* Otherwise add this line to the variable definition. */
1416 len = strlen (line);
1417 if (idx + len + 1 > length)
1419 length = (idx + len) * 2;
1420 definition = (char *) xrealloc (definition, length + 1);
1423 bcopy (line, &definition[idx], len);
1424 idx += len;
1425 /* Separate lines with a newline. */
1426 definition[idx++] = '\n';
1429 /* No `endef'!! */
1430 fatal (&defstart, _("missing `endef', unterminated `define'"));
1432 /* NOTREACHED */
1433 return;
1436 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1437 "ifneq", "else" and "endif".
1438 LINE is the input line, with the command as its first word.
1440 FILENAME and LINENO are the filename and line number in the
1441 current makefile. They are used for error messages.
1443 Value is -2 if the line is not a conditional at all,
1444 -1 if the line is an invalid conditional,
1445 0 if following text should be interpreted,
1446 1 if following text should be ignored. */
1448 static int
1449 conditional_line (char *line, int len, const struct floc *flocp)
1451 char *cmdname;
1452 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1453 unsigned int i;
1454 unsigned int o;
1456 /* Compare a word, both length and contents. */
1457 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1458 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1460 /* Make sure this line is a conditional. */
1461 chkword ("ifdef", c_ifdef)
1462 else chkword ("ifndef", c_ifndef)
1463 else chkword ("ifeq", c_ifeq)
1464 else chkword ("ifneq", c_ifneq)
1465 else chkword ("else", c_else)
1466 else chkword ("endif", c_endif)
1467 else
1468 return -2;
1470 /* Found one: skip past it and any whitespace after it. */
1471 line = next_token (line + len);
1473 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1475 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1476 if (cmdtype == c_endif)
1478 if (*line != '\0')
1479 EXTRANEOUS ();
1481 if (!conditionals->if_cmds)
1482 fatal (flocp, _("extraneous `%s'"), cmdname);
1484 --conditionals->if_cmds;
1486 goto DONE;
1489 /* An 'else' statement can either be simple, or it can have another
1490 conditional after it. */
1491 if (cmdtype == c_else)
1493 const char *p;
1495 if (!conditionals->if_cmds)
1496 fatal (flocp, _("extraneous `%s'"), cmdname);
1498 o = conditionals->if_cmds - 1;
1500 if (conditionals->seen_else[o])
1501 fatal (flocp, _("only one `else' per conditional"));
1503 /* Change the state of ignorance. */
1504 switch (conditionals->ignoring[o])
1506 case 0:
1507 /* We've just been interpreting. Never do it again. */
1508 conditionals->ignoring[o] = 2;
1509 break;
1510 case 1:
1511 /* We've never interpreted yet. Maybe this time! */
1512 conditionals->ignoring[o] = 0;
1513 break;
1516 /* It's a simple 'else'. */
1517 if (*line == '\0')
1519 conditionals->seen_else[o] = 1;
1520 goto DONE;
1523 /* The 'else' has extra text. That text must be another conditional
1524 and cannot be an 'else' or 'endif'. */
1526 /* Find the length of the next word. */
1527 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1529 len = p - line;
1531 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1532 if (word1eq("else") || word1eq("endif")
1533 || conditional_line (line, len, flocp) < 0)
1534 EXTRANEOUS ();
1535 else
1537 /* conditional_line() created a new level of conditional.
1538 Raise it back to this level. */
1539 if (conditionals->ignoring[o] < 2)
1540 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1541 --conditionals->if_cmds;
1544 goto DONE;
1547 if (conditionals->allocated == 0)
1549 conditionals->allocated = 5;
1550 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1551 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1554 o = conditionals->if_cmds++;
1555 if (conditionals->if_cmds > conditionals->allocated)
1557 conditionals->allocated += 5;
1558 conditionals->ignoring = (char *)
1559 xrealloc (conditionals->ignoring, conditionals->allocated);
1560 conditionals->seen_else = (char *)
1561 xrealloc (conditionals->seen_else, conditionals->allocated);
1564 /* Record that we have seen an `if...' but no `else' so far. */
1565 conditionals->seen_else[o] = 0;
1567 /* Search through the stack to see if we're already ignoring. */
1568 for (i = 0; i < o; ++i)
1569 if (conditionals->ignoring[i])
1571 /* We are already ignoring, so just push a level to match the next
1572 "else" or "endif", and keep ignoring. We don't want to expand
1573 variables in the condition. */
1574 conditionals->ignoring[o] = 1;
1575 return 1;
1578 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1580 char *var;
1581 struct variable *v;
1582 char *p;
1584 /* Expand the thing we're looking up, so we can use indirect and
1585 constructed variable names. */
1586 var = allocated_variable_expand (line);
1588 /* Make sure there's only one variable name to test. */
1589 p = end_of_token (var);
1590 i = p - var;
1591 p = next_token (p);
1592 if (*p != '\0')
1593 return -1;
1595 var[i] = '\0';
1596 v = lookup_variable (var, i);
1598 conditionals->ignoring[o] =
1599 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1601 free (var);
1603 else
1605 /* "Ifeq" or "ifneq". */
1606 char *s1, *s2;
1607 unsigned int len;
1608 char termin = *line == '(' ? ',' : *line;
1610 if (termin != ',' && termin != '"' && termin != '\'')
1611 return -1;
1613 s1 = ++line;
1614 /* Find the end of the first string. */
1615 if (termin == ',')
1617 int count = 0;
1618 for (; *line != '\0'; ++line)
1619 if (*line == '(')
1620 ++count;
1621 else if (*line == ')')
1622 --count;
1623 else if (*line == ',' && count <= 0)
1624 break;
1626 else
1627 while (*line != '\0' && *line != termin)
1628 ++line;
1630 if (*line == '\0')
1631 return -1;
1633 if (termin == ',')
1635 /* Strip blanks after the first string. */
1636 char *p = line++;
1637 while (isblank ((unsigned char)p[-1]))
1638 --p;
1639 *p = '\0';
1641 else
1642 *line++ = '\0';
1644 s2 = variable_expand (s1);
1645 /* We must allocate a new copy of the expanded string because
1646 variable_expand re-uses the same buffer. */
1647 len = strlen (s2);
1648 s1 = (char *) alloca (len + 1);
1649 bcopy (s2, s1, len + 1);
1651 if (termin != ',')
1652 /* Find the start of the second string. */
1653 line = next_token (line);
1655 termin = termin == ',' ? ')' : *line;
1656 if (termin != ')' && termin != '"' && termin != '\'')
1657 return -1;
1659 /* Find the end of the second string. */
1660 if (termin == ')')
1662 register int count = 0;
1663 s2 = next_token (line);
1664 for (line = s2; *line != '\0'; ++line)
1666 if (*line == '(')
1667 ++count;
1668 else if (*line == ')')
1670 if (count <= 0)
1671 break;
1672 else
1673 --count;
1677 else
1679 ++line;
1680 s2 = line;
1681 while (*line != '\0' && *line != termin)
1682 ++line;
1685 if (*line == '\0')
1686 return -1;
1688 *line = '\0';
1689 line = next_token (++line);
1690 if (*line != '\0')
1691 EXTRANEOUS ();
1693 s2 = variable_expand (s2);
1694 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1697 DONE:
1698 /* Search through the stack to see if we're ignoring. */
1699 for (i = 0; i < conditionals->if_cmds; ++i)
1700 if (conditionals->ignoring[i])
1701 return 1;
1702 return 0;
1705 /* Remove duplicate dependencies in CHAIN. */
1707 static unsigned long
1708 dep_hash_1 (const void *key)
1710 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1713 static unsigned long
1714 dep_hash_2 (const void *key)
1716 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1719 static int
1720 dep_hash_cmp (const void *x, const void *y)
1722 struct dep *dx = (struct dep *) x;
1723 struct dep *dy = (struct dep *) y;
1724 int cmp = strcmp (dep_name (dx), dep_name (dy));
1726 /* If the names are the same but ignore_mtimes are not equal, one of these
1727 is an order-only prerequisite and one isn't. That means that we should
1728 remove the one that isn't and keep the one that is. */
1730 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1731 dx->ignore_mtime = dy->ignore_mtime = 0;
1733 return cmp;
1737 void
1738 uniquize_deps (struct dep *chain)
1740 struct hash_table deps;
1741 register struct dep **depp;
1743 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1745 /* Make sure that no dependencies are repeated. This does not
1746 really matter for the purpose of updating targets, but it
1747 might make some names be listed twice for $^ and $?. */
1749 depp = &chain;
1750 while (*depp)
1752 struct dep *dep = *depp;
1753 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1754 if (HASH_VACANT (*dep_slot))
1756 hash_insert_at (&deps, dep, dep_slot);
1757 depp = &dep->next;
1759 else
1761 /* Don't bother freeing duplicates.
1762 It's dangerous and little benefit accrues. */
1763 *depp = dep->next;
1767 hash_free (&deps, 0);
1770 /* Record target-specific variable values for files FILENAMES.
1771 TWO_COLON is nonzero if a double colon was used.
1773 The links of FILENAMES are freed, and so are any names in it
1774 that are not incorporated into other data structures.
1776 If the target is a pattern, add the variable to the pattern-specific
1777 variable value list. */
1779 static void
1780 record_target_var (struct nameseq *filenames, char *defn,
1781 enum variable_origin origin, int exported,
1782 const struct floc *flocp)
1784 struct nameseq *nextf;
1785 struct variable_set_list *global;
1787 global = current_variable_set_list;
1789 /* If the variable is an append version, store that but treat it as a
1790 normal recursive variable. */
1792 for (; filenames != 0; filenames = nextf)
1794 struct variable *v;
1795 register char *name = filenames->name;
1796 char *fname;
1797 char *percent;
1798 struct pattern_var *p;
1800 nextf = filenames->next;
1801 free ((char *) filenames);
1803 /* If it's a pattern target, then add it to the pattern-specific
1804 variable list. */
1805 percent = find_percent (name);
1806 if (percent)
1808 /* Get a reference for this pattern-specific variable struct. */
1809 p = create_pattern_var (name, percent);
1810 p->variable.fileinfo = *flocp;
1811 /* I don't think this can fail since we already determined it was a
1812 variable definition. */
1813 v = parse_variable_definition (&p->variable, defn);
1814 assert (v != 0);
1816 if (v->flavor == f_simple)
1817 v->value = allocated_variable_expand (v->value);
1818 else
1819 v->value = xstrdup (v->value);
1821 fname = p->target;
1823 else
1825 struct file *f;
1827 /* Get a file reference for this file, and initialize it.
1828 We don't want to just call enter_file() because that allocates a
1829 new entry if the file is a double-colon, which we don't want in
1830 this situation. */
1831 f = lookup_file (name);
1832 if (!f)
1833 f = enter_file (name);
1834 else if (f->double_colon)
1835 f = f->double_colon;
1837 initialize_file_variables (f, 1);
1838 fname = f->name;
1840 current_variable_set_list = f->variables;
1841 v = try_variable_definition (flocp, defn, origin, 1);
1842 if (!v)
1843 error (flocp, _("Malformed target-specific variable definition"));
1844 current_variable_set_list = global;
1847 /* Set up the variable to be *-specific. */
1848 v->origin = origin;
1849 v->per_target = 1;
1850 v->export = exported ? v_export : v_default;
1852 /* If it's not an override, check to see if there was a command-line
1853 setting. If so, reset the value. */
1854 if (origin != o_override)
1856 struct variable *gv;
1857 int len = strlen(v->name);
1859 gv = lookup_variable (v->name, len);
1860 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1862 if (v->value != 0)
1863 free (v->value);
1864 v->value = xstrdup (gv->value);
1865 v->origin = gv->origin;
1866 v->recursive = gv->recursive;
1867 v->append = 0;
1871 /* Free name if not needed further. */
1872 if (name != fname && (name < fname || name > fname + strlen (fname)))
1873 free (name);
1877 /* Record a description line for files FILENAMES,
1878 with dependencies DEPS, commands to execute described
1879 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1880 TWO_COLON is nonzero if a double colon was used.
1881 If not nil, PATTERN is the `%' pattern to make this
1882 a static pattern rule, and PATTERN_PERCENT is a pointer
1883 to the `%' within it.
1885 The links of FILENAMES are freed, and so are any names in it
1886 that are not incorporated into other data structures. */
1888 static void
1889 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1890 struct dep *deps, unsigned int cmds_started, char *commands,
1891 unsigned int commands_idx, int two_colon,
1892 const struct floc *flocp)
1894 struct nameseq *nextf;
1895 int implicit = 0;
1896 unsigned int max_targets = 0, target_idx = 0;
1897 char **targets = 0, **target_percents = 0;
1898 struct commands *cmds;
1900 /* If we've already snapped deps, that means we're in an eval being
1901 resolved after the makefiles have been read in. We can't add more rules
1902 at this time, since they won't get snapped and we'll get core dumps.
1903 See Savannah bug # 12124. */
1904 if (snapped_deps)
1905 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1907 if (commands_idx > 0)
1909 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1910 cmds->fileinfo.filenm = flocp->filenm;
1911 cmds->fileinfo.lineno = cmds_started;
1912 cmds->commands = savestring (commands, commands_idx);
1913 cmds->command_lines = 0;
1915 else
1916 cmds = 0;
1918 for (; filenames != 0; filenames = nextf)
1920 char *name = filenames->name;
1921 struct file *f;
1922 struct dep *this = 0;
1923 char *implicit_percent;
1925 nextf = filenames->next;
1926 free (filenames);
1928 /* Check for special targets. Do it here instead of, say, snap_deps()
1929 so that we can immediately use the value. */
1931 if (streq (name, ".POSIX"))
1932 posix_pedantic = 1;
1933 else if (streq (name, ".SECONDEXPANSION"))
1934 second_expansion = 1;
1936 implicit_percent = find_percent (name);
1937 implicit |= implicit_percent != 0;
1939 if (implicit && pattern != 0)
1940 fatal (flocp, _("mixed implicit and static pattern rules"));
1942 if (implicit && implicit_percent == 0)
1943 fatal (flocp, _("mixed implicit and normal rules"));
1945 if (implicit)
1947 if (targets == 0)
1949 max_targets = 5;
1950 targets = (char **) xmalloc (5 * sizeof (char *));
1951 target_percents = (char **) xmalloc (5 * sizeof (char *));
1952 target_idx = 0;
1954 else if (target_idx == max_targets - 1)
1956 max_targets += 5;
1957 targets = (char **) xrealloc ((char *) targets,
1958 max_targets * sizeof (char *));
1959 target_percents
1960 = (char **) xrealloc ((char *) target_percents,
1961 max_targets * sizeof (char *));
1963 targets[target_idx] = name;
1964 target_percents[target_idx] = implicit_percent;
1965 ++target_idx;
1966 continue;
1969 /* If this is a static pattern rule:
1970 `targets: target%pattern: dep%pattern; cmds',
1971 make sure the pattern matches this target name. */
1972 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1973 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1974 else if (deps)
1976 /* If there are multiple filenames, copy the chain DEPS for all but
1977 the last one. It is not safe for the same deps to go in more
1978 than one place in the database. */
1979 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1980 this->need_2nd_expansion = (second_expansion
1981 && strchr (this->name, '$'));
1984 if (!two_colon)
1986 /* Single-colon. Combine these dependencies
1987 with others in file's existing record, if any. */
1988 f = enter_file (name);
1990 if (f->double_colon)
1991 fatal (flocp,
1992 _("target file `%s' has both : and :: entries"), f->name);
1994 /* If CMDS == F->CMDS, this target was listed in this rule
1995 more than once. Just give a warning since this is harmless. */
1996 if (cmds != 0 && cmds == f->cmds)
1997 error (flocp,
1998 _("target `%s' given more than once in the same rule."),
1999 f->name);
2001 /* Check for two single-colon entries both with commands.
2002 Check is_target so that we don't lose on files such as .c.o
2003 whose commands were preinitialized. */
2004 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2006 error (&cmds->fileinfo,
2007 _("warning: overriding commands for target `%s'"),
2008 f->name);
2009 error (&f->cmds->fileinfo,
2010 _("warning: ignoring old commands for target `%s'"),
2011 f->name);
2014 f->is_target = 1;
2016 /* Defining .DEFAULT with no deps or cmds clears it. */
2017 if (f == default_file && this == 0 && cmds == 0)
2018 f->cmds = 0;
2019 if (cmds != 0)
2020 f->cmds = cmds;
2022 /* Defining .SUFFIXES with no dependencies clears out the list of
2023 suffixes. */
2024 if (f == suffix_file && this == 0)
2026 free_dep_chain (f->deps);
2027 f->deps = 0;
2029 else if (this != 0)
2031 /* Add the file's old deps and the new ones in THIS together. */
2033 if (f->deps != 0)
2035 struct dep **d_ptr = &f->deps;
2037 while ((*d_ptr)->next != 0)
2038 d_ptr = &(*d_ptr)->next;
2040 if (cmds != 0)
2041 /* This is the rule with commands, so put its deps
2042 last. The rationale behind this is that $< expands to
2043 the first dep in the chain, and commands use $<
2044 expecting to get the dep that rule specifies. However
2045 the second expansion algorithm reverses the order thus
2046 we need to make it last here. */
2047 (*d_ptr)->next = this;
2048 else
2050 /* This is the rule without commands. Put its
2051 dependencies at the end but before dependencies from
2052 the rule with commands (if any). This way everything
2053 appears in makefile order. */
2055 if (f->cmds != 0)
2057 this->next = *d_ptr;
2058 *d_ptr = this;
2060 else
2061 (*d_ptr)->next = this;
2064 else
2065 f->deps = this;
2067 /* This is a hack. I need a way to communicate to snap_deps()
2068 that the last dependency line in this file came with commands
2069 (so that logic in snap_deps() can put it in front and all
2070 this $< -logic works). I cannot simply rely on file->cmds
2071 being not 0 because of the cases like the following:
2073 foo: bar
2074 foo:
2077 I am going to temporarily "borrow" UPDATING member in
2078 `struct file' for this. */
2080 if (cmds != 0)
2081 f->updating = 1;
2084 else
2086 /* Double-colon. Make a new record even if there already is one. */
2087 f = lookup_file (name);
2089 /* Check for both : and :: rules. Check is_target so
2090 we don't lose on default suffix rules or makefiles. */
2091 if (f != 0 && f->is_target && !f->double_colon)
2092 fatal (flocp,
2093 _("target file `%s' has both : and :: entries"), f->name);
2094 f = enter_file (name);
2095 /* If there was an existing entry and it was a double-colon entry,
2096 enter_file will have returned a new one, making it the prev
2097 pointer of the old one, and setting its double_colon pointer to
2098 the first one. */
2099 if (f->double_colon == 0)
2100 /* This is the first entry for this name, so we must set its
2101 double_colon pointer to itself. */
2102 f->double_colon = f;
2103 f->is_target = 1;
2104 f->deps = this;
2105 f->cmds = cmds;
2108 /* If this is a static pattern rule, set the stem to the part of its
2109 name that matched the `%' in the pattern, so you can use $* in the
2110 commands. */
2111 if (pattern)
2113 static char *percent = "%";
2114 char *buffer = variable_expand ("");
2115 char *o = patsubst_expand (buffer, name, pattern, percent,
2116 pattern_percent+1, percent+1);
2117 f->stem = savestring (buffer, o - buffer);
2118 if (this)
2119 this->staticpattern = 1;
2122 /* Free name if not needed further. */
2123 if (f != 0 && name != f->name
2124 && (name < f->name || name > f->name + strlen (f->name)))
2126 free (name);
2127 name = f->name;
2130 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2131 if (streq (*default_goal_name, name)
2132 && (default_goal_file == 0
2133 || ! streq (default_goal_file->name, name)))
2134 default_goal_file = f;
2137 if (implicit)
2139 targets[target_idx] = 0;
2140 target_percents[target_idx] = 0;
2141 if (deps)
2142 deps->need_2nd_expansion = second_expansion;
2143 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2144 free ((char *) target_percents);
2148 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2149 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2150 Quoting backslashes are removed from STRING by compacting it into
2151 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2152 one, or nil if there are none. STOPCHARs inside variable references are
2153 ignored if IGNOREVARS is true.
2155 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2157 static char *
2158 find_char_unquote (char *string, int stop1, int stop2, int blank,
2159 int ignorevars)
2161 unsigned int string_len = 0;
2162 register char *p = string;
2164 if (ignorevars)
2165 ignorevars = '$';
2167 while (1)
2169 if (stop2 && blank)
2170 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2171 && ! isblank ((unsigned char) *p))
2172 ++p;
2173 else if (stop2)
2174 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2175 ++p;
2176 else if (blank)
2177 while (*p != '\0' && *p != ignorevars && *p != stop1
2178 && ! isblank ((unsigned char) *p))
2179 ++p;
2180 else
2181 while (*p != '\0' && *p != ignorevars && *p != stop1)
2182 ++p;
2184 if (*p == '\0')
2185 break;
2187 /* If we stopped due to a variable reference, skip over its contents. */
2188 if (*p == ignorevars)
2190 char openparen = p[1];
2192 p += 2;
2194 /* Skip the contents of a non-quoted, multi-char variable ref. */
2195 if (openparen == '(' || openparen == '{')
2197 unsigned int pcount = 1;
2198 char closeparen = (openparen == '(' ? ')' : '}');
2200 while (*p)
2202 if (*p == openparen)
2203 ++pcount;
2204 else if (*p == closeparen)
2205 if (--pcount == 0)
2207 ++p;
2208 break;
2210 ++p;
2214 /* Skipped the variable reference: look for STOPCHARS again. */
2215 continue;
2218 if (p > string && p[-1] == '\\')
2220 /* Search for more backslashes. */
2221 register int i = -2;
2222 while (&p[i] >= string && p[i] == '\\')
2223 --i;
2224 ++i;
2225 /* Only compute the length if really needed. */
2226 if (string_len == 0)
2227 string_len = strlen (string);
2228 /* The number of backslashes is now -I.
2229 Copy P over itself to swallow half of them. */
2230 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2231 p += i / 2;
2232 if (i % 2 == 0)
2233 /* All the backslashes quoted each other; the STOPCHAR was
2234 unquoted. */
2235 return p;
2237 /* The STOPCHAR was quoted by a backslash. Look for another. */
2239 else
2240 /* No backslash in sight. */
2241 return p;
2244 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2245 return 0;
2248 /* Search PATTERN for an unquoted %. */
2250 char *
2251 find_percent (char *pattern)
2253 return find_char_unquote (pattern, '%', 0, 0, 0);
2256 /* Parse a string into a sequence of filenames represented as a
2257 chain of struct nameseq's in reverse order and return that chain.
2259 The string is passed as STRINGP, the address of a string pointer.
2260 The string pointer is updated to point at the first character
2261 not parsed, which either is a null char or equals STOPCHAR.
2263 SIZE is how big to construct chain elements.
2264 This is useful if we want them actually to be other structures
2265 that have room for additional info.
2267 If STRIP is nonzero, strip `./'s off the beginning. */
2269 struct nameseq *
2270 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2272 struct nameseq *new = 0;
2273 struct nameseq *new1, *lastnew1;
2274 char *p = *stringp;
2275 char *q;
2276 char *name;
2278 #ifdef VMS
2279 # define VMS_COMMA ','
2280 #else
2281 # define VMS_COMMA 0
2282 #endif
2284 while (1)
2286 /* Skip whitespace; see if any more names are left. */
2287 p = next_token (p);
2288 if (*p == '\0')
2289 break;
2290 if (*p == stopchar)
2291 break;
2293 /* Yes, find end of next name. */
2294 q = p;
2295 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2296 #ifdef VMS
2297 /* convert comma separated list to space separated */
2298 if (p && *p == ',')
2299 *p =' ';
2300 #endif
2301 #ifdef _AMIGA
2302 if (stopchar == ':' && p && *p == ':'
2303 && !(isspace ((unsigned char)p[1]) || !p[1]
2304 || isspace ((unsigned char)p[-1])))
2306 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2308 #endif
2309 #ifdef HAVE_DOS_PATHS
2310 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2311 first colon which isn't followed by a slash or a backslash.
2312 Note that tokens separated by spaces should be treated as separate
2313 tokens since make doesn't allow path names with spaces */
2314 if (stopchar == ':')
2315 while (p != 0 && !isspace ((unsigned char)*p) &&
2316 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2317 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2318 #endif
2319 if (p == 0)
2320 p = q + strlen (q);
2322 if (strip)
2323 #ifdef VMS
2324 /* Skip leading `[]'s. */
2325 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2326 #else
2327 /* Skip leading `./'s. */
2328 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2329 #endif
2331 q += 2; /* Skip "./". */
2332 while (q < p && *q == '/')
2333 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2334 ++q;
2337 /* Extract the filename just found, and skip it. */
2339 if (q == p)
2340 /* ".///" was stripped to "". */
2341 #ifdef VMS
2342 continue;
2343 #else
2344 #ifdef _AMIGA
2345 name = savestring ("", 0);
2346 #else
2347 name = savestring ("./", 2);
2348 #endif
2349 #endif
2350 else
2351 #ifdef VMS
2352 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2353 * to remove this '\' before we can use the filename.
2354 * Savestring called because q may be read-only string constant.
2357 char *qbase = xstrdup (q);
2358 char *pbase = qbase + (p-q);
2359 char *q1 = qbase;
2360 char *q2 = q1;
2361 char *p1 = pbase;
2363 while (q1 != pbase)
2365 if (*q1 == '\\' && *(q1+1) == ':')
2367 q1++;
2368 p1--;
2370 *q2++ = *q1++;
2372 name = savestring (qbase, p1 - qbase);
2373 free (qbase);
2375 #else
2376 name = savestring (q, p - q);
2377 #endif
2379 /* Add it to the front of the chain. */
2380 new1 = (struct nameseq *) xmalloc (size);
2381 new1->name = name;
2382 new1->next = new;
2383 new = new1;
2386 #ifndef NO_ARCHIVES
2388 /* Look for multi-word archive references.
2389 They are indicated by a elt ending with an unmatched `)' and
2390 an elt further down the chain (i.e., previous in the file list)
2391 with an unmatched `(' (e.g., "lib(mem"). */
2393 new1 = new;
2394 lastnew1 = 0;
2395 while (new1 != 0)
2396 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2397 && new1->name[strlen (new1->name) - 1] == ')'
2398 && strchr (new1->name, '(') == 0)
2400 /* NEW1 ends with a `)' but does not contain a `('.
2401 Look back for an elt with an opening `(' but no closing `)'. */
2403 struct nameseq *n = new1->next, *lastn = new1;
2404 char *paren = 0;
2405 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2407 lastn = n;
2408 n = n->next;
2410 if (n != 0
2411 /* Ignore something starting with `(', as that cannot actually
2412 be an archive-member reference (and treating it as such
2413 results in an empty file name, which causes much lossage). */
2414 && n->name[0] != '(')
2416 /* N is the first element in the archive group.
2417 Its name looks like "lib(mem" (with no closing `)'). */
2419 char *libname;
2421 /* Copy "lib(" into LIBNAME. */
2422 ++paren;
2423 libname = (char *) alloca (paren - n->name + 1);
2424 bcopy (n->name, libname, paren - n->name);
2425 libname[paren - n->name] = '\0';
2427 if (*paren == '\0')
2429 /* N was just "lib(", part of something like "lib( a b)".
2430 Edit it out of the chain and free its storage. */
2431 lastn->next = n->next;
2432 free (n->name);
2433 free ((char *) n);
2434 /* LASTN->next is the new stopping elt for the loop below. */
2435 n = lastn->next;
2437 else
2439 /* Replace N's name with the full archive reference. */
2440 name = concat (libname, paren, ")");
2441 free (n->name);
2442 n->name = name;
2445 if (new1->name[1] == '\0')
2447 /* NEW1 is just ")", part of something like "lib(a b )".
2448 Omit it from the chain and free its storage. */
2449 if (lastnew1 == 0)
2450 new = new1->next;
2451 else
2452 lastnew1->next = new1->next;
2453 lastn = new1;
2454 new1 = new1->next;
2455 free (lastn->name);
2456 free ((char *) lastn);
2458 else
2460 /* Replace also NEW1->name, which already has closing `)'. */
2461 name = concat (libname, new1->name, "");
2462 free (new1->name);
2463 new1->name = name;
2464 new1 = new1->next;
2467 /* Trace back from NEW1 (the end of the list) until N
2468 (the beginning of the list), rewriting each name
2469 with the full archive reference. */
2471 while (new1 != n)
2473 name = concat (libname, new1->name, ")");
2474 free (new1->name);
2475 new1->name = name;
2476 lastnew1 = new1;
2477 new1 = new1->next;
2480 else
2482 /* No frobnication happening. Just step down the list. */
2483 lastnew1 = new1;
2484 new1 = new1->next;
2487 else
2489 lastnew1 = new1;
2490 new1 = new1->next;
2493 #endif
2495 *stringp = p;
2496 return new;
2499 /* Find the next line of text in an eval buffer, combining continuation lines
2500 into one line.
2501 Return the number of actual lines read (> 1 if continuation lines).
2502 Returns -1 if there's nothing left in the buffer.
2504 After this function, ebuf->buffer points to the first character of the
2505 line we just found.
2508 /* Read a line of text from a STRING.
2509 Since we aren't really reading from a file, don't bother with linenumbers.
2512 static unsigned long
2513 readstring (struct ebuffer *ebuf)
2515 char *eol;
2517 /* If there is nothing left in this buffer, return 0. */
2518 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2519 return -1;
2521 /* Set up a new starting point for the buffer, and find the end of the
2522 next logical line (taking into account backslash/newline pairs). */
2524 eol = ebuf->buffer = ebuf->bufnext;
2526 while (1)
2528 int backslash = 0;
2529 char *bol = eol;
2530 char *p;
2532 /* Find the next newline. At EOS, stop. */
2533 eol = p = strchr (eol , '\n');
2534 if (!eol)
2536 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2537 return 0;
2540 /* Found a newline; if it's escaped continue; else we're done. */
2541 while (p > bol && *(--p) == '\\')
2542 backslash = !backslash;
2543 if (!backslash)
2544 break;
2545 ++eol;
2548 /* Overwrite the newline char. */
2549 *eol = '\0';
2550 ebuf->bufnext = eol+1;
2552 return 0;
2555 static long
2556 readline (struct ebuffer *ebuf)
2558 char *p;
2559 char *end;
2560 char *start;
2561 long nlines = 0;
2563 /* The behaviors between string and stream buffers are different enough to
2564 warrant different functions. Do the Right Thing. */
2566 if (!ebuf->fp)
2567 return readstring (ebuf);
2569 /* When reading from a file, we always start over at the beginning of the
2570 buffer for each new line. */
2572 p = start = ebuf->bufstart;
2573 end = p + ebuf->size;
2574 *p = '\0';
2576 while (fgets (p, end - p, ebuf->fp) != 0)
2578 char *p2;
2579 unsigned long len;
2580 int backslash;
2582 len = strlen (p);
2583 if (len == 0)
2585 /* This only happens when the first thing on the line is a '\0'.
2586 It is a pretty hopeless case, but (wonder of wonders) Athena
2587 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2588 There is nothing really to be done; we synthesize a newline so
2589 the following line doesn't appear to be part of this line. */
2590 error (&ebuf->floc,
2591 _("warning: NUL character seen; rest of line ignored"));
2592 p[0] = '\n';
2593 len = 1;
2596 /* Jump past the text we just read. */
2597 p += len;
2599 /* If the last char isn't a newline, the whole line didn't fit into the
2600 buffer. Get some more buffer and try again. */
2601 if (p[-1] != '\n')
2602 goto more_buffer;
2604 /* We got a newline, so add one to the count of lines. */
2605 ++nlines;
2607 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2608 /* Check to see if the line was really ended with CRLF; if so ignore
2609 the CR. */
2610 if ((p - start) > 1 && p[-2] == '\r')
2612 --p;
2613 p[-1] = '\n';
2615 #endif
2617 backslash = 0;
2618 for (p2 = p - 2; p2 >= start; --p2)
2620 if (*p2 != '\\')
2621 break;
2622 backslash = !backslash;
2625 if (!backslash)
2627 p[-1] = '\0';
2628 break;
2631 /* It was a backslash/newline combo. If we have more space, read
2632 another line. */
2633 if (end - p >= 80)
2634 continue;
2636 /* We need more space at the end of our buffer, so realloc it.
2637 Make sure to preserve the current offset of p. */
2638 more_buffer:
2640 unsigned long off = p - start;
2641 ebuf->size *= 2;
2642 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2643 ebuf->size);
2644 p = start + off;
2645 end = start + ebuf->size;
2646 *p = '\0';
2650 if (ferror (ebuf->fp))
2651 pfatal_with_name (ebuf->floc.filenm);
2653 /* If we found some lines, return how many.
2654 If we didn't, but we did find _something_, that indicates we read the last
2655 line of a file with no final newline; return 1.
2656 If we read nothing, we're at EOF; return -1. */
2658 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2661 /* Parse the next "makefile word" from the input buffer, and return info
2662 about it.
2664 A "makefile word" is one of:
2666 w_bogus Should never happen
2667 w_eol End of input
2668 w_static A static word; cannot be expanded
2669 w_variable A word containing one or more variables/functions
2670 w_colon A colon
2671 w_dcolon A double-colon
2672 w_semicolon A semicolon
2673 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2675 Note that this function is only used when reading certain parts of the
2676 makefile. Don't use it where special rules hold sway (RHS of a variable,
2677 in a command list, etc.) */
2679 static enum make_word_type
2680 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2682 enum make_word_type wtype = w_bogus;
2683 char *p = buffer, *beg;
2684 char c;
2686 /* Skip any leading whitespace. */
2687 while (isblank ((unsigned char)*p))
2688 ++p;
2690 beg = p;
2691 c = *(p++);
2692 switch (c)
2694 case '\0':
2695 wtype = w_eol;
2696 break;
2698 case ';':
2699 wtype = w_semicolon;
2700 break;
2702 case '=':
2703 wtype = w_varassign;
2704 break;
2706 case ':':
2707 wtype = w_colon;
2708 switch (*p)
2710 case ':':
2711 ++p;
2712 wtype = w_dcolon;
2713 break;
2715 case '=':
2716 ++p;
2717 wtype = w_varassign;
2718 break;
2720 break;
2722 case '+':
2723 case '?':
2724 if (*p == '=')
2726 ++p;
2727 wtype = w_varassign;
2728 break;
2731 default:
2732 if (delim && strchr (delim, c))
2733 wtype = w_static;
2734 break;
2737 /* Did we find something? If so, return now. */
2738 if (wtype != w_bogus)
2739 goto done;
2741 /* This is some non-operator word. A word consists of the longest
2742 string of characters that doesn't contain whitespace, one of [:=#],
2743 or [?+]=, or one of the chars in the DELIM string. */
2745 /* We start out assuming a static word; if we see a variable we'll
2746 adjust our assumptions then. */
2747 wtype = w_static;
2749 /* We already found the first value of "c", above. */
2750 while (1)
2752 char closeparen;
2753 int count;
2755 switch (c)
2757 case '\0':
2758 case ' ':
2759 case '\t':
2760 case '=':
2761 goto done_word;
2763 case ':':
2764 #ifdef HAVE_DOS_PATHS
2765 /* A word CAN include a colon in its drive spec. The drive
2766 spec is allowed either at the beginning of a word, or as part
2767 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2768 if (!(p - beg >= 2
2769 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2770 && (p - beg == 2 || p[-3] == '(')))
2771 #endif
2772 goto done_word;
2774 case '$':
2775 c = *(p++);
2776 if (c == '$')
2777 break;
2779 /* This is a variable reference, so note that it's expandable.
2780 Then read it to the matching close paren. */
2781 wtype = w_variable;
2783 if (c == '(')
2784 closeparen = ')';
2785 else if (c == '{')
2786 closeparen = '}';
2787 else
2788 /* This is a single-letter variable reference. */
2789 break;
2791 for (count=0; *p != '\0'; ++p)
2793 if (*p == c)
2794 ++count;
2795 else if (*p == closeparen && --count < 0)
2797 ++p;
2798 break;
2801 break;
2803 case '?':
2804 case '+':
2805 if (*p == '=')
2806 goto done_word;
2807 break;
2809 case '\\':
2810 switch (*p)
2812 case ':':
2813 case ';':
2814 case '=':
2815 case '\\':
2816 ++p;
2817 break;
2819 break;
2821 default:
2822 if (delim && strchr (delim, c))
2823 goto done_word;
2824 break;
2827 c = *(p++);
2829 done_word:
2830 --p;
2832 done:
2833 if (startp)
2834 *startp = beg;
2835 if (length)
2836 *length = p - beg;
2837 return wtype;
2840 /* Construct the list of include directories
2841 from the arguments and the default list. */
2843 void
2844 construct_include_path (char **arg_dirs)
2846 register unsigned int i;
2847 #ifdef VAXC /* just don't ask ... */
2848 stat_t stbuf;
2849 #else
2850 struct stat stbuf;
2851 #endif
2852 /* Table to hold the dirs. */
2854 register unsigned int defsize = (sizeof (default_include_directories)
2855 / sizeof (default_include_directories[0]));
2856 register unsigned int max = 5;
2857 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2858 register unsigned int idx = 0;
2860 #ifdef __MSDOS__
2861 defsize++;
2862 #endif
2864 /* First consider any dirs specified with -I switches.
2865 Ignore dirs that don't exist. */
2867 if (arg_dirs != 0)
2868 while (*arg_dirs != 0)
2870 char *dir = *arg_dirs++;
2871 int e;
2873 if (dir[0] == '~')
2875 char *expanded = tilde_expand (dir);
2876 if (expanded != 0)
2877 dir = expanded;
2880 EINTRLOOP (e, stat (dir, &stbuf));
2881 if (e == 0 && S_ISDIR (stbuf.st_mode))
2883 if (idx == max - 1)
2885 max += 5;
2886 dirs = (char **)
2887 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2889 dirs[idx++] = dir;
2891 else if (dir != arg_dirs[-1])
2892 free (dir);
2895 /* Now add at the end the standard default dirs. */
2897 #ifdef __MSDOS__
2899 /* The environment variable $DJDIR holds the root of the
2900 DJGPP directory tree; add ${DJDIR}/include. */
2901 struct variable *djdir = lookup_variable ("DJDIR", 5);
2903 if (djdir)
2905 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2907 strcat (strcpy (defdir, djdir->value), "/include");
2908 dirs[idx++] = defdir;
2911 #endif
2913 for (i = 0; default_include_directories[i] != 0; ++i)
2915 int e;
2917 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2918 if (e == 0 && S_ISDIR (stbuf.st_mode))
2919 dirs[idx++] = default_include_directories[i];
2922 dirs[idx] = 0;
2924 /* Now compute the maximum length of any name in it. Also add each
2925 dir to the .INCLUDE_DIRS variable. */
2927 max_incl_len = 0;
2928 for (i = 0; i < idx; ++i)
2930 unsigned int len = strlen (dirs[i]);
2931 /* If dir name is written with a trailing slash, discard it. */
2932 if (dirs[i][len - 1] == '/')
2933 /* We can't just clobber a null in because it may have come from
2934 a literal string and literal strings may not be writable. */
2935 dirs[i] = savestring (dirs[i], len - 1);
2936 if (len > max_incl_len)
2937 max_incl_len = len;
2939 /* Append to .INCLUDE_DIRS. */
2940 do_variable_definition (NILF, ".INCLUDE_DIRS", dirs[i],
2941 o_default, f_append, 0);
2944 include_directories = dirs;
2947 /* Expand ~ or ~USER at the beginning of NAME.
2948 Return a newly malloc'd string or 0. */
2950 char *
2951 tilde_expand (char *name)
2953 #ifndef VMS
2954 if (name[1] == '/' || name[1] == '\0')
2956 extern char *getenv ();
2957 char *home_dir;
2958 int is_variable;
2961 /* Turn off --warn-undefined-variables while we expand HOME. */
2962 int save = warn_undefined_variables_flag;
2963 warn_undefined_variables_flag = 0;
2965 home_dir = allocated_variable_expand ("$(HOME)");
2967 warn_undefined_variables_flag = save;
2970 is_variable = home_dir[0] != '\0';
2971 if (!is_variable)
2973 free (home_dir);
2974 home_dir = getenv ("HOME");
2976 #if !defined(_AMIGA) && !defined(WINDOWS32)
2977 if (home_dir == 0 || home_dir[0] == '\0')
2979 extern char *getlogin ();
2980 char *logname = getlogin ();
2981 home_dir = 0;
2982 if (logname != 0)
2984 struct passwd *p = getpwnam (logname);
2985 if (p != 0)
2986 home_dir = p->pw_dir;
2989 #endif /* !AMIGA && !WINDOWS32 */
2990 if (home_dir != 0)
2992 char *new = concat (home_dir, "", name + 1);
2993 if (is_variable)
2994 free (home_dir);
2995 return new;
2998 #if !defined(_AMIGA) && !defined(WINDOWS32)
2999 else
3001 struct passwd *pwent;
3002 char *userend = strchr (name + 1, '/');
3003 if (userend != 0)
3004 *userend = '\0';
3005 pwent = getpwnam (name + 1);
3006 if (pwent != 0)
3008 if (userend == 0)
3009 return xstrdup (pwent->pw_dir);
3010 else
3011 return concat (pwent->pw_dir, "/", userend + 1);
3013 else if (userend != 0)
3014 *userend = '/';
3016 #endif /* !AMIGA && !WINDOWS32 */
3017 #endif /* !VMS */
3018 return 0;
3021 /* Given a chain of struct nameseq's describing a sequence of filenames,
3022 in reverse of the intended order, return a new chain describing the
3023 result of globbing the filenames. The new chain is in forward order.
3024 The links of the old chain are freed or used in the new chain.
3025 Likewise for the names in the old chain.
3027 SIZE is how big to construct chain elements.
3028 This is useful if we want them actually to be other structures
3029 that have room for additional info. */
3031 struct nameseq *
3032 multi_glob (struct nameseq *chain, unsigned int size)
3034 extern void dir_setup_glob ();
3035 register struct nameseq *new = 0;
3036 register struct nameseq *old;
3037 struct nameseq *nexto;
3038 glob_t gl;
3040 dir_setup_glob (&gl);
3042 for (old = chain; old != 0; old = nexto)
3044 #ifndef NO_ARCHIVES
3045 char *memname;
3046 #endif
3048 nexto = old->next;
3050 if (old->name[0] == '~')
3052 char *newname = tilde_expand (old->name);
3053 if (newname != 0)
3055 free (old->name);
3056 old->name = newname;
3060 #ifndef NO_ARCHIVES
3061 if (ar_name (old->name))
3063 /* OLD->name is an archive member reference.
3064 Replace it with the archive file name,
3065 and save the member name in MEMNAME.
3066 We will glob on the archive name and then
3067 reattach MEMNAME later. */
3068 char *arname;
3069 ar_parse_name (old->name, &arname, &memname);
3070 free (old->name);
3071 old->name = arname;
3073 else
3074 memname = 0;
3075 #endif /* !NO_ARCHIVES */
3077 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3079 case 0: /* Success. */
3081 register int i = gl.gl_pathc;
3082 while (i-- > 0)
3084 #ifndef NO_ARCHIVES
3085 if (memname != 0)
3087 /* Try to glob on MEMNAME within the archive. */
3088 struct nameseq *found
3089 = ar_glob (gl.gl_pathv[i], memname, size);
3090 if (found == 0)
3092 /* No matches. Use MEMNAME as-is. */
3093 unsigned int alen = strlen (gl.gl_pathv[i]);
3094 unsigned int mlen = strlen (memname);
3095 struct nameseq *elt
3096 = (struct nameseq *) xmalloc (size);
3097 if (size > sizeof (struct nameseq))
3098 bzero (((char *) elt) + sizeof (struct nameseq),
3099 size - sizeof (struct nameseq));
3100 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3101 bcopy (gl.gl_pathv[i], elt->name, alen);
3102 elt->name[alen] = '(';
3103 bcopy (memname, &elt->name[alen + 1], mlen);
3104 elt->name[alen + 1 + mlen] = ')';
3105 elt->name[alen + 1 + mlen + 1] = '\0';
3106 elt->next = new;
3107 new = elt;
3109 else
3111 /* Find the end of the FOUND chain. */
3112 struct nameseq *f = found;
3113 while (f->next != 0)
3114 f = f->next;
3116 /* Attach the chain being built to the end of the FOUND
3117 chain, and make FOUND the new NEW chain. */
3118 f->next = new;
3119 new = found;
3122 free (memname);
3124 else
3125 #endif /* !NO_ARCHIVES */
3127 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3128 if (size > sizeof (struct nameseq))
3129 bzero (((char *) elt) + sizeof (struct nameseq),
3130 size - sizeof (struct nameseq));
3131 elt->name = xstrdup (gl.gl_pathv[i]);
3132 elt->next = new;
3133 new = elt;
3136 globfree (&gl);
3137 free (old->name);
3138 free ((char *)old);
3139 break;
3142 case GLOB_NOSPACE:
3143 fatal (NILF, _("virtual memory exhausted"));
3144 break;
3146 default:
3147 old->next = new;
3148 new = old;
3149 break;
3153 return new;