Many bug fixes etc.
[make.git] / read.c
blob3469806f6b5bae411aa14648c68f53dc523b68d9
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
23 #include <assert.h>
25 #include <glob.h>
27 #include "dep.h"
28 #include "filedef.h"
29 #include "job.h"
30 #include "commands.h"
31 #include "variable.h"
32 #include "rule.h"
33 #include "debug.h"
34 #include "hash.h"
37 #ifndef WINDOWS32
38 #ifndef _AMIGA
39 #ifndef VMS
40 #include <pwd.h>
41 #else
42 struct passwd *getpwnam PARAMS ((char *name));
43 #endif
44 #endif
45 #endif /* !WINDOWS32 */
47 /* A 'struct ebuffer' controls the origin of the makefile we are currently
48 eval'ing.
51 struct ebuffer
53 char *buffer; /* Start of the current line in the buffer. */
54 char *bufnext; /* Start of the next line in the buffer. */
55 char *bufstart; /* Start of the entire buffer. */
56 unsigned int size; /* Malloc'd size of buffer. */
57 FILE *fp; /* File, or NULL if this is an internal buffer. */
58 struct floc floc; /* Info on the file in fp (if any). */
61 /* Types of "words" that can be read in a makefile. */
62 enum make_word_type
64 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
65 w_varassign
69 /* A `struct conditionals' contains the information describing
70 all the active conditionals in a makefile.
72 The global variable `conditionals' contains the conditionals
73 information for the current makefile. It is initialized from
74 the static structure `toplevel_conditionals' and is later changed
75 to new structures for included makefiles. */
77 struct conditionals
79 unsigned int if_cmds; /* Depth of conditional nesting. */
80 unsigned int allocated; /* Elts allocated in following arrays. */
81 char *ignoring; /* Are we ignoring or interepreting? */
82 char *seen_else; /* Have we already seen an `else'? */
85 static struct conditionals toplevel_conditionals;
86 static struct conditionals *conditionals = &toplevel_conditionals;
89 /* Default directories to search for include files in */
91 static char *default_include_directories[] =
93 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
95 * This completely up to the user when they install MSVC or other packages.
96 * This is defined as a placeholder.
98 #define INCLUDEDIR "."
99 #endif
100 INCLUDEDIR,
101 #ifndef _AMIGA
102 "/usr/gnu/include",
103 "/usr/local/include",
104 "/usr/include",
105 #endif
109 /* List of directories to search for include files in */
111 static char **include_directories;
113 /* Maximum length of an element of the above. */
115 static unsigned int max_incl_len;
117 /* The filename and pointer to line number of the
118 makefile currently being read in. */
120 const struct floc *reading_file = 0;
122 /* The chain of makefiles read by read_makefile. */
124 static struct dep *read_makefiles = 0;
126 static int eval_makefile PARAMS ((char *filename, int flags));
127 static int eval PARAMS ((struct ebuffer *buffer, int flags));
129 static long readline PARAMS ((struct ebuffer *ebuf));
130 static void do_define PARAMS ((char *name, unsigned int namelen,
131 enum variable_origin origin,
132 struct ebuffer *ebuf));
133 static int conditional_line PARAMS ((char *line, const struct floc *flocp));
134 static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
135 struct dep *deps, unsigned int cmds_started, char *commands,
136 unsigned int commands_idx, int two_colon,
137 int have_sysv_atvar,
138 const struct floc *flocp, int set_default));
139 static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
140 enum variable_origin origin,
141 int enabled,
142 const struct floc *flocp));
143 static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
144 char **startp, unsigned int *length));
146 /* Read in all the makefiles and return the chain of their names. */
148 struct dep *
149 read_all_makefiles (char **makefiles)
151 unsigned int num_makefiles = 0;
153 /* Create *_LIST variables, to hold the makefiles, targets, and variables
154 we will be reading. */
156 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
158 DB (DB_BASIC, (_("Reading makefiles...\n")));
160 /* If there's a non-null variable MAKEFILES, its value is a list of
161 files to read first thing. But don't let it prevent reading the
162 default makefiles and don't let the default goal come from there. */
165 char *value;
166 char *name, *p;
167 unsigned int length;
170 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
171 int save = warn_undefined_variables_flag;
172 warn_undefined_variables_flag = 0;
174 value = allocated_variable_expand ("$(MAKEFILES)");
176 warn_undefined_variables_flag = save;
179 /* Set NAME to the start of next token and LENGTH to its length.
180 MAKEFILES is updated for finding remaining tokens. */
181 p = value;
183 while ((name = find_next_token (&p, &length)) != 0)
185 if (*p != '\0')
186 *p++ = '\0';
187 name = xstrdup (name);
188 if (eval_makefile (name,
189 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
190 free (name);
193 free (value);
196 /* Read makefiles specified with -f switches. */
198 if (makefiles != 0)
199 while (*makefiles != 0)
201 struct dep *tail = read_makefiles;
202 register struct dep *d;
204 if (! eval_makefile (*makefiles, 0))
205 perror_with_name ("", *makefiles);
207 /* Find the right element of read_makefiles. */
208 d = read_makefiles;
209 while (d->next != tail)
210 d = d->next;
212 /* Use the storage read_makefile allocates. */
213 *makefiles = dep_name (d);
214 ++num_makefiles;
215 ++makefiles;
218 /* If there were no -f switches, try the default names. */
220 if (num_makefiles == 0)
222 static char *default_makefiles[] =
223 #ifdef VMS
224 /* all lower case since readdir() (the vms version) 'lowercasifies' */
225 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
226 #else
227 #ifdef _AMIGA
228 { "GNUmakefile", "Makefile", "SMakefile", 0 };
229 #else /* !Amiga && !VMS */
230 { "GNUmakefile", "makefile", "Makefile", 0 };
231 #endif /* AMIGA */
232 #endif /* VMS */
233 register char **p = default_makefiles;
234 while (*p != 0 && !file_exists_p (*p))
235 ++p;
237 if (*p != 0)
239 if (! eval_makefile (*p, 0))
240 perror_with_name ("", *p);
242 else
244 /* No default makefile was found. Add the default makefiles to the
245 `read_makefiles' chain so they will be updated if possible. */
246 struct dep *tail = read_makefiles;
247 /* Add them to the tail, after any MAKEFILES variable makefiles. */
248 while (tail != 0 && tail->next != 0)
249 tail = tail->next;
250 for (p = default_makefiles; *p != 0; ++p)
252 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
253 d->name = 0;
254 d->file = enter_file (*p);
255 d->file->dontcare = 1;
256 d->ignore_mtime = 0;
257 /* Tell update_goal_chain to bail out as soon as this file is
258 made, and main not to die if we can't make this file. */
259 d->changed = RM_DONTCARE;
260 if (tail == 0)
261 read_makefiles = d;
262 else
263 tail->next = d;
264 tail = d;
266 if (tail != 0)
267 tail->next = 0;
271 return read_makefiles;
274 /* Install a new conditional and return the previous one. */
276 static struct conditionals *
277 install_conditionals (struct conditionals *new)
279 struct conditionals *save = conditionals;
281 bzero ((char *) new, sizeof (*new));
282 conditionals = new;
284 return save;
287 /* Free the current conditionals and reinstate a saved one. */
289 static void
290 restore_conditionals (struct conditionals *saved)
292 /* Free any space allocated by conditional_line. */
293 if (conditionals->ignoring)
294 free (conditionals->ignoring);
295 if (conditionals->seen_else)
296 free (conditionals->seen_else);
298 /* Restore state. */
299 conditionals = saved;
302 static int
303 eval_makefile (char *filename, int flags)
305 struct dep *deps;
306 struct ebuffer ebuf;
307 const struct floc *curfile;
308 int makefile_errno;
309 int r;
311 ebuf.floc.filenm = filename;
312 ebuf.floc.lineno = 1;
314 if (ISDB (DB_VERBOSE))
316 printf (_("Reading makefile `%s'"), filename);
317 if (flags & RM_NO_DEFAULT_GOAL)
318 printf (_(" (no default goal)"));
319 if (flags & RM_INCLUDED)
320 printf (_(" (search path)"));
321 if (flags & RM_DONTCARE)
322 printf (_(" (don't care)"));
323 if (flags & RM_NO_TILDE)
324 printf (_(" (no ~ expansion)"));
325 puts ("...");
328 /* First, get a stream to read. */
330 /* Expand ~ in FILENAME unless it came from `include',
331 in which case it was already done. */
332 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
334 char *expanded = tilde_expand (filename);
335 if (expanded != 0)
336 filename = expanded;
339 ebuf.fp = fopen (filename, "r");
340 /* Save the error code so we print the right message later. */
341 makefile_errno = errno;
343 /* If the makefile wasn't found and it's either a makefile from
344 the `MAKEFILES' variable or an included makefile,
345 search the included makefile search path for this makefile. */
346 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
348 register unsigned int i;
349 for (i = 0; include_directories[i] != 0; ++i)
351 char *name = concat (include_directories[i], "/", filename);
352 ebuf.fp = fopen (name, "r");
353 if (ebuf.fp == 0)
354 free (name);
355 else
357 filename = name;
358 break;
363 /* Add FILENAME to the chain of read makefiles. */
364 deps = (struct dep *) xmalloc (sizeof (struct dep));
365 deps->next = read_makefiles;
366 read_makefiles = deps;
367 deps->name = 0;
368 deps->file = lookup_file (filename);
369 if (deps->file == 0)
371 deps->file = enter_file (xstrdup (filename));
372 if (flags & RM_DONTCARE)
373 deps->file->dontcare = 1;
375 if (filename != ebuf.floc.filenm)
376 free (filename);
377 filename = deps->file->name;
378 deps->changed = flags;
379 deps->ignore_mtime = 0;
381 /* If the makefile can't be found at all, give up entirely. */
383 if (ebuf.fp == 0)
385 /* If we did some searching, errno has the error from the last
386 attempt, rather from FILENAME itself. Restore it in case the
387 caller wants to use it in a message. */
388 errno = makefile_errno;
389 return 0;
392 /* Add this makefile to the list. */
393 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
394 f_append, 0);
396 /* Evaluate the makefile */
398 ebuf.size = 200;
399 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
401 curfile = reading_file;
402 reading_file = &ebuf.floc;
404 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
406 reading_file = curfile;
408 fclose (ebuf.fp);
410 free (ebuf.bufstart);
411 return r;
415 eval_buffer (char *buffer)
417 struct ebuffer ebuf;
418 struct conditionals *saved;
419 struct conditionals new;
420 const struct floc *curfile;
421 int r;
423 /* Evaluate the buffer */
425 ebuf.size = strlen (buffer);
426 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
427 ebuf.fp = NULL;
429 ebuf.floc = *reading_file;
431 curfile = reading_file;
432 reading_file = &ebuf.floc;
434 saved = install_conditionals (&new);
436 r = eval (&ebuf, 1);
438 restore_conditionals (saved);
440 reading_file = curfile;
442 return r;
446 /* Read file FILENAME as a makefile and add its contents to the data base.
448 SET_DEFAULT is true if we are allowed to set the default goal. */
451 static int
452 eval (struct ebuffer *ebuf, int set_default)
454 char *collapsed = 0;
455 unsigned int collapsed_length = 0;
456 unsigned int commands_len = 200;
457 char *commands;
458 unsigned int commands_idx = 0;
459 unsigned int cmds_started, tgts_started;
460 int ignoring = 0, in_ignored_define = 0;
461 int no_targets = 0; /* Set when reading a rule without targets. */
462 int have_sysv_atvar = 0;
463 struct nameseq *filenames = 0;
464 struct dep *deps = 0;
465 long nlines = 0;
466 int two_colon = 0;
467 char *pattern = 0, *pattern_percent;
468 struct floc *fstart;
469 struct floc fi;
471 #define record_waiting_files() \
472 do \
474 if (filenames != 0) \
476 fi.lineno = tgts_started; \
477 record_files (filenames, pattern, pattern_percent, deps, \
478 cmds_started, commands, commands_idx, two_colon, \
479 have_sysv_atvar, &fi, set_default); \
481 filenames = 0; \
482 commands_idx = 0; \
483 no_targets = 0; \
484 if (pattern) { free(pattern); pattern = 0; } \
485 } while (0)
487 pattern_percent = 0;
488 cmds_started = tgts_started = 1;
490 fstart = &ebuf->floc;
491 fi.filenm = ebuf->floc.filenm;
493 /* Loop over lines in the file.
494 The strategy is to accumulate target names in FILENAMES, dependencies
495 in DEPS and commands in COMMANDS. These are used to define a rule
496 when the start of the next rule (or eof) is encountered.
498 When you see a "continue" in the loop below, that means we are moving on
499 to the next line _without_ ending any rule that we happen to be working
500 with at the moment. If you see a "goto rule_complete", then the
501 statement we just parsed also finishes the previous rule. */
503 commands = xmalloc (200);
505 while (1)
507 unsigned int linelen;
508 char *line;
509 int len;
510 char *p;
511 char *p2;
513 /* Grab the next line to be evaluated */
514 ebuf->floc.lineno += nlines;
515 nlines = readline (ebuf);
517 /* If there is nothing left to eval, we're done. */
518 if (nlines < 0)
519 break;
521 /* If this line is empty, skip it. */
522 line = ebuf->buffer;
523 if (line[0] == '\0')
524 continue;
526 linelen = strlen (line);
528 /* Check for a shell command line first.
529 If it is not one, we can stop treating tab specially. */
530 if (line[0] == '\t')
532 if (no_targets)
533 /* Ignore the commands in a rule with no targets. */
534 continue;
536 /* If there is no preceding rule line, don't treat this line
537 as a command, even though it begins with a tab character.
538 SunOS 4 make appears to behave this way. */
540 if (filenames != 0)
542 if (ignoring)
543 /* Yep, this is a shell command, and we don't care. */
544 continue;
546 /* Append this command line to the line being accumulated. */
547 if (commands_idx == 0)
548 cmds_started = ebuf->floc.lineno;
550 if (linelen + 1 + commands_idx > commands_len)
552 commands_len = (linelen + 1 + commands_idx) * 2;
553 commands = xrealloc (commands, commands_len);
555 bcopy (line, &commands[commands_idx], linelen);
556 commands_idx += linelen;
557 commands[commands_idx++] = '\n';
559 continue;
563 /* This line is not a shell command line. Don't worry about tabs.
564 Get more space if we need it; we don't need to preserve the current
565 contents of the buffer. */
567 if (collapsed_length < linelen+1)
569 collapsed_length = linelen+1;
570 if (collapsed)
571 free ((char *)collapsed);
572 collapsed = (char *) xmalloc (collapsed_length);
574 strcpy (collapsed, line);
575 /* Collapse continuation lines. */
576 collapse_continuations (collapsed);
577 remove_comments (collapsed);
579 /* Compare a word, both length and contents. */
580 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
581 p = collapsed;
582 while (isspace ((unsigned char)*p))
583 ++p;
585 if (*p == '\0')
586 /* This line is completely empty--ignore it. */
587 continue;
589 /* Find the end of the first token. Note we don't need to worry about
590 * ":" here since we compare tokens by length (so "export" will never
591 * be equal to "export:").
593 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
595 len = p2 - p;
597 /* Find the start of the second token. If it looks like a target or
598 variable definition it can't be a preprocessor token so skip
599 them--this allows variables/targets named `ifdef', `export', etc. */
600 while (isspace ((unsigned char)*p2))
601 ++p2;
603 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
605 /* It can't be a preprocessor token so skip it if we're ignoring */
606 if (ignoring)
607 continue;
609 goto skip_conditionals;
612 /* We must first check for conditional and `define' directives before
613 ignoring anything, since they control what we will do with
614 following lines. */
616 if (!in_ignored_define
617 && (word1eq ("ifdef") || word1eq ("ifndef")
618 || word1eq ("ifeq") || word1eq ("ifneq")
619 || word1eq ("else") || word1eq ("endif")))
621 int i = conditional_line (p, fstart);
622 if (i < 0)
623 fatal (fstart, _("invalid syntax in conditional"));
625 ignoring = i;
626 continue;
629 if (word1eq ("endef"))
631 if (!in_ignored_define)
632 fatal (fstart, _("extraneous `endef'"));
633 in_ignored_define = 0;
634 continue;
637 if (word1eq ("define"))
639 if (ignoring)
640 in_ignored_define = 1;
641 else
643 if (*p2 == '\0')
644 fatal (fstart, _("empty variable name"));
646 /* Let the variable name be the whole rest of the line,
647 with trailing blanks stripped (comments have already been
648 removed), so it could be a complex variable/function
649 reference that might contain blanks. */
650 p = strchr (p2, '\0');
651 while (isblank ((unsigned char)p[-1]))
652 --p;
653 do_define (p2, p - p2, o_file, ebuf);
655 continue;
658 if (word1eq ("override"))
660 if (*p2 == '\0')
661 error (fstart, _("empty `override' directive"));
663 if (strneq (p2, "define", 6)
664 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
666 if (ignoring)
667 in_ignored_define = 1;
668 else
670 p2 = next_token (p2 + 6);
671 if (*p2 == '\0')
672 fatal (fstart, _("empty variable name"));
674 /* Let the variable name be the whole rest of the line,
675 with trailing blanks stripped (comments have already been
676 removed), so it could be a complex variable/function
677 reference that might contain blanks. */
678 p = strchr (p2, '\0');
679 while (isblank ((unsigned char)p[-1]))
680 --p;
681 do_define (p2, p - p2, o_override, ebuf);
684 else if (!ignoring
685 && !try_variable_definition (fstart, p2, o_override, 0))
686 error (fstart, _("invalid `override' directive"));
688 continue;
691 if (ignoring)
692 /* Ignore the line. We continue here so conditionals
693 can appear in the middle of a rule. */
694 continue;
696 if (word1eq ("export"))
698 /* 'export' by itself causes everything to be exported. */
699 if (*p2 == '\0')
700 export_all_variables = 1;
701 else
703 struct variable *v;
705 v = try_variable_definition (fstart, p2, o_file, 0);
706 if (v != 0)
707 v->export = v_export;
708 else
710 unsigned int len;
711 char *ap;
713 /* Expand the line so we can use indirect and constructed
714 variable names in an export command. */
715 p2 = ap = allocated_variable_expand (p2);
717 for (p = find_next_token (&p2, &len); p != 0;
718 p = find_next_token (&p2, &len))
720 v = lookup_variable (p, len);
721 if (v == 0)
722 v = define_variable_loc (p, len, "", o_file, 0,
723 fstart);
724 v->export = v_export;
727 free (ap);
730 goto rule_complete;
733 if (word1eq ("unexport"))
735 if (*p2 == '\0')
736 export_all_variables = 0;
737 else
739 unsigned int len;
740 struct variable *v;
741 char *ap;
743 /* Expand the line so we can use indirect and constructed
744 variable names in an unexport command. */
745 p2 = ap = allocated_variable_expand (p2);
747 for (p = find_next_token (&p2, &len); p != 0;
748 p = find_next_token (&p2, &len))
750 v = lookup_variable (p, len);
751 if (v == 0)
752 v = define_variable_loc (p, len, "", o_file, 0, fstart);
754 v->export = v_noexport;
757 free (ap);
759 goto rule_complete;
762 skip_conditionals:
763 if (word1eq ("vpath"))
765 char *pattern;
766 unsigned int len;
767 p2 = variable_expand (p2);
768 p = find_next_token (&p2, &len);
769 if (p != 0)
771 pattern = savestring (p, len);
772 p = find_next_token (&p2, &len);
773 /* No searchpath means remove all previous
774 selective VPATH's with the same pattern. */
776 else
777 /* No pattern means remove all previous selective VPATH's. */
778 pattern = 0;
779 construct_vpath_list (pattern, p);
780 if (pattern != 0)
781 free (pattern);
783 goto rule_complete;
786 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
788 /* We have found an `include' line specifying a nested
789 makefile to be read at this point. */
790 struct conditionals *save;
791 struct conditionals new_conditionals;
792 struct nameseq *files;
793 /* "-include" (vs "include") says no error if the file does not
794 exist. "sinclude" is an alias for this from SGI. */
795 int noerror = (p[0] != 'i');
797 p = allocated_variable_expand (p2);
798 if (*p == '\0')
800 error (fstart,
801 _("no file name for `%sinclude'"), noerror ? "-" : "");
802 continue;
805 /* Parse the list of file names. */
806 p2 = p;
807 files = multi_glob (parse_file_seq (&p2, '\0',
808 sizeof (struct nameseq),
810 sizeof (struct nameseq));
811 free (p);
813 /* Save the state of conditionals and start
814 the included makefile with a clean slate. */
815 save = install_conditionals (&new_conditionals);
817 /* Record the rules that are waiting so they will determine
818 the default goal before those in the included makefile. */
819 record_waiting_files ();
821 /* Read each included makefile. */
822 while (files != 0)
824 struct nameseq *next = files->next;
825 char *name = files->name;
826 int r;
828 free ((char *)files);
829 files = next;
831 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
832 | (noerror ? RM_DONTCARE : 0)));
833 if (!r)
835 if (!noerror)
836 error (fstart, "%s: %s", name, strerror (errno));
837 free (name);
841 /* Restore conditional state. */
842 restore_conditionals (save);
844 goto rule_complete;
847 if (try_variable_definition (fstart, p, o_file, 0))
848 /* This line has been dealt with. */
849 goto rule_complete;
851 if (line[0] == '\t')
853 p = collapsed; /* Ignore comments, etc. */
854 while (isblank ((unsigned char)*p))
855 ++p;
856 if (*p == '\0')
857 /* The line is completely blank; that is harmless. */
858 continue;
860 /* This line starts with a tab but was not caught above
861 because there was no preceding target, and the line
862 might have been usable as a variable definition.
863 But now we know it is definitely lossage. */
864 fatal(fstart, _("commands commence before first target"));
867 /* This line describes some target files. This is complicated by
868 the existence of target-specific variables, because we can't
869 expand the entire line until we know if we have one or not. So
870 we expand the line word by word until we find the first `:',
871 then check to see if it's a target-specific variable.
873 In this algorithm, `lb_next' will point to the beginning of the
874 unexpanded parts of the input buffer, while `p2' points to the
875 parts of the expanded buffer we haven't searched yet. */
878 enum make_word_type wtype;
879 enum variable_origin v_origin;
880 int exported;
881 char *cmdleft, *semip, *lb_next;
882 unsigned int len, plen = 0;
883 char *colonp;
885 /* Record the previous rule. */
887 record_waiting_files ();
888 tgts_started = fstart->lineno;
890 /* Search the line for an unquoted ; that is not after an
891 unquoted #. */
892 cmdleft = find_char_unquote (line, ';', '#', 0);
893 if (cmdleft != 0 && *cmdleft == '#')
895 /* We found a comment before a semicolon. */
896 *cmdleft = '\0';
897 cmdleft = 0;
899 else if (cmdleft != 0)
900 /* Found one. Cut the line short there before expanding it. */
901 *(cmdleft++) = '\0';
902 semip = cmdleft;
904 collapse_continuations (line);
906 /* We can't expand the entire line, since if it's a per-target
907 variable we don't want to expand it. So, walk from the
908 beginning, expanding as we go, and looking for "interesting"
909 chars. The first word is always expandable. */
910 wtype = get_next_mword(line, NULL, &lb_next, &len);
911 switch (wtype)
913 case w_eol:
914 if (cmdleft != 0)
915 fatal(fstart, _("missing rule before commands"));
916 /* This line contained something but turned out to be nothing
917 but whitespace (a comment?). */
918 continue;
920 case w_colon:
921 case w_dcolon:
922 /* We accept and ignore rules without targets for
923 compatibility with SunOS 4 make. */
924 no_targets = 1;
925 continue;
927 default:
928 break;
931 p2 = variable_expand_string(NULL, lb_next, len);
932 while (1)
934 lb_next += len;
935 if (cmdleft == 0)
937 /* Look for a semicolon in the expanded line. */
938 cmdleft = find_char_unquote (p2, ';', 0, 0);
940 if (cmdleft != 0)
942 unsigned long p2_off = p2 - variable_buffer;
943 unsigned long cmd_off = cmdleft - variable_buffer;
944 char *pend = p2 + strlen(p2);
946 /* Append any remnants of lb, then cut the line short
947 at the semicolon. */
948 *cmdleft = '\0';
950 /* One school of thought says that you shouldn't expand
951 here, but merely copy, since now you're beyond a ";"
952 and into a command script. However, the old parser
953 expanded the whole line, so we continue that for
954 backwards-compatiblity. Also, it wouldn't be
955 entirely consistent, since we do an unconditional
956 expand below once we know we don't have a
957 target-specific variable. */
958 (void)variable_expand_string(pend, lb_next, (long)-1);
959 lb_next += strlen(lb_next);
960 p2 = variable_buffer + p2_off;
961 cmdleft = variable_buffer + cmd_off + 1;
965 colonp = find_char_unquote(p2, ':', 0, 0);
966 #ifdef HAVE_DOS_PATHS
967 /* The drive spec brain-damage strikes again... */
968 /* Note that the only separators of targets in this context
969 are whitespace and a left paren. If others are possible,
970 they should be added to the string in the call to index. */
971 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
972 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
973 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
974 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
975 #endif
976 if (colonp != 0)
977 break;
979 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
980 if (wtype == w_eol)
981 break;
983 p2 += strlen(p2);
984 *(p2++) = ' ';
985 p2 = variable_expand_string(p2, lb_next, len);
986 /* We don't need to worry about cmdleft here, because if it was
987 found in the variable_buffer the entire buffer has already
988 been expanded... we'll never get here. */
991 p2 = next_token (variable_buffer);
993 /* If the word we're looking at is EOL, see if there's _anything_
994 on the line. If not, a variable expanded to nothing, so ignore
995 it. If so, we can't parse this line so punt. */
996 if (wtype == w_eol)
998 if (*p2 != '\0')
999 /* There's no need to be ivory-tower about this: check for
1000 one of the most common bugs found in makefiles... */
1001 fatal (fstart, _("missing separator%s"),
1002 !strneq(line, " ", 8) ? ""
1003 : _(" (did you mean TAB instead of 8 spaces?)"));
1004 continue;
1007 /* Make the colon the end-of-string so we know where to stop
1008 looking for targets. */
1009 *colonp = '\0';
1010 filenames = multi_glob (parse_file_seq (&p2, '\0',
1011 sizeof (struct nameseq),
1013 sizeof (struct nameseq));
1014 *p2 = ':';
1016 if (!filenames)
1018 /* We accept and ignore rules without targets for
1019 compatibility with SunOS 4 make. */
1020 no_targets = 1;
1021 continue;
1023 /* This should never be possible; we handled it above. */
1024 assert (*p2 != '\0');
1025 ++p2;
1027 /* Is this a one-colon or two-colon entry? */
1028 two_colon = *p2 == ':';
1029 if (two_colon)
1030 p2++;
1032 /* Test to see if it's a target-specific variable. Copy the rest
1033 of the buffer over, possibly temporarily (we'll expand it later
1034 if it's not a target-specific variable). PLEN saves the length
1035 of the unparsed section of p2, for later. */
1036 if (*lb_next != '\0')
1038 unsigned int l = p - variable_buffer;
1039 unsigned int l2 = p2 - variable_buffer;
1040 plen = strlen (p2);
1041 (void) variable_buffer_output (p2+plen,
1042 lb_next, strlen (lb_next)+1);
1043 p = variable_buffer + l;
1044 p2 = variable_buffer + l2;
1047 /* See if it's an "override" or "export" keyword; if so see if what
1048 comes after it looks like a variable definition. */
1050 wtype = get_next_mword (p2, NULL, &p, &len);
1052 v_origin = o_file;
1053 exported = 0;
1054 if (wtype == w_static)
1056 if (word1eq ("override"))
1058 v_origin = o_override;
1059 wtype = get_next_mword (p+len, NULL, &p, &len);
1061 else if (word1eq ("export"))
1063 exported = 1;
1064 wtype = get_next_mword (p+len, NULL, &p, &len);
1068 if (wtype != w_eol)
1069 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1071 if (wtype == w_varassign)
1073 /* If there was a semicolon found, add it back, plus anything
1074 after it. */
1075 if (semip)
1077 unsigned int l = p - variable_buffer;
1078 *(--semip) = ';';
1079 variable_buffer_output (p2 + strlen (p2),
1080 semip, strlen (semip)+1);
1081 p = variable_buffer + l;
1083 record_target_var (filenames, p, v_origin, exported, fstart);
1084 filenames = 0;
1085 continue;
1088 /* This is a normal target, _not_ a target-specific variable.
1089 Unquote any = in the dependency list. */
1090 find_char_unquote (lb_next, '=', 0, 0);
1092 /* We have some targets, so don't ignore the following commands. */
1093 no_targets = 0;
1095 /* Expand the dependencies, etc. */
1096 if (*lb_next != '\0')
1098 unsigned int l = p2 - variable_buffer;
1099 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1100 p2 = variable_buffer + l;
1102 /* Look for a semicolon in the expanded line. */
1103 if (cmdleft == 0)
1105 cmdleft = find_char_unquote (p2, ';', 0, 0);
1106 if (cmdleft != 0)
1107 *(cmdleft++) = '\0';
1111 /* Do any of the prerequisites appear to have $@ etc.? */
1112 have_sysv_atvar = 0;
1113 if (!posix_pedantic)
1114 for (p = strchr (p2, '$'); p != 0; p = strchr (p+1, '$'))
1115 if (p[1] == '@' || ((p[1] == '(' || p[1] == '{') && p[2] == '@'))
1117 have_sysv_atvar = 1;
1118 break;
1121 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1122 p = strchr (p2, ':');
1123 while (p != 0 && p[-1] == '\\')
1125 register char *q = &p[-1];
1126 register int backslash = 0;
1127 while (*q-- == '\\')
1128 backslash = !backslash;
1129 if (backslash)
1130 p = strchr (p + 1, ':');
1131 else
1132 break;
1134 #ifdef _AMIGA
1135 /* Here, the situation is quite complicated. Let's have a look
1136 at a couple of targets:
1138 install: dev:make
1140 dev:make: make
1142 dev:make:: xyz
1144 The rule is that it's only a target, if there are TWO :'s
1145 OR a space around the :.
1147 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1148 || isspace ((unsigned char)p[-1])))
1149 p = 0;
1150 #endif
1151 #ifdef HAVE_DOS_PATHS
1153 int check_again;
1155 do {
1156 check_again = 0;
1157 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1158 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1159 isalpha ((unsigned char)p[-1]) &&
1160 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1161 p = strchr (p + 1, ':');
1162 check_again = 1;
1164 } while (check_again);
1166 #endif
1167 if (p != 0)
1169 struct nameseq *target;
1170 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1171 ++p2;
1172 if (target == 0)
1173 fatal (fstart, _("missing target pattern"));
1174 else if (target->next != 0)
1175 fatal (fstart, _("multiple target patterns"));
1176 pattern = target->name;
1177 pattern_percent = find_percent (pattern);
1178 if (pattern_percent == 0)
1179 fatal (fstart, _("target pattern contains no `%%'"));
1180 free((char *)target);
1182 else
1183 pattern = 0;
1185 /* Parse the dependencies. */
1186 deps = (struct dep *)
1187 multi_glob (parse_file_seq (&p2, '|', sizeof (struct dep), 1),
1188 sizeof (struct dep));
1189 if (*p2)
1191 /* Files that follow '|' are special prerequisites that
1192 need only exist in order to satisfy the dependency.
1193 Their modification times are irrelevant. */
1194 struct dep **deps_ptr = &deps;
1195 struct dep *d;
1196 for (deps_ptr = &deps; *deps_ptr; deps_ptr = &(*deps_ptr)->next)
1198 ++p2;
1199 *deps_ptr = (struct dep *)
1200 multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
1201 sizeof (struct dep));
1202 for (d = *deps_ptr; d != 0; d = d->next)
1203 d->ignore_mtime = 1;
1206 commands_idx = 0;
1207 if (cmdleft != 0)
1209 /* Semicolon means rest of line is a command. */
1210 unsigned int len = strlen (cmdleft);
1212 cmds_started = fstart->lineno;
1214 /* Add this command line to the buffer. */
1215 if (len + 2 > commands_len)
1217 commands_len = (len + 2) * 2;
1218 commands = (char *) xrealloc (commands, commands_len);
1220 bcopy (cmdleft, commands, len);
1221 commands_idx += len;
1222 commands[commands_idx++] = '\n';
1225 continue;
1228 /* We get here except in the case that we just read a rule line.
1229 Record now the last rule we read, so following spurious
1230 commands are properly diagnosed. */
1231 rule_complete:
1232 record_waiting_files ();
1235 #undef word1eq
1237 if (conditionals->if_cmds)
1238 fatal (fstart, _("missing `endif'"));
1240 /* At eof, record the last rule. */
1241 record_waiting_files ();
1243 if (collapsed)
1244 free ((char *) collapsed);
1245 free ((char *) commands);
1247 return 1;
1251 /* Execute a `define' directive.
1252 The first line has already been read, and NAME is the name of
1253 the variable to be defined. The following lines remain to be read. */
1255 static void
1256 do_define (char *name, unsigned int namelen,
1257 enum variable_origin origin, struct ebuffer *ebuf)
1259 struct floc defstart;
1260 long nlines = 0;
1261 int nlevels = 1;
1262 unsigned int length = 100;
1263 char *definition = (char *) xmalloc (length);
1264 unsigned int idx = 0;
1265 char *p;
1267 /* Expand the variable name. */
1268 char *var = (char *) alloca (namelen + 1);
1269 bcopy (name, var, namelen);
1270 var[namelen] = '\0';
1271 var = variable_expand (var);
1273 defstart = ebuf->floc;
1275 while (1)
1277 unsigned int len;
1278 char *line;
1280 ebuf->floc.lineno += nlines;
1281 nlines = readline (ebuf);
1283 /* If there is nothing left to eval, we're done. */
1284 if (nlines < 0)
1285 break;
1287 line = ebuf->buffer;
1289 collapse_continuations (line);
1291 /* If the line doesn't begin with a tab, test to see if it introduces
1292 another define, or ends one. */
1294 /* Stop if we find an 'endef' */
1295 if (line[0] != '\t')
1297 p = next_token (line);
1298 len = strlen (p);
1300 /* If this is another 'define', increment the level count. */
1301 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1302 && strneq (p, "define", 6))
1303 ++nlevels;
1305 /* If this is an 'endef', decrement the count. If it's now 0,
1306 we've found the last one. */
1307 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1308 && strneq (p, "endef", 5))
1310 p += 5;
1311 remove_comments (p);
1312 if (*next_token (p) != '\0')
1313 error (&ebuf->floc,
1314 _("Extraneous text after `endef' directive"));
1316 if (--nlevels == 0)
1318 /* Define the variable. */
1319 if (idx == 0)
1320 definition[0] = '\0';
1321 else
1322 definition[idx - 1] = '\0';
1324 /* Always define these variables in the global set. */
1325 define_variable_global (var, strlen (var), definition,
1326 origin, 1, &defstart);
1327 free (definition);
1328 return;
1333 /* Otherwise add this line to the variable definition. */
1334 len = strlen (line);
1335 if (idx + len + 1 > length)
1337 length = (idx + len) * 2;
1338 definition = (char *) xrealloc (definition, length + 1);
1341 bcopy (line, &definition[idx], len);
1342 idx += len;
1343 /* Separate lines with a newline. */
1344 definition[idx++] = '\n';
1347 /* No `endef'!! */
1348 fatal (&defstart, _("missing `endef', unterminated `define'"));
1350 /* NOTREACHED */
1351 return;
1354 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1355 "ifneq", "else" and "endif".
1356 LINE is the input line, with the command as its first word.
1358 FILENAME and LINENO are the filename and line number in the
1359 current makefile. They are used for error messages.
1361 Value is -1 if the line is invalid,
1362 0 if following text should be interpreted,
1363 1 if following text should be ignored. */
1365 static int
1366 conditional_line (char *line, const struct floc *flocp)
1368 int notdef;
1369 char *cmdname;
1370 register unsigned int i;
1372 if (*line == 'i')
1374 /* It's an "if..." command. */
1375 notdef = line[2] == 'n';
1376 if (notdef)
1378 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1379 line += cmdname[3] == 'd' ? 7 : 6;
1381 else
1383 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1384 line += cmdname[2] == 'd' ? 6 : 5;
1387 else
1389 /* It's an "else" or "endif" command. */
1390 notdef = line[1] == 'n';
1391 cmdname = notdef ? "endif" : "else";
1392 line += notdef ? 5 : 4;
1395 line = next_token (line);
1397 if (*cmdname == 'e')
1399 if (*line != '\0')
1400 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1401 /* "Else" or "endif". */
1402 if (conditionals->if_cmds == 0)
1403 fatal (flocp, _("extraneous `%s'"), cmdname);
1404 /* NOTDEF indicates an `endif' command. */
1405 if (notdef)
1406 --conditionals->if_cmds;
1407 else if (conditionals->seen_else[conditionals->if_cmds - 1])
1408 fatal (flocp, _("only one `else' per conditional"));
1409 else
1411 /* Toggle the state of ignorance. */
1412 conditionals->ignoring[conditionals->if_cmds - 1]
1413 = !conditionals->ignoring[conditionals->if_cmds - 1];
1414 /* Record that we have seen an `else' in this conditional.
1415 A second `else' will be erroneous. */
1416 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1418 for (i = 0; i < conditionals->if_cmds; ++i)
1419 if (conditionals->ignoring[i])
1420 return 1;
1421 return 0;
1424 if (conditionals->allocated == 0)
1426 conditionals->allocated = 5;
1427 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1428 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1431 ++conditionals->if_cmds;
1432 if (conditionals->if_cmds > conditionals->allocated)
1434 conditionals->allocated += 5;
1435 conditionals->ignoring = (char *)
1436 xrealloc (conditionals->ignoring, conditionals->allocated);
1437 conditionals->seen_else = (char *)
1438 xrealloc (conditionals->seen_else, conditionals->allocated);
1441 /* Record that we have seen an `if...' but no `else' so far. */
1442 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1444 /* Search through the stack to see if we're already ignoring. */
1445 for (i = 0; i < conditionals->if_cmds - 1; ++i)
1446 if (conditionals->ignoring[i])
1448 /* We are already ignoring, so just push a level
1449 to match the next "else" or "endif", and keep ignoring.
1450 We don't want to expand variables in the condition. */
1451 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1452 return 1;
1455 if (cmdname[notdef ? 3 : 2] == 'd')
1457 /* "Ifdef" or "ifndef". */
1458 char *var;
1459 struct variable *v;
1460 register char *p;
1462 /* Expand the thing we're looking up, so we can use indirect and
1463 constructed variable names. */
1464 var = allocated_variable_expand (line);
1466 /* Make sure there's only one variable name to test. */
1467 p = end_of_token (var);
1468 i = p - var;
1469 p = next_token (p);
1470 if (*p != '\0')
1471 return -1;
1473 var[i] = '\0';
1474 v = lookup_variable (var, strlen (var));
1475 conditionals->ignoring[conditionals->if_cmds - 1]
1476 = (v != 0 && *v->value != '\0') == notdef;
1478 free (var);
1480 else
1482 /* "Ifeq" or "ifneq". */
1483 char *s1, *s2;
1484 unsigned int len;
1485 char termin = *line == '(' ? ',' : *line;
1487 if (termin != ',' && termin != '"' && termin != '\'')
1488 return -1;
1490 s1 = ++line;
1491 /* Find the end of the first string. */
1492 if (termin == ',')
1494 register int count = 0;
1495 for (; *line != '\0'; ++line)
1496 if (*line == '(')
1497 ++count;
1498 else if (*line == ')')
1499 --count;
1500 else if (*line == ',' && count <= 0)
1501 break;
1503 else
1504 while (*line != '\0' && *line != termin)
1505 ++line;
1507 if (*line == '\0')
1508 return -1;
1510 if (termin == ',')
1512 /* Strip blanks after the first string. */
1513 char *p = line++;
1514 while (isblank ((unsigned char)p[-1]))
1515 --p;
1516 *p = '\0';
1518 else
1519 *line++ = '\0';
1521 s2 = variable_expand (s1);
1522 /* We must allocate a new copy of the expanded string because
1523 variable_expand re-uses the same buffer. */
1524 len = strlen (s2);
1525 s1 = (char *) alloca (len + 1);
1526 bcopy (s2, s1, len + 1);
1528 if (termin != ',')
1529 /* Find the start of the second string. */
1530 line = next_token (line);
1532 termin = termin == ',' ? ')' : *line;
1533 if (termin != ')' && termin != '"' && termin != '\'')
1534 return -1;
1536 /* Find the end of the second string. */
1537 if (termin == ')')
1539 register int count = 0;
1540 s2 = next_token (line);
1541 for (line = s2; *line != '\0'; ++line)
1543 if (*line == '(')
1544 ++count;
1545 else if (*line == ')')
1547 if (count <= 0)
1548 break;
1549 else
1550 --count;
1554 else
1556 ++line;
1557 s2 = line;
1558 while (*line != '\0' && *line != termin)
1559 ++line;
1562 if (*line == '\0')
1563 return -1;
1565 *line = '\0';
1566 line = next_token (++line);
1567 if (*line != '\0')
1568 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1570 s2 = variable_expand (s2);
1571 conditionals->ignoring[conditionals->if_cmds - 1]
1572 = streq (s1, s2) == notdef;
1575 /* Search through the stack to see if we're ignoring. */
1576 for (i = 0; i < conditionals->if_cmds; ++i)
1577 if (conditionals->ignoring[i])
1578 return 1;
1579 return 0;
1582 /* Remove duplicate dependencies in CHAIN. */
1584 static unsigned long
1585 dep_hash_1 (const void *key)
1587 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1590 static unsigned long
1591 dep_hash_2 (const void *key)
1593 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1596 static int
1597 dep_hash_cmp (const void *x, const void *y)
1599 struct dep *dx = (struct dep *) x;
1600 struct dep *dy = (struct dep *) y;
1601 int cmp = strcmp (dep_name (dx), dep_name (dy));
1603 /* If the names are the same but ignore_mtimes are not equal, one of these
1604 is an order-only prerequisite and one isn't. That means that we should
1605 remove the one that isn't and keep the one that is. */
1607 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1608 dx->ignore_mtime = dy->ignore_mtime = 0;
1610 return cmp;
1614 void
1615 uniquize_deps (struct dep *chain)
1617 struct hash_table deps;
1618 register struct dep **depp;
1620 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1622 /* Make sure that no dependencies are repeated. This does not
1623 really matter for the purpose of updating targets, but it
1624 might make some names be listed twice for $^ and $?. */
1626 depp = &chain;
1627 while (*depp)
1629 struct dep *dep = *depp;
1630 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1631 if (HASH_VACANT (*dep_slot))
1633 hash_insert_at (&deps, dep, dep_slot);
1634 depp = &dep->next;
1636 else
1638 /* Don't bother freeing duplicates.
1639 It's dangerous and little benefit accrues. */
1640 *depp = dep->next;
1644 hash_free (&deps, 0);
1647 /* Record target-specific variable values for files FILENAMES.
1648 TWO_COLON is nonzero if a double colon was used.
1650 The links of FILENAMES are freed, and so are any names in it
1651 that are not incorporated into other data structures.
1653 If the target is a pattern, add the variable to the pattern-specific
1654 variable value list. */
1656 static void
1657 record_target_var (struct nameseq *filenames, char *defn,
1658 enum variable_origin origin, int exported,
1659 const struct floc *flocp)
1661 struct nameseq *nextf;
1662 struct variable_set_list *global;
1664 global = current_variable_set_list;
1666 /* If the variable is an append version, store that but treat it as a
1667 normal recursive variable. */
1669 for (; filenames != 0; filenames = nextf)
1671 struct variable *v;
1672 register char *name = filenames->name;
1673 char *fname;
1674 char *percent;
1675 struct pattern_var *p;
1677 nextf = filenames->next;
1678 free ((char *) filenames);
1680 /* If it's a pattern target, then add it to the pattern-specific
1681 variable list. */
1682 percent = find_percent (name);
1683 if (percent)
1685 /* Get a reference for this pattern-specific variable struct. */
1686 p = create_pattern_var (name, percent);
1687 p->variable.fileinfo = *flocp;
1688 v = parse_variable_definition (&p->variable, defn);
1689 v->value = xstrdup (v->value);
1690 if (!v)
1691 error (flocp, _("Malformed pattern-specific variable definition"));
1692 fname = p->target;
1694 else
1696 struct file *f;
1698 /* Get a file reference for this file, and initialize it.
1699 We don't want to just call enter_file() because that allocates a
1700 new entry if the file is a double-colon, which we don't want in
1701 this situation. */
1702 f = lookup_file (name);
1703 if (!f)
1704 f = enter_file (name);
1705 else if (f->double_colon)
1706 f = f->double_colon;
1708 initialize_file_variables (f, 1);
1709 fname = f->name;
1711 current_variable_set_list = f->variables;
1712 v = try_variable_definition (flocp, defn, origin, 1);
1713 if (!v)
1714 error (flocp, _("Malformed target-specific variable definition"));
1715 current_variable_set_list = global;
1718 /* Set up the variable to be *-specific. */
1719 v->origin = origin;
1720 v->per_target = 1;
1721 if (exported)
1722 v->export = v_export;
1724 /* If it's not an override, check to see if there was a command-line
1725 setting. If so, reset the value. */
1726 if (origin != o_override)
1728 struct variable *gv;
1729 int len = strlen(v->name);
1731 gv = lookup_variable (v->name, len);
1732 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1734 if (v->value != 0)
1735 free (v->value);
1736 v->value = xstrdup (gv->value);
1737 v->origin = gv->origin;
1738 v->recursive = gv->recursive;
1739 v->append = 0;
1743 /* Free name if not needed further. */
1744 if (name != fname && (name < fname || name > fname + strlen (fname)))
1745 free (name);
1749 /* Record a description line for files FILENAMES,
1750 with dependencies DEPS, commands to execute described
1751 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1752 TWO_COLON is nonzero if a double colon was used.
1753 If not nil, PATTERN is the `%' pattern to make this
1754 a static pattern rule, and PATTERN_PERCENT is a pointer
1755 to the `%' within it.
1757 The links of FILENAMES are freed, and so are any names in it
1758 that are not incorporated into other data structures. */
1760 static void
1761 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1762 struct dep *deps, unsigned int cmds_started, char *commands,
1763 unsigned int commands_idx, int two_colon,
1764 int have_sysv_atvar, const struct floc *flocp, int set_default)
1766 struct nameseq *nextf;
1767 int implicit = 0;
1768 unsigned int max_targets = 0, target_idx = 0;
1769 char **targets = 0, **target_percents = 0;
1770 struct commands *cmds;
1772 if (commands_idx > 0)
1774 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1775 cmds->fileinfo.filenm = flocp->filenm;
1776 cmds->fileinfo.lineno = cmds_started;
1777 cmds->commands = savestring (commands, commands_idx);
1778 cmds->command_lines = 0;
1780 else
1781 cmds = 0;
1783 for (; filenames != 0; filenames = nextf)
1785 char *name = filenames->name;
1786 struct file *f;
1787 struct dep *d;
1788 struct dep *this;
1789 char *implicit_percent;
1791 nextf = filenames->next;
1792 free (filenames);
1794 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1795 good enough: it doesn't happen until after the makefile is read,
1796 which means we cannot use its value during parsing. */
1798 if (streq (name, ".POSIX"))
1799 posix_pedantic = 1;
1801 implicit_percent = find_percent (name);
1802 implicit |= implicit_percent != 0;
1804 if (implicit && pattern != 0)
1805 fatal (flocp, _("mixed implicit and static pattern rules"));
1807 if (implicit && implicit_percent == 0)
1808 fatal (flocp, _("mixed implicit and normal rules"));
1810 if (implicit)
1812 if (targets == 0)
1814 max_targets = 5;
1815 targets = (char **) xmalloc (5 * sizeof (char *));
1816 target_percents = (char **) xmalloc (5 * sizeof (char *));
1817 target_idx = 0;
1819 else if (target_idx == max_targets - 1)
1821 max_targets += 5;
1822 targets = (char **) xrealloc ((char *) targets,
1823 max_targets * sizeof (char *));
1824 target_percents
1825 = (char **) xrealloc ((char *) target_percents,
1826 max_targets * sizeof (char *));
1828 targets[target_idx] = name;
1829 target_percents[target_idx] = implicit_percent;
1830 ++target_idx;
1831 continue;
1834 /* If there are multiple filenames, copy the chain DEPS
1835 for all but the last one. It is not safe for the same deps
1836 to go in more than one place in the data base. */
1837 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1839 if (pattern != 0)
1841 /* If this is an extended static rule:
1842 `targets: target%pattern: dep%pattern; cmds',
1843 translate each dependency pattern into a plain filename
1844 using the target pattern and this target's name. */
1845 if (!pattern_matches (pattern, pattern_percent, name))
1847 /* Give a warning if the rule is meaningless. */
1848 error (flocp,
1849 _("target `%s' doesn't match the target pattern"), name);
1850 this = 0;
1852 else
1854 /* We use patsubst_expand to do the work of translating
1855 the target pattern, the target's name and the dependencies'
1856 patterns into plain dependency names. */
1857 char *buffer = variable_expand ("");
1859 for (d = this; d != 0; d = d->next)
1861 char *o;
1862 char *percent = find_percent (d->name);
1863 if (percent == 0)
1864 continue;
1865 o = patsubst_expand (buffer, name, pattern, d->name,
1866 pattern_percent, percent);
1867 /* If the name expanded to the empty string, that's
1868 illegal. */
1869 if (o == buffer)
1870 fatal (flocp,
1871 _("target `%s' leaves prerequisite pattern empty"),
1872 name);
1873 free (d->name);
1874 d->name = savestring (buffer, o - buffer);
1879 /* If at least one of the dependencies uses $$@ etc. deal with that.
1880 It would be very nice and very simple to just expand everything, but
1881 it would break a lot of backward compatibility. Maybe that's OK
1882 since we're just emulating a SysV function, and if we do that then
1883 why not emulate it completely (that's what SysV make does: it
1884 re-expands the entire prerequisite list, all the time, with $@
1885 etc. in scope). But, it would be a pain indeed to document this
1886 ("iff you use $$@, your prerequisite lists is expanded twice...")
1887 Ouch. Maybe better to make the code more complex. */
1889 if (have_sysv_atvar)
1891 char *p;
1892 int tlen = strlen (name);
1893 char *fnp = strrchr (name, '/');
1894 int dlen;
1895 int flen;
1897 if (fnp)
1899 dlen = fnp - name;
1900 ++fnp;
1901 flen = strlen (fnp);
1903 else
1905 dlen = 0;
1906 fnp = name;
1907 flen = tlen;
1911 for (d = this; d != 0; d = d->next)
1912 for (p = strchr (d->name, '$'); p != 0; p = strchr (p+1, '$'))
1914 char *s = p;
1915 char *at;
1916 int atlen;
1918 /* If it's '$@', '$(@', or '${@', it's escaped */
1919 if ((++p)[0] == '$'
1920 && (p[1] == '@'
1921 || ((p[1] == '(' || p[1] == '{') && p[2] == '@')))
1923 bcopy (p, s, strlen (p)+1);
1924 continue;
1927 /* Maybe found one. We like anything of any form matching @,
1928 [({]@[}):], or [({]@[DF][}):]. */
1930 if (! (p[0] == '@'
1931 || ((p[0] == '(' || p[0] == '{') && (++p)[0] == '@'
1932 && (((++p)[0] == ')' || p[0] == '}' || p[0] == ':')
1933 || ((p[1] == ')' || p[1] == '}' || p[1] == ':')
1934 && (p[0] == 'D' || p[0] == 'F'))))))
1935 continue;
1937 /* Found one. Compute the length and string ptr. Move p
1938 past the variable reference. */
1939 switch (p[0])
1941 case 'D':
1942 atlen = dlen;
1943 at = name;
1944 p += 2;
1945 break;
1947 case 'F':
1948 atlen = flen;
1949 at = fnp;
1950 p += 2;
1951 break;
1953 default:
1954 atlen = tlen;
1955 at = name;
1956 ++p;
1957 break;
1960 /* Get more space. */
1962 int soff = s - d->name;
1963 int poff = p - d->name;
1964 d->name = (char *) xrealloc (d->name,
1965 strlen (d->name) + atlen + 1);
1966 s = d->name + soff;
1967 p = d->name + poff;
1970 /* Copy the string over. */
1971 bcopy(p, s+atlen, strlen (p)+1);
1972 bcopy(at, s, atlen);
1973 p = s + atlen - 1;
1977 if (!two_colon)
1979 /* Single-colon. Combine these dependencies
1980 with others in file's existing record, if any. */
1981 f = enter_file (name);
1983 if (f->double_colon)
1984 fatal (flocp,
1985 _("target file `%s' has both : and :: entries"), f->name);
1987 /* If CMDS == F->CMDS, this target was listed in this rule
1988 more than once. Just give a warning since this is harmless. */
1989 if (cmds != 0 && cmds == f->cmds)
1990 error (flocp,
1991 _("target `%s' given more than once in the same rule."),
1992 f->name);
1994 /* Check for two single-colon entries both with commands.
1995 Check is_target so that we don't lose on files such as .c.o
1996 whose commands were preinitialized. */
1997 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1999 error (&cmds->fileinfo,
2000 _("warning: overriding commands for target `%s'"),
2001 f->name);
2002 error (&f->cmds->fileinfo,
2003 _("warning: ignoring old commands for target `%s'"),
2004 f->name);
2007 f->is_target = 1;
2009 /* Defining .DEFAULT with no deps or cmds clears it. */
2010 if (f == default_file && this == 0 && cmds == 0)
2011 f->cmds = 0;
2012 if (cmds != 0)
2013 f->cmds = cmds;
2014 /* Defining .SUFFIXES with no dependencies
2015 clears out the list of suffixes. */
2016 if (f == suffix_file && this == 0)
2018 d = f->deps;
2019 while (d != 0)
2021 struct dep *nextd = d->next;
2022 free (d->name);
2023 free ((char *)d);
2024 d = nextd;
2026 f->deps = 0;
2028 else if (f->deps != 0)
2030 /* Add the file's old deps and the new ones in THIS together. */
2032 struct dep *firstdeps, *moredeps;
2033 if (cmds != 0)
2035 /* This is the rule with commands, so put its deps first.
2036 The rationale behind this is that $< expands to the
2037 first dep in the chain, and commands use $< expecting
2038 to get the dep that rule specifies. */
2039 firstdeps = this;
2040 moredeps = f->deps;
2042 else
2044 /* Append the new deps to the old ones. */
2045 firstdeps = f->deps;
2046 moredeps = this;
2049 if (firstdeps == 0)
2050 firstdeps = moredeps;
2051 else
2053 d = firstdeps;
2054 while (d->next != 0)
2055 d = d->next;
2056 d->next = moredeps;
2059 f->deps = firstdeps;
2061 else
2062 f->deps = this;
2064 /* If this is a static pattern rule, set the file's stem to
2065 the part of its name that matched the `%' in the pattern,
2066 so you can use $* in the commands. */
2067 if (pattern != 0)
2069 static char *percent = "%";
2070 char *buffer = variable_expand ("");
2071 char *o = patsubst_expand (buffer, name, pattern, percent,
2072 pattern_percent, percent);
2073 f->stem = savestring (buffer, o - buffer);
2076 else
2078 /* Double-colon. Make a new record
2079 even if the file already has one. */
2080 f = lookup_file (name);
2081 /* Check for both : and :: rules. Check is_target so
2082 we don't lose on default suffix rules or makefiles. */
2083 if (f != 0 && f->is_target && !f->double_colon)
2084 fatal (flocp,
2085 _("target file `%s' has both : and :: entries"), f->name);
2086 f = enter_file (name);
2087 /* If there was an existing entry and it was a double-colon
2088 entry, enter_file will have returned a new one, making it the
2089 prev pointer of the old one, and setting its double_colon
2090 pointer to the first one. */
2091 if (f->double_colon == 0)
2092 /* This is the first entry for this name, so we must
2093 set its double_colon pointer to itself. */
2094 f->double_colon = f;
2095 f->is_target = 1;
2096 f->deps = this;
2097 f->cmds = cmds;
2100 /* Free name if not needed further. */
2101 if (f != 0 && name != f->name
2102 && (name < f->name || name > f->name + strlen (f->name)))
2104 free (name);
2105 name = f->name;
2108 /* See if this is first target seen whose name does
2109 not start with a `.', unless it contains a slash. */
2110 if (default_goal_file == 0 && set_default
2111 && (*name != '.' || strchr (name, '/') != 0
2112 #ifdef HAVE_DOS_PATHS
2113 || strchr (name, '\\') != 0
2114 #endif
2117 int reject = 0;
2119 /* If this file is a suffix, don't
2120 let it be the default goal file. */
2122 for (d = suffix_file->deps; d != 0; d = d->next)
2124 register struct dep *d2;
2125 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
2127 reject = 1;
2128 break;
2130 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
2132 register unsigned int len = strlen (dep_name (d2));
2133 if (!strneq (name, dep_name (d2), len))
2134 continue;
2135 if (streq (name + len, dep_name (d)))
2137 reject = 1;
2138 break;
2141 if (reject)
2142 break;
2145 if (!reject)
2146 default_goal_file = f;
2150 if (implicit)
2152 targets[target_idx] = 0;
2153 target_percents[target_idx] = 0;
2154 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2155 free ((char *) target_percents);
2159 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2160 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2161 Quoting backslashes are removed from STRING by compacting it into
2162 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2163 one, or nil if there are none. */
2165 char *
2166 find_char_unquote (char *string, int stop1, int stop2, int blank)
2168 unsigned int string_len = 0;
2169 register char *p = string;
2171 while (1)
2173 if (stop2 && blank)
2174 while (*p != '\0' && *p != stop1 && *p != stop2
2175 && ! isblank ((unsigned char) *p))
2176 ++p;
2177 else if (stop2)
2178 while (*p != '\0' && *p != stop1 && *p != stop2)
2179 ++p;
2180 else if (blank)
2181 while (*p != '\0' && *p != stop1
2182 && ! isblank ((unsigned char) *p))
2183 ++p;
2184 else
2185 while (*p != '\0' && *p != stop1)
2186 ++p;
2188 if (*p == '\0')
2189 break;
2191 if (p > string && p[-1] == '\\')
2193 /* Search for more backslashes. */
2194 register int i = -2;
2195 while (&p[i] >= string && p[i] == '\\')
2196 --i;
2197 ++i;
2198 /* Only compute the length if really needed. */
2199 if (string_len == 0)
2200 string_len = strlen (string);
2201 /* The number of backslashes is now -I.
2202 Copy P over itself to swallow half of them. */
2203 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2204 p += i / 2;
2205 if (i % 2 == 0)
2206 /* All the backslashes quoted each other; the STOPCHAR was
2207 unquoted. */
2208 return p;
2210 /* The STOPCHAR was quoted by a backslash. Look for another. */
2212 else
2213 /* No backslash in sight. */
2214 return p;
2217 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2218 return 0;
2221 /* Search PATTERN for an unquoted %. */
2223 char *
2224 find_percent (char *pattern)
2226 return find_char_unquote (pattern, '%', 0, 0);
2229 /* Parse a string into a sequence of filenames represented as a
2230 chain of struct nameseq's in reverse order and return that chain.
2232 The string is passed as STRINGP, the address of a string pointer.
2233 The string pointer is updated to point at the first character
2234 not parsed, which either is a null char or equals STOPCHAR.
2236 SIZE is how big to construct chain elements.
2237 This is useful if we want them actually to be other structures
2238 that have room for additional info.
2240 If STRIP is nonzero, strip `./'s off the beginning. */
2242 struct nameseq *
2243 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2245 register struct nameseq *new = 0;
2246 register struct nameseq *new1, *lastnew1;
2247 register char *p = *stringp;
2248 char *q;
2249 char *name;
2251 #ifdef VMS
2252 # define VMS_COMMA ','
2253 #else
2254 # define VMS_COMMA 0
2255 #endif
2257 while (1)
2259 /* Skip whitespace; see if any more names are left. */
2260 p = next_token (p);
2261 if (*p == '\0')
2262 break;
2263 if (*p == stopchar)
2264 break;
2266 /* Yes, find end of next name. */
2267 q = p;
2268 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2269 #ifdef VMS
2270 /* convert comma separated list to space separated */
2271 if (p && *p == ',')
2272 *p =' ';
2273 #endif
2274 #ifdef _AMIGA
2275 if (stopchar == ':' && p && *p == ':'
2276 && !(isspace ((unsigned char)p[1]) || !p[1]
2277 || isspace ((unsigned char)p[-1])))
2279 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2281 #endif
2282 #ifdef HAVE_DOS_PATHS
2283 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2284 first colon which isn't followed by a slash or a backslash.
2285 Note that tokens separated by spaces should be treated as separate
2286 tokens since make doesn't allow path names with spaces */
2287 if (stopchar == ':')
2288 while (p != 0 && !isspace ((unsigned char)*p) &&
2289 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2290 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2291 #endif
2292 if (p == 0)
2293 p = q + strlen (q);
2295 if (strip)
2296 #ifdef VMS
2297 /* Skip leading `[]'s. */
2298 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2299 #else
2300 /* Skip leading `./'s. */
2301 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2302 #endif
2304 q += 2; /* Skip "./". */
2305 while (q < p && *q == '/')
2306 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2307 ++q;
2310 /* Extract the filename just found, and skip it. */
2312 if (q == p)
2313 /* ".///" was stripped to "". */
2314 #ifdef VMS
2315 continue;
2316 #else
2317 #ifdef _AMIGA
2318 name = savestring ("", 0);
2319 #else
2320 name = savestring ("./", 2);
2321 #endif
2322 #endif
2323 else
2324 #ifdef VMS
2325 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2326 * to remove this '\' before we can use the filename.
2327 * Savestring called because q may be read-only string constant.
2330 char *qbase = xstrdup (q);
2331 char *pbase = qbase + (p-q);
2332 char *q1 = qbase;
2333 char *q2 = q1;
2334 char *p1 = pbase;
2336 while (q1 != pbase)
2338 if (*q1 == '\\' && *(q1+1) == ':')
2340 q1++;
2341 p1--;
2343 *q2++ = *q1++;
2345 name = savestring (qbase, p1 - qbase);
2346 free (qbase);
2348 #else
2349 name = savestring (q, p - q);
2350 #endif
2352 /* Add it to the front of the chain. */
2353 new1 = (struct nameseq *) xmalloc (size);
2354 new1->name = name;
2355 new1->next = new;
2356 new = new1;
2359 #ifndef NO_ARCHIVES
2361 /* Look for multi-word archive references.
2362 They are indicated by a elt ending with an unmatched `)' and
2363 an elt further down the chain (i.e., previous in the file list)
2364 with an unmatched `(' (e.g., "lib(mem"). */
2366 new1 = new;
2367 lastnew1 = 0;
2368 while (new1 != 0)
2369 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2370 && new1->name[strlen (new1->name) - 1] == ')'
2371 && strchr (new1->name, '(') == 0)
2373 /* NEW1 ends with a `)' but does not contain a `('.
2374 Look back for an elt with an opening `(' but no closing `)'. */
2376 struct nameseq *n = new1->next, *lastn = new1;
2377 char *paren = 0;
2378 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2380 lastn = n;
2381 n = n->next;
2383 if (n != 0
2384 /* Ignore something starting with `(', as that cannot actually
2385 be an archive-member reference (and treating it as such
2386 results in an empty file name, which causes much lossage). */
2387 && n->name[0] != '(')
2389 /* N is the first element in the archive group.
2390 Its name looks like "lib(mem" (with no closing `)'). */
2392 char *libname;
2394 /* Copy "lib(" into LIBNAME. */
2395 ++paren;
2396 libname = (char *) alloca (paren - n->name + 1);
2397 bcopy (n->name, libname, paren - n->name);
2398 libname[paren - n->name] = '\0';
2400 if (*paren == '\0')
2402 /* N was just "lib(", part of something like "lib( a b)".
2403 Edit it out of the chain and free its storage. */
2404 lastn->next = n->next;
2405 free (n->name);
2406 free ((char *) n);
2407 /* LASTN->next is the new stopping elt for the loop below. */
2408 n = lastn->next;
2410 else
2412 /* Replace N's name with the full archive reference. */
2413 name = concat (libname, paren, ")");
2414 free (n->name);
2415 n->name = name;
2418 if (new1->name[1] == '\0')
2420 /* NEW1 is just ")", part of something like "lib(a b )".
2421 Omit it from the chain and free its storage. */
2422 if (lastnew1 == 0)
2423 new = new1->next;
2424 else
2425 lastnew1->next = new1->next;
2426 lastn = new1;
2427 new1 = new1->next;
2428 free (lastn->name);
2429 free ((char *) lastn);
2431 else
2433 /* Replace also NEW1->name, which already has closing `)'. */
2434 name = concat (libname, new1->name, "");
2435 free (new1->name);
2436 new1->name = name;
2437 new1 = new1->next;
2440 /* Trace back from NEW1 (the end of the list) until N
2441 (the beginning of the list), rewriting each name
2442 with the full archive reference. */
2444 while (new1 != n)
2446 name = concat (libname, new1->name, ")");
2447 free (new1->name);
2448 new1->name = name;
2449 lastnew1 = new1;
2450 new1 = new1->next;
2453 else
2455 /* No frobnication happening. Just step down the list. */
2456 lastnew1 = new1;
2457 new1 = new1->next;
2460 else
2462 lastnew1 = new1;
2463 new1 = new1->next;
2466 #endif
2468 *stringp = p;
2469 return new;
2472 /* Find the next line of text in an eval buffer, combining continuation lines
2473 into one line.
2474 Return the number of actual lines read (> 1 if continuation lines).
2475 Returns -1 if there's nothing left in the buffer.
2477 After this function, ebuf->buffer points to the first character of the
2478 line we just found.
2481 /* Read a line of text from a STRING.
2482 Since we aren't really reading from a file, don't bother with linenumbers.
2485 static unsigned long
2486 readstring (struct ebuffer *ebuf)
2488 char *p;
2490 /* If there is nothing left in this buffer, return 0. */
2491 if (ebuf->bufnext > ebuf->bufstart + ebuf->size)
2492 return -1;
2494 /* Set up a new starting point for the buffer, and find the end of the
2495 next logical line (taking into account backslash/newline pairs). */
2497 p = ebuf->buffer = ebuf->bufnext;
2499 while (1)
2501 int backslash = 0;
2503 /* Find the next newline. Keep track of backslashes as we look. */
2504 for (; *p != '\n' && *p != '\0'; ++p)
2505 if (*p == '\\')
2506 backslash = !backslash;
2508 /* If we got to the end of the string or a newline with no backslash,
2509 we're done. */
2510 if (*p == '\0' || !backslash)
2511 break;
2514 /* Overwrite the newline char. */
2515 *p = '\0';
2516 ebuf->bufnext = p+1;
2518 return 0;
2521 static long
2522 readline (struct ebuffer *ebuf)
2524 char *p;
2525 char *end;
2526 char *start;
2527 long nlines = 0;
2529 /* The behaviors between string and stream buffers are different enough to
2530 warrant different functions. Do the Right Thing. */
2532 if (!ebuf->fp)
2533 return readstring (ebuf);
2535 /* When reading from a file, we always start over at the beginning of the
2536 buffer for each new line. */
2538 p = start = ebuf->bufstart;
2539 end = p + ebuf->size;
2540 *p = '\0';
2542 while (fgets (p, end - p, ebuf->fp) != 0)
2544 char *p2;
2545 unsigned long len;
2546 int backslash;
2548 len = strlen (p);
2549 if (len == 0)
2551 /* This only happens when the first thing on the line is a '\0'.
2552 It is a pretty hopeless case, but (wonder of wonders) Athena
2553 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2554 There is nothing really to be done; we synthesize a newline so
2555 the following line doesn't appear to be part of this line. */
2556 error (&ebuf->floc,
2557 _("warning: NUL character seen; rest of line ignored"));
2558 p[0] = '\n';
2559 len = 1;
2562 /* Jump past the text we just read. */
2563 p += len;
2565 /* If the last char isn't a newline, the whole line didn't fit into the
2566 buffer. Get some more buffer and try again. */
2567 if (p[-1] != '\n')
2568 goto more_buffer;
2570 /* We got a newline, so add one to the count of lines. */
2571 ++nlines;
2573 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2574 /* Check to see if the line was really ended with CRLF; if so ignore
2575 the CR. */
2576 if ((p - start) > 1 && p[-2] == '\r')
2578 --p;
2579 p[-1] = '\n';
2581 #endif
2583 backslash = 0;
2584 for (p2 = p - 2; p2 >= start; --p2)
2586 if (*p2 != '\\')
2587 break;
2588 backslash = !backslash;
2591 if (!backslash)
2593 p[-1] = '\0';
2594 break;
2597 /* It was a backslash/newline combo. If we have more space, read
2598 another line. */
2599 if (end - p >= 80)
2600 continue;
2602 /* We need more space at the end of our buffer, so realloc it.
2603 Make sure to preserve the current offset of p. */
2604 more_buffer:
2606 unsigned long off = p - start;
2607 ebuf->size *= 2;
2608 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2609 ebuf->size);
2610 p = start + off;
2611 end = start + ebuf->size;
2612 *p = '\0';
2616 if (ferror (ebuf->fp))
2617 pfatal_with_name (ebuf->floc.filenm);
2619 /* If we found some lines, return how many.
2620 If we didn't, but we did find _something_, that indicates we read the last
2621 line of a file with no final newline; return 1.
2622 If we read nothing, we're at EOF; return -1. */
2624 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2627 /* Parse the next "makefile word" from the input buffer, and return info
2628 about it.
2630 A "makefile word" is one of:
2632 w_bogus Should never happen
2633 w_eol End of input
2634 w_static A static word; cannot be expanded
2635 w_variable A word containing one or more variables/functions
2636 w_colon A colon
2637 w_dcolon A double-colon
2638 w_semicolon A semicolon
2639 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2641 Note that this function is only used when reading certain parts of the
2642 makefile. Don't use it where special rules hold sway (RHS of a variable,
2643 in a command list, etc.) */
2645 static enum make_word_type
2646 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2648 enum make_word_type wtype = w_bogus;
2649 char *p = buffer, *beg;
2650 char c;
2652 /* Skip any leading whitespace. */
2653 while (isblank ((unsigned char)*p))
2654 ++p;
2656 beg = p;
2657 c = *(p++);
2658 switch (c)
2660 case '\0':
2661 wtype = w_eol;
2662 break;
2664 case ';':
2665 wtype = w_semicolon;
2666 break;
2668 case '=':
2669 wtype = w_varassign;
2670 break;
2672 case ':':
2673 wtype = w_colon;
2674 switch (*p)
2676 case ':':
2677 ++p;
2678 wtype = w_dcolon;
2679 break;
2681 case '=':
2682 ++p;
2683 wtype = w_varassign;
2684 break;
2686 break;
2688 case '+':
2689 case '?':
2690 if (*p == '=')
2692 ++p;
2693 wtype = w_varassign;
2694 break;
2697 default:
2698 if (delim && strchr (delim, c))
2699 wtype = w_static;
2700 break;
2703 /* Did we find something? If so, return now. */
2704 if (wtype != w_bogus)
2705 goto done;
2707 /* This is some non-operator word. A word consists of the longest
2708 string of characters that doesn't contain whitespace, one of [:=#],
2709 or [?+]=, or one of the chars in the DELIM string. */
2711 /* We start out assuming a static word; if we see a variable we'll
2712 adjust our assumptions then. */
2713 wtype = w_static;
2715 /* We already found the first value of "c", above. */
2716 while (1)
2718 char closeparen;
2719 int count;
2721 switch (c)
2723 case '\0':
2724 case ' ':
2725 case '\t':
2726 case '=':
2727 goto done_word;
2729 case ':':
2730 #ifdef HAVE_DOS_PATHS
2731 /* A word CAN include a colon in its drive spec. The drive
2732 spec is allowed either at the beginning of a word, or as part
2733 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2734 if (!(p - beg >= 2
2735 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2736 && (p - beg == 2 || p[-3] == '(')))
2737 #endif
2738 goto done_word;
2740 case '$':
2741 c = *(p++);
2742 if (c == '$')
2743 break;
2745 /* This is a variable reference, so note that it's expandable.
2746 Then read it to the matching close paren. */
2747 wtype = w_variable;
2749 if (c == '(')
2750 closeparen = ')';
2751 else if (c == '{')
2752 closeparen = '}';
2753 else
2754 /* This is a single-letter variable reference. */
2755 break;
2757 for (count=0; *p != '\0'; ++p)
2759 if (*p == c)
2760 ++count;
2761 else if (*p == closeparen && --count < 0)
2763 ++p;
2764 break;
2767 break;
2769 case '?':
2770 case '+':
2771 if (*p == '=')
2772 goto done_word;
2773 break;
2775 case '\\':
2776 switch (*p)
2778 case ':':
2779 case ';':
2780 case '=':
2781 case '\\':
2782 ++p;
2783 break;
2785 break;
2787 default:
2788 if (delim && strchr (delim, c))
2789 goto done_word;
2790 break;
2793 c = *(p++);
2795 done_word:
2796 --p;
2798 done:
2799 if (startp)
2800 *startp = beg;
2801 if (length)
2802 *length = p - beg;
2803 return wtype;
2806 /* Construct the list of include directories
2807 from the arguments and the default list. */
2809 void
2810 construct_include_path (char **arg_dirs)
2812 register unsigned int i;
2813 #ifdef VAXC /* just don't ask ... */
2814 stat_t stbuf;
2815 #else
2816 struct stat stbuf;
2817 #endif
2818 /* Table to hold the dirs. */
2820 register unsigned int defsize = (sizeof (default_include_directories)
2821 / sizeof (default_include_directories[0]));
2822 register unsigned int max = 5;
2823 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2824 register unsigned int idx = 0;
2826 #ifdef __MSDOS__
2827 defsize++;
2828 #endif
2830 /* First consider any dirs specified with -I switches.
2831 Ignore dirs that don't exist. */
2833 if (arg_dirs != 0)
2834 while (*arg_dirs != 0)
2836 char *dir = *arg_dirs++;
2837 int e;
2839 if (dir[0] == '~')
2841 char *expanded = tilde_expand (dir);
2842 if (expanded != 0)
2843 dir = expanded;
2846 EINTRLOOP (e, stat (dir, &stbuf));
2847 if (e == 0 && S_ISDIR (stbuf.st_mode))
2849 if (idx == max - 1)
2851 max += 5;
2852 dirs = (char **)
2853 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2855 dirs[idx++] = dir;
2857 else if (dir != arg_dirs[-1])
2858 free (dir);
2861 /* Now add at the end the standard default dirs. */
2863 #ifdef __MSDOS__
2865 /* The environment variable $DJDIR holds the root of the
2866 DJGPP directory tree; add ${DJDIR}/include. */
2867 struct variable *djdir = lookup_variable ("DJDIR", 5);
2869 if (djdir)
2871 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2873 strcat (strcpy (defdir, djdir->value), "/include");
2874 dirs[idx++] = defdir;
2877 #endif
2879 for (i = 0; default_include_directories[i] != 0; ++i)
2881 int e;
2883 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2884 if (e == 0 && S_ISDIR (stbuf.st_mode))
2885 dirs[idx++] = default_include_directories[i];
2888 dirs[idx] = 0;
2890 /* Now compute the maximum length of any name in it. */
2892 max_incl_len = 0;
2893 for (i = 0; i < idx; ++i)
2895 unsigned int len = strlen (dirs[i]);
2896 /* If dir name is written with a trailing slash, discard it. */
2897 if (dirs[i][len - 1] == '/')
2898 /* We can't just clobber a null in because it may have come from
2899 a literal string and literal strings may not be writable. */
2900 dirs[i] = savestring (dirs[i], len - 1);
2901 if (len > max_incl_len)
2902 max_incl_len = len;
2905 include_directories = dirs;
2908 /* Expand ~ or ~USER at the beginning of NAME.
2909 Return a newly malloc'd string or 0. */
2911 char *
2912 tilde_expand (char *name)
2914 #ifndef VMS
2915 if (name[1] == '/' || name[1] == '\0')
2917 extern char *getenv ();
2918 char *home_dir;
2919 int is_variable;
2922 /* Turn off --warn-undefined-variables while we expand HOME. */
2923 int save = warn_undefined_variables_flag;
2924 warn_undefined_variables_flag = 0;
2926 home_dir = allocated_variable_expand ("$(HOME)");
2928 warn_undefined_variables_flag = save;
2931 is_variable = home_dir[0] != '\0';
2932 if (!is_variable)
2934 free (home_dir);
2935 home_dir = getenv ("HOME");
2937 #if !defined(_AMIGA) && !defined(WINDOWS32)
2938 if (home_dir == 0 || home_dir[0] == '\0')
2940 extern char *getlogin ();
2941 char *logname = getlogin ();
2942 home_dir = 0;
2943 if (logname != 0)
2945 struct passwd *p = getpwnam (logname);
2946 if (p != 0)
2947 home_dir = p->pw_dir;
2950 #endif /* !AMIGA && !WINDOWS32 */
2951 if (home_dir != 0)
2953 char *new = concat (home_dir, "", name + 1);
2954 if (is_variable)
2955 free (home_dir);
2956 return new;
2959 #if !defined(_AMIGA) && !defined(WINDOWS32)
2960 else
2962 struct passwd *pwent;
2963 char *userend = strchr (name + 1, '/');
2964 if (userend != 0)
2965 *userend = '\0';
2966 pwent = getpwnam (name + 1);
2967 if (pwent != 0)
2969 if (userend == 0)
2970 return xstrdup (pwent->pw_dir);
2971 else
2972 return concat (pwent->pw_dir, "/", userend + 1);
2974 else if (userend != 0)
2975 *userend = '/';
2977 #endif /* !AMIGA && !WINDOWS32 */
2978 #endif /* !VMS */
2979 return 0;
2982 /* Given a chain of struct nameseq's describing a sequence of filenames,
2983 in reverse of the intended order, return a new chain describing the
2984 result of globbing the filenames. The new chain is in forward order.
2985 The links of the old chain are freed or used in the new chain.
2986 Likewise for the names in the old chain.
2988 SIZE is how big to construct chain elements.
2989 This is useful if we want them actually to be other structures
2990 that have room for additional info. */
2992 struct nameseq *
2993 multi_glob (struct nameseq *chain, unsigned int size)
2995 extern void dir_setup_glob ();
2996 register struct nameseq *new = 0;
2997 register struct nameseq *old;
2998 struct nameseq *nexto;
2999 glob_t gl;
3001 dir_setup_glob (&gl);
3003 for (old = chain; old != 0; old = nexto)
3005 #ifndef NO_ARCHIVES
3006 char *memname;
3007 #endif
3009 nexto = old->next;
3011 if (old->name[0] == '~')
3013 char *newname = tilde_expand (old->name);
3014 if (newname != 0)
3016 free (old->name);
3017 old->name = newname;
3021 #ifndef NO_ARCHIVES
3022 if (ar_name (old->name))
3024 /* OLD->name is an archive member reference.
3025 Replace it with the archive file name,
3026 and save the member name in MEMNAME.
3027 We will glob on the archive name and then
3028 reattach MEMNAME later. */
3029 char *arname;
3030 ar_parse_name (old->name, &arname, &memname);
3031 free (old->name);
3032 old->name = arname;
3034 else
3035 memname = 0;
3036 #endif /* !NO_ARCHIVES */
3038 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3040 case 0: /* Success. */
3042 register int i = gl.gl_pathc;
3043 while (i-- > 0)
3045 #ifndef NO_ARCHIVES
3046 if (memname != 0)
3048 /* Try to glob on MEMNAME within the archive. */
3049 struct nameseq *found
3050 = ar_glob (gl.gl_pathv[i], memname, size);
3051 if (found == 0)
3053 /* No matches. Use MEMNAME as-is. */
3054 unsigned int alen = strlen (gl.gl_pathv[i]);
3055 unsigned int mlen = strlen (memname);
3056 struct nameseq *elt
3057 = (struct nameseq *) xmalloc (size);
3058 if (size > sizeof (struct nameseq))
3059 bzero (((char *) elt) + sizeof (struct nameseq),
3060 size - sizeof (struct nameseq));
3061 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3062 bcopy (gl.gl_pathv[i], elt->name, alen);
3063 elt->name[alen] = '(';
3064 bcopy (memname, &elt->name[alen + 1], mlen);
3065 elt->name[alen + 1 + mlen] = ')';
3066 elt->name[alen + 1 + mlen + 1] = '\0';
3067 elt->next = new;
3068 new = elt;
3070 else
3072 /* Find the end of the FOUND chain. */
3073 struct nameseq *f = found;
3074 while (f->next != 0)
3075 f = f->next;
3077 /* Attach the chain being built to the end of the FOUND
3078 chain, and make FOUND the new NEW chain. */
3079 f->next = new;
3080 new = found;
3083 free (memname);
3085 else
3086 #endif /* !NO_ARCHIVES */
3088 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3089 if (size > sizeof (struct nameseq))
3090 bzero (((char *) elt) + sizeof (struct nameseq),
3091 size - sizeof (struct nameseq));
3092 elt->name = xstrdup (gl.gl_pathv[i]);
3093 elt->next = new;
3094 new = elt;
3097 globfree (&gl);
3098 free (old->name);
3099 free ((char *)old);
3100 break;
3103 case GLOB_NOSPACE:
3104 fatal (NILF, _("virtual memory exhausted"));
3105 break;
3107 default:
3108 old->next = new;
3109 new = old;
3110 break;
3114 return new;