glob/glob.c [__GNU_LIBRARY__ && __DJGPP__]: Add a realloc declaration
[make.git] / read.c
blob5287de8742376d310ddf8ba6db8b7b90bbaa6a39
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include <glob.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
35 #ifndef WINDOWS32
36 #ifndef _AMIGA
37 #ifndef VMS
38 #include <pwd.h>
39 #else
40 struct passwd *getpwnam (char *name);
41 #endif
42 #endif
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46 eval'ing.
49 struct ebuffer
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 unsigned int size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 struct floc floc; /* Info on the file in fp (if any). */
59 /* Types of "words" that can be read in a makefile. */
60 enum make_word_type
62 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
63 w_varassign
67 /* A `struct conditionals' contains the information describing
68 all the active conditionals in a makefile.
70 The global variable `conditionals' contains the conditionals
71 information for the current makefile. It is initialized from
72 the static structure `toplevel_conditionals' and is later changed
73 to new structures for included makefiles. */
75 struct conditionals
77 unsigned int if_cmds; /* Depth of conditional nesting. */
78 unsigned int allocated; /* Elts allocated in following arrays. */
79 char *ignoring; /* Are we ignoring or interpreting?
80 0=interpreting, 1=not yet interpreted,
81 2=already interpreted */
82 char *seen_else; /* Have we already seen an `else'? */
85 static struct conditionals toplevel_conditionals;
86 static struct conditionals *conditionals = &toplevel_conditionals;
89 /* Default directories to search for include files in */
91 static const char *default_include_directories[] =
93 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
94 /* This completely up to the user when they install MSVC or other packages.
95 This is defined as a placeholder. */
96 # define INCLUDEDIR "."
97 #endif
98 INCLUDEDIR,
99 #ifndef _AMIGA
100 "/usr/gnu/include",
101 "/usr/local/include",
102 "/usr/include",
103 #endif
107 /* List of directories to search for include files in */
109 static const char **include_directories;
111 /* Maximum length of an element of the above. */
113 static unsigned int max_incl_len;
115 /* The filename and pointer to line number of the
116 makefile currently being read in. */
118 const struct floc *reading_file = 0;
120 /* The chain of makefiles read by read_makefile. */
122 static struct dep *read_makefiles = 0;
124 static int eval_makefile (const char *filename, int flags);
125 static int eval (struct ebuffer *buffer, int flags);
127 static long readline (struct ebuffer *ebuf);
128 static void do_define (char *name, unsigned int namelen,
129 enum variable_origin origin, struct ebuffer *ebuf);
130 static int conditional_line (char *line, int len, const struct floc *flocp);
131 static void record_files (struct nameseq *filenames, const char *pattern,
132 const char *pattern_percent, struct dep *deps,
133 unsigned int cmds_started, char *commands,
134 unsigned int commands_idx, int two_colon,
135 const struct floc *flocp);
136 static void record_target_var (struct nameseq *filenames, char *defn,
137 enum variable_origin origin, int enabled,
138 const struct floc *flocp);
139 static enum make_word_type get_next_mword (char *buffer, char *delim,
140 char **startp, unsigned int *length);
141 static void remove_comments (char *line);
142 static char *find_char_unquote (char *string, int stop1, int stop2,
143 int blank, int ignorevars);
145 /* Read in all the makefiles and return the chain of their names. */
147 struct dep *
148 read_all_makefiles (const char **makefiles)
150 unsigned int num_makefiles = 0;
152 /* Create *_LIST variables, to hold the makefiles, targets, and variables
153 we will be reading. */
155 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
157 DB (DB_BASIC, (_("Reading makefiles...\n")));
159 /* If there's a non-null variable MAKEFILES, its value is a list of
160 files to read first thing. But don't let it prevent reading the
161 default makefiles and don't let the default goal come from there. */
164 char *value;
165 char *name, *p;
166 unsigned int length;
169 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
170 int save = warn_undefined_variables_flag;
171 warn_undefined_variables_flag = 0;
173 value = allocated_variable_expand ("$(MAKEFILES)");
175 warn_undefined_variables_flag = save;
178 /* Set NAME to the start of next token and LENGTH to its length.
179 MAKEFILES is updated for finding remaining tokens. */
180 p = value;
182 while ((name = find_next_token ((const char **)&p, &length)) != 0)
184 if (*p != '\0')
185 *p++ = '\0';
186 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
189 free (value);
192 /* Read makefiles specified with -f switches. */
194 if (makefiles != 0)
195 while (*makefiles != 0)
197 struct dep *tail = read_makefiles;
198 register struct dep *d;
200 if (! eval_makefile (*makefiles, 0))
201 perror_with_name ("", *makefiles);
203 /* Find the right element of read_makefiles. */
204 d = read_makefiles;
205 while (d->next != tail)
206 d = d->next;
208 /* Use the storage read_makefile allocates. */
209 *makefiles = dep_name (d);
210 ++num_makefiles;
211 ++makefiles;
214 /* If there were no -f switches, try the default names. */
216 if (num_makefiles == 0)
218 static char *default_makefiles[] =
219 #ifdef VMS
220 /* all lower case since readdir() (the vms version) 'lowercasifies' */
221 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
222 #else
223 #ifdef _AMIGA
224 { "GNUmakefile", "Makefile", "SMakefile", 0 };
225 #else /* !Amiga && !VMS */
226 { "GNUmakefile", "makefile", "Makefile", 0 };
227 #endif /* AMIGA */
228 #endif /* VMS */
229 register char **p = default_makefiles;
230 while (*p != 0 && !file_exists_p (*p))
231 ++p;
233 if (*p != 0)
235 if (! eval_makefile (*p, 0))
236 perror_with_name ("", *p);
238 else
240 /* No default makefile was found. Add the default makefiles to the
241 `read_makefiles' chain so they will be updated if possible. */
242 struct dep *tail = read_makefiles;
243 /* Add them to the tail, after any MAKEFILES variable makefiles. */
244 while (tail != 0 && tail->next != 0)
245 tail = tail->next;
246 for (p = default_makefiles; *p != 0; ++p)
248 struct dep *d = alloc_dep ();
249 d->file = enter_file (strcache_add (*p));
250 d->file->dontcare = 1;
251 /* Tell update_goal_chain to bail out as soon as this file is
252 made, and main not to die if we can't make this file. */
253 d->changed = RM_DONTCARE;
254 if (tail == 0)
255 read_makefiles = d;
256 else
257 tail->next = d;
258 tail = d;
260 if (tail != 0)
261 tail->next = 0;
265 return read_makefiles;
268 /* Install a new conditional and return the previous one. */
270 static struct conditionals *
271 install_conditionals (struct conditionals *new)
273 struct conditionals *save = conditionals;
275 memset (new, '\0', sizeof (*new));
276 conditionals = new;
278 return save;
281 /* Free the current conditionals and reinstate a saved one. */
283 static void
284 restore_conditionals (struct conditionals *saved)
286 /* Free any space allocated by conditional_line. */
287 if (conditionals->ignoring)
288 free (conditionals->ignoring);
289 if (conditionals->seen_else)
290 free (conditionals->seen_else);
292 /* Restore state. */
293 conditionals = saved;
296 static int
297 eval_makefile (const char *filename, int flags)
299 struct dep *deps;
300 struct ebuffer ebuf;
301 const struct floc *curfile;
302 char *expanded = 0;
303 int makefile_errno;
304 int r;
306 filename = strcache_add (filename);
307 ebuf.floc.filenm = filename;
308 ebuf.floc.lineno = 1;
310 if (ISDB (DB_VERBOSE))
312 printf (_("Reading makefile `%s'"), filename);
313 if (flags & RM_NO_DEFAULT_GOAL)
314 printf (_(" (no default goal)"));
315 if (flags & RM_INCLUDED)
316 printf (_(" (search path)"));
317 if (flags & RM_DONTCARE)
318 printf (_(" (don't care)"));
319 if (flags & RM_NO_TILDE)
320 printf (_(" (no ~ expansion)"));
321 puts ("...");
324 /* First, get a stream to read. */
326 /* Expand ~ in FILENAME unless it came from `include',
327 in which case it was already done. */
328 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
330 expanded = tilde_expand (filename);
331 if (expanded != 0)
332 filename = expanded;
335 ebuf.fp = fopen (filename, "r");
336 /* Save the error code so we print the right message later. */
337 makefile_errno = errno;
339 /* If the makefile wasn't found and it's either a makefile from
340 the `MAKEFILES' variable or an included makefile,
341 search the included makefile search path for this makefile. */
342 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
344 unsigned int i;
345 for (i = 0; include_directories[i] != 0; ++i)
347 const char *included = concat (include_directories[i], "/", filename);
348 ebuf.fp = fopen (included, "r");
349 if (ebuf.fp)
351 filename = strcache_add (included);
352 break;
357 /* Add FILENAME to the chain of read makefiles. */
358 deps = alloc_dep ();
359 deps->next = read_makefiles;
360 read_makefiles = deps;
361 deps->file = lookup_file (filename);
362 if (deps->file == 0)
363 deps->file = enter_file (filename);
364 filename = deps->file->name;
365 deps->changed = flags;
366 if (flags & RM_DONTCARE)
367 deps->file->dontcare = 1;
369 if (expanded)
370 free (expanded);
372 /* If the makefile can't be found at all, give up entirely. */
374 if (ebuf.fp == 0)
376 /* If we did some searching, errno has the error from the last
377 attempt, rather from FILENAME itself. Restore it in case the
378 caller wants to use it in a message. */
379 errno = makefile_errno;
380 return 0;
383 /* Add this makefile to the list. */
384 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
385 f_append, 0);
387 /* Evaluate the makefile */
389 ebuf.size = 200;
390 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
392 curfile = reading_file;
393 reading_file = &ebuf.floc;
395 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
397 reading_file = curfile;
399 fclose (ebuf.fp);
401 free (ebuf.bufstart);
402 alloca (0);
403 return r;
407 eval_buffer (char *buffer)
409 struct ebuffer ebuf;
410 struct conditionals *saved;
411 struct conditionals new;
412 const struct floc *curfile;
413 int r;
415 /* Evaluate the buffer */
417 ebuf.size = strlen (buffer);
418 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
419 ebuf.fp = NULL;
421 ebuf.floc = *reading_file;
423 curfile = reading_file;
424 reading_file = &ebuf.floc;
426 saved = install_conditionals (&new);
428 r = eval (&ebuf, 1);
430 restore_conditionals (saved);
432 reading_file = curfile;
434 alloca (0);
435 return r;
439 /* Read file FILENAME as a makefile and add its contents to the data base.
441 SET_DEFAULT is true if we are allowed to set the default goal. */
444 static int
445 eval (struct ebuffer *ebuf, int set_default)
447 char *collapsed = 0;
448 unsigned int collapsed_length = 0;
449 unsigned int commands_len = 200;
450 char *commands;
451 unsigned int commands_idx = 0;
452 unsigned int cmds_started, tgts_started;
453 int ignoring = 0, in_ignored_define = 0;
454 int no_targets = 0; /* Set when reading a rule without targets. */
455 struct nameseq *filenames = 0;
456 struct dep *deps = 0;
457 long nlines = 0;
458 int two_colon = 0;
459 const char *pattern = 0;
460 const char *pattern_percent;
461 struct floc *fstart;
462 struct floc fi;
464 #define record_waiting_files() \
465 do \
467 if (filenames != 0) \
469 fi.lineno = tgts_started; \
470 record_files (filenames, pattern, pattern_percent, deps, \
471 cmds_started, commands, commands_idx, two_colon, \
472 &fi); \
474 filenames = 0; \
475 commands_idx = 0; \
476 no_targets = 0; \
477 pattern = 0; \
478 } while (0)
480 pattern_percent = 0;
481 cmds_started = tgts_started = 1;
483 fstart = &ebuf->floc;
484 fi.filenm = ebuf->floc.filenm;
486 /* Loop over lines in the file.
487 The strategy is to accumulate target names in FILENAMES, dependencies
488 in DEPS and commands in COMMANDS. These are used to define a rule
489 when the start of the next rule (or eof) is encountered.
491 When you see a "continue" in the loop below, that means we are moving on
492 to the next line _without_ ending any rule that we happen to be working
493 with at the moment. If you see a "goto rule_complete", then the
494 statement we just parsed also finishes the previous rule. */
496 commands = xmalloc (200);
498 while (1)
500 unsigned int linelen;
501 char *line;
502 unsigned int wlen;
503 char *p;
504 char *p2;
506 /* Grab the next line to be evaluated */
507 ebuf->floc.lineno += nlines;
508 nlines = readline (ebuf);
510 /* If there is nothing left to eval, we're done. */
511 if (nlines < 0)
512 break;
514 /* If this line is empty, skip it. */
515 line = ebuf->buffer;
516 if (line[0] == '\0')
517 continue;
519 linelen = strlen (line);
521 /* Check for a shell command line first.
522 If it is not one, we can stop treating tab specially. */
523 if (line[0] == cmd_prefix)
525 if (no_targets)
526 /* Ignore the commands in a rule with no targets. */
527 continue;
529 /* If there is no preceding rule line, don't treat this line
530 as a command, even though it begins with a tab character.
531 SunOS 4 make appears to behave this way. */
533 if (filenames != 0)
535 if (ignoring)
536 /* Yep, this is a shell command, and we don't care. */
537 continue;
539 /* Append this command line to the line being accumulated.
540 Strip command prefix chars that appear after newlines. */
541 if (commands_idx == 0)
542 cmds_started = ebuf->floc.lineno;
544 if (linelen + commands_idx > commands_len)
546 commands_len = (linelen + commands_idx) * 2;
547 commands = xrealloc (commands, commands_len);
549 p = &commands[commands_idx];
550 p2 = line + 1;
551 while (--linelen)
553 ++commands_idx;
554 *(p++) = *p2;
555 if (p2[0] == '\n' && p2[1] == cmd_prefix)
557 ++p2;
558 --linelen;
560 ++p2;
562 *p = '\n';
563 ++commands_idx;
565 continue;
569 /* This line is not a shell command line. Don't worry about tabs.
570 Get more space if we need it; we don't need to preserve the current
571 contents of the buffer. */
573 if (collapsed_length < linelen+1)
575 collapsed_length = linelen+1;
576 if (collapsed)
577 free (collapsed);
578 collapsed = xmalloc (collapsed_length);
580 strcpy (collapsed, line);
581 /* Collapse continuation lines. */
582 collapse_continuations (collapsed);
583 remove_comments (collapsed);
585 /* Compare a word, both length and contents. */
586 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
587 p = collapsed;
588 while (isspace ((unsigned char)*p))
589 ++p;
591 if (*p == '\0')
592 /* This line is completely empty--ignore it. */
593 continue;
595 /* Find the end of the first token. Note we don't need to worry about
596 * ":" here since we compare tokens by length (so "export" will never
597 * be equal to "export:").
599 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
601 wlen = p2 - p;
603 /* Find the start of the second token. If it looks like a target or
604 variable definition it can't be a preprocessor token so skip
605 them--this allows variables/targets named `ifdef', `export', etc. */
606 while (isspace ((unsigned char)*p2))
607 ++p2;
609 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
611 /* It can't be a preprocessor token so skip it if we're ignoring */
612 if (ignoring)
613 continue;
615 goto skip_conditionals;
618 /* We must first check for conditional and `define' directives before
619 ignoring anything, since they control what we will do with
620 following lines. */
622 if (!in_ignored_define)
624 int i = conditional_line (p, wlen, fstart);
625 if (i != -2)
627 if (i == -1)
628 fatal (fstart, _("invalid syntax in conditional"));
630 ignoring = i;
631 continue;
635 if (word1eq ("endef"))
637 if (!in_ignored_define)
638 fatal (fstart, _("extraneous `endef'"));
639 in_ignored_define = 0;
640 continue;
643 if (word1eq ("define"))
645 if (ignoring)
646 in_ignored_define = 1;
647 else
649 if (*p2 == '\0')
650 fatal (fstart, _("empty variable name"));
652 /* Let the variable name be the whole rest of the line,
653 with trailing blanks stripped (comments have already been
654 removed), so it could be a complex variable/function
655 reference that might contain blanks. */
656 p = strchr (p2, '\0');
657 while (isblank ((unsigned char)p[-1]))
658 --p;
659 do_define (p2, p - p2, o_file, ebuf);
661 continue;
664 if (word1eq ("override"))
666 if (*p2 == '\0')
667 error (fstart, _("empty `override' directive"));
669 if (strneq (p2, "define", 6)
670 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
672 if (ignoring)
673 in_ignored_define = 1;
674 else
676 p2 = next_token (p2 + 6);
677 if (*p2 == '\0')
678 fatal (fstart, _("empty variable name"));
680 /* Let the variable name be the whole rest of the line,
681 with trailing blanks stripped (comments have already been
682 removed), so it could be a complex variable/function
683 reference that might contain blanks. */
684 p = strchr (p2, '\0');
685 while (isblank ((unsigned char)p[-1]))
686 --p;
687 do_define (p2, p - p2, o_override, ebuf);
690 else if (!ignoring
691 && !try_variable_definition (fstart, p2, o_override, 0))
692 error (fstart, _("invalid `override' directive"));
694 continue;
697 if (ignoring)
698 /* Ignore the line. We continue here so conditionals
699 can appear in the middle of a rule. */
700 continue;
702 if (word1eq ("export"))
704 /* 'export' by itself causes everything to be exported. */
705 if (*p2 == '\0')
706 export_all_variables = 1;
707 else
709 struct variable *v;
711 v = try_variable_definition (fstart, p2, o_file, 0);
712 if (v != 0)
713 v->export = v_export;
714 else
716 unsigned int l;
717 const char *cp;
718 char *ap;
720 /* Expand the line so we can use indirect and constructed
721 variable names in an export command. */
722 cp = ap = allocated_variable_expand (p2);
724 for (p = find_next_token (&cp, &l); p != 0;
725 p = find_next_token (&cp, &l))
727 v = lookup_variable (p, l);
728 if (v == 0)
729 v = define_variable_loc (p, l, "", o_file, 0, fstart);
730 v->export = v_export;
733 free (ap);
736 goto rule_complete;
739 if (word1eq ("unexport"))
741 if (*p2 == '\0')
742 export_all_variables = 0;
743 else
745 unsigned int l;
746 struct variable *v;
747 const char *cp;
748 char *ap;
750 /* Expand the line so we can use indirect and constructed
751 variable names in an unexport command. */
752 cp = ap = allocated_variable_expand (p2);
754 for (p = find_next_token (&cp, &l); p != 0;
755 p = find_next_token (&cp, &l))
757 v = lookup_variable (p, l);
758 if (v == 0)
759 v = define_variable_loc (p, l, "", o_file, 0, fstart);
761 v->export = v_noexport;
764 free (ap);
766 goto rule_complete;
769 skip_conditionals:
770 if (word1eq ("vpath"))
772 const char *cp;
773 char *vpat;
774 unsigned int l;
775 cp = variable_expand (p2);
776 p = find_next_token (&cp, &l);
777 if (p != 0)
779 vpat = savestring (p, l);
780 p = find_next_token (&cp, &l);
781 /* No searchpath means remove all previous
782 selective VPATH's with the same pattern. */
784 else
785 /* No pattern means remove all previous selective VPATH's. */
786 vpat = 0;
787 construct_vpath_list (vpat, p);
788 if (vpat != 0)
789 free (vpat);
791 goto rule_complete;
794 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
796 /* We have found an `include' line specifying a nested
797 makefile to be read at this point. */
798 struct conditionals *save;
799 struct conditionals new_conditionals;
800 struct nameseq *files;
801 /* "-include" (vs "include") says no error if the file does not
802 exist. "sinclude" is an alias for this from SGI. */
803 int noerror = (p[0] != 'i');
805 p = allocated_variable_expand (p2);
807 /* If no filenames, it's a no-op. */
808 if (*p == '\0')
810 free (p);
811 continue;
814 /* Parse the list of file names. */
815 p2 = p;
816 files = multi_glob (parse_file_seq (&p2, '\0',
817 sizeof (struct nameseq),
819 sizeof (struct nameseq));
820 free (p);
822 /* Save the state of conditionals and start
823 the included makefile with a clean slate. */
824 save = install_conditionals (&new_conditionals);
826 /* Record the rules that are waiting so they will determine
827 the default goal before those in the included makefile. */
828 record_waiting_files ();
830 /* Read each included makefile. */
831 while (files != 0)
833 struct nameseq *next = files->next;
834 const char *name = files->name;
835 int r;
837 free (files);
838 files = next;
840 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
841 | (noerror ? RM_DONTCARE : 0)));
842 if (!r && !noerror)
843 error (fstart, "%s: %s", name, strerror (errno));
846 /* Restore conditional state. */
847 restore_conditionals (save);
849 goto rule_complete;
852 if (try_variable_definition (fstart, p, o_file, 0))
853 /* This line has been dealt with. */
854 goto rule_complete;
856 /* This line starts with a tab but was not caught above because there
857 was no preceding target, and the line might have been usable as a
858 variable definition. But now we know it is definitely lossage. */
859 if (line[0] == cmd_prefix)
860 fatal(fstart, _("recipe commences before first target"));
862 /* This line describes some target files. This is complicated by
863 the existence of target-specific variables, because we can't
864 expand the entire line until we know if we have one or not. So
865 we expand the line word by word until we find the first `:',
866 then check to see if it's a target-specific variable.
868 In this algorithm, `lb_next' will point to the beginning of the
869 unexpanded parts of the input buffer, while `p2' points to the
870 parts of the expanded buffer we haven't searched yet. */
873 enum make_word_type wtype;
874 enum variable_origin v_origin;
875 int exported;
876 char *cmdleft, *semip, *lb_next;
877 unsigned int plen = 0;
878 char *colonp;
879 const char *end, *beg; /* Helpers for whitespace stripping. */
881 /* Record the previous rule. */
883 record_waiting_files ();
884 tgts_started = fstart->lineno;
886 /* Search the line for an unquoted ; that is not after an
887 unquoted #. */
888 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
889 if (cmdleft != 0 && *cmdleft == '#')
891 /* We found a comment before a semicolon. */
892 *cmdleft = '\0';
893 cmdleft = 0;
895 else if (cmdleft != 0)
896 /* Found one. Cut the line short there before expanding it. */
897 *(cmdleft++) = '\0';
898 semip = cmdleft;
900 collapse_continuations (line);
902 /* We can't expand the entire line, since if it's a per-target
903 variable we don't want to expand it. So, walk from the
904 beginning, expanding as we go, and looking for "interesting"
905 chars. The first word is always expandable. */
906 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
907 switch (wtype)
909 case w_eol:
910 if (cmdleft != 0)
911 fatal(fstart, _("missing rule before recipe"));
912 /* This line contained something but turned out to be nothing
913 but whitespace (a comment?). */
914 continue;
916 case w_colon:
917 case w_dcolon:
918 /* We accept and ignore rules without targets for
919 compatibility with SunOS 4 make. */
920 no_targets = 1;
921 continue;
923 default:
924 break;
927 p2 = variable_expand_string(NULL, lb_next, wlen);
929 while (1)
931 lb_next += wlen;
932 if (cmdleft == 0)
934 /* Look for a semicolon in the expanded line. */
935 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
937 if (cmdleft != 0)
939 unsigned long p2_off = p2 - variable_buffer;
940 unsigned long cmd_off = cmdleft - variable_buffer;
941 char *pend = p2 + strlen(p2);
943 /* Append any remnants of lb, then cut the line short
944 at the semicolon. */
945 *cmdleft = '\0';
947 /* One school of thought says that you shouldn't expand
948 here, but merely copy, since now you're beyond a ";"
949 and into a command script. However, the old parser
950 expanded the whole line, so we continue that for
951 backwards-compatiblity. Also, it wouldn't be
952 entirely consistent, since we do an unconditional
953 expand below once we know we don't have a
954 target-specific variable. */
955 (void)variable_expand_string(pend, lb_next, (long)-1);
956 lb_next += strlen(lb_next);
957 p2 = variable_buffer + p2_off;
958 cmdleft = variable_buffer + cmd_off + 1;
962 colonp = find_char_unquote(p2, ':', 0, 0, 0);
963 #ifdef HAVE_DOS_PATHS
964 /* The drive spec brain-damage strikes again... */
965 /* Note that the only separators of targets in this context
966 are whitespace and a left paren. If others are possible,
967 they should be added to the string in the call to index. */
968 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
969 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
970 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
971 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
972 #endif
973 if (colonp != 0)
974 break;
976 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
977 if (wtype == w_eol)
978 break;
980 p2 += strlen(p2);
981 *(p2++) = ' ';
982 p2 = variable_expand_string(p2, lb_next, wlen);
983 /* We don't need to worry about cmdleft here, because if it was
984 found in the variable_buffer the entire buffer has already
985 been expanded... we'll never get here. */
988 p2 = next_token (variable_buffer);
990 /* If the word we're looking at is EOL, see if there's _anything_
991 on the line. If not, a variable expanded to nothing, so ignore
992 it. If so, we can't parse this line so punt. */
993 if (wtype == w_eol)
995 if (*p2 != '\0')
996 /* There's no need to be ivory-tower about this: check for
997 one of the most common bugs found in makefiles... */
998 fatal (fstart, _("missing separator%s"),
999 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1000 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1001 continue;
1004 /* Make the colon the end-of-string so we know where to stop
1005 looking for targets. */
1006 *colonp = '\0';
1007 filenames = multi_glob (parse_file_seq (&p2, '\0',
1008 sizeof (struct nameseq),
1010 sizeof (struct nameseq));
1011 *p2 = ':';
1013 if (!filenames)
1015 /* We accept and ignore rules without targets for
1016 compatibility with SunOS 4 make. */
1017 no_targets = 1;
1018 continue;
1020 /* This should never be possible; we handled it above. */
1021 assert (*p2 != '\0');
1022 ++p2;
1024 /* Is this a one-colon or two-colon entry? */
1025 two_colon = *p2 == ':';
1026 if (two_colon)
1027 p2++;
1029 /* Test to see if it's a target-specific variable. Copy the rest
1030 of the buffer over, possibly temporarily (we'll expand it later
1031 if it's not a target-specific variable). PLEN saves the length
1032 of the unparsed section of p2, for later. */
1033 if (*lb_next != '\0')
1035 unsigned int l = p2 - variable_buffer;
1036 plen = strlen (p2);
1037 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1038 p2 = variable_buffer + l;
1041 /* See if it's an "override" or "export" keyword; if so see if what
1042 comes after it looks like a variable definition. */
1044 wtype = get_next_mword (p2, NULL, &p, &wlen);
1046 v_origin = o_file;
1047 exported = 0;
1048 if (wtype == w_static)
1050 if (word1eq ("override"))
1052 v_origin = o_override;
1053 wtype = get_next_mword (p+wlen, NULL, &p, &wlen);
1055 else if (word1eq ("export"))
1057 exported = 1;
1058 wtype = get_next_mword (p+wlen, NULL, &p, &wlen);
1062 if (wtype != w_eol)
1063 wtype = get_next_mword (p+wlen, NULL, NULL, NULL);
1065 if (wtype == w_varassign)
1067 /* If there was a semicolon found, add it back, plus anything
1068 after it. */
1069 if (semip)
1071 unsigned int l = p - variable_buffer;
1072 *(--semip) = ';';
1073 variable_buffer_output (p2 + strlen (p2),
1074 semip, strlen (semip)+1);
1075 p = variable_buffer + l;
1077 record_target_var (filenames, p, v_origin, exported, fstart);
1078 filenames = 0;
1079 continue;
1082 /* This is a normal target, _not_ a target-specific variable.
1083 Unquote any = in the dependency list. */
1084 find_char_unquote (lb_next, '=', 0, 0, 0);
1086 /* We have some targets, so don't ignore the following commands. */
1087 no_targets = 0;
1089 /* Expand the dependencies, etc. */
1090 if (*lb_next != '\0')
1092 unsigned int l = p2 - variable_buffer;
1093 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1094 p2 = variable_buffer + l;
1096 /* Look for a semicolon in the expanded line. */
1097 if (cmdleft == 0)
1099 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1100 if (cmdleft != 0)
1101 *(cmdleft++) = '\0';
1105 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1106 p = strchr (p2, ':');
1107 while (p != 0 && p[-1] == '\\')
1109 register char *q = &p[-1];
1110 register int backslash = 0;
1111 while (*q-- == '\\')
1112 backslash = !backslash;
1113 if (backslash)
1114 p = strchr (p + 1, ':');
1115 else
1116 break;
1118 #ifdef _AMIGA
1119 /* Here, the situation is quite complicated. Let's have a look
1120 at a couple of targets:
1122 install: dev:make
1124 dev:make: make
1126 dev:make:: xyz
1128 The rule is that it's only a target, if there are TWO :'s
1129 OR a space around the :.
1131 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1132 || isspace ((unsigned char)p[-1])))
1133 p = 0;
1134 #endif
1135 #ifdef HAVE_DOS_PATHS
1137 int check_again;
1138 do {
1139 check_again = 0;
1140 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1141 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1142 isalpha ((unsigned char)p[-1]) &&
1143 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1144 p = strchr (p + 1, ':');
1145 check_again = 1;
1147 } while (check_again);
1149 #endif
1150 if (p != 0)
1152 struct nameseq *target;
1153 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1154 ++p2;
1155 if (target == 0)
1156 fatal (fstart, _("missing target pattern"));
1157 else if (target->next != 0)
1158 fatal (fstart, _("multiple target patterns"));
1159 pattern_percent = find_percent_cached (&target->name);
1160 pattern = target->name;
1161 if (pattern_percent == 0)
1162 fatal (fstart, _("target pattern contains no `%%'"));
1163 free (target);
1165 else
1166 pattern = 0;
1168 /* Strip leading and trailing whitespaces. */
1169 beg = p2;
1170 end = beg + strlen (beg) - 1;
1171 strip_whitespace (&beg, &end);
1173 if (beg <= end && *beg != '\0')
1175 /* Put all the prerequisites here; they'll be parsed later. */
1176 deps = alloc_dep ();
1177 deps->name = strcache_add_len (beg, end - beg + 1);
1179 else
1180 deps = 0;
1182 commands_idx = 0;
1183 if (cmdleft != 0)
1185 /* Semicolon means rest of line is a command. */
1186 unsigned int l = strlen (cmdleft);
1188 cmds_started = fstart->lineno;
1190 /* Add this command line to the buffer. */
1191 if (l + 2 > commands_len)
1193 commands_len = (l + 2) * 2;
1194 commands = xrealloc (commands, commands_len);
1196 memcpy (commands, cmdleft, l);
1197 commands_idx += l;
1198 commands[commands_idx++] = '\n';
1201 /* Determine if this target should be made default. We used to do
1202 this in record_files() but because of the delayed target recording
1203 and because preprocessor directives are legal in target's commands
1204 it is too late. Consider this fragment for example:
1206 foo:
1208 ifeq ($(.DEFAULT_GOAL),foo)
1210 endif
1212 Because the target is not recorded until after ifeq directive is
1213 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1214 would expect. Because of this we have to move some of the logic
1215 here. */
1217 if (**default_goal_name == '\0' && set_default)
1219 const char *name;
1220 struct dep *d;
1221 struct nameseq *t = filenames;
1223 for (; t != 0; t = t->next)
1225 int reject = 0;
1226 name = t->name;
1228 /* We have nothing to do if this is an implicit rule. */
1229 if (strchr (name, '%') != 0)
1230 break;
1232 /* See if this target's name does not start with a `.',
1233 unless it contains a slash. */
1234 if (*name == '.' && strchr (name, '/') == 0
1235 #ifdef HAVE_DOS_PATHS
1236 && strchr (name, '\\') == 0
1237 #endif
1239 continue;
1242 /* If this file is a suffix, don't let it be
1243 the default goal file. */
1244 for (d = suffix_file->deps; d != 0; d = d->next)
1246 register struct dep *d2;
1247 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1249 reject = 1;
1250 break;
1252 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1254 unsigned int l = strlen (dep_name (d2));
1255 if (!strneq (name, dep_name (d2), l))
1256 continue;
1257 if (streq (name + l, dep_name (d)))
1259 reject = 1;
1260 break;
1264 if (reject)
1265 break;
1268 if (!reject)
1270 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1271 o_file, 0, NILF);
1272 break;
1277 continue;
1280 /* We get here except in the case that we just read a rule line.
1281 Record now the last rule we read, so following spurious
1282 commands are properly diagnosed. */
1283 rule_complete:
1284 record_waiting_files ();
1287 #undef word1eq
1289 if (conditionals->if_cmds)
1290 fatal (fstart, _("missing `endif'"));
1292 /* At eof, record the last rule. */
1293 record_waiting_files ();
1295 if (collapsed)
1296 free (collapsed);
1297 free (commands);
1299 return 1;
1303 /* Remove comments from LINE.
1304 This is done by copying the text at LINE onto itself. */
1306 static void
1307 remove_comments (char *line)
1309 char *comment;
1311 comment = find_char_unquote (line, '#', 0, 0, 0);
1313 if (comment != 0)
1314 /* Cut off the line at the #. */
1315 *comment = '\0';
1318 /* Execute a `define' directive.
1319 The first line has already been read, and NAME is the name of
1320 the variable to be defined. The following lines remain to be read. */
1322 static void
1323 do_define (char *name, unsigned int namelen,
1324 enum variable_origin origin, struct ebuffer *ebuf)
1326 struct floc defstart;
1327 long nlines = 0;
1328 int nlevels = 1;
1329 unsigned int length = 100;
1330 char *definition = xmalloc (length);
1331 unsigned int idx = 0;
1332 char *p;
1334 /* Expand the variable name. */
1335 char *var = alloca (namelen + 1);
1336 memcpy (var, name, namelen);
1337 var[namelen] = '\0';
1338 var = variable_expand (var);
1340 defstart = ebuf->floc;
1342 while (1)
1344 unsigned int len;
1345 char *line;
1347 nlines = readline (ebuf);
1348 ebuf->floc.lineno += nlines;
1350 /* If there is nothing left to eval, we're done. */
1351 if (nlines < 0)
1352 break;
1354 line = ebuf->buffer;
1356 collapse_continuations (line);
1358 /* If the line doesn't begin with a tab, test to see if it introduces
1359 another define, or ends one. */
1361 /* Stop if we find an 'endef' */
1362 if (line[0] != cmd_prefix)
1364 p = next_token (line);
1365 len = strlen (p);
1367 /* If this is another 'define', increment the level count. */
1368 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1369 && strneq (p, "define", 6))
1370 ++nlevels;
1372 /* If this is an 'endef', decrement the count. If it's now 0,
1373 we've found the last one. */
1374 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1375 && strneq (p, "endef", 5))
1377 p += 5;
1378 remove_comments (p);
1379 if (*next_token (p) != '\0')
1380 error (&ebuf->floc,
1381 _("Extraneous text after `endef' directive"));
1383 if (--nlevels == 0)
1385 /* Define the variable. */
1386 if (idx == 0)
1387 definition[0] = '\0';
1388 else
1389 definition[idx - 1] = '\0';
1391 /* Always define these variables in the global set. */
1392 define_variable_global (var, strlen (var), definition,
1393 origin, 1, &defstart);
1394 free (definition);
1395 return;
1400 /* Otherwise add this line to the variable definition. */
1401 len = strlen (line);
1402 if (idx + len + 1 > length)
1404 length = (idx + len) * 2;
1405 definition = xrealloc (definition, length + 1);
1408 memcpy (&definition[idx], line, len);
1409 idx += len;
1410 /* Separate lines with a newline. */
1411 definition[idx++] = '\n';
1414 /* No `endef'!! */
1415 fatal (&defstart, _("missing `endef', unterminated `define'"));
1417 /* NOTREACHED */
1418 return;
1421 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1422 "ifneq", "else" and "endif".
1423 LINE is the input line, with the command as its first word.
1425 FILENAME and LINENO are the filename and line number in the
1426 current makefile. They are used for error messages.
1428 Value is -2 if the line is not a conditional at all,
1429 -1 if the line is an invalid conditional,
1430 0 if following text should be interpreted,
1431 1 if following text should be ignored. */
1433 static int
1434 conditional_line (char *line, int len, const struct floc *flocp)
1436 char *cmdname;
1437 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1438 unsigned int i;
1439 unsigned int o;
1441 /* Compare a word, both length and contents. */
1442 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1443 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1445 /* Make sure this line is a conditional. */
1446 chkword ("ifdef", c_ifdef)
1447 else chkword ("ifndef", c_ifndef)
1448 else chkword ("ifeq", c_ifeq)
1449 else chkword ("ifneq", c_ifneq)
1450 else chkword ("else", c_else)
1451 else chkword ("endif", c_endif)
1452 else
1453 return -2;
1455 /* Found one: skip past it and any whitespace after it. */
1456 line = next_token (line + len);
1458 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1460 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1461 if (cmdtype == c_endif)
1463 if (*line != '\0')
1464 EXTRANEOUS ();
1466 if (!conditionals->if_cmds)
1467 fatal (flocp, _("extraneous `%s'"), cmdname);
1469 --conditionals->if_cmds;
1471 goto DONE;
1474 /* An 'else' statement can either be simple, or it can have another
1475 conditional after it. */
1476 if (cmdtype == c_else)
1478 const char *p;
1480 if (!conditionals->if_cmds)
1481 fatal (flocp, _("extraneous `%s'"), cmdname);
1483 o = conditionals->if_cmds - 1;
1485 if (conditionals->seen_else[o])
1486 fatal (flocp, _("only one `else' per conditional"));
1488 /* Change the state of ignorance. */
1489 switch (conditionals->ignoring[o])
1491 case 0:
1492 /* We've just been interpreting. Never do it again. */
1493 conditionals->ignoring[o] = 2;
1494 break;
1495 case 1:
1496 /* We've never interpreted yet. Maybe this time! */
1497 conditionals->ignoring[o] = 0;
1498 break;
1501 /* It's a simple 'else'. */
1502 if (*line == '\0')
1504 conditionals->seen_else[o] = 1;
1505 goto DONE;
1508 /* The 'else' has extra text. That text must be another conditional
1509 and cannot be an 'else' or 'endif'. */
1511 /* Find the length of the next word. */
1512 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1514 len = p - line;
1516 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1517 if (word1eq("else") || word1eq("endif")
1518 || conditional_line (line, len, flocp) < 0)
1519 EXTRANEOUS ();
1520 else
1522 /* conditional_line() created a new level of conditional.
1523 Raise it back to this level. */
1524 if (conditionals->ignoring[o] < 2)
1525 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1526 --conditionals->if_cmds;
1529 goto DONE;
1532 if (conditionals->allocated == 0)
1534 conditionals->allocated = 5;
1535 conditionals->ignoring = xmalloc (conditionals->allocated);
1536 conditionals->seen_else = xmalloc (conditionals->allocated);
1539 o = conditionals->if_cmds++;
1540 if (conditionals->if_cmds > conditionals->allocated)
1542 conditionals->allocated += 5;
1543 conditionals->ignoring = xrealloc (conditionals->ignoring,
1544 conditionals->allocated);
1545 conditionals->seen_else = xrealloc (conditionals->seen_else,
1546 conditionals->allocated);
1549 /* Record that we have seen an `if...' but no `else' so far. */
1550 conditionals->seen_else[o] = 0;
1552 /* Search through the stack to see if we're already ignoring. */
1553 for (i = 0; i < o; ++i)
1554 if (conditionals->ignoring[i])
1556 /* We are already ignoring, so just push a level to match the next
1557 "else" or "endif", and keep ignoring. We don't want to expand
1558 variables in the condition. */
1559 conditionals->ignoring[o] = 1;
1560 return 1;
1563 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1565 char *var;
1566 struct variable *v;
1567 char *p;
1569 /* Expand the thing we're looking up, so we can use indirect and
1570 constructed variable names. */
1571 var = allocated_variable_expand (line);
1573 /* Make sure there's only one variable name to test. */
1574 p = end_of_token (var);
1575 i = p - var;
1576 p = next_token (p);
1577 if (*p != '\0')
1578 return -1;
1580 var[i] = '\0';
1581 v = lookup_variable (var, i);
1583 conditionals->ignoring[o] =
1584 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1586 free (var);
1588 else
1590 /* "ifeq" or "ifneq". */
1591 char *s1, *s2;
1592 unsigned int l;
1593 char termin = *line == '(' ? ',' : *line;
1595 if (termin != ',' && termin != '"' && termin != '\'')
1596 return -1;
1598 s1 = ++line;
1599 /* Find the end of the first string. */
1600 if (termin == ',')
1602 int count = 0;
1603 for (; *line != '\0'; ++line)
1604 if (*line == '(')
1605 ++count;
1606 else if (*line == ')')
1607 --count;
1608 else if (*line == ',' && count <= 0)
1609 break;
1611 else
1612 while (*line != '\0' && *line != termin)
1613 ++line;
1615 if (*line == '\0')
1616 return -1;
1618 if (termin == ',')
1620 /* Strip blanks after the first string. */
1621 char *p = line++;
1622 while (isblank ((unsigned char)p[-1]))
1623 --p;
1624 *p = '\0';
1626 else
1627 *line++ = '\0';
1629 s2 = variable_expand (s1);
1630 /* We must allocate a new copy of the expanded string because
1631 variable_expand re-uses the same buffer. */
1632 l = strlen (s2);
1633 s1 = alloca (l + 1);
1634 memcpy (s1, s2, l + 1);
1636 if (termin != ',')
1637 /* Find the start of the second string. */
1638 line = next_token (line);
1640 termin = termin == ',' ? ')' : *line;
1641 if (termin != ')' && termin != '"' && termin != '\'')
1642 return -1;
1644 /* Find the end of the second string. */
1645 if (termin == ')')
1647 int count = 0;
1648 s2 = next_token (line);
1649 for (line = s2; *line != '\0'; ++line)
1651 if (*line == '(')
1652 ++count;
1653 else if (*line == ')')
1655 if (count <= 0)
1656 break;
1657 else
1658 --count;
1662 else
1664 ++line;
1665 s2 = line;
1666 while (*line != '\0' && *line != termin)
1667 ++line;
1670 if (*line == '\0')
1671 return -1;
1673 *line = '\0';
1674 line = next_token (++line);
1675 if (*line != '\0')
1676 EXTRANEOUS ();
1678 s2 = variable_expand (s2);
1679 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1682 DONE:
1683 /* Search through the stack to see if we're ignoring. */
1684 for (i = 0; i < conditionals->if_cmds; ++i)
1685 if (conditionals->ignoring[i])
1686 return 1;
1687 return 0;
1690 /* Remove duplicate dependencies in CHAIN. */
1692 static unsigned long
1693 dep_hash_1 (const void *key)
1695 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1698 static unsigned long
1699 dep_hash_2 (const void *key)
1701 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1704 static int
1705 dep_hash_cmp (const void *x, const void *y)
1707 struct dep *dx = (struct dep *) x;
1708 struct dep *dy = (struct dep *) y;
1709 int cmp = strcmp (dep_name (dx), dep_name (dy));
1711 /* If the names are the same but ignore_mtimes are not equal, one of these
1712 is an order-only prerequisite and one isn't. That means that we should
1713 remove the one that isn't and keep the one that is. */
1715 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1716 dx->ignore_mtime = dy->ignore_mtime = 0;
1718 return cmp;
1722 void
1723 uniquize_deps (struct dep *chain)
1725 struct hash_table deps;
1726 register struct dep **depp;
1728 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1730 /* Make sure that no dependencies are repeated. This does not
1731 really matter for the purpose of updating targets, but it
1732 might make some names be listed twice for $^ and $?. */
1734 depp = &chain;
1735 while (*depp)
1737 struct dep *dep = *depp;
1738 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1739 if (HASH_VACANT (*dep_slot))
1741 hash_insert_at (&deps, dep, dep_slot);
1742 depp = &dep->next;
1744 else
1746 /* Don't bother freeing duplicates.
1747 It's dangerous and little benefit accrues. */
1748 *depp = dep->next;
1752 hash_free (&deps, 0);
1755 /* Record target-specific variable values for files FILENAMES.
1756 TWO_COLON is nonzero if a double colon was used.
1758 The links of FILENAMES are freed, and so are any names in it
1759 that are not incorporated into other data structures.
1761 If the target is a pattern, add the variable to the pattern-specific
1762 variable value list. */
1764 static void
1765 record_target_var (struct nameseq *filenames, char *defn,
1766 enum variable_origin origin, int exported,
1767 const struct floc *flocp)
1769 struct nameseq *nextf;
1770 struct variable_set_list *global;
1772 global = current_variable_set_list;
1774 /* If the variable is an append version, store that but treat it as a
1775 normal recursive variable. */
1777 for (; filenames != 0; filenames = nextf)
1779 struct variable *v;
1780 const char *name = filenames->name;
1781 const char *fname;
1782 const char *percent;
1783 struct pattern_var *p;
1785 nextf = filenames->next;
1786 free (filenames);
1788 /* If it's a pattern target, then add it to the pattern-specific
1789 variable list. */
1790 percent = find_percent_cached (&name);
1791 if (percent)
1793 /* Get a reference for this pattern-specific variable struct. */
1794 p = create_pattern_var (name, percent);
1795 p->variable.fileinfo = *flocp;
1796 /* I don't think this can fail since we already determined it was a
1797 variable definition. */
1798 v = parse_variable_definition (&p->variable, defn);
1799 assert (v != 0);
1801 if (v->flavor == f_simple)
1802 v->value = allocated_variable_expand (v->value);
1803 else
1804 v->value = xstrdup (v->value);
1806 fname = p->target;
1808 else
1810 struct file *f;
1812 /* Get a file reference for this file, and initialize it.
1813 We don't want to just call enter_file() because that allocates a
1814 new entry if the file is a double-colon, which we don't want in
1815 this situation. */
1816 f = lookup_file (name);
1817 if (!f)
1818 f = enter_file (strcache_add (name));
1819 else if (f->double_colon)
1820 f = f->double_colon;
1822 initialize_file_variables (f, 1);
1823 fname = f->name;
1825 current_variable_set_list = f->variables;
1826 v = try_variable_definition (flocp, defn, origin, 1);
1827 if (!v)
1828 error (flocp, _("Malformed target-specific variable definition"));
1829 current_variable_set_list = global;
1832 /* Set up the variable to be *-specific. */
1833 v->origin = origin;
1834 v->per_target = 1;
1835 v->export = exported ? v_export : v_default;
1837 /* If it's not an override, check to see if there was a command-line
1838 setting. If so, reset the value. */
1839 if (origin != o_override)
1841 struct variable *gv;
1842 int len = strlen(v->name);
1844 gv = lookup_variable (v->name, len);
1845 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1847 if (v->value != 0)
1848 free (v->value);
1849 v->value = xstrdup (gv->value);
1850 v->origin = gv->origin;
1851 v->recursive = gv->recursive;
1852 v->append = 0;
1858 /* Record a description line for files FILENAMES,
1859 with dependencies DEPS, commands to execute described
1860 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1861 TWO_COLON is nonzero if a double colon was used.
1862 If not nil, PATTERN is the `%' pattern to make this
1863 a static pattern rule, and PATTERN_PERCENT is a pointer
1864 to the `%' within it.
1866 The links of FILENAMES are freed, and so are any names in it
1867 that are not incorporated into other data structures. */
1869 static void
1870 record_files (struct nameseq *filenames, const char *pattern,
1871 const char *pattern_percent, struct dep *deps,
1872 unsigned int cmds_started, char *commands,
1873 unsigned int commands_idx, int two_colon,
1874 const struct floc *flocp)
1876 struct nameseq *nextf;
1877 int implicit = 0;
1878 unsigned int max_targets = 0, target_idx = 0;
1879 const char **targets = 0, **target_percents = 0;
1880 struct commands *cmds;
1882 /* If we've already snapped deps, that means we're in an eval being
1883 resolved after the makefiles have been read in. We can't add more rules
1884 at this time, since they won't get snapped and we'll get core dumps.
1885 See Savannah bug # 12124. */
1886 if (snapped_deps)
1887 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1889 if (commands_idx > 0)
1891 cmds = xmalloc (sizeof (struct commands));
1892 cmds->fileinfo.filenm = flocp->filenm;
1893 cmds->fileinfo.lineno = cmds_started;
1894 cmds->commands = savestring (commands, commands_idx);
1895 cmds->command_lines = 0;
1897 else
1898 cmds = 0;
1900 for (; filenames != 0; filenames = nextf)
1902 const char *name = filenames->name;
1903 struct file *f;
1904 struct dep *this = 0;
1905 const char *implicit_percent;
1907 nextf = filenames->next;
1908 free (filenames);
1910 /* Check for special targets. Do it here instead of, say, snap_deps()
1911 so that we can immediately use the value. */
1913 if (streq (name, ".POSIX"))
1914 posix_pedantic = 1;
1915 else if (streq (name, ".SECONDEXPANSION"))
1916 second_expansion = 1;
1918 implicit_percent = find_percent_cached (&name);
1919 implicit |= implicit_percent != 0;
1921 if (implicit)
1923 if (pattern != 0)
1924 fatal (flocp, _("mixed implicit and static pattern rules"));
1926 if (implicit_percent == 0)
1927 fatal (flocp, _("mixed implicit and normal rules"));
1929 if (targets == 0)
1931 max_targets = 5;
1932 targets = xmalloc (5 * sizeof (char *));
1933 target_percents = xmalloc (5 * sizeof (char *));
1934 target_idx = 0;
1936 else if (target_idx == max_targets - 1)
1938 max_targets += 5;
1939 targets = xrealloc (targets, max_targets * sizeof (char *));
1940 target_percents = xrealloc (target_percents,
1941 max_targets * sizeof (char *));
1943 targets[target_idx] = name;
1944 target_percents[target_idx] = implicit_percent;
1945 ++target_idx;
1946 continue;
1949 /* If this is a static pattern rule:
1950 `targets: target%pattern: dep%pattern; cmds',
1951 make sure the pattern matches this target name. */
1952 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1953 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1954 else if (deps)
1956 /* If there are multiple filenames, copy the chain DEPS for all but
1957 the last one. It is not safe for the same deps to go in more
1958 than one place in the database. */
1959 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1960 this->need_2nd_expansion = (second_expansion
1961 && strchr (this->name, '$'));
1964 if (!two_colon)
1966 /* Single-colon. Combine these dependencies
1967 with others in file's existing record, if any. */
1968 f = enter_file (strcache_add (name));
1970 if (f->double_colon)
1971 fatal (flocp,
1972 _("target file `%s' has both : and :: entries"), f->name);
1974 /* If CMDS == F->CMDS, this target was listed in this rule
1975 more than once. Just give a warning since this is harmless. */
1976 if (cmds != 0 && cmds == f->cmds)
1977 error (flocp,
1978 _("target `%s' given more than once in the same rule."),
1979 f->name);
1981 /* Check for two single-colon entries both with commands.
1982 Check is_target so that we don't lose on files such as .c.o
1983 whose commands were preinitialized. */
1984 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1986 error (&cmds->fileinfo,
1987 _("warning: overriding recipe for target `%s'"),
1988 f->name);
1989 error (&f->cmds->fileinfo,
1990 _("warning: ignoring old recipe for target `%s'"),
1991 f->name);
1994 f->is_target = 1;
1996 /* Defining .DEFAULT with no deps or cmds clears it. */
1997 if (f == default_file && this == 0 && cmds == 0)
1998 f->cmds = 0;
1999 if (cmds != 0)
2000 f->cmds = cmds;
2002 /* Defining .SUFFIXES with no dependencies clears out the list of
2003 suffixes. */
2004 if (f == suffix_file && this == 0)
2006 free_dep_chain (f->deps);
2007 f->deps = 0;
2009 else if (this != 0)
2011 /* Add the file's old deps and the new ones in THIS together. */
2013 if (f->deps != 0)
2015 struct dep **d_ptr = &f->deps;
2017 while ((*d_ptr)->next != 0)
2018 d_ptr = &(*d_ptr)->next;
2020 if (cmds != 0)
2021 /* This is the rule with commands, so put its deps
2022 last. The rationale behind this is that $< expands to
2023 the first dep in the chain, and commands use $<
2024 expecting to get the dep that rule specifies. However
2025 the second expansion algorithm reverses the order thus
2026 we need to make it last here. */
2027 (*d_ptr)->next = this;
2028 else
2030 /* This is the rule without commands. Put its
2031 dependencies at the end but before dependencies from
2032 the rule with commands (if any). This way everything
2033 appears in makefile order. */
2035 if (f->cmds != 0)
2037 this->next = *d_ptr;
2038 *d_ptr = this;
2040 else
2041 (*d_ptr)->next = this;
2044 else
2045 f->deps = this;
2047 /* This is a hack. I need a way to communicate to snap_deps()
2048 that the last dependency line in this file came with commands
2049 (so that logic in snap_deps() can put it in front and all
2050 this $< -logic works). I cannot simply rely on file->cmds
2051 being not 0 because of the cases like the following:
2053 foo: bar
2054 foo:
2057 I am going to temporarily "borrow" UPDATING member in
2058 `struct file' for this. */
2060 if (cmds != 0)
2061 f->updating = 1;
2064 else
2066 /* Double-colon. Make a new record even if there already is one. */
2067 f = lookup_file (name);
2069 /* Check for both : and :: rules. Check is_target so
2070 we don't lose on default suffix rules or makefiles. */
2071 if (f != 0 && f->is_target && !f->double_colon)
2072 fatal (flocp,
2073 _("target file `%s' has both : and :: entries"), f->name);
2074 f = enter_file (strcache_add (name));
2075 /* If there was an existing entry and it was a double-colon entry,
2076 enter_file will have returned a new one, making it the prev
2077 pointer of the old one, and setting its double_colon pointer to
2078 the first one. */
2079 if (f->double_colon == 0)
2080 /* This is the first entry for this name, so we must set its
2081 double_colon pointer to itself. */
2082 f->double_colon = f;
2083 f->is_target = 1;
2084 f->deps = this;
2085 f->cmds = cmds;
2088 /* If this is a static pattern rule, set the stem to the part of its
2089 name that matched the `%' in the pattern, so you can use $* in the
2090 commands. */
2091 if (pattern)
2093 static const char *percent = "%";
2094 char *buffer = variable_expand ("");
2095 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2096 pattern_percent+1, percent+1);
2097 f->stem = strcache_add_len (buffer, o - buffer);
2098 if (this)
2100 this->staticpattern = 1;
2101 this->stem = f->stem;
2105 name = f->name;
2107 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2108 if (streq (*default_goal_name, name)
2109 && (default_goal_file == 0
2110 || ! streq (default_goal_file->name, name)))
2111 default_goal_file = f;
2114 if (implicit)
2116 if (deps)
2117 deps->need_2nd_expansion = second_expansion;
2118 create_pattern_rule (targets, target_percents, target_idx,
2119 two_colon, deps, cmds, 1);
2123 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2124 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2125 Quoting backslashes are removed from STRING by compacting it into
2126 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2127 one, or nil if there are none. STOPCHARs inside variable references are
2128 ignored if IGNOREVARS is true.
2130 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2132 static char *
2133 find_char_unquote (char *string, int stop1, int stop2, int blank,
2134 int ignorevars)
2136 unsigned int string_len = 0;
2137 char *p = string;
2139 if (ignorevars)
2140 ignorevars = '$';
2142 while (1)
2144 if (stop2 && blank)
2145 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2146 && ! isblank ((unsigned char) *p))
2147 ++p;
2148 else if (stop2)
2149 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2150 ++p;
2151 else if (blank)
2152 while (*p != '\0' && *p != ignorevars && *p != stop1
2153 && ! isblank ((unsigned char) *p))
2154 ++p;
2155 else
2156 while (*p != '\0' && *p != ignorevars && *p != stop1)
2157 ++p;
2159 if (*p == '\0')
2160 break;
2162 /* If we stopped due to a variable reference, skip over its contents. */
2163 if (*p == ignorevars)
2165 char openparen = p[1];
2167 p += 2;
2169 /* Skip the contents of a non-quoted, multi-char variable ref. */
2170 if (openparen == '(' || openparen == '{')
2172 unsigned int pcount = 1;
2173 char closeparen = (openparen == '(' ? ')' : '}');
2175 while (*p)
2177 if (*p == openparen)
2178 ++pcount;
2179 else if (*p == closeparen)
2180 if (--pcount == 0)
2182 ++p;
2183 break;
2185 ++p;
2189 /* Skipped the variable reference: look for STOPCHARS again. */
2190 continue;
2193 if (p > string && p[-1] == '\\')
2195 /* Search for more backslashes. */
2196 int i = -2;
2197 while (&p[i] >= string && p[i] == '\\')
2198 --i;
2199 ++i;
2200 /* Only compute the length if really needed. */
2201 if (string_len == 0)
2202 string_len = strlen (string);
2203 /* The number of backslashes is now -I.
2204 Copy P over itself to swallow half of them. */
2205 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2206 p += i/2;
2207 if (i % 2 == 0)
2208 /* All the backslashes quoted each other; the STOPCHAR was
2209 unquoted. */
2210 return p;
2212 /* The STOPCHAR was quoted by a backslash. Look for another. */
2214 else
2215 /* No backslash in sight. */
2216 return p;
2219 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2220 return 0;
2223 /* Search PATTERN for an unquoted % and handle quoting. */
2225 char *
2226 find_percent (char *pattern)
2228 return find_char_unquote (pattern, '%', 0, 0, 0);
2231 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2232 the % or NULL if no % was found.
2233 This version is used with strings in the string cache: if there's a need to
2234 modify the string a new version will be added to the string cache and
2235 *STRING will be set to that. */
2237 const char *
2238 find_percent_cached (const char **string)
2240 const char *p = *string;
2241 char *new = 0;
2242 int slen;
2244 /* If the first char is a % return now. This lets us avoid extra tests
2245 inside the loop. */
2246 if (*p == '%')
2247 return p;
2249 while (1)
2251 while (*p != '\0' && *p != '%')
2252 ++p;
2254 if (*p == '\0')
2255 break;
2257 /* See if this % is escaped with a backslash; if not we're done. */
2258 if (p[-1] != '\\')
2259 break;
2262 /* Search for more backslashes. */
2263 char *pv;
2264 int i = -2;
2266 while (&p[i] >= *string && p[i] == '\\')
2267 --i;
2268 ++i;
2270 /* At this point we know we'll need to allocate a new string.
2271 Make a copy if we haven't yet done so. */
2272 if (! new)
2274 slen = strlen (*string);
2275 new = alloca (slen + 1);
2276 memcpy (new, *string, slen + 1);
2277 p = new + (p - *string);
2278 *string = new;
2281 /* At this point *string, p, and new all point into the same string.
2282 Get a non-const version of p so we can modify new. */
2283 pv = new + (p - *string);
2285 /* The number of backslashes is now -I.
2286 Copy P over itself to swallow half of them. */
2287 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2288 p += i/2;
2290 /* If the backslashes quoted each other; the % was unquoted. */
2291 if (i % 2 == 0)
2292 break;
2296 /* If we had to change STRING, add it to the strcache. */
2297 if (new)
2299 *string = strcache_add (*string);
2300 p = *string + (p - new);
2303 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2304 return (*p == '\0') ? NULL : p;
2307 /* Parse a string into a sequence of filenames represented as a
2308 chain of struct nameseq's in reverse order and return that chain.
2310 The string is passed as STRINGP, the address of a string pointer.
2311 The string pointer is updated to point at the first character
2312 not parsed, which either is a null char or equals STOPCHAR.
2314 SIZE is how big to construct chain elements.
2315 This is useful if we want them actually to be other structures
2316 that have room for additional info.
2318 If STRIP is nonzero, strip `./'s off the beginning. */
2320 struct nameseq *
2321 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2323 struct nameseq *new = 0;
2324 struct nameseq *new1, *lastnew1;
2325 char *p = *stringp;
2327 #ifdef VMS
2328 # define VMS_COMMA ','
2329 #else
2330 # define VMS_COMMA 0
2331 #endif
2333 while (1)
2335 const char *name;
2336 char *q;
2338 /* Skip whitespace; see if any more names are left. */
2339 p = next_token (p);
2340 if (*p == '\0')
2341 break;
2342 if (*p == stopchar)
2343 break;
2345 /* There are, so find the end of the next name. */
2346 q = p;
2347 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2348 #ifdef VMS
2349 /* convert comma separated list to space separated */
2350 if (p && *p == ',')
2351 *p =' ';
2352 #endif
2353 #ifdef _AMIGA
2354 if (stopchar == ':' && p && *p == ':'
2355 && !(isspace ((unsigned char)p[1]) || !p[1]
2356 || isspace ((unsigned char)p[-1])))
2357 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2358 #endif
2359 #ifdef HAVE_DOS_PATHS
2360 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2361 first colon which isn't followed by a slash or a backslash.
2362 Note that tokens separated by spaces should be treated as separate
2363 tokens since make doesn't allow path names with spaces */
2364 if (stopchar == ':')
2365 while (p != 0 && !isspace ((unsigned char)*p) &&
2366 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2367 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2368 #endif
2369 if (p == 0)
2370 p = q + strlen (q);
2372 if (strip)
2373 #ifdef VMS
2374 /* Skip leading `[]'s. */
2375 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2376 #else
2377 /* Skip leading `./'s. */
2378 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2379 #endif
2381 q += 2; /* Skip "./". */
2382 while (q < p && *q == '/')
2383 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2384 ++q;
2387 /* Extract the filename just found, and skip it. */
2389 if (q == p)
2390 /* ".///" was stripped to "". */
2391 #if defined(VMS)
2392 continue;
2393 #elif defined(_AMIGA)
2394 name = "";
2395 #else
2396 name = "./";
2397 #endif
2398 else
2399 #ifdef VMS
2400 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2401 * to remove this '\' before we can use the filename.
2402 * Savestring called because q may be read-only string constant.
2405 char *qbase = xstrdup (q);
2406 char *pbase = qbase + (p-q);
2407 char *q1 = qbase;
2408 char *q2 = q1;
2409 char *p1 = pbase;
2411 while (q1 != pbase)
2413 if (*q1 == '\\' && *(q1+1) == ':')
2415 q1++;
2416 p1--;
2418 *q2++ = *q1++;
2420 name = strcache_add_len (qbase, p1 - qbase);
2421 free (qbase);
2423 #else
2424 name = strcache_add_len (q, p - q);
2425 #endif
2427 /* Add it to the front of the chain. */
2428 new1 = xmalloc (size);
2429 new1->name = name;
2430 new1->next = new;
2431 new = new1;
2434 #ifndef NO_ARCHIVES
2436 /* Look for multi-word archive references.
2437 They are indicated by a elt ending with an unmatched `)' and
2438 an elt further down the chain (i.e., previous in the file list)
2439 with an unmatched `(' (e.g., "lib(mem"). */
2441 new1 = new;
2442 lastnew1 = 0;
2443 while (new1 != 0)
2444 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2445 && new1->name[strlen (new1->name) - 1] == ')'
2446 && strchr (new1->name, '(') == 0)
2448 /* NEW1 ends with a `)' but does not contain a `('.
2449 Look back for an elt with an opening `(' but no closing `)'. */
2451 struct nameseq *n = new1->next, *lastn = new1;
2452 char *paren = 0;
2453 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2455 lastn = n;
2456 n = n->next;
2458 if (n != 0
2459 /* Ignore something starting with `(', as that cannot actually
2460 be an archive-member reference (and treating it as such
2461 results in an empty file name, which causes much lossage). */
2462 && n->name[0] != '(')
2464 /* N is the first element in the archive group.
2465 Its name looks like "lib(mem" (with no closing `)'). */
2467 char *libname;
2469 /* Copy "lib(" into LIBNAME. */
2470 ++paren;
2471 libname = alloca (paren - n->name + 1);
2472 memcpy (libname, n->name, paren - n->name);
2473 libname[paren - n->name] = '\0';
2475 if (*paren == '\0')
2477 /* N was just "lib(", part of something like "lib( a b)".
2478 Edit it out of the chain and free its storage. */
2479 lastn->next = n->next;
2480 free (n);
2481 /* LASTN->next is the new stopping elt for the loop below. */
2482 n = lastn->next;
2484 else
2486 /* Replace N's name with the full archive reference. */
2487 n->name = strcache_add (concat (libname, paren, ")"));
2490 if (new1->name[1] == '\0')
2492 /* NEW1 is just ")", part of something like "lib(a b )".
2493 Omit it from the chain and free its storage. */
2494 if (lastnew1 == 0)
2495 new = new1->next;
2496 else
2497 lastnew1->next = new1->next;
2498 lastn = new1;
2499 new1 = new1->next;
2500 free (lastn);
2502 else
2504 /* Replace also NEW1->name, which already has closing `)'. */
2505 new1->name = strcache_add (concat (libname, new1->name, ""));
2506 new1 = new1->next;
2509 /* Trace back from NEW1 (the end of the list) until N
2510 (the beginning of the list), rewriting each name
2511 with the full archive reference. */
2513 while (new1 != n)
2515 new1->name = strcache_add (concat (libname, new1->name, ")"));
2516 lastnew1 = new1;
2517 new1 = new1->next;
2520 else
2522 /* No frobnication happening. Just step down the list. */
2523 lastnew1 = new1;
2524 new1 = new1->next;
2527 else
2529 lastnew1 = new1;
2530 new1 = new1->next;
2533 #endif
2535 *stringp = p;
2536 return new;
2539 /* Find the next line of text in an eval buffer, combining continuation lines
2540 into one line.
2541 Return the number of actual lines read (> 1 if continuation lines).
2542 Returns -1 if there's nothing left in the buffer.
2544 After this function, ebuf->buffer points to the first character of the
2545 line we just found.
2548 /* Read a line of text from a STRING.
2549 Since we aren't really reading from a file, don't bother with linenumbers.
2552 static unsigned long
2553 readstring (struct ebuffer *ebuf)
2555 char *eol;
2557 /* If there is nothing left in this buffer, return 0. */
2558 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2559 return -1;
2561 /* Set up a new starting point for the buffer, and find the end of the
2562 next logical line (taking into account backslash/newline pairs). */
2564 eol = ebuf->buffer = ebuf->bufnext;
2566 while (1)
2568 int backslash = 0;
2569 char *bol = eol;
2570 char *p;
2572 /* Find the next newline. At EOS, stop. */
2573 eol = p = strchr (eol , '\n');
2574 if (!eol)
2576 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2577 return 0;
2580 /* Found a newline; if it's escaped continue; else we're done. */
2581 while (p > bol && *(--p) == '\\')
2582 backslash = !backslash;
2583 if (!backslash)
2584 break;
2585 ++eol;
2588 /* Overwrite the newline char. */
2589 *eol = '\0';
2590 ebuf->bufnext = eol+1;
2592 return 0;
2595 static long
2596 readline (struct ebuffer *ebuf)
2598 char *p;
2599 char *end;
2600 char *start;
2601 long nlines = 0;
2603 /* The behaviors between string and stream buffers are different enough to
2604 warrant different functions. Do the Right Thing. */
2606 if (!ebuf->fp)
2607 return readstring (ebuf);
2609 /* When reading from a file, we always start over at the beginning of the
2610 buffer for each new line. */
2612 p = start = ebuf->bufstart;
2613 end = p + ebuf->size;
2614 *p = '\0';
2616 while (fgets (p, end - p, ebuf->fp) != 0)
2618 char *p2;
2619 unsigned long len;
2620 int backslash;
2622 len = strlen (p);
2623 if (len == 0)
2625 /* This only happens when the first thing on the line is a '\0'.
2626 It is a pretty hopeless case, but (wonder of wonders) Athena
2627 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2628 There is nothing really to be done; we synthesize a newline so
2629 the following line doesn't appear to be part of this line. */
2630 error (&ebuf->floc,
2631 _("warning: NUL character seen; rest of line ignored"));
2632 p[0] = '\n';
2633 len = 1;
2636 /* Jump past the text we just read. */
2637 p += len;
2639 /* If the last char isn't a newline, the whole line didn't fit into the
2640 buffer. Get some more buffer and try again. */
2641 if (p[-1] != '\n')
2642 goto more_buffer;
2644 /* We got a newline, so add one to the count of lines. */
2645 ++nlines;
2647 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2648 /* Check to see if the line was really ended with CRLF; if so ignore
2649 the CR. */
2650 if ((p - start) > 1 && p[-2] == '\r')
2652 --p;
2653 p[-1] = '\n';
2655 #endif
2657 backslash = 0;
2658 for (p2 = p - 2; p2 >= start; --p2)
2660 if (*p2 != '\\')
2661 break;
2662 backslash = !backslash;
2665 if (!backslash)
2667 p[-1] = '\0';
2668 break;
2671 /* It was a backslash/newline combo. If we have more space, read
2672 another line. */
2673 if (end - p >= 80)
2674 continue;
2676 /* We need more space at the end of our buffer, so realloc it.
2677 Make sure to preserve the current offset of p. */
2678 more_buffer:
2680 unsigned long off = p - start;
2681 ebuf->size *= 2;
2682 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2683 p = start + off;
2684 end = start + ebuf->size;
2685 *p = '\0';
2689 if (ferror (ebuf->fp))
2690 pfatal_with_name (ebuf->floc.filenm);
2692 /* If we found some lines, return how many.
2693 If we didn't, but we did find _something_, that indicates we read the last
2694 line of a file with no final newline; return 1.
2695 If we read nothing, we're at EOF; return -1. */
2697 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2700 /* Parse the next "makefile word" from the input buffer, and return info
2701 about it.
2703 A "makefile word" is one of:
2705 w_bogus Should never happen
2706 w_eol End of input
2707 w_static A static word; cannot be expanded
2708 w_variable A word containing one or more variables/functions
2709 w_colon A colon
2710 w_dcolon A double-colon
2711 w_semicolon A semicolon
2712 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2714 Note that this function is only used when reading certain parts of the
2715 makefile. Don't use it where special rules hold sway (RHS of a variable,
2716 in a command list, etc.) */
2718 static enum make_word_type
2719 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2721 enum make_word_type wtype = w_bogus;
2722 char *p = buffer, *beg;
2723 char c;
2725 /* Skip any leading whitespace. */
2726 while (isblank ((unsigned char)*p))
2727 ++p;
2729 beg = p;
2730 c = *(p++);
2731 switch (c)
2733 case '\0':
2734 wtype = w_eol;
2735 break;
2737 case ';':
2738 wtype = w_semicolon;
2739 break;
2741 case '=':
2742 wtype = w_varassign;
2743 break;
2745 case ':':
2746 wtype = w_colon;
2747 switch (*p)
2749 case ':':
2750 ++p;
2751 wtype = w_dcolon;
2752 break;
2754 case '=':
2755 ++p;
2756 wtype = w_varassign;
2757 break;
2759 break;
2761 case '+':
2762 case '?':
2763 if (*p == '=')
2765 ++p;
2766 wtype = w_varassign;
2767 break;
2770 default:
2771 if (delim && strchr (delim, c))
2772 wtype = w_static;
2773 break;
2776 /* Did we find something? If so, return now. */
2777 if (wtype != w_bogus)
2778 goto done;
2780 /* This is some non-operator word. A word consists of the longest
2781 string of characters that doesn't contain whitespace, one of [:=#],
2782 or [?+]=, or one of the chars in the DELIM string. */
2784 /* We start out assuming a static word; if we see a variable we'll
2785 adjust our assumptions then. */
2786 wtype = w_static;
2788 /* We already found the first value of "c", above. */
2789 while (1)
2791 char closeparen;
2792 int count;
2794 switch (c)
2796 case '\0':
2797 case ' ':
2798 case '\t':
2799 case '=':
2800 goto done_word;
2802 case ':':
2803 #ifdef HAVE_DOS_PATHS
2804 /* A word CAN include a colon in its drive spec. The drive
2805 spec is allowed either at the beginning of a word, or as part
2806 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2807 if (!(p - beg >= 2
2808 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2809 && (p - beg == 2 || p[-3] == '(')))
2810 #endif
2811 goto done_word;
2813 case '$':
2814 c = *(p++);
2815 if (c == '$')
2816 break;
2818 /* This is a variable reference, so note that it's expandable.
2819 Then read it to the matching close paren. */
2820 wtype = w_variable;
2822 if (c == '(')
2823 closeparen = ')';
2824 else if (c == '{')
2825 closeparen = '}';
2826 else
2827 /* This is a single-letter variable reference. */
2828 break;
2830 for (count=0; *p != '\0'; ++p)
2832 if (*p == c)
2833 ++count;
2834 else if (*p == closeparen && --count < 0)
2836 ++p;
2837 break;
2840 break;
2842 case '?':
2843 case '+':
2844 if (*p == '=')
2845 goto done_word;
2846 break;
2848 case '\\':
2849 switch (*p)
2851 case ':':
2852 case ';':
2853 case '=':
2854 case '\\':
2855 ++p;
2856 break;
2858 break;
2860 default:
2861 if (delim && strchr (delim, c))
2862 goto done_word;
2863 break;
2866 c = *(p++);
2868 done_word:
2869 --p;
2871 done:
2872 if (startp)
2873 *startp = beg;
2874 if (length)
2875 *length = p - beg;
2876 return wtype;
2879 /* Construct the list of include directories
2880 from the arguments and the default list. */
2882 void
2883 construct_include_path (const char **arg_dirs)
2885 #ifdef VAXC /* just don't ask ... */
2886 stat_t stbuf;
2887 #else
2888 struct stat stbuf;
2889 #endif
2890 const char **dirs;
2891 const char **cpp;
2892 unsigned int idx;
2894 /* Compute the number of pointers we need in the table. */
2895 idx = sizeof (default_include_directories) / sizeof (const char *);
2896 if (arg_dirs)
2897 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2898 ++idx;
2900 #ifdef __MSDOS__
2901 /* Add one for $DJDIR. */
2902 ++idx;
2903 #endif
2905 dirs = xmalloc (idx * sizeof (const char *));
2907 idx = 0;
2908 max_incl_len = 0;
2910 /* First consider any dirs specified with -I switches.
2911 Ignore any that don't exist. Remember the maximum string length. */
2913 if (arg_dirs)
2914 while (*arg_dirs != 0)
2916 const char *dir = *(arg_dirs++);
2917 char *expanded = 0;
2918 int e;
2920 if (dir[0] == '~')
2922 expanded = tilde_expand (dir);
2923 if (expanded != 0)
2924 dir = expanded;
2927 EINTRLOOP (e, stat (dir, &stbuf));
2928 if (e == 0 && S_ISDIR (stbuf.st_mode))
2930 unsigned int len = strlen (dir);
2931 /* If dir name is written with trailing slashes, discard them. */
2932 while (len > 1 && dir[len - 1] == '/')
2933 --len;
2934 if (len > max_incl_len)
2935 max_incl_len = len;
2936 dirs[idx++] = strcache_add_len (dir, len);
2939 if (expanded)
2940 free (expanded);
2943 /* Now add the standard default dirs at the end. */
2945 #ifdef __MSDOS__
2947 /* The environment variable $DJDIR holds the root of the DJGPP directory
2948 tree; add ${DJDIR}/include. */
2949 struct variable *djdir = lookup_variable ("DJDIR", 5);
2951 if (djdir)
2953 unsigned int len = strlen (djdir->value) + 8;
2954 char *defdir = alloca (len + 1);
2956 strcat (strcpy (defdir, djdir->value), "/include");
2957 dirs[idx++] = strcache_add (defdir);
2959 if (len > max_incl_len)
2960 max_incl_len = len;
2963 #endif
2965 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2967 int e;
2969 EINTRLOOP (e, stat (*cpp, &stbuf));
2970 if (e == 0 && S_ISDIR (stbuf.st_mode))
2972 unsigned int len = strlen (*cpp);
2973 /* If dir name is written with trailing slashes, discard them. */
2974 while (len > 1 && (*cpp)[len - 1] == '/')
2975 --len;
2976 if (len > max_incl_len)
2977 max_incl_len = len;
2978 dirs[idx++] = strcache_add_len (*cpp, len);
2982 dirs[idx] = 0;
2984 /* Now add each dir to the .INCLUDE_DIRS variable. */
2986 for (cpp = dirs; *cpp != 0; ++cpp)
2987 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2988 o_default, f_append, 0);
2990 include_directories = dirs;
2993 /* Expand ~ or ~USER at the beginning of NAME.
2994 Return a newly malloc'd string or 0. */
2996 char *
2997 tilde_expand (const char *name)
2999 #ifndef VMS
3000 if (name[1] == '/' || name[1] == '\0')
3002 extern char *getenv ();
3003 char *home_dir;
3004 int is_variable;
3007 /* Turn off --warn-undefined-variables while we expand HOME. */
3008 int save = warn_undefined_variables_flag;
3009 warn_undefined_variables_flag = 0;
3011 home_dir = allocated_variable_expand ("$(HOME)");
3013 warn_undefined_variables_flag = save;
3016 is_variable = home_dir[0] != '\0';
3017 if (!is_variable)
3019 free (home_dir);
3020 home_dir = getenv ("HOME");
3022 # if !defined(_AMIGA) && !defined(WINDOWS32)
3023 if (home_dir == 0 || home_dir[0] == '\0')
3025 extern char *getlogin ();
3026 char *logname = getlogin ();
3027 home_dir = 0;
3028 if (logname != 0)
3030 struct passwd *p = getpwnam (logname);
3031 if (p != 0)
3032 home_dir = p->pw_dir;
3035 # endif /* !AMIGA && !WINDOWS32 */
3036 if (home_dir != 0)
3038 char *new = xstrdup (concat (home_dir, "", name + 1));
3039 if (is_variable)
3040 free (home_dir);
3041 return new;
3044 # if !defined(_AMIGA) && !defined(WINDOWS32)
3045 else
3047 struct passwd *pwent;
3048 char *userend = strchr (name + 1, '/');
3049 if (userend != 0)
3050 *userend = '\0';
3051 pwent = getpwnam (name + 1);
3052 if (pwent != 0)
3054 if (userend == 0)
3055 return xstrdup (pwent->pw_dir);
3056 else
3057 return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
3059 else if (userend != 0)
3060 *userend = '/';
3062 # endif /* !AMIGA && !WINDOWS32 */
3063 #endif /* !VMS */
3064 return 0;
3067 /* Given a chain of struct nameseq's describing a sequence of filenames,
3068 in reverse of the intended order, return a new chain describing the
3069 result of globbing the filenames. The new chain is in forward order.
3070 The links of the old chain are freed or used in the new chain.
3071 Likewise for the names in the old chain.
3073 SIZE is how big to construct chain elements.
3074 This is useful if we want them actually to be other structures
3075 that have room for additional info. */
3077 struct nameseq *
3078 multi_glob (struct nameseq *chain, unsigned int size)
3080 void dir_setup_glob (glob_t *);
3081 struct nameseq *new = 0;
3082 struct nameseq *old;
3083 struct nameseq *nexto;
3084 glob_t gl;
3086 dir_setup_glob (&gl);
3088 for (old = chain; old != 0; old = nexto)
3090 const char *gname;
3091 #ifndef NO_ARCHIVES
3092 char *arname = 0;
3093 char *memname = 0;
3094 #endif
3095 nexto = old->next;
3096 gname = old->name;
3098 if (gname[0] == '~')
3100 char *newname = tilde_expand (old->name);
3101 if (newname != 0)
3102 gname = newname;
3105 #ifndef NO_ARCHIVES
3106 if (ar_name (gname))
3108 /* OLD->name is an archive member reference. Replace it with the
3109 archive file name, and save the member name in MEMNAME. We will
3110 glob on the archive name and then reattach MEMNAME later. */
3111 ar_parse_name (gname, &arname, &memname);
3112 gname = arname;
3114 #endif /* !NO_ARCHIVES */
3116 switch (glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3118 case 0: /* Success. */
3120 int i = gl.gl_pathc;
3121 while (i-- > 0)
3123 #ifndef NO_ARCHIVES
3124 if (memname != 0)
3126 /* Try to glob on MEMNAME within the archive. */
3127 struct nameseq *found
3128 = ar_glob (gl.gl_pathv[i], memname, size);
3129 if (! found)
3131 /* No matches. Use MEMNAME as-is. */
3132 unsigned int alen = strlen (gl.gl_pathv[i]);
3133 unsigned int mlen = strlen (memname);
3134 char *name;
3135 struct nameseq *elt = xmalloc (size);
3136 memset (elt, '\0', size);
3138 name = alloca (alen + 1 + mlen + 2);
3139 memcpy (name, gl.gl_pathv[i], alen);
3140 name[alen] = '(';
3141 memcpy (name+alen+1, memname, mlen);
3142 name[alen + 1 + mlen] = ')';
3143 name[alen + 1 + mlen + 1] = '\0';
3144 elt->name = strcache_add (name);
3145 elt->next = new;
3146 new = elt;
3148 else
3150 /* Find the end of the FOUND chain. */
3151 struct nameseq *f = found;
3152 while (f->next != 0)
3153 f = f->next;
3155 /* Attach the chain being built to the end of the FOUND
3156 chain, and make FOUND the new NEW chain. */
3157 f->next = new;
3158 new = found;
3161 else
3162 #endif /* !NO_ARCHIVES */
3164 struct nameseq *elt = xmalloc (size);
3165 memset (elt, '\0', size);
3166 elt->name = strcache_add (gl.gl_pathv[i]);
3167 elt->next = new;
3168 new = elt;
3171 globfree (&gl);
3172 free (old);
3173 break;
3176 case GLOB_NOSPACE:
3177 fatal (NILF, _("virtual memory exhausted"));
3178 break;
3180 default:
3181 old->next = new;
3182 new = old;
3183 break;
3186 #ifndef NO_ARCHIVES
3187 if (arname)
3188 free (arname);
3189 #endif
3192 return new;