- Fix Savannah bug #27093
[make.git] / read.c
blob19d5559150687ff1bccd1f4138473671a29e932d
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include <glob.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
35 #ifndef WINDOWS32
36 #ifndef _AMIGA
37 #ifndef VMS
38 #include <pwd.h>
39 #else
40 struct passwd *getpwnam (char *name);
41 #endif
42 #endif
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46 eval'ing.
49 struct ebuffer
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 unsigned int size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 struct floc floc; /* Info on the file in fp (if any). */
59 /* Track the modifiers we can have on variable assignments */
61 struct vmodifiers
63 unsigned int assign_v:1;
64 unsigned int define_v:1;
65 unsigned int export_v:1;
66 unsigned int override_v:1;
67 unsigned int private_v:1;
70 /* Types of "words" that can be read in a makefile. */
71 enum make_word_type
73 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
74 w_varassign
78 /* A `struct conditionals' contains the information describing
79 all the active conditionals in a makefile.
81 The global variable `conditionals' contains the conditionals
82 information for the current makefile. It is initialized from
83 the static structure `toplevel_conditionals' and is later changed
84 to new structures for included makefiles. */
86 struct conditionals
88 unsigned int if_cmds; /* Depth of conditional nesting. */
89 unsigned int allocated; /* Elts allocated in following arrays. */
90 char *ignoring; /* Are we ignoring or interpreting?
91 0=interpreting, 1=not yet interpreted,
92 2=already interpreted */
93 char *seen_else; /* Have we already seen an `else'? */
96 static struct conditionals toplevel_conditionals;
97 static struct conditionals *conditionals = &toplevel_conditionals;
100 /* Default directories to search for include files in */
102 static const char *default_include_directories[] =
104 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
105 /* This completely up to the user when they install MSVC or other packages.
106 This is defined as a placeholder. */
107 # define INCLUDEDIR "."
108 #endif
109 INCLUDEDIR,
110 #ifndef _AMIGA
111 "/usr/gnu/include",
112 "/usr/local/include",
113 "/usr/include",
114 #endif
118 /* List of directories to search for include files in */
120 static const char **include_directories;
122 /* Maximum length of an element of the above. */
124 static unsigned int max_incl_len;
126 /* The filename and pointer to line number of the
127 makefile currently being read in. */
129 const struct floc *reading_file = 0;
131 /* The chain of makefiles read by read_makefile. */
133 static struct dep *read_makefiles = 0;
135 static int eval_makefile (const char *filename, int flags);
136 static int eval (struct ebuffer *buffer, int flags);
138 static long readline (struct ebuffer *ebuf);
139 static struct variable *do_define (char *name, enum variable_origin origin,
140 struct ebuffer *ebuf);
141 static int conditional_line (char *line, int len, const struct floc *flocp);
142 static void record_files (struct nameseq *filenames, const char *pattern,
143 const char *pattern_percent, struct dep *deps,
144 unsigned int cmds_started, char *commands,
145 unsigned int commands_idx, int two_colon,
146 const struct floc *flocp);
147 static void record_target_var (struct nameseq *filenames, char *defn,
148 enum variable_origin origin,
149 struct vmodifiers *vmod,
150 const struct floc *flocp);
151 static enum make_word_type get_next_mword (char *buffer, char *delim,
152 char **startp, unsigned int *length);
153 static void remove_comments (char *line);
154 static char *find_char_unquote (char *string, int stop1, int stop2,
155 int blank, int ignorevars);
158 /* Compare a word, both length and contents.
159 P must point to the word to be tested, and WLEN must be the length.
161 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
164 /* Read in all the makefiles and return the chain of their names. */
166 struct dep *
167 read_all_makefiles (const char **makefiles)
169 unsigned int num_makefiles = 0;
171 /* Create *_LIST variables, to hold the makefiles, targets, and variables
172 we will be reading. */
174 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
176 DB (DB_BASIC, (_("Reading makefiles...\n")));
178 /* If there's a non-null variable MAKEFILES, its value is a list of
179 files to read first thing. But don't let it prevent reading the
180 default makefiles and don't let the default goal come from there. */
183 char *value;
184 char *name, *p;
185 unsigned int length;
188 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
189 int save = warn_undefined_variables_flag;
190 warn_undefined_variables_flag = 0;
192 value = allocated_variable_expand ("$(MAKEFILES)");
194 warn_undefined_variables_flag = save;
197 /* Set NAME to the start of next token and LENGTH to its length.
198 MAKEFILES is updated for finding remaining tokens. */
199 p = value;
201 while ((name = find_next_token ((const char **)&p, &length)) != 0)
203 if (*p != '\0')
204 *p++ = '\0';
205 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
208 free (value);
211 /* Read makefiles specified with -f switches. */
213 if (makefiles != 0)
214 while (*makefiles != 0)
216 struct dep *tail = read_makefiles;
217 register struct dep *d;
219 if (! eval_makefile (*makefiles, 0))
220 perror_with_name ("", *makefiles);
222 /* Find the right element of read_makefiles. */
223 d = read_makefiles;
224 while (d->next != tail)
225 d = d->next;
227 /* Use the storage read_makefile allocates. */
228 *makefiles = dep_name (d);
229 ++num_makefiles;
230 ++makefiles;
233 /* If there were no -f switches, try the default names. */
235 if (num_makefiles == 0)
237 static char *default_makefiles[] =
238 #ifdef VMS
239 /* all lower case since readdir() (the vms version) 'lowercasifies' */
240 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
241 #else
242 #ifdef _AMIGA
243 { "GNUmakefile", "Makefile", "SMakefile", 0 };
244 #else /* !Amiga && !VMS */
245 { "GNUmakefile", "makefile", "Makefile", 0 };
246 #endif /* AMIGA */
247 #endif /* VMS */
248 register char **p = default_makefiles;
249 while (*p != 0 && !file_exists_p (*p))
250 ++p;
252 if (*p != 0)
254 if (! eval_makefile (*p, 0))
255 perror_with_name ("", *p);
257 else
259 /* No default makefile was found. Add the default makefiles to the
260 `read_makefiles' chain so they will be updated if possible. */
261 struct dep *tail = read_makefiles;
262 /* Add them to the tail, after any MAKEFILES variable makefiles. */
263 while (tail != 0 && tail->next != 0)
264 tail = tail->next;
265 for (p = default_makefiles; *p != 0; ++p)
267 struct dep *d = alloc_dep ();
268 d->file = enter_file (strcache_add (*p));
269 d->file->dontcare = 1;
270 /* Tell update_goal_chain to bail out as soon as this file is
271 made, and main not to die if we can't make this file. */
272 d->changed = RM_DONTCARE;
273 if (tail == 0)
274 read_makefiles = d;
275 else
276 tail->next = d;
277 tail = d;
279 if (tail != 0)
280 tail->next = 0;
284 return read_makefiles;
287 /* Install a new conditional and return the previous one. */
289 static struct conditionals *
290 install_conditionals (struct conditionals *new)
292 struct conditionals *save = conditionals;
294 memset (new, '\0', sizeof (*new));
295 conditionals = new;
297 return save;
300 /* Free the current conditionals and reinstate a saved one. */
302 static void
303 restore_conditionals (struct conditionals *saved)
305 /* Free any space allocated by conditional_line. */
306 if (conditionals->ignoring)
307 free (conditionals->ignoring);
308 if (conditionals->seen_else)
309 free (conditionals->seen_else);
311 /* Restore state. */
312 conditionals = saved;
315 static int
316 eval_makefile (const char *filename, int flags)
318 struct dep *deps;
319 struct ebuffer ebuf;
320 const struct floc *curfile;
321 char *expanded = 0;
322 int makefile_errno;
323 int r;
325 filename = strcache_add (filename);
326 ebuf.floc.filenm = filename;
327 ebuf.floc.lineno = 1;
329 if (ISDB (DB_VERBOSE))
331 printf (_("Reading makefile `%s'"), filename);
332 if (flags & RM_NO_DEFAULT_GOAL)
333 printf (_(" (no default goal)"));
334 if (flags & RM_INCLUDED)
335 printf (_(" (search path)"));
336 if (flags & RM_DONTCARE)
337 printf (_(" (don't care)"));
338 if (flags & RM_NO_TILDE)
339 printf (_(" (no ~ expansion)"));
340 puts ("...");
343 /* First, get a stream to read. */
345 /* Expand ~ in FILENAME unless it came from `include',
346 in which case it was already done. */
347 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
349 expanded = tilde_expand (filename);
350 if (expanded != 0)
351 filename = expanded;
354 ebuf.fp = fopen (filename, "r");
355 /* Save the error code so we print the right message later. */
356 makefile_errno = errno;
358 /* If the makefile wasn't found and it's either a makefile from
359 the `MAKEFILES' variable or an included makefile,
360 search the included makefile search path for this makefile. */
361 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
363 unsigned int i;
364 for (i = 0; include_directories[i] != 0; ++i)
366 const char *included = concat (include_directories[i], "/", filename);
367 ebuf.fp = fopen (included, "r");
368 if (ebuf.fp)
370 filename = strcache_add (included);
371 break;
376 /* Add FILENAME to the chain of read makefiles. */
377 deps = alloc_dep ();
378 deps->next = read_makefiles;
379 read_makefiles = deps;
380 deps->file = lookup_file (filename);
381 if (deps->file == 0)
382 deps->file = enter_file (filename);
383 filename = deps->file->name;
384 deps->changed = flags;
385 if (flags & RM_DONTCARE)
386 deps->file->dontcare = 1;
388 if (expanded)
389 free (expanded);
391 /* If the makefile can't be found at all, give up entirely. */
393 if (ebuf.fp == 0)
395 /* If we did some searching, errno has the error from the last
396 attempt, rather from FILENAME itself. Restore it in case the
397 caller wants to use it in a message. */
398 errno = makefile_errno;
399 return 0;
402 /* Set close-on-exec to avoid leaking the makefile to children, such as
403 $(shell ...). */
404 #ifdef HAVE_FILENO
405 CLOSE_ON_EXEC (fileno (ebuf.fp));
406 #endif
408 /* Add this makefile to the list. */
409 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
410 f_append, 0);
412 /* Evaluate the makefile */
414 ebuf.size = 200;
415 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
417 curfile = reading_file;
418 reading_file = &ebuf.floc;
420 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
422 reading_file = curfile;
424 fclose (ebuf.fp);
426 free (ebuf.bufstart);
427 alloca (0);
428 return r;
432 eval_buffer (char *buffer)
434 struct ebuffer ebuf;
435 struct conditionals *saved;
436 struct conditionals new;
437 const struct floc *curfile;
438 int r;
440 /* Evaluate the buffer */
442 ebuf.size = strlen (buffer);
443 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
444 ebuf.fp = NULL;
446 if (reading_file)
447 ebuf.floc = *reading_file;
448 else
449 ebuf.floc.filenm = NULL;
451 curfile = reading_file;
452 reading_file = &ebuf.floc;
454 saved = install_conditionals (&new);
456 r = eval (&ebuf, 1);
458 restore_conditionals (saved);
460 reading_file = curfile;
462 alloca (0);
463 return r;
466 /* Check LINE to see if it's a variable assignment.
468 It might use one of the modifiers "export", "override", "private", or it
469 might be one of the conditional tokens like "ifdef", "include", etc.
471 If it's not a variable assignment, VMOD.V_ASSIGN is 0. Returns LINE.
473 Returns a pointer to the first non-modifier character, and sets VMOD
474 based on the modifiers found if any, plus V_ASSIGN is 1.
476 char *
477 parse_var_assignment (const char *line, struct vmodifiers *vmod)
479 const char *p;
480 memset (vmod, '\0', sizeof (*vmod));
482 /* Find the start of the next token. If there isn't one we're done. */
483 line = next_token (line);
484 if (*line == '\0')
485 return (char *)line;
487 p = line;
488 while (1)
490 int wlen;
491 const char *p2;
492 enum variable_flavor flavor;
494 p2 = parse_variable_definition (p, &flavor);
496 /* If this is a variable assignment, we're done. */
497 if (p2)
498 break;
500 /* It's not a variable; see if it's a modifier. */
501 p2 = end_of_token (p);
502 wlen = p2 - p;
504 if (word1eq ("export"))
505 vmod->export_v = 1;
506 else if (word1eq ("override"))
507 vmod->override_v = 1;
508 else if (word1eq ("private"))
509 vmod->private_v = 1;
510 else if (word1eq ("define"))
512 /* We can't have modifiers after 'define' */
513 vmod->define_v = 1;
514 p = next_token (p2);
515 break;
517 else
518 /* Not a variable or modifier: this is not a variable assignment. */
519 return (char *)line;
521 /* It was a modifier. Try the next word. */
522 p = next_token (p2);
523 if (*p == '\0')
524 return (char *)line;
527 /* Found a variable assignment. */
528 vmod->assign_v = 1;
529 return (char *)p;
534 /* Read file FILENAME as a makefile and add its contents to the data base.
536 SET_DEFAULT is true if we are allowed to set the default goal. */
539 static int
540 eval (struct ebuffer *ebuf, int set_default)
542 char *collapsed = 0;
543 unsigned int collapsed_length = 0;
544 unsigned int commands_len = 200;
545 char *commands;
546 unsigned int commands_idx = 0;
547 unsigned int cmds_started, tgts_started;
548 int ignoring = 0, in_ignored_define = 0;
549 int no_targets = 0; /* Set when reading a rule without targets. */
550 struct nameseq *filenames = 0;
551 struct dep *deps = 0;
552 long nlines = 0;
553 int two_colon = 0;
554 const char *pattern = 0;
555 const char *pattern_percent;
556 struct floc *fstart;
557 struct floc fi;
559 #define record_waiting_files() \
560 do \
562 if (filenames != 0) \
564 fi.lineno = tgts_started; \
565 record_files (filenames, pattern, pattern_percent, deps, \
566 cmds_started, commands, commands_idx, two_colon, \
567 &fi); \
569 filenames = 0; \
570 commands_idx = 0; \
571 no_targets = 0; \
572 pattern = 0; \
573 } while (0)
575 pattern_percent = 0;
576 cmds_started = tgts_started = 1;
578 fstart = &ebuf->floc;
579 fi.filenm = ebuf->floc.filenm;
581 /* Loop over lines in the file.
582 The strategy is to accumulate target names in FILENAMES, dependencies
583 in DEPS and commands in COMMANDS. These are used to define a rule
584 when the start of the next rule (or eof) is encountered.
586 When you see a "continue" in the loop below, that means we are moving on
587 to the next line _without_ ending any rule that we happen to be working
588 with at the moment. If you see a "goto rule_complete", then the
589 statement we just parsed also finishes the previous rule. */
591 commands = xmalloc (200);
593 while (1)
595 unsigned int linelen;
596 char *line;
597 unsigned int wlen;
598 char *p;
599 char *p2;
600 struct vmodifiers vmod;
602 /* At the top of this loop, we are starting a brand new line. */
603 /* Grab the next line to be evaluated */
604 ebuf->floc.lineno += nlines;
605 nlines = readline (ebuf);
607 /* If there is nothing left to eval, we're done. */
608 if (nlines < 0)
609 break;
611 /* If this line is empty, skip it. */
612 line = ebuf->buffer;
613 if (line[0] == '\0')
614 continue;
616 linelen = strlen (line);
618 /* Check for a shell command line first.
619 If it is not one, we can stop treating tab specially. */
620 if (line[0] == cmd_prefix)
622 if (no_targets)
623 /* Ignore the commands in a rule with no targets. */
624 continue;
626 /* If there is no preceding rule line, don't treat this line
627 as a command, even though it begins with a recipe prefix.
628 SunOS 4 make appears to behave this way. */
630 if (filenames != 0)
632 if (ignoring)
633 /* Yep, this is a shell command, and we don't care. */
634 continue;
636 /* Append this command line to the line being accumulated.
637 Strip command prefix chars that appear after newlines. */
638 if (commands_idx == 0)
639 cmds_started = ebuf->floc.lineno;
641 if (linelen + commands_idx > commands_len)
643 commands_len = (linelen + commands_idx) * 2;
644 commands = xrealloc (commands, commands_len);
646 p = &commands[commands_idx];
647 p2 = line + 1;
648 while (--linelen)
650 ++commands_idx;
651 *(p++) = *p2;
652 if (p2[0] == '\n' && p2[1] == cmd_prefix)
654 ++p2;
655 --linelen;
657 ++p2;
659 *p = '\n';
660 ++commands_idx;
662 continue;
666 /* This line is not a shell command line. Don't worry about whitespace.
667 Get more space if we need it; we don't need to preserve the current
668 contents of the buffer. */
670 if (collapsed_length < linelen+1)
672 collapsed_length = linelen+1;
673 if (collapsed)
674 free (collapsed);
675 /* Don't need xrealloc: we don't need to preserve the content. */
676 collapsed = xmalloc (collapsed_length);
678 strcpy (collapsed, line);
679 /* Collapse continuation lines. */
680 collapse_continuations (collapsed);
681 remove_comments (collapsed);
683 /* Get rid if starting space (including formfeed, vtab, etc.) */
684 p = collapsed;
685 while (isspace ((unsigned char)*p))
686 ++p;
688 /* See if this is a variable assignment. We need to do this early, to
689 allow variables with names like 'ifdef', 'export', 'private', etc. */
690 p = parse_var_assignment(p, &vmod);
691 if (vmod.assign_v)
693 struct variable *v;
694 enum variable_origin origin = vmod.override_v ? o_override : o_file;
696 /* If we're ignoring then we're done now. */
697 if (ignoring)
699 if (vmod.define_v)
700 in_ignored_define = 1;
701 continue;
704 if (vmod.define_v)
705 v = do_define (p, origin, ebuf);
706 else
707 v = try_variable_definition (fstart, p, origin, 0);
709 assert (v != NULL);
711 if (vmod.export_v)
712 v->export = v_export;
713 if (vmod.private_v)
714 v->private_var = 1;
716 /* This line has been dealt with. */
717 goto rule_complete;
720 /* If this line is completely empty, ignore it. */
721 if (*p == '\0')
722 continue;
724 p2 = end_of_token (p);
725 wlen = p2 - p;
726 p2 = next_token (p2);
728 /* If we're in an ignored define, skip this line (but maybe get out). */
729 if (in_ignored_define)
731 /* See if this is an endef line (plus optional comment). */
732 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
733 in_ignored_define = 0;
735 continue;
738 /* Check for conditional state changes. */
740 int i = conditional_line (p, wlen, fstart);
741 if (i != -2)
743 if (i == -1)
744 fatal (fstart, _("invalid syntax in conditional"));
746 ignoring = i;
747 continue;
751 /* Nothing to see here... move along. */
752 if (ignoring)
753 continue;
755 /* Manage the "export" keyword used outside of variable assignment
756 as well as "unexport". */
757 if (word1eq ("export") || word1eq ("unexport"))
759 int exporting = *p == 'u' ? 0 : 1;
761 /* (un)export by itself causes everything to be (un)exported. */
762 if (*p2 == '\0')
763 export_all_variables = exporting;
764 else
766 unsigned int l;
767 const char *cp;
768 char *ap;
770 /* Expand the line so we can use indirect and constructed
771 variable names in an (un)export command. */
772 cp = ap = allocated_variable_expand (p2);
774 for (p = find_next_token (&cp, &l); p != 0;
775 p = find_next_token (&cp, &l))
777 struct variable *v = lookup_variable (p, l);
778 if (v == 0)
779 v = define_variable_loc (p, l, "", o_file, 0, fstart);
780 v->export = exporting ? v_export : v_noexport;
783 free (ap);
785 goto rule_complete;
788 /* Handle the special syntax for vpath. */
789 if (word1eq ("vpath"))
791 const char *cp;
792 char *vpat;
793 unsigned int l;
794 cp = variable_expand (p2);
795 p = find_next_token (&cp, &l);
796 if (p != 0)
798 vpat = xstrndup (p, l);
799 p = find_next_token (&cp, &l);
800 /* No searchpath means remove all previous
801 selective VPATH's with the same pattern. */
803 else
804 /* No pattern means remove all previous selective VPATH's. */
805 vpat = 0;
806 construct_vpath_list (vpat, p);
807 if (vpat != 0)
808 free (vpat);
810 goto rule_complete;
813 /* Handle include and variants. */
814 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
816 /* We have found an `include' line specifying a nested
817 makefile to be read at this point. */
818 struct conditionals *save;
819 struct conditionals new_conditionals;
820 struct nameseq *files;
821 /* "-include" (vs "include") says no error if the file does not
822 exist. "sinclude" is an alias for this from SGI. */
823 int noerror = (p[0] != 'i');
825 p = allocated_variable_expand (p2);
827 /* If no filenames, it's a no-op. */
828 if (*p == '\0')
830 free (p);
831 continue;
834 /* Parse the list of file names. */
835 p2 = p;
836 files = multi_glob (parse_file_seq (&p2, '\0',
837 sizeof (struct nameseq),
839 sizeof (struct nameseq), 0);
840 free (p);
842 /* Save the state of conditionals and start
843 the included makefile with a clean slate. */
844 save = install_conditionals (&new_conditionals);
846 /* Record the rules that are waiting so they will determine
847 the default goal before those in the included makefile. */
848 record_waiting_files ();
850 /* Read each included makefile. */
851 while (files != 0)
853 struct nameseq *next = files->next;
854 const char *name = files->name;
855 int r;
857 free (files);
858 files = next;
860 r = eval_makefile (name,
861 (RM_INCLUDED | RM_NO_TILDE
862 | (noerror ? RM_DONTCARE : 0)
863 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
864 if (!r && !noerror)
865 error (fstart, "%s: %s", name, strerror (errno));
868 /* Restore conditional state. */
869 restore_conditionals (save);
871 goto rule_complete;
874 /* This line starts with a tab but was not caught above because there
875 was no preceding target, and the line might have been usable as a
876 variable definition. But now we know it is definitely lossage. */
877 if (line[0] == cmd_prefix)
878 fatal(fstart, _("recipe commences before first target"));
880 /* This line describes some target files. This is complicated by
881 the existence of target-specific variables, because we can't
882 expand the entire line until we know if we have one or not. So
883 we expand the line word by word until we find the first `:',
884 then check to see if it's a target-specific variable.
886 In this algorithm, `lb_next' will point to the beginning of the
887 unexpanded parts of the input buffer, while `p2' points to the
888 parts of the expanded buffer we haven't searched yet. */
891 enum make_word_type wtype;
892 char *cmdleft, *semip, *lb_next;
893 unsigned int plen = 0;
894 char *colonp;
895 const char *end, *beg; /* Helpers for whitespace stripping. */
897 /* Record the previous rule. */
899 record_waiting_files ();
900 tgts_started = fstart->lineno;
902 /* Search the line for an unquoted ; that is not after an
903 unquoted #. */
904 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
905 if (cmdleft != 0 && *cmdleft == '#')
907 /* We found a comment before a semicolon. */
908 *cmdleft = '\0';
909 cmdleft = 0;
911 else if (cmdleft != 0)
912 /* Found one. Cut the line short there before expanding it. */
913 *(cmdleft++) = '\0';
914 semip = cmdleft;
916 collapse_continuations (line);
918 /* We can't expand the entire line, since if it's a per-target
919 variable we don't want to expand it. So, walk from the
920 beginning, expanding as we go, and looking for "interesting"
921 chars. The first word is always expandable. */
922 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
923 switch (wtype)
925 case w_eol:
926 if (cmdleft != 0)
927 fatal(fstart, _("missing rule before recipe"));
928 /* This line contained something but turned out to be nothing
929 but whitespace (a comment?). */
930 continue;
932 case w_colon:
933 case w_dcolon:
934 /* We accept and ignore rules without targets for
935 compatibility with SunOS 4 make. */
936 no_targets = 1;
937 continue;
939 default:
940 break;
943 p2 = variable_expand_string(NULL, lb_next, wlen);
945 while (1)
947 lb_next += wlen;
948 if (cmdleft == 0)
950 /* Look for a semicolon in the expanded line. */
951 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
953 if (cmdleft != 0)
955 unsigned long p2_off = p2 - variable_buffer;
956 unsigned long cmd_off = cmdleft - variable_buffer;
957 char *pend = p2 + strlen(p2);
959 /* Append any remnants of lb, then cut the line short
960 at the semicolon. */
961 *cmdleft = '\0';
963 /* One school of thought says that you shouldn't expand
964 here, but merely copy, since now you're beyond a ";"
965 and into a command script. However, the old parser
966 expanded the whole line, so we continue that for
967 backwards-compatiblity. Also, it wouldn't be
968 entirely consistent, since we do an unconditional
969 expand below once we know we don't have a
970 target-specific variable. */
971 (void)variable_expand_string(pend, lb_next, (long)-1);
972 lb_next += strlen(lb_next);
973 p2 = variable_buffer + p2_off;
974 cmdleft = variable_buffer + cmd_off + 1;
978 colonp = find_char_unquote(p2, ':', 0, 0, 0);
979 #ifdef HAVE_DOS_PATHS
980 /* The drive spec brain-damage strikes again... */
981 /* Note that the only separators of targets in this context
982 are whitespace and a left paren. If others are possible,
983 they should be added to the string in the call to index. */
984 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
985 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
986 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
987 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
988 #endif
989 if (colonp != 0)
990 break;
992 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
993 if (wtype == w_eol)
994 break;
996 p2 += strlen(p2);
997 *(p2++) = ' ';
998 p2 = variable_expand_string(p2, lb_next, wlen);
999 /* We don't need to worry about cmdleft here, because if it was
1000 found in the variable_buffer the entire buffer has already
1001 been expanded... we'll never get here. */
1004 p2 = next_token (variable_buffer);
1006 /* If the word we're looking at is EOL, see if there's _anything_
1007 on the line. If not, a variable expanded to nothing, so ignore
1008 it. If so, we can't parse this line so punt. */
1009 if (wtype == w_eol)
1011 if (*p2 != '\0')
1012 /* There's no need to be ivory-tower about this: check for
1013 one of the most common bugs found in makefiles... */
1014 fatal (fstart, _("missing separator%s"),
1015 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1016 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1017 continue;
1020 /* Make the colon the end-of-string so we know where to stop
1021 looking for targets. */
1022 *colonp = '\0';
1023 filenames = multi_glob (parse_file_seq (&p2, '\0',
1024 sizeof (struct nameseq),
1026 sizeof (struct nameseq), 0);
1027 *p2 = ':';
1029 if (!filenames)
1031 /* We accept and ignore rules without targets for
1032 compatibility with SunOS 4 make. */
1033 no_targets = 1;
1034 continue;
1036 /* This should never be possible; we handled it above. */
1037 assert (*p2 != '\0');
1038 ++p2;
1040 /* Is this a one-colon or two-colon entry? */
1041 two_colon = *p2 == ':';
1042 if (two_colon)
1043 p2++;
1045 /* Test to see if it's a target-specific variable. Copy the rest
1046 of the buffer over, possibly temporarily (we'll expand it later
1047 if it's not a target-specific variable). PLEN saves the length
1048 of the unparsed section of p2, for later. */
1049 if (*lb_next != '\0')
1051 unsigned int l = p2 - variable_buffer;
1052 plen = strlen (p2);
1053 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1054 p2 = variable_buffer + l;
1057 p2 = parse_var_assignment (p2, &vmod);
1058 if (vmod.assign_v)
1060 /* If there was a semicolon found, add it back, plus anything
1061 after it. */
1062 if (semip)
1064 unsigned int l = p - variable_buffer;
1065 *(--semip) = ';';
1066 collapse_continuations (semip);
1067 variable_buffer_output (p2 + strlen (p2),
1068 semip, strlen (semip)+1);
1069 p = variable_buffer + l;
1071 record_target_var (filenames, p2,
1072 vmod.override_v ? o_override : o_file,
1073 &vmod, fstart);
1074 filenames = 0;
1075 continue;
1078 /* This is a normal target, _not_ a target-specific variable.
1079 Unquote any = in the dependency list. */
1080 find_char_unquote (lb_next, '=', 0, 0, 0);
1082 /* We have some targets, so don't ignore the following commands. */
1083 no_targets = 0;
1085 /* Expand the dependencies, etc. */
1086 if (*lb_next != '\0')
1088 unsigned int l = p2 - variable_buffer;
1089 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1090 p2 = variable_buffer + l;
1092 /* Look for a semicolon in the expanded line. */
1093 if (cmdleft == 0)
1095 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1096 if (cmdleft != 0)
1097 *(cmdleft++) = '\0';
1101 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1102 p = strchr (p2, ':');
1103 while (p != 0 && p[-1] == '\\')
1105 register char *q = &p[-1];
1106 register int backslash = 0;
1107 while (*q-- == '\\')
1108 backslash = !backslash;
1109 if (backslash)
1110 p = strchr (p + 1, ':');
1111 else
1112 break;
1114 #ifdef _AMIGA
1115 /* Here, the situation is quite complicated. Let's have a look
1116 at a couple of targets:
1118 install: dev:make
1120 dev:make: make
1122 dev:make:: xyz
1124 The rule is that it's only a target, if there are TWO :'s
1125 OR a space around the :.
1127 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1128 || isspace ((unsigned char)p[-1])))
1129 p = 0;
1130 #endif
1131 #ifdef HAVE_DOS_PATHS
1133 int check_again;
1134 do {
1135 check_again = 0;
1136 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1137 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1138 isalpha ((unsigned char)p[-1]) &&
1139 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1140 p = strchr (p + 1, ':');
1141 check_again = 1;
1143 } while (check_again);
1145 #endif
1146 if (p != 0)
1148 struct nameseq *target;
1149 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
1150 ++p2;
1151 if (target == 0)
1152 fatal (fstart, _("missing target pattern"));
1153 else if (target->next != 0)
1154 fatal (fstart, _("multiple target patterns"));
1155 pattern_percent = find_percent_cached (&target->name);
1156 pattern = target->name;
1157 if (pattern_percent == 0)
1158 fatal (fstart, _("target pattern contains no `%%'"));
1159 free (target);
1161 else
1162 pattern = 0;
1164 /* Strip leading and trailing whitespaces. */
1165 beg = p2;
1166 end = beg + strlen (beg) - 1;
1167 strip_whitespace (&beg, &end);
1169 if (beg <= end && *beg != '\0')
1171 /* Put all the prerequisites here; they'll be parsed later. */
1172 deps = alloc_dep ();
1173 deps->name = strcache_add_len (beg, end - beg + 1);
1175 else
1176 deps = 0;
1178 commands_idx = 0;
1179 if (cmdleft != 0)
1181 /* Semicolon means rest of line is a command. */
1182 unsigned int l = strlen (cmdleft);
1184 cmds_started = fstart->lineno;
1186 /* Add this command line to the buffer. */
1187 if (l + 2 > commands_len)
1189 commands_len = (l + 2) * 2;
1190 commands = xrealloc (commands, commands_len);
1192 memcpy (commands, cmdleft, l);
1193 commands_idx += l;
1194 commands[commands_idx++] = '\n';
1197 /* Determine if this target should be made default. We used to do
1198 this in record_files() but because of the delayed target recording
1199 and because preprocessor directives are legal in target's commands
1200 it is too late. Consider this fragment for example:
1202 foo:
1204 ifeq ($(.DEFAULT_GOAL),foo)
1206 endif
1208 Because the target is not recorded until after ifeq directive is
1209 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1210 would expect. Because of this we have to move the logic here. */
1212 if (set_default && default_goal_var->value[0] == '\0')
1214 const char *name;
1215 struct dep *d;
1216 struct nameseq *t = filenames;
1218 for (; t != 0; t = t->next)
1220 int reject = 0;
1221 name = t->name;
1223 /* We have nothing to do if this is an implicit rule. */
1224 if (strchr (name, '%') != 0)
1225 break;
1227 /* See if this target's name does not start with a `.',
1228 unless it contains a slash. */
1229 if (*name == '.' && strchr (name, '/') == 0
1230 #ifdef HAVE_DOS_PATHS
1231 && strchr (name, '\\') == 0
1232 #endif
1234 continue;
1237 /* If this file is a suffix, don't let it be
1238 the default goal file. */
1239 for (d = suffix_file->deps; d != 0; d = d->next)
1241 register struct dep *d2;
1242 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1244 reject = 1;
1245 break;
1247 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1249 unsigned int l = strlen (dep_name (d2));
1250 if (!strneq (name, dep_name (d2), l))
1251 continue;
1252 if (streq (name + l, dep_name (d)))
1254 reject = 1;
1255 break;
1259 if (reject)
1260 break;
1263 if (!reject)
1265 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1266 o_file, 0, NILF);
1267 break;
1272 continue;
1275 /* We get here except in the case that we just read a rule line.
1276 Record now the last rule we read, so following spurious
1277 commands are properly diagnosed. */
1278 rule_complete:
1279 record_waiting_files ();
1282 #undef word1eq
1284 if (conditionals->if_cmds)
1285 fatal (fstart, _("missing `endif'"));
1287 /* At eof, record the last rule. */
1288 record_waiting_files ();
1290 if (collapsed)
1291 free (collapsed);
1292 free (commands);
1294 return 1;
1298 /* Remove comments from LINE.
1299 This is done by copying the text at LINE onto itself. */
1301 static void
1302 remove_comments (char *line)
1304 char *comment;
1306 comment = find_char_unquote (line, '#', 0, 0, 0);
1308 if (comment != 0)
1309 /* Cut off the line at the #. */
1310 *comment = '\0';
1313 /* Execute a `define' directive.
1314 The first line has already been read, and NAME is the name of
1315 the variable to be defined. The following lines remain to be read. */
1317 static struct variable *
1318 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1320 struct variable *v;
1321 enum variable_flavor flavor;
1322 struct floc defstart;
1323 int nlevels = 1;
1324 unsigned int length = 100;
1325 char *definition = xmalloc (length);
1326 unsigned int idx = 0;
1327 char *p, *var;
1329 defstart = ebuf->floc;
1331 p = parse_variable_definition (name, &flavor);
1332 if (p == NULL)
1333 /* No assignment token, so assume recursive. */
1334 flavor = f_recursive;
1335 else
1337 if (*(next_token (p)) != '\0')
1338 error (&defstart, _("extraneous text after `define' directive"));
1340 /* Chop the string before the assignment token to get the name. */
1341 p[flavor == f_recursive ? -1 : -2] = '\0';
1344 /* Expand the variable name and find the beginning (NAME) and end. */
1345 var = allocated_variable_expand (name);
1346 name = next_token (var);
1347 if (*name == '\0')
1348 fatal (&defstart, _("empty variable name"));
1349 p = name + strlen (name) - 1;
1350 while (p > name && isblank ((unsigned char)*p))
1351 --p;
1352 p[1] = '\0';
1354 /* Now read the value of the variable. */
1355 while (1)
1357 unsigned int len;
1358 char *line;
1359 long nlines = readline (ebuf);
1361 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1362 if (nlines < 0)
1363 fatal (&defstart, _("missing `endef', unterminated `define'"));
1365 ebuf->floc.lineno += nlines;
1366 line = ebuf->buffer;
1368 collapse_continuations (line);
1370 /* If the line doesn't begin with a tab, test to see if it introduces
1371 another define, or ends one. Stop if we find an 'endef' */
1372 if (line[0] != cmd_prefix)
1374 p = next_token (line);
1375 len = strlen (p);
1377 /* If this is another 'define', increment the level count. */
1378 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1379 && strneq (p, "define", 6))
1380 ++nlevels;
1382 /* If this is an 'endef', decrement the count. If it's now 0,
1383 we've found the last one. */
1384 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1385 && strneq (p, "endef", 5))
1387 p += 5;
1388 remove_comments (p);
1389 if (*(next_token (p)) != '\0')
1390 error (&ebuf->floc,
1391 _("extraneous text after `endef' directive"));
1393 if (--nlevels == 0)
1394 break;
1398 /* Add this line to the variable definition. */
1399 len = strlen (line);
1400 if (idx + len + 1 > length)
1402 length = (idx + len) * 2;
1403 definition = xrealloc (definition, length + 1);
1406 memcpy (&definition[idx], line, len);
1407 idx += len;
1408 /* Separate lines with a newline. */
1409 definition[idx++] = '\n';
1412 /* We've got what we need; define the variable. */
1413 if (idx == 0)
1414 definition[0] = '\0';
1415 else
1416 definition[idx - 1] = '\0';
1418 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1419 free (definition);
1420 free (var);
1421 return (v);
1424 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1425 "ifneq", "else" and "endif".
1426 LINE is the input line, with the command as its first word.
1428 FILENAME and LINENO are the filename and line number in the
1429 current makefile. They are used for error messages.
1431 Value is -2 if the line is not a conditional at all,
1432 -1 if the line is an invalid conditional,
1433 0 if following text should be interpreted,
1434 1 if following text should be ignored. */
1436 static int
1437 conditional_line (char *line, int len, const struct floc *flocp)
1439 char *cmdname;
1440 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1441 unsigned int i;
1442 unsigned int o;
1444 /* Compare a word, both length and contents. */
1445 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1446 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1448 /* Make sure this line is a conditional. */
1449 chkword ("ifdef", c_ifdef)
1450 else chkword ("ifndef", c_ifndef)
1451 else chkword ("ifeq", c_ifeq)
1452 else chkword ("ifneq", c_ifneq)
1453 else chkword ("else", c_else)
1454 else chkword ("endif", c_endif)
1455 else
1456 return -2;
1458 /* Found one: skip past it and any whitespace after it. */
1459 line = next_token (line + len);
1461 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1463 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1464 if (cmdtype == c_endif)
1466 if (*line != '\0')
1467 EXTRANEOUS ();
1469 if (!conditionals->if_cmds)
1470 fatal (flocp, _("extraneous `%s'"), cmdname);
1472 --conditionals->if_cmds;
1474 goto DONE;
1477 /* An 'else' statement can either be simple, or it can have another
1478 conditional after it. */
1479 if (cmdtype == c_else)
1481 const char *p;
1483 if (!conditionals->if_cmds)
1484 fatal (flocp, _("extraneous `%s'"), cmdname);
1486 o = conditionals->if_cmds - 1;
1488 if (conditionals->seen_else[o])
1489 fatal (flocp, _("only one `else' per conditional"));
1491 /* Change the state of ignorance. */
1492 switch (conditionals->ignoring[o])
1494 case 0:
1495 /* We've just been interpreting. Never do it again. */
1496 conditionals->ignoring[o] = 2;
1497 break;
1498 case 1:
1499 /* We've never interpreted yet. Maybe this time! */
1500 conditionals->ignoring[o] = 0;
1501 break;
1504 /* It's a simple 'else'. */
1505 if (*line == '\0')
1507 conditionals->seen_else[o] = 1;
1508 goto DONE;
1511 /* The 'else' has extra text. That text must be another conditional
1512 and cannot be an 'else' or 'endif'. */
1514 /* Find the length of the next word. */
1515 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1517 len = p - line;
1519 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1520 if (word1eq("else") || word1eq("endif")
1521 || conditional_line (line, len, flocp) < 0)
1522 EXTRANEOUS ();
1523 else
1525 /* conditional_line() created a new level of conditional.
1526 Raise it back to this level. */
1527 if (conditionals->ignoring[o] < 2)
1528 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1529 --conditionals->if_cmds;
1532 goto DONE;
1535 if (conditionals->allocated == 0)
1537 conditionals->allocated = 5;
1538 conditionals->ignoring = xmalloc (conditionals->allocated);
1539 conditionals->seen_else = xmalloc (conditionals->allocated);
1542 o = conditionals->if_cmds++;
1543 if (conditionals->if_cmds > conditionals->allocated)
1545 conditionals->allocated += 5;
1546 conditionals->ignoring = xrealloc (conditionals->ignoring,
1547 conditionals->allocated);
1548 conditionals->seen_else = xrealloc (conditionals->seen_else,
1549 conditionals->allocated);
1552 /* Record that we have seen an `if...' but no `else' so far. */
1553 conditionals->seen_else[o] = 0;
1555 /* Search through the stack to see if we're already ignoring. */
1556 for (i = 0; i < o; ++i)
1557 if (conditionals->ignoring[i])
1559 /* We are already ignoring, so just push a level to match the next
1560 "else" or "endif", and keep ignoring. We don't want to expand
1561 variables in the condition. */
1562 conditionals->ignoring[o] = 1;
1563 return 1;
1566 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1568 char *var;
1569 struct variable *v;
1570 char *p;
1572 /* Expand the thing we're looking up, so we can use indirect and
1573 constructed variable names. */
1574 var = allocated_variable_expand (line);
1576 /* Make sure there's only one variable name to test. */
1577 p = end_of_token (var);
1578 i = p - var;
1579 p = next_token (p);
1580 if (*p != '\0')
1581 return -1;
1583 var[i] = '\0';
1584 v = lookup_variable (var, i);
1586 conditionals->ignoring[o] =
1587 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1589 free (var);
1591 else
1593 /* "ifeq" or "ifneq". */
1594 char *s1, *s2;
1595 unsigned int l;
1596 char termin = *line == '(' ? ',' : *line;
1598 if (termin != ',' && termin != '"' && termin != '\'')
1599 return -1;
1601 s1 = ++line;
1602 /* Find the end of the first string. */
1603 if (termin == ',')
1605 int count = 0;
1606 for (; *line != '\0'; ++line)
1607 if (*line == '(')
1608 ++count;
1609 else if (*line == ')')
1610 --count;
1611 else if (*line == ',' && count <= 0)
1612 break;
1614 else
1615 while (*line != '\0' && *line != termin)
1616 ++line;
1618 if (*line == '\0')
1619 return -1;
1621 if (termin == ',')
1623 /* Strip blanks after the first string. */
1624 char *p = line++;
1625 while (isblank ((unsigned char)p[-1]))
1626 --p;
1627 *p = '\0';
1629 else
1630 *line++ = '\0';
1632 s2 = variable_expand (s1);
1633 /* We must allocate a new copy of the expanded string because
1634 variable_expand re-uses the same buffer. */
1635 l = strlen (s2);
1636 s1 = alloca (l + 1);
1637 memcpy (s1, s2, l + 1);
1639 if (termin != ',')
1640 /* Find the start of the second string. */
1641 line = next_token (line);
1643 termin = termin == ',' ? ')' : *line;
1644 if (termin != ')' && termin != '"' && termin != '\'')
1645 return -1;
1647 /* Find the end of the second string. */
1648 if (termin == ')')
1650 int count = 0;
1651 s2 = next_token (line);
1652 for (line = s2; *line != '\0'; ++line)
1654 if (*line == '(')
1655 ++count;
1656 else if (*line == ')')
1658 if (count <= 0)
1659 break;
1660 else
1661 --count;
1665 else
1667 ++line;
1668 s2 = line;
1669 while (*line != '\0' && *line != termin)
1670 ++line;
1673 if (*line == '\0')
1674 return -1;
1676 *line = '\0';
1677 line = next_token (++line);
1678 if (*line != '\0')
1679 EXTRANEOUS ();
1681 s2 = variable_expand (s2);
1682 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1685 DONE:
1686 /* Search through the stack to see if we're ignoring. */
1687 for (i = 0; i < conditionals->if_cmds; ++i)
1688 if (conditionals->ignoring[i])
1689 return 1;
1690 return 0;
1693 /* Remove duplicate dependencies in CHAIN. */
1695 static unsigned long
1696 dep_hash_1 (const void *key)
1698 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1701 static unsigned long
1702 dep_hash_2 (const void *key)
1704 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1707 static int
1708 dep_hash_cmp (const void *x, const void *y)
1710 struct dep *dx = (struct dep *) x;
1711 struct dep *dy = (struct dep *) y;
1712 int cmp = strcmp (dep_name (dx), dep_name (dy));
1714 /* If the names are the same but ignore_mtimes are not equal, one of these
1715 is an order-only prerequisite and one isn't. That means that we should
1716 remove the one that isn't and keep the one that is. */
1718 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1719 dx->ignore_mtime = dy->ignore_mtime = 0;
1721 return cmp;
1725 void
1726 uniquize_deps (struct dep *chain)
1728 struct hash_table deps;
1729 register struct dep **depp;
1731 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1733 /* Make sure that no dependencies are repeated. This does not
1734 really matter for the purpose of updating targets, but it
1735 might make some names be listed twice for $^ and $?. */
1737 depp = &chain;
1738 while (*depp)
1740 struct dep *dep = *depp;
1741 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1742 if (HASH_VACANT (*dep_slot))
1744 hash_insert_at (&deps, dep, dep_slot);
1745 depp = &dep->next;
1747 else
1749 /* Don't bother freeing duplicates.
1750 It's dangerous and little benefit accrues. */
1751 *depp = dep->next;
1755 hash_free (&deps, 0);
1758 /* Record target-specific variable values for files FILENAMES.
1759 TWO_COLON is nonzero if a double colon was used.
1761 The links of FILENAMES are freed, and so are any names in it
1762 that are not incorporated into other data structures.
1764 If the target is a pattern, add the variable to the pattern-specific
1765 variable value list. */
1767 static void
1768 record_target_var (struct nameseq *filenames, char *defn,
1769 enum variable_origin origin, struct vmodifiers *vmod,
1770 const struct floc *flocp)
1772 struct nameseq *nextf;
1773 struct variable_set_list *global;
1775 global = current_variable_set_list;
1777 /* If the variable is an append version, store that but treat it as a
1778 normal recursive variable. */
1780 for (; filenames != 0; filenames = nextf)
1782 struct variable *v;
1783 const char *name = filenames->name;
1784 const char *fname;
1785 const char *percent;
1786 struct pattern_var *p;
1788 nextf = filenames->next;
1789 free (filenames);
1791 /* If it's a pattern target, then add it to the pattern-specific
1792 variable list. */
1793 percent = find_percent_cached (&name);
1794 if (percent)
1796 /* Get a reference for this pattern-specific variable struct. */
1797 p = create_pattern_var (name, percent);
1798 p->variable.fileinfo = *flocp;
1799 /* I don't think this can fail since we already determined it was a
1800 variable definition. */
1801 v = assign_variable_definition (&p->variable, defn);
1802 assert (v != 0);
1804 v->origin = origin;
1805 if (v->flavor == f_simple)
1806 v->value = allocated_variable_expand (v->value);
1807 else
1808 v->value = xstrdup (v->value);
1810 fname = p->target;
1812 else
1814 struct file *f;
1816 /* Get a file reference for this file, and initialize it.
1817 We don't want to just call enter_file() because that allocates a
1818 new entry if the file is a double-colon, which we don't want in
1819 this situation. */
1820 f = lookup_file (name);
1821 if (!f)
1822 f = enter_file (strcache_add (name));
1823 else if (f->double_colon)
1824 f = f->double_colon;
1826 initialize_file_variables (f, 1);
1827 fname = f->name;
1829 current_variable_set_list = f->variables;
1830 v = try_variable_definition (flocp, defn, origin, 1);
1831 if (!v)
1832 fatal (flocp, _("Malformed target-specific variable definition"));
1833 current_variable_set_list = global;
1836 /* Set up the variable to be *-specific. */
1837 v->per_target = 1;
1838 v->private_var = vmod->private_v;
1839 v->export = vmod->export_v ? v_export : v_default;
1841 /* If it's not an override, check to see if there was a command-line
1842 setting. If so, reset the value. */
1843 if (v->origin != o_override)
1845 struct variable *gv;
1846 int len = strlen(v->name);
1848 gv = lookup_variable (v->name, len);
1849 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1851 if (v->value != 0)
1852 free (v->value);
1853 v->value = xstrdup (gv->value);
1854 v->origin = gv->origin;
1855 v->recursive = gv->recursive;
1856 v->append = 0;
1862 /* Record a description line for files FILENAMES,
1863 with dependencies DEPS, commands to execute described
1864 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1865 TWO_COLON is nonzero if a double colon was used.
1866 If not nil, PATTERN is the `%' pattern to make this
1867 a static pattern rule, and PATTERN_PERCENT is a pointer
1868 to the `%' within it.
1870 The links of FILENAMES are freed, and so are any names in it
1871 that are not incorporated into other data structures. */
1873 static void
1874 record_files (struct nameseq *filenames, const char *pattern,
1875 const char *pattern_percent, struct dep *deps,
1876 unsigned int cmds_started, char *commands,
1877 unsigned int commands_idx, int two_colon,
1878 const struct floc *flocp)
1880 struct nameseq *nextf;
1881 int implicit = 0;
1882 unsigned int max_targets = 0, target_idx = 0;
1883 const char **targets = 0, **target_percents = 0;
1884 struct commands *cmds;
1886 /* If we've already snapped deps, that means we're in an eval being
1887 resolved after the makefiles have been read in. We can't add more rules
1888 at this time, since they won't get snapped and we'll get core dumps.
1889 See Savannah bug # 12124. */
1890 if (snapped_deps)
1891 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1893 if (commands_idx > 0)
1895 cmds = xmalloc (sizeof (struct commands));
1896 cmds->fileinfo.filenm = flocp->filenm;
1897 cmds->fileinfo.lineno = cmds_started;
1898 cmds->commands = xstrndup (commands, commands_idx);
1899 cmds->command_lines = 0;
1901 else
1902 cmds = 0;
1904 for (; filenames != 0; filenames = nextf)
1906 const char *name = filenames->name;
1907 struct file *f;
1908 struct dep *this = 0;
1909 const char *implicit_percent;
1911 nextf = filenames->next;
1912 free (filenames);
1914 /* Check for special targets. Do it here instead of, say, snap_deps()
1915 so that we can immediately use the value. */
1917 if (streq (name, ".POSIX"))
1918 posix_pedantic = 1;
1919 else if (streq (name, ".SECONDEXPANSION"))
1920 second_expansion = 1;
1922 implicit_percent = find_percent_cached (&name);
1923 implicit |= implicit_percent != 0;
1925 if (implicit)
1927 if (pattern != 0)
1928 fatal (flocp, _("mixed implicit and static pattern rules"));
1930 if (implicit_percent == 0)
1931 fatal (flocp, _("mixed implicit and normal rules"));
1933 if (targets == 0)
1935 max_targets = 5;
1936 targets = xmalloc (5 * sizeof (char *));
1937 target_percents = xmalloc (5 * sizeof (char *));
1938 target_idx = 0;
1940 else if (target_idx == max_targets - 1)
1942 max_targets += 5;
1943 targets = xrealloc (targets, max_targets * sizeof (char *));
1944 target_percents = xrealloc (target_percents,
1945 max_targets * sizeof (char *));
1947 targets[target_idx] = name;
1948 target_percents[target_idx] = implicit_percent;
1949 ++target_idx;
1950 continue;
1953 /* If this is a static pattern rule:
1954 `targets: target%pattern: dep%pattern; cmds',
1955 make sure the pattern matches this target name. */
1956 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1957 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1958 else if (deps)
1960 /* If there are multiple filenames, copy the chain DEPS for all but
1961 the last one. It is not safe for the same deps to go in more
1962 than one place in the database. */
1963 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1964 this->need_2nd_expansion = (second_expansion
1965 && strchr (this->name, '$'));
1968 if (!two_colon)
1970 /* Single-colon. Combine these dependencies
1971 with others in file's existing record, if any. */
1972 f = enter_file (strcache_add (name));
1974 if (f->double_colon)
1975 fatal (flocp,
1976 _("target file `%s' has both : and :: entries"), f->name);
1978 /* If CMDS == F->CMDS, this target was listed in this rule
1979 more than once. Just give a warning since this is harmless. */
1980 if (cmds != 0 && cmds == f->cmds)
1981 error (flocp,
1982 _("target `%s' given more than once in the same rule."),
1983 f->name);
1985 /* Check for two single-colon entries both with commands.
1986 Check is_target so that we don't lose on files such as .c.o
1987 whose commands were preinitialized. */
1988 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1990 error (&cmds->fileinfo,
1991 _("warning: overriding recipe for target `%s'"),
1992 f->name);
1993 error (&f->cmds->fileinfo,
1994 _("warning: ignoring old recipe for target `%s'"),
1995 f->name);
1998 f->is_target = 1;
2000 /* Defining .DEFAULT with no deps or cmds clears it. */
2001 if (f == default_file && this == 0 && cmds == 0)
2002 f->cmds = 0;
2003 if (cmds != 0)
2004 f->cmds = cmds;
2006 /* Defining .SUFFIXES with no dependencies clears out the list of
2007 suffixes. */
2008 if (f == suffix_file && this == 0)
2010 free_dep_chain (f->deps);
2011 f->deps = 0;
2013 else if (this != 0)
2015 /* Add the file's old deps and the new ones in THIS together. */
2017 if (f->deps != 0)
2019 struct dep **d_ptr = &f->deps;
2021 while ((*d_ptr)->next != 0)
2022 d_ptr = &(*d_ptr)->next;
2024 if (cmds != 0)
2026 /* This is the rule with commands, so put its deps
2027 last. The rationale behind this is that $< expands to
2028 the first dep in the chain, and commands use $<
2029 expecting to get the dep that rule specifies. However
2030 the second expansion algorithm reverses the order thus
2031 we need to make it last here. */
2032 (*d_ptr)->next = this;
2033 /* This is a hack. I need a way to communicate to
2034 snap_deps() that the last dependency line in this
2035 file came with commands (so that logic in snap_deps()
2036 can put it in front and all this $< -logic works). I
2037 cannot simply rely on file->cmds being not 0 because
2038 of the cases like the following:
2040 foo: bar
2041 foo:
2044 I am going to temporarily "borrow" UPDATING member in
2045 `struct file' for this. */
2046 f->updating = 1;
2048 else
2050 /* This is a rule without commands. If we already have
2051 a rule with commands and prerequisites (see "hack"
2052 comment above), put these prereqs at the end but
2053 before prereqs from the rule with commands. This way
2054 everything appears in makefile order. */
2055 if (f->updating)
2057 this->next = *d_ptr;
2058 *d_ptr = this;
2060 else
2061 (*d_ptr)->next = this;
2064 else
2065 f->deps = this;
2068 else
2070 /* Double-colon. Make a new record even if there already is one. */
2071 f = lookup_file (name);
2073 /* Check for both : and :: rules. Check is_target so
2074 we don't lose on default suffix rules or makefiles. */
2075 if (f != 0 && f->is_target && !f->double_colon)
2076 fatal (flocp,
2077 _("target file `%s' has both : and :: entries"), f->name);
2078 f = enter_file (strcache_add (name));
2079 /* If there was an existing entry and it was a double-colon entry,
2080 enter_file will have returned a new one, making it the prev
2081 pointer of the old one, and setting its double_colon pointer to
2082 the first one. */
2083 if (f->double_colon == 0)
2084 /* This is the first entry for this name, so we must set its
2085 double_colon pointer to itself. */
2086 f->double_colon = f;
2087 f->is_target = 1;
2088 f->deps = this;
2089 f->cmds = cmds;
2092 /* If this is a static pattern rule, set the stem to the part of its
2093 name that matched the `%' in the pattern, so you can use $* in the
2094 commands. */
2095 if (pattern)
2097 static const char *percent = "%";
2098 char *buffer = variable_expand ("");
2099 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2100 pattern_percent+1, percent+1);
2101 f->stem = strcache_add_len (buffer, o - buffer);
2102 if (this)
2104 this->staticpattern = 1;
2105 this->stem = f->stem;
2109 name = f->name;
2112 if (implicit)
2114 if (deps)
2115 deps->need_2nd_expansion = second_expansion;
2116 create_pattern_rule (targets, target_percents, target_idx,
2117 two_colon, deps, cmds, 1);
2121 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2122 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2123 Quoting backslashes are removed from STRING by compacting it into
2124 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2125 one, or nil if there are none. STOPCHARs inside variable references are
2126 ignored if IGNOREVARS is true.
2128 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2130 static char *
2131 find_char_unquote (char *string, int stop1, int stop2, int blank,
2132 int ignorevars)
2134 unsigned int string_len = 0;
2135 char *p = string;
2137 if (ignorevars)
2138 ignorevars = '$';
2140 while (1)
2142 if (stop2 && blank)
2143 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2144 && ! isblank ((unsigned char) *p))
2145 ++p;
2146 else if (stop2)
2147 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2148 ++p;
2149 else if (blank)
2150 while (*p != '\0' && *p != ignorevars && *p != stop1
2151 && ! isblank ((unsigned char) *p))
2152 ++p;
2153 else
2154 while (*p != '\0' && *p != ignorevars && *p != stop1)
2155 ++p;
2157 if (*p == '\0')
2158 break;
2160 /* If we stopped due to a variable reference, skip over its contents. */
2161 if (*p == ignorevars)
2163 char openparen = p[1];
2165 p += 2;
2167 /* Skip the contents of a non-quoted, multi-char variable ref. */
2168 if (openparen == '(' || openparen == '{')
2170 unsigned int pcount = 1;
2171 char closeparen = (openparen == '(' ? ')' : '}');
2173 while (*p)
2175 if (*p == openparen)
2176 ++pcount;
2177 else if (*p == closeparen)
2178 if (--pcount == 0)
2180 ++p;
2181 break;
2183 ++p;
2187 /* Skipped the variable reference: look for STOPCHARS again. */
2188 continue;
2191 if (p > string && p[-1] == '\\')
2193 /* Search for more backslashes. */
2194 int i = -2;
2195 while (&p[i] >= string && p[i] == '\\')
2196 --i;
2197 ++i;
2198 /* Only compute the length if really needed. */
2199 if (string_len == 0)
2200 string_len = strlen (string);
2201 /* The number of backslashes is now -I.
2202 Copy P over itself to swallow half of them. */
2203 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2204 p += i/2;
2205 if (i % 2 == 0)
2206 /* All the backslashes quoted each other; the STOPCHAR was
2207 unquoted. */
2208 return p;
2210 /* The STOPCHAR was quoted by a backslash. Look for another. */
2212 else
2213 /* No backslash in sight. */
2214 return p;
2217 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2218 return 0;
2221 /* Search PATTERN for an unquoted % and handle quoting. */
2223 char *
2224 find_percent (char *pattern)
2226 return find_char_unquote (pattern, '%', 0, 0, 0);
2229 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2230 the % or NULL if no % was found.
2231 This version is used with strings in the string cache: if there's a need to
2232 modify the string a new version will be added to the string cache and
2233 *STRING will be set to that. */
2235 const char *
2236 find_percent_cached (const char **string)
2238 const char *p = *string;
2239 char *new = 0;
2240 int slen;
2242 /* If the first char is a % return now. This lets us avoid extra tests
2243 inside the loop. */
2244 if (*p == '%')
2245 return p;
2247 while (1)
2249 while (*p != '\0' && *p != '%')
2250 ++p;
2252 if (*p == '\0')
2253 break;
2255 /* See if this % is escaped with a backslash; if not we're done. */
2256 if (p[-1] != '\\')
2257 break;
2260 /* Search for more backslashes. */
2261 char *pv;
2262 int i = -2;
2264 while (&p[i] >= *string && p[i] == '\\')
2265 --i;
2266 ++i;
2268 /* At this point we know we'll need to allocate a new string.
2269 Make a copy if we haven't yet done so. */
2270 if (! new)
2272 slen = strlen (*string);
2273 new = alloca (slen + 1);
2274 memcpy (new, *string, slen + 1);
2275 p = new + (p - *string);
2276 *string = new;
2279 /* At this point *string, p, and new all point into the same string.
2280 Get a non-const version of p so we can modify new. */
2281 pv = new + (p - *string);
2283 /* The number of backslashes is now -I.
2284 Copy P over itself to swallow half of them. */
2285 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2286 p += i/2;
2288 /* If the backslashes quoted each other; the % was unquoted. */
2289 if (i % 2 == 0)
2290 break;
2294 /* If we had to change STRING, add it to the strcache. */
2295 if (new)
2297 *string = strcache_add (*string);
2298 p = *string + (p - new);
2301 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2302 return (*p == '\0') ? NULL : p;
2305 /* Parse a string into a sequence of filenames represented as a
2306 chain of struct nameseq's in reverse order and return that chain.
2308 The string is passed as STRINGP, the address of a string pointer.
2309 The string pointer is updated to point at the first character
2310 not parsed, which either is a null char or equals STOPCHAR.
2312 SIZE is how big to construct chain elements.
2313 This is useful if we want them actually to be other structures
2314 that have room for additional info.
2316 If STRIP is nonzero, strip `./'s off the beginning. */
2318 struct nameseq *
2319 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2321 struct nameseq *new = 0;
2322 struct nameseq *new1, *lastnew1;
2323 char *p = *stringp;
2325 #ifdef VMS
2326 # define VMS_COMMA ','
2327 #else
2328 # define VMS_COMMA 0
2329 #endif
2331 while (1)
2333 const char *name;
2334 char *q;
2336 /* Skip whitespace; see if any more names are left. */
2337 p = next_token (p);
2338 if (*p == '\0')
2339 break;
2340 if (*p == stopchar)
2341 break;
2343 /* There are, so find the end of the next name. */
2344 q = p;
2345 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2346 #ifdef VMS
2347 /* convert comma separated list to space separated */
2348 if (p && *p == ',')
2349 *p =' ';
2350 #endif
2351 #ifdef _AMIGA
2352 if (stopchar == ':' && p && *p == ':'
2353 && !(isspace ((unsigned char)p[1]) || !p[1]
2354 || isspace ((unsigned char)p[-1])))
2355 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2356 #endif
2357 #ifdef HAVE_DOS_PATHS
2358 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2359 first colon which isn't followed by a slash or a backslash.
2360 Note that tokens separated by spaces should be treated as separate
2361 tokens since make doesn't allow path names with spaces */
2362 if (stopchar == ':')
2363 while (p != 0 && !isspace ((unsigned char)*p) &&
2364 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2365 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2366 #endif
2367 if (p == 0)
2368 p = q + strlen (q);
2370 if (strip)
2371 #ifdef VMS
2372 /* Skip leading `[]'s. */
2373 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2374 #else
2375 /* Skip leading `./'s. */
2376 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2377 #endif
2379 q += 2; /* Skip "./". */
2380 while (q < p && *q == '/')
2381 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2382 ++q;
2385 /* Extract the filename just found, and skip it. */
2387 if (q == p)
2388 /* ".///" was stripped to "". */
2389 #if defined(VMS)
2390 continue;
2391 #elif defined(_AMIGA)
2392 name = "";
2393 #else
2394 name = "./";
2395 #endif
2396 else
2397 #ifdef VMS
2398 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2399 * to remove this '\' before we can use the filename.
2400 * xstrdup called because q may be read-only string constant.
2403 char *qbase = xstrdup (q);
2404 char *pbase = qbase + (p-q);
2405 char *q1 = qbase;
2406 char *q2 = q1;
2407 char *p1 = pbase;
2409 while (q1 != pbase)
2411 if (*q1 == '\\' && *(q1+1) == ':')
2413 q1++;
2414 p1--;
2416 *q2++ = *q1++;
2418 name = strcache_add_len (qbase, p1 - qbase);
2419 free (qbase);
2421 #else
2422 name = strcache_add_len (q, p - q);
2423 #endif
2425 /* Add it to the front of the chain. */
2426 new1 = xmalloc (size);
2427 memset (new1, '\0', size);
2428 new1->name = name;
2429 new1->next = new;
2430 new = new1;
2433 #ifndef NO_ARCHIVES
2435 /* Look for multi-word archive references.
2436 They are indicated by a elt ending with an unmatched `)' and
2437 an elt further down the chain (i.e., previous in the file list)
2438 with an unmatched `(' (e.g., "lib(mem"). */
2440 new1 = new;
2441 lastnew1 = 0;
2442 while (new1 != 0)
2443 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2444 && new1->name[strlen (new1->name) - 1] == ')'
2445 && strchr (new1->name, '(') == 0)
2447 /* NEW1 ends with a `)' but does not contain a `('.
2448 Look back for an elt with an opening `(' but no closing `)'. */
2450 struct nameseq *n = new1->next, *lastn = new1;
2451 char *paren = 0;
2452 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2454 lastn = n;
2455 n = n->next;
2457 if (n != 0
2458 /* Ignore something starting with `(', as that cannot actually
2459 be an archive-member reference (and treating it as such
2460 results in an empty file name, which causes much lossage). */
2461 && n->name[0] != '(')
2463 /* N is the first element in the archive group.
2464 Its name looks like "lib(mem" (with no closing `)'). */
2466 char *libname;
2468 /* Copy "lib(" into LIBNAME. */
2469 ++paren;
2470 libname = alloca (paren - n->name + 1);
2471 memcpy (libname, n->name, paren - n->name);
2472 libname[paren - n->name] = '\0';
2474 if (*paren == '\0')
2476 /* N was just "lib(", part of something like "lib( a b)".
2477 Edit it out of the chain and free its storage. */
2478 lastn->next = n->next;
2479 free (n);
2480 /* LASTN->next is the new stopping elt for the loop below. */
2481 n = lastn->next;
2483 else
2485 /* Replace N's name with the full archive reference. */
2486 n->name = strcache_add (concat (libname, paren, ")"));
2489 if (new1->name[1] == '\0')
2491 /* NEW1 is just ")", part of something like "lib(a b )".
2492 Omit it from the chain and free its storage. */
2493 if (lastnew1 == 0)
2494 new = new1->next;
2495 else
2496 lastnew1->next = new1->next;
2497 lastn = new1;
2498 new1 = new1->next;
2499 free (lastn);
2501 else
2503 /* Replace also NEW1->name, which already has closing `)'. */
2504 new1->name = strcache_add (concat (libname, new1->name, ""));
2505 new1 = new1->next;
2508 /* Trace back from NEW1 (the end of the list) until N
2509 (the beginning of the list), rewriting each name
2510 with the full archive reference. */
2512 while (new1 != n)
2514 new1->name = strcache_add (concat (libname, new1->name, ")"));
2515 lastnew1 = new1;
2516 new1 = new1->next;
2519 else
2521 /* No frobnication happening. Just step down the list. */
2522 lastnew1 = new1;
2523 new1 = new1->next;
2526 else
2528 lastnew1 = new1;
2529 new1 = new1->next;
2532 #endif
2534 *stringp = p;
2535 return new;
2538 /* Find the next line of text in an eval buffer, combining continuation lines
2539 into one line.
2540 Return the number of actual lines read (> 1 if continuation lines).
2541 Returns -1 if there's nothing left in the buffer.
2543 After this function, ebuf->buffer points to the first character of the
2544 line we just found.
2547 /* Read a line of text from a STRING.
2548 Since we aren't really reading from a file, don't bother with linenumbers.
2551 static unsigned long
2552 readstring (struct ebuffer *ebuf)
2554 char *eol;
2556 /* If there is nothing left in this buffer, return 0. */
2557 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2558 return -1;
2560 /* Set up a new starting point for the buffer, and find the end of the
2561 next logical line (taking into account backslash/newline pairs). */
2563 eol = ebuf->buffer = ebuf->bufnext;
2565 while (1)
2567 int backslash = 0;
2568 char *bol = eol;
2569 char *p;
2571 /* Find the next newline. At EOS, stop. */
2572 eol = p = strchr (eol , '\n');
2573 if (!eol)
2575 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2576 return 0;
2579 /* Found a newline; if it's escaped continue; else we're done. */
2580 while (p > bol && *(--p) == '\\')
2581 backslash = !backslash;
2582 if (!backslash)
2583 break;
2584 ++eol;
2587 /* Overwrite the newline char. */
2588 *eol = '\0';
2589 ebuf->bufnext = eol+1;
2591 return 0;
2594 static long
2595 readline (struct ebuffer *ebuf)
2597 char *p;
2598 char *end;
2599 char *start;
2600 long nlines = 0;
2602 /* The behaviors between string and stream buffers are different enough to
2603 warrant different functions. Do the Right Thing. */
2605 if (!ebuf->fp)
2606 return readstring (ebuf);
2608 /* When reading from a file, we always start over at the beginning of the
2609 buffer for each new line. */
2611 p = start = ebuf->bufstart;
2612 end = p + ebuf->size;
2613 *p = '\0';
2615 while (fgets (p, end - p, ebuf->fp) != 0)
2617 char *p2;
2618 unsigned long len;
2619 int backslash;
2621 len = strlen (p);
2622 if (len == 0)
2624 /* This only happens when the first thing on the line is a '\0'.
2625 It is a pretty hopeless case, but (wonder of wonders) Athena
2626 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2627 There is nothing really to be done; we synthesize a newline so
2628 the following line doesn't appear to be part of this line. */
2629 error (&ebuf->floc,
2630 _("warning: NUL character seen; rest of line ignored"));
2631 p[0] = '\n';
2632 len = 1;
2635 /* Jump past the text we just read. */
2636 p += len;
2638 /* If the last char isn't a newline, the whole line didn't fit into the
2639 buffer. Get some more buffer and try again. */
2640 if (p[-1] != '\n')
2641 goto more_buffer;
2643 /* We got a newline, so add one to the count of lines. */
2644 ++nlines;
2646 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2647 /* Check to see if the line was really ended with CRLF; if so ignore
2648 the CR. */
2649 if ((p - start) > 1 && p[-2] == '\r')
2651 --p;
2652 p[-1] = '\n';
2654 #endif
2656 backslash = 0;
2657 for (p2 = p - 2; p2 >= start; --p2)
2659 if (*p2 != '\\')
2660 break;
2661 backslash = !backslash;
2664 if (!backslash)
2666 p[-1] = '\0';
2667 break;
2670 /* It was a backslash/newline combo. If we have more space, read
2671 another line. */
2672 if (end - p >= 80)
2673 continue;
2675 /* We need more space at the end of our buffer, so realloc it.
2676 Make sure to preserve the current offset of p. */
2677 more_buffer:
2679 unsigned long off = p - start;
2680 ebuf->size *= 2;
2681 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2682 p = start + off;
2683 end = start + ebuf->size;
2684 *p = '\0';
2688 if (ferror (ebuf->fp))
2689 pfatal_with_name (ebuf->floc.filenm);
2691 /* If we found some lines, return how many.
2692 If we didn't, but we did find _something_, that indicates we read the last
2693 line of a file with no final newline; return 1.
2694 If we read nothing, we're at EOF; return -1. */
2696 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2699 /* Parse the next "makefile word" from the input buffer, and return info
2700 about it.
2702 A "makefile word" is one of:
2704 w_bogus Should never happen
2705 w_eol End of input
2706 w_static A static word; cannot be expanded
2707 w_variable A word containing one or more variables/functions
2708 w_colon A colon
2709 w_dcolon A double-colon
2710 w_semicolon A semicolon
2711 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2713 Note that this function is only used when reading certain parts of the
2714 makefile. Don't use it where special rules hold sway (RHS of a variable,
2715 in a command list, etc.) */
2717 static enum make_word_type
2718 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2720 enum make_word_type wtype = w_bogus;
2721 char *p = buffer, *beg;
2722 char c;
2724 /* Skip any leading whitespace. */
2725 while (isblank ((unsigned char)*p))
2726 ++p;
2728 beg = p;
2729 c = *(p++);
2730 switch (c)
2732 case '\0':
2733 wtype = w_eol;
2734 break;
2736 case ';':
2737 wtype = w_semicolon;
2738 break;
2740 case '=':
2741 wtype = w_varassign;
2742 break;
2744 case ':':
2745 wtype = w_colon;
2746 switch (*p)
2748 case ':':
2749 ++p;
2750 wtype = w_dcolon;
2751 break;
2753 case '=':
2754 ++p;
2755 wtype = w_varassign;
2756 break;
2758 break;
2760 case '+':
2761 case '?':
2762 if (*p == '=')
2764 ++p;
2765 wtype = w_varassign;
2766 break;
2769 default:
2770 if (delim && strchr (delim, c))
2771 wtype = w_static;
2772 break;
2775 /* Did we find something? If so, return now. */
2776 if (wtype != w_bogus)
2777 goto done;
2779 /* This is some non-operator word. A word consists of the longest
2780 string of characters that doesn't contain whitespace, one of [:=#],
2781 or [?+]=, or one of the chars in the DELIM string. */
2783 /* We start out assuming a static word; if we see a variable we'll
2784 adjust our assumptions then. */
2785 wtype = w_static;
2787 /* We already found the first value of "c", above. */
2788 while (1)
2790 char closeparen;
2791 int count;
2793 switch (c)
2795 case '\0':
2796 case ' ':
2797 case '\t':
2798 case '=':
2799 goto done_word;
2801 case ':':
2802 #ifdef HAVE_DOS_PATHS
2803 /* A word CAN include a colon in its drive spec. The drive
2804 spec is allowed either at the beginning of a word, or as part
2805 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2806 if (!(p - beg >= 2
2807 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2808 && (p - beg == 2 || p[-3] == '(')))
2809 #endif
2810 goto done_word;
2812 case '$':
2813 c = *(p++);
2814 if (c == '$')
2815 break;
2817 /* This is a variable reference, so note that it's expandable.
2818 Then read it to the matching close paren. */
2819 wtype = w_variable;
2821 if (c == '(')
2822 closeparen = ')';
2823 else if (c == '{')
2824 closeparen = '}';
2825 else
2826 /* This is a single-letter variable reference. */
2827 break;
2829 for (count=0; *p != '\0'; ++p)
2831 if (*p == c)
2832 ++count;
2833 else if (*p == closeparen && --count < 0)
2835 ++p;
2836 break;
2839 break;
2841 case '?':
2842 case '+':
2843 if (*p == '=')
2844 goto done_word;
2845 break;
2847 case '\\':
2848 switch (*p)
2850 case ':':
2851 case ';':
2852 case '=':
2853 case '\\':
2854 ++p;
2855 break;
2857 break;
2859 default:
2860 if (delim && strchr (delim, c))
2861 goto done_word;
2862 break;
2865 c = *(p++);
2867 done_word:
2868 --p;
2870 done:
2871 if (startp)
2872 *startp = beg;
2873 if (length)
2874 *length = p - beg;
2875 return wtype;
2878 /* Construct the list of include directories
2879 from the arguments and the default list. */
2881 void
2882 construct_include_path (const char **arg_dirs)
2884 #ifdef VAXC /* just don't ask ... */
2885 stat_t stbuf;
2886 #else
2887 struct stat stbuf;
2888 #endif
2889 const char **dirs;
2890 const char **cpp;
2891 unsigned int idx;
2893 /* Compute the number of pointers we need in the table. */
2894 idx = sizeof (default_include_directories) / sizeof (const char *);
2895 if (arg_dirs)
2896 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2897 ++idx;
2899 #ifdef __MSDOS__
2900 /* Add one for $DJDIR. */
2901 ++idx;
2902 #endif
2904 dirs = xmalloc (idx * sizeof (const char *));
2906 idx = 0;
2907 max_incl_len = 0;
2909 /* First consider any dirs specified with -I switches.
2910 Ignore any that don't exist. Remember the maximum string length. */
2912 if (arg_dirs)
2913 while (*arg_dirs != 0)
2915 const char *dir = *(arg_dirs++);
2916 char *expanded = 0;
2917 int e;
2919 if (dir[0] == '~')
2921 expanded = tilde_expand (dir);
2922 if (expanded != 0)
2923 dir = expanded;
2926 EINTRLOOP (e, stat (dir, &stbuf));
2927 if (e == 0 && S_ISDIR (stbuf.st_mode))
2929 unsigned int len = strlen (dir);
2930 /* If dir name is written with trailing slashes, discard them. */
2931 while (len > 1 && dir[len - 1] == '/')
2932 --len;
2933 if (len > max_incl_len)
2934 max_incl_len = len;
2935 dirs[idx++] = strcache_add_len (dir, len);
2938 if (expanded)
2939 free (expanded);
2942 /* Now add the standard default dirs at the end. */
2944 #ifdef __MSDOS__
2946 /* The environment variable $DJDIR holds the root of the DJGPP directory
2947 tree; add ${DJDIR}/include. */
2948 struct variable *djdir = lookup_variable ("DJDIR", 5);
2950 if (djdir)
2952 unsigned int len = strlen (djdir->value) + 8;
2953 char *defdir = alloca (len + 1);
2955 strcat (strcpy (defdir, djdir->value), "/include");
2956 dirs[idx++] = strcache_add (defdir);
2958 if (len > max_incl_len)
2959 max_incl_len = len;
2962 #endif
2964 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2966 int e;
2968 EINTRLOOP (e, stat (*cpp, &stbuf));
2969 if (e == 0 && S_ISDIR (stbuf.st_mode))
2971 unsigned int len = strlen (*cpp);
2972 /* If dir name is written with trailing slashes, discard them. */
2973 while (len > 1 && (*cpp)[len - 1] == '/')
2974 --len;
2975 if (len > max_incl_len)
2976 max_incl_len = len;
2977 dirs[idx++] = strcache_add_len (*cpp, len);
2981 dirs[idx] = 0;
2983 /* Now add each dir to the .INCLUDE_DIRS variable. */
2985 for (cpp = dirs; *cpp != 0; ++cpp)
2986 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2987 o_default, f_append, 0);
2989 include_directories = dirs;
2992 /* Expand ~ or ~USER at the beginning of NAME.
2993 Return a newly malloc'd string or 0. */
2995 char *
2996 tilde_expand (const char *name)
2998 #ifndef VMS
2999 if (name[1] == '/' || name[1] == '\0')
3001 extern char *getenv ();
3002 char *home_dir;
3003 int is_variable;
3006 /* Turn off --warn-undefined-variables while we expand HOME. */
3007 int save = warn_undefined_variables_flag;
3008 warn_undefined_variables_flag = 0;
3010 home_dir = allocated_variable_expand ("$(HOME)");
3012 warn_undefined_variables_flag = save;
3015 is_variable = home_dir[0] != '\0';
3016 if (!is_variable)
3018 free (home_dir);
3019 home_dir = getenv ("HOME");
3021 # if !defined(_AMIGA) && !defined(WINDOWS32)
3022 if (home_dir == 0 || home_dir[0] == '\0')
3024 extern char *getlogin ();
3025 char *logname = getlogin ();
3026 home_dir = 0;
3027 if (logname != 0)
3029 struct passwd *p = getpwnam (logname);
3030 if (p != 0)
3031 home_dir = p->pw_dir;
3034 # endif /* !AMIGA && !WINDOWS32 */
3035 if (home_dir != 0)
3037 char *new = xstrdup (concat (home_dir, "", name + 1));
3038 if (is_variable)
3039 free (home_dir);
3040 return new;
3043 # if !defined(_AMIGA) && !defined(WINDOWS32)
3044 else
3046 struct passwd *pwent;
3047 char *userend = strchr (name + 1, '/');
3048 if (userend != 0)
3049 *userend = '\0';
3050 pwent = getpwnam (name + 1);
3051 if (pwent != 0)
3053 if (userend == 0)
3054 return xstrdup (pwent->pw_dir);
3055 else
3056 return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
3058 else if (userend != 0)
3059 *userend = '/';
3061 # endif /* !AMIGA && !WINDOWS32 */
3062 #endif /* !VMS */
3063 return 0;
3066 /* Given a chain of struct nameseq's describing a sequence of filenames,
3067 in reverse of the intended order, return a new chain describing the
3068 result of globbing the filenames. The new chain is in forward order.
3069 The links of the old chain are freed or used in the new chain.
3070 Likewise for the names in the old chain.
3072 SIZE is how big to construct chain elements.
3073 This is useful if we want them actually to be other structures
3074 that have room for additional info.
3076 If EXISTS_ONLY is true only return existing files. */
3078 struct nameseq *
3079 multi_glob (struct nameseq *chain, unsigned int size, int exists_only)
3081 void dir_setup_glob (glob_t *);
3082 struct nameseq *new = 0;
3083 struct nameseq *old;
3084 struct nameseq *nexto;
3085 glob_t gl;
3087 dir_setup_glob (&gl);
3089 for (old = chain; old != 0; old = nexto)
3091 int r;
3092 const char **nlist = 0;
3093 int i = 0;
3094 const char *gname;
3095 #ifndef NO_ARCHIVES
3096 char *arname = 0;
3097 char *memname = 0;
3098 #endif
3099 nexto = old->next;
3100 gname = old->name;
3102 if (gname[0] == '~')
3104 char *newname = tilde_expand (old->name);
3105 if (newname != 0)
3106 gname = newname;
3109 #ifndef NO_ARCHIVES
3110 if (ar_name (gname))
3112 /* OLD->name is an archive member reference. Replace it with the
3113 archive file name, and save the member name in MEMNAME. We will
3114 glob on the archive name and then reattach MEMNAME later. */
3115 ar_parse_name (gname, &arname, &memname);
3116 gname = arname;
3118 #endif /* !NO_ARCHIVES */
3120 r = glob (gname, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl);
3121 switch (r)
3123 case GLOB_NOSPACE:
3124 fatal (NILF, _("virtual memory exhausted"));
3126 case 0:
3127 /* Success. */
3128 i = gl.gl_pathc;
3129 nlist = (const char **)gl.gl_pathv;
3130 break;
3132 case GLOB_NOMATCH:
3133 if (exists_only)
3135 i = 0;
3136 break;
3138 /* FALLTHROUGH */
3140 default:
3141 /* By default keep this name. */
3142 i = 1;
3143 nlist = &gname;
3144 break;
3147 /* For each matched element, add it to the list. */
3148 while (i-- > 0)
3149 #ifndef NO_ARCHIVES
3150 if (memname != 0)
3152 /* Try to glob on MEMNAME within the archive. */
3153 struct nameseq *found
3154 = ar_glob (nlist[i], memname, size);
3155 if (! found)
3157 /* No matches. Use MEMNAME as-is. */
3158 unsigned int alen = strlen (nlist[i]);
3159 unsigned int mlen = strlen (memname);
3160 char *name;
3161 struct nameseq *elt = xmalloc (size);
3162 memset (elt, '\0', size);
3164 name = alloca (alen + 1 + mlen + 2);
3165 memcpy (name, nlist[i], alen);
3166 name[alen] = '(';
3167 memcpy (name+alen+1, memname, mlen);
3168 name[alen + 1 + mlen] = ')';
3169 name[alen + 1 + mlen + 1] = '\0';
3170 elt->name = strcache_add (name);
3171 elt->next = new;
3172 new = elt;
3174 else
3176 /* Find the end of the FOUND chain. */
3177 struct nameseq *f = found;
3178 while (f->next != 0)
3179 f = f->next;
3181 /* Attach the chain being built to the end of the FOUND
3182 chain, and make FOUND the new NEW chain. */
3183 f->next = new;
3184 new = found;
3187 else
3188 #endif /* !NO_ARCHIVES */
3190 struct nameseq *elt = xmalloc (size);
3191 memset (elt, '\0', size);
3192 elt->name = strcache_add (nlist[i]);
3193 elt->next = new;
3194 new = elt;
3197 if (r == 0)
3198 globfree (&gl);
3199 free (old);
3200 #ifndef NO_ARCHIVES
3201 if (arname)
3202 free (arname);
3203 #endif
3206 return new;