Fix for the problem that SDL applications exited
[AROS-Contrib.git] / gnu / make / read.c
blob4dd732deedfbd76cad19db1b4daaa8287b6947ce
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
23 #include <assert.h>
25 #include <glob.h>
27 #include "dep.h"
28 #include "filedef.h"
29 #include "job.h"
30 #include "commands.h"
31 #include "variable.h"
32 #include "rule.h"
33 #include "debug.h"
34 #include "hash.h"
37 #ifndef WINDOWS32
38 #ifndef _AMIGA
39 #ifndef VMS
40 #include <pwd.h>
41 #else
42 struct passwd *getpwnam PARAMS ((char *name));
43 #endif
44 #endif
45 #endif /* !WINDOWS32 */
47 /* A 'struct ebuffer' controls the origin of the makefile we are currently
48 eval'ing.
51 struct ebuffer
53 char *buffer; /* Start of the current line in the buffer. */
54 char *bufnext; /* Start of the next line in the buffer. */
55 char *bufstart; /* Start of the entire buffer. */
56 unsigned int size; /* Malloc'd size of buffer. */
57 FILE *fp; /* File, or NULL if this is an internal buffer. */
58 struct floc floc; /* Info on the file in fp (if any). */
61 /* Types of "words" that can be read in a makefile. */
62 enum make_word_type
64 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
65 w_varassign
69 /* A `struct conditionals' contains the information describing
70 all the active conditionals in a makefile.
72 The global variable `conditionals' contains the conditionals
73 information for the current makefile. It is initialized from
74 the static structure `toplevel_conditionals' and is later changed
75 to new structures for included makefiles. */
77 struct conditionals
79 unsigned int if_cmds; /* Depth of conditional nesting. */
80 unsigned int allocated; /* Elts allocated in following arrays. */
81 char *ignoring; /* Are we ignoring or interepreting? */
82 char *seen_else; /* Have we already seen an `else'? */
85 static struct conditionals toplevel_conditionals;
86 static struct conditionals *conditionals = &toplevel_conditionals;
89 /* Default directories to search for include files in */
91 static char *default_include_directories[] =
93 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
95 * This completely up to the user when they install MSVC or other packages.
96 * This is defined as a placeholder.
98 #define INCLUDEDIR "."
99 #endif
100 "", //INCLUDEDIR,
101 #ifndef _AMIGA
102 "/usr/gnu/include",
103 "/usr/local/include",
104 "/usr/include",
105 #endif
109 /* List of directories to search for include files in */
111 static char **include_directories;
113 /* Maximum length of an element of the above. */
115 static unsigned int max_incl_len;
117 /* The filename and pointer to line number of the
118 makefile currently being read in. */
120 const struct floc *reading_file = 0;
122 /* The chain of makefiles read by read_makefile. */
124 static struct dep *read_makefiles = 0;
126 static int eval_makefile PARAMS ((char *filename, int flags));
127 static int eval PARAMS ((struct ebuffer *buffer, int flags));
129 static long readline PARAMS ((struct ebuffer *ebuf));
130 static void do_define PARAMS ((char *name, unsigned int namelen,
131 enum variable_origin origin,
132 struct ebuffer *ebuf));
133 static int conditional_line PARAMS ((char *line, const struct floc *flocp));
134 static void record_files PARAMS ((struct nameseq *filenames, char *pattern, char *pattern_percent,
135 struct dep *deps, unsigned int cmds_started, char *commands,
136 unsigned int commands_idx, int two_colon,
137 int have_sysv_atvar,
138 const struct floc *flocp, int set_default));
139 static void record_target_var PARAMS ((struct nameseq *filenames, char *defn,
140 enum variable_origin origin,
141 int enabled,
142 const struct floc *flocp));
143 static enum make_word_type get_next_mword PARAMS ((char *buffer, char *delim,
144 char **startp, unsigned int *length));
146 /* Read in all the makefiles and return the chain of their names. */
148 struct dep *
149 read_all_makefiles (char **makefiles)
151 unsigned int num_makefiles = 0;
153 /* Create *_LIST variables, to hold the makefiles, targets, and variables
154 we will be reading. */
156 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
158 DB (DB_BASIC, (_("Reading makefiles...\n")));
160 /* If there's a non-null variable MAKEFILES, its value is a list of
161 files to read first thing. But don't let it prevent reading the
162 default makefiles and don't let the default goal come from there. */
165 char *value;
166 char *name, *p;
167 unsigned int length;
170 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
171 int save = warn_undefined_variables_flag;
172 warn_undefined_variables_flag = 0;
174 value = allocated_variable_expand ("$(MAKEFILES)");
176 warn_undefined_variables_flag = save;
179 /* Set NAME to the start of next token and LENGTH to its length.
180 MAKEFILES is updated for finding remaining tokens. */
181 p = value;
183 while ((name = find_next_token (&p, &length)) != 0)
185 if (*p != '\0')
186 *p++ = '\0';
187 name = xstrdup (name);
188 if (eval_makefile (name,
189 RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE) < 2)
190 free (name);
193 free (value);
196 /* Read makefiles specified with -f switches. */
198 if (makefiles != 0)
199 while (*makefiles != 0)
201 struct dep *tail = read_makefiles;
202 register struct dep *d;
204 if (! eval_makefile (*makefiles, 0))
205 perror_with_name ("", *makefiles);
207 /* Find the right element of read_makefiles. */
208 d = read_makefiles;
209 while (d->next != tail)
210 d = d->next;
212 /* Use the storage read_makefile allocates. */
213 *makefiles = dep_name (d);
214 ++num_makefiles;
215 ++makefiles;
218 /* If there were no -f switches, try the default names. */
220 if (num_makefiles == 0)
222 static char *default_makefiles[] =
223 #ifdef VMS
224 /* all lower case since readdir() (the vms version) 'lowercasifies' */
225 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
226 #else
227 #ifdef _AMIGA
228 { "GNUmakefile", "Makefile", "SMakefile", 0 };
229 #else /* !Amiga && !VMS */
230 { "GNUmakefile", "makefile", "Makefile", 0 };
231 #endif /* AMIGA */
232 #endif /* VMS */
233 register char **p = default_makefiles;
234 while (*p != 0 && !file_exists_p (*p))
235 ++p;
237 if (*p != 0)
239 if (! eval_makefile (*p, 0))
240 perror_with_name ("", *p);
242 else
244 /* No default makefile was found. Add the default makefiles to the
245 `read_makefiles' chain so they will be updated if possible. */
246 struct dep *tail = read_makefiles;
247 /* Add them to the tail, after any MAKEFILES variable makefiles. */
248 while (tail != 0 && tail->next != 0)
249 tail = tail->next;
250 for (p = default_makefiles; *p != 0; ++p)
252 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
253 d->name = 0;
254 d->file = enter_file (*p);
255 d->file->dontcare = 1;
256 d->ignore_mtime = 0;
257 /* Tell update_goal_chain to bail out as soon as this file is
258 made, and main not to die if we can't make this file. */
259 d->changed = RM_DONTCARE;
260 if (tail == 0)
261 read_makefiles = d;
262 else
263 tail->next = d;
264 tail = d;
266 if (tail != 0)
267 tail->next = 0;
271 return read_makefiles;
274 /* Install a new conditional and return the previous one. */
276 static struct conditionals *
277 install_conditionals (struct conditionals *new)
279 struct conditionals *save = conditionals;
281 bzero ((char *) new, sizeof (*new));
282 conditionals = new;
284 return save;
287 /* Free the current conditionals and reinstate a saved one. */
289 static void
290 restore_conditionals (struct conditionals *saved)
292 /* Free any space allocated by conditional_line. */
293 if (conditionals->ignoring)
294 free (conditionals->ignoring);
295 if (conditionals->seen_else)
296 free (conditionals->seen_else);
298 /* Restore state. */
299 conditionals = saved;
302 static int
303 eval_makefile (char *filename, int flags)
305 struct dep *deps;
306 struct ebuffer ebuf;
307 const struct floc *curfile;
308 int makefile_errno;
309 int r;
311 ebuf.floc.filenm = filename;
312 ebuf.floc.lineno = 1;
314 if (ISDB (DB_VERBOSE))
316 printf (_("Reading makefile `%s'"), filename);
317 if (flags & RM_NO_DEFAULT_GOAL)
318 printf (_(" (no default goal)"));
319 if (flags & RM_INCLUDED)
320 printf (_(" (search path)"));
321 if (flags & RM_DONTCARE)
322 printf (_(" (don't care)"));
323 if (flags & RM_NO_TILDE)
324 printf (_(" (no ~ expansion)"));
325 puts ("...");
328 /* First, get a stream to read. */
330 /* Expand ~ in FILENAME unless it came from `include',
331 in which case it was already done. */
332 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
334 char *expanded = tilde_expand (filename);
335 if (expanded != 0)
336 filename = expanded;
339 ebuf.fp = fopen (filename, "r");
340 /* Save the error code so we print the right message later. */
341 makefile_errno = errno;
343 /* If the makefile wasn't found and it's either a makefile from
344 the `MAKEFILES' variable or an included makefile,
345 search the included makefile search path for this makefile. */
346 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
348 register unsigned int i;
349 for (i = 0; include_directories[i] != 0; ++i)
351 char *name = concat (include_directories[i], "/", filename);
352 ebuf.fp = fopen (name, "r");
353 if (ebuf.fp == 0)
354 free (name);
355 else
357 filename = name;
358 break;
363 /* Add FILENAME to the chain of read makefiles. */
364 deps = (struct dep *) xmalloc (sizeof (struct dep));
365 deps->next = read_makefiles;
366 read_makefiles = deps;
367 deps->name = 0;
368 deps->file = lookup_file (filename);
369 if (deps->file == 0)
370 deps->file = enter_file (xstrdup (filename));
371 if (filename != ebuf.floc.filenm)
372 free (filename);
373 filename = deps->file->name;
374 deps->changed = flags;
375 deps->ignore_mtime = 0;
376 if (flags & RM_DONTCARE)
377 deps->file->dontcare = 1;
379 /* If the makefile can't be found at all, give up entirely. */
381 if (ebuf.fp == 0)
383 /* If we did some searching, errno has the error from the last
384 attempt, rather from FILENAME itself. Restore it in case the
385 caller wants to use it in a message. */
386 errno = makefile_errno;
387 return 0;
390 /* Add this makefile to the list. */
391 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
392 f_append, 0);
394 /* Evaluate the makefile */
396 ebuf.size = 200;
397 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
399 curfile = reading_file;
400 reading_file = &ebuf.floc;
402 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
404 reading_file = curfile;
406 fclose (ebuf.fp);
408 free (ebuf.bufstart);
409 return r;
413 eval_buffer (char *buffer)
415 struct ebuffer ebuf;
416 struct conditionals *saved;
417 struct conditionals new;
418 const struct floc *curfile;
419 int r;
421 /* Evaluate the buffer */
423 ebuf.size = strlen (buffer);
424 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
425 ebuf.fp = NULL;
427 ebuf.floc = *reading_file;
429 curfile = reading_file;
430 reading_file = &ebuf.floc;
432 saved = install_conditionals (&new);
434 r = eval (&ebuf, 1);
436 restore_conditionals (saved);
438 reading_file = curfile;
440 return r;
444 /* Read file FILENAME as a makefile and add its contents to the data base.
446 SET_DEFAULT is true if we are allowed to set the default goal. */
449 static int
450 eval (struct ebuffer *ebuf, int set_default)
452 char *collapsed = 0;
453 unsigned int collapsed_length = 0;
454 unsigned int commands_len = 200;
455 char *commands;
456 unsigned int commands_idx = 0;
457 unsigned int cmds_started, tgts_started;
458 int ignoring = 0, in_ignored_define = 0;
459 int no_targets = 0; /* Set when reading a rule without targets. */
460 int have_sysv_atvar = 0;
461 struct nameseq *filenames = 0;
462 struct dep *deps = 0;
463 long nlines = 0;
464 int two_colon = 0;
465 char *pattern = 0, *pattern_percent;
466 struct floc *fstart;
467 struct floc fi;
469 #define record_waiting_files() \
470 do \
472 if (filenames != 0) \
474 fi.lineno = tgts_started; \
475 record_files (filenames, pattern, pattern_percent, deps, \
476 cmds_started, commands, commands_idx, two_colon, \
477 have_sysv_atvar, &fi, set_default); \
479 filenames = 0; \
480 commands_idx = 0; \
481 no_targets = 0; \
482 if (pattern) { free(pattern); pattern = 0; } \
483 } while (0)
485 pattern_percent = 0;
486 cmds_started = tgts_started = 1;
488 fstart = &ebuf->floc;
489 fi.filenm = ebuf->floc.filenm;
491 /* Loop over lines in the file.
492 The strategy is to accumulate target names in FILENAMES, dependencies
493 in DEPS and commands in COMMANDS. These are used to define a rule
494 when the start of the next rule (or eof) is encountered.
496 When you see a "continue" in the loop below, that means we are moving on
497 to the next line _without_ ending any rule that we happen to be working
498 with at the moment. If you see a "goto rule_complete", then the
499 statement we just parsed also finishes the previous rule. */
501 commands = xmalloc (200);
503 while (1)
505 unsigned int linelen;
506 char *line;
507 int len;
508 char *p;
509 char *p2;
511 /* Grab the next line to be evaluated */
512 ebuf->floc.lineno += nlines;
513 nlines = readline (ebuf);
515 /* If there is nothing left to eval, we're done. */
516 if (nlines < 0)
517 break;
519 /* If this line is empty, skip it. */
520 line = ebuf->buffer;
521 if (line[0] == '\0')
522 continue;
524 linelen = strlen (line);
526 /* Check for a shell command line first.
527 If it is not one, we can stop treating tab specially. */
528 if (line[0] == '\t')
530 if (no_targets)
531 /* Ignore the commands in a rule with no targets. */
532 continue;
534 /* If there is no preceding rule line, don't treat this line
535 as a command, even though it begins with a tab character.
536 SunOS 4 make appears to behave this way. */
538 if (filenames != 0)
540 if (ignoring)
541 /* Yep, this is a shell command, and we don't care. */
542 continue;
544 /* Append this command line to the line being accumulated. */
545 if (commands_idx == 0)
546 cmds_started = ebuf->floc.lineno;
548 if (linelen + 1 + commands_idx > commands_len)
550 commands_len = (linelen + 1 + commands_idx) * 2;
551 commands = xrealloc (commands, commands_len);
553 bcopy (line, &commands[commands_idx], linelen);
554 commands_idx += linelen;
555 commands[commands_idx++] = '\n';
557 continue;
561 /* This line is not a shell command line. Don't worry about tabs.
562 Get more space if we need it; we don't need to preserve the current
563 contents of the buffer. */
565 if (collapsed_length < linelen+1)
567 collapsed_length = linelen+1;
568 if (collapsed)
569 free ((char *)collapsed);
570 collapsed = (char *) xmalloc (collapsed_length);
572 strcpy (collapsed, line);
573 /* Collapse continuation lines. */
574 collapse_continuations (collapsed);
575 remove_comments (collapsed);
577 /* Compare a word, both length and contents. */
578 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
579 p = collapsed;
580 while (isspace ((unsigned char)*p))
581 ++p;
583 if (*p == '\0')
584 /* This line is completely empty--ignore it. */
585 continue;
587 /* Find the end of the first token. Note we don't need to worry about
588 * ":" here since we compare tokens by length (so "export" will never
589 * be equal to "export:").
591 for (p2 = p+1; *p2 != '\0' && !isspace ((unsigned char)*p2); ++p2)
593 len = p2 - p;
595 /* Find the start of the second token. If it looks like a target or
596 variable definition it can't be a preprocessor token so skip
597 them--this allows variables/targets named `ifdef', `export', etc. */
598 while (isspace ((unsigned char)*p2))
599 ++p2;
601 if ((p2[0] == ':' || p2[0] == '+' || p2[0] == '=') && p2[1] == '\0')
603 /* It can't be a preprocessor token so skip it if we're ignoring */
604 if (ignoring)
605 continue;
607 goto skip_conditionals;
610 /* We must first check for conditional and `define' directives before
611 ignoring anything, since they control what we will do with
612 following lines. */
614 if (!in_ignored_define
615 && (word1eq ("ifdef") || word1eq ("ifndef")
616 || word1eq ("ifeq") || word1eq ("ifneq")
617 || word1eq ("else") || word1eq ("endif")))
619 int i = conditional_line (p, fstart);
620 if (i < 0)
621 fatal (fstart, _("invalid syntax in conditional"));
623 ignoring = i;
624 continue;
627 if (word1eq ("endef"))
629 if (!in_ignored_define)
630 fatal (fstart, _("extraneous `endef'"));
631 in_ignored_define = 0;
632 continue;
635 if (word1eq ("define"))
637 if (ignoring)
638 in_ignored_define = 1;
639 else
641 if (*p2 == '\0')
642 fatal (fstart, _("empty variable name"));
644 /* Let the variable name be the whole rest of the line,
645 with trailing blanks stripped (comments have already been
646 removed), so it could be a complex variable/function
647 reference that might contain blanks. */
648 p = strchr (p2, '\0');
649 while (isblank ((unsigned char)p[-1]))
650 --p;
651 do_define (p2, p - p2, o_file, ebuf);
653 continue;
656 if (word1eq ("override"))
658 if (*p2 == '\0')
659 error (fstart, _("empty `override' directive"));
661 if (strneq (p2, "define", 6)
662 && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
664 if (ignoring)
665 in_ignored_define = 1;
666 else
668 p2 = next_token (p2 + 6);
669 if (*p2 == '\0')
670 fatal (fstart, _("empty variable name"));
672 /* Let the variable name be the whole rest of the line,
673 with trailing blanks stripped (comments have already been
674 removed), so it could be a complex variable/function
675 reference that might contain blanks. */
676 p = strchr (p2, '\0');
677 while (isblank ((unsigned char)p[-1]))
678 --p;
679 do_define (p2, p - p2, o_override, ebuf);
682 else if (!ignoring
683 && !try_variable_definition (fstart, p2, o_override, 0))
684 error (fstart, _("invalid `override' directive"));
686 continue;
689 if (ignoring)
690 /* Ignore the line. We continue here so conditionals
691 can appear in the middle of a rule. */
692 continue;
694 if (word1eq ("export"))
696 /* 'export' by itself causes everything to be exported. */
697 if (*p2 == '\0')
698 export_all_variables = 1;
699 else
701 struct variable *v;
703 v = try_variable_definition (fstart, p2, o_file, 0);
704 if (v != 0)
705 v->export = v_export;
706 else
708 unsigned int len;
709 char *ap;
711 /* Expand the line so we can use indirect and constructed
712 variable names in an export command. */
713 p2 = ap = allocated_variable_expand (p2);
715 for (p = find_next_token (&p2, &len); p != 0;
716 p = find_next_token (&p2, &len))
718 v = lookup_variable (p, len);
719 if (v == 0)
720 v = define_variable_loc (p, len, "", o_file, 0,
721 fstart);
722 v->export = v_export;
725 free (ap);
728 goto rule_complete;
731 if (word1eq ("unexport"))
733 if (*p2 == '\0')
734 export_all_variables = 0;
735 else
737 unsigned int len;
738 struct variable *v;
739 char *ap;
741 /* Expand the line so we can use indirect and constructed
742 variable names in an unexport command. */
743 p2 = ap = allocated_variable_expand (p2);
745 for (p = find_next_token (&p2, &len); p != 0;
746 p = find_next_token (&p2, &len))
748 v = lookup_variable (p, len);
749 if (v == 0)
750 v = define_variable_loc (p, len, "", o_file, 0, fstart);
752 v->export = v_noexport;
755 free (ap);
757 goto rule_complete;
760 skip_conditionals:
761 if (word1eq ("vpath"))
763 char *pattern;
764 unsigned int len;
765 p2 = variable_expand (p2);
766 p = find_next_token (&p2, &len);
767 if (p != 0)
769 pattern = savestring (p, len);
770 p = find_next_token (&p2, &len);
771 /* No searchpath means remove all previous
772 selective VPATH's with the same pattern. */
774 else
775 /* No pattern means remove all previous selective VPATH's. */
776 pattern = 0;
777 construct_vpath_list (pattern, p);
778 if (pattern != 0)
779 free (pattern);
781 goto rule_complete;
784 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
786 /* We have found an `include' line specifying a nested
787 makefile to be read at this point. */
788 struct conditionals *save;
789 struct conditionals new_conditionals;
790 struct nameseq *files;
791 /* "-include" (vs "include") says no error if the file does not
792 exist. "sinclude" is an alias for this from SGI. */
793 int noerror = (p[0] != 'i');
795 p = allocated_variable_expand (p2);
796 if (*p == '\0')
798 error (fstart,
799 _("no file name for `%sinclude'"), noerror ? "-" : "");
800 continue;
803 /* Parse the list of file names. */
804 p2 = p;
805 files = multi_glob (parse_file_seq (&p2, '\0',
806 sizeof (struct nameseq),
808 sizeof (struct nameseq));
809 free (p);
811 /* Save the state of conditionals and start
812 the included makefile with a clean slate. */
813 save = install_conditionals (&new_conditionals);
815 /* Record the rules that are waiting so they will determine
816 the default goal before those in the included makefile. */
817 record_waiting_files ();
819 /* Read each included makefile. */
820 while (files != 0)
822 struct nameseq *next = files->next;
823 char *name = files->name;
824 int r;
826 free ((char *)files);
827 files = next;
829 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
830 | (noerror ? RM_DONTCARE : 0)));
831 if (!r)
833 if (!noerror)
834 error (fstart, "%s: %s", name, strerror (errno));
835 free (name);
839 /* Restore conditional state. */
840 restore_conditionals (save);
842 goto rule_complete;
845 if (try_variable_definition (fstart, p, o_file, 0))
846 /* This line has been dealt with. */
847 goto rule_complete;
849 if (line[0] == '\t')
851 p = collapsed; /* Ignore comments, etc. */
852 while (isblank ((unsigned char)*p))
853 ++p;
854 if (*p == '\0')
855 /* The line is completely blank; that is harmless. */
856 continue;
858 /* This line starts with a tab but was not caught above
859 because there was no preceding target, and the line
860 might have been usable as a variable definition.
861 But now we know it is definitely lossage. */
862 fatal(fstart, _("commands commence before first target"));
865 /* This line describes some target files. This is complicated by
866 the existence of target-specific variables, because we can't
867 expand the entire line until we know if we have one or not. So
868 we expand the line word by word until we find the first `:',
869 then check to see if it's a target-specific variable.
871 In this algorithm, `lb_next' will point to the beginning of the
872 unexpanded parts of the input buffer, while `p2' points to the
873 parts of the expanded buffer we haven't searched yet. */
876 enum make_word_type wtype;
877 enum variable_origin v_origin;
878 int exported;
879 char *cmdleft, *semip, *lb_next;
880 unsigned int len, plen = 0;
881 char *colonp;
883 /* Record the previous rule. */
885 record_waiting_files ();
886 tgts_started = fstart->lineno;
888 /* Search the line for an unquoted ; that is not after an
889 unquoted #. */
890 cmdleft = find_char_unquote (line, ';', '#', 0);
891 if (cmdleft != 0 && *cmdleft == '#')
893 /* We found a comment before a semicolon. */
894 *cmdleft = '\0';
895 cmdleft = 0;
897 else if (cmdleft != 0)
898 /* Found one. Cut the line short there before expanding it. */
899 *(cmdleft++) = '\0';
900 semip = cmdleft;
902 collapse_continuations (line);
904 /* We can't expand the entire line, since if it's a per-target
905 variable we don't want to expand it. So, walk from the
906 beginning, expanding as we go, and looking for "interesting"
907 chars. The first word is always expandable. */
908 wtype = get_next_mword(line, NULL, &lb_next, &len);
909 switch (wtype)
911 case w_eol:
912 if (cmdleft != 0)
913 fatal(fstart, _("missing rule before commands"));
914 /* This line contained something but turned out to be nothing
915 but whitespace (a comment?). */
916 continue;
918 case w_colon:
919 case w_dcolon:
920 /* We accept and ignore rules without targets for
921 compatibility with SunOS 4 make. */
922 no_targets = 1;
923 continue;
925 default:
926 break;
929 p2 = variable_expand_string(NULL, lb_next, len);
930 while (1)
932 lb_next += len;
933 if (cmdleft == 0)
935 /* Look for a semicolon in the expanded line. */
936 cmdleft = find_char_unquote (p2, ';', 0, 0);
938 if (cmdleft != 0)
940 unsigned long p2_off = p2 - variable_buffer;
941 unsigned long cmd_off = cmdleft - variable_buffer;
942 char *pend = p2 + strlen(p2);
944 /* Append any remnants of lb, then cut the line short
945 at the semicolon. */
946 *cmdleft = '\0';
948 /* One school of thought says that you shouldn't expand
949 here, but merely copy, since now you're beyond a ";"
950 and into a command script. However, the old parser
951 expanded the whole line, so we continue that for
952 backwards-compatiblity. Also, it wouldn't be
953 entirely consistent, since we do an unconditional
954 expand below once we know we don't have a
955 target-specific variable. */
956 (void)variable_expand_string(pend, lb_next, (long)-1);
957 lb_next += strlen(lb_next);
958 p2 = variable_buffer + p2_off;
959 cmdleft = variable_buffer + cmd_off + 1;
963 colonp = find_char_unquote(p2, ':', 0, 0);
964 #ifdef HAVE_DOS_PATHS
965 /* The drive spec brain-damage strikes again... */
966 /* Note that the only separators of targets in this context
967 are whitespace and a left paren. If others are possible,
968 they should be added to the string in the call to index. */
969 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
970 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
971 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
972 colonp = find_char_unquote(colonp + 1, ':', 0, 0);
973 #endif
974 if (colonp != 0)
975 break;
977 wtype = get_next_mword(lb_next, NULL, &lb_next, &len);
978 if (wtype == w_eol)
979 break;
981 p2 += strlen(p2);
982 *(p2++) = ' ';
983 p2 = variable_expand_string(p2, lb_next, len);
984 /* We don't need to worry about cmdleft here, because if it was
985 found in the variable_buffer the entire buffer has already
986 been expanded... we'll never get here. */
989 p2 = next_token (variable_buffer);
991 /* If the word we're looking at is EOL, see if there's _anything_
992 on the line. If not, a variable expanded to nothing, so ignore
993 it. If so, we can't parse this line so punt. */
994 if (wtype == w_eol)
996 if (*p2 != '\0')
997 /* There's no need to be ivory-tower about this: check for
998 one of the most common bugs found in makefiles... */
999 fatal (fstart, _("missing separator%s"),
1000 !strneq(line, " ", 8) ? ""
1001 : _(" (did you mean TAB instead of 8 spaces?)"));
1002 continue;
1005 /* Make the colon the end-of-string so we know where to stop
1006 looking for targets. */
1007 *colonp = '\0';
1008 filenames = multi_glob (parse_file_seq (&p2, '\0',
1009 sizeof (struct nameseq),
1011 sizeof (struct nameseq));
1012 *p2 = ':';
1014 if (!filenames)
1016 /* We accept and ignore rules without targets for
1017 compatibility with SunOS 4 make. */
1018 no_targets = 1;
1019 continue;
1021 /* This should never be possible; we handled it above. */
1022 assert (*p2 != '\0');
1023 ++p2;
1025 /* Is this a one-colon or two-colon entry? */
1026 two_colon = *p2 == ':';
1027 if (two_colon)
1028 p2++;
1030 /* Test to see if it's a target-specific variable. Copy the rest
1031 of the buffer over, possibly temporarily (we'll expand it later
1032 if it's not a target-specific variable). PLEN saves the length
1033 of the unparsed section of p2, for later. */
1034 if (*lb_next != '\0')
1036 unsigned int l = p - variable_buffer;
1037 unsigned int l2 = p2 - variable_buffer;
1038 plen = strlen (p2);
1039 (void) variable_buffer_output (p2+plen,
1040 lb_next, strlen (lb_next)+1);
1041 p = variable_buffer + l;
1042 p2 = variable_buffer + l2;
1045 /* See if it's an "override" or "export" keyword; if so see if what
1046 comes after it looks like a variable definition. */
1048 wtype = get_next_mword (p2, NULL, &p, &len);
1050 v_origin = o_file;
1051 exported = 0;
1052 if (wtype == w_static)
1054 if (word1eq ("override"))
1056 v_origin = o_override;
1057 wtype = get_next_mword (p+len, NULL, &p, &len);
1059 else if (word1eq ("export"))
1061 exported = 1;
1062 wtype = get_next_mword (p+len, NULL, &p, &len);
1066 if (wtype != w_eol)
1067 wtype = get_next_mword (p+len, NULL, NULL, NULL);
1069 if (wtype == w_varassign)
1071 /* If there was a semicolon found, add it back, plus anything
1072 after it. */
1073 if (semip)
1075 unsigned int l = p - variable_buffer;
1076 *(--semip) = ';';
1077 variable_buffer_output (p2 + strlen (p2),
1078 semip, strlen (semip)+1);
1079 p = variable_buffer + l;
1081 record_target_var (filenames, p, v_origin, exported, fstart);
1082 filenames = 0;
1083 continue;
1086 /* This is a normal target, _not_ a target-specific variable.
1087 Unquote any = in the dependency list. */
1088 find_char_unquote (lb_next, '=', 0, 0);
1090 /* We have some targets, so don't ignore the following commands. */
1091 no_targets = 0;
1093 /* Expand the dependencies, etc. */
1094 if (*lb_next != '\0')
1096 unsigned int l = p2 - variable_buffer;
1097 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1098 p2 = variable_buffer + l;
1100 /* Look for a semicolon in the expanded line. */
1101 if (cmdleft == 0)
1103 cmdleft = find_char_unquote (p2, ';', 0, 0);
1104 if (cmdleft != 0)
1105 *(cmdleft++) = '\0';
1109 /* Do any of the prerequisites appear to have $@ etc.? */
1110 have_sysv_atvar = 0;
1111 if (!posix_pedantic)
1112 for (p = strchr (p2, '$'); p != 0; p = strchr (p+1, '$'))
1113 if (p[1] == '@' || ((p[1] == '(' || p[1] == '{') && p[2] == '@'))
1115 have_sysv_atvar = 1;
1116 break;
1119 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1120 p = strchr (p2, ':');
1121 while (p != 0 && p[-1] == '\\')
1123 register char *q = &p[-1];
1124 register int backslash = 0;
1125 while (*q-- == '\\')
1126 backslash = !backslash;
1127 if (backslash)
1128 p = strchr (p + 1, ':');
1129 else
1130 break;
1132 #ifdef _AMIGA
1133 /* Here, the situation is quite complicated. Let's have a look
1134 at a couple of targets:
1136 install: dev:make
1138 dev:make: make
1140 dev:make:: xyz
1142 The rule is that it's only a target, if there are TWO :'s
1143 OR a space around the :.
1145 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1146 || isspace ((unsigned char)p[-1])))
1147 p = 0;
1148 #endif
1149 #ifdef HAVE_DOS_PATHS
1151 int check_again;
1153 do {
1154 check_again = 0;
1155 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1156 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1157 isalpha ((unsigned char)p[-1]) &&
1158 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1159 p = strchr (p + 1, ':');
1160 check_again = 1;
1162 } while (check_again);
1164 #endif
1165 if (p != 0)
1167 struct nameseq *target;
1168 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1169 ++p2;
1170 if (target == 0)
1171 fatal (fstart, _("missing target pattern"));
1172 else if (target->next != 0)
1173 fatal (fstart, _("multiple target patterns"));
1174 pattern = target->name;
1175 pattern_percent = find_percent (pattern);
1176 if (pattern_percent == 0)
1177 fatal (fstart, _("target pattern contains no `%%'"));
1178 free((char *)target);
1180 else
1181 pattern = 0;
1183 /* Parse the dependencies. */
1184 deps = (struct dep *)
1185 multi_glob (parse_file_seq (&p2, '|', sizeof (struct dep), 1),
1186 sizeof (struct dep));
1187 if (*p2)
1189 /* Files that follow '|' are special prerequisites that
1190 need only exist in order to satisfy the dependency.
1191 Their modification times are irrelevant. */
1192 struct dep **deps_ptr = &deps;
1193 struct dep *d;
1194 for (deps_ptr = &deps; *deps_ptr; deps_ptr = &(*deps_ptr)->next)
1196 ++p2;
1197 *deps_ptr = (struct dep *)
1198 multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
1199 sizeof (struct dep));
1200 for (d = *deps_ptr; d != 0; d = d->next)
1201 d->ignore_mtime = 1;
1204 commands_idx = 0;
1205 if (cmdleft != 0)
1207 /* Semicolon means rest of line is a command. */
1208 unsigned int len = strlen (cmdleft);
1210 cmds_started = fstart->lineno;
1212 /* Add this command line to the buffer. */
1213 if (len + 2 > commands_len)
1215 commands_len = (len + 2) * 2;
1216 commands = (char *) xrealloc (commands, commands_len);
1218 bcopy (cmdleft, commands, len);
1219 commands_idx += len;
1220 commands[commands_idx++] = '\n';
1223 continue;
1226 /* We get here except in the case that we just read a rule line.
1227 Record now the last rule we read, so following spurious
1228 commands are properly diagnosed. */
1229 rule_complete:
1230 record_waiting_files ();
1233 #undef word1eq
1235 if (conditionals->if_cmds)
1236 fatal (fstart, _("missing `endif'"));
1238 /* At eof, record the last rule. */
1239 record_waiting_files ();
1241 if (collapsed)
1242 free ((char *) collapsed);
1243 free ((char *) commands);
1245 return 1;
1249 /* Execute a `define' directive.
1250 The first line has already been read, and NAME is the name of
1251 the variable to be defined. The following lines remain to be read. */
1253 static void
1254 do_define (char *name, unsigned int namelen,
1255 enum variable_origin origin, struct ebuffer *ebuf)
1257 struct floc defstart;
1258 long nlines = 0;
1259 int nlevels = 1;
1260 unsigned int length = 100;
1261 char *definition = (char *) xmalloc (length);
1262 unsigned int idx = 0;
1263 char *p;
1265 /* Expand the variable name. */
1266 char *var = (char *) alloca (namelen + 1);
1267 bcopy (name, var, namelen);
1268 var[namelen] = '\0';
1269 var = variable_expand (var);
1271 defstart = ebuf->floc;
1273 while (1)
1275 unsigned int len;
1276 char *line;
1278 nlines = readline (ebuf);
1279 ebuf->floc.lineno += nlines;
1281 /* If there is nothing left to eval, we're done. */
1282 if (nlines < 0)
1283 break;
1285 line = ebuf->buffer;
1287 collapse_continuations (line);
1289 /* If the line doesn't begin with a tab, test to see if it introduces
1290 another define, or ends one. */
1292 /* Stop if we find an 'endef' */
1293 if (line[0] != '\t')
1295 p = next_token (line);
1296 len = strlen (p);
1298 /* If this is another 'define', increment the level count. */
1299 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1300 && strneq (p, "define", 6))
1301 ++nlevels;
1303 /* If this is an 'endef', decrement the count. If it's now 0,
1304 we've found the last one. */
1305 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1306 && strneq (p, "endef", 5))
1308 p += 5;
1309 remove_comments (p);
1310 if (*next_token (p) != '\0')
1311 error (&ebuf->floc,
1312 _("Extraneous text after `endef' directive"));
1314 if (--nlevels == 0)
1316 /* Define the variable. */
1317 if (idx == 0)
1318 definition[0] = '\0';
1319 else
1320 definition[idx - 1] = '\0';
1322 /* Always define these variables in the global set. */
1323 define_variable_global (var, strlen (var), definition,
1324 origin, 1, &defstart);
1325 free (definition);
1326 return;
1331 /* Otherwise add this line to the variable definition. */
1332 len = strlen (line);
1333 if (idx + len + 1 > length)
1335 length = (idx + len) * 2;
1336 definition = (char *) xrealloc (definition, length + 1);
1339 bcopy (line, &definition[idx], len);
1340 idx += len;
1341 /* Separate lines with a newline. */
1342 definition[idx++] = '\n';
1345 /* No `endef'!! */
1346 fatal (&defstart, _("missing `endef', unterminated `define'"));
1348 /* NOTREACHED */
1349 return;
1352 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1353 "ifneq", "else" and "endif".
1354 LINE is the input line, with the command as its first word.
1356 FILENAME and LINENO are the filename and line number in the
1357 current makefile. They are used for error messages.
1359 Value is -1 if the line is invalid,
1360 0 if following text should be interpreted,
1361 1 if following text should be ignored. */
1363 static int
1364 conditional_line (char *line, const struct floc *flocp)
1366 int notdef;
1367 char *cmdname;
1368 register unsigned int i;
1370 if (*line == 'i')
1372 /* It's an "if..." command. */
1373 notdef = line[2] == 'n';
1374 if (notdef)
1376 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
1377 line += cmdname[3] == 'd' ? 7 : 6;
1379 else
1381 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
1382 line += cmdname[2] == 'd' ? 6 : 5;
1385 else
1387 /* It's an "else" or "endif" command. */
1388 notdef = line[1] == 'n';
1389 cmdname = notdef ? "endif" : "else";
1390 line += notdef ? 5 : 4;
1393 line = next_token (line);
1395 if (*cmdname == 'e')
1397 if (*line != '\0')
1398 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1399 /* "Else" or "endif". */
1400 if (conditionals->if_cmds == 0)
1401 fatal (flocp, _("extraneous `%s'"), cmdname);
1402 /* NOTDEF indicates an `endif' command. */
1403 if (notdef)
1404 --conditionals->if_cmds;
1405 else if (conditionals->seen_else[conditionals->if_cmds - 1])
1406 fatal (flocp, _("only one `else' per conditional"));
1407 else
1409 /* Toggle the state of ignorance. */
1410 conditionals->ignoring[conditionals->if_cmds - 1]
1411 = !conditionals->ignoring[conditionals->if_cmds - 1];
1412 /* Record that we have seen an `else' in this conditional.
1413 A second `else' will be erroneous. */
1414 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
1416 for (i = 0; i < conditionals->if_cmds; ++i)
1417 if (conditionals->ignoring[i])
1418 return 1;
1419 return 0;
1422 if (conditionals->allocated == 0)
1424 conditionals->allocated = 5;
1425 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
1426 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
1429 ++conditionals->if_cmds;
1430 if (conditionals->if_cmds > conditionals->allocated)
1432 conditionals->allocated += 5;
1433 conditionals->ignoring = (char *)
1434 xrealloc (conditionals->ignoring, conditionals->allocated);
1435 conditionals->seen_else = (char *)
1436 xrealloc (conditionals->seen_else, conditionals->allocated);
1439 /* Record that we have seen an `if...' but no `else' so far. */
1440 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
1442 /* Search through the stack to see if we're already ignoring. */
1443 for (i = 0; i < conditionals->if_cmds - 1; ++i)
1444 if (conditionals->ignoring[i])
1446 /* We are already ignoring, so just push a level
1447 to match the next "else" or "endif", and keep ignoring.
1448 We don't want to expand variables in the condition. */
1449 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
1450 return 1;
1453 if (cmdname[notdef ? 3 : 2] == 'd')
1455 /* "Ifdef" or "ifndef". */
1456 char *var;
1457 struct variable *v;
1458 register char *p;
1460 /* Expand the thing we're looking up, so we can use indirect and
1461 constructed variable names. */
1462 var = allocated_variable_expand (line);
1464 /* Make sure there's only one variable name to test. */
1465 p = end_of_token (var);
1466 i = p - var;
1467 p = next_token (p);
1468 if (*p != '\0')
1469 return -1;
1471 var[i] = '\0';
1472 v = lookup_variable (var, strlen (var));
1473 conditionals->ignoring[conditionals->if_cmds - 1]
1474 = (v != 0 && *v->value != '\0') == notdef;
1476 free (var);
1478 else
1480 /* "Ifeq" or "ifneq". */
1481 char *s1, *s2;
1482 unsigned int len;
1483 char termin = *line == '(' ? ',' : *line;
1485 if (termin != ',' && termin != '"' && termin != '\'')
1486 return -1;
1488 s1 = ++line;
1489 /* Find the end of the first string. */
1490 if (termin == ',')
1492 register int count = 0;
1493 for (; *line != '\0'; ++line)
1494 if (*line == '(')
1495 ++count;
1496 else if (*line == ')')
1497 --count;
1498 else if (*line == ',' && count <= 0)
1499 break;
1501 else
1502 while (*line != '\0' && *line != termin)
1503 ++line;
1505 if (*line == '\0')
1506 return -1;
1508 if (termin == ',')
1510 /* Strip blanks after the first string. */
1511 char *p = line++;
1512 while (isblank ((unsigned char)p[-1]))
1513 --p;
1514 *p = '\0';
1516 else
1517 *line++ = '\0';
1519 s2 = variable_expand (s1);
1520 /* We must allocate a new copy of the expanded string because
1521 variable_expand re-uses the same buffer. */
1522 len = strlen (s2);
1523 s1 = (char *) alloca (len + 1);
1524 bcopy (s2, s1, len + 1);
1526 if (termin != ',')
1527 /* Find the start of the second string. */
1528 line = next_token (line);
1530 termin = termin == ',' ? ')' : *line;
1531 if (termin != ')' && termin != '"' && termin != '\'')
1532 return -1;
1534 /* Find the end of the second string. */
1535 if (termin == ')')
1537 register int count = 0;
1538 s2 = next_token (line);
1539 for (line = s2; *line != '\0'; ++line)
1541 if (*line == '(')
1542 ++count;
1543 else if (*line == ')')
1545 if (count <= 0)
1546 break;
1547 else
1548 --count;
1552 else
1554 ++line;
1555 s2 = line;
1556 while (*line != '\0' && *line != termin)
1557 ++line;
1560 if (*line == '\0')
1561 return -1;
1563 *line = '\0';
1564 line = next_token (++line);
1565 if (*line != '\0')
1566 error (flocp, _("Extraneous text after `%s' directive"), cmdname);
1568 s2 = variable_expand (s2);
1569 conditionals->ignoring[conditionals->if_cmds - 1]
1570 = streq (s1, s2) == notdef;
1573 /* Search through the stack to see if we're ignoring. */
1574 for (i = 0; i < conditionals->if_cmds; ++i)
1575 if (conditionals->ignoring[i])
1576 return 1;
1577 return 0;
1580 /* Remove duplicate dependencies in CHAIN. */
1582 static unsigned long
1583 dep_hash_1 (const void *key)
1585 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1588 static unsigned long
1589 dep_hash_2 (const void *key)
1591 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1594 static int
1595 dep_hash_cmp (const void *x, const void *y)
1597 struct dep *dx = (struct dep *) x;
1598 struct dep *dy = (struct dep *) y;
1599 int cmp = strcmp (dep_name (dx), dep_name (dy));
1601 /* If the names are the same but ignore_mtimes are not equal, one of these
1602 is an order-only prerequisite and one isn't. That means that we should
1603 remove the one that isn't and keep the one that is. */
1605 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1606 dx->ignore_mtime = dy->ignore_mtime = 0;
1608 return cmp;
1612 void
1613 uniquize_deps (struct dep *chain)
1615 struct hash_table deps;
1616 register struct dep **depp;
1618 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1620 /* Make sure that no dependencies are repeated. This does not
1621 really matter for the purpose of updating targets, but it
1622 might make some names be listed twice for $^ and $?. */
1624 depp = &chain;
1625 while (*depp)
1627 struct dep *dep = *depp;
1628 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1629 if (HASH_VACANT (*dep_slot))
1631 hash_insert_at (&deps, dep, dep_slot);
1632 depp = &dep->next;
1634 else
1636 /* Don't bother freeing duplicates.
1637 It's dangerous and little benefit accrues. */
1638 *depp = dep->next;
1642 hash_free (&deps, 0);
1645 /* Record target-specific variable values for files FILENAMES.
1646 TWO_COLON is nonzero if a double colon was used.
1648 The links of FILENAMES are freed, and so are any names in it
1649 that are not incorporated into other data structures.
1651 If the target is a pattern, add the variable to the pattern-specific
1652 variable value list. */
1654 static void
1655 record_target_var (struct nameseq *filenames, char *defn,
1656 enum variable_origin origin, int exported,
1657 const struct floc *flocp)
1659 struct nameseq *nextf;
1660 struct variable_set_list *global;
1662 global = current_variable_set_list;
1664 /* If the variable is an append version, store that but treat it as a
1665 normal recursive variable. */
1667 for (; filenames != 0; filenames = nextf)
1669 struct variable *v;
1670 register char *name = filenames->name;
1671 char *fname;
1672 char *percent;
1673 struct pattern_var *p;
1675 nextf = filenames->next;
1676 free ((char *) filenames);
1678 /* If it's a pattern target, then add it to the pattern-specific
1679 variable list. */
1680 percent = find_percent (name);
1681 if (percent)
1683 /* Get a reference for this pattern-specific variable struct. */
1684 p = create_pattern_var (name, percent);
1685 p->variable.fileinfo = *flocp;
1686 v = parse_variable_definition (&p->variable, defn);
1687 v->value = xstrdup (v->value);
1688 if (!v)
1689 error (flocp, _("Malformed pattern-specific variable definition"));
1690 fname = p->target;
1692 else
1694 struct file *f;
1696 /* Get a file reference for this file, and initialize it.
1697 We don't want to just call enter_file() because that allocates a
1698 new entry if the file is a double-colon, which we don't want in
1699 this situation. */
1700 f = lookup_file (name);
1701 if (!f)
1702 f = enter_file (name);
1703 else if (f->double_colon)
1704 f = f->double_colon;
1706 initialize_file_variables (f, 1);
1707 fname = f->name;
1709 current_variable_set_list = f->variables;
1710 v = try_variable_definition (flocp, defn, origin, 1);
1711 if (!v)
1712 error (flocp, _("Malformed target-specific variable definition"));
1713 current_variable_set_list = global;
1716 /* Set up the variable to be *-specific. */
1717 v->origin = origin;
1718 v->per_target = 1;
1719 if (exported)
1720 v->export = v_export;
1722 /* If it's not an override, check to see if there was a command-line
1723 setting. If so, reset the value. */
1724 if (origin != o_override)
1726 struct variable *gv;
1727 int len = strlen(v->name);
1729 gv = lookup_variable (v->name, len);
1730 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1732 if (v->value != 0)
1733 free (v->value);
1734 v->value = xstrdup (gv->value);
1735 v->origin = gv->origin;
1736 v->recursive = gv->recursive;
1737 v->append = 0;
1741 /* Free name if not needed further. */
1742 if (name != fname && (name < fname || name > fname + strlen (fname)))
1743 free (name);
1747 /* Record a description line for files FILENAMES,
1748 with dependencies DEPS, commands to execute described
1749 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1750 TWO_COLON is nonzero if a double colon was used.
1751 If not nil, PATTERN is the `%' pattern to make this
1752 a static pattern rule, and PATTERN_PERCENT is a pointer
1753 to the `%' within it.
1755 The links of FILENAMES are freed, and so are any names in it
1756 that are not incorporated into other data structures. */
1758 static void
1759 record_files (struct nameseq *filenames, char *pattern, char *pattern_percent,
1760 struct dep *deps, unsigned int cmds_started, char *commands,
1761 unsigned int commands_idx, int two_colon,
1762 int have_sysv_atvar, const struct floc *flocp, int set_default)
1764 struct nameseq *nextf;
1765 int implicit = 0;
1766 unsigned int max_targets = 0, target_idx = 0;
1767 char **targets = 0, **target_percents = 0;
1768 struct commands *cmds;
1770 if (commands_idx > 0)
1772 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1773 cmds->fileinfo.filenm = flocp->filenm;
1774 cmds->fileinfo.lineno = cmds_started;
1775 cmds->commands = savestring (commands, commands_idx);
1776 cmds->command_lines = 0;
1778 else
1779 cmds = 0;
1781 for (; filenames != 0; filenames = nextf)
1783 char *name = filenames->name;
1784 struct file *f;
1785 struct dep *d;
1786 struct dep *this;
1787 char *implicit_percent;
1789 nextf = filenames->next;
1790 free (filenames);
1792 /* Check for .POSIX. We used to do this in snap_deps() but that's not
1793 good enough: it doesn't happen until after the makefile is read,
1794 which means we cannot use its value during parsing. */
1796 if (streq (name, ".POSIX"))
1797 posix_pedantic = 1;
1799 implicit_percent = find_percent (name);
1800 implicit |= implicit_percent != 0;
1802 if (implicit && pattern != 0)
1803 fatal (flocp, _("mixed implicit and static pattern rules"));
1805 if (implicit && implicit_percent == 0)
1806 fatal (flocp, _("mixed implicit and normal rules"));
1808 if (implicit)
1810 if (targets == 0)
1812 max_targets = 5;
1813 targets = (char **) xmalloc (5 * sizeof (char *));
1814 target_percents = (char **) xmalloc (5 * sizeof (char *));
1815 target_idx = 0;
1817 else if (target_idx == max_targets - 1)
1819 max_targets += 5;
1820 targets = (char **) xrealloc ((char *) targets,
1821 max_targets * sizeof (char *));
1822 target_percents
1823 = (char **) xrealloc ((char *) target_percents,
1824 max_targets * sizeof (char *));
1826 targets[target_idx] = name;
1827 target_percents[target_idx] = implicit_percent;
1828 ++target_idx;
1829 continue;
1832 /* If there are multiple filenames, copy the chain DEPS
1833 for all but the last one. It is not safe for the same deps
1834 to go in more than one place in the data base. */
1835 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1837 if (pattern != 0)
1839 /* If this is an extended static rule:
1840 `targets: target%pattern: dep%pattern; cmds',
1841 translate each dependency pattern into a plain filename
1842 using the target pattern and this target's name. */
1843 if (!pattern_matches (pattern, pattern_percent, name))
1845 /* Give a warning if the rule is meaningless. */
1846 error (flocp,
1847 _("target `%s' doesn't match the target pattern"), name);
1848 this = 0;
1850 else
1852 /* We use patsubst_expand to do the work of translating
1853 the target pattern, the target's name and the dependencies'
1854 patterns into plain dependency names. */
1855 char *buffer = variable_expand ("");
1857 for (d = this; d != 0; d = d->next)
1859 char *o;
1860 char *percent = find_percent (d->name);
1861 if (percent == 0)
1862 continue;
1863 o = patsubst_expand (buffer, name, pattern, d->name,
1864 pattern_percent, percent);
1865 /* If the name expanded to the empty string, that's
1866 illegal. */
1867 if (o == buffer)
1868 fatal (flocp,
1869 _("target `%s' leaves prerequisite pattern empty"),
1870 name);
1871 free (d->name);
1872 d->name = savestring (buffer, o - buffer);
1877 /* If at least one of the dependencies uses $$@ etc. deal with that.
1878 It would be very nice and very simple to just expand everything, but
1879 it would break a lot of backward compatibility. Maybe that's OK
1880 since we're just emulating a SysV function, and if we do that then
1881 why not emulate it completely (that's what SysV make does: it
1882 re-expands the entire prerequisite list, all the time, with $@
1883 etc. in scope). But, it would be a pain indeed to document this
1884 ("iff you use $$@, your prerequisite lists is expanded twice...")
1885 Ouch. Maybe better to make the code more complex. */
1887 if (have_sysv_atvar)
1889 char *p;
1890 int tlen = strlen (name);
1891 char *fnp = strrchr (name, '/');
1892 int dlen;
1893 int flen;
1895 if (fnp)
1897 dlen = fnp - name;
1898 ++fnp;
1899 flen = strlen (fnp);
1901 else
1903 dlen = 0;
1904 fnp = name;
1905 flen = tlen;
1909 for (d = this; d != 0; d = d->next)
1910 for (p = strchr (d->name, '$'); p != 0; p = strchr (p+1, '$'))
1912 char *s = p;
1913 char *at;
1914 int atlen;
1916 /* If it's '$@', '$(@', or '${@', it's escaped */
1917 if ((++p)[0] == '$'
1918 && (p[1] == '@'
1919 || ((p[1] == '(' || p[1] == '{') && p[2] == '@')))
1921 bcopy (p, s, strlen (p)+1);
1922 continue;
1925 /* Maybe found one. We like anything of any form matching @,
1926 [({]@[}):], or [({]@[DF][}):]. */
1928 if (! (p[0] == '@'
1929 || ((p[0] == '(' || p[0] == '{') && (++p)[0] == '@'
1930 && (((++p)[0] == ')' || p[0] == '}' || p[0] == ':')
1931 || ((p[1] == ')' || p[1] == '}' || p[1] == ':')
1932 && (p[0] == 'D' || p[0] == 'F'))))))
1933 continue;
1935 /* Found one. Compute the length and string ptr. Move p
1936 past the variable reference. */
1937 switch (p[0])
1939 case 'D':
1940 atlen = dlen;
1941 at = name;
1942 p += 2;
1943 break;
1945 case 'F':
1946 atlen = flen;
1947 at = fnp;
1948 p += 2;
1949 break;
1951 default:
1952 atlen = tlen;
1953 at = name;
1954 ++p;
1955 break;
1958 /* Get more space. */
1960 int soff = s - d->name;
1961 int poff = p - d->name;
1962 d->name = (char *) xrealloc (d->name,
1963 strlen (d->name) + atlen + 1);
1964 s = d->name + soff;
1965 p = d->name + poff;
1968 /* Copy the string over. */
1969 bcopy(p, s+atlen, strlen (p)+1);
1970 bcopy(at, s, atlen);
1971 p = s + atlen - 1;
1975 if (!two_colon)
1977 /* Single-colon. Combine these dependencies
1978 with others in file's existing record, if any. */
1979 f = enter_file (name);
1981 if (f->double_colon)
1982 fatal (flocp,
1983 _("target file `%s' has both : and :: entries"), f->name);
1985 /* If CMDS == F->CMDS, this target was listed in this rule
1986 more than once. Just give a warning since this is harmless. */
1987 if (cmds != 0 && cmds == f->cmds)
1988 error (flocp,
1989 _("target `%s' given more than once in the same rule."),
1990 f->name);
1992 /* Check for two single-colon entries both with commands.
1993 Check is_target so that we don't lose on files such as .c.o
1994 whose commands were preinitialized. */
1995 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1997 error (&cmds->fileinfo,
1998 _("warning: overriding commands for target `%s'"),
1999 f->name);
2000 error (&f->cmds->fileinfo,
2001 _("warning: ignoring old commands for target `%s'"),
2002 f->name);
2005 f->is_target = 1;
2007 /* Defining .DEFAULT with no deps or cmds clears it. */
2008 if (f == default_file && this == 0 && cmds == 0)
2009 f->cmds = 0;
2010 if (cmds != 0)
2011 f->cmds = cmds;
2012 /* Defining .SUFFIXES with no dependencies
2013 clears out the list of suffixes. */
2014 if (f == suffix_file && this == 0)
2016 d = f->deps;
2017 while (d != 0)
2019 struct dep *nextd = d->next;
2020 free (d->name);
2021 free ((char *)d);
2022 d = nextd;
2024 f->deps = 0;
2026 else if (f->deps != 0)
2028 /* Add the file's old deps and the new ones in THIS together. */
2030 struct dep *firstdeps, *moredeps;
2031 if (cmds != 0)
2033 /* This is the rule with commands, so put its deps first.
2034 The rationale behind this is that $< expands to the
2035 first dep in the chain, and commands use $< expecting
2036 to get the dep that rule specifies. */
2037 firstdeps = this;
2038 moredeps = f->deps;
2040 else
2042 /* Append the new deps to the old ones. */
2043 firstdeps = f->deps;
2044 moredeps = this;
2047 if (firstdeps == 0)
2048 firstdeps = moredeps;
2049 else
2051 d = firstdeps;
2052 while (d->next != 0)
2053 d = d->next;
2054 d->next = moredeps;
2057 f->deps = firstdeps;
2059 else
2060 f->deps = this;
2062 /* If this is a static pattern rule, set the file's stem to
2063 the part of its name that matched the `%' in the pattern,
2064 so you can use $* in the commands. */
2065 if (pattern != 0)
2067 static char *percent = "%";
2068 char *buffer = variable_expand ("");
2069 char *o = patsubst_expand (buffer, name, pattern, percent,
2070 pattern_percent, percent);
2071 f->stem = savestring (buffer, o - buffer);
2074 else
2076 /* Double-colon. Make a new record
2077 even if the file already has one. */
2078 f = lookup_file (name);
2079 /* Check for both : and :: rules. Check is_target so
2080 we don't lose on default suffix rules or makefiles. */
2081 if (f != 0 && f->is_target && !f->double_colon)
2082 fatal (flocp,
2083 _("target file `%s' has both : and :: entries"), f->name);
2084 f = enter_file (name);
2085 /* If there was an existing entry and it was a double-colon
2086 entry, enter_file will have returned a new one, making it the
2087 prev pointer of the old one, and setting its double_colon
2088 pointer to the first one. */
2089 if (f->double_colon == 0)
2090 /* This is the first entry for this name, so we must
2091 set its double_colon pointer to itself. */
2092 f->double_colon = f;
2093 f->is_target = 1;
2094 f->deps = this;
2095 f->cmds = cmds;
2098 /* Free name if not needed further. */
2099 if (f != 0 && name != f->name
2100 && (name < f->name || name > f->name + strlen (f->name)))
2102 free (name);
2103 name = f->name;
2106 /* See if this is first target seen whose name does
2107 not start with a `.', unless it contains a slash. */
2108 if (default_goal_file == 0 && set_default
2109 && (*name != '.' || strchr (name, '/') != 0
2110 #ifdef HAVE_DOS_PATHS
2111 || strchr (name, '\\') != 0
2112 #endif
2115 int reject = 0;
2117 /* If this file is a suffix, don't
2118 let it be the default goal file. */
2120 for (d = suffix_file->deps; d != 0; d = d->next)
2122 register struct dep *d2;
2123 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
2125 reject = 1;
2126 break;
2128 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
2130 register unsigned int len = strlen (dep_name (d2));
2131 if (!strneq (name, dep_name (d2), len))
2132 continue;
2133 if (streq (name + len, dep_name (d)))
2135 reject = 1;
2136 break;
2139 if (reject)
2140 break;
2143 if (!reject)
2144 default_goal_file = f;
2148 if (implicit)
2150 targets[target_idx] = 0;
2151 target_percents[target_idx] = 0;
2152 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
2153 free ((char *) target_percents);
2157 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2158 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2159 Quoting backslashes are removed from STRING by compacting it into
2160 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2161 one, or nil if there are none. */
2163 char *
2164 find_char_unquote (char *string, int stop1, int stop2, int blank)
2166 unsigned int string_len = 0;
2167 register char *p = string;
2169 while (1)
2171 if (stop2 && blank)
2172 while (*p != '\0' && *p != stop1 && *p != stop2
2173 && ! isblank ((unsigned char) *p))
2174 ++p;
2175 else if (stop2)
2176 while (*p != '\0' && *p != stop1 && *p != stop2)
2177 ++p;
2178 else if (blank)
2179 while (*p != '\0' && *p != stop1
2180 && ! isblank ((unsigned char) *p))
2181 ++p;
2182 else
2183 while (*p != '\0' && *p != stop1)
2184 ++p;
2186 if (*p == '\0')
2187 break;
2189 if (p > string && p[-1] == '\\')
2191 /* Search for more backslashes. */
2192 register int i = -2;
2193 while (&p[i] >= string && p[i] == '\\')
2194 --i;
2195 ++i;
2196 /* Only compute the length if really needed. */
2197 if (string_len == 0)
2198 string_len = strlen (string);
2199 /* The number of backslashes is now -I.
2200 Copy P over itself to swallow half of them. */
2201 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
2202 p += i / 2;
2203 if (i % 2 == 0)
2204 /* All the backslashes quoted each other; the STOPCHAR was
2205 unquoted. */
2206 return p;
2208 /* The STOPCHAR was quoted by a backslash. Look for another. */
2210 else
2211 /* No backslash in sight. */
2212 return p;
2215 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2216 return 0;
2219 /* Search PATTERN for an unquoted %. */
2221 char *
2222 find_percent (char *pattern)
2224 return find_char_unquote (pattern, '%', 0, 0);
2227 /* Parse a string into a sequence of filenames represented as a
2228 chain of struct nameseq's in reverse order and return that chain.
2230 The string is passed as STRINGP, the address of a string pointer.
2231 The string pointer is updated to point at the first character
2232 not parsed, which either is a null char or equals STOPCHAR.
2234 SIZE is how big to construct chain elements.
2235 This is useful if we want them actually to be other structures
2236 that have room for additional info.
2238 If STRIP is nonzero, strip `./'s off the beginning. */
2240 struct nameseq *
2241 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2243 register struct nameseq *new = 0;
2244 register struct nameseq *new1, *lastnew1;
2245 register char *p = *stringp;
2246 char *q;
2247 char *name;
2249 #ifdef VMS
2250 # define VMS_COMMA ','
2251 #else
2252 # define VMS_COMMA 0
2253 #endif
2255 while (1)
2257 /* Skip whitespace; see if any more names are left. */
2258 p = next_token (p);
2259 if (*p == '\0')
2260 break;
2261 if (*p == stopchar)
2262 break;
2264 /* Yes, find end of next name. */
2265 q = p;
2266 p = find_char_unquote (q, stopchar, VMS_COMMA, 1);
2267 #ifdef VMS
2268 /* convert comma separated list to space separated */
2269 if (p && *p == ',')
2270 *p =' ';
2271 #endif
2272 #ifdef _AMIGA
2273 if (stopchar == ':' && p && *p == ':'
2274 && !(isspace ((unsigned char)p[1]) || !p[1]
2275 || isspace ((unsigned char)p[-1])))
2277 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1);
2279 #endif
2280 #ifdef HAVE_DOS_PATHS
2281 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2282 first colon which isn't followed by a slash or a backslash.
2283 Note that tokens separated by spaces should be treated as separate
2284 tokens since make doesn't allow path names with spaces */
2285 if (stopchar == ':')
2286 while (p != 0 && !isspace ((unsigned char)*p) &&
2287 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2288 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1);
2289 #endif
2290 if (p == 0)
2291 p = q + strlen (q);
2293 if (strip)
2294 #ifdef VMS
2295 /* Skip leading `[]'s. */
2296 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2297 #else
2298 /* Skip leading `./'s. */
2299 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2300 #endif
2302 q += 2; /* Skip "./". */
2303 while (q < p && *q == '/')
2304 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2305 ++q;
2308 /* Extract the filename just found, and skip it. */
2310 if (q == p)
2311 /* ".///" was stripped to "". */
2312 #ifdef VMS
2313 continue;
2314 #else
2315 #ifdef _AMIGA
2316 name = savestring ("", 0);
2317 #else
2318 name = savestring ("./", 2);
2319 #endif
2320 #endif
2321 else
2322 #ifdef VMS
2323 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2324 * to remove this '\' before we can use the filename.
2325 * Savestring called because q may be read-only string constant.
2328 char *qbase = xstrdup (q);
2329 char *pbase = qbase + (p-q);
2330 char *q1 = qbase;
2331 char *q2 = q1;
2332 char *p1 = pbase;
2334 while (q1 != pbase)
2336 if (*q1 == '\\' && *(q1+1) == ':')
2338 q1++;
2339 p1--;
2341 *q2++ = *q1++;
2343 name = savestring (qbase, p1 - qbase);
2344 free (qbase);
2346 #else
2347 name = savestring (q, p - q);
2348 #endif
2350 /* Add it to the front of the chain. */
2351 new1 = (struct nameseq *) xmalloc (size);
2352 new1->name = name;
2353 new1->next = new;
2354 new = new1;
2357 #ifndef NO_ARCHIVES
2359 /* Look for multi-word archive references.
2360 They are indicated by a elt ending with an unmatched `)' and
2361 an elt further down the chain (i.e., previous in the file list)
2362 with an unmatched `(' (e.g., "lib(mem"). */
2364 new1 = new;
2365 lastnew1 = 0;
2366 while (new1 != 0)
2367 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2368 && new1->name[strlen (new1->name) - 1] == ')'
2369 && strchr (new1->name, '(') == 0)
2371 /* NEW1 ends with a `)' but does not contain a `('.
2372 Look back for an elt with an opening `(' but no closing `)'. */
2374 struct nameseq *n = new1->next, *lastn = new1;
2375 char *paren = 0;
2376 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2378 lastn = n;
2379 n = n->next;
2381 if (n != 0
2382 /* Ignore something starting with `(', as that cannot actually
2383 be an archive-member reference (and treating it as such
2384 results in an empty file name, which causes much lossage). */
2385 && n->name[0] != '(')
2387 /* N is the first element in the archive group.
2388 Its name looks like "lib(mem" (with no closing `)'). */
2390 char *libname;
2392 /* Copy "lib(" into LIBNAME. */
2393 ++paren;
2394 libname = (char *) alloca (paren - n->name + 1);
2395 bcopy (n->name, libname, paren - n->name);
2396 libname[paren - n->name] = '\0';
2398 if (*paren == '\0')
2400 /* N was just "lib(", part of something like "lib( a b)".
2401 Edit it out of the chain and free its storage. */
2402 lastn->next = n->next;
2403 free (n->name);
2404 free ((char *) n);
2405 /* LASTN->next is the new stopping elt for the loop below. */
2406 n = lastn->next;
2408 else
2410 /* Replace N's name with the full archive reference. */
2411 name = concat (libname, paren, ")");
2412 free (n->name);
2413 n->name = name;
2416 if (new1->name[1] == '\0')
2418 /* NEW1 is just ")", part of something like "lib(a b )".
2419 Omit it from the chain and free its storage. */
2420 if (lastnew1 == 0)
2421 new = new1->next;
2422 else
2423 lastnew1->next = new1->next;
2424 lastn = new1;
2425 new1 = new1->next;
2426 free (lastn->name);
2427 free ((char *) lastn);
2429 else
2431 /* Replace also NEW1->name, which already has closing `)'. */
2432 name = concat (libname, new1->name, "");
2433 free (new1->name);
2434 new1->name = name;
2435 new1 = new1->next;
2438 /* Trace back from NEW1 (the end of the list) until N
2439 (the beginning of the list), rewriting each name
2440 with the full archive reference. */
2442 while (new1 != n)
2444 name = concat (libname, new1->name, ")");
2445 free (new1->name);
2446 new1->name = name;
2447 lastnew1 = new1;
2448 new1 = new1->next;
2451 else
2453 /* No frobnication happening. Just step down the list. */
2454 lastnew1 = new1;
2455 new1 = new1->next;
2458 else
2460 lastnew1 = new1;
2461 new1 = new1->next;
2464 #endif
2466 *stringp = p;
2467 return new;
2470 /* Find the next line of text in an eval buffer, combining continuation lines
2471 into one line.
2472 Return the number of actual lines read (> 1 if continuation lines).
2473 Returns -1 if there's nothing left in the buffer.
2475 After this function, ebuf->buffer points to the first character of the
2476 line we just found.
2479 /* Read a line of text from a STRING.
2480 Since we aren't really reading from a file, don't bother with linenumbers.
2483 static unsigned long
2484 readstring (struct ebuffer *ebuf)
2486 char *p;
2488 /* If there is nothing left in this buffer, return 0. */
2489 if (ebuf->bufnext > ebuf->bufstart + ebuf->size)
2490 return -1;
2492 /* Set up a new starting point for the buffer, and find the end of the
2493 next logical line (taking into account backslash/newline pairs). */
2495 p = ebuf->buffer = ebuf->bufnext;
2497 while (1)
2499 int backslash = 0;
2501 /* Find the next newline. Keep track of backslashes as we look. */
2502 for (; *p != '\n' && *p != '\0'; ++p)
2503 if (*p == '\\')
2504 backslash = !backslash;
2506 /* If we got to the end of the string or a newline with no backslash,
2507 we're done. */
2508 if (*p == '\0' || !backslash)
2509 break;
2512 /* Overwrite the newline char. */
2513 *p = '\0';
2514 ebuf->bufnext = p+1;
2516 return 0;
2519 static long
2520 readline (struct ebuffer *ebuf)
2522 char *p;
2523 char *end;
2524 char *start;
2525 long nlines = 0;
2527 /* The behaviors between string and stream buffers are different enough to
2528 warrant different functions. Do the Right Thing. */
2530 if (!ebuf->fp)
2531 return readstring (ebuf);
2533 /* When reading from a file, we always start over at the beginning of the
2534 buffer for each new line. */
2536 p = start = ebuf->bufstart;
2537 end = p + ebuf->size;
2538 *p = '\0';
2540 while (fgets (p, end - p, ebuf->fp) != 0)
2542 char *p2;
2543 unsigned long len;
2544 int backslash;
2546 len = strlen (p);
2547 if (len == 0)
2549 /* This only happens when the first thing on the line is a '\0'.
2550 It is a pretty hopeless case, but (wonder of wonders) Athena
2551 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2552 There is nothing really to be done; we synthesize a newline so
2553 the following line doesn't appear to be part of this line. */
2554 error (&ebuf->floc,
2555 _("warning: NUL character seen; rest of line ignored"));
2556 p[0] = '\n';
2557 len = 1;
2560 /* Jump past the text we just read. */
2561 p += len;
2563 /* If the last char isn't a newline, the whole line didn't fit into the
2564 buffer. Get some more buffer and try again. */
2565 if (p[-1] != '\n')
2566 goto more_buffer;
2568 /* We got a newline, so add one to the count of lines. */
2569 ++nlines;
2571 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2572 /* Check to see if the line was really ended with CRLF; if so ignore
2573 the CR. */
2574 if ((p - start) > 1 && p[-2] == '\r')
2576 --p;
2577 p[-1] = '\n';
2579 #endif
2581 backslash = 0;
2582 for (p2 = p - 2; p2 >= start; --p2)
2584 if (*p2 != '\\')
2585 break;
2586 backslash = !backslash;
2589 if (!backslash)
2591 p[-1] = '\0';
2592 break;
2595 /* It was a backslash/newline combo. If we have more space, read
2596 another line. */
2597 if (end - p >= 80)
2598 continue;
2600 /* We need more space at the end of our buffer, so realloc it.
2601 Make sure to preserve the current offset of p. */
2602 more_buffer:
2604 unsigned long off = p - start;
2605 ebuf->size *= 2;
2606 start = ebuf->buffer = ebuf->bufstart = (char *) xrealloc (start,
2607 ebuf->size);
2608 p = start + off;
2609 end = start + ebuf->size;
2610 *p = '\0';
2614 if (ferror (ebuf->fp))
2615 pfatal_with_name (ebuf->floc.filenm);
2617 /* If we found some lines, return how many.
2618 If we didn't, but we did find _something_, that indicates we read the last
2619 line of a file with no final newline; return 1.
2620 If we read nothing, we're at EOF; return -1. */
2622 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2625 /* Parse the next "makefile word" from the input buffer, and return info
2626 about it.
2628 A "makefile word" is one of:
2630 w_bogus Should never happen
2631 w_eol End of input
2632 w_static A static word; cannot be expanded
2633 w_variable A word containing one or more variables/functions
2634 w_colon A colon
2635 w_dcolon A double-colon
2636 w_semicolon A semicolon
2637 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2639 Note that this function is only used when reading certain parts of the
2640 makefile. Don't use it where special rules hold sway (RHS of a variable,
2641 in a command list, etc.) */
2643 static enum make_word_type
2644 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2646 enum make_word_type wtype = w_bogus;
2647 char *p = buffer, *beg;
2648 char c;
2650 /* Skip any leading whitespace. */
2651 while (isblank ((unsigned char)*p))
2652 ++p;
2654 beg = p;
2655 c = *(p++);
2656 switch (c)
2658 case '\0':
2659 wtype = w_eol;
2660 break;
2662 case ';':
2663 wtype = w_semicolon;
2664 break;
2666 case '=':
2667 wtype = w_varassign;
2668 break;
2670 case ':':
2671 wtype = w_colon;
2672 switch (*p)
2674 case ':':
2675 ++p;
2676 wtype = w_dcolon;
2677 break;
2679 case '=':
2680 ++p;
2681 wtype = w_varassign;
2682 break;
2684 break;
2686 case '+':
2687 case '?':
2688 if (*p == '=')
2690 ++p;
2691 wtype = w_varassign;
2692 break;
2695 default:
2696 if (delim && strchr (delim, c))
2697 wtype = w_static;
2698 break;
2701 /* Did we find something? If so, return now. */
2702 if (wtype != w_bogus)
2703 goto done;
2705 /* This is some non-operator word. A word consists of the longest
2706 string of characters that doesn't contain whitespace, one of [:=#],
2707 or [?+]=, or one of the chars in the DELIM string. */
2709 /* We start out assuming a static word; if we see a variable we'll
2710 adjust our assumptions then. */
2711 wtype = w_static;
2713 /* We already found the first value of "c", above. */
2714 while (1)
2716 char closeparen;
2717 int count;
2719 switch (c)
2721 case '\0':
2722 case ' ':
2723 case '\t':
2724 case '=':
2725 goto done_word;
2727 case ':':
2728 #ifdef HAVE_DOS_PATHS
2729 /* A word CAN include a colon in its drive spec. The drive
2730 spec is allowed either at the beginning of a word, or as part
2731 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2732 if (!(p - beg >= 2
2733 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2734 && (p - beg == 2 || p[-3] == '(')))
2735 #endif
2736 goto done_word;
2738 case '$':
2739 c = *(p++);
2740 if (c == '$')
2741 break;
2743 /* This is a variable reference, so note that it's expandable.
2744 Then read it to the matching close paren. */
2745 wtype = w_variable;
2747 if (c == '(')
2748 closeparen = ')';
2749 else if (c == '{')
2750 closeparen = '}';
2751 else
2752 /* This is a single-letter variable reference. */
2753 break;
2755 for (count=0; *p != '\0'; ++p)
2757 if (*p == c)
2758 ++count;
2759 else if (*p == closeparen && --count < 0)
2761 ++p;
2762 break;
2765 break;
2767 case '?':
2768 case '+':
2769 if (*p == '=')
2770 goto done_word;
2771 break;
2773 case '\\':
2774 switch (*p)
2776 case ':':
2777 case ';':
2778 case '=':
2779 case '\\':
2780 ++p;
2781 break;
2783 break;
2785 default:
2786 if (delim && strchr (delim, c))
2787 goto done_word;
2788 break;
2791 c = *(p++);
2793 done_word:
2794 --p;
2796 done:
2797 if (startp)
2798 *startp = beg;
2799 if (length)
2800 *length = p - beg;
2801 return wtype;
2804 /* Construct the list of include directories
2805 from the arguments and the default list. */
2807 void
2808 construct_include_path (char **arg_dirs)
2810 register unsigned int i;
2811 #ifdef VAXC /* just don't ask ... */
2812 stat_t stbuf;
2813 #else
2814 struct stat stbuf;
2815 #endif
2816 /* Table to hold the dirs. */
2818 register unsigned int defsize = (sizeof (default_include_directories)
2819 / sizeof (default_include_directories[0]));
2820 register unsigned int max = 5;
2821 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
2822 register unsigned int idx = 0;
2824 #ifdef __MSDOS__
2825 defsize++;
2826 #endif
2828 /* First consider any dirs specified with -I switches.
2829 Ignore dirs that don't exist. */
2831 if (arg_dirs != 0)
2832 while (*arg_dirs != 0)
2834 char *dir = *arg_dirs++;
2835 int e;
2837 if (dir[0] == '~')
2839 char *expanded = tilde_expand (dir);
2840 if (expanded != 0)
2841 dir = expanded;
2844 EINTRLOOP (e, stat (dir, &stbuf));
2845 if (e == 0 && S_ISDIR (stbuf.st_mode))
2847 if (idx == max - 1)
2849 max += 5;
2850 dirs = (char **)
2851 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
2853 dirs[idx++] = dir;
2855 else if (dir != arg_dirs[-1])
2856 free (dir);
2859 /* Now add at the end the standard default dirs. */
2861 #ifdef __MSDOS__
2863 /* The environment variable $DJDIR holds the root of the
2864 DJGPP directory tree; add ${DJDIR}/include. */
2865 struct variable *djdir = lookup_variable ("DJDIR", 5);
2867 if (djdir)
2869 char *defdir = (char *) xmalloc (strlen (djdir->value) + 8 + 1);
2871 strcat (strcpy (defdir, djdir->value), "/include");
2872 dirs[idx++] = defdir;
2875 #endif
2877 for (i = 0; default_include_directories[i] != 0; ++i)
2879 int e;
2881 EINTRLOOP (e, stat (default_include_directories[i], &stbuf));
2882 if (e == 0 && S_ISDIR (stbuf.st_mode))
2883 dirs[idx++] = default_include_directories[i];
2886 dirs[idx] = 0;
2888 /* Now compute the maximum length of any name in it. */
2890 max_incl_len = 0;
2891 for (i = 0; i < idx; ++i)
2893 unsigned int len = strlen (dirs[i]);
2894 /* If dir name is written with a trailing slash, discard it. */
2895 if (len > 0 && dirs[i][len - 1] == '/')
2896 /* We can't just clobber a null in because it may have come from
2897 a literal string and literal strings may not be writable. */
2898 dirs[i] = savestring (dirs[i], len - 1);
2899 if (len > max_incl_len)
2900 max_incl_len = len;
2903 include_directories = dirs;
2906 /* Expand ~ or ~USER at the beginning of NAME.
2907 Return a newly malloc'd string or 0. */
2909 char *
2910 tilde_expand (char *name)
2912 #ifndef VMS
2913 if (name[1] == '/' || name[1] == '\0')
2915 extern char *getenv ();
2916 char *home_dir;
2917 int is_variable;
2920 /* Turn off --warn-undefined-variables while we expand HOME. */
2921 int save = warn_undefined_variables_flag;
2922 warn_undefined_variables_flag = 0;
2924 home_dir = allocated_variable_expand ("$(HOME)");
2926 warn_undefined_variables_flag = save;
2929 is_variable = home_dir[0] != '\0';
2930 if (!is_variable)
2932 free (home_dir);
2933 home_dir = getenv ("HOME");
2935 #if !defined(_AMIGA) && !defined(WINDOWS32)
2936 if (home_dir == 0 || home_dir[0] == '\0')
2938 extern char *getlogin ();
2939 char *logname = getlogin ();
2940 home_dir = 0;
2941 if (logname != 0)
2943 struct passwd *p = getpwnam (logname);
2944 if (p != 0)
2945 home_dir = p->pw_dir;
2948 #endif /* !AMIGA && !WINDOWS32 */
2949 if (home_dir != 0)
2951 char *new = concat (home_dir, "", name + 1);
2952 if (is_variable)
2953 free (home_dir);
2954 return new;
2957 #if !defined(_AMIGA) && !defined(WINDOWS32)
2958 else
2960 struct passwd *pwent;
2961 char *userend = strchr (name + 1, '/');
2962 if (userend != 0)
2963 *userend = '\0';
2964 pwent = getpwnam (name + 1);
2965 if (pwent != 0)
2967 if (userend == 0)
2968 return xstrdup (pwent->pw_dir);
2969 else
2970 return concat (pwent->pw_dir, "/", userend + 1);
2972 else if (userend != 0)
2973 *userend = '/';
2975 #endif /* !AMIGA && !WINDOWS32 */
2976 #endif /* !VMS */
2977 return 0;
2980 /* Given a chain of struct nameseq's describing a sequence of filenames,
2981 in reverse of the intended order, return a new chain describing the
2982 result of globbing the filenames. The new chain is in forward order.
2983 The links of the old chain are freed or used in the new chain.
2984 Likewise for the names in the old chain.
2986 SIZE is how big to construct chain elements.
2987 This is useful if we want them actually to be other structures
2988 that have room for additional info. */
2990 struct nameseq *
2991 multi_glob (struct nameseq *chain, unsigned int size)
2993 extern void dir_setup_glob ();
2994 register struct nameseq *new = 0;
2995 register struct nameseq *old;
2996 struct nameseq *nexto;
2997 glob_t gl;
2999 dir_setup_glob (&gl);
3001 for (old = chain; old != 0; old = nexto)
3003 #ifndef NO_ARCHIVES
3004 char *memname;
3005 #endif
3007 nexto = old->next;
3009 if (old->name[0] == '~')
3011 char *newname = tilde_expand (old->name);
3012 if (newname != 0)
3014 free (old->name);
3015 old->name = newname;
3019 #ifndef NO_ARCHIVES
3020 if (ar_name (old->name))
3022 /* OLD->name is an archive member reference.
3023 Replace it with the archive file name,
3024 and save the member name in MEMNAME.
3025 We will glob on the archive name and then
3026 reattach MEMNAME later. */
3027 char *arname;
3028 ar_parse_name (old->name, &arname, &memname);
3029 free (old->name);
3030 old->name = arname;
3032 else
3033 memname = 0;
3034 #endif /* !NO_ARCHIVES */
3036 switch (glob (old->name, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3038 case 0: /* Success. */
3040 register int i = gl.gl_pathc;
3041 while (i-- > 0)
3043 #ifndef NO_ARCHIVES
3044 if (memname != 0)
3046 /* Try to glob on MEMNAME within the archive. */
3047 struct nameseq *found
3048 = ar_glob (gl.gl_pathv[i], memname, size);
3049 if (found == 0)
3051 /* No matches. Use MEMNAME as-is. */
3052 unsigned int alen = strlen (gl.gl_pathv[i]);
3053 unsigned int mlen = strlen (memname);
3054 struct nameseq *elt
3055 = (struct nameseq *) xmalloc (size);
3056 if (size > sizeof (struct nameseq))
3057 bzero (((char *) elt) + sizeof (struct nameseq),
3058 size - sizeof (struct nameseq));
3059 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
3060 bcopy (gl.gl_pathv[i], elt->name, alen);
3061 elt->name[alen] = '(';
3062 bcopy (memname, &elt->name[alen + 1], mlen);
3063 elt->name[alen + 1 + mlen] = ')';
3064 elt->name[alen + 1 + mlen + 1] = '\0';
3065 elt->next = new;
3066 new = elt;
3068 else
3070 /* Find the end of the FOUND chain. */
3071 struct nameseq *f = found;
3072 while (f->next != 0)
3073 f = f->next;
3075 /* Attach the chain being built to the end of the FOUND
3076 chain, and make FOUND the new NEW chain. */
3077 f->next = new;
3078 new = found;
3081 free (memname);
3083 else
3084 #endif /* !NO_ARCHIVES */
3086 struct nameseq *elt = (struct nameseq *) xmalloc (size);
3087 if (size > sizeof (struct nameseq))
3088 bzero (((char *) elt) + sizeof (struct nameseq),
3089 size - sizeof (struct nameseq));
3090 elt->name = xstrdup (gl.gl_pathv[i]);
3091 elt->next = new;
3092 new = elt;
3095 globfree (&gl);
3096 free (old->name);
3097 free ((char *)old);
3098 break;
3101 case GLOB_NOSPACE:
3102 fatal (NILF, _("virtual memory exhausted"));
3103 break;
3105 default:
3106 old->next = new;
3107 new = old;
3108 break;
3112 return new;