Portability fix for glob.h building in FreeBSD ports system.
[make.git] / read.c
bloba0bf5caa834e340e6c498ef159cd80bf855112f1
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 (char **makefiles)
152 unsigned int num_makefiles = 0;
154 /* Create *_LIST variables, to hold the makefiles, targets, and variables
155 we will be reading. */
157 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
159 DB (DB_BASIC, (_("Reading makefiles...\n")));
161 /* If there's a non-null variable MAKEFILES, its value is a list of
162 files to read first thing. But don't let it prevent reading the
163 default makefiles and don't let the default goal come from there. */
166 char *value;
167 char *name, *p;
168 unsigned int length;
171 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
172 int save = warn_undefined_variables_flag;
173 warn_undefined_variables_flag = 0;
175 value = allocated_variable_expand ("$(MAKEFILES)");
177 warn_undefined_variables_flag = save;
180 /* Set NAME to the start of next token and LENGTH to its length.
181 MAKEFILES is updated for finding remaining tokens. */
182 p = value;
184 while ((name = find_next_token (&p, &length)) != 0)
186 if (*p != '\0')
187 *p++ = '\0';
188 name = xstrdup (name);
189 if (eval_makefile (name,
190 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
191 free (name);
194 free (value);
197 /* Read makefiles specified with -f switches. */
199 if (makefiles != 0)
200 while (*makefiles != 0)
202 struct dep *tail = read_makefiles;
203 register struct dep *d;
205 if (! eval_makefile (*makefiles, 0))
206 perror_with_name ("", *makefiles);
208 /* Find the right element of read_makefiles. */
209 d = read_makefiles;
210 while (d->next != tail)
211 d = d->next;
213 /* Use the storage read_makefile allocates. */
214 *makefiles = dep_name (d);
215 ++num_makefiles;
216 ++makefiles;
219 /* If there were no -f switches, try the default names. */
221 if (num_makefiles == 0)
223 static char *default_makefiles[] =
224 #ifdef VMS
225 /* all lower case since readdir() (the vms version) 'lowercasifies' */
226 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
227 #else
228 #ifdef _AMIGA
229 { "GNUmakefile", "Makefile", "SMakefile", 0 };
230 #else /* !Amiga && !VMS */
231 { "GNUmakefile", "makefile", "Makefile", 0 };
232 #endif /* AMIGA */
233 #endif /* VMS */
234 register char **p = default_makefiles;
235 while (*p != 0 && !file_exists_p (*p))
236 ++p;
238 if (*p != 0)
240 if (! eval_makefile (*p, 0))
241 perror_with_name ("", *p);
243 else
245 /* No default makefile was found. Add the default makefiles to the
246 `read_makefiles' chain so they will be updated if possible. */
247 struct dep *tail = read_makefiles;
248 /* Add them to the tail, after any MAKEFILES variable makefiles. */
249 while (tail != 0 && tail->next != 0)
250 tail = tail->next;
251 for (p = default_makefiles; *p != 0; ++p)
253 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
254 d->name = 0;
255 d->file = enter_file (*p);
256 d->file->dontcare = 1;
257 d->ignore_mtime = 0;
258 /* Tell update_goal_chain to bail out as soon as this file is
259 made, and main not to die if we can't make this file. */
260 d->changed = RM_DONTCARE;
261 if (tail == 0)
262 read_makefiles = d;
263 else
264 tail->next = d;
265 tail = d;
267 if (tail != 0)
268 tail->next = 0;
272 return read_makefiles;
275 /* Install a new conditional and return the previous one. */
277 static struct conditionals *
278 install_conditionals (struct conditionals *new)
280 struct conditionals *save = conditionals;
282 bzero ((char *) new, sizeof (*new));
283 conditionals = new;
285 return save;
288 /* Free the current conditionals and reinstate a saved one. */
290 static void
291 restore_conditionals (struct conditionals *saved)
293 /* Free any space allocated by conditional_line. */
294 if (conditionals->ignoring)
295 free (conditionals->ignoring);
296 if (conditionals->seen_else)
297 free (conditionals->seen_else);
299 /* Restore state. */
300 conditionals = saved;
303 static int
304 eval_makefile (char *filename, int flags)
306 struct dep *deps;
307 struct ebuffer ebuf;
308 const struct floc *curfile;
309 int makefile_errno;
310 int r;
312 ebuf.floc.filenm = filename;
313 ebuf.floc.lineno = 1;
315 if (ISDB (DB_VERBOSE))
317 printf (_("Reading makefile `%s'"), filename);
318 if (flags & RM_NO_DEFAULT_GOAL)
319 printf (_(" (no default goal)"));
320 if (flags & RM_INCLUDED)
321 printf (_(" (search path)"));
322 if (flags & RM_DONTCARE)
323 printf (_(" (don't care)"));
324 if (flags & RM_NO_TILDE)
325 printf (_(" (no ~ expansion)"));
326 puts ("...");
329 /* First, get a stream to read. */
331 /* Expand ~ in FILENAME unless it came from `include',
332 in which case it was already done. */
333 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
335 char *expanded = tilde_expand (filename);
336 if (expanded != 0)
337 filename = expanded;
340 ebuf.fp = fopen (filename, "r");
341 /* Save the error code so we print the right message later. */
342 makefile_errno = errno;
344 /* If the makefile wasn't found and it's either a makefile from
345 the `MAKEFILES' variable or an included makefile,
346 search the included makefile search path for this makefile. */
347 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
349 register unsigned int i;
350 for (i = 0; include_directories[i] != 0; ++i)
352 char *name = concat (include_directories[i], "/", filename);
353 ebuf.fp = fopen (name, "r");
354 if (ebuf.fp == 0)
355 free (name);
356 else
358 filename = name;
359 break;
364 /* Add FILENAME to the chain of read makefiles. */
365 deps = (struct dep *) xmalloc (sizeof (struct dep));
366 deps->next = read_makefiles;
367 read_makefiles = deps;
368 deps->name = 0;
369 deps->file = lookup_file (filename);
370 if (deps->file == 0)
372 deps->file = enter_file (xstrdup (filename));
373 if (flags & RM_DONTCARE)
374 deps->file->dontcare = 1;
376 if (filename != ebuf.floc.filenm)
377 free (filename);
378 filename = deps->file->name;
379 deps->changed = flags;
380 deps->ignore_mtime = 0;
382 /* If the makefile can't be found at all, give up entirely. */
384 if (ebuf.fp == 0)
386 /* If we did some searching, errno has the error from the last
387 attempt, rather from FILENAME itself. Restore it in case the
388 caller wants to use it in a message. */
389 errno = makefile_errno;
390 return 0;
393 /* Add this makefile to the list. */
394 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
395 f_append, 0);
397 /* Evaluate the makefile */
399 ebuf.size = 200;
400 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
402 curfile = reading_file;
403 reading_file = &ebuf.floc;
405 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
407 reading_file = curfile;
409 fclose (ebuf.fp);
411 free (ebuf.bufstart);
412 return r;
416 eval_buffer (char *buffer)
418 struct ebuffer ebuf;
419 struct conditionals *saved;
420 struct conditionals new;
421 const struct floc *curfile;
422 int r;
424 /* Evaluate the buffer */
426 ebuf.size = strlen (buffer);
427 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
428 ebuf.fp = NULL;
430 ebuf.floc = *reading_file;
432 curfile = reading_file;
433 reading_file = &ebuf.floc;
435 saved = install_conditionals (&new);
437 r = eval (&ebuf, 1);
439 restore_conditionals (saved);
441 reading_file = curfile;
443 return r;
447 /* Read file FILENAME as a makefile and add its contents to the data base.
449 SET_DEFAULT is true if we are allowed to set the default goal. */
452 static int
453 eval (struct ebuffer *ebuf, int set_default)
455 static char *collapsed = 0;
456 static unsigned int collapsed_length = 0;
457 unsigned int commands_len = 200;
458 char *commands;
459 unsigned int commands_idx = 0;
460 unsigned int cmds_started, tgts_started;
461 int ignoring = 0, in_ignored_define = 0;
462 int no_targets = 0; /* Set when reading a rule without targets. */
463 int have_sysv_atvar = 0;
464 struct nameseq *filenames = 0;
465 struct dep *deps = 0;
466 long nlines = 0;
467 int two_colon = 0;
468 char *pattern = 0, *pattern_percent;
469 struct floc *fstart;
470 struct floc fi;
472 #define record_waiting_files() \
473 do \
475 if (filenames != 0) \
477 fi.lineno = tgts_started; \
478 record_files (filenames, pattern, pattern_percent, deps, \
479 cmds_started, commands, commands_idx, two_colon, \
480 have_sysv_atvar, &fi, set_default); \
482 filenames = 0; \
483 commands_idx = 0; \
484 no_targets = 0; \
485 if (pattern) { free(pattern); pattern = 0; } \
486 } while (0)
488 pattern_percent = 0;
489 cmds_started = tgts_started = 1;
491 fstart = &ebuf->floc;
492 fi.filenm = ebuf->floc.filenm;
494 /* Loop over lines in the file.
495 The strategy is to accumulate target names in FILENAMES, dependencies
496 in DEPS and commands in COMMANDS. These are used to define a rule
497 when the start of the next rule (or eof) is encountered.
499 When you see a "continue" in the loop below, that means we are moving on
500 to the next line _without_ ending any rule that we happen to be working
501 with at the moment. If you see a "goto rule_complete", then the
502 statement we just parsed also finishes the previous rule. */
504 commands = xmalloc (200);
506 while (1)
508 int linelen;
509 char *line;
510 int len;
511 char *p;
512 char *p2;
514 /* Grab the next line to be evaluated */
515 ebuf->floc.lineno += nlines;
516 nlines = readline (ebuf);
518 /* If there is nothing left to eval, we're done. */
519 if (nlines < 0)
520 break;
522 /* If this line is empty, skip it. */
523 line = ebuf->buffer;
524 if (line[0] == '\0')
525 continue;
527 linelen = strlen (line);
529 /* Check for a shell command line first.
530 If it is not one, we can stop treating tab specially. */
531 if (line[0] == '\t')
533 if (no_targets)
534 /* Ignore the commands in a rule with no targets. */
535 continue;
537 /* If there is no preceding rule line, don't treat this line
538 as a command, even though it begins with a tab character.
539 SunOS 4 make appears to behave this way. */
541 if (filenames != 0)
543 if (ignoring)
544 /* Yep, this is a shell command, and we don't care. */
545 continue;
547 /* Append this command line to the line being accumulated. */
548 if (commands_idx == 0)
549 cmds_started = ebuf->floc.lineno;
551 if (linelen + 1 + commands_idx > commands_len)
553 commands_len = (linelen + 1 + commands_idx) * 2;
554 commands = xrealloc (commands, commands_len);
556 bcopy (line, &commands[commands_idx], linelen);
557 commands_idx += linelen;
558 commands[commands_idx++] = '\n';
560 continue;
564 /* This line is not a shell command line. Don't worry about tabs. */
566 if (collapsed_length < linelen+1)
568 collapsed_length = linelen+1;
569 if (collapsed != 0)
570 free (collapsed);
571 collapsed = (char *) xmalloc (collapsed_length);
573 strcpy (collapsed, line);
574 /* Collapse continuation lines. */
575 collapse_continuations (collapsed);
576 remove_comments (collapsed);
578 /* Compare a word, both length and contents. */
579 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
580 p = collapsed;
581 while (isspace ((unsigned char)*p))
582 ++p;
584 if (*p == '\0')
585 /* This line is completely empty--ignore it. */
586 continue;
588 /* Find the end of the first token. Note we don't need to worry about
589 * ":" here since we compare tokens by length (so "export" will never
590 * be equal to "export:").
592 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
594 len = p2 - p;
596 /* Find the start of the second token. If it looks like a target or
597 variable definition it can't be a preprocessor token so skip
598 them--this allows variables/targets named `ifdef', `export', etc. */
599 while (isspace ((unsigned char)*p2))
600 ++p2;
602 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
604 /* It can't be a preprocessor token so skip it if we're ignoring */
605 if (ignoring)
606 continue;
608 goto skip_conditionals;
611 /* We must first check for conditional and `define' directives before
612 ignoring anything, since they control what we will do with
613 following lines. */
615 if (!in_ignored_define
616 && (word1eq ("ifdef") || word1eq ("ifndef")
617 || word1eq ("ifeq") || word1eq ("ifneq")
618 || word1eq ("else") || word1eq ("endif")))
620 int i = conditional_line (p, fstart);
621 if (i < 0)
622 fatal (fstart, _("invalid syntax in conditional"));
624 ignoring = i;
625 continue;
628 if (word1eq ("endef"))
630 if (!in_ignored_define)
631 fatal (fstart, _("extraneous `endef'"));
632 in_ignored_define = 0;
633 continue;
636 if (word1eq ("define"))
638 if (ignoring)
639 in_ignored_define = 1;
640 else
642 if (*p2 == '\0')
643 fatal (fstart, _("empty variable name"));
645 /* Let the variable name be the whole rest of the line,
646 with trailing blanks stripped (comments have already been
647 removed), so it could be a complex variable/function
648 reference that might contain blanks. */
649 p = strchr (p2, '\0');
650 while (isblank ((unsigned char)p[-1]))
651 --p;
652 do_define (p2, p - p2, o_file, ebuf);
654 continue;
657 if (word1eq ("override"))
659 if (*p2 == '\0')
660 error (fstart, _("empty `override' directive"));
662 if (strneq (p2, "define", 6)
663 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
665 if (ignoring)
666 in_ignored_define = 1;
667 else
669 p2 = next_token (p2 + 6);
670 if (*p2 == '\0')
671 fatal (fstart, _("empty variable name"));
673 /* Let the variable name be the whole rest of the line,
674 with trailing blanks stripped (comments have already been
675 removed), so it could be a complex variable/function
676 reference that might contain blanks. */
677 p = strchr (p2, '\0');
678 while (isblank ((unsigned char)p[-1]))
679 --p;
680 do_define (p2, p - p2, o_override, ebuf);
683 else if (!ignoring
684 && !try_variable_definition (fstart, p2, o_override, 0))
685 error (fstart, _("invalid `override' directive"));
687 continue;
690 if (ignoring)
691 /* Ignore the line. We continue here so conditionals
692 can appear in the middle of a rule. */
693 continue;
695 if (word1eq ("export"))
697 /* 'export' by itself causes everything to be exported. */
698 if (*p2 == '\0')
699 export_all_variables = 1;
700 else
702 struct variable *v;
704 v = try_variable_definition (fstart, p2, o_file, 0);
705 if (v != 0)
706 v->export = v_export;
707 else
709 unsigned int len;
710 char *ap;
712 /* Expand the line so we can use indirect and constructed
713 variable names in an export command. */
714 p2 = ap = allocated_variable_expand (p2);
716 for (p = find_next_token (&p2, &len); p != 0;
717 p = find_next_token (&p2, &len))
719 v = lookup_variable (p, len);
720 if (v == 0)
721 v = define_variable_loc (p, len, "", o_file, 0,
722 fstart);
723 v->export = v_export;
726 free (ap);
729 goto rule_complete;
732 if (word1eq ("unexport"))
734 if (*p2 == '\0')
735 export_all_variables = 0;
736 else
738 unsigned int len;
739 struct variable *v;
740 char *ap;
742 /* Expand the line so we can use indirect and constructed
743 variable names in an unexport command. */
744 p2 = ap = allocated_variable_expand (p2);
746 for (p = find_next_token (&p2, &len); p != 0;
747 p = find_next_token (&p2, &len))
749 v = lookup_variable (p, len);
750 if (v == 0)
751 v = define_variable_loc (p, len, "", o_file, 0, fstart);
753 v->export = v_noexport;
756 free (ap);
758 goto rule_complete;
761 skip_conditionals:
762 if (word1eq ("vpath"))
764 char *pattern;
765 unsigned int len;
766 p2 = variable_expand (p2);
767 p = find_next_token (&p2, &len);
768 if (p != 0)
770 pattern = savestring (p, len);
771 p = find_next_token (&p2, &len);
772 /* No searchpath means remove all previous
773 selective VPATH's with the same pattern. */
775 else
776 /* No pattern means remove all previous selective VPATH's. */
777 pattern = 0;
778 construct_vpath_list (pattern, p);
779 if (pattern != 0)
780 free (pattern);
782 goto rule_complete;
785 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
787 /* We have found an `include' line specifying a nested
788 makefile to be read at this point. */
789 struct conditionals *save;
790 struct conditionals new_conditionals;
791 struct nameseq *files;
792 /* "-include" (vs "include") says no error if the file does not
793 exist. "sinclude" is an alias for this from SGI. */
794 int noerror = (p[0] != 'i');
796 p = allocated_variable_expand (p2);
797 if (*p == '\0')
799 error (fstart,
800 _("no file name for `%sinclude'"), noerror ? "-" : "");
801 continue;
804 /* Parse the list of file names. */
805 p2 = p;
806 files = multi_glob (parse_file_seq (&p2, '\0',
807 sizeof (struct nameseq),
809 sizeof (struct nameseq));
810 free (p);
812 /* Save the state of conditionals and start
813 the included makefile with a clean slate. */
814 save = install_conditionals (&new_conditionals);
816 /* Record the rules that are waiting so they will determine
817 the default goal before those in the included makefile. */
818 record_waiting_files ();
820 /* Read each included makefile. */
821 while (files != 0)
823 struct nameseq *next = files->next;
824 char *name = files->name;
825 int r;
827 free ((char *)files);
828 files = next;
830 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
831 | (noerror ? RM_DONTCARE : 0)));
832 if (!r)
834 if (!noerror)
835 error (fstart, "%s: %s", name, strerror (errno));
836 free (name);
840 /* Restore conditional state. */
841 restore_conditionals (save);
843 goto rule_complete;
846 if (try_variable_definition (fstart, p, o_file, 0))
847 /* This line has been dealt with. */
848 goto rule_complete;
850 if (line[0] == '\t')
852 p = collapsed; /* Ignore comments, etc. */
853 while (isblank ((unsigned char)*p))
854 ++p;
855 if (*p == '\0')
856 /* The line is completely blank; that is harmless. */
857 continue;
859 /* This line starts with a tab but was not caught above
860 because there was no preceding target, and the line
861 might have been usable as a variable definition.
862 But now we know it is definitely lossage. */
863 fatal(fstart, _("commands commence before first target"));
866 /* This line describes some target files. This is complicated by
867 the existence of target-specific variables, because we can't
868 expand the entire line until we know if we have one or not. So
869 we expand the line word by word until we find the first `:',
870 then check to see if it's a target-specific variable.
872 In this algorithm, `lb_next' will point to the beginning of the
873 unexpanded parts of the input buffer, while `p2' points to the
874 parts of the expanded buffer we haven't searched yet. */
877 enum make_word_type wtype;
878 enum variable_origin v_origin;
879 int exported;
880 char *cmdleft, *semip, *lb_next;
881 unsigned int len, plen = 0;
882 char *colonp;
884 /* Record the previous rule. */
886 record_waiting_files ();
887 tgts_started = fstart->lineno;
889 /* Search the line for an unquoted ; that is not after an
890 unquoted #. */
891 cmdleft = find_char_unquote (line, ';', '#', 0);
892 if (cmdleft != 0 && *cmdleft == '#')
894 /* We found a comment before a semicolon. */
895 *cmdleft = '\0';
896 cmdleft = 0;
898 else if (cmdleft != 0)
899 /* Found one. Cut the line short there before expanding it. */
900 *(cmdleft++) = '\0';
901 semip = cmdleft;
903 collapse_continuations (line);
905 /* We can't expand the entire line, since if it's a per-target
906 variable we don't want to expand it. So, walk from the
907 beginning, expanding as we go, and looking for "interesting"
908 chars. The first word is always expandable. */
909 wtype = get_next_mword(line, NULL, &lb_next, &len);
910 switch (wtype)
912 case w_eol:
913 if (cmdleft != 0)
914 fatal(fstart, _("missing rule before commands"));
915 /* This line contained something but turned out to be nothing
916 but whitespace (a comment?). */
917 continue;
919 case w_colon:
920 case w_dcolon:
921 /* We accept and ignore rules without targets for
922 compatibility with SunOS 4 make. */
923 no_targets = 1;
924 continue;
926 default:
927 break;
930 p2 = variable_expand_string(NULL, lb_next, len);
931 while (1)
933 lb_next += len;
934 if (cmdleft == 0)
936 /* Look for a semicolon in the expanded line. */
937 cmdleft = find_char_unquote (p2, ';', 0, 0);
939 if (cmdleft != 0)
941 unsigned long p2_off = p2 - variable_buffer;
942 unsigned long cmd_off = cmdleft - variable_buffer;
943 char *pend = p2 + strlen(p2);
945 /* Append any remnants of lb, then cut the line short
946 at the semicolon. */
947 *cmdleft = '\0';
949 /* One school of thought says that you shouldn't expand
950 here, but merely copy, since now you're beyond a ";"
951 and into a command script. However, the old parser
952 expanded the whole line, so we continue that for
953 backwards-compatiblity. Also, it wouldn't be
954 entirely consistent, since we do an unconditional
955 expand below once we know we don't have a
956 target-specific variable. */
957 (void)variable_expand_string(pend, lb_next, (long)-1);
958 lb_next += strlen(lb_next);
959 p2 = variable_buffer + p2_off;
960 cmdleft = variable_buffer + cmd_off + 1;
964 colonp = find_char_unquote(p2, ':', 0, 0);
965 #ifdef HAVE_DOS_PATHS
966 /* The drive spec brain-damage strikes again... */
967 /* Note that the only separators of targets in this context
968 are whitespace and a left paren. If others are possible,
969 they should be added to the string in the call to index. */
970 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
971 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
972 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
973 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
974 #endif
975 if (colonp != 0)
976 break;
978 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
979 if (wtype == w_eol)
980 break;
982 p2 += strlen(p2);
983 *(p2++) = ' ';
984 p2 = variable_expand_string(p2, lb_next, len);
985 /* We don't need to worry about cmdleft here, because if it was
986 found in the variable_buffer the entire buffer has already
987 been expanded... we'll never get here. */
990 p2 = next_token (variable_buffer);
992 /* If the word we're looking at is EOL, see if there's _anything_
993 on the line. If not, a variable expanded to nothing, so ignore
994 it. If so, we can't parse this line so punt. */
995 if (wtype == w_eol)
997 if (*p2 != '\0')
998 /* There's no need to be ivory-tower about this: check for
999 one of the most common bugs found in makefiles... */
1000 fatal (fstart, _("missing separator%s"),
1001 !strneq(line, " ", 8) ? ""
1002 : _(" (did you mean TAB instead of 8 spaces?)"));
1003 continue;
1006 /* Make the colon the end-of-string so we know where to stop
1007 looking for targets. */
1008 *colonp = '\0';
1009 filenames = multi_glob (parse_file_seq (&p2, '\0',
1010 sizeof (struct nameseq),
1012 sizeof (struct nameseq));
1013 *p2 = ':';
1015 if (!filenames)
1017 /* We accept and ignore rules without targets for
1018 compatibility with SunOS 4 make. */
1019 no_targets = 1;
1020 continue;
1022 /* This should never be possible; we handled it above. */
1023 assert (*p2 != '\0');
1024 ++p2;
1026 /* Is this a one-colon or two-colon entry? */
1027 two_colon = *p2 == ':';
1028 if (two_colon)
1029 p2++;
1031 /* Test to see if it's a target-specific variable. Copy the rest
1032 of the buffer over, possibly temporarily (we'll expand it later
1033 if it's not a target-specific variable). PLEN saves the length
1034 of the unparsed section of p2, for later. */
1035 if (*lb_next != '\0')
1037 unsigned int l = p2 - variable_buffer;
1038 plen = strlen (p2);
1039 (void) variable_buffer_output (p2+plen,
1040 lb_next, strlen (lb_next)+1);
1041 p2 = variable_buffer + l;
1044 /* See if it's an "override" or "export" keyword; if so see if what
1045 comes after it looks like a variable definition. */
1047 wtype = get_next_mword (p2, NULL, &p, &len);
1049 v_origin = o_file;
1050 exported = 0;
1051 if (wtype == w_static)
1052 if (word1eq ("override"))
1054 v_origin = o_override;
1055 wtype = get_next_mword (p+len, NULL, &p, &len);
1057 else if (word1eq ("export"))
1059 exported = 1;
1060 wtype = get_next_mword (p+len, NULL, &p, &len);
1063 if (wtype != w_eol)
1064 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1066 if (wtype == w_varassign)
1068 /* If there was a semicolon found, add it back, plus anything
1069 after it. */
1070 if (semip)
1072 *(--semip) = ';';
1073 variable_buffer_output (p2 + strlen (p2),
1074 semip, strlen (semip)+1);
1076 record_target_var (filenames, p, two_colon, v_origin, exported,
1077 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);
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);
1100 if (cmdleft != 0)
1101 *(cmdleft++) = '\0';
1105 /* Do any of the prerequisites appear to have $@ etc.? */
1106 have_sysv_atvar = 0;
1107 if (!posix_pedantic)
1108 for (p = strchr (p2, '$'); p != 0; p = strchr (p+1, '$'))
1109 if (p[1] == '@' || ((p[1] == '(' || p[1] == '{') && p[2] == '@'))
1111 have_sysv_atvar = 1;
1112 break;
1115 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1116 p = strchr (p2, ':');
1117 while (p != 0 && p[-1] == '\\')
1119 register char *q = &p[-1];
1120 register int backslash = 0;
1121 while (*q-- == '\\')
1122 backslash = !backslash;
1123 if (backslash)
1124 p = strchr (p + 1, ':');
1125 else
1126 break;
1128 #ifdef _AMIGA
1129 /* Here, the situation is quite complicated. Let's have a look
1130 at a couple of targets:
1132 install: dev:make
1134 dev:make: make
1136 dev:make:: xyz
1138 The rule is that it's only a target, if there are TWO :'s
1139 OR a space around the :.
1141 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1142 || isspace ((unsigned char)p[-1])))
1143 p = 0;
1144 #endif
1145 #ifdef HAVE_DOS_PATHS
1147 int check_again;
1149 do {
1150 check_again = 0;
1151 /* For DOS paths, skip a "C:\..." or a "C:/..." */
1152 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1153 isalpha ((unsigned char)p[-1]) &&
1154 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1155 p = strchr (p + 1, ':');
1156 check_again = 1;
1158 } while (check_again);
1160 #endif
1161 if (p != 0)
1163 struct nameseq *target;
1164 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1165 ++p2;
1166 if (target == 0)
1167 fatal (fstart, _("missing target pattern"));
1168 else if (target->next != 0)
1169 fatal (fstart, _("multiple target patterns"));
1170 pattern = target->name;
1171 pattern_percent = find_percent (pattern);
1172 if (pattern_percent == 0)
1173 fatal (fstart, _("target pattern contains no `%%'"));
1174 free((char *)target);
1176 else
1177 pattern = 0;
1179 /* Parse the dependencies. */
1180 deps = (struct dep *)
1181 multi_glob (parse_file_seq (&p2, '|', sizeof (struct dep), 1),
1182 sizeof (struct dep));
1183 if (*p2)
1185 /* Files that follow '|' are special prerequisites that
1186 need only exist in order to satisfy the dependency.
1187 Their modification times are irrelevant. */
1188 struct dep **deps_ptr = &deps;
1189 struct dep *d;
1190 for (deps_ptr = &deps; *deps_ptr; deps_ptr = &(*deps_ptr)->next)
1192 ++p2;
1193 *deps_ptr = (struct dep *)
1194 multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
1195 sizeof (struct dep));
1196 for (d = *deps_ptr; d != 0; d = d->next)
1197 d->ignore_mtime = 1;
1200 commands_idx = 0;
1201 if (cmdleft != 0)
1203 /* Semicolon means rest of line is a command. */
1204 unsigned int len = strlen (cmdleft);
1206 cmds_started = fstart->lineno;
1208 /* Add this command line to the buffer. */
1209 if (len + 2 > commands_len)
1211 commands_len = (len + 2) * 2;
1212 commands = (char *) xrealloc (commands, commands_len);
1214 bcopy (cmdleft, commands, len);
1215 commands_idx += len;
1216 commands[commands_idx++] = '\n';
1219 continue;
1222 /* We get here except in the case that we just read a rule line.
1223 Record now the last rule we read, so following spurious
1224 commands are properly diagnosed. */
1225 rule_complete:
1226 record_waiting_files ();
1229 #undef word1eq
1231 if (conditionals->if_cmds)
1232 fatal (fstart, _("missing `endif'"));
1234 /* At eof, record the last rule. */
1235 record_waiting_files ();
1237 free ((char *) commands);
1239 return 1;
1243 /* Execute a `define' directive.
1244 The first line has already been read, and NAME is the name of
1245 the variable to be defined. The following lines remain to be read. */
1247 static void
1248 do_define (char *name, unsigned int namelen,
1249 enum variable_origin origin, struct ebuffer *ebuf)
1251 struct floc defstart;
1252 long nlines = 0;
1253 int nlevels = 1;
1254 unsigned int length = 100;
1255 char *definition = (char *) xmalloc (length);
1256 unsigned int idx = 0;
1257 char *p;
1259 /* Expand the variable name. */
1260 char *var = (char *) alloca (namelen + 1);
1261 bcopy (name, var, namelen);
1262 var[namelen] = '\0';
1263 var = variable_expand (var);
1265 defstart = ebuf->floc;
1267 while (1)
1269 unsigned int len;
1270 char *line;
1272 ebuf->floc.lineno += nlines;
1273 nlines = readline (ebuf);
1275 /* If there is nothing left to eval, we're done. */
1276 if (nlines < 0)
1277 break;
1279 line = ebuf->buffer;
1281 collapse_continuations (line);
1283 /* If the line doesn't begin with a tab, test to see if it introduces
1284 another define, or ends one. */
1286 /* Stop if we find an 'endef' */
1287 if (line[0] != '\t')
1289 p = next_token (line);
1290 len = strlen (p);
1292 /* If this is another 'define', increment the level count. */
1293 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1294 && strneq (p, "define", 6))
1295 ++nlevels;
1297 /* If this is an 'endef', decrement the count. If it's now 0,
1298 we've found the last one. */
1299 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1300 && strneq (p, "endef", 5))
1302 p += 5;
1303 remove_comments (p);
1304 if (*next_token (p) != '\0')
1305 error (&ebuf->floc,
1306 _("Extraneous text after `endef' directive"));
1308 if (--nlevels == 0)
1310 /* Define the variable. */
1311 if (idx == 0)
1312 definition[0] = '\0';
1313 else
1314 definition[idx - 1] = '\0';
1316 /* Always define these variables in the global set. */
1317 define_variable_global (var, strlen (var), definition,
1318 origin, 1, &defstart);
1319 free (definition);
1320 return;
1325 /* Otherwise add this line to the variable definition. */
1326 len = strlen (line);
1327 if (idx + len + 1 > length)
1329 length = (idx + len) * 2;
1330 definition = (char *) xrealloc (definition, length + 1);
1333 bcopy (line, &definition[idx], len);
1334 idx += len;
1335 /* Separate lines with a newline. */
1336 definition[idx++] = '\n';
1339 /* No `endef'!! */
1340 fatal (&defstart, _("missing `endef', unterminated `define'"));
1342 /* NOTREACHED */
1343 return;
1346 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1347 "ifneq", "else" and "endif".
1348 LINE is the input line, with the command as its first word.
1350 FILENAME and LINENO are the filename and line number in the
1351 current makefile. They are used for error messages.
1353 Value is -1 if the line is invalid,
1354 0 if following text should be interpreted,
1355 1 if following text should be ignored. */
1357 static int
1358 conditional_line (char *line, const struct floc *flocp)
1360 int notdef;
1361 char *cmdname;
1362 register unsigned int i;
1364 if (*line == 'i')
1366 /* It's an "if..." command. */
1367 notdef = line[2] == 'n';
1368 if (notdef)
1370 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1371 line += cmdname[3] == 'd' ? 7 : 6;
1373 else
1375 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1376 line += cmdname[2] == 'd' ? 6 : 5;
1379 else
1381 /* It's an "else" or "endif" command. */
1382 notdef = line[1] == 'n';
1383 cmdname = notdef ? "endif" : "else";
1384 line += notdef ? 5 : 4;
1387 line = next_token (line);
1389 if (*cmdname == 'e')
1391 if (*line != '\0')
1392 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1393 /* "Else" or "endif". */
1394 if (conditionals->if_cmds == 0)
1395 fatal (flocp, _("extraneous `%s'"), cmdname);
1396 /* NOTDEF indicates an `endif' command. */
1397 if (notdef)
1398 --conditionals->if_cmds;
1399 else if (conditionals->seen_else[conditionals->if_cmds - 1])
1400 fatal (flocp, _("only one `else' per conditional"));
1401 else
1403 /* Toggle the state of ignorance. */
1404 conditionals->ignoring[conditionals->if_cmds - 1]
1405 = !conditionals->ignoring[conditionals->if_cmds - 1];
1406 /* Record that we have seen an `else' in this conditional.
1407 A second `else' will be erroneous. */
1408 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1410 for (i = 0; i < conditionals->if_cmds; ++i)
1411 if (conditionals->ignoring[i])
1412 return 1;
1413 return 0;
1416 if (conditionals->allocated == 0)
1418 conditionals->allocated = 5;
1419 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1420 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1423 ++conditionals->if_cmds;
1424 if (conditionals->if_cmds > conditionals->allocated)
1426 conditionals->allocated += 5;
1427 conditionals->ignoring = (char *)
1428 xrealloc (conditionals->ignoring, conditionals->allocated);
1429 conditionals->seen_else = (char *)
1430 xrealloc (conditionals->seen_else, conditionals->allocated);
1433 /* Record that we have seen an `if...' but no `else' so far. */
1434 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1436 /* Search through the stack to see if we're already ignoring. */
1437 for (i = 0; i < conditionals->if_cmds - 1; ++i)
1438 if (conditionals->ignoring[i])
1440 /* We are already ignoring, so just push a level
1441 to match the next "else" or "endif", and keep ignoring.
1442 We don't want to expand variables in the condition. */
1443 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1444 return 1;
1447 if (cmdname[notdef ? 3 : 2] == 'd')
1449 /* "Ifdef" or "ifndef". */
1450 char *var;
1451 struct variable *v;
1452 register char *p = end_of_token (line);
1453 i = p - line;
1454 p = next_token (p);
1455 if (*p != '\0')
1456 return -1;
1458 /* Expand the thing we're looking up, so we can use indirect and
1459 constructed variable names. */
1460 line[i] = '\0';
1461 var = allocated_variable_expand (line);
1463 v = lookup_variable (var, strlen (var));
1464 conditionals->ignoring[conditionals->if_cmds - 1]
1465 = (v != 0 && *v->value != '\0') == notdef;
1467 free (var);
1469 else
1471 /* "Ifeq" or "ifneq". */
1472 char *s1, *s2;
1473 unsigned int len;
1474 char termin = *line == '(' ? ',' : *line;
1476 if (termin != ',' && termin != '"' && termin != '\'')
1477 return -1;
1479 s1 = ++line;
1480 /* Find the end of the first string. */
1481 if (termin == ',')
1483 register int count = 0;
1484 for (; *line != '\0'; ++line)
1485 if (*line == '(')
1486 ++count;
1487 else if (*line == ')')
1488 --count;
1489 else if (*line == ',' && count <= 0)
1490 break;
1492 else
1493 while (*line != '\0' && *line != termin)
1494 ++line;
1496 if (*line == '\0')
1497 return -1;
1499 if (termin == ',')
1501 /* Strip blanks after the first string. */
1502 char *p = line++;
1503 while (isblank ((unsigned char)p[-1]))
1504 --p;
1505 *p = '\0';
1507 else
1508 *line++ = '\0';
1510 s2 = variable_expand (s1);
1511 /* We must allocate a new copy of the expanded string because
1512 variable_expand re-uses the same buffer. */
1513 len = strlen (s2);
1514 s1 = (char *) alloca (len + 1);
1515 bcopy (s2, s1, len + 1);
1517 if (termin != ',')
1518 /* Find the start of the second string. */
1519 line = next_token (line);
1521 termin = termin == ',' ? ')' : *line;
1522 if (termin != ')' && termin != '"' && termin != '\'')
1523 return -1;
1525 /* Find the end of the second string. */
1526 if (termin == ')')
1528 register int count = 0;
1529 s2 = next_token (line);
1530 for (line = s2; *line != '\0'; ++line)
1532 if (*line == '(')
1533 ++count;
1534 else if (*line == ')')
1536 if (count <= 0)
1537 break;
1538 else
1539 --count;
1543 else
1545 ++line;
1546 s2 = line;
1547 while (*line != '\0' && *line != termin)
1548 ++line;
1551 if (*line == '\0')
1552 return -1;
1554 *line = '\0';
1555 line = next_token (++line);
1556 if (*line != '\0')
1557 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1559 s2 = variable_expand (s2);
1560 conditionals->ignoring[conditionals->if_cmds - 1]
1561 = streq (s1, s2) == notdef;
1564 /* Search through the stack to see if we're ignoring. */
1565 for (i = 0; i < conditionals->if_cmds; ++i)
1566 if (conditionals->ignoring[i])
1567 return 1;
1568 return 0;
1571 /* Remove duplicate dependencies in CHAIN. */
1573 static unsigned long
1574 dep_hash_1 (const void *key)
1576 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1579 static unsigned long
1580 dep_hash_2 (const void *key)
1582 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1585 static int
1586 dep_hash_cmp (const void *x, const void *y)
1588 struct dep *dx = (struct dep *) x;
1589 struct dep *dy = (struct dep *) y;
1590 int cmp = strcmp (dep_name (dx), dep_name (dy));
1592 /* If the names are the same but ignore_mtimes are not equal, one of these
1593 is an order-only prerequisite and one isn't. That means that we should
1594 remove the one that isn't and keep the one that is. */
1596 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1597 dx->ignore_mtime = dy->ignore_mtime = 0;
1599 return cmp;
1603 void
1604 uniquize_deps (struct dep *chain)
1606 struct hash_table deps;
1607 register struct dep **depp;
1609 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1611 /* Make sure that no dependencies are repeated. This does not
1612 really matter for the purpose of updating targets, but it
1613 might make some names be listed twice for $^ and $?. */
1615 depp = &chain;
1616 while (*depp)
1618 struct dep *dep = *depp;
1619 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1620 if (HASH_VACANT (*dep_slot))
1622 hash_insert_at (&deps, dep, dep_slot);
1623 depp = &dep->next;
1625 else
1627 /* Don't bother freeing duplicates.
1628 It's dangerous and little benefit accrues. */
1629 *depp = dep->next;
1633 hash_free (&deps, 0);
1636 /* Record target-specific variable values for files FILENAMES.
1637 TWO_COLON is nonzero if a double colon was used.
1639 The links of FILENAMES are freed, and so are any names in it
1640 that are not incorporated into other data structures.
1642 If the target is a pattern, add the variable to the pattern-specific
1643 variable value list. */
1645 static void
1646 record_target_var (struct nameseq *filenames, char *defn, int two_colon,
1647 enum variable_origin origin, int exported,
1648 const struct floc *flocp)
1650 struct nameseq *nextf;
1651 struct variable_set_list *global;
1653 global = current_variable_set_list;
1655 /* If the variable is an append version, store that but treat it as a
1656 normal recursive variable. */
1658 for (; filenames != 0; filenames = nextf)
1660 struct variable *v;
1661 register char *name = filenames->name;
1662 struct variable_set_list *vlist;
1663 char *fname;
1664 char *percent;
1666 nextf = filenames->next;
1667 free ((char *) filenames);
1669 /* If it's a pattern target, then add it to the pattern-specific
1670 variable list. */
1671 percent = find_percent (name);
1672 if (percent)
1674 struct pattern_var *p;
1676 /* Get a reference for this pattern-specific variable struct. */
1677 p = create_pattern_var(name, percent);
1678 vlist = p->vars;
1679 fname = p->target;
1681 else
1683 struct file *f;
1685 /* Get a file reference for this file, and initialize it.
1686 We don't want to just call enter_file() because that allocates a
1687 new entry if the file is a double-colon, which we don't want in
1688 this situation. */
1689 f = lookup_file (name);
1690 if (!f)
1691 f = enter_file (name);
1692 else if (f->double_colon)
1693 f = f->double_colon;
1695 initialize_file_variables (f, 1);
1696 vlist = f->variables;
1697 fname = f->name;
1700 /* Make the new variable context current and define the variable. */
1701 current_variable_set_list = vlist;
1702 v = try_variable_definition (flocp, defn, origin, 1);
1703 if (!v)
1704 error (flocp, _("Malformed per-target variable definition"));
1705 v->per_target = 1;
1706 if (exported)
1707 v->export = v_export;
1709 /* If it's not an override, check to see if there was a command-line
1710 setting. If so, reset the value. */
1711 if (origin != o_override)
1713 struct variable *gv;
1714 int len = strlen(v->name);
1716 current_variable_set_list = global;
1717 gv = lookup_variable (v->name, len);
1718 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1720 v = define_variable_in_set (v->name, len, gv->value, gv->origin,
1721 gv->recursive, vlist->set, flocp);
1722 v->append = 0;
1726 /* Free name if not needed further. */
1727 if (name != fname && (name < fname || name > fname + strlen (fname)))
1728 free (name);
1731 current_variable_set_list = global;
1734 /* Record a description line for files FILENAMES,
1735 with dependencies DEPS, commands to execute described
1736 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1737 TWO_COLON is nonzero if a double colon was used.
1738 If not nil, PATTERN is the `%' pattern to make this
1739 a static pattern rule, and PATTERN_PERCENT is a pointer
1740 to the `%' within it.
1742 The links of FILENAMES are freed, and so are any names in it
1743 that are not incorporated into other data structures. */
1745 static void
1746 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1747 struct dep *deps, unsigned int cmds_started, char *commands,
1748 unsigned int commands_idx, int two_colon,
1749 int have_sysv_atvar, const struct floc *flocp, int set_default)
1751 struct nameseq *nextf;
1752 int implicit = 0;
1753 unsigned int max_targets = 0, target_idx = 0;
1754 char **targets = 0, **target_percents = 0;
1755 struct commands *cmds;
1757 if (commands_idx > 0)
1759 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1760 cmds->fileinfo.filenm = flocp->filenm;
1761 cmds->fileinfo.lineno = cmds_started;
1762 cmds->commands = savestring (commands, commands_idx);
1763 cmds->command_lines = 0;
1765 else
1766 cmds = 0;
1768 for (; filenames != 0; filenames = nextf)
1770 char *name = filenames->name;
1771 struct file *f;
1772 struct dep *d;
1773 struct dep *this;
1774 char *implicit_percent;
1776 nextf = filenames->next;
1777 free (filenames);
1779 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1780 good enough: it doesn't happen until after the makefile is read,
1781 which means we cannot use its value during parsing. */
1783 if (streq (name, ".POSIX"))
1784 posix_pedantic = 1;
1786 implicit_percent = find_percent (name);
1787 implicit |= implicit_percent != 0;
1789 if (implicit && pattern != 0)
1790 fatal (flocp, _("mixed implicit and static pattern rules"));
1792 if (implicit && implicit_percent == 0)
1793 fatal (flocp, _("mixed implicit and normal rules"));
1795 if (implicit)
1797 if (targets == 0)
1799 max_targets = 5;
1800 targets = (char **) xmalloc (5 * sizeof (char *));
1801 target_percents = (char **) xmalloc (5 * sizeof (char *));
1802 target_idx = 0;
1804 else if (target_idx == max_targets - 1)
1806 max_targets += 5;
1807 targets = (char **) xrealloc ((char *) targets,
1808 max_targets * sizeof (char *));
1809 target_percents
1810 = (char **) xrealloc ((char *) target_percents,
1811 max_targets * sizeof (char *));
1813 targets[target_idx] = name;
1814 target_percents[target_idx] = implicit_percent;
1815 ++target_idx;
1816 continue;
1819 /* If there are multiple filenames, copy the chain DEPS
1820 for all but the last one. It is not safe for the same deps
1821 to go in more than one place in the data base. */
1822 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1824 if (pattern != 0)
1826 /* If this is an extended static rule:
1827 `targets: target%pattern: dep%pattern; cmds',
1828 translate each dependency pattern into a plain filename
1829 using the target pattern and this target's name. */
1830 if (!pattern_matches (pattern, pattern_percent, name))
1832 /* Give a warning if the rule is meaningless. */
1833 error (flocp,
1834 _("target `%s' doesn't match the target pattern"), name);
1835 this = 0;
1837 else
1839 /* We use patsubst_expand to do the work of translating
1840 the target pattern, the target's name and the dependencies'
1841 patterns into plain dependency names. */
1842 char *buffer = variable_expand ("");
1844 for (d = this; d != 0; d = d->next)
1846 char *o;
1847 char *percent = find_percent (d->name);
1848 if (percent == 0)
1849 continue;
1850 o = patsubst_expand (buffer, name, pattern, d->name,
1851 pattern_percent, percent);
1852 /* If the name expanded to the empty string, that's
1853 illegal. */
1854 if (o == buffer)
1855 fatal (flocp,
1856 _("target `%s' leaves prerequisite pattern empty"),
1857 name);
1858 free (d->name);
1859 d->name = savestring (buffer, o - buffer);
1864 /* If at least one of the dependencies uses $$@ etc. deal with that.
1865 It would be very nice and very simple to just expand everything, but
1866 it would break a lot of backward compatibility. Maybe that's OK
1867 since we're just emulating a SysV function, and if we do that then
1868 why not emulate it completely (that's what SysV make does: it
1869 re-expands the entire prerequisite list, all the time, with $@
1870 etc. in scope). But, it would be a pain indeed to document this
1871 ("iff you use $$@, your prerequisite lists is expanded twice...")
1872 Ouch. Maybe better to make the code more complex. */
1874 if (have_sysv_atvar)
1876 char *p;
1877 int tlen = strlen (name);
1878 char *fnp = strrchr (name, '/');
1879 int dlen;
1880 int flen;
1882 if (fnp)
1884 dlen = fnp - name;
1885 ++fnp;
1886 flen = strlen (fnp);
1888 else
1890 dlen = 0;
1891 fnp = name;
1892 flen = tlen;
1896 for (d = this; d != 0; d = d->next)
1897 for (p = strchr (d->name, '$'); p != 0; p = strchr (p+1, '$'))
1899 char *s = p;
1900 char *at;
1901 int atlen;
1903 /* If it's '$@', '$(@', or '${@', it's escaped */
1904 if ((++p)[0] == '$'
1905 && (p[1] == '@'
1906 || ((p[1] == '(' || p[1] == '{') && p[2] == '@')))
1908 bcopy (p, s, strlen (p)+1);
1909 continue;
1912 /* Maybe found one. We like anything of any form matching @,
1913 [({]@[}):], or [({]@[DF][}):]. */
1915 if (! (p[0] == '@'
1916 || ((p[0] == '(' || p[0] == '{') && (++p)[0] == '@'
1917 && (((++p)[0] == ')' || p[0] == '}' || p[0] == ':')
1918 || ((p[1] == ')' || p[1] == '}' || p[1] == ':')
1919 && (p[0] == 'D' || p[0] == 'F'))))))
1920 continue;
1922 /* Found one. Compute the length and string ptr. Move p
1923 past the variable reference. */
1924 switch (p[0])
1926 case 'D':
1927 atlen = dlen;
1928 at = name;
1929 p += 2;
1930 break;
1932 case 'F':
1933 atlen = flen;
1934 at = fnp;
1935 p += 2;
1936 break;
1938 default:
1939 atlen = tlen;
1940 at = name;
1941 ++p;
1942 break;
1945 /* Get more space. */
1947 int soff = s - d->name;
1948 int poff = p - d->name;
1949 d->name = (char *) xrealloc (d->name,
1950 strlen (d->name) + atlen + 1);
1951 s = d->name + soff;
1952 p = d->name + poff;
1955 /* Copy the string over. */
1956 bcopy(p, s+atlen, strlen (p)+1);
1957 bcopy(at, s, atlen);
1958 p = s + atlen - 1;
1962 if (!two_colon)
1964 /* Single-colon. Combine these dependencies
1965 with others in file's existing record, if any. */
1966 f = enter_file (name);
1968 if (f->double_colon)
1969 fatal (flocp,
1970 _("target file `%s' has both : and :: entries"), f->name);
1972 /* If CMDS == F->CMDS, this target was listed in this rule
1973 more than once. Just give a warning since this is harmless. */
1974 if (cmds != 0 && cmds == f->cmds)
1975 error (flocp,
1976 _("target `%s' given more than once in the same rule."),
1977 f->name);
1979 /* Check for two single-colon entries both with commands.
1980 Check is_target so that we don't lose on files such as .c.o
1981 whose commands were preinitialized. */
1982 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1984 error (&cmds->fileinfo,
1985 _("warning: overriding commands for target `%s'"),
1986 f->name);
1987 error (&f->cmds->fileinfo,
1988 _("warning: ignoring old commands for target `%s'"),
1989 f->name);
1992 f->is_target = 1;
1994 /* Defining .DEFAULT with no deps or cmds clears it. */
1995 if (f == default_file && this == 0 && cmds == 0)
1996 f->cmds = 0;
1997 if (cmds != 0)
1998 f->cmds = cmds;
1999 /* Defining .SUFFIXES with no dependencies
2000 clears out the list of suffixes. */
2001 if (f == suffix_file && this == 0)
2003 d = f->deps;
2004 while (d != 0)
2006 struct dep *nextd = d->next;
2007 free (d->name);
2008 free ((char *)d);
2009 d = nextd;
2011 f->deps = 0;
2013 else if (f->deps != 0)
2015 /* Add the file's old deps and the new ones in THIS together. */
2017 struct dep *firstdeps, *moredeps;
2018 if (cmds != 0)
2020 /* This is the rule with commands, so put its deps first.
2021 The rationale behind this is that $< expands to the
2022 first dep in the chain, and commands use $< expecting
2023 to get the dep that rule specifies. */
2024 firstdeps = this;
2025 moredeps = f->deps;
2027 else
2029 /* Append the new deps to the old ones. */
2030 firstdeps = f->deps;
2031 moredeps = this;
2034 if (firstdeps == 0)
2035 firstdeps = moredeps;
2036 else
2038 d = firstdeps;
2039 while (d->next != 0)
2040 d = d->next;
2041 d->next = moredeps;
2044 f->deps = firstdeps;
2046 else
2047 f->deps = this;
2049 /* If this is a static pattern rule, set the file's stem to
2050 the part of its name that matched the `%' in the pattern,
2051 so you can use $* in the commands. */
2052 if (pattern != 0)
2054 static char *percent = "%";
2055 char *buffer = variable_expand ("");
2056 char *o = patsubst_expand (buffer, name, pattern, percent,
2057 pattern_percent, percent);
2058 f->stem = savestring (buffer, o - buffer);
2061 else
2063 /* Double-colon. Make a new record
2064 even if the file already has one. */
2065 f = lookup_file (name);
2066 /* Check for both : and :: rules. Check is_target so
2067 we don't lose on default suffix rules or makefiles. */
2068 if (f != 0 && f->is_target && !f->double_colon)
2069 fatal (flocp,
2070 _("target file `%s' has both : and :: entries"), f->name);
2071 f = enter_file (name);
2072 /* If there was an existing entry and it was a double-colon
2073 entry, enter_file will have returned a new one, making it the
2074 prev pointer of the old one, and setting its double_colon
2075 pointer to the first one. */
2076 if (f->double_colon == 0)
2077 /* This is the first entry for this name, so we must
2078 set its double_colon pointer to itself. */
2079 f->double_colon = f;
2080 f->is_target = 1;
2081 f->deps = this;
2082 f->cmds = cmds;
2085 /* Free name if not needed further. */
2086 if (f != 0 && name != f->name
2087 && (name < f->name || name > f->name + strlen (f->name)))
2089 free (name);
2090 name = f->name;
2093 /* See if this is first target seen whose name does
2094 not start with a `.', unless it contains a slash. */
2095 if (default_goal_file == 0 && set_default
2096 && (*name != '.' || strchr (name, '/') != 0
2097 #ifdef HAVE_DOS_PATHS
2098 || strchr (name, '\\') != 0
2099 #endif
2102 int reject = 0;
2104 /* If this file is a suffix, don't
2105 let it be the default goal file. */
2107 for (d = suffix_file->deps; d != 0; d = d->next)
2109 register struct dep *d2;
2110 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
2112 reject = 1;
2113 break;
2115 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
2117 register unsigned int len = strlen (dep_name (d2));
2118 if (!strneq (name, dep_name (d2), len))
2119 continue;
2120 if (streq (name + len, dep_name (d)))
2122 reject = 1;
2123 break;
2126 if (reject)
2127 break;
2130 if (!reject)
2131 default_goal_file = f;
2135 if (implicit)
2137 targets[target_idx] = 0;
2138 target_percents[target_idx] = 0;
2139 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2140 free ((char *) target_percents);
2144 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2145 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2146 Quoting backslashes are removed from STRING by compacting it into
2147 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2148 one, or nil if there are none. */
2150 char *
2151 find_char_unquote (char *string, int stop1, int stop2, int blank)
2153 unsigned int string_len = 0;
2154 register char *p = string;
2156 while (1)
2158 if (stop2 && blank)
2159 while (*p != '\0' && *p != stop1 && *p != stop2
2160 && ! isblank ((unsigned char) *p))
2161 ++p;
2162 else if (stop2)
2163 while (*p != '\0' && *p != stop1 && *p != stop2)
2164 ++p;
2165 else if (blank)
2166 while (*p != '\0' && *p != stop1
2167 && ! isblank ((unsigned char) *p))
2168 ++p;
2169 else
2170 while (*p != '\0' && *p != stop1)
2171 ++p;
2173 if (*p == '\0')
2174 break;
2176 if (p > string && p[-1] == '\\')
2178 /* Search for more backslashes. */
2179 register int i = -2;
2180 while (&p[i] >= string && p[i] == '\\')
2181 --i;
2182 ++i;
2183 /* Only compute the length if really needed. */
2184 if (string_len == 0)
2185 string_len = strlen (string);
2186 /* The number of backslashes is now -I.
2187 Copy P over itself to swallow half of them. */
2188 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2189 p += i / 2;
2190 if (i % 2 == 0)
2191 /* All the backslashes quoted each other; the STOPCHAR was
2192 unquoted. */
2193 return p;
2195 /* The STOPCHAR was quoted by a backslash. Look for another. */
2197 else
2198 /* No backslash in sight. */
2199 return p;
2202 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2203 return 0;
2206 /* Search PATTERN for an unquoted %. */
2208 char *
2209 find_percent (char *pattern)
2211 return find_char_unquote (pattern, '%', 0, 0);
2214 /* Parse a string into a sequence of filenames represented as a
2215 chain of struct nameseq's in reverse order and return that chain.
2217 The string is passed as STRINGP, the address of a string pointer.
2218 The string pointer is updated to point at the first character
2219 not parsed, which either is a null char or equals STOPCHAR.
2221 SIZE is how big to construct chain elements.
2222 This is useful if we want them actually to be other structures
2223 that have room for additional info.
2225 If STRIP is nonzero, strip `./'s off the beginning. */
2227 struct nameseq *
2228 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2230 register struct nameseq *new = 0;
2231 register struct nameseq *new1, *lastnew1;
2232 register char *p = *stringp;
2233 char *q;
2234 char *name;
2236 #ifdef VMS
2237 # define VMS_COMMA ','
2238 #else
2239 # define VMS_COMMA 0
2240 #endif
2242 while (1)
2244 /* Skip whitespace; see if any more names are left. */
2245 p = next_token (p);
2246 if (*p == '\0')
2247 break;
2248 if (*p == stopchar)
2249 break;
2251 /* Yes, find end of next name. */
2252 q = p;
2253 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2254 #ifdef VMS
2255 /* convert comma separated list to space separated */
2256 if (p && *p == ',')
2257 *p =' ';
2258 #endif
2259 #ifdef _AMIGA
2260 if (stopchar == ':' && p && *p == ':'
2261 && !(isspace ((unsigned char)p[1]) || !p[1]
2262 || isspace ((unsigned char)p[-1])))
2264 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2266 #endif
2267 #ifdef HAVE_DOS_PATHS
2268 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2269 first colon which isn't followed by a slash or a backslash.
2270 Note that tokens separated by spaces should be treated as separate
2271 tokens since make doesn't allow path names with spaces */
2272 if (stopchar == ':')
2273 while (p != 0 && !isspace ((unsigned char)*p) &&
2274 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2275 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2276 #endif
2277 if (p == 0)
2278 p = q + strlen (q);
2280 if (strip)
2281 #ifdef VMS
2282 /* Skip leading `[]'s. */
2283 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2284 #else
2285 /* Skip leading `./'s. */
2286 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2287 #endif
2289 q += 2; /* Skip "./". */
2290 while (q < p && *q == '/')
2291 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2292 ++q;
2295 /* Extract the filename just found, and skip it. */
2297 if (q == p)
2298 /* ".///" was stripped to "". */
2299 #ifdef VMS
2300 continue;
2301 #else
2302 #ifdef _AMIGA
2303 name = savestring ("", 0);
2304 #else
2305 name = savestring ("./", 2);
2306 #endif
2307 #endif
2308 else
2309 #ifdef VMS
2310 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2311 * to remove this '\' before we can use the filename.
2312 * Savestring called because q may be read-only string constant.
2315 char *qbase = xstrdup (q);
2316 char *pbase = qbase + (p-q);
2317 char *q1 = qbase;
2318 char *q2 = q1;
2319 char *p1 = pbase;
2321 while (q1 != pbase)
2323 if (*q1 == '\\' && *(q1+1) == ':')
2325 q1++;
2326 p1--;
2328 *q2++ = *q1++;
2330 name = savestring (qbase, p1 - qbase);
2331 free (qbase);
2333 #else
2334 name = savestring (q, p - q);
2335 #endif
2337 /* Add it to the front of the chain. */
2338 new1 = (struct nameseq *) xmalloc (size);
2339 new1->name = name;
2340 new1->next = new;
2341 new = new1;
2344 #ifndef NO_ARCHIVES
2346 /* Look for multi-word archive references.
2347 They are indicated by a elt ending with an unmatched `)' and
2348 an elt further down the chain (i.e., previous in the file list)
2349 with an unmatched `(' (e.g., "lib(mem"). */
2351 new1 = new;
2352 lastnew1 = 0;
2353 while (new1 != 0)
2354 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2355 && new1->name[strlen (new1->name) - 1] == ')'
2356 && strchr (new1->name, '(') == 0)
2358 /* NEW1 ends with a `)' but does not contain a `('.
2359 Look back for an elt with an opening `(' but no closing `)'. */
2361 struct nameseq *n = new1->next, *lastn = new1;
2362 char *paren = 0;
2363 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2365 lastn = n;
2366 n = n->next;
2368 if (n != 0
2369 /* Ignore something starting with `(', as that cannot actually
2370 be an archive-member reference (and treating it as such
2371 results in an empty file name, which causes much lossage). */
2372 && n->name[0] != '(')
2374 /* N is the first element in the archive group.
2375 Its name looks like "lib(mem" (with no closing `)'). */
2377 char *libname;
2379 /* Copy "lib(" into LIBNAME. */
2380 ++paren;
2381 libname = (char *) alloca (paren - n->name + 1);
2382 bcopy (n->name, libname, paren - n->name);
2383 libname[paren - n->name] = '\0';
2385 if (*paren == '\0')
2387 /* N was just "lib(", part of something like "lib( a b)".
2388 Edit it out of the chain and free its storage. */
2389 lastn->next = n->next;
2390 free (n->name);
2391 free ((char *) n);
2392 /* LASTN->next is the new stopping elt for the loop below. */
2393 n = lastn->next;
2395 else
2397 /* Replace N's name with the full archive reference. */
2398 name = concat (libname, paren, ")");
2399 free (n->name);
2400 n->name = name;
2403 if (new1->name[1] == '\0')
2405 /* NEW1 is just ")", part of something like "lib(a b )".
2406 Omit it from the chain and free its storage. */
2407 if (lastnew1 == 0)
2408 new = new1->next;
2409 else
2410 lastnew1->next = new1->next;
2411 lastn = new1;
2412 new1 = new1->next;
2413 free (lastn->name);
2414 free ((char *) lastn);
2416 else
2418 /* Replace also NEW1->name, which already has closing `)'. */
2419 name = concat (libname, new1->name, "");
2420 free (new1->name);
2421 new1->name = name;
2422 new1 = new1->next;
2425 /* Trace back from NEW1 (the end of the list) until N
2426 (the beginning of the list), rewriting each name
2427 with the full archive reference. */
2429 while (new1 != n)
2431 name = concat (libname, new1->name, ")");
2432 free (new1->name);
2433 new1->name = name;
2434 lastnew1 = new1;
2435 new1 = new1->next;
2438 else
2440 /* No frobnication happening. Just step down the list. */
2441 lastnew1 = new1;
2442 new1 = new1->next;
2445 else
2447 lastnew1 = new1;
2448 new1 = new1->next;
2451 #endif
2453 *stringp = p;
2454 return new;
2457 /* Find the next line of text in an eval buffer, combining continuation lines
2458 into one line.
2459 Return the number of actual lines read (> 1 if continuation lines).
2460 Returns -1 if there's nothing left in the buffer.
2462 After this function, ebuf->buffer points to the first character of the
2463 line we just found.
2466 /* Read a line of text from a STRING.
2467 Since we aren't really reading from a file, don't bother with linenumbers.
2470 static unsigned long
2471 readstring (struct ebuffer *ebuf)
2473 char *p;
2475 /* If there is nothing left in this buffer, return 0. */
2476 if (ebuf->bufnext > ebuf->bufstart + ebuf->size)
2477 return -1;
2479 /* Set up a new starting point for the buffer, and find the end of the
2480 next logical line (taking into account backslash/newline pairs). */
2482 p = ebuf->buffer = ebuf->bufnext;
2484 while (1)
2486 int backslash = 0;
2488 /* Find the next newline. Keep track of backslashes as we look. */
2489 for (; *p != '\n' && *p != '\0'; ++p)
2490 if (*p == '\\')
2491 backslash = !backslash;
2493 /* If we got to the end of the string or a newline with no backslash,
2494 we're done. */
2495 if (*p == '\0' || !backslash)
2496 break;
2499 /* Overwrite the newline char. */
2500 *p = '\0';
2501 ebuf->bufnext = p+1;
2503 return 0;
2506 static long
2507 readline (struct ebuffer *ebuf)
2509 char *p;
2510 char *end;
2511 char *start;
2512 long nlines = 0;
2514 /* The behaviors between string and stream buffers are different enough to
2515 warrant different functions. Do the Right Thing. */
2517 if (!ebuf->fp)
2518 return readstring (ebuf);
2520 /* When reading from a file, we always start over at the beginning of the
2521 buffer for each new line. */
2523 p = start = ebuf->bufstart;
2524 end = p + ebuf->size;
2525 *p = '\0';
2527 while (fgets (p, end - p, ebuf->fp) != 0)
2529 char *p2;
2530 unsigned long len;
2531 int backslash;
2533 len = strlen (p);
2534 if (len == 0)
2536 /* This only happens when the first thing on the line is a '\0'.
2537 It is a pretty hopeless case, but (wonder of wonders) Athena
2538 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2539 There is nothing really to be done; we synthesize a newline so
2540 the following line doesn't appear to be part of this line. */
2541 error (&ebuf->floc,
2542 _("warning: NUL character seen; rest of line ignored"));
2543 p[0] = '\n';
2544 len = 1;
2547 /* Jump past the text we just read. */
2548 p += len;
2550 /* If the last char isn't a newline, the whole line didn't fit into the
2551 buffer. Get some more buffer and try again. */
2552 if (p[-1] != '\n')
2553 goto more_buffer;
2555 /* We got a newline, so add one to the count of lines. */
2556 ++nlines;
2558 #if !defined(WINDOWS32) && !defined(__MSDOS__)
2559 /* Check to see if the line was really ended with CRLF; if so ignore
2560 the CR. */
2561 if ((p - start) > 1 && p[-2] == '\r')
2563 --p;
2564 p[-1] = '\n';
2566 #endif
2568 backslash = 0;
2569 for (p2 = p - 2; p2 >= start; --p2)
2571 if (*p2 != '\\')
2572 break;
2573 backslash = !backslash;
2576 if (!backslash)
2578 p[-1] = '\0';
2579 break;
2582 /* It was a backslash/newline combo. If we have more space, read
2583 another line. */
2584 if (end - p >= 80)
2585 continue;
2587 /* We need more space at the end of our buffer, so realloc it.
2588 Make sure to preserve the current offset of p. */
2589 more_buffer:
2591 unsigned long off = p - start;
2592 ebuf->size *= 2;
2593 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2594 ebuf->size);
2595 p = start + off;
2596 end = start + ebuf->size;
2597 *p = '\0';
2601 if (ferror (ebuf->fp))
2602 pfatal_with_name (ebuf->floc.filenm);
2604 /* If we found some lines, return how many.
2605 If we didn't, but we did find _something_, that indicates we read the last
2606 line of a file with no final newline; return 1.
2607 If we read nothing, we're at EOF; return -1. */
2609 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2612 /* Parse the next "makefile word" from the input buffer, and return info
2613 about it.
2615 A "makefile word" is one of:
2617 w_bogus Should never happen
2618 w_eol End of input
2619 w_static A static word; cannot be expanded
2620 w_variable A word containing one or more variables/functions
2621 w_colon A colon
2622 w_dcolon A double-colon
2623 w_semicolon A semicolon
2624 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2626 Note that this function is only used when reading certain parts of the
2627 makefile. Don't use it where special rules hold sway (RHS of a variable,
2628 in a command list, etc.) */
2630 static enum make_word_type
2631 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2633 enum make_word_type wtype = w_bogus;
2634 char *p = buffer, *beg;
2635 char c;
2637 /* Skip any leading whitespace. */
2638 while (isblank ((unsigned char)*p))
2639 ++p;
2641 beg = p;
2642 c = *(p++);
2643 switch (c)
2645 case '\0':
2646 wtype = w_eol;
2647 break;
2649 case ';':
2650 wtype = w_semicolon;
2651 break;
2653 case '=':
2654 wtype = w_varassign;
2655 break;
2657 case ':':
2658 wtype = w_colon;
2659 switch (*p)
2661 case ':':
2662 ++p;
2663 wtype = w_dcolon;
2664 break;
2666 case '=':
2667 ++p;
2668 wtype = w_varassign;
2669 break;
2671 break;
2673 case '+':
2674 case '?':
2675 if (*p == '=')
2677 ++p;
2678 wtype = w_varassign;
2679 break;
2682 default:
2683 if (delim && strchr (delim, c))
2684 wtype = w_static;
2685 break;
2688 /* Did we find something? If so, return now. */
2689 if (wtype != w_bogus)
2690 goto done;
2692 /* This is some non-operator word. A word consists of the longest
2693 string of characters that doesn't contain whitespace, one of [:=#],
2694 or [?+]=, or one of the chars in the DELIM string. */
2696 /* We start out assuming a static word; if we see a variable we'll
2697 adjust our assumptions then. */
2698 wtype = w_static;
2700 /* We already found the first value of "c", above. */
2701 while (1)
2703 char closeparen;
2704 int count;
2706 switch (c)
2708 case '\0':
2709 case ' ':
2710 case '\t':
2711 case '=':
2712 goto done_word;
2714 case ':':
2715 #ifdef HAVE_DOS_PATHS
2716 /* A word CAN include a colon in its drive spec. The drive
2717 spec is allowed either at the beginning of a word, or as part
2718 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2719 if (!(p - beg >= 2
2720 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2721 && (p - beg == 2 || p[-3] == '(')))
2722 #endif
2723 goto done_word;
2725 case '$':
2726 c = *(p++);
2727 if (c == '$')
2728 break;
2730 /* This is a variable reference, so note that it's expandable.
2731 Then read it to the matching close paren. */
2732 wtype = w_variable;
2734 if (c == '(')
2735 closeparen = ')';
2736 else if (c == '{')
2737 closeparen = '}';
2738 else
2739 /* This is a single-letter variable reference. */
2740 break;
2742 for (count=0; *p != '\0'; ++p)
2744 if (*p == c)
2745 ++count;
2746 else if (*p == closeparen && --count < 0)
2748 ++p;
2749 break;
2752 break;
2754 case '?':
2755 case '+':
2756 if (*p == '=')
2757 goto done_word;
2758 break;
2760 case '\\':
2761 switch (*p)
2763 case ':':
2764 case ';':
2765 case '=':
2766 case '\\':
2767 ++p;
2768 break;
2770 break;
2772 default:
2773 if (delim && strchr (delim, c))
2774 goto done_word;
2775 break;
2778 c = *(p++);
2780 done_word:
2781 --p;
2783 done:
2784 if (startp)
2785 *startp = beg;
2786 if (length)
2787 *length = p - beg;
2788 return wtype;
2791 /* Construct the list of include directories
2792 from the arguments and the default list. */
2794 void
2795 construct_include_path (char **arg_dirs)
2797 register unsigned int i;
2798 #ifdef VAXC /* just don't ask ... */
2799 stat_t stbuf;
2800 #else
2801 struct stat stbuf;
2802 #endif
2803 /* Table to hold the dirs. */
2805 register unsigned int defsize = (sizeof (default_include_directories)
2806 / sizeof (default_include_directories[0]));
2807 register unsigned int max = 5;
2808 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2809 register unsigned int idx = 0;
2811 #ifdef __MSDOS__
2812 defsize++;
2813 #endif
2815 /* First consider any dirs specified with -I switches.
2816 Ignore dirs that don't exist. */
2818 if (arg_dirs != 0)
2819 while (*arg_dirs != 0)
2821 char *dir = *arg_dirs++;
2822 int e;
2824 if (dir[0] == '~')
2826 char *expanded = tilde_expand (dir);
2827 if (expanded != 0)
2828 dir = expanded;
2831 EINTRLOOP (e, stat (dir, &stbuf));
2832 if (e == 0 && S_ISDIR (stbuf.st_mode))
2834 if (idx == max - 1)
2836 max += 5;
2837 dirs = (char **)
2838 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2840 dirs[idx++] = dir;
2842 else if (dir != arg_dirs[-1])
2843 free (dir);
2846 /* Now add at the end the standard default dirs. */
2848 #ifdef __MSDOS__
2850 /* The environment variable $DJDIR holds the root of the
2851 DJGPP directory tree; add ${DJDIR}/include. */
2852 struct variable *djdir = lookup_variable ("DJDIR", 5);
2854 if (djdir)
2856 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2858 strcat (strcpy (defdir, djdir->value), "/include");
2859 dirs[idx++] = defdir;
2862 #endif
2864 for (i = 0; default_include_directories[i] != 0; ++i)
2866 int e;
2868 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2869 if (e == 0 && S_ISDIR (stbuf.st_mode))
2870 dirs[idx++] = default_include_directories[i];
2873 dirs[idx] = 0;
2875 /* Now compute the maximum length of any name in it. */
2877 max_incl_len = 0;
2878 for (i = 0; i < idx; ++i)
2880 unsigned int len = strlen (dirs[i]);
2881 /* If dir name is written with a trailing slash, discard it. */
2882 if (dirs[i][len - 1] == '/')
2883 /* We can't just clobber a null in because it may have come from
2884 a literal string and literal strings may not be writable. */
2885 dirs[i] = savestring (dirs[i], len - 1);
2886 if (len > max_incl_len)
2887 max_incl_len = len;
2890 include_directories = dirs;
2893 /* Expand ~ or ~USER at the beginning of NAME.
2894 Return a newly malloc'd string or 0. */
2896 char *
2897 tilde_expand (char *name)
2899 #ifndef VMS
2900 if (name[1] == '/' || name[1] == '\0')
2902 extern char *getenv ();
2903 char *home_dir;
2904 int is_variable;
2907 /* Turn off --warn-undefined-variables while we expand HOME. */
2908 int save = warn_undefined_variables_flag;
2909 warn_undefined_variables_flag = 0;
2911 home_dir = allocated_variable_expand ("$(HOME)");
2913 warn_undefined_variables_flag = save;
2916 is_variable = home_dir[0] != '\0';
2917 if (!is_variable)
2919 free (home_dir);
2920 home_dir = getenv ("HOME");
2922 #if !defined(_AMIGA) && !defined(WINDOWS32)
2923 if (home_dir == 0 || home_dir[0] == '\0')
2925 extern char *getlogin ();
2926 char *logname = getlogin ();
2927 home_dir = 0;
2928 if (logname != 0)
2930 struct passwd *p = getpwnam (logname);
2931 if (p != 0)
2932 home_dir = p->pw_dir;
2935 #endif /* !AMIGA && !WINDOWS32 */
2936 if (home_dir != 0)
2938 char *new = concat (home_dir, "", name + 1);
2939 if (is_variable)
2940 free (home_dir);
2941 return new;
2944 #if !defined(_AMIGA) && !defined(WINDOWS32)
2945 else
2947 struct passwd *pwent;
2948 char *userend = strchr (name + 1, '/');
2949 if (userend != 0)
2950 *userend = '\0';
2951 pwent = getpwnam (name + 1);
2952 if (pwent != 0)
2954 if (userend == 0)
2955 return xstrdup (pwent->pw_dir);
2956 else
2957 return concat (pwent->pw_dir, "/", userend + 1);
2959 else if (userend != 0)
2960 *userend = '/';
2962 #endif /* !AMIGA && !WINDOWS32 */
2963 #endif /* !VMS */
2964 return 0;
2967 /* Given a chain of struct nameseq's describing a sequence of filenames,
2968 in reverse of the intended order, return a new chain describing the
2969 result of globbing the filenames. The new chain is in forward order.
2970 The links of the old chain are freed or used in the new chain.
2971 Likewise for the names in the old chain.
2973 SIZE is how big to construct chain elements.
2974 This is useful if we want them actually to be other structures
2975 that have room for additional info. */
2977 struct nameseq *
2978 multi_glob (struct nameseq *chain, unsigned int size)
2980 extern void dir_setup_glob ();
2981 register struct nameseq *new = 0;
2982 register struct nameseq *old;
2983 struct nameseq *nexto;
2984 glob_t gl;
2986 dir_setup_glob (&gl);
2988 for (old = chain; old != 0; old = nexto)
2990 #ifndef NO_ARCHIVES
2991 char *memname;
2992 #endif
2994 nexto = old->next;
2996 if (old->name[0] == '~')
2998 char *newname = tilde_expand (old->name);
2999 if (newname != 0)
3001 free (old->name);
3002 old->name = newname;
3006 #ifndef NO_ARCHIVES
3007 if (ar_name (old->name))
3009 /* OLD->name is an archive member reference.
3010 Replace it with the archive file name,
3011 and save the member name in MEMNAME.
3012 We will glob on the archive name and then
3013 reattach MEMNAME later. */
3014 char *arname;
3015 ar_parse_name (old->name, &arname, &memname);
3016 free (old->name);
3017 old->name = arname;
3019 else
3020 memname = 0;
3021 #endif /* !NO_ARCHIVES */
3023 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3025 case 0: /* Success. */
3027 register int i = gl.gl_pathc;
3028 while (i-- > 0)
3030 #ifndef NO_ARCHIVES
3031 if (memname != 0)
3033 /* Try to glob on MEMNAME within the archive. */
3034 struct nameseq *found
3035 = ar_glob (gl.gl_pathv[i], memname, size);
3036 if (found == 0)
3038 /* No matches. Use MEMNAME as-is. */
3039 unsigned int alen = strlen (gl.gl_pathv[i]);
3040 unsigned int mlen = strlen (memname);
3041 struct nameseq *elt
3042 = (struct nameseq *) xmalloc (size);
3043 if (size > sizeof (struct nameseq))
3044 bzero (((char *) elt) + sizeof (struct nameseq),
3045 size - sizeof (struct nameseq));
3046 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3047 bcopy (gl.gl_pathv[i], elt->name, alen);
3048 elt->name[alen] = '(';
3049 bcopy (memname, &elt->name[alen + 1], mlen);
3050 elt->name[alen + 1 + mlen] = ')';
3051 elt->name[alen + 1 + mlen + 1] = '\0';
3052 elt->next = new;
3053 new = elt;
3055 else
3057 /* Find the end of the FOUND chain. */
3058 struct nameseq *f = found;
3059 while (f->next != 0)
3060 f = f->next;
3062 /* Attach the chain being built to the end of the FOUND
3063 chain, and make FOUND the new NEW chain. */
3064 f->next = new;
3065 new = found;
3068 free (memname);
3070 else
3071 #endif /* !NO_ARCHIVES */
3073 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3074 if (size > sizeof (struct nameseq))
3075 bzero (((char *) elt) + sizeof (struct nameseq),
3076 size - sizeof (struct nameseq));
3077 elt->name = xstrdup (gl.gl_pathv[i]);
3078 elt->next = new;
3079 new = elt;
3082 globfree (&gl);
3083 free (old->name);
3084 free ((char *)old);
3085 break;
3088 case GLOB_NOSPACE:
3089 fatal (NILF, _("virtual memory exhausted"));
3090 break;
3092 default:
3093 old->next = new;
3094 new = old;
3095 break;
3099 return new;