Fix bug#1379: don't use alloca() where it could overrun the stack size.
[make/kirr.git] / read.c
blob1d916479479d18ded88cb237785edaf66dd2a9bd
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 int two_colon,
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));
147 /* Read in all the makefiles and return the chain of their names. */
149 struct dep *
150 read_all_makefiles (makefiles)
151 char **makefiles;
153 unsigned int num_makefiles = 0;
155 /* Create *_LIST variables, to hold the makefiles, targets, and variables
156 we will be reading. */
158 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
160 DB (DB_BASIC, (_("Reading makefiles...\n")));
162 /* If there's a non-null variable MAKEFILES, its value is a list of
163 files to read first thing. But don't let it prevent reading the
164 default makefiles and don't let the default goal come from there. */
167 char *value;
168 char *name, *p;
169 unsigned int length;
172 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
173 int save = warn_undefined_variables_flag;
174 warn_undefined_variables_flag = 0;
176 value = allocated_variable_expand ("$(MAKEFILES)");
178 warn_undefined_variables_flag = save;
181 /* Set NAME to the start of next token and LENGTH to its length.
182 MAKEFILES is updated for finding remaining tokens. */
183 p = value;
185 while ((name = find_next_token (&p, &length)) != 0)
187 if (*p != '\0')
188 *p++ = '\0';
189 name = xstrdup (name);
190 if (eval_makefile (name,
191 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
192 free (name);
195 free (value);
198 /* Read makefiles specified with -f switches. */
200 if (makefiles != 0)
201 while (*makefiles != 0)
203 struct dep *tail = read_makefiles;
204 register struct dep *d;
206 if (! eval_makefile (*makefiles, 0))
207 perror_with_name ("", *makefiles);
209 /* Find the right element of read_makefiles. */
210 d = read_makefiles;
211 while (d->next != tail)
212 d = d->next;
214 /* Use the storage read_makefile allocates. */
215 *makefiles = dep_name (d);
216 ++num_makefiles;
217 ++makefiles;
220 /* If there were no -f switches, try the default names. */
222 if (num_makefiles == 0)
224 static char *default_makefiles[] =
225 #ifdef VMS
226 /* all lower case since readdir() (the vms version) 'lowercasifies' */
227 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
228 #else
229 #ifdef _AMIGA
230 { "GNUmakefile", "Makefile", "SMakefile", 0 };
231 #else /* !Amiga && !VMS */
232 { "GNUmakefile", "makefile", "Makefile", 0 };
233 #endif /* AMIGA */
234 #endif /* VMS */
235 register char **p = default_makefiles;
236 while (*p != 0 && !file_exists_p (*p))
237 ++p;
239 if (*p != 0)
241 if (! eval_makefile (*p, 0))
242 perror_with_name ("", *p);
244 else
246 /* No default makefile was found. Add the default makefiles to the
247 `read_makefiles' chain so they will be updated if possible. */
248 struct dep *tail = read_makefiles;
249 /* Add them to the tail, after any MAKEFILES variable makefiles. */
250 while (tail != 0 && tail->next != 0)
251 tail = tail->next;
252 for (p = default_makefiles; *p != 0; ++p)
254 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
255 d->name = 0;
256 d->file = enter_file (*p);
257 d->file->dontcare = 1;
258 d->ignore_mtime = 0;
259 /* Tell update_goal_chain to bail out as soon as this file is
260 made, and main not to die if we can't make this file. */
261 d->changed = RM_DONTCARE;
262 if (tail == 0)
263 read_makefiles = d;
264 else
265 tail->next = d;
266 tail = d;
268 if (tail != 0)
269 tail->next = 0;
273 return read_makefiles;
276 static int
277 eval_makefile (filename, flags)
278 char *filename;
279 int flags;
281 struct dep *deps;
282 struct ebuffer ebuf;
283 const struct floc *curfile;
284 int makefile_errno;
285 int r;
287 ebuf.floc.filenm = filename;
288 ebuf.floc.lineno = 1;
290 if (ISDB (DB_VERBOSE))
292 printf (_("Reading makefile `%s'"), filename);
293 if (flags & RM_NO_DEFAULT_GOAL)
294 printf (_(" (no default goal)"));
295 if (flags & RM_INCLUDED)
296 printf (_(" (search path)"));
297 if (flags & RM_DONTCARE)
298 printf (_(" (don't care)"));
299 if (flags & RM_NO_TILDE)
300 printf (_(" (no ~ expansion)"));
301 puts ("...");
304 /* First, get a stream to read. */
306 /* Expand ~ in FILENAME unless it came from `include',
307 in which case it was already done. */
308 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
310 char *expanded = tilde_expand (filename);
311 if (expanded != 0)
312 filename = expanded;
315 ebuf.fp = fopen (filename, "r");
316 /* Save the error code so we print the right message later. */
317 makefile_errno = errno;
319 /* If the makefile wasn't found and it's either a makefile from
320 the `MAKEFILES' variable or an included makefile,
321 search the included makefile search path for this makefile. */
322 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
324 register unsigned int i;
325 for (i = 0; include_directories[i] != 0; ++i)
327 char *name = concat (include_directories[i], "/", filename);
328 ebuf.fp = fopen (name, "r");
329 if (ebuf.fp == 0)
330 free (name);
331 else
333 filename = name;
334 break;
339 /* Add FILENAME to the chain of read makefiles. */
340 deps = (struct dep *) xmalloc (sizeof (struct dep));
341 deps->next = read_makefiles;
342 read_makefiles = deps;
343 deps->name = 0;
344 deps->file = lookup_file (filename);
345 if (deps->file == 0)
347 deps->file = enter_file (xstrdup (filename));
348 if (flags & RM_DONTCARE)
349 deps->file->dontcare = 1;
351 if (filename != ebuf.floc.filenm)
352 free (filename);
353 filename = deps->file->name;
354 deps->changed = flags;
355 deps->ignore_mtime = 0;
357 /* If the makefile can't be found at all, give up entirely. */
359 if (ebuf.fp == 0)
361 /* If we did some searching, errno has the error from the last
362 attempt, rather from FILENAME itself. Restore it in case the
363 caller wants to use it in a message. */
364 errno = makefile_errno;
365 return 0;
368 /* Add this makefile to the list. */
369 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
370 f_append, 0);
372 /* Evaluate the makefile */
374 ebuf.size = 200;
375 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
377 curfile = reading_file;
378 reading_file = &ebuf.floc;
380 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
382 reading_file = curfile;
384 fclose (ebuf.fp);
386 free (ebuf.bufstart);
387 return r;
391 eval_buffer (buffer)
392 char *buffer;
394 struct ebuffer ebuf;
395 const struct floc *curfile;
396 int r;
398 /* Evaluate the buffer */
400 ebuf.size = strlen (buffer);
401 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
402 ebuf.fp = NULL;
404 ebuf.floc = *reading_file;
406 curfile = reading_file;
407 reading_file = &ebuf.floc;
409 r = eval (&ebuf, 1);
411 reading_file = curfile;
413 return r;
417 /* Read file FILENAME as a makefile and add its contents to the data base.
419 SET_DEFAULT is true if we are allowed to set the default goal.
421 FILENAME is added to the `read_makefiles' chain.
423 Returns 0 if a file was not found or not read.
424 Returns 1 if FILENAME was found and read.
425 Returns 2 if FILENAME was read, and we kept a reference (don't free it). */
427 static int
428 eval (ebuf, set_default)
429 struct ebuffer *ebuf;
430 int set_default;
432 static char *collapsed = 0;
433 static unsigned int collapsed_length = 0;
434 unsigned int commands_len = 200;
435 char *commands;
436 unsigned int commands_idx = 0;
437 unsigned int cmds_started, tgts_started;
438 int ignoring = 0, in_ignored_define = 0;
439 int no_targets = 0; /* Set when reading a rule without targets. */
440 int have_sysv_atvar = 0;
441 struct nameseq *filenames = 0;
442 struct dep *deps = 0;
443 long nlines = 0;
444 int two_colon = 0;
445 char *pattern = 0, *pattern_percent;
446 struct floc *fstart;
447 struct floc fi;
449 #define record_waiting_files() \
450 do \
452 if (filenames != 0) \
454 fi.lineno = tgts_started; \
455 record_files (filenames, pattern, pattern_percent, deps, \
456 cmds_started, commands, commands_idx, two_colon, \
457 have_sysv_atvar, &fi, set_default); \
459 filenames = 0; \
460 commands_idx = 0; \
461 no_targets = 0; \
462 if (pattern) { free(pattern); pattern = 0; } \
463 } while (0)
465 pattern_percent = 0;
466 cmds_started = tgts_started = 1;
468 fstart = &ebuf->floc;
469 fi.filenm = ebuf->floc.filenm;
471 /* Loop over lines in the file.
472 The strategy is to accumulate target names in FILENAMES, dependencies
473 in DEPS and commands in COMMANDS. These are used to define a rule
474 when the start of the next rule (or eof) is encountered.
476 When you see a "continue" in the loop below, that means we are moving on
477 to the next line _without_ ending any rule that we happen to be working
478 with at the moment. If you see a "goto rule_complete", then the
479 statement we just parsed also finishes the previous rule. */
481 commands = xmalloc (200);
483 while (1)
485 int linelen;
486 char *line;
487 int len;
488 char *p;
489 char *p2;
491 /* Grab the next line to be evaluated */
492 ebuf->floc.lineno += nlines;
493 nlines = readline (ebuf);
495 /* If there is nothing left to eval, we're done. */
496 if (nlines < 0)
497 break;
499 /* If this line is empty, skip it. */
500 line = ebuf->buffer;
501 if (line[0] == '\0')
502 continue;
504 linelen = strlen (line);
506 /* Check for a shell command line first.
507 If it is not one, we can stop treating tab specially. */
508 if (line[0] == '\t')
510 if (no_targets)
511 /* Ignore the commands in a rule with no targets. */
512 continue;
514 /* If there is no preceding rule line, don't treat this line
515 as a command, even though it begins with a tab character.
516 SunOS 4 make appears to behave this way. */
518 if (filenames != 0)
520 if (ignoring)
521 /* Yep, this is a shell command, and we don't care. */
522 continue;
524 /* Append this command line to the line being accumulated. */
525 if (commands_idx == 0)
526 cmds_started = ebuf->floc.lineno;
528 if (linelen + 1 + commands_idx > commands_len)
530 commands_len = (linelen + 1 + commands_idx) * 2;
531 commands = xrealloc (commands, commands_len);
533 bcopy (line, &commands[commands_idx], linelen);
534 commands_idx += linelen;
535 commands[commands_idx++] = '\n';
537 continue;
541 /* This line is not a shell command line. Don't worry about tabs. */
543 if (collapsed_length < linelen+1)
545 collapsed_length = linelen+1;
546 if (collapsed != 0)
547 free (collapsed);
548 collapsed = (char *) xmalloc (collapsed_length);
550 strcpy (collapsed, line);
551 /* Collapse continuation lines. */
552 collapse_continuations (collapsed);
553 remove_comments (collapsed);
555 /* Compare a word, both length and contents. */
556 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
557 p = collapsed;
558 while (isspace ((unsigned char)*p))
559 ++p;
561 if (*p == '\0')
562 /* This line is completely empty--ignore it. */
563 continue;
565 /* Find the end of the first token. Note we don't need to worry about
566 * ":" here since we compare tokens by length (so "export" will never
567 * be equal to "export:").
569 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
571 len = p2 - p;
573 /* Find the start of the second token. If it looks like a target or
574 variable definition it can't be a preprocessor token so skip
575 them--this allows variables/targets named `ifdef', `export', etc. */
576 while (isspace ((unsigned char)*p2))
577 ++p2;
579 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
581 /* It can't be a preprocessor token so skip it if we're ignoring */
582 if (ignoring)
583 continue;
585 goto skip_conditionals;
588 /* We must first check for conditional and `define' directives before
589 ignoring anything, since they control what we will do with
590 following lines. */
592 if (!in_ignored_define
593 && (word1eq ("ifdef") || word1eq ("ifndef")
594 || word1eq ("ifeq") || word1eq ("ifneq")
595 || word1eq ("else") || word1eq ("endif")))
597 int i = conditional_line (p, fstart);
598 if (i < 0)
599 fatal (fstart, _("invalid syntax in conditional"));
601 ignoring = i;
602 continue;
605 if (word1eq ("endef"))
607 if (!in_ignored_define)
608 fatal (fstart, _("extraneous `endef'"));
609 in_ignored_define = 0;
610 continue;
613 if (word1eq ("define"))
615 if (ignoring)
616 in_ignored_define = 1;
617 else
619 if (*p2 == '\0')
620 fatal (fstart, _("empty variable name"));
622 /* Let the variable name be the whole rest of the line,
623 with trailing blanks stripped (comments have already been
624 removed), so it could be a complex variable/function
625 reference that might contain blanks. */
626 p = strchr (p2, '\0');
627 while (isblank ((unsigned char)p[-1]))
628 --p;
629 do_define (p2, p - p2, o_file, ebuf);
631 continue;
634 if (word1eq ("override"))
636 if (*p2 == '\0')
637 error (fstart, _("empty `override' directive"));
639 if (strneq (p2, "define", 6)
640 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
642 if (ignoring)
643 in_ignored_define = 1;
644 else
646 p2 = next_token (p2 + 6);
647 if (*p2 == '\0')
648 fatal (fstart, _("empty variable name"));
650 /* Let the variable name be the whole rest of the line,
651 with trailing blanks stripped (comments have already been
652 removed), so it could be a complex variable/function
653 reference that might contain blanks. */
654 p = strchr (p2, '\0');
655 while (isblank ((unsigned char)p[-1]))
656 --p;
657 do_define (p2, p - p2, o_override, ebuf);
660 else if (!ignoring
661 && !try_variable_definition (fstart, p2, o_override, 0))
662 error (fstart, _("invalid `override' directive"));
664 continue;
667 if (ignoring)
668 /* Ignore the line. We continue here so conditionals
669 can appear in the middle of a rule. */
670 continue;
672 if (word1eq ("export"))
674 /* 'export' by itself causes everything to be exported. */
675 if (*p2 == '\0')
676 export_all_variables = 1;
677 else
679 struct variable *v;
681 v = try_variable_definition (fstart, p2, o_file, 0);
682 if (v != 0)
683 v->export = v_export;
684 else
686 unsigned int len;
687 char *ap;
689 /* Expand the line so we can use indirect and constructed
690 variable names in an export command. */
691 p2 = ap = allocated_variable_expand (p2);
693 for (p = find_next_token (&p2, &len); p != 0;
694 p = find_next_token (&p2, &len))
696 v = lookup_variable (p, len);
697 if (v == 0)
698 v = define_variable_loc (p, len, "", o_file, 0,
699 fstart);
700 v->export = v_export;
703 free (ap);
706 goto rule_complete;
709 if (word1eq ("unexport"))
711 if (*p2 == '\0')
712 export_all_variables = 0;
713 else
715 unsigned int len;
716 struct variable *v;
717 char *ap;
719 /* Expand the line so we can use indirect and constructed
720 variable names in an unexport command. */
721 p2 = ap = allocated_variable_expand (p2);
723 for (p = find_next_token (&p2, &len); p != 0;
724 p = find_next_token (&p2, &len))
726 v = lookup_variable (p, len);
727 if (v == 0)
728 v = define_variable_loc (p, len, "", o_file, 0, fstart);
730 v->export = v_noexport;
733 free (ap);
735 goto rule_complete;
738 skip_conditionals:
739 if (word1eq ("vpath"))
741 char *pattern;
742 unsigned int len;
743 p2 = variable_expand (p2);
744 p = find_next_token (&p2, &len);
745 if (p != 0)
747 pattern = savestring (p, len);
748 p = find_next_token (&p2, &len);
749 /* No searchpath means remove all previous
750 selective VPATH's with the same pattern. */
752 else
753 /* No pattern means remove all previous selective VPATH's. */
754 pattern = 0;
755 construct_vpath_list (pattern, p);
756 if (pattern != 0)
757 free (pattern);
759 goto rule_complete;
762 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
764 /* We have found an `include' line specifying a nested
765 makefile to be read at this point. */
766 struct conditionals *save;
767 struct conditionals new_conditionals;
768 struct nameseq *files;
769 /* "-include" (vs "include") says no error if the file does not
770 exist. "sinclude" is an alias for this from SGI. */
771 int noerror = (p[0] != 'i');
773 p = allocated_variable_expand (p2);
774 if (*p == '\0')
776 error (fstart,
777 _("no file name for `%sinclude'"), noerror ? "-" : "");
778 continue;
781 /* Parse the list of file names. */
782 p2 = p;
783 files = multi_glob (parse_file_seq (&p2, '\0',
784 sizeof (struct nameseq),
786 sizeof (struct nameseq));
787 free (p);
789 /* Save the state of conditionals and start
790 the included makefile with a clean slate. */
791 save = conditionals;
792 bzero ((char *) &new_conditionals, sizeof new_conditionals);
793 conditionals = &new_conditionals;
795 /* Record the rules that are waiting so they will determine
796 the default goal before those in the included makefile. */
797 record_waiting_files ();
799 /* Read each included makefile. */
800 while (files != 0)
802 struct nameseq *next = files->next;
803 char *name = files->name;
804 int r;
806 free ((char *)files);
807 files = next;
809 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
810 | (noerror ? RM_DONTCARE : 0)));
811 if (!r)
813 if (!noerror)
814 error (fstart, "%s: %s", name, strerror (errno));
815 free (name);
819 /* Free any space allocated by conditional_line. */
820 if (conditionals->ignoring)
821 free (conditionals->ignoring);
822 if (conditionals->seen_else)
823 free (conditionals->seen_else);
825 /* Restore state. */
826 conditionals = save;
828 goto rule_complete;
831 if (try_variable_definition (fstart, p, o_file, 0))
832 /* This line has been dealt with. */
833 goto rule_complete;
835 if (line[0] == '\t')
837 p = collapsed; /* Ignore comments, etc. */
838 while (isblank ((unsigned char)*p))
839 ++p;
840 if (*p == '\0')
841 /* The line is completely blank; that is harmless. */
842 continue;
844 /* This line starts with a tab but was not caught above
845 because there was no preceding target, and the line
846 might have been usable as a variable definition.
847 But now we know it is definitely lossage. */
848 fatal(fstart, _("commands commence before first target"));
851 /* This line describes some target files. This is complicated by
852 the existence of target-specific variables, because we can't
853 expand the entire line until we know if we have one or not. So
854 we expand the line word by word until we find the first `:',
855 then check to see if it's a target-specific variable.
857 In this algorithm, `lb_next' will point to the beginning of the
858 unexpanded parts of the input buffer, while `p2' points to the
859 parts of the expanded buffer we haven't searched yet. */
862 enum make_word_type wtype;
863 enum variable_origin v_origin;
864 int exported;
865 char *cmdleft, *semip, *lb_next;
866 unsigned int len, plen = 0;
867 char *colonp;
869 /* Record the previous rule. */
871 record_waiting_files ();
872 tgts_started = fstart->lineno;
874 /* Search the line for an unquoted ; that is not after an
875 unquoted #. */
876 cmdleft = find_char_unquote (line, ';', '#', 0);
877 if (cmdleft != 0 && *cmdleft == '#')
879 /* We found a comment before a semicolon. */
880 *cmdleft = '\0';
881 cmdleft = 0;
883 else if (cmdleft != 0)
884 /* Found one. Cut the line short there before expanding it. */
885 *(cmdleft++) = '\0';
886 semip = cmdleft;
888 collapse_continuations (line);
890 /* We can't expand the entire line, since if it's a per-target
891 variable we don't want to expand it. So, walk from the
892 beginning, expanding as we go, and looking for "interesting"
893 chars. The first word is always expandable. */
894 wtype = get_next_mword(line, NULL, &lb_next, &len);
895 switch (wtype)
897 case w_eol:
898 if (cmdleft != 0)
899 fatal(fstart, _("missing rule before commands"));
900 /* This line contained something but turned out to be nothing
901 but whitespace (a comment?). */
902 continue;
904 case w_colon:
905 case w_dcolon:
906 /* We accept and ignore rules without targets for
907 compatibility with SunOS 4 make. */
908 no_targets = 1;
909 continue;
911 default:
912 break;
915 p2 = variable_expand_string(NULL, lb_next, len);
916 while (1)
918 lb_next += len;
919 if (cmdleft == 0)
921 /* Look for a semicolon in the expanded line. */
922 cmdleft = find_char_unquote (p2, ';', 0, 0);
924 if (cmdleft != 0)
926 unsigned long p2_off = p2 - variable_buffer;
927 unsigned long cmd_off = cmdleft - variable_buffer;
928 char *pend = p2 + strlen(p2);
930 /* Append any remnants of lb, then cut the line short
931 at the semicolon. */
932 *cmdleft = '\0';
934 /* One school of thought says that you shouldn't expand
935 here, but merely copy, since now you're beyond a ";"
936 and into a command script. However, the old parser
937 expanded the whole line, so we continue that for
938 backwards-compatiblity. Also, it wouldn't be
939 entirely consistent, since we do an unconditional
940 expand below once we know we don't have a
941 target-specific variable. */
942 (void)variable_expand_string(pend, lb_next, (long)-1);
943 lb_next += strlen(lb_next);
944 p2 = variable_buffer + p2_off;
945 cmdleft = variable_buffer + cmd_off + 1;
949 colonp = find_char_unquote(p2, ':', 0, 0);
950 #ifdef HAVE_DOS_PATHS
951 /* The drive spec brain-damage strikes again... */
952 /* Note that the only separators of targets in this context
953 are whitespace and a left paren. If others are possible,
954 they should be added to the string in the call to index. */
955 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
956 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
957 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
958 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
959 #endif
960 if (colonp != 0)
961 break;
963 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
964 if (wtype == w_eol)
965 break;
967 p2 += strlen(p2);
968 *(p2++) = ' ';
969 p2 = variable_expand_string(p2, lb_next, len);
970 /* We don't need to worry about cmdleft here, because if it was
971 found in the variable_buffer the entire buffer has already
972 been expanded... we'll never get here. */
975 p2 = next_token (variable_buffer);
977 /* If the word we're looking at is EOL, see if there's _anything_
978 on the line. If not, a variable expanded to nothing, so ignore
979 it. If so, we can't parse this line so punt. */
980 if (wtype == w_eol)
982 if (*p2 != '\0')
983 /* There's no need to be ivory-tower about this: check for
984 one of the most common bugs found in makefiles... */
985 fatal (fstart, _("missing separator%s"),
986 !strneq(line, " ", 8) ? ""
987 : _(" (did you mean TAB instead of 8 spaces?)"));
988 continue;
991 /* Make the colon the end-of-string so we know where to stop
992 looking for targets. */
993 *colonp = '\0';
994 filenames = multi_glob (parse_file_seq (&p2, '\0',
995 sizeof (struct nameseq),
997 sizeof (struct nameseq));
998 *p2 = ':';
1000 if (!filenames)
1002 /* We accept and ignore rules without targets for
1003 compatibility with SunOS 4 make. */
1004 no_targets = 1;
1005 continue;
1007 /* This should never be possible; we handled it above. */
1008 assert (*p2 != '\0');
1009 ++p2;
1011 /* Is this a one-colon or two-colon entry? */
1012 two_colon = *p2 == ':';
1013 if (two_colon)
1014 p2++;
1016 /* Test to see if it's a target-specific variable. Copy the rest
1017 of the buffer over, possibly temporarily (we'll expand it later
1018 if it's not a target-specific variable). PLEN saves the length
1019 of the unparsed section of p2, for later. */
1020 if (*lb_next != '\0')
1022 unsigned int l = p2 - variable_buffer;
1023 plen = strlen (p2);
1024 (void) variable_buffer_output (p2+plen,
1025 lb_next, strlen (lb_next)+1);
1026 p2 = variable_buffer + l;
1029 /* See if it's an "override" or "export" keyword; if so see if what
1030 comes after it looks like a variable definition. */
1032 wtype = get_next_mword (p2, NULL, &p, &len);
1034 v_origin = o_file;
1035 exported = 0;
1036 if (wtype == w_static)
1037 if (word1eq ("override"))
1039 v_origin = o_override;
1040 wtype = get_next_mword (p+len, NULL, &p, &len);
1042 else if (word1eq ("export"))
1044 exported = 1;
1045 wtype = get_next_mword (p+len, NULL, &p, &len);
1048 if (wtype != w_eol)
1049 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1051 if (wtype == w_varassign)
1053 /* If there was a semicolon found, add it back, plus anything
1054 after it. */
1055 if (semip)
1057 *(--semip) = ';';
1058 variable_buffer_output (p2 + strlen (p2),
1059 semip, strlen (semip)+1);
1061 record_target_var (filenames, p, two_colon, v_origin, exported,
1062 fstart);
1063 filenames = 0;
1064 continue;
1067 /* This is a normal target, _not_ a target-specific variable.
1068 Unquote any = in the dependency list. */
1069 find_char_unquote (lb_next, '=', 0, 0);
1071 /* We have some targets, so don't ignore the following commands. */
1072 no_targets = 0;
1074 /* Expand the dependencies, etc. */
1075 if (*lb_next != '\0')
1077 unsigned int l = p2 - variable_buffer;
1078 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1079 p2 = variable_buffer + l;
1081 /* Look for a semicolon in the expanded line. */
1082 if (cmdleft == 0)
1084 cmdleft = find_char_unquote (p2, ';', 0, 0);
1085 if (cmdleft != 0)
1086 *(cmdleft++) = '\0';
1090 /* Do any of the prerequisites appear to have $@ etc.? */
1091 have_sysv_atvar = 0;
1092 if (!posix_pedantic)
1093 for (p = strchr (p2, '$'); p != 0; p = strchr (p+1, '$'))
1094 if (p[1] == '@' || ((p[1] == '(' || p[1] == '{') && p[2] == '@'))
1096 have_sysv_atvar = 1;
1097 break;
1100 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1101 p = strchr (p2, ':');
1102 while (p != 0 && p[-1] == '\\')
1104 register char *q = &p[-1];
1105 register int backslash = 0;
1106 while (*q-- == '\\')
1107 backslash = !backslash;
1108 if (backslash)
1109 p = strchr (p + 1, ':');
1110 else
1111 break;
1113 #ifdef _AMIGA
1114 /* Here, the situation is quite complicated. Let's have a look
1115 at a couple of targets:
1117 install: dev:make
1119 dev:make: make
1121 dev:make:: xyz
1123 The rule is that it's only a target, if there are TWO :'s
1124 OR a space around the :.
1126 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1127 || isspace ((unsigned char)p[-1])))
1128 p = 0;
1129 #endif
1130 #ifdef HAVE_DOS_PATHS
1132 int check_again;
1134 do {
1135 check_again = 0;
1136 /* For DOS paths, skip a "C:\..." or a "C:/..." */
1137 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1138 isalpha ((unsigned char)p[-1]) &&
1139 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1140 p = strchr (p + 1, ':');
1141 check_again = 1;
1143 } while (check_again);
1145 #endif
1146 if (p != 0)
1148 struct nameseq *target;
1149 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1150 ++p2;
1151 if (target == 0)
1152 fatal (fstart, _("missing target pattern"));
1153 else if (target->next != 0)
1154 fatal (fstart, _("multiple target patterns"));
1155 pattern = target->name;
1156 pattern_percent = find_percent (pattern);
1157 if (pattern_percent == 0)
1158 fatal (fstart, _("target pattern contains no `%%'"));
1159 free((char *)target);
1161 else
1162 pattern = 0;
1164 /* Parse the dependencies. */
1165 deps = (struct dep *)
1166 multi_glob (parse_file_seq (&p2, '|', sizeof (struct dep), 1),
1167 sizeof (struct dep));
1168 if (*p2)
1170 /* Files that follow '|' are special prerequisites that
1171 need only exist in order to satisfy the dependency.
1172 Their modification times are irrelevant. */
1173 struct dep **deps_ptr = &deps;
1174 struct dep *d;
1175 for (deps_ptr = &deps; *deps_ptr; deps_ptr = &(*deps_ptr)->next)
1177 ++p2;
1178 *deps_ptr = (struct dep *)
1179 multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
1180 sizeof (struct dep));
1181 for (d = *deps_ptr; d != 0; d = d->next)
1182 d->ignore_mtime = 1;
1185 commands_idx = 0;
1186 if (cmdleft != 0)
1188 /* Semicolon means rest of line is a command. */
1189 unsigned int len = strlen (cmdleft);
1191 cmds_started = fstart->lineno;
1193 /* Add this command line to the buffer. */
1194 if (len + 2 > commands_len)
1196 commands_len = (len + 2) * 2;
1197 commands = (char *) xrealloc (commands, commands_len);
1199 bcopy (cmdleft, commands, len);
1200 commands_idx += len;
1201 commands[commands_idx++] = '\n';
1204 continue;
1207 /* We get here except in the case that we just read a rule line.
1208 Record now the last rule we read, so following spurious
1209 commands are properly diagnosed. */
1210 rule_complete:
1211 record_waiting_files ();
1214 #undef word1eq
1216 if (conditionals->if_cmds)
1217 fatal (fstart, _("missing `endif'"));
1219 /* At eof, record the last rule. */
1220 record_waiting_files ();
1222 free ((char *) commands);
1224 return 1;
1228 /* Execute a `define' directive.
1229 The first line has already been read, and NAME is the name of
1230 the variable to be defined. The following lines remain to be read. */
1232 static void
1233 do_define (name, namelen, origin, ebuf)
1234 char *name;
1235 unsigned int namelen;
1236 enum variable_origin origin;
1237 struct ebuffer *ebuf;
1239 struct floc defstart;
1240 long nlines = 0;
1241 int nlevels = 1;
1242 unsigned int length = 100;
1243 char *definition = (char *) xmalloc (length);
1244 unsigned int idx = 0;
1245 char *p;
1247 /* Expand the variable name. */
1248 char *var = (char *) alloca (namelen + 1);
1249 bcopy (name, var, namelen);
1250 var[namelen] = '\0';
1251 var = variable_expand (var);
1253 defstart = ebuf->floc;
1255 while (1)
1257 unsigned int len;
1258 char *line;
1260 ebuf->floc.lineno += nlines;
1261 nlines = readline (ebuf);
1263 /* If there is nothing left to eval, we're done. */
1264 if (nlines < 0)
1265 break;
1267 line = ebuf->buffer;
1269 collapse_continuations (line);
1271 /* If the line doesn't begin with a tab, test to see if it introduces
1272 another define, or ends one. */
1274 /* Stop if we find an 'endef' */
1275 if (line[0] != '\t')
1277 p = next_token (line);
1278 len = strlen (p);
1280 /* If this is another 'define', increment the level count. */
1281 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1282 && strneq (p, "define", 6))
1283 ++nlevels;
1285 /* If this is an 'endef', decrement the count. If it's now 0,
1286 we've found the last one. */
1287 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1288 && strneq (p, "endef", 5))
1290 p += 5;
1291 remove_comments (p);
1292 if (*next_token (p) != '\0')
1293 error (&ebuf->floc,
1294 _("Extraneous text after `endef' directive"));
1296 if (--nlevels == 0)
1298 /* Define the variable. */
1299 if (idx == 0)
1300 definition[0] = '\0';
1301 else
1302 definition[idx - 1] = '\0';
1304 /* Always define these variables in the global set. */
1305 define_variable_global (var, strlen (var), definition,
1306 origin, 1, &defstart);
1307 free (definition);
1308 return;
1313 /* Otherwise add this line to the variable definition. */
1314 len = strlen (line);
1315 if (idx + len + 1 > length)
1317 length = (idx + len) * 2;
1318 definition = (char *) xrealloc (definition, length + 1);
1321 bcopy (line, &definition[idx], len);
1322 idx += len;
1323 /* Separate lines with a newline. */
1324 definition[idx++] = '\n';
1327 /* No `endef'!! */
1328 fatal (&defstart, _("missing `endef', unterminated `define'"));
1330 /* NOTREACHED */
1331 return;
1334 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1335 "ifneq", "else" and "endif".
1336 LINE is the input line, with the command as its first word.
1338 FILENAME and LINENO are the filename and line number in the
1339 current makefile. They are used for error messages.
1341 Value is -1 if the line is invalid,
1342 0 if following text should be interpreted,
1343 1 if following text should be ignored. */
1345 static int
1346 conditional_line (line, flocp)
1347 char *line;
1348 const struct floc *flocp;
1350 int notdef;
1351 char *cmdname;
1352 register unsigned int i;
1354 if (*line == 'i')
1356 /* It's an "if..." command. */
1357 notdef = line[2] == 'n';
1358 if (notdef)
1360 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1361 line += cmdname[3] == 'd' ? 7 : 6;
1363 else
1365 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1366 line += cmdname[2] == 'd' ? 6 : 5;
1369 else
1371 /* It's an "else" or "endif" command. */
1372 notdef = line[1] == 'n';
1373 cmdname = notdef ? "endif" : "else";
1374 line += notdef ? 5 : 4;
1377 line = next_token (line);
1379 if (*cmdname == 'e')
1381 if (*line != '\0')
1382 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1383 /* "Else" or "endif". */
1384 if (conditionals->if_cmds == 0)
1385 fatal (flocp, _("extraneous `%s'"), cmdname);
1386 /* NOTDEF indicates an `endif' command. */
1387 if (notdef)
1388 --conditionals->if_cmds;
1389 else if (conditionals->seen_else[conditionals->if_cmds - 1])
1390 fatal (flocp, _("only one `else' per conditional"));
1391 else
1393 /* Toggle the state of ignorance. */
1394 conditionals->ignoring[conditionals->if_cmds - 1]
1395 = !conditionals->ignoring[conditionals->if_cmds - 1];
1396 /* Record that we have seen an `else' in this conditional.
1397 A second `else' will be erroneous. */
1398 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1400 for (i = 0; i < conditionals->if_cmds; ++i)
1401 if (conditionals->ignoring[i])
1402 return 1;
1403 return 0;
1406 if (conditionals->allocated == 0)
1408 conditionals->allocated = 5;
1409 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1410 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1413 ++conditionals->if_cmds;
1414 if (conditionals->if_cmds > conditionals->allocated)
1416 conditionals->allocated += 5;
1417 conditionals->ignoring = (char *)
1418 xrealloc (conditionals->ignoring, conditionals->allocated);
1419 conditionals->seen_else = (char *)
1420 xrealloc (conditionals->seen_else, conditionals->allocated);
1423 /* Record that we have seen an `if...' but no `else' so far. */
1424 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1426 /* Search through the stack to see if we're already ignoring. */
1427 for (i = 0; i < conditionals->if_cmds - 1; ++i)
1428 if (conditionals->ignoring[i])
1430 /* We are already ignoring, so just push a level
1431 to match the next "else" or "endif", and keep ignoring.
1432 We don't want to expand variables in the condition. */
1433 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1434 return 1;
1437 if (cmdname[notdef ? 3 : 2] == 'd')
1439 /* "Ifdef" or "ifndef". */
1440 char *var;
1441 struct variable *v;
1442 register char *p = end_of_token (line);
1443 i = p - line;
1444 p = next_token (p);
1445 if (*p != '\0')
1446 return -1;
1448 /* Expand the thing we're looking up, so we can use indirect and
1449 constructed variable names. */
1450 line[i] = '\0';
1451 var = allocated_variable_expand (line);
1453 v = lookup_variable (var, strlen (var));
1454 conditionals->ignoring[conditionals->if_cmds - 1]
1455 = (v != 0 && *v->value != '\0') == notdef;
1457 free (var);
1459 else
1461 /* "Ifeq" or "ifneq". */
1462 char *s1, *s2;
1463 unsigned int len;
1464 char termin = *line == '(' ? ',' : *line;
1466 if (termin != ',' && termin != '"' && termin != '\'')
1467 return -1;
1469 s1 = ++line;
1470 /* Find the end of the first string. */
1471 if (termin == ',')
1473 register int count = 0;
1474 for (; *line != '\0'; ++line)
1475 if (*line == '(')
1476 ++count;
1477 else if (*line == ')')
1478 --count;
1479 else if (*line == ',' && count <= 0)
1480 break;
1482 else
1483 while (*line != '\0' && *line != termin)
1484 ++line;
1486 if (*line == '\0')
1487 return -1;
1489 if (termin == ',')
1491 /* Strip blanks after the first string. */
1492 char *p = line++;
1493 while (isblank ((unsigned char)p[-1]))
1494 --p;
1495 *p = '\0';
1497 else
1498 *line++ = '\0';
1500 s2 = variable_expand (s1);
1501 /* We must allocate a new copy of the expanded string because
1502 variable_expand re-uses the same buffer. */
1503 len = strlen (s2);
1504 s1 = (char *) alloca (len + 1);
1505 bcopy (s2, s1, len + 1);
1507 if (termin != ',')
1508 /* Find the start of the second string. */
1509 line = next_token (line);
1511 termin = termin == ',' ? ')' : *line;
1512 if (termin != ')' && termin != '"' && termin != '\'')
1513 return -1;
1515 /* Find the end of the second string. */
1516 if (termin == ')')
1518 register int count = 0;
1519 s2 = next_token (line);
1520 for (line = s2; *line != '\0'; ++line)
1522 if (*line == '(')
1523 ++count;
1524 else if (*line == ')')
1526 if (count <= 0)
1527 break;
1528 else
1529 --count;
1533 else
1535 ++line;
1536 s2 = line;
1537 while (*line != '\0' && *line != termin)
1538 ++line;
1541 if (*line == '\0')
1542 return -1;
1544 *line = '\0';
1545 line = next_token (++line);
1546 if (*line != '\0')
1547 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1549 s2 = variable_expand (s2);
1550 conditionals->ignoring[conditionals->if_cmds - 1]
1551 = streq (s1, s2) == notdef;
1554 /* Search through the stack to see if we're ignoring. */
1555 for (i = 0; i < conditionals->if_cmds; ++i)
1556 if (conditionals->ignoring[i])
1557 return 1;
1558 return 0;
1561 /* Remove duplicate dependencies in CHAIN. */
1563 static unsigned long
1564 dep_hash_1 (key)
1565 const void *key;
1567 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1570 static unsigned long
1571 dep_hash_2 (key)
1572 const void *key;
1574 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1577 static int
1578 dep_hash_cmp (x, y)
1579 const void *x;
1580 const void *y;
1582 struct dep *dx = (struct dep *) x;
1583 struct dep *dy = (struct dep *) y;
1584 int cmp = strcmp (dep_name (dx), dep_name (dy));
1586 /* If the names are the same but ignore_mtimes are not equal, one of these
1587 is an order-only prerequisite and one isn't. That means that we should
1588 remove the one that isn't and keep the one that is. */
1590 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1591 dx->ignore_mtime = dy->ignore_mtime = 0;
1593 return cmp;
1597 void
1598 uniquize_deps (chain)
1599 struct dep *chain;
1601 struct hash_table deps;
1602 register struct dep **depp;
1604 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1606 /* Make sure that no dependencies are repeated. This does not
1607 really matter for the purpose of updating targets, but it
1608 might make some names be listed twice for $^ and $?. */
1610 depp = &chain;
1611 while (*depp)
1613 struct dep *dep = *depp;
1614 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1615 if (HASH_VACANT (*dep_slot))
1617 hash_insert_at (&deps, dep, dep_slot);
1618 depp = &dep->next;
1620 else
1622 /* Don't bother freeing duplicates.
1623 It's dangerous and little benefit accrues. */
1624 *depp = dep->next;
1628 hash_free (&deps, 0);
1631 /* Record target-specific variable values for files FILENAMES.
1632 TWO_COLON is nonzero if a double colon was used.
1634 The links of FILENAMES are freed, and so are any names in it
1635 that are not incorporated into other data structures.
1637 If the target is a pattern, add the variable to the pattern-specific
1638 variable value list. */
1640 static void
1641 record_target_var (filenames, defn, two_colon, origin, exported, flocp)
1642 struct nameseq *filenames;
1643 char *defn;
1644 int two_colon;
1645 enum variable_origin origin;
1646 int exported;
1647 const struct floc *flocp;
1649 struct nameseq *nextf;
1650 struct variable_set_list *global;
1652 global = current_variable_set_list;
1654 /* If the variable is an append version, store that but treat it as a
1655 normal recursive variable. */
1657 for (; filenames != 0; filenames = nextf)
1659 struct variable *v;
1660 register char *name = filenames->name;
1661 struct variable_set_list *vlist;
1662 char *fname;
1663 char *percent;
1665 nextf = filenames->next;
1666 free ((char *) filenames);
1668 /* If it's a pattern target, then add it to the pattern-specific
1669 variable list. */
1670 percent = find_percent (name);
1671 if (percent)
1673 struct pattern_var *p;
1675 /* Get a reference for this pattern-specific variable struct. */
1676 p = create_pattern_var(name, percent);
1677 vlist = p->vars;
1678 fname = p->target;
1680 else
1682 struct file *f;
1684 /* Get a file reference for this file, and initialize it.
1685 We don't want to just call enter_file() because that allocates a
1686 new entry if the file is a double-colon, which we don't want in
1687 this situation. */
1688 f = lookup_file (name);
1689 if (!f)
1690 f = enter_file (name);
1691 else if (f->double_colon)
1692 f = f->double_colon;
1694 initialize_file_variables (f, 1);
1695 vlist = f->variables;
1696 fname = f->name;
1699 /* Make the new variable context current and define the variable. */
1700 current_variable_set_list = vlist;
1701 v = try_variable_definition (flocp, defn, origin, 1);
1702 if (!v)
1703 error (flocp, _("Malformed per-target variable definition"));
1704 v->per_target = 1;
1705 if (exported)
1706 v->export = v_export;
1708 /* If it's not an override, check to see if there was a command-line
1709 setting. If so, reset the value. */
1710 if (origin != o_override)
1712 struct variable *gv;
1713 int len = strlen(v->name);
1715 current_variable_set_list = global;
1716 gv = lookup_variable (v->name, len);
1717 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1719 v = define_variable_in_set (v->name, len, gv->value, gv->origin,
1720 gv->recursive, vlist->set, flocp);
1721 v->append = 0;
1725 /* Free name if not needed further. */
1726 if (name != fname && (name < fname || name > fname + strlen (fname)))
1727 free (name);
1730 current_variable_set_list = global;
1733 /* Record a description line for files FILENAMES,
1734 with dependencies DEPS, commands to execute described
1735 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1736 TWO_COLON is nonzero if a double colon was used.
1737 If not nil, PATTERN is the `%' pattern to make this
1738 a static pattern rule, and PATTERN_PERCENT is a pointer
1739 to the `%' within it.
1741 The links of FILENAMES are freed, and so are any names in it
1742 that are not incorporated into other data structures. */
1744 static void
1745 record_files (filenames, pattern, pattern_percent, deps, cmds_started,
1746 commands, commands_idx, two_colon, have_sysv_atvar,
1747 flocp, set_default)
1748 struct nameseq *filenames;
1749 char *pattern, *pattern_percent;
1750 struct dep *deps;
1751 unsigned int cmds_started;
1752 char *commands;
1753 unsigned int commands_idx;
1754 int two_colon;
1755 int have_sysv_atvar;
1756 const struct floc *flocp;
1757 int set_default;
1759 struct nameseq *nextf;
1760 int implicit = 0;
1761 unsigned int max_targets = 0, target_idx = 0;
1762 char **targets = 0, **target_percents = 0;
1763 struct commands *cmds;
1765 if (commands_idx > 0)
1767 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1768 cmds->fileinfo.filenm = flocp->filenm;
1769 cmds->fileinfo.lineno = cmds_started;
1770 cmds->commands = savestring (commands, commands_idx);
1771 cmds->command_lines = 0;
1773 else
1774 cmds = 0;
1776 for (; filenames != 0; filenames = nextf)
1778 char *name = filenames->name;
1779 struct file *f;
1780 struct dep *d;
1781 struct dep *this;
1782 char *implicit_percent;
1784 nextf = filenames->next;
1785 free (filenames);
1787 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1788 good enough: it doesn't happen until after the makefile is read,
1789 which means we cannot use its value during parsing. */
1791 if (streq (name, ".POSIX"))
1792 posix_pedantic = 1;
1794 implicit_percent = find_percent (name);
1795 implicit |= implicit_percent != 0;
1797 if (implicit && pattern != 0)
1798 fatal (flocp, _("mixed implicit and static pattern rules"));
1800 if (implicit && implicit_percent == 0)
1801 fatal (flocp, _("mixed implicit and normal rules"));
1803 if (implicit)
1805 if (targets == 0)
1807 max_targets = 5;
1808 targets = (char **) xmalloc (5 * sizeof (char *));
1809 target_percents = (char **) xmalloc (5 * sizeof (char *));
1810 target_idx = 0;
1812 else if (target_idx == max_targets - 1)
1814 max_targets += 5;
1815 targets = (char **) xrealloc ((char *) targets,
1816 max_targets * sizeof (char *));
1817 target_percents
1818 = (char **) xrealloc ((char *) target_percents,
1819 max_targets * sizeof (char *));
1821 targets[target_idx] = name;
1822 target_percents[target_idx] = implicit_percent;
1823 ++target_idx;
1824 continue;
1827 /* If there are multiple filenames, copy the chain DEPS
1828 for all but the last one. It is not safe for the same deps
1829 to go in more than one place in the data base. */
1830 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1832 if (pattern != 0)
1834 /* If this is an extended static rule:
1835 `targets: target%pattern: dep%pattern; cmds',
1836 translate each dependency pattern into a plain filename
1837 using the target pattern and this target's name. */
1838 if (!pattern_matches (pattern, pattern_percent, name))
1840 /* Give a warning if the rule is meaningless. */
1841 error (flocp,
1842 _("target `%s' doesn't match the target pattern"), name);
1843 this = 0;
1845 else
1847 /* We use patsubst_expand to do the work of translating
1848 the target pattern, the target's name and the dependencies'
1849 patterns into plain dependency names. */
1850 char *buffer = variable_expand ("");
1852 for (d = this; d != 0; d = d->next)
1854 char *o;
1855 char *percent = find_percent (d->name);
1856 if (percent == 0)
1857 continue;
1858 o = patsubst_expand (buffer, name, pattern, d->name,
1859 pattern_percent, percent);
1860 /* If the name expanded to the empty string, that's
1861 illegal. */
1862 if (o == buffer)
1863 fatal (flocp,
1864 _("target `%s' leaves prerequisite pattern empty"),
1865 name);
1866 free (d->name);
1867 d->name = savestring (buffer, o - buffer);
1872 /* If at least one of the dependencies uses $$@ etc. deal with that.
1873 It would be very nice and very simple to just expand everything, but
1874 it would break a lot of backward compatibility. Maybe that's OK
1875 since we're just emulating a SysV function, and if we do that then
1876 why not emulate it completely (that's what SysV make does: it
1877 re-expands the entire prerequisite list, all the time, with $@
1878 etc. in scope). But, it would be a pain indeed to document this
1879 ("iff you use $$@, your prerequisite lists is expanded twice...")
1880 Ouch. Maybe better to make the code more complex. */
1882 if (have_sysv_atvar)
1884 char *p;
1885 int tlen = strlen (name);
1886 char *fnp = strrchr (name, '/');
1887 int dlen;
1888 int flen;
1890 if (fnp)
1892 dlen = fnp - name;
1893 ++fnp;
1894 flen = strlen (fnp);
1896 else
1898 dlen = 0;
1899 fnp = name;
1900 flen = tlen;
1904 for (d = this; d != 0; d = d->next)
1905 for (p = strchr (d->name, '$'); p != 0; p = strchr (p+1, '$'))
1907 char *s = p;
1908 char *at;
1909 int atlen;
1911 /* If it's '$@', '$(@', or '${@', it's escaped */
1912 if ((++p)[0] == '$'
1913 && (p[1] == '@'
1914 || ((p[1] == '(' || p[1] == '{') && p[2] == '@')))
1916 bcopy (p, s, strlen (p)+1);
1917 continue;
1920 /* Maybe found one. We like anything of any form matching @,
1921 [({]@[}):], or [({]@[DF][}):]. */
1923 if (! (p[0] == '@'
1924 || ((p[0] == '(' || p[0] == '{') && (++p)[0] == '@'
1925 && (((++p)[0] == ')' || p[0] == '}' || p[0] == ':')
1926 || ((p[1] == ')' || p[1] == '}' || p[1] == ':')
1927 && (p[0] == 'D' || p[0] == 'F'))))))
1928 continue;
1930 /* Found one. Compute the length and string ptr. Move p
1931 past the variable reference. */
1932 switch (p[0])
1934 case 'D':
1935 atlen = dlen;
1936 at = name;
1937 p += 2;
1938 break;
1940 case 'F':
1941 atlen = flen;
1942 at = fnp;
1943 p += 2;
1944 break;
1946 default:
1947 atlen = tlen;
1948 at = name;
1949 ++p;
1950 break;
1953 /* Get more space. */
1955 int soff = s - d->name;
1956 int poff = p - d->name;
1957 d->name = (char *) xrealloc (d->name,
1958 strlen (d->name) + atlen + 1);
1959 s = d->name + soff;
1960 p = d->name + poff;
1963 /* Copy the string over. */
1964 bcopy(p, s+atlen, strlen (p)+1);
1965 bcopy(at, s, atlen);
1966 p = s + atlen - 1;
1970 if (!two_colon)
1972 /* Single-colon. Combine these dependencies
1973 with others in file's existing record, if any. */
1974 f = enter_file (name);
1976 if (f->double_colon)
1977 fatal (flocp,
1978 _("target file `%s' has both : and :: entries"), f->name);
1980 /* If CMDS == F->CMDS, this target was listed in this rule
1981 more than once. Just give a warning since this is harmless. */
1982 if (cmds != 0 && cmds == f->cmds)
1983 error (flocp,
1984 _("target `%s' given more than once in the same rule."),
1985 f->name);
1987 /* Check for two single-colon entries both with commands.
1988 Check is_target so that we don't lose on files such as .c.o
1989 whose commands were preinitialized. */
1990 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1992 error (&cmds->fileinfo,
1993 _("warning: overriding commands for target `%s'"),
1994 f->name);
1995 error (&f->cmds->fileinfo,
1996 _("warning: ignoring old commands for target `%s'"),
1997 f->name);
2000 f->is_target = 1;
2002 /* Defining .DEFAULT with no deps or cmds clears it. */
2003 if (f == default_file && this == 0 && cmds == 0)
2004 f->cmds = 0;
2005 if (cmds != 0)
2006 f->cmds = cmds;
2007 /* Defining .SUFFIXES with no dependencies
2008 clears out the list of suffixes. */
2009 if (f == suffix_file && this == 0)
2011 d = f->deps;
2012 while (d != 0)
2014 struct dep *nextd = d->next;
2015 free (d->name);
2016 free ((char *)d);
2017 d = nextd;
2019 f->deps = 0;
2021 else if (f->deps != 0)
2023 /* Add the file's old deps and the new ones in THIS together. */
2025 struct dep *firstdeps, *moredeps;
2026 if (cmds != 0)
2028 /* This is the rule with commands, so put its deps first.
2029 The rationale behind this is that $< expands to the
2030 first dep in the chain, and commands use $< expecting
2031 to get the dep that rule specifies. */
2032 firstdeps = this;
2033 moredeps = f->deps;
2035 else
2037 /* Append the new deps to the old ones. */
2038 firstdeps = f->deps;
2039 moredeps = this;
2042 if (firstdeps == 0)
2043 firstdeps = moredeps;
2044 else
2046 d = firstdeps;
2047 while (d->next != 0)
2048 d = d->next;
2049 d->next = moredeps;
2052 f->deps = firstdeps;
2054 else
2055 f->deps = this;
2057 /* If this is a static pattern rule, set the file's stem to
2058 the part of its name that matched the `%' in the pattern,
2059 so you can use $* in the commands. */
2060 if (pattern != 0)
2062 static char *percent = "%";
2063 char *buffer = variable_expand ("");
2064 char *o = patsubst_expand (buffer, name, pattern, percent,
2065 pattern_percent, percent);
2066 f->stem = savestring (buffer, o - buffer);
2069 else
2071 /* Double-colon. Make a new record
2072 even if the file already has one. */
2073 f = lookup_file (name);
2074 /* Check for both : and :: rules. Check is_target so
2075 we don't lose on default suffix rules or makefiles. */
2076 if (f != 0 && f->is_target && !f->double_colon)
2077 fatal (flocp,
2078 _("target file `%s' has both : and :: entries"), f->name);
2079 f = enter_file (name);
2080 /* If there was an existing entry and it was a double-colon
2081 entry, enter_file will have returned a new one, making it the
2082 prev pointer of the old one, and setting its double_colon
2083 pointer to the first one. */
2084 if (f->double_colon == 0)
2085 /* This is the first entry for this name, so we must
2086 set its double_colon pointer to itself. */
2087 f->double_colon = f;
2088 f->is_target = 1;
2089 f->deps = this;
2090 f->cmds = cmds;
2093 /* Free name if not needed further. */
2094 if (f != 0 && name != f->name
2095 && (name < f->name || name > f->name + strlen (f->name)))
2097 free (name);
2098 name = f->name;
2101 /* See if this is first target seen whose name does
2102 not start with a `.', unless it contains a slash. */
2103 if (default_goal_file == 0 && set_default
2104 && (*name != '.' || strchr (name, '/') != 0
2105 #ifdef HAVE_DOS_PATHS
2106 || strchr (name, '\\') != 0
2107 #endif
2110 int reject = 0;
2112 /* If this file is a suffix, don't
2113 let it be the default goal file. */
2115 for (d = suffix_file->deps; d != 0; d = d->next)
2117 register struct dep *d2;
2118 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
2120 reject = 1;
2121 break;
2123 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
2125 register unsigned int len = strlen (dep_name (d2));
2126 if (!strneq (name, dep_name (d2), len))
2127 continue;
2128 if (streq (name + len, dep_name (d)))
2130 reject = 1;
2131 break;
2134 if (reject)
2135 break;
2138 if (!reject)
2139 default_goal_file = f;
2143 if (implicit)
2145 targets[target_idx] = 0;
2146 target_percents[target_idx] = 0;
2147 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2148 free ((char *) target_percents);
2152 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2153 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2154 Quoting backslashes are removed from STRING by compacting it into
2155 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2156 one, or nil if there are none. */
2158 char *
2159 find_char_unquote (string, stop1, stop2, blank)
2160 char *string;
2161 int stop1;
2162 int stop2;
2163 int blank;
2165 unsigned int string_len = 0;
2166 register char *p = string;
2168 while (1)
2170 if (stop2 && blank)
2171 while (*p != '\0' && *p != stop1 && *p != stop2
2172 && ! isblank ((unsigned char) *p))
2173 ++p;
2174 else if (stop2)
2175 while (*p != '\0' && *p != stop1 && *p != stop2)
2176 ++p;
2177 else if (blank)
2178 while (*p != '\0' && *p != stop1
2179 && ! isblank ((unsigned char) *p))
2180 ++p;
2181 else
2182 while (*p != '\0' && *p != stop1)
2183 ++p;
2185 if (*p == '\0')
2186 break;
2188 if (p > string && p[-1] == '\\')
2190 /* Search for more backslashes. */
2191 register int i = -2;
2192 while (&p[i] >= string && p[i] == '\\')
2193 --i;
2194 ++i;
2195 /* Only compute the length if really needed. */
2196 if (string_len == 0)
2197 string_len = strlen (string);
2198 /* The number of backslashes is now -I.
2199 Copy P over itself to swallow half of them. */
2200 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2201 p += i / 2;
2202 if (i % 2 == 0)
2203 /* All the backslashes quoted each other; the STOPCHAR was
2204 unquoted. */
2205 return p;
2207 /* The STOPCHAR was quoted by a backslash. Look for another. */
2209 else
2210 /* No backslash in sight. */
2211 return p;
2214 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2215 return 0;
2218 /* Search PATTERN for an unquoted %. */
2220 char *
2221 find_percent (pattern)
2222 char *pattern;
2224 return find_char_unquote (pattern, '%', 0, 0);
2227 /* Parse a string into a sequence of filenames represented as a
2228 chain of struct nameseq's in reverse order and return that chain.
2230 The string is passed as STRINGP, the address of a string pointer.
2231 The string pointer is updated to point at the first character
2232 not parsed, which either is a null char or equals STOPCHAR.
2234 SIZE is how big to construct chain elements.
2235 This is useful if we want them actually to be other structures
2236 that have room for additional info.
2238 If STRIP is nonzero, strip `./'s off the beginning. */
2240 struct nameseq *
2241 parse_file_seq (stringp, stopchar, size, strip)
2242 char **stringp;
2243 int stopchar;
2244 unsigned int size;
2245 int strip;
2247 register struct nameseq *new = 0;
2248 register struct nameseq *new1, *lastnew1;
2249 register char *p = *stringp;
2250 char *q;
2251 char *name;
2253 #ifdef VMS
2254 # define VMS_COMMA ','
2255 #else
2256 # define VMS_COMMA 0
2257 #endif
2259 while (1)
2261 /* Skip whitespace; see if any more names are left. */
2262 p = next_token (p);
2263 if (*p == '\0')
2264 break;
2265 if (*p == stopchar)
2266 break;
2268 /* Yes, find end of next name. */
2269 q = p;
2270 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2271 #ifdef VMS
2272 /* convert comma separated list to space separated */
2273 if (p && *p == ',')
2274 *p =' ';
2275 #endif
2276 #ifdef _AMIGA
2277 if (stopchar == ':' && p && *p == ':'
2278 && !(isspace ((unsigned char)p[1]) || !p[1]
2279 || isspace ((unsigned char)p[-1])))
2281 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2283 #endif
2284 #ifdef HAVE_DOS_PATHS
2285 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2286 first colon which isn't followed by a slash or a backslash.
2287 Note that tokens separated by spaces should be treated as separate
2288 tokens since make doesn't allow path names with spaces */
2289 if (stopchar == ':')
2290 while (p != 0 && !isspace ((unsigned char)*p) &&
2291 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2292 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2293 #endif
2294 if (p == 0)
2295 p = q + strlen (q);
2297 if (strip)
2298 #ifdef VMS
2299 /* Skip leading `[]'s. */
2300 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2301 #else
2302 /* Skip leading `./'s. */
2303 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2304 #endif
2306 q += 2; /* Skip "./". */
2307 while (q < p && *q == '/')
2308 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2309 ++q;
2312 /* Extract the filename just found, and skip it. */
2314 if (q == p)
2315 /* ".///" was stripped to "". */
2316 #ifdef VMS
2317 continue;
2318 #else
2319 #ifdef _AMIGA
2320 name = savestring ("", 0);
2321 #else
2322 name = savestring ("./", 2);
2323 #endif
2324 #endif
2325 else
2326 #ifdef VMS
2327 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2328 * to remove this '\' before we can use the filename.
2329 * Savestring called because q may be read-only string constant.
2332 char *qbase = xstrdup (q);
2333 char *pbase = qbase + (p-q);
2334 char *q1 = qbase;
2335 char *q2 = q1;
2336 char *p1 = pbase;
2338 while (q1 != pbase)
2340 if (*q1 == '\\' && *(q1+1) == ':')
2342 q1++;
2343 p1--;
2345 *q2++ = *q1++;
2347 name = savestring (qbase, p1 - qbase);
2348 free (qbase);
2350 #else
2351 name = savestring (q, p - q);
2352 #endif
2354 /* Add it to the front of the chain. */
2355 new1 = (struct nameseq *) xmalloc (size);
2356 new1->name = name;
2357 new1->next = new;
2358 new = new1;
2361 #ifndef NO_ARCHIVES
2363 /* Look for multi-word archive references.
2364 They are indicated by a elt ending with an unmatched `)' and
2365 an elt further down the chain (i.e., previous in the file list)
2366 with an unmatched `(' (e.g., "lib(mem"). */
2368 new1 = new;
2369 lastnew1 = 0;
2370 while (new1 != 0)
2371 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2372 && new1->name[strlen (new1->name) - 1] == ')'
2373 && strchr (new1->name, '(') == 0)
2375 /* NEW1 ends with a `)' but does not contain a `('.
2376 Look back for an elt with an opening `(' but no closing `)'. */
2378 struct nameseq *n = new1->next, *lastn = new1;
2379 char *paren = 0;
2380 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2382 lastn = n;
2383 n = n->next;
2385 if (n != 0
2386 /* Ignore something starting with `(', as that cannot actually
2387 be an archive-member reference (and treating it as such
2388 results in an empty file name, which causes much lossage). */
2389 && n->name[0] != '(')
2391 /* N is the first element in the archive group.
2392 Its name looks like "lib(mem" (with no closing `)'). */
2394 char *libname;
2396 /* Copy "lib(" into LIBNAME. */
2397 ++paren;
2398 libname = (char *) alloca (paren - n->name + 1);
2399 bcopy (n->name, libname, paren - n->name);
2400 libname[paren - n->name] = '\0';
2402 if (*paren == '\0')
2404 /* N was just "lib(", part of something like "lib( a b)".
2405 Edit it out of the chain and free its storage. */
2406 lastn->next = n->next;
2407 free (n->name);
2408 free ((char *) n);
2409 /* LASTN->next is the new stopping elt for the loop below. */
2410 n = lastn->next;
2412 else
2414 /* Replace N's name with the full archive reference. */
2415 name = concat (libname, paren, ")");
2416 free (n->name);
2417 n->name = name;
2420 if (new1->name[1] == '\0')
2422 /* NEW1 is just ")", part of something like "lib(a b )".
2423 Omit it from the chain and free its storage. */
2424 if (lastnew1 == 0)
2425 new = new1->next;
2426 else
2427 lastnew1->next = new1->next;
2428 lastn = new1;
2429 new1 = new1->next;
2430 free (lastn->name);
2431 free ((char *) lastn);
2433 else
2435 /* Replace also NEW1->name, which already has closing `)'. */
2436 name = concat (libname, new1->name, "");
2437 free (new1->name);
2438 new1->name = name;
2439 new1 = new1->next;
2442 /* Trace back from NEW1 (the end of the list) until N
2443 (the beginning of the list), rewriting each name
2444 with the full archive reference. */
2446 while (new1 != n)
2448 name = concat (libname, new1->name, ")");
2449 free (new1->name);
2450 new1->name = name;
2451 lastnew1 = new1;
2452 new1 = new1->next;
2455 else
2457 /* No frobnication happening. Just step down the list. */
2458 lastnew1 = new1;
2459 new1 = new1->next;
2462 else
2464 lastnew1 = new1;
2465 new1 = new1->next;
2468 #endif
2470 *stringp = p;
2471 return new;
2474 /* Find the next line of text in an eval buffer, combining continuation lines
2475 into one line.
2476 Return the number of actual lines read (> 1 if continuation lines).
2477 Returns -1 if there's nothing left in the buffer.
2479 After this function, ebuf->buffer points to the first character of the
2480 line we just found.
2483 /* Read a line of text from a STRING.
2484 Since we aren't really reading from a file, don't bother with linenumbers.
2487 static unsigned long
2488 readstring (ebuf)
2489 struct ebuffer *ebuf;
2491 char *p;
2493 /* If there is nothing left in this buffer, return 0. */
2494 if (ebuf->bufnext > ebuf->bufstart + ebuf->size)
2495 return -1;
2497 /* Set up a new starting point for the buffer, and find the end of the
2498 next logical line (taking into account backslash/newline pairs). */
2500 p = ebuf->buffer = ebuf->bufnext;
2502 while (1)
2504 int backslash = 0;
2506 /* Find the next newline. Keep track of backslashes as we look. */
2507 for (; *p != '\n' && *p != '\0'; ++p)
2508 if (*p == '\\')
2509 backslash = !backslash;
2511 /* If we got to the end of the string or a newline with no backslash,
2512 we're done. */
2513 if (*p == '\0' || !backslash)
2514 break;
2517 /* Overwrite the newline char. */
2518 *p = '\0';
2519 ebuf->bufnext = p+1;
2521 return 0;
2524 static long
2525 readline (ebuf)
2526 struct ebuffer *ebuf;
2528 char *p;
2529 char *end;
2530 char *start;
2531 long nlines = 0;
2533 /* The behaviors between string and stream buffers are different enough to
2534 warrant different functions. Do the Right Thing. */
2536 if (!ebuf->fp)
2537 return readstring (ebuf);
2539 /* When reading from a file, we always start over at the beginning of the
2540 buffer for each new line. */
2542 p = start = ebuf->bufstart;
2543 end = p + ebuf->size;
2544 *p = '\0';
2546 while (fgets (p, end - p, ebuf->fp) != 0)
2548 char *p2;
2549 unsigned long len;
2550 int backslash;
2552 len = strlen (p);
2553 if (len == 0)
2555 /* This only happens when the first thing on the line is a '\0'.
2556 It is a pretty hopeless case, but (wonder of wonders) Athena
2557 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2558 There is nothing really to be done; we synthesize a newline so
2559 the following line doesn't appear to be part of this line. */
2560 error (&ebuf->floc,
2561 _("warning: NUL character seen; rest of line ignored"));
2562 p[0] = '\n';
2563 len = 1;
2566 /* Jump past the text we just read. */
2567 p += len;
2569 /* If the last char isn't a newline, the whole line didn't fit into the
2570 buffer. Get some more buffer and try again. */
2571 if (p[-1] != '\n')
2572 goto more_buffer;
2574 /* We got a newline, so add one to the count of lines. */
2575 ++nlines;
2577 #if !defined(WINDOWS32) && !defined(__MSDOS__)
2578 /* Check to see if the line was really ended with CRLF; if so ignore
2579 the CR. */
2580 if ((p - start) > 1 && p[-2] == '\r')
2582 --p;
2583 p[-1] = '\n';
2585 #endif
2587 backslash = 0;
2588 for (p2 = p - 2; p2 >= start; --p2)
2590 if (*p2 != '\\')
2591 break;
2592 backslash = !backslash;
2595 if (!backslash)
2597 p[-1] = '\0';
2598 break;
2601 /* It was a backslash/newline combo. If we have more space, read
2602 another line. */
2603 if (end - p >= 80)
2604 continue;
2606 /* We need more space at the end of our buffer, so realloc it.
2607 Make sure to preserve the current offset of p. */
2608 more_buffer:
2610 unsigned long off = p - start;
2611 ebuf->size *= 2;
2612 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2613 ebuf->size);
2614 p = start + off;
2615 end = start + ebuf->size;
2616 *p = '\0';
2620 if (ferror (ebuf->fp))
2621 pfatal_with_name (ebuf->floc.filenm);
2623 /* If we found some lines, return how many.
2624 If we didn't, but we did find _something_, that indicates we read the last
2625 line of a file with no final newline; return 1.
2626 If we read nothing, we're at EOF; return -1. */
2628 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2631 /* Parse the next "makefile word" from the input buffer, and return info
2632 about it.
2634 A "makefile word" is one of:
2636 w_bogus Should never happen
2637 w_eol End of input
2638 w_static A static word; cannot be expanded
2639 w_variable A word containing one or more variables/functions
2640 w_colon A colon
2641 w_dcolon A double-colon
2642 w_semicolon A semicolon
2643 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2645 Note that this function is only used when reading certain parts of the
2646 makefile. Don't use it where special rules hold sway (RHS of a variable,
2647 in a command list, etc.) */
2649 static enum make_word_type
2650 get_next_mword (buffer, delim, startp, length)
2651 char *buffer;
2652 char *delim;
2653 char **startp;
2654 unsigned int *length;
2656 enum make_word_type wtype = w_bogus;
2657 char *p = buffer, *beg;
2658 char c;
2660 /* Skip any leading whitespace. */
2661 while (isblank ((unsigned char)*p))
2662 ++p;
2664 beg = p;
2665 c = *(p++);
2666 switch (c)
2668 case '\0':
2669 wtype = w_eol;
2670 break;
2672 case ';':
2673 wtype = w_semicolon;
2674 break;
2676 case '=':
2677 wtype = w_varassign;
2678 break;
2680 case ':':
2681 wtype = w_colon;
2682 switch (*p)
2684 case ':':
2685 ++p;
2686 wtype = w_dcolon;
2687 break;
2689 case '=':
2690 ++p;
2691 wtype = w_varassign;
2692 break;
2694 break;
2696 case '+':
2697 case '?':
2698 if (*p == '=')
2700 ++p;
2701 wtype = w_varassign;
2702 break;
2705 default:
2706 if (delim && strchr (delim, c))
2707 wtype = w_static;
2708 break;
2711 /* Did we find something? If so, return now. */
2712 if (wtype != w_bogus)
2713 goto done;
2715 /* This is some non-operator word. A word consists of the longest
2716 string of characters that doesn't contain whitespace, one of [:=#],
2717 or [?+]=, or one of the chars in the DELIM string. */
2719 /* We start out assuming a static word; if we see a variable we'll
2720 adjust our assumptions then. */
2721 wtype = w_static;
2723 /* We already found the first value of "c", above. */
2724 while (1)
2726 char closeparen;
2727 int count;
2729 switch (c)
2731 case '\0':
2732 case ' ':
2733 case '\t':
2734 case '=':
2735 goto done_word;
2737 case ':':
2738 #ifdef HAVE_DOS_PATHS
2739 /* A word CAN include a colon in its drive spec. The drive
2740 spec is allowed either at the beginning of a word, or as part
2741 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2742 if (!(p - beg >= 2
2743 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2744 && (p - beg == 2 || p[-3] == '(')))
2745 #endif
2746 goto done_word;
2748 case '$':
2749 c = *(p++);
2750 if (c == '$')
2751 break;
2753 /* This is a variable reference, so note that it's expandable.
2754 Then read it to the matching close paren. */
2755 wtype = w_variable;
2757 if (c == '(')
2758 closeparen = ')';
2759 else if (c == '{')
2760 closeparen = '}';
2761 else
2762 /* This is a single-letter variable reference. */
2763 break;
2765 for (count=0; *p != '\0'; ++p)
2767 if (*p == c)
2768 ++count;
2769 else if (*p == closeparen && --count < 0)
2771 ++p;
2772 break;
2775 break;
2777 case '?':
2778 case '+':
2779 if (*p == '=')
2780 goto done_word;
2781 break;
2783 case '\\':
2784 switch (*p)
2786 case ':':
2787 case ';':
2788 case '=':
2789 case '\\':
2790 ++p;
2791 break;
2793 break;
2795 default:
2796 if (delim && strchr (delim, c))
2797 goto done_word;
2798 break;
2801 c = *(p++);
2803 done_word:
2804 --p;
2806 done:
2807 if (startp)
2808 *startp = beg;
2809 if (length)
2810 *length = p - beg;
2811 return wtype;
2814 /* Construct the list of include directories
2815 from the arguments and the default list. */
2817 void
2818 construct_include_path (arg_dirs)
2819 char **arg_dirs;
2821 register unsigned int i;
2822 #ifdef VAXC /* just don't ask ... */
2823 stat_t stbuf;
2824 #else
2825 struct stat stbuf;
2826 #endif
2827 /* Table to hold the dirs. */
2829 register unsigned int defsize = (sizeof (default_include_directories)
2830 / sizeof (default_include_directories[0]));
2831 register unsigned int max = 5;
2832 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2833 register unsigned int idx = 0;
2835 #ifdef __MSDOS__
2836 defsize++;
2837 #endif
2839 /* First consider any dirs specified with -I switches.
2840 Ignore dirs that don't exist. */
2842 if (arg_dirs != 0)
2843 while (*arg_dirs != 0)
2845 char *dir = *arg_dirs++;
2847 if (dir[0] == '~')
2849 char *expanded = tilde_expand (dir);
2850 if (expanded != 0)
2851 dir = expanded;
2854 if (stat (dir, &stbuf) == 0 && S_ISDIR (stbuf.st_mode))
2856 if (idx == max - 1)
2858 max += 5;
2859 dirs = (char **)
2860 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2862 dirs[idx++] = dir;
2864 else if (dir != arg_dirs[-1])
2865 free (dir);
2868 /* Now add at the end the standard default dirs. */
2870 #ifdef __MSDOS__
2872 /* The environment variable $DJDIR holds the root of the
2873 DJGPP directory tree; add ${DJDIR}/include. */
2874 struct variable *djdir = lookup_variable ("DJDIR", 5);
2876 if (djdir)
2878 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2880 strcat (strcpy (defdir, djdir->value), "/include");
2881 dirs[idx++] = defdir;
2884 #endif
2886 for (i = 0; default_include_directories[i] != 0; ++i)
2887 if (stat (default_include_directories[i], &stbuf) == 0
2888 && S_ISDIR (stbuf.st_mode))
2889 dirs[idx++] = default_include_directories[i];
2891 dirs[idx] = 0;
2893 /* Now compute the maximum length of any name in it. */
2895 max_incl_len = 0;
2896 for (i = 0; i < idx; ++i)
2898 unsigned int len = strlen (dirs[i]);
2899 /* If dir name is written with a trailing slash, discard it. */
2900 if (dirs[i][len - 1] == '/')
2901 /* We can't just clobber a null in because it may have come from
2902 a literal string and literal strings may not be writable. */
2903 dirs[i] = savestring (dirs[i], len - 1);
2904 if (len > max_incl_len)
2905 max_incl_len = len;
2908 include_directories = dirs;
2911 /* Expand ~ or ~USER at the beginning of NAME.
2912 Return a newly malloc'd string or 0. */
2914 char *
2915 tilde_expand (name)
2916 char *name;
2918 #ifndef VMS
2919 if (name[1] == '/' || name[1] == '\0')
2921 extern char *getenv ();
2922 char *home_dir;
2923 int is_variable;
2926 /* Turn off --warn-undefined-variables while we expand HOME. */
2927 int save = warn_undefined_variables_flag;
2928 warn_undefined_variables_flag = 0;
2930 home_dir = allocated_variable_expand ("$(HOME)");
2932 warn_undefined_variables_flag = save;
2935 is_variable = home_dir[0] != '\0';
2936 if (!is_variable)
2938 free (home_dir);
2939 home_dir = getenv ("HOME");
2941 #if !defined(_AMIGA) && !defined(WINDOWS32)
2942 if (home_dir == 0 || home_dir[0] == '\0')
2944 extern char *getlogin ();
2945 char *logname = getlogin ();
2946 home_dir = 0;
2947 if (logname != 0)
2949 struct passwd *p = getpwnam (logname);
2950 if (p != 0)
2951 home_dir = p->pw_dir;
2954 #endif /* !AMIGA && !WINDOWS32 */
2955 if (home_dir != 0)
2957 char *new = concat (home_dir, "", name + 1);
2958 if (is_variable)
2959 free (home_dir);
2960 return new;
2963 #if !defined(_AMIGA) && !defined(WINDOWS32)
2964 else
2966 struct passwd *pwent;
2967 char *userend = strchr (name + 1, '/');
2968 if (userend != 0)
2969 *userend = '\0';
2970 pwent = getpwnam (name + 1);
2971 if (pwent != 0)
2973 if (userend == 0)
2974 return xstrdup (pwent->pw_dir);
2975 else
2976 return concat (pwent->pw_dir, "/", userend + 1);
2978 else if (userend != 0)
2979 *userend = '/';
2981 #endif /* !AMIGA && !WINDOWS32 */
2982 #endif /* !VMS */
2983 return 0;
2986 /* Given a chain of struct nameseq's describing a sequence of filenames,
2987 in reverse of the intended order, return a new chain describing the
2988 result of globbing the filenames. The new chain is in forward order.
2989 The links of the old chain are freed or used in the new chain.
2990 Likewise for the names in the old chain.
2992 SIZE is how big to construct chain elements.
2993 This is useful if we want them actually to be other structures
2994 that have room for additional info. */
2996 struct nameseq *
2997 multi_glob (chain, size)
2998 struct nameseq *chain;
2999 unsigned int size;
3001 extern void dir_setup_glob ();
3002 register struct nameseq *new = 0;
3003 register struct nameseq *old;
3004 struct nameseq *nexto;
3005 glob_t gl;
3007 dir_setup_glob (&gl);
3009 for (old = chain; old != 0; old = nexto)
3011 #ifndef NO_ARCHIVES
3012 char *memname;
3013 #endif
3015 nexto = old->next;
3017 if (old->name[0] == '~')
3019 char *newname = tilde_expand (old->name);
3020 if (newname != 0)
3022 free (old->name);
3023 old->name = newname;
3027 #ifndef NO_ARCHIVES
3028 if (ar_name (old->name))
3030 /* OLD->name is an archive member reference.
3031 Replace it with the archive file name,
3032 and save the member name in MEMNAME.
3033 We will glob on the archive name and then
3034 reattach MEMNAME later. */
3035 char *arname;
3036 ar_parse_name (old->name, &arname, &memname);
3037 free (old->name);
3038 old->name = arname;
3040 else
3041 memname = 0;
3042 #endif /* !NO_ARCHIVES */
3044 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3046 case 0: /* Success. */
3048 register int i = gl.gl_pathc;
3049 while (i-- > 0)
3051 #ifndef NO_ARCHIVES
3052 if (memname != 0)
3054 /* Try to glob on MEMNAME within the archive. */
3055 struct nameseq *found
3056 = ar_glob (gl.gl_pathv[i], memname, size);
3057 if (found == 0)
3059 /* No matches. Use MEMNAME as-is. */
3060 unsigned int alen = strlen (gl.gl_pathv[i]);
3061 unsigned int mlen = strlen (memname);
3062 struct nameseq *elt
3063 = (struct nameseq *) xmalloc (size);
3064 if (size > sizeof (struct nameseq))
3065 bzero (((char *) elt) + sizeof (struct nameseq),
3066 size - sizeof (struct nameseq));
3067 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3068 bcopy (gl.gl_pathv[i], elt->name, alen);
3069 elt->name[alen] = '(';
3070 bcopy (memname, &elt->name[alen + 1], mlen);
3071 elt->name[alen + 1 + mlen] = ')';
3072 elt->name[alen + 1 + mlen + 1] = '\0';
3073 elt->next = new;
3074 new = elt;
3076 else
3078 /* Find the end of the FOUND chain. */
3079 struct nameseq *f = found;
3080 while (f->next != 0)
3081 f = f->next;
3083 /* Attach the chain being built to the end of the FOUND
3084 chain, and make FOUND the new NEW chain. */
3085 f->next = new;
3086 new = found;
3089 free (memname);
3091 else
3092 #endif /* !NO_ARCHIVES */
3094 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3095 if (size > sizeof (struct nameseq))
3096 bzero (((char *) elt) + sizeof (struct nameseq),
3097 size - sizeof (struct nameseq));
3098 elt->name = xstrdup (gl.gl_pathv[i]);
3099 elt->next = new;
3100 new = elt;
3103 globfree (&gl);
3104 free (old->name);
3105 free ((char *)old);
3106 break;
3109 case GLOB_NOSPACE:
3110 fatal (NILF, _("virtual memory exhausted"));
3111 break;
3113 default:
3114 old->next = new;
3115 new = old;
3116 break;
3120 return new;