Make sure to assign a boolean value to a 1-bit bitfield. Reported on
[make.git] / read.c
blob0f07ee91c0af9c6dfe001a014e0048b88c3de9e6
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->need_2nd_expansion = 0;
262 /* Tell update_goal_chain to bail out as soon as this file is
263 made, and main not to die if we can't make this file. */
264 d->changed = RM_DONTCARE;
265 if (tail == 0)
266 read_makefiles = d;
267 else
268 tail->next = d;
269 tail = d;
271 if (tail != 0)
272 tail->next = 0;
276 return read_makefiles;
279 /* Install a new conditional and return the previous one. */
281 static struct conditionals *
282 install_conditionals (struct conditionals *new)
284 struct conditionals *save = conditionals;
286 bzero ((char *) new, sizeof (*new));
287 conditionals = new;
289 return save;
292 /* Free the current conditionals and reinstate a saved one. */
294 static void
295 restore_conditionals (struct conditionals *saved)
297 /* Free any space allocated by conditional_line. */
298 if (conditionals->ignoring)
299 free (conditionals->ignoring);
300 if (conditionals->seen_else)
301 free (conditionals->seen_else);
303 /* Restore state. */
304 conditionals = saved;
307 static int
308 eval_makefile (char *filename, int flags)
310 struct dep *deps;
311 struct ebuffer ebuf;
312 const struct floc *curfile;
313 int makefile_errno;
314 int r;
316 ebuf.floc.filenm = filename;
317 ebuf.floc.lineno = 1;
319 if (ISDB (DB_VERBOSE))
321 printf (_("Reading makefile `%s'"), filename);
322 if (flags & RM_NO_DEFAULT_GOAL)
323 printf (_(" (no default goal)"));
324 if (flags & RM_INCLUDED)
325 printf (_(" (search path)"));
326 if (flags & RM_DONTCARE)
327 printf (_(" (don't care)"));
328 if (flags & RM_NO_TILDE)
329 printf (_(" (no ~ expansion)"));
330 puts ("...");
333 /* First, get a stream to read. */
335 /* Expand ~ in FILENAME unless it came from `include',
336 in which case it was already done. */
337 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
339 char *expanded = tilde_expand (filename);
340 if (expanded != 0)
341 filename = expanded;
344 ebuf.fp = fopen (filename, "r");
345 /* Save the error code so we print the right message later. */
346 makefile_errno = errno;
348 /* If the makefile wasn't found and it's either a makefile from
349 the `MAKEFILES' variable or an included makefile,
350 search the included makefile search path for this makefile. */
351 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
353 register unsigned int i;
354 for (i = 0; include_directories[i] != 0; ++i)
356 char *name = concat (include_directories[i], "/", filename);
357 ebuf.fp = fopen (name, "r");
358 if (ebuf.fp == 0)
359 free (name);
360 else
362 filename = name;
363 break;
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 if (filename != ebuf.floc.filenm)
377 free (filename);
378 filename = deps->file->name;
379 deps->changed = flags;
380 deps->ignore_mtime = 0;
381 deps->need_2nd_expansion = 0;
382 if (flags & RM_DONTCARE)
383 deps->file->dontcare = 1;
385 /* If the makefile can't be found at all, give up entirely. */
387 if (ebuf.fp == 0)
389 /* If we did some searching, errno has the error from the last
390 attempt, rather from FILENAME itself. Restore it in case the
391 caller wants to use it in a message. */
392 errno = makefile_errno;
393 return 0;
396 /* Add this makefile to the list. */
397 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
398 f_append, 0);
400 /* Evaluate the makefile */
402 ebuf.size = 200;
403 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
405 curfile = reading_file;
406 reading_file = &ebuf.floc;
408 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
410 reading_file = curfile;
412 fclose (ebuf.fp);
414 free (ebuf.bufstart);
415 alloca (0);
416 return r;
420 eval_buffer (char *buffer)
422 struct ebuffer ebuf;
423 struct conditionals *saved;
424 struct conditionals new;
425 const struct floc *curfile;
426 int r;
428 /* Evaluate the buffer */
430 ebuf.size = strlen (buffer);
431 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
432 ebuf.fp = NULL;
434 ebuf.floc = *reading_file;
436 curfile = reading_file;
437 reading_file = &ebuf.floc;
439 saved = install_conditionals (&new);
441 r = eval (&ebuf, 1);
443 restore_conditionals (saved);
445 reading_file = curfile;
447 alloca (0);
448 return r;
452 /* Read file FILENAME as a makefile and add its contents to the data base.
454 SET_DEFAULT is true if we are allowed to set the default goal. */
457 static int
458 eval (struct ebuffer *ebuf, int set_default)
460 char *collapsed = 0;
461 unsigned int collapsed_length = 0;
462 unsigned int commands_len = 200;
463 char *commands;
464 unsigned int commands_idx = 0;
465 unsigned int cmds_started, tgts_started;
466 int ignoring = 0, in_ignored_define = 0;
467 int no_targets = 0; /* Set when reading a rule without targets. */
468 struct nameseq *filenames = 0;
469 struct dep *deps = 0;
470 long nlines = 0;
471 int two_colon = 0;
472 char *pattern = 0, *pattern_percent;
473 struct floc *fstart;
474 struct floc fi;
476 #define record_waiting_files() \
477 do \
479 if (filenames != 0) \
481 fi.lineno = tgts_started; \
482 record_files (filenames, pattern, pattern_percent, deps, \
483 cmds_started, commands, commands_idx, two_colon, \
484 &fi); \
486 filenames = 0; \
487 commands_idx = 0; \
488 no_targets = 0; \
489 if (pattern) { free(pattern); pattern = 0; } \
490 } while (0)
492 pattern_percent = 0;
493 cmds_started = tgts_started = 1;
495 fstart = &ebuf->floc;
496 fi.filenm = ebuf->floc.filenm;
498 /* Loop over lines in the file.
499 The strategy is to accumulate target names in FILENAMES, dependencies
500 in DEPS and commands in COMMANDS. These are used to define a rule
501 when the start of the next rule (or eof) is encountered.
503 When you see a "continue" in the loop below, that means we are moving on
504 to the next line _without_ ending any rule that we happen to be working
505 with at the moment. If you see a "goto rule_complete", then the
506 statement we just parsed also finishes the previous rule. */
508 commands = xmalloc (200);
510 while (1)
512 unsigned int linelen;
513 char *line;
514 int len;
515 char *p;
516 char *p2;
518 /* Grab the next line to be evaluated */
519 ebuf->floc.lineno += nlines;
520 nlines = readline (ebuf);
522 /* If there is nothing left to eval, we're done. */
523 if (nlines < 0)
524 break;
526 /* If this line is empty, skip it. */
527 line = ebuf->buffer;
528 if (line[0] == '\0')
529 continue;
531 linelen = strlen (line);
533 /* Check for a shell command line first.
534 If it is not one, we can stop treating tab specially. */
535 if (line[0] == '\t')
537 if (no_targets)
538 /* Ignore the commands in a rule with no targets. */
539 continue;
541 /* If there is no preceding rule line, don't treat this line
542 as a command, even though it begins with a tab character.
543 SunOS 4 make appears to behave this way. */
545 if (filenames != 0)
547 if (ignoring)
548 /* Yep, this is a shell command, and we don't care. */
549 continue;
551 /* Append this command line to the line being accumulated. */
552 if (commands_idx == 0)
553 cmds_started = ebuf->floc.lineno;
555 if (linelen + 1 + commands_idx > commands_len)
557 commands_len = (linelen + 1 + commands_idx) * 2;
558 commands = xrealloc (commands, commands_len);
560 bcopy (line, &commands[commands_idx], linelen);
561 commands_idx += linelen;
562 commands[commands_idx++] = '\n';
564 continue;
568 /* This line is not a shell command line. Don't worry about tabs.
569 Get more space if we need it; we don't need to preserve the current
570 contents of the buffer. */
572 if (collapsed_length < linelen+1)
574 collapsed_length = linelen+1;
575 if (collapsed)
576 free ((char *)collapsed);
577 collapsed = (char *) xmalloc (collapsed_length);
579 strcpy (collapsed, line);
580 /* Collapse continuation lines. */
581 collapse_continuations (collapsed);
582 remove_comments (collapsed);
584 /* Compare a word, both length and contents. */
585 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
586 p = collapsed;
587 while (isspace ((unsigned char)*p))
588 ++p;
590 if (*p == '\0')
591 /* This line is completely empty--ignore it. */
592 continue;
594 /* Find the end of the first token. Note we don't need to worry about
595 * ":" here since we compare tokens by length (so "export" will never
596 * be equal to "export:").
598 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
600 len = p2 - p;
602 /* Find the start of the second token. If it looks like a target or
603 variable definition it can't be a preprocessor token so skip
604 them--this allows variables/targets named `ifdef', `export', etc. */
605 while (isspace ((unsigned char)*p2))
606 ++p2;
608 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
610 /* It can't be a preprocessor token so skip it if we're ignoring */
611 if (ignoring)
612 continue;
614 goto skip_conditionals;
617 /* We must first check for conditional and `define' directives before
618 ignoring anything, since they control what we will do with
619 following lines. */
621 if (!in_ignored_define)
623 int i = conditional_line (p, len, fstart);
624 if (i != -2)
626 if (i == -1)
627 fatal (fstart, _("invalid syntax in conditional"));
629 ignoring = i;
630 continue;
634 if (word1eq ("endef"))
636 if (!in_ignored_define)
637 fatal (fstart, _("extraneous `endef'"));
638 in_ignored_define = 0;
639 continue;
642 if (word1eq ("define"))
644 if (ignoring)
645 in_ignored_define = 1;
646 else
648 if (*p2 == '\0')
649 fatal (fstart, _("empty variable name"));
651 /* Let the variable name be the whole rest of the line,
652 with trailing blanks stripped (comments have already been
653 removed), so it could be a complex variable/function
654 reference that might contain blanks. */
655 p = strchr (p2, '\0');
656 while (isblank ((unsigned char)p[-1]))
657 --p;
658 do_define (p2, p - p2, o_file, ebuf);
660 continue;
663 if (word1eq ("override"))
665 if (*p2 == '\0')
666 error (fstart, _("empty `override' directive"));
668 if (strneq (p2, "define", 6)
669 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
671 if (ignoring)
672 in_ignored_define = 1;
673 else
675 p2 = next_token (p2 + 6);
676 if (*p2 == '\0')
677 fatal (fstart, _("empty variable name"));
679 /* Let the variable name be the whole rest of the line,
680 with trailing blanks stripped (comments have already been
681 removed), so it could be a complex variable/function
682 reference that might contain blanks. */
683 p = strchr (p2, '\0');
684 while (isblank ((unsigned char)p[-1]))
685 --p;
686 do_define (p2, p - p2, o_override, ebuf);
689 else if (!ignoring
690 && !try_variable_definition (fstart, p2, o_override, 0))
691 error (fstart, _("invalid `override' directive"));
693 continue;
696 if (ignoring)
697 /* Ignore the line. We continue here so conditionals
698 can appear in the middle of a rule. */
699 continue;
701 if (word1eq ("export"))
703 /* 'export' by itself causes everything to be exported. */
704 if (*p2 == '\0')
705 export_all_variables = 1;
706 else
708 struct variable *v;
710 v = try_variable_definition (fstart, p2, o_file, 0);
711 if (v != 0)
712 v->export = v_export;
713 else
715 unsigned int len;
716 char *ap;
718 /* Expand the line so we can use indirect and constructed
719 variable names in an export command. */
720 p2 = ap = allocated_variable_expand (p2);
722 for (p = find_next_token (&p2, &len); p != 0;
723 p = find_next_token (&p2, &len))
725 v = lookup_variable (p, len);
726 if (v == 0)
727 v = define_variable_loc (p, len, "", o_file, 0,
728 fstart);
729 v->export = v_export;
732 free (ap);
735 goto rule_complete;
738 if (word1eq ("unexport"))
740 if (*p2 == '\0')
741 export_all_variables = 0;
742 else
744 unsigned int len;
745 struct variable *v;
746 char *ap;
748 /* Expand the line so we can use indirect and constructed
749 variable names in an unexport command. */
750 p2 = ap = allocated_variable_expand (p2);
752 for (p = find_next_token (&p2, &len); p != 0;
753 p = find_next_token (&p2, &len))
755 v = lookup_variable (p, len);
756 if (v == 0)
757 v = define_variable_loc (p, len, "", o_file, 0, fstart);
759 v->export = v_noexport;
762 free (ap);
764 goto rule_complete;
767 skip_conditionals:
768 if (word1eq ("vpath"))
770 char *pattern;
771 unsigned int len;
772 p2 = variable_expand (p2);
773 p = find_next_token (&p2, &len);
774 if (p != 0)
776 pattern = savestring (p, len);
777 p = find_next_token (&p2, &len);
778 /* No searchpath means remove all previous
779 selective VPATH's with the same pattern. */
781 else
782 /* No pattern means remove all previous selective VPATH's. */
783 pattern = 0;
784 construct_vpath_list (pattern, p);
785 if (pattern != 0)
786 free (pattern);
788 goto rule_complete;
791 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
793 /* We have found an `include' line specifying a nested
794 makefile to be read at this point. */
795 struct conditionals *save;
796 struct conditionals new_conditionals;
797 struct nameseq *files;
798 /* "-include" (vs "include") says no error if the file does not
799 exist. "sinclude" is an alias for this from SGI. */
800 int noerror = (p[0] != 'i');
802 p = allocated_variable_expand (p2);
804 /* If no filenames, it's a no-op. */
805 if (*p == '\0')
806 continue;
808 /* Parse the list of file names. */
809 p2 = p;
810 files = multi_glob (parse_file_seq (&p2, '\0',
811 sizeof (struct nameseq),
813 sizeof (struct nameseq));
814 free (p);
816 /* Save the state of conditionals and start
817 the included makefile with a clean slate. */
818 save = install_conditionals (&new_conditionals);
820 /* Record the rules that are waiting so they will determine
821 the default goal before those in the included makefile. */
822 record_waiting_files ();
824 /* Read each included makefile. */
825 while (files != 0)
827 struct nameseq *next = files->next;
828 char *name = files->name;
829 int r;
831 free ((char *)files);
832 files = next;
834 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
835 | (noerror ? RM_DONTCARE : 0)));
836 if (!r)
838 if (!noerror)
839 error (fstart, "%s: %s", name, strerror (errno));
840 free (name);
844 /* Restore conditional state. */
845 restore_conditionals (save);
847 goto rule_complete;
850 if (try_variable_definition (fstart, p, o_file, 0))
851 /* This line has been dealt with. */
852 goto rule_complete;
854 /* This line starts with a tab but was not caught above because there
855 was no preceding target, and the line might have been usable as a
856 variable definition. But now we know it is definitely lossage. */
857 if (line[0] == '\t')
858 fatal(fstart, _("commands commence before first target"));
860 /* This line describes some target files. This is complicated by
861 the existence of target-specific variables, because we can't
862 expand the entire line until we know if we have one or not. So
863 we expand the line word by word until we find the first `:',
864 then check to see if it's a target-specific variable.
866 In this algorithm, `lb_next' will point to the beginning of the
867 unexpanded parts of the input buffer, while `p2' points to the
868 parts of the expanded buffer we haven't searched yet. */
871 enum make_word_type wtype;
872 enum variable_origin v_origin;
873 int exported;
874 char *cmdleft, *semip, *lb_next;
875 unsigned int len, plen = 0;
876 char *colonp;
877 const char *end, *beg; /* Helpers for whitespace stripping. */
879 /* Record the previous rule. */
881 record_waiting_files ();
882 tgts_started = fstart->lineno;
884 /* Search the line for an unquoted ; that is not after an
885 unquoted #. */
886 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
887 if (cmdleft != 0 && *cmdleft == '#')
889 /* We found a comment before a semicolon. */
890 *cmdleft = '\0';
891 cmdleft = 0;
893 else if (cmdleft != 0)
894 /* Found one. Cut the line short there before expanding it. */
895 *(cmdleft++) = '\0';
896 semip = cmdleft;
898 collapse_continuations (line);
900 /* We can't expand the entire line, since if it's a per-target
901 variable we don't want to expand it. So, walk from the
902 beginning, expanding as we go, and looking for "interesting"
903 chars. The first word is always expandable. */
904 wtype = get_next_mword(line, NULL, &lb_next, &len);
905 switch (wtype)
907 case w_eol:
908 if (cmdleft != 0)
909 fatal(fstart, _("missing rule before commands"));
910 /* This line contained something but turned out to be nothing
911 but whitespace (a comment?). */
912 continue;
914 case w_colon:
915 case w_dcolon:
916 /* We accept and ignore rules without targets for
917 compatibility with SunOS 4 make. */
918 no_targets = 1;
919 continue;
921 default:
922 break;
925 p2 = variable_expand_string(NULL, lb_next, len);
927 while (1)
929 lb_next += len;
930 if (cmdleft == 0)
932 /* Look for a semicolon in the expanded line. */
933 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
935 if (cmdleft != 0)
937 unsigned long p2_off = p2 - variable_buffer;
938 unsigned long cmd_off = cmdleft - variable_buffer;
939 char *pend = p2 + strlen(p2);
941 /* Append any remnants of lb, then cut the line short
942 at the semicolon. */
943 *cmdleft = '\0';
945 /* One school of thought says that you shouldn't expand
946 here, but merely copy, since now you're beyond a ";"
947 and into a command script. However, the old parser
948 expanded the whole line, so we continue that for
949 backwards-compatiblity. Also, it wouldn't be
950 entirely consistent, since we do an unconditional
951 expand below once we know we don't have a
952 target-specific variable. */
953 (void)variable_expand_string(pend, lb_next, (long)-1);
954 lb_next += strlen(lb_next);
955 p2 = variable_buffer + p2_off;
956 cmdleft = variable_buffer + cmd_off + 1;
960 colonp = find_char_unquote(p2, ':', 0, 0, 0);
961 #ifdef HAVE_DOS_PATHS
962 /* The drive spec brain-damage strikes again... */
963 /* Note that the only separators of targets in this context
964 are whitespace and a left paren. If others are possible,
965 they should be added to the string in the call to index. */
966 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
967 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
968 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
969 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
970 #endif
971 if (colonp != 0)
972 break;
974 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
975 if (wtype == w_eol)
976 break;
978 p2 += strlen(p2);
979 *(p2++) = ' ';
980 p2 = variable_expand_string(p2, lb_next, len);
981 /* We don't need to worry about cmdleft here, because if it was
982 found in the variable_buffer the entire buffer has already
983 been expanded... we'll never get here. */
986 p2 = next_token (variable_buffer);
988 /* If the word we're looking at is EOL, see if there's _anything_
989 on the line. If not, a variable expanded to nothing, so ignore
990 it. If so, we can't parse this line so punt. */
991 if (wtype == w_eol)
993 if (*p2 != '\0')
994 /* There's no need to be ivory-tower about this: check for
995 one of the most common bugs found in makefiles... */
996 fatal (fstart, _("missing separator%s"),
997 !strneq(line, " ", 8) ? ""
998 : _(" (did you mean TAB instead of 8 spaces?)"));
999 continue;
1002 /* Make the colon the end-of-string so we know where to stop
1003 looking for targets. */
1004 *colonp = '\0';
1005 filenames = multi_glob (parse_file_seq (&p2, '\0',
1006 sizeof (struct nameseq),
1008 sizeof (struct nameseq));
1009 *p2 = ':';
1011 if (!filenames)
1013 /* We accept and ignore rules without targets for
1014 compatibility with SunOS 4 make. */
1015 no_targets = 1;
1016 continue;
1018 /* This should never be possible; we handled it above. */
1019 assert (*p2 != '\0');
1020 ++p2;
1022 /* Is this a one-colon or two-colon entry? */
1023 two_colon = *p2 == ':';
1024 if (two_colon)
1025 p2++;
1027 /* Test to see if it's a target-specific variable. Copy the rest
1028 of the buffer over, possibly temporarily (we'll expand it later
1029 if it's not a target-specific variable). PLEN saves the length
1030 of the unparsed section of p2, for later. */
1031 if (*lb_next != '\0')
1033 unsigned int l = p2 - variable_buffer;
1034 plen = strlen (p2);
1035 (void) variable_buffer_output (p2+plen,
1036 lb_next, strlen (lb_next)+1);
1037 p2 = variable_buffer + l;
1040 /* See if it's an "override" or "export" keyword; if so see if what
1041 comes after it looks like a variable definition. */
1043 wtype = get_next_mword (p2, NULL, &p, &len);
1045 v_origin = o_file;
1046 exported = 0;
1047 if (wtype == w_static)
1049 if (word1eq ("override"))
1051 v_origin = o_override;
1052 wtype = get_next_mword (p+len, NULL, &p, &len);
1054 else if (word1eq ("export"))
1056 exported = 1;
1057 wtype = get_next_mword (p+len, NULL, &p, &len);
1061 if (wtype != w_eol)
1062 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1064 if (wtype == w_varassign)
1066 /* If there was a semicolon found, add it back, plus anything
1067 after it. */
1068 if (semip)
1070 unsigned int l = p - variable_buffer;
1071 *(--semip) = ';';
1072 variable_buffer_output (p2 + strlen (p2),
1073 semip, strlen (semip)+1);
1074 p = variable_buffer + l;
1076 record_target_var (filenames, p, v_origin, exported, fstart);
1077 filenames = 0;
1078 continue;
1081 /* This is a normal target, _not_ a target-specific variable.
1082 Unquote any = in the dependency list. */
1083 find_char_unquote (lb_next, '=', 0, 0, 0);
1085 /* We have some targets, so don't ignore the following commands. */
1086 no_targets = 0;
1088 /* Expand the dependencies, etc. */
1089 if (*lb_next != '\0')
1091 unsigned int l = p2 - variable_buffer;
1092 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1093 p2 = variable_buffer + l;
1095 /* Look for a semicolon in the expanded line. */
1096 if (cmdleft == 0)
1098 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1099 if (cmdleft != 0)
1100 *(cmdleft++) = '\0';
1104 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1105 p = strchr (p2, ':');
1106 while (p != 0 && p[-1] == '\\')
1108 register char *q = &p[-1];
1109 register int backslash = 0;
1110 while (*q-- == '\\')
1111 backslash = !backslash;
1112 if (backslash)
1113 p = strchr (p + 1, ':');
1114 else
1115 break;
1117 #ifdef _AMIGA
1118 /* Here, the situation is quite complicated. Let's have a look
1119 at a couple of targets:
1121 install: dev:make
1123 dev:make: make
1125 dev:make:: xyz
1127 The rule is that it's only a target, if there are TWO :'s
1128 OR a space around the :.
1130 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1131 || isspace ((unsigned char)p[-1])))
1132 p = 0;
1133 #endif
1134 #ifdef HAVE_DOS_PATHS
1136 int check_again;
1138 do {
1139 check_again = 0;
1140 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1141 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1142 isalpha ((unsigned char)p[-1]) &&
1143 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1144 p = strchr (p + 1, ':');
1145 check_again = 1;
1147 } while (check_again);
1149 #endif
1150 if (p != 0)
1152 struct nameseq *target;
1153 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1154 ++p2;
1155 if (target == 0)
1156 fatal (fstart, _("missing target pattern"));
1157 else if (target->next != 0)
1158 fatal (fstart, _("multiple target patterns"));
1159 pattern = target->name;
1160 pattern_percent = find_percent (pattern);
1161 if (pattern_percent == 0)
1162 fatal (fstart, _("target pattern contains no `%%'"));
1163 free((char *)target);
1165 else
1166 pattern = 0;
1168 /* Strip leading and trailing whitespaces. */
1169 beg = p2;
1170 end = beg + strlen (beg) - 1;
1171 strip_whitespace (&beg, &end);
1173 if (beg <= end && *beg != '\0')
1175 char *top;
1176 const char *fromp = beg;
1178 /* Make a copy of the dependency string. Note if we find '$'. */
1179 deps = (struct dep*) xmalloc (sizeof (struct dep));
1180 deps->next = 0;
1181 deps->name = top = (char *) xmalloc (end - beg + 2);
1182 deps->need_2nd_expansion = 0;
1183 while (fromp <= end)
1185 if (*fromp == '$')
1186 deps->need_2nd_expansion = 1;
1187 *(top++) = *(fromp++);
1189 *top = '\0';
1190 deps->file = 0;
1192 else
1193 deps = 0;
1195 commands_idx = 0;
1196 if (cmdleft != 0)
1198 /* Semicolon means rest of line is a command. */
1199 unsigned int len = strlen (cmdleft);
1201 cmds_started = fstart->lineno;
1203 /* Add this command line to the buffer. */
1204 if (len + 2 > commands_len)
1206 commands_len = (len + 2) * 2;
1207 commands = (char *) xrealloc (commands, commands_len);
1209 bcopy (cmdleft, commands, len);
1210 commands_idx += len;
1211 commands[commands_idx++] = '\n';
1214 /* Determine if this target should be made default. We used to do
1215 this in record_files() but because of the delayed target recording
1216 and because preprocessor directives are legal in target's commands
1217 it is too late. Consider this fragment for example:
1219 foo:
1221 ifeq ($(.DEFAULT_GOAL),foo)
1223 endif
1225 Because the target is not recorded until after ifeq directive is
1226 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1227 would expect. Because of this we have to move some of the logic
1228 here. */
1230 if (**default_goal_name == '\0' && set_default)
1232 char* name;
1233 struct dep *d;
1234 struct nameseq *t = filenames;
1236 for (; t != 0; t = t->next)
1238 int reject = 0;
1239 name = t->name;
1241 /* We have nothing to do if this is an implicit rule. */
1242 if (strchr (name, '%') != 0)
1243 break;
1245 /* See if this target's name does not start with a `.',
1246 unless it contains a slash. */
1247 if (*name == '.' && strchr (name, '/') == 0
1248 #ifdef HAVE_DOS_PATHS
1249 && strchr (name, '\\') == 0
1250 #endif
1252 continue;
1255 /* If this file is a suffix, don't let it be
1256 the default goal file. */
1257 for (d = suffix_file->deps; d != 0; d = d->next)
1259 register struct dep *d2;
1260 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1262 reject = 1;
1263 break;
1265 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1267 register unsigned int len = strlen (dep_name (d2));
1268 if (!strneq (name, dep_name (d2), len))
1269 continue;
1270 if (streq (name + len, dep_name (d)))
1272 reject = 1;
1273 break;
1277 if (reject)
1278 break;
1281 if (!reject)
1283 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1284 o_file, 0, NILF);
1285 break;
1290 continue;
1293 /* We get here except in the case that we just read a rule line.
1294 Record now the last rule we read, so following spurious
1295 commands are properly diagnosed. */
1296 rule_complete:
1297 record_waiting_files ();
1300 #undef word1eq
1302 if (conditionals->if_cmds)
1303 fatal (fstart, _("missing `endif'"));
1305 /* At eof, record the last rule. */
1306 record_waiting_files ();
1308 if (collapsed)
1309 free ((char *) collapsed);
1310 free ((char *) commands);
1312 return 1;
1316 /* Remove comments from LINE.
1317 This is done by copying the text at LINE onto itself. */
1319 static void
1320 remove_comments (char *line)
1322 char *comment;
1324 comment = find_char_unquote (line, '#', 0, 0, 0);
1326 if (comment != 0)
1327 /* Cut off the line at the #. */
1328 *comment = '\0';
1331 /* Execute a `define' directive.
1332 The first line has already been read, and NAME is the name of
1333 the variable to be defined. The following lines remain to be read. */
1335 static void
1336 do_define (char *name, unsigned int namelen,
1337 enum variable_origin origin, struct ebuffer *ebuf)
1339 struct floc defstart;
1340 long nlines = 0;
1341 int nlevels = 1;
1342 unsigned int length = 100;
1343 char *definition = (char *) xmalloc (length);
1344 unsigned int idx = 0;
1345 char *p;
1347 /* Expand the variable name. */
1348 char *var = (char *) alloca (namelen + 1);
1349 bcopy (name, var, namelen);
1350 var[namelen] = '\0';
1351 var = variable_expand (var);
1353 defstart = ebuf->floc;
1355 while (1)
1357 unsigned int len;
1358 char *line;
1360 nlines = readline (ebuf);
1361 ebuf->floc.lineno += nlines;
1363 /* If there is nothing left to eval, we're done. */
1364 if (nlines < 0)
1365 break;
1367 line = ebuf->buffer;
1369 collapse_continuations (line);
1371 /* If the line doesn't begin with a tab, test to see if it introduces
1372 another define, or ends one. */
1374 /* Stop if we find an 'endef' */
1375 if (line[0] != '\t')
1377 p = next_token (line);
1378 len = strlen (p);
1380 /* If this is another 'define', increment the level count. */
1381 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1382 && strneq (p, "define", 6))
1383 ++nlevels;
1385 /* If this is an 'endef', decrement the count. If it's now 0,
1386 we've found the last one. */
1387 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1388 && strneq (p, "endef", 5))
1390 p += 5;
1391 remove_comments (p);
1392 if (*next_token (p) != '\0')
1393 error (&ebuf->floc,
1394 _("Extraneous text after `endef' directive"));
1396 if (--nlevels == 0)
1398 /* Define the variable. */
1399 if (idx == 0)
1400 definition[0] = '\0';
1401 else
1402 definition[idx - 1] = '\0';
1404 /* Always define these variables in the global set. */
1405 define_variable_global (var, strlen (var), definition,
1406 origin, 1, &defstart);
1407 free (definition);
1408 return;
1413 /* Otherwise add this line to the variable definition. */
1414 len = strlen (line);
1415 if (idx + len + 1 > length)
1417 length = (idx + len) * 2;
1418 definition = (char *) xrealloc (definition, length + 1);
1421 bcopy (line, &definition[idx], len);
1422 idx += len;
1423 /* Separate lines with a newline. */
1424 definition[idx++] = '\n';
1427 /* No `endef'!! */
1428 fatal (&defstart, _("missing `endef', unterminated `define'"));
1430 /* NOTREACHED */
1431 return;
1434 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1435 "ifneq", "else" and "endif".
1436 LINE is the input line, with the command as its first word.
1438 FILENAME and LINENO are the filename and line number in the
1439 current makefile. They are used for error messages.
1441 Value is -2 if the line is not a conditional at all,
1442 -1 if the line is an invalid conditional,
1443 0 if following text should be interpreted,
1444 1 if following text should be ignored. */
1446 static int
1447 conditional_line (char *line, int len, const struct floc *flocp)
1449 char *cmdname;
1450 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1451 unsigned int i;
1452 unsigned int o;
1454 /* Compare a word, both length and contents. */
1455 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1456 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1458 /* Make sure this line is a conditional. */
1459 chkword ("ifdef", c_ifdef)
1460 else chkword ("ifndef", c_ifndef)
1461 else chkword ("ifeq", c_ifeq)
1462 else chkword ("ifneq", c_ifneq)
1463 else chkword ("else", c_else)
1464 else chkword ("endif", c_endif)
1465 else
1466 return -2;
1468 /* Found one: skip past it and any whitespace after it. */
1469 line = next_token (line + len);
1471 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1473 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1474 if (cmdtype == c_endif)
1476 if (*line != '\0')
1477 EXTRANEOUS ();
1479 if (!conditionals->if_cmds)
1480 fatal (flocp, _("extraneous `%s'"), cmdname);
1482 --conditionals->if_cmds;
1484 goto DONE;
1487 /* An 'else' statement can either be simple, or it can have another
1488 conditional after it. */
1489 if (cmdtype == c_else)
1491 const char *p;
1493 if (!conditionals->if_cmds)
1494 fatal (flocp, _("extraneous `%s'"), cmdname);
1496 o = conditionals->if_cmds - 1;
1498 if (conditionals->seen_else[o])
1499 fatal (flocp, _("only one `else' per conditional"));
1501 /* Change the state of ignorance. */
1502 switch (conditionals->ignoring[o])
1504 case 0:
1505 /* We've just been interpreting. Never do it again. */
1506 conditionals->ignoring[o] = 2;
1507 break;
1508 case 1:
1509 /* We've never interpreted yet. Maybe this time! */
1510 conditionals->ignoring[o] = 0;
1511 break;
1514 /* It's a simple 'else'. */
1515 if (*line == '\0')
1517 conditionals->seen_else[o] = 1;
1518 goto DONE;
1521 /* The 'else' has extra text. That text must be another conditional
1522 and cannot be an 'else' or 'endif'. */
1524 /* Find the length of the next word. */
1525 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1527 len = p - line;
1529 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1530 if (word1eq("else") || word1eq("endif")
1531 || conditional_line (line, len, flocp) < 0)
1532 EXTRANEOUS ();
1533 else
1535 /* conditional_line() created a new level of conditional.
1536 Raise it back to this level. */
1537 if (conditionals->ignoring[o] < 2)
1538 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1539 --conditionals->if_cmds;
1542 goto DONE;
1545 if (conditionals->allocated == 0)
1547 conditionals->allocated = 5;
1548 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1549 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1552 o = conditionals->if_cmds++;
1553 if (conditionals->if_cmds > conditionals->allocated)
1555 conditionals->allocated += 5;
1556 conditionals->ignoring = (char *)
1557 xrealloc (conditionals->ignoring, conditionals->allocated);
1558 conditionals->seen_else = (char *)
1559 xrealloc (conditionals->seen_else, conditionals->allocated);
1562 /* Record that we have seen an `if...' but no `else' so far. */
1563 conditionals->seen_else[o] = 0;
1565 /* Search through the stack to see if we're already ignoring. */
1566 for (i = 0; i < o; ++i)
1567 if (conditionals->ignoring[i])
1569 /* We are already ignoring, so just push a level to match the next
1570 "else" or "endif", and keep ignoring. We don't want to expand
1571 variables in the condition. */
1572 conditionals->ignoring[o] = 1;
1573 return 1;
1576 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1578 char *var;
1579 struct variable *v;
1580 char *p;
1582 /* Expand the thing we're looking up, so we can use indirect and
1583 constructed variable names. */
1584 var = allocated_variable_expand (line);
1586 /* Make sure there's only one variable name to test. */
1587 p = end_of_token (var);
1588 i = p - var;
1589 p = next_token (p);
1590 if (*p != '\0')
1591 return -1;
1593 var[i] = '\0';
1594 v = lookup_variable (var, i);
1596 conditionals->ignoring[o] =
1597 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1599 free (var);
1601 else
1603 /* "Ifeq" or "ifneq". */
1604 char *s1, *s2;
1605 unsigned int len;
1606 char termin = *line == '(' ? ',' : *line;
1608 if (termin != ',' && termin != '"' && termin != '\'')
1609 return -1;
1611 s1 = ++line;
1612 /* Find the end of the first string. */
1613 if (termin == ',')
1615 int count = 0;
1616 for (; *line != '\0'; ++line)
1617 if (*line == '(')
1618 ++count;
1619 else if (*line == ')')
1620 --count;
1621 else if (*line == ',' && count <= 0)
1622 break;
1624 else
1625 while (*line != '\0' && *line != termin)
1626 ++line;
1628 if (*line == '\0')
1629 return -1;
1631 if (termin == ',')
1633 /* Strip blanks after the first string. */
1634 char *p = line++;
1635 while (isblank ((unsigned char)p[-1]))
1636 --p;
1637 *p = '\0';
1639 else
1640 *line++ = '\0';
1642 s2 = variable_expand (s1);
1643 /* We must allocate a new copy of the expanded string because
1644 variable_expand re-uses the same buffer. */
1645 len = strlen (s2);
1646 s1 = (char *) alloca (len + 1);
1647 bcopy (s2, s1, len + 1);
1649 if (termin != ',')
1650 /* Find the start of the second string. */
1651 line = next_token (line);
1653 termin = termin == ',' ? ')' : *line;
1654 if (termin != ')' && termin != '"' && termin != '\'')
1655 return -1;
1657 /* Find the end of the second string. */
1658 if (termin == ')')
1660 register int count = 0;
1661 s2 = next_token (line);
1662 for (line = s2; *line != '\0'; ++line)
1664 if (*line == '(')
1665 ++count;
1666 else if (*line == ')')
1668 if (count <= 0)
1669 break;
1670 else
1671 --count;
1675 else
1677 ++line;
1678 s2 = line;
1679 while (*line != '\0' && *line != termin)
1680 ++line;
1683 if (*line == '\0')
1684 return -1;
1686 *line = '\0';
1687 line = next_token (++line);
1688 if (*line != '\0')
1689 EXTRANEOUS ();
1691 s2 = variable_expand (s2);
1692 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1695 DONE:
1696 /* Search through the stack to see if we're ignoring. */
1697 for (i = 0; i < conditionals->if_cmds; ++i)
1698 if (conditionals->ignoring[i])
1699 return 1;
1700 return 0;
1703 /* Remove duplicate dependencies in CHAIN. */
1705 static unsigned long
1706 dep_hash_1 (const void *key)
1708 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1711 static unsigned long
1712 dep_hash_2 (const void *key)
1714 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1717 static int
1718 dep_hash_cmp (const void *x, const void *y)
1720 struct dep *dx = (struct dep *) x;
1721 struct dep *dy = (struct dep *) y;
1722 int cmp = strcmp (dep_name (dx), dep_name (dy));
1724 /* If the names are the same but ignore_mtimes are not equal, one of these
1725 is an order-only prerequisite and one isn't. That means that we should
1726 remove the one that isn't and keep the one that is. */
1728 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1729 dx->ignore_mtime = dy->ignore_mtime = 0;
1731 return cmp;
1735 void
1736 uniquize_deps (struct dep *chain)
1738 struct hash_table deps;
1739 register struct dep **depp;
1741 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1743 /* Make sure that no dependencies are repeated. This does not
1744 really matter for the purpose of updating targets, but it
1745 might make some names be listed twice for $^ and $?. */
1747 depp = &chain;
1748 while (*depp)
1750 struct dep *dep = *depp;
1751 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1752 if (HASH_VACANT (*dep_slot))
1754 hash_insert_at (&deps, dep, dep_slot);
1755 depp = &dep->next;
1757 else
1759 /* Don't bother freeing duplicates.
1760 It's dangerous and little benefit accrues. */
1761 *depp = dep->next;
1765 hash_free (&deps, 0);
1768 /* Record target-specific variable values for files FILENAMES.
1769 TWO_COLON is nonzero if a double colon was used.
1771 The links of FILENAMES are freed, and so are any names in it
1772 that are not incorporated into other data structures.
1774 If the target is a pattern, add the variable to the pattern-specific
1775 variable value list. */
1777 static void
1778 record_target_var (struct nameseq *filenames, char *defn,
1779 enum variable_origin origin, int exported,
1780 const struct floc *flocp)
1782 struct nameseq *nextf;
1783 struct variable_set_list *global;
1785 global = current_variable_set_list;
1787 /* If the variable is an append version, store that but treat it as a
1788 normal recursive variable. */
1790 for (; filenames != 0; filenames = nextf)
1792 struct variable *v;
1793 register char *name = filenames->name;
1794 char *fname;
1795 char *percent;
1796 struct pattern_var *p;
1798 nextf = filenames->next;
1799 free ((char *) filenames);
1801 /* If it's a pattern target, then add it to the pattern-specific
1802 variable list. */
1803 percent = find_percent (name);
1804 if (percent)
1806 /* Get a reference for this pattern-specific variable struct. */
1807 p = create_pattern_var (name, percent);
1808 p->variable.fileinfo = *flocp;
1809 /* I don't think this can fail since we already determined it was a
1810 variable definition. */
1811 v = parse_variable_definition (&p->variable, defn);
1812 assert (v != 0);
1814 if (v->flavor == f_simple)
1815 v->value = allocated_variable_expand (v->value);
1816 else
1817 v->value = xstrdup (v->value);
1819 fname = p->target;
1821 else
1823 struct file *f;
1825 /* Get a file reference for this file, and initialize it.
1826 We don't want to just call enter_file() because that allocates a
1827 new entry if the file is a double-colon, which we don't want in
1828 this situation. */
1829 f = lookup_file (name);
1830 if (!f)
1831 f = enter_file (name);
1832 else if (f->double_colon)
1833 f = f->double_colon;
1835 initialize_file_variables (f, 1);
1836 fname = f->name;
1838 current_variable_set_list = f->variables;
1839 v = try_variable_definition (flocp, defn, origin, 1);
1840 if (!v)
1841 error (flocp, _("Malformed target-specific variable definition"));
1842 current_variable_set_list = global;
1845 /* Set up the variable to be *-specific. */
1846 v->origin = origin;
1847 v->per_target = 1;
1848 if (exported)
1849 v->export = v_export;
1851 /* If it's not an override, check to see if there was a command-line
1852 setting. If so, reset the value. */
1853 if (origin != o_override)
1855 struct variable *gv;
1856 int len = strlen(v->name);
1858 gv = lookup_variable (v->name, len);
1859 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1861 if (v->value != 0)
1862 free (v->value);
1863 v->value = xstrdup (gv->value);
1864 v->origin = gv->origin;
1865 v->recursive = gv->recursive;
1866 v->append = 0;
1870 /* Free name if not needed further. */
1871 if (name != fname && (name < fname || name > fname + strlen (fname)))
1872 free (name);
1876 /* Record a description line for files FILENAMES,
1877 with dependencies DEPS, commands to execute described
1878 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1879 TWO_COLON is nonzero if a double colon was used.
1880 If not nil, PATTERN is the `%' pattern to make this
1881 a static pattern rule, and PATTERN_PERCENT is a pointer
1882 to the `%' within it.
1884 The links of FILENAMES are freed, and so are any names in it
1885 that are not incorporated into other data structures. */
1887 static void
1888 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1889 struct dep *deps, unsigned int cmds_started, char *commands,
1890 unsigned int commands_idx, int two_colon,
1891 const struct floc *flocp)
1893 struct nameseq *nextf;
1894 int implicit = 0;
1895 unsigned int max_targets = 0, target_idx = 0;
1896 char **targets = 0, **target_percents = 0;
1897 struct commands *cmds;
1899 /* If we've already snapped deps, that means we're in an eval being
1900 resolved after the makefiles have been read in. We can't add more rules
1901 at this time, since they won't get snapped and we'll get core dumps.
1902 See Savannah bug # 12124. */
1903 if (snapped_deps)
1904 fatal (flocp, _("prerequisites cannot be defined in command scripts"));
1906 if (commands_idx > 0)
1908 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1909 cmds->fileinfo.filenm = flocp->filenm;
1910 cmds->fileinfo.lineno = cmds_started;
1911 cmds->commands = savestring (commands, commands_idx);
1912 cmds->command_lines = 0;
1914 else
1915 cmds = 0;
1917 for (; filenames != 0; filenames = nextf)
1919 char *name = filenames->name;
1920 struct file *f;
1921 struct dep *d;
1922 struct dep *this;
1923 char *implicit_percent;
1925 nextf = filenames->next;
1926 free (filenames);
1928 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1929 good enough: it doesn't happen until after the makefile is read,
1930 which means we cannot use its value during parsing. */
1932 if (streq (name, ".POSIX"))
1933 posix_pedantic = 1;
1935 implicit_percent = find_percent (name);
1936 implicit |= implicit_percent != 0;
1938 if (implicit && pattern != 0)
1939 fatal (flocp, _("mixed implicit and static pattern rules"));
1941 if (implicit && implicit_percent == 0)
1942 fatal (flocp, _("mixed implicit and normal rules"));
1944 if (implicit)
1946 if (targets == 0)
1948 max_targets = 5;
1949 targets = (char **) xmalloc (5 * sizeof (char *));
1950 target_percents = (char **) xmalloc (5 * sizeof (char *));
1951 target_idx = 0;
1953 else if (target_idx == max_targets - 1)
1955 max_targets += 5;
1956 targets = (char **) xrealloc ((char *) targets,
1957 max_targets * sizeof (char *));
1958 target_percents
1959 = (char **) xrealloc ((char *) target_percents,
1960 max_targets * sizeof (char *));
1962 targets[target_idx] = name;
1963 target_percents[target_idx] = implicit_percent;
1964 ++target_idx;
1965 continue;
1968 /* If there are multiple filenames, copy the chain DEPS
1969 for all but the last one. It is not safe for the same deps
1970 to go in more than one place in the database. */
1971 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1973 if (pattern != 0)
1975 /* If this is an extended static rule:
1976 `targets: target%pattern: dep%pattern; cmds',
1977 translate each dependency pattern into a plain filename
1978 using the target pattern and this target's name. */
1979 if (!pattern_matches (pattern, pattern_percent, name))
1981 /* Give a warning if the rule is meaningless. */
1982 error (flocp,
1983 _("target `%s' doesn't match the target pattern"), name);
1984 this = 0;
1986 else
1987 /* We use subst_expand to do the work of translating % to $* in
1988 the dependency line. */
1990 if (this != 0 && find_percent (this->name) != 0)
1992 char *o;
1993 char *buffer = variable_expand ("");
1995 o = subst_expand (buffer, this->name, "%", "$*", 1, 2, 0);
1997 free (this->name);
1998 this->name = savestring (buffer, o - buffer);
1999 this->need_2nd_expansion = 1;
2003 if (!two_colon)
2005 /* Single-colon. Combine these dependencies
2006 with others in file's existing record, if any. */
2007 f = enter_file (name);
2009 if (f->double_colon)
2010 fatal (flocp,
2011 _("target file `%s' has both : and :: entries"), f->name);
2013 /* If CMDS == F->CMDS, this target was listed in this rule
2014 more than once. Just give a warning since this is harmless. */
2015 if (cmds != 0 && cmds == f->cmds)
2016 error (flocp,
2017 _("target `%s' given more than once in the same rule."),
2018 f->name);
2020 /* Check for two single-colon entries both with commands.
2021 Check is_target so that we don't lose on files such as .c.o
2022 whose commands were preinitialized. */
2023 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2025 error (&cmds->fileinfo,
2026 _("warning: overriding commands for target `%s'"),
2027 f->name);
2028 error (&f->cmds->fileinfo,
2029 _("warning: ignoring old commands for target `%s'"),
2030 f->name);
2033 f->is_target = 1;
2035 /* Defining .DEFAULT with no deps or cmds clears it. */
2036 if (f == default_file && this == 0 && cmds == 0)
2037 f->cmds = 0;
2038 if (cmds != 0)
2039 f->cmds = cmds;
2041 /* Defining .SUFFIXES with no dependencies
2042 clears out the list of suffixes. */
2043 if (f == suffix_file && this == 0)
2045 d = f->deps;
2046 while (d != 0)
2048 struct dep *nextd = d->next;
2049 free (d->name);
2050 free ((char *)d);
2051 d = nextd;
2053 f->deps = 0;
2055 else if (this != 0)
2057 /* Add the file's old deps and the new ones in THIS together. */
2059 if (f->deps != 0)
2061 struct dep **d_ptr = &f->deps;
2063 while ((*d_ptr)->next != 0)
2064 d_ptr = &(*d_ptr)->next;
2066 if (cmds != 0)
2067 /* This is the rule with commands, so put its deps
2068 last. The rationale behind this is that $< expands to
2069 the first dep in the chain, and commands use $<
2070 expecting to get the dep that rule specifies. However
2071 the second expansion algorithm reverses the order thus
2072 we need to make it last here. */
2073 (*d_ptr)->next = this;
2074 else
2076 /* This is the rule without commands. Put its
2077 dependencies at the end but before dependencies from
2078 the rule with commands (if any). This way everything
2079 appears in makefile order. */
2081 if (f->cmds != 0)
2083 this->next = *d_ptr;
2084 *d_ptr = this;
2086 else
2087 (*d_ptr)->next = this;
2090 else
2091 f->deps = this;
2093 /* This is a hack. I need a way to communicate to snap_deps()
2094 that the last dependency line in this file came with commands
2095 (so that logic in snap_deps() can put it in front and all
2096 this $< -logic works). I cannot simply rely on file->cmds
2097 being not 0 because of the cases like the following:
2099 foo: bar
2100 foo:
2103 I am going to temporarily "borrow" UPDATING member in
2104 `struct file' for this. */
2106 if (cmds != 0)
2107 f->updating = 1;
2110 else
2112 /* Double-colon. Make a new record
2113 even if the file already has one. */
2114 f = lookup_file (name);
2115 /* Check for both : and :: rules. Check is_target so
2116 we don't lose on default suffix rules or makefiles. */
2117 if (f != 0 && f->is_target && !f->double_colon)
2118 fatal (flocp,
2119 _("target file `%s' has both : and :: entries"), f->name);
2120 f = enter_file (name);
2121 /* If there was an existing entry and it was a double-colon
2122 entry, enter_file will have returned a new one, making it the
2123 prev pointer of the old one, and setting its double_colon
2124 pointer to the first one. */
2125 if (f->double_colon == 0)
2126 /* This is the first entry for this name, so we must
2127 set its double_colon pointer to itself. */
2128 f->double_colon = f;
2129 f->is_target = 1;
2130 f->deps = this;
2131 f->cmds = cmds;
2134 /* If this is a static pattern rule, set the file's stem to
2135 the part of its name that matched the `%' in the pattern,
2136 so you can use $* in the commands. */
2137 if (pattern != 0)
2139 static char *percent = "%";
2140 char *buffer = variable_expand ("");
2141 char *o = patsubst_expand (buffer, name, pattern, percent,
2142 pattern_percent+1, percent+1);
2143 f->stem = savestring (buffer, o - buffer);
2146 /* Free name if not needed further. */
2147 if (f != 0 && name != f->name
2148 && (name < f->name || name > f->name + strlen (f->name)))
2150 free (name);
2151 name = f->name;
2154 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2155 if (strcmp (*default_goal_name, name) == 0
2156 && (default_goal_file == 0
2157 || strcmp (default_goal_file->name, name) != 0))
2158 default_goal_file = f;
2161 if (implicit)
2163 targets[target_idx] = 0;
2164 target_percents[target_idx] = 0;
2165 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2166 free ((char *) target_percents);
2170 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2171 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2172 Quoting backslashes are removed from STRING by compacting it into
2173 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2174 one, or nil if there are none. STOPCHARs inside variable references are
2175 ignored if IGNOREVARS is true.
2177 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2179 static char *
2180 find_char_unquote (char *string, int stop1, int stop2, int blank,
2181 int ignorevars)
2183 unsigned int string_len = 0;
2184 register char *p = string;
2186 if (ignorevars)
2187 ignorevars = '$';
2189 while (1)
2191 if (stop2 && blank)
2192 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2193 && ! isblank ((unsigned char) *p))
2194 ++p;
2195 else if (stop2)
2196 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2197 ++p;
2198 else if (blank)
2199 while (*p != '\0' && *p != ignorevars && *p != stop1
2200 && ! isblank ((unsigned char) *p))
2201 ++p;
2202 else
2203 while (*p != '\0' && *p != ignorevars && *p != stop1)
2204 ++p;
2206 if (*p == '\0')
2207 break;
2209 /* If we stopped due to a variable reference, skip over its contents. */
2210 if (*p == ignorevars)
2212 char openparen = p[1];
2214 p += 2;
2216 /* Skip the contents of a non-quoted, multi-char variable ref. */
2217 if (openparen == '(' || openparen == '{')
2219 unsigned int pcount = 1;
2220 char closeparen = (openparen == '(' ? ')' : '}');
2222 while (*p)
2224 if (*p == openparen)
2225 ++pcount;
2226 else if (*p == closeparen)
2227 if (--pcount == 0)
2229 ++p;
2230 break;
2232 ++p;
2236 /* Skipped the variable reference: look for STOPCHARS again. */
2237 continue;
2240 if (p > string && p[-1] == '\\')
2242 /* Search for more backslashes. */
2243 register int i = -2;
2244 while (&p[i] >= string && p[i] == '\\')
2245 --i;
2246 ++i;
2247 /* Only compute the length if really needed. */
2248 if (string_len == 0)
2249 string_len = strlen (string);
2250 /* The number of backslashes is now -I.
2251 Copy P over itself to swallow half of them. */
2252 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2253 p += i / 2;
2254 if (i % 2 == 0)
2255 /* All the backslashes quoted each other; the STOPCHAR was
2256 unquoted. */
2257 return p;
2259 /* The STOPCHAR was quoted by a backslash. Look for another. */
2261 else
2262 /* No backslash in sight. */
2263 return p;
2266 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2267 return 0;
2270 /* Search PATTERN for an unquoted %. */
2272 char *
2273 find_percent (char *pattern)
2275 return find_char_unquote (pattern, '%', 0, 0, 0);
2278 /* Parse a string into a sequence of filenames represented as a
2279 chain of struct nameseq's in reverse order and return that chain.
2281 The string is passed as STRINGP, the address of a string pointer.
2282 The string pointer is updated to point at the first character
2283 not parsed, which either is a null char or equals STOPCHAR.
2285 SIZE is how big to construct chain elements.
2286 This is useful if we want them actually to be other structures
2287 that have room for additional info.
2289 If STRIP is nonzero, strip `./'s off the beginning. */
2291 struct nameseq *
2292 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2294 register struct nameseq *new = 0;
2295 register struct nameseq *new1, *lastnew1;
2296 register char *p = *stringp;
2297 char *q;
2298 char *name;
2300 #ifdef VMS
2301 # define VMS_COMMA ','
2302 #else
2303 # define VMS_COMMA 0
2304 #endif
2306 while (1)
2308 /* Skip whitespace; see if any more names are left. */
2309 p = next_token (p);
2310 if (*p == '\0')
2311 break;
2312 if (*p == stopchar)
2313 break;
2315 /* Yes, find end of next name. */
2316 q = p;
2317 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2318 #ifdef VMS
2319 /* convert comma separated list to space separated */
2320 if (p && *p == ',')
2321 *p =' ';
2322 #endif
2323 #ifdef _AMIGA
2324 if (stopchar == ':' && p && *p == ':'
2325 && !(isspace ((unsigned char)p[1]) || !p[1]
2326 || isspace ((unsigned char)p[-1])))
2328 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2330 #endif
2331 #ifdef HAVE_DOS_PATHS
2332 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2333 first colon which isn't followed by a slash or a backslash.
2334 Note that tokens separated by spaces should be treated as separate
2335 tokens since make doesn't allow path names with spaces */
2336 if (stopchar == ':')
2337 while (p != 0 && !isspace ((unsigned char)*p) &&
2338 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2339 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2340 #endif
2341 if (p == 0)
2342 p = q + strlen (q);
2344 if (strip)
2345 #ifdef VMS
2346 /* Skip leading `[]'s. */
2347 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2348 #else
2349 /* Skip leading `./'s. */
2350 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2351 #endif
2353 q += 2; /* Skip "./". */
2354 while (q < p && *q == '/')
2355 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2356 ++q;
2359 /* Extract the filename just found, and skip it. */
2361 if (q == p)
2362 /* ".///" was stripped to "". */
2363 #ifdef VMS
2364 continue;
2365 #else
2366 #ifdef _AMIGA
2367 name = savestring ("", 0);
2368 #else
2369 name = savestring ("./", 2);
2370 #endif
2371 #endif
2372 else
2373 #ifdef VMS
2374 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2375 * to remove this '\' before we can use the filename.
2376 * Savestring called because q may be read-only string constant.
2379 char *qbase = xstrdup (q);
2380 char *pbase = qbase + (p-q);
2381 char *q1 = qbase;
2382 char *q2 = q1;
2383 char *p1 = pbase;
2385 while (q1 != pbase)
2387 if (*q1 == '\\' && *(q1+1) == ':')
2389 q1++;
2390 p1--;
2392 *q2++ = *q1++;
2394 name = savestring (qbase, p1 - qbase);
2395 free (qbase);
2397 #else
2398 name = savestring (q, p - q);
2399 #endif
2401 /* Add it to the front of the chain. */
2402 new1 = (struct nameseq *) xmalloc (size);
2403 new1->name = name;
2404 new1->next = new;
2405 new = new1;
2408 #ifndef NO_ARCHIVES
2410 /* Look for multi-word archive references.
2411 They are indicated by a elt ending with an unmatched `)' and
2412 an elt further down the chain (i.e., previous in the file list)
2413 with an unmatched `(' (e.g., "lib(mem"). */
2415 new1 = new;
2416 lastnew1 = 0;
2417 while (new1 != 0)
2418 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2419 && new1->name[strlen (new1->name) - 1] == ')'
2420 && strchr (new1->name, '(') == 0)
2422 /* NEW1 ends with a `)' but does not contain a `('.
2423 Look back for an elt with an opening `(' but no closing `)'. */
2425 struct nameseq *n = new1->next, *lastn = new1;
2426 char *paren = 0;
2427 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2429 lastn = n;
2430 n = n->next;
2432 if (n != 0
2433 /* Ignore something starting with `(', as that cannot actually
2434 be an archive-member reference (and treating it as such
2435 results in an empty file name, which causes much lossage). */
2436 && n->name[0] != '(')
2438 /* N is the first element in the archive group.
2439 Its name looks like "lib(mem" (with no closing `)'). */
2441 char *libname;
2443 /* Copy "lib(" into LIBNAME. */
2444 ++paren;
2445 libname = (char *) alloca (paren - n->name + 1);
2446 bcopy (n->name, libname, paren - n->name);
2447 libname[paren - n->name] = '\0';
2449 if (*paren == '\0')
2451 /* N was just "lib(", part of something like "lib( a b)".
2452 Edit it out of the chain and free its storage. */
2453 lastn->next = n->next;
2454 free (n->name);
2455 free ((char *) n);
2456 /* LASTN->next is the new stopping elt for the loop below. */
2457 n = lastn->next;
2459 else
2461 /* Replace N's name with the full archive reference. */
2462 name = concat (libname, paren, ")");
2463 free (n->name);
2464 n->name = name;
2467 if (new1->name[1] == '\0')
2469 /* NEW1 is just ")", part of something like "lib(a b )".
2470 Omit it from the chain and free its storage. */
2471 if (lastnew1 == 0)
2472 new = new1->next;
2473 else
2474 lastnew1->next = new1->next;
2475 lastn = new1;
2476 new1 = new1->next;
2477 free (lastn->name);
2478 free ((char *) lastn);
2480 else
2482 /* Replace also NEW1->name, which already has closing `)'. */
2483 name = concat (libname, new1->name, "");
2484 free (new1->name);
2485 new1->name = name;
2486 new1 = new1->next;
2489 /* Trace back from NEW1 (the end of the list) until N
2490 (the beginning of the list), rewriting each name
2491 with the full archive reference. */
2493 while (new1 != n)
2495 name = concat (libname, new1->name, ")");
2496 free (new1->name);
2497 new1->name = name;
2498 lastnew1 = new1;
2499 new1 = new1->next;
2502 else
2504 /* No frobnication happening. Just step down the list. */
2505 lastnew1 = new1;
2506 new1 = new1->next;
2509 else
2511 lastnew1 = new1;
2512 new1 = new1->next;
2515 #endif
2517 *stringp = p;
2518 return new;
2521 /* Find the next line of text in an eval buffer, combining continuation lines
2522 into one line.
2523 Return the number of actual lines read (> 1 if continuation lines).
2524 Returns -1 if there's nothing left in the buffer.
2526 After this function, ebuf->buffer points to the first character of the
2527 line we just found.
2530 /* Read a line of text from a STRING.
2531 Since we aren't really reading from a file, don't bother with linenumbers.
2534 static unsigned long
2535 readstring (struct ebuffer *ebuf)
2537 char *eol;
2539 /* If there is nothing left in this buffer, return 0. */
2540 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2541 return -1;
2543 /* Set up a new starting point for the buffer, and find the end of the
2544 next logical line (taking into account backslash/newline pairs). */
2546 eol = ebuf->buffer = ebuf->bufnext;
2548 while (1)
2550 int backslash = 0;
2551 char *bol = eol;
2552 char *p;
2554 /* Find the next newline. At EOS, stop. */
2555 eol = p = strchr (eol , '\n');
2556 if (!eol)
2558 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2559 return 0;
2562 /* Found a newline; if it's escaped continue; else we're done. */
2563 while (p > bol && *(--p) == '\\')
2564 backslash = !backslash;
2565 if (!backslash)
2566 break;
2567 ++eol;
2570 /* Overwrite the newline char. */
2571 *eol = '\0';
2572 ebuf->bufnext = eol+1;
2574 return 0;
2577 static long
2578 readline (struct ebuffer *ebuf)
2580 char *p;
2581 char *end;
2582 char *start;
2583 long nlines = 0;
2585 /* The behaviors between string and stream buffers are different enough to
2586 warrant different functions. Do the Right Thing. */
2588 if (!ebuf->fp)
2589 return readstring (ebuf);
2591 /* When reading from a file, we always start over at the beginning of the
2592 buffer for each new line. */
2594 p = start = ebuf->bufstart;
2595 end = p + ebuf->size;
2596 *p = '\0';
2598 while (fgets (p, end - p, ebuf->fp) != 0)
2600 char *p2;
2601 unsigned long len;
2602 int backslash;
2604 len = strlen (p);
2605 if (len == 0)
2607 /* This only happens when the first thing on the line is a '\0'.
2608 It is a pretty hopeless case, but (wonder of wonders) Athena
2609 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2610 There is nothing really to be done; we synthesize a newline so
2611 the following line doesn't appear to be part of this line. */
2612 error (&ebuf->floc,
2613 _("warning: NUL character seen; rest of line ignored"));
2614 p[0] = '\n';
2615 len = 1;
2618 /* Jump past the text we just read. */
2619 p += len;
2621 /* If the last char isn't a newline, the whole line didn't fit into the
2622 buffer. Get some more buffer and try again. */
2623 if (p[-1] != '\n')
2624 goto more_buffer;
2626 /* We got a newline, so add one to the count of lines. */
2627 ++nlines;
2629 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2630 /* Check to see if the line was really ended with CRLF; if so ignore
2631 the CR. */
2632 if ((p - start) > 1 && p[-2] == '\r')
2634 --p;
2635 p[-1] = '\n';
2637 #endif
2639 backslash = 0;
2640 for (p2 = p - 2; p2 >= start; --p2)
2642 if (*p2 != '\\')
2643 break;
2644 backslash = !backslash;
2647 if (!backslash)
2649 p[-1] = '\0';
2650 break;
2653 /* It was a backslash/newline combo. If we have more space, read
2654 another line. */
2655 if (end - p >= 80)
2656 continue;
2658 /* We need more space at the end of our buffer, so realloc it.
2659 Make sure to preserve the current offset of p. */
2660 more_buffer:
2662 unsigned long off = p - start;
2663 ebuf->size *= 2;
2664 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2665 ebuf->size);
2666 p = start + off;
2667 end = start + ebuf->size;
2668 *p = '\0';
2672 if (ferror (ebuf->fp))
2673 pfatal_with_name (ebuf->floc.filenm);
2675 /* If we found some lines, return how many.
2676 If we didn't, but we did find _something_, that indicates we read the last
2677 line of a file with no final newline; return 1.
2678 If we read nothing, we're at EOF; return -1. */
2680 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2683 /* Parse the next "makefile word" from the input buffer, and return info
2684 about it.
2686 A "makefile word" is one of:
2688 w_bogus Should never happen
2689 w_eol End of input
2690 w_static A static word; cannot be expanded
2691 w_variable A word containing one or more variables/functions
2692 w_colon A colon
2693 w_dcolon A double-colon
2694 w_semicolon A semicolon
2695 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2697 Note that this function is only used when reading certain parts of the
2698 makefile. Don't use it where special rules hold sway (RHS of a variable,
2699 in a command list, etc.) */
2701 static enum make_word_type
2702 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2704 enum make_word_type wtype = w_bogus;
2705 char *p = buffer, *beg;
2706 char c;
2708 /* Skip any leading whitespace. */
2709 while (isblank ((unsigned char)*p))
2710 ++p;
2712 beg = p;
2713 c = *(p++);
2714 switch (c)
2716 case '\0':
2717 wtype = w_eol;
2718 break;
2720 case ';':
2721 wtype = w_semicolon;
2722 break;
2724 case '=':
2725 wtype = w_varassign;
2726 break;
2728 case ':':
2729 wtype = w_colon;
2730 switch (*p)
2732 case ':':
2733 ++p;
2734 wtype = w_dcolon;
2735 break;
2737 case '=':
2738 ++p;
2739 wtype = w_varassign;
2740 break;
2742 break;
2744 case '+':
2745 case '?':
2746 if (*p == '=')
2748 ++p;
2749 wtype = w_varassign;
2750 break;
2753 default:
2754 if (delim && strchr (delim, c))
2755 wtype = w_static;
2756 break;
2759 /* Did we find something? If so, return now. */
2760 if (wtype != w_bogus)
2761 goto done;
2763 /* This is some non-operator word. A word consists of the longest
2764 string of characters that doesn't contain whitespace, one of [:=#],
2765 or [?+]=, or one of the chars in the DELIM string. */
2767 /* We start out assuming a static word; if we see a variable we'll
2768 adjust our assumptions then. */
2769 wtype = w_static;
2771 /* We already found the first value of "c", above. */
2772 while (1)
2774 char closeparen;
2775 int count;
2777 switch (c)
2779 case '\0':
2780 case ' ':
2781 case '\t':
2782 case '=':
2783 goto done_word;
2785 case ':':
2786 #ifdef HAVE_DOS_PATHS
2787 /* A word CAN include a colon in its drive spec. The drive
2788 spec is allowed either at the beginning of a word, or as part
2789 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2790 if (!(p - beg >= 2
2791 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2792 && (p - beg == 2 || p[-3] == '(')))
2793 #endif
2794 goto done_word;
2796 case '$':
2797 c = *(p++);
2798 if (c == '$')
2799 break;
2801 /* This is a variable reference, so note that it's expandable.
2802 Then read it to the matching close paren. */
2803 wtype = w_variable;
2805 if (c == '(')
2806 closeparen = ')';
2807 else if (c == '{')
2808 closeparen = '}';
2809 else
2810 /* This is a single-letter variable reference. */
2811 break;
2813 for (count=0; *p != '\0'; ++p)
2815 if (*p == c)
2816 ++count;
2817 else if (*p == closeparen && --count < 0)
2819 ++p;
2820 break;
2823 break;
2825 case '?':
2826 case '+':
2827 if (*p == '=')
2828 goto done_word;
2829 break;
2831 case '\\':
2832 switch (*p)
2834 case ':':
2835 case ';':
2836 case '=':
2837 case '\\':
2838 ++p;
2839 break;
2841 break;
2843 default:
2844 if (delim && strchr (delim, c))
2845 goto done_word;
2846 break;
2849 c = *(p++);
2851 done_word:
2852 --p;
2854 done:
2855 if (startp)
2856 *startp = beg;
2857 if (length)
2858 *length = p - beg;
2859 return wtype;
2862 /* Construct the list of include directories
2863 from the arguments and the default list. */
2865 void
2866 construct_include_path (char **arg_dirs)
2868 register unsigned int i;
2869 #ifdef VAXC /* just don't ask ... */
2870 stat_t stbuf;
2871 #else
2872 struct stat stbuf;
2873 #endif
2874 /* Table to hold the dirs. */
2876 register unsigned int defsize = (sizeof (default_include_directories)
2877 / sizeof (default_include_directories[0]));
2878 register unsigned int max = 5;
2879 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2880 register unsigned int idx = 0;
2882 #ifdef __MSDOS__
2883 defsize++;
2884 #endif
2886 /* First consider any dirs specified with -I switches.
2887 Ignore dirs that don't exist. */
2889 if (arg_dirs != 0)
2890 while (*arg_dirs != 0)
2892 char *dir = *arg_dirs++;
2893 int e;
2895 if (dir[0] == '~')
2897 char *expanded = tilde_expand (dir);
2898 if (expanded != 0)
2899 dir = expanded;
2902 EINTRLOOP (e, stat (dir, &stbuf));
2903 if (e == 0 && S_ISDIR (stbuf.st_mode))
2905 if (idx == max - 1)
2907 max += 5;
2908 dirs = (char **)
2909 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2911 dirs[idx++] = dir;
2913 else if (dir != arg_dirs[-1])
2914 free (dir);
2917 /* Now add at the end the standard default dirs. */
2919 #ifdef __MSDOS__
2921 /* The environment variable $DJDIR holds the root of the
2922 DJGPP directory tree; add ${DJDIR}/include. */
2923 struct variable *djdir = lookup_variable ("DJDIR", 5);
2925 if (djdir)
2927 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2929 strcat (strcpy (defdir, djdir->value), "/include");
2930 dirs[idx++] = defdir;
2933 #endif
2935 for (i = 0; default_include_directories[i] != 0; ++i)
2937 int e;
2939 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2940 if (e == 0 && S_ISDIR (stbuf.st_mode))
2941 dirs[idx++] = default_include_directories[i];
2944 dirs[idx] = 0;
2946 /* Now compute the maximum length of any name in it. */
2948 max_incl_len = 0;
2949 for (i = 0; i < idx; ++i)
2951 unsigned int len = strlen (dirs[i]);
2952 /* If dir name is written with a trailing slash, discard it. */
2953 if (dirs[i][len - 1] == '/')
2954 /* We can't just clobber a null in because it may have come from
2955 a literal string and literal strings may not be writable. */
2956 dirs[i] = savestring (dirs[i], len - 1);
2957 if (len > max_incl_len)
2958 max_incl_len = len;
2961 include_directories = dirs;
2964 /* Expand ~ or ~USER at the beginning of NAME.
2965 Return a newly malloc'd string or 0. */
2967 char *
2968 tilde_expand (char *name)
2970 #ifndef VMS
2971 if (name[1] == '/' || name[1] == '\0')
2973 extern char *getenv ();
2974 char *home_dir;
2975 int is_variable;
2978 /* Turn off --warn-undefined-variables while we expand HOME. */
2979 int save = warn_undefined_variables_flag;
2980 warn_undefined_variables_flag = 0;
2982 home_dir = allocated_variable_expand ("$(HOME)");
2984 warn_undefined_variables_flag = save;
2987 is_variable = home_dir[0] != '\0';
2988 if (!is_variable)
2990 free (home_dir);
2991 home_dir = getenv ("HOME");
2993 #if !defined(_AMIGA) && !defined(WINDOWS32)
2994 if (home_dir == 0 || home_dir[0] == '\0')
2996 extern char *getlogin ();
2997 char *logname = getlogin ();
2998 home_dir = 0;
2999 if (logname != 0)
3001 struct passwd *p = getpwnam (logname);
3002 if (p != 0)
3003 home_dir = p->pw_dir;
3006 #endif /* !AMIGA && !WINDOWS32 */
3007 if (home_dir != 0)
3009 char *new = concat (home_dir, "", name + 1);
3010 if (is_variable)
3011 free (home_dir);
3012 return new;
3015 #if !defined(_AMIGA) && !defined(WINDOWS32)
3016 else
3018 struct passwd *pwent;
3019 char *userend = strchr (name + 1, '/');
3020 if (userend != 0)
3021 *userend = '\0';
3022 pwent = getpwnam (name + 1);
3023 if (pwent != 0)
3025 if (userend == 0)
3026 return xstrdup (pwent->pw_dir);
3027 else
3028 return concat (pwent->pw_dir, "/", userend + 1);
3030 else if (userend != 0)
3031 *userend = '/';
3033 #endif /* !AMIGA && !WINDOWS32 */
3034 #endif /* !VMS */
3035 return 0;
3038 /* Given a chain of struct nameseq's describing a sequence of filenames,
3039 in reverse of the intended order, return a new chain describing the
3040 result of globbing the filenames. The new chain is in forward order.
3041 The links of the old chain are freed or used in the new chain.
3042 Likewise for the names in the old chain.
3044 SIZE is how big to construct chain elements.
3045 This is useful if we want them actually to be other structures
3046 that have room for additional info. */
3048 struct nameseq *
3049 multi_glob (struct nameseq *chain, unsigned int size)
3051 extern void dir_setup_glob ();
3052 register struct nameseq *new = 0;
3053 register struct nameseq *old;
3054 struct nameseq *nexto;
3055 glob_t gl;
3057 dir_setup_glob (&gl);
3059 for (old = chain; old != 0; old = nexto)
3061 #ifndef NO_ARCHIVES
3062 char *memname;
3063 #endif
3065 nexto = old->next;
3067 if (old->name[0] == '~')
3069 char *newname = tilde_expand (old->name);
3070 if (newname != 0)
3072 free (old->name);
3073 old->name = newname;
3077 #ifndef NO_ARCHIVES
3078 if (ar_name (old->name))
3080 /* OLD->name is an archive member reference.
3081 Replace it with the archive file name,
3082 and save the member name in MEMNAME.
3083 We will glob on the archive name and then
3084 reattach MEMNAME later. */
3085 char *arname;
3086 ar_parse_name (old->name, &arname, &memname);
3087 free (old->name);
3088 old->name = arname;
3090 else
3091 memname = 0;
3092 #endif /* !NO_ARCHIVES */
3094 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3096 case 0: /* Success. */
3098 register int i = gl.gl_pathc;
3099 while (i-- > 0)
3101 #ifndef NO_ARCHIVES
3102 if (memname != 0)
3104 /* Try to glob on MEMNAME within the archive. */
3105 struct nameseq *found
3106 = ar_glob (gl.gl_pathv[i], memname, size);
3107 if (found == 0)
3109 /* No matches. Use MEMNAME as-is. */
3110 unsigned int alen = strlen (gl.gl_pathv[i]);
3111 unsigned int mlen = strlen (memname);
3112 struct nameseq *elt
3113 = (struct nameseq *) xmalloc (size);
3114 if (size > sizeof (struct nameseq))
3115 bzero (((char *) elt) + sizeof (struct nameseq),
3116 size - sizeof (struct nameseq));
3117 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3118 bcopy (gl.gl_pathv[i], elt->name, alen);
3119 elt->name[alen] = '(';
3120 bcopy (memname, &elt->name[alen + 1], mlen);
3121 elt->name[alen + 1 + mlen] = ')';
3122 elt->name[alen + 1 + mlen + 1] = '\0';
3123 elt->next = new;
3124 new = elt;
3126 else
3128 /* Find the end of the FOUND chain. */
3129 struct nameseq *f = found;
3130 while (f->next != 0)
3131 f = f->next;
3133 /* Attach the chain being built to the end of the FOUND
3134 chain, and make FOUND the new NEW chain. */
3135 f->next = new;
3136 new = found;
3139 free (memname);
3141 else
3142 #endif /* !NO_ARCHIVES */
3144 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3145 if (size > sizeof (struct nameseq))
3146 bzero (((char *) elt) + sizeof (struct nameseq),
3147 size - sizeof (struct nameseq));
3148 elt->name = xstrdup (gl.gl_pathv[i]);
3149 elt->next = new;
3150 new = elt;
3153 globfree (&gl);
3154 free (old->name);
3155 free ((char *)old);
3156 break;
3159 case GLOB_NOSPACE:
3160 fatal (NILF, _("virtual memory exhausted"));
3161 break;
3163 default:
3164 old->next = new;
3165 new = old;
3166 break;
3170 return new;