- Add xcalloc() and call it
[make.git] / read.c
blobbb85d4eb3e888cd6df44759c842e28796163d6eb
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 (3, include_directories[i],
367 "/", filename);
368 ebuf.fp = fopen (included, "r");
369 if (ebuf.fp)
371 filename = strcache_add (included);
372 break;
377 /* Add FILENAME to the chain of read makefiles. */
378 deps = alloc_dep ();
379 deps->next = read_makefiles;
380 read_makefiles = deps;
381 deps->file = lookup_file (filename);
382 if (deps->file == 0)
383 deps->file = enter_file (filename);
384 filename = deps->file->name;
385 deps->changed = flags;
386 if (flags & RM_DONTCARE)
387 deps->file->dontcare = 1;
389 if (expanded)
390 free (expanded);
392 /* If the makefile can't be found at all, give up entirely. */
394 if (ebuf.fp == 0)
396 /* If we did some searching, errno has the error from the last
397 attempt, rather from FILENAME itself. Restore it in case the
398 caller wants to use it in a message. */
399 errno = makefile_errno;
400 return 0;
403 /* Set close-on-exec to avoid leaking the makefile to children, such as
404 $(shell ...). */
405 #ifdef HAVE_FILENO
406 CLOSE_ON_EXEC (fileno (ebuf.fp));
407 #endif
409 /* Add this makefile to the list. */
410 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
411 f_append, 0);
413 /* Evaluate the makefile */
415 ebuf.size = 200;
416 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
418 curfile = reading_file;
419 reading_file = &ebuf.floc;
421 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
423 reading_file = curfile;
425 fclose (ebuf.fp);
427 free (ebuf.bufstart);
428 alloca (0);
429 return r;
433 eval_buffer (char *buffer)
435 struct ebuffer ebuf;
436 struct conditionals *saved;
437 struct conditionals new;
438 const struct floc *curfile;
439 int r;
441 /* Evaluate the buffer */
443 ebuf.size = strlen (buffer);
444 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
445 ebuf.fp = NULL;
447 if (reading_file)
448 ebuf.floc = *reading_file;
449 else
450 ebuf.floc.filenm = NULL;
452 curfile = reading_file;
453 reading_file = &ebuf.floc;
455 saved = install_conditionals (&new);
457 r = eval (&ebuf, 1);
459 restore_conditionals (saved);
461 reading_file = curfile;
463 alloca (0);
464 return r;
467 /* Check LINE to see if it's a variable assignment.
469 It might use one of the modifiers "export", "override", "private", or it
470 might be one of the conditional tokens like "ifdef", "include", etc.
472 If it's not a variable assignment, VMOD.V_ASSIGN is 0. Returns LINE.
474 Returns a pointer to the first non-modifier character, and sets VMOD
475 based on the modifiers found if any, plus V_ASSIGN is 1.
477 static char *
478 parse_var_assignment (const char *line, struct vmodifiers *vmod)
480 const char *p;
481 memset (vmod, '\0', sizeof (*vmod));
483 /* Find the start of the next token. If there isn't one we're done. */
484 line = next_token (line);
485 if (*line == '\0')
486 return (char *)line;
488 p = line;
489 while (1)
491 int wlen;
492 const char *p2;
493 enum variable_flavor flavor;
495 p2 = parse_variable_definition (p, &flavor);
497 /* If this is a variable assignment, we're done. */
498 if (p2)
499 break;
501 /* It's not a variable; see if it's a modifier. */
502 p2 = end_of_token (p);
503 wlen = p2 - p;
505 if (word1eq ("export"))
506 vmod->export_v = 1;
507 else if (word1eq ("override"))
508 vmod->override_v = 1;
509 else if (word1eq ("private"))
510 vmod->private_v = 1;
511 else if (word1eq ("define"))
513 /* We can't have modifiers after 'define' */
514 vmod->define_v = 1;
515 p = next_token (p2);
516 break;
518 else
519 /* Not a variable or modifier: this is not a variable assignment. */
520 return (char *)line;
522 /* It was a modifier. Try the next word. */
523 p = next_token (p2);
524 if (*p == '\0')
525 return (char *)line;
528 /* Found a variable assignment. */
529 vmod->assign_v = 1;
530 return (char *)p;
535 /* Read file FILENAME as a makefile and add its contents to the data base.
537 SET_DEFAULT is true if we are allowed to set the default goal. */
540 static int
541 eval (struct ebuffer *ebuf, int set_default)
543 char *collapsed = 0;
544 unsigned int collapsed_length = 0;
545 unsigned int commands_len = 200;
546 char *commands;
547 unsigned int commands_idx = 0;
548 unsigned int cmds_started, tgts_started;
549 int ignoring = 0, in_ignored_define = 0;
550 int no_targets = 0; /* Set when reading a rule without targets. */
551 struct nameseq *filenames = 0;
552 struct dep *deps = 0;
553 long nlines = 0;
554 int two_colon = 0;
555 const char *pattern = 0;
556 const char *pattern_percent;
557 struct floc *fstart;
558 struct floc fi;
560 #define record_waiting_files() \
561 do \
563 if (filenames != 0) \
565 fi.lineno = tgts_started; \
566 record_files (filenames, pattern, pattern_percent, deps, \
567 cmds_started, commands, commands_idx, two_colon, \
568 &fi); \
570 filenames = 0; \
571 commands_idx = 0; \
572 no_targets = 0; \
573 pattern = 0; \
574 } while (0)
576 pattern_percent = 0;
577 cmds_started = tgts_started = 1;
579 fstart = &ebuf->floc;
580 fi.filenm = ebuf->floc.filenm;
582 /* Loop over lines in the file.
583 The strategy is to accumulate target names in FILENAMES, dependencies
584 in DEPS and commands in COMMANDS. These are used to define a rule
585 when the start of the next rule (or eof) is encountered.
587 When you see a "continue" in the loop below, that means we are moving on
588 to the next line _without_ ending any rule that we happen to be working
589 with at the moment. If you see a "goto rule_complete", then the
590 statement we just parsed also finishes the previous rule. */
592 commands = xmalloc (200);
594 while (1)
596 unsigned int linelen;
597 char *line;
598 unsigned int wlen;
599 char *p;
600 char *p2;
601 struct vmodifiers vmod;
603 /* At the top of this loop, we are starting a brand new line. */
604 /* Grab the next line to be evaluated */
605 ebuf->floc.lineno += nlines;
606 nlines = readline (ebuf);
608 /* If there is nothing left to eval, we're done. */
609 if (nlines < 0)
610 break;
612 /* If this line is empty, skip it. */
613 line = ebuf->buffer;
614 if (line[0] == '\0')
615 continue;
617 linelen = strlen (line);
619 /* Check for a shell command line first.
620 If it is not one, we can stop treating tab specially. */
621 if (line[0] == cmd_prefix)
623 if (no_targets)
624 /* Ignore the commands in a rule with no targets. */
625 continue;
627 /* If there is no preceding rule line, don't treat this line
628 as a command, even though it begins with a recipe prefix.
629 SunOS 4 make appears to behave this way. */
631 if (filenames != 0)
633 if (ignoring)
634 /* Yep, this is a shell command, and we don't care. */
635 continue;
637 /* Append this command line to the line being accumulated.
638 Strip command prefix chars that appear after newlines. */
639 if (commands_idx == 0)
640 cmds_started = ebuf->floc.lineno;
642 if (linelen + commands_idx > commands_len)
644 commands_len = (linelen + commands_idx) * 2;
645 commands = xrealloc (commands, commands_len);
647 p = &commands[commands_idx];
648 p2 = line + 1;
649 while (--linelen)
651 ++commands_idx;
652 *(p++) = *p2;
653 if (p2[0] == '\n' && p2[1] == cmd_prefix)
655 ++p2;
656 --linelen;
658 ++p2;
660 *p = '\n';
661 ++commands_idx;
663 continue;
667 /* This line is not a shell command line. Don't worry about whitespace.
668 Get more space if we need it; we don't need to preserve the current
669 contents of the buffer. */
671 if (collapsed_length < linelen+1)
673 collapsed_length = linelen+1;
674 if (collapsed)
675 free (collapsed);
676 /* Don't need xrealloc: we don't need to preserve the content. */
677 collapsed = xmalloc (collapsed_length);
679 strcpy (collapsed, line);
680 /* Collapse continuation lines. */
681 collapse_continuations (collapsed);
682 remove_comments (collapsed);
684 /* Get rid if starting space (including formfeed, vtab, etc.) */
685 p = collapsed;
686 while (isspace ((unsigned char)*p))
687 ++p;
689 /* See if this is a variable assignment. We need to do this early, to
690 allow variables with names like 'ifdef', 'export', 'private', etc. */
691 p = parse_var_assignment(p, &vmod);
692 if (vmod.assign_v)
694 struct variable *v;
695 enum variable_origin origin = vmod.override_v ? o_override : o_file;
697 /* If we're ignoring then we're done now. */
698 if (ignoring)
700 if (vmod.define_v)
701 in_ignored_define = 1;
702 continue;
705 if (vmod.define_v)
706 v = do_define (p, origin, ebuf);
707 else
708 v = try_variable_definition (fstart, p, origin, 0);
710 assert (v != NULL);
712 if (vmod.export_v)
713 v->export = v_export;
714 if (vmod.private_v)
715 v->private_var = 1;
717 /* This line has been dealt with. */
718 goto rule_complete;
721 /* If this line is completely empty, ignore it. */
722 if (*p == '\0')
723 continue;
725 p2 = end_of_token (p);
726 wlen = p2 - p;
727 p2 = next_token (p2);
729 /* If we're in an ignored define, skip this line (but maybe get out). */
730 if (in_ignored_define)
732 /* See if this is an endef line (plus optional comment). */
733 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
734 in_ignored_define = 0;
736 continue;
739 /* Check for conditional state changes. */
741 int i = conditional_line (p, wlen, fstart);
742 if (i != -2)
744 if (i == -1)
745 fatal (fstart, _("invalid syntax in conditional"));
747 ignoring = i;
748 continue;
752 /* Nothing to see here... move along. */
753 if (ignoring)
754 continue;
756 /* Manage the "export" keyword used outside of variable assignment
757 as well as "unexport". */
758 if (word1eq ("export") || word1eq ("unexport"))
760 int exporting = *p == 'u' ? 0 : 1;
762 /* (un)export by itself causes everything to be (un)exported. */
763 if (*p2 == '\0')
764 export_all_variables = exporting;
765 else
767 unsigned int l;
768 const char *cp;
769 char *ap;
771 /* Expand the line so we can use indirect and constructed
772 variable names in an (un)export command. */
773 cp = ap = allocated_variable_expand (p2);
775 for (p = find_next_token (&cp, &l); p != 0;
776 p = find_next_token (&cp, &l))
778 struct variable *v = lookup_variable (p, l);
779 if (v == 0)
780 v = define_variable_loc (p, l, "", o_file, 0, fstart);
781 v->export = exporting ? v_export : v_noexport;
784 free (ap);
786 goto rule_complete;
789 /* Handle the special syntax for vpath. */
790 if (word1eq ("vpath"))
792 const char *cp;
793 char *vpat;
794 unsigned int l;
795 cp = variable_expand (p2);
796 p = find_next_token (&cp, &l);
797 if (p != 0)
799 vpat = xstrndup (p, l);
800 p = find_next_token (&cp, &l);
801 /* No searchpath means remove all previous
802 selective VPATH's with the same pattern. */
804 else
805 /* No pattern means remove all previous selective VPATH's. */
806 vpat = 0;
807 construct_vpath_list (vpat, p);
808 if (vpat != 0)
809 free (vpat);
811 goto rule_complete;
814 /* Handle include and variants. */
815 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
817 /* We have found an `include' line specifying a nested
818 makefile to be read at this point. */
819 struct conditionals *save;
820 struct conditionals new_conditionals;
821 struct nameseq *files;
822 /* "-include" (vs "include") says no error if the file does not
823 exist. "sinclude" is an alias for this from SGI. */
824 int noerror = (p[0] != 'i');
826 p = allocated_variable_expand (p2);
828 /* If no filenames, it's a no-op. */
829 if (*p == '\0')
831 free (p);
832 continue;
835 /* Parse the list of file names. */
836 p2 = p;
837 files = parse_file_seq (&p2, sizeof (struct nameseq), '\0',
838 NULL, 0);
839 free (p);
841 /* Save the state of conditionals and start
842 the included makefile with a clean slate. */
843 save = install_conditionals (&new_conditionals);
845 /* Record the rules that are waiting so they will determine
846 the default goal before those in the included makefile. */
847 record_waiting_files ();
849 /* Read each included makefile. */
850 while (files != 0)
852 struct nameseq *next = files->next;
853 const char *name = files->name;
854 int r;
856 free (files);
857 files = next;
859 r = eval_makefile (name,
860 (RM_INCLUDED | RM_NO_TILDE
861 | (noerror ? RM_DONTCARE : 0)
862 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
863 if (!r && !noerror)
864 error (fstart, "%s: %s", name, strerror (errno));
867 /* Restore conditional state. */
868 restore_conditionals (save);
870 goto rule_complete;
873 /* This line starts with a tab but was not caught above because there
874 was no preceding target, and the line might have been usable as a
875 variable definition. But now we know it is definitely lossage. */
876 if (line[0] == cmd_prefix)
877 fatal(fstart, _("recipe commences before first target"));
879 /* This line describes some target files. This is complicated by
880 the existence of target-specific variables, because we can't
881 expand the entire line until we know if we have one or not. So
882 we expand the line word by word until we find the first `:',
883 then check to see if it's a target-specific variable.
885 In this algorithm, `lb_next' will point to the beginning of the
886 unexpanded parts of the input buffer, while `p2' points to the
887 parts of the expanded buffer we haven't searched yet. */
890 enum make_word_type wtype;
891 char *cmdleft, *semip, *lb_next;
892 unsigned int plen = 0;
893 char *colonp;
894 const char *end, *beg; /* Helpers for whitespace stripping. */
896 /* Record the previous rule. */
898 record_waiting_files ();
899 tgts_started = fstart->lineno;
901 /* Search the line for an unquoted ; that is not after an
902 unquoted #. */
903 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
904 if (cmdleft != 0 && *cmdleft == '#')
906 /* We found a comment before a semicolon. */
907 *cmdleft = '\0';
908 cmdleft = 0;
910 else if (cmdleft != 0)
911 /* Found one. Cut the line short there before expanding it. */
912 *(cmdleft++) = '\0';
913 semip = cmdleft;
915 collapse_continuations (line);
917 /* We can't expand the entire line, since if it's a per-target
918 variable we don't want to expand it. So, walk from the
919 beginning, expanding as we go, and looking for "interesting"
920 chars. The first word is always expandable. */
921 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
922 switch (wtype)
924 case w_eol:
925 if (cmdleft != 0)
926 fatal(fstart, _("missing rule before recipe"));
927 /* This line contained something but turned out to be nothing
928 but whitespace (a comment?). */
929 continue;
931 case w_colon:
932 case w_dcolon:
933 /* We accept and ignore rules without targets for
934 compatibility with SunOS 4 make. */
935 no_targets = 1;
936 continue;
938 default:
939 break;
942 p2 = variable_expand_string(NULL, lb_next, wlen);
944 while (1)
946 lb_next += wlen;
947 if (cmdleft == 0)
949 /* Look for a semicolon in the expanded line. */
950 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
952 if (cmdleft != 0)
954 unsigned long p2_off = p2 - variable_buffer;
955 unsigned long cmd_off = cmdleft - variable_buffer;
956 char *pend = p2 + strlen(p2);
958 /* Append any remnants of lb, then cut the line short
959 at the semicolon. */
960 *cmdleft = '\0';
962 /* One school of thought says that you shouldn't expand
963 here, but merely copy, since now you're beyond a ";"
964 and into a command script. However, the old parser
965 expanded the whole line, so we continue that for
966 backwards-compatiblity. Also, it wouldn't be
967 entirely consistent, since we do an unconditional
968 expand below once we know we don't have a
969 target-specific variable. */
970 (void)variable_expand_string(pend, lb_next, (long)-1);
971 lb_next += strlen(lb_next);
972 p2 = variable_buffer + p2_off;
973 cmdleft = variable_buffer + cmd_off + 1;
977 colonp = find_char_unquote(p2, ':', 0, 0, 0);
978 #ifdef HAVE_DOS_PATHS
979 /* The drive spec brain-damage strikes again... */
980 /* Note that the only separators of targets in this context
981 are whitespace and a left paren. If others are possible,
982 they should be added to the string in the call to index. */
983 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
984 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
985 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
986 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
987 #endif
988 if (colonp != 0)
989 break;
991 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
992 if (wtype == w_eol)
993 break;
995 p2 += strlen(p2);
996 *(p2++) = ' ';
997 p2 = variable_expand_string(p2, lb_next, wlen);
998 /* We don't need to worry about cmdleft here, because if it was
999 found in the variable_buffer the entire buffer has already
1000 been expanded... we'll never get here. */
1003 p2 = next_token (variable_buffer);
1005 /* If the word we're looking at is EOL, see if there's _anything_
1006 on the line. If not, a variable expanded to nothing, so ignore
1007 it. If so, we can't parse this line so punt. */
1008 if (wtype == w_eol)
1010 if (*p2 != '\0')
1011 /* There's no need to be ivory-tower about this: check for
1012 one of the most common bugs found in makefiles... */
1013 fatal (fstart, _("missing separator%s"),
1014 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1015 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1016 continue;
1019 /* Make the colon the end-of-string so we know where to stop
1020 looking for targets. */
1021 *colonp = '\0';
1022 filenames = parse_file_seq (&p2, sizeof (struct nameseq), '\0',
1023 NULL, 0);
1024 *p2 = ':';
1026 if (!filenames)
1028 /* We accept and ignore rules without targets for
1029 compatibility with SunOS 4 make. */
1030 no_targets = 1;
1031 continue;
1033 /* This should never be possible; we handled it above. */
1034 assert (*p2 != '\0');
1035 ++p2;
1037 /* Is this a one-colon or two-colon entry? */
1038 two_colon = *p2 == ':';
1039 if (two_colon)
1040 p2++;
1042 /* Test to see if it's a target-specific variable. Copy the rest
1043 of the buffer over, possibly temporarily (we'll expand it later
1044 if it's not a target-specific variable). PLEN saves the length
1045 of the unparsed section of p2, for later. */
1046 if (*lb_next != '\0')
1048 unsigned int l = p2 - variable_buffer;
1049 plen = strlen (p2);
1050 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1051 p2 = variable_buffer + l;
1054 p2 = parse_var_assignment (p2, &vmod);
1055 if (vmod.assign_v)
1057 /* If there was a semicolon found, add it back, plus anything
1058 after it. */
1059 if (semip)
1061 unsigned int l = p - variable_buffer;
1062 *(--semip) = ';';
1063 collapse_continuations (semip);
1064 variable_buffer_output (p2 + strlen (p2),
1065 semip, strlen (semip)+1);
1066 p = variable_buffer + l;
1068 record_target_var (filenames, p2,
1069 vmod.override_v ? o_override : o_file,
1070 &vmod, fstart);
1071 filenames = 0;
1072 continue;
1075 /* This is a normal target, _not_ a target-specific variable.
1076 Unquote any = in the dependency list. */
1077 find_char_unquote (lb_next, '=', 0, 0, 0);
1079 /* We have some targets, so don't ignore the following commands. */
1080 no_targets = 0;
1082 /* Expand the dependencies, etc. */
1083 if (*lb_next != '\0')
1085 unsigned int l = p2 - variable_buffer;
1086 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1087 p2 = variable_buffer + l;
1089 /* Look for a semicolon in the expanded line. */
1090 if (cmdleft == 0)
1092 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1093 if (cmdleft != 0)
1094 *(cmdleft++) = '\0';
1098 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1099 p = strchr (p2, ':');
1100 while (p != 0 && p[-1] == '\\')
1102 register char *q = &p[-1];
1103 register int backslash = 0;
1104 while (*q-- == '\\')
1105 backslash = !backslash;
1106 if (backslash)
1107 p = strchr (p + 1, ':');
1108 else
1109 break;
1111 #ifdef _AMIGA
1112 /* Here, the situation is quite complicated. Let's have a look
1113 at a couple of targets:
1115 install: dev:make
1117 dev:make: make
1119 dev:make:: xyz
1121 The rule is that it's only a target, if there are TWO :'s
1122 OR a space around the :.
1124 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1125 || isspace ((unsigned char)p[-1])))
1126 p = 0;
1127 #endif
1128 #ifdef HAVE_DOS_PATHS
1130 int check_again;
1131 do {
1132 check_again = 0;
1133 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1134 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1135 isalpha ((unsigned char)p[-1]) &&
1136 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1137 p = strchr (p + 1, ':');
1138 check_again = 1;
1140 } while (check_again);
1142 #endif
1143 if (p != 0)
1145 struct nameseq *target;
1146 target = parse_file_seq (&p2, sizeof (struct nameseq), ':',
1147 NULL, PARSEFS_NOGLOB|PARSEFS_NOCACHE);
1148 ++p2;
1149 if (target == 0)
1150 fatal (fstart, _("missing target pattern"));
1151 else if (target->next != 0)
1152 fatal (fstart, _("multiple target patterns"));
1153 pattern_percent = find_percent_cached (&target->name);
1154 pattern = target->name;
1155 if (pattern_percent == 0)
1156 fatal (fstart, _("target pattern contains no `%%'"));
1157 free (target);
1159 else
1160 pattern = 0;
1162 /* Strip leading and trailing whitespaces. */
1163 beg = p2;
1164 end = beg + strlen (beg) - 1;
1165 strip_whitespace (&beg, &end);
1167 if (beg <= end && *beg != '\0')
1169 /* Put all the prerequisites here; they'll be parsed later. */
1170 deps = alloc_dep ();
1171 deps->name = strcache_add_len (beg, end - beg + 1);
1173 else
1174 deps = 0;
1176 commands_idx = 0;
1177 if (cmdleft != 0)
1179 /* Semicolon means rest of line is a command. */
1180 unsigned int l = strlen (cmdleft);
1182 cmds_started = fstart->lineno;
1184 /* Add this command line to the buffer. */
1185 if (l + 2 > commands_len)
1187 commands_len = (l + 2) * 2;
1188 commands = xrealloc (commands, commands_len);
1190 memcpy (commands, cmdleft, l);
1191 commands_idx += l;
1192 commands[commands_idx++] = '\n';
1195 /* Determine if this target should be made default. We used to do
1196 this in record_files() but because of the delayed target recording
1197 and because preprocessor directives are legal in target's commands
1198 it is too late. Consider this fragment for example:
1200 foo:
1202 ifeq ($(.DEFAULT_GOAL),foo)
1204 endif
1206 Because the target is not recorded until after ifeq directive is
1207 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1208 would expect. Because of this we have to move the logic here. */
1210 if (set_default && default_goal_var->value[0] == '\0')
1212 const char *name;
1213 struct dep *d;
1214 struct nameseq *t = filenames;
1216 for (; t != 0; t = t->next)
1218 int reject = 0;
1219 name = t->name;
1221 /* We have nothing to do if this is an implicit rule. */
1222 if (strchr (name, '%') != 0)
1223 break;
1225 /* See if this target's name does not start with a `.',
1226 unless it contains a slash. */
1227 if (*name == '.' && strchr (name, '/') == 0
1228 #ifdef HAVE_DOS_PATHS
1229 && strchr (name, '\\') == 0
1230 #endif
1232 continue;
1235 /* If this file is a suffix, don't let it be
1236 the default goal file. */
1237 for (d = suffix_file->deps; d != 0; d = d->next)
1239 register struct dep *d2;
1240 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1242 reject = 1;
1243 break;
1245 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1247 unsigned int l = strlen (dep_name (d2));
1248 if (!strneq (name, dep_name (d2), l))
1249 continue;
1250 if (streq (name + l, dep_name (d)))
1252 reject = 1;
1253 break;
1257 if (reject)
1258 break;
1261 if (!reject)
1263 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1264 o_file, 0, NILF);
1265 break;
1270 continue;
1273 /* We get here except in the case that we just read a rule line.
1274 Record now the last rule we read, so following spurious
1275 commands are properly diagnosed. */
1276 rule_complete:
1277 record_waiting_files ();
1280 #undef word1eq
1282 if (conditionals->if_cmds)
1283 fatal (fstart, _("missing `endif'"));
1285 /* At eof, record the last rule. */
1286 record_waiting_files ();
1288 if (collapsed)
1289 free (collapsed);
1290 free (commands);
1292 return 1;
1296 /* Remove comments from LINE.
1297 This is done by copying the text at LINE onto itself. */
1299 static void
1300 remove_comments (char *line)
1302 char *comment;
1304 comment = find_char_unquote (line, '#', 0, 0, 0);
1306 if (comment != 0)
1307 /* Cut off the line at the #. */
1308 *comment = '\0';
1311 /* Execute a `define' directive.
1312 The first line has already been read, and NAME is the name of
1313 the variable to be defined. The following lines remain to be read. */
1315 static struct variable *
1316 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1318 struct variable *v;
1319 enum variable_flavor flavor;
1320 struct floc defstart;
1321 int nlevels = 1;
1322 unsigned int length = 100;
1323 char *definition = xmalloc (length);
1324 unsigned int idx = 0;
1325 char *p, *var;
1327 defstart = ebuf->floc;
1329 p = parse_variable_definition (name, &flavor);
1330 if (p == NULL)
1331 /* No assignment token, so assume recursive. */
1332 flavor = f_recursive;
1333 else
1335 if (*(next_token (p)) != '\0')
1336 error (&defstart, _("extraneous text after `define' directive"));
1338 /* Chop the string before the assignment token to get the name. */
1339 p[flavor == f_recursive ? -1 : -2] = '\0';
1342 /* Expand the variable name and find the beginning (NAME) and end. */
1343 var = allocated_variable_expand (name);
1344 name = next_token (var);
1345 if (*name == '\0')
1346 fatal (&defstart, _("empty variable name"));
1347 p = name + strlen (name) - 1;
1348 while (p > name && isblank ((unsigned char)*p))
1349 --p;
1350 p[1] = '\0';
1352 /* Now read the value of the variable. */
1353 while (1)
1355 unsigned int len;
1356 char *line;
1357 long nlines = readline (ebuf);
1359 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1360 if (nlines < 0)
1361 fatal (&defstart, _("missing `endef', unterminated `define'"));
1363 ebuf->floc.lineno += nlines;
1364 line = ebuf->buffer;
1366 collapse_continuations (line);
1368 /* If the line doesn't begin with a tab, test to see if it introduces
1369 another define, or ends one. Stop if we find an 'endef' */
1370 if (line[0] != cmd_prefix)
1372 p = next_token (line);
1373 len = strlen (p);
1375 /* If this is another 'define', increment the level count. */
1376 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1377 && strneq (p, "define", 6))
1378 ++nlevels;
1380 /* If this is an 'endef', decrement the count. If it's now 0,
1381 we've found the last one. */
1382 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1383 && strneq (p, "endef", 5))
1385 p += 5;
1386 remove_comments (p);
1387 if (*(next_token (p)) != '\0')
1388 error (&ebuf->floc,
1389 _("extraneous text after `endef' directive"));
1391 if (--nlevels == 0)
1392 break;
1396 /* Add this line to the variable definition. */
1397 len = strlen (line);
1398 if (idx + len + 1 > length)
1400 length = (idx + len) * 2;
1401 definition = xrealloc (definition, length + 1);
1404 memcpy (&definition[idx], line, len);
1405 idx += len;
1406 /* Separate lines with a newline. */
1407 definition[idx++] = '\n';
1410 /* We've got what we need; define the variable. */
1411 if (idx == 0)
1412 definition[0] = '\0';
1413 else
1414 definition[idx - 1] = '\0';
1416 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1417 free (definition);
1418 free (var);
1419 return (v);
1422 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1423 "ifneq", "else" and "endif".
1424 LINE is the input line, with the command as its first word.
1426 FILENAME and LINENO are the filename and line number in the
1427 current makefile. They are used for error messages.
1429 Value is -2 if the line is not a conditional at all,
1430 -1 if the line is an invalid conditional,
1431 0 if following text should be interpreted,
1432 1 if following text should be ignored. */
1434 static int
1435 conditional_line (char *line, int len, const struct floc *flocp)
1437 char *cmdname;
1438 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1439 unsigned int i;
1440 unsigned int o;
1442 /* Compare a word, both length and contents. */
1443 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1444 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1446 /* Make sure this line is a conditional. */
1447 chkword ("ifdef", c_ifdef)
1448 else chkword ("ifndef", c_ifndef)
1449 else chkword ("ifeq", c_ifeq)
1450 else chkword ("ifneq", c_ifneq)
1451 else chkword ("else", c_else)
1452 else chkword ("endif", c_endif)
1453 else
1454 return -2;
1456 /* Found one: skip past it and any whitespace after it. */
1457 line = next_token (line + len);
1459 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1461 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1462 if (cmdtype == c_endif)
1464 if (*line != '\0')
1465 EXTRANEOUS ();
1467 if (!conditionals->if_cmds)
1468 fatal (flocp, _("extraneous `%s'"), cmdname);
1470 --conditionals->if_cmds;
1472 goto DONE;
1475 /* An 'else' statement can either be simple, or it can have another
1476 conditional after it. */
1477 if (cmdtype == c_else)
1479 const char *p;
1481 if (!conditionals->if_cmds)
1482 fatal (flocp, _("extraneous `%s'"), cmdname);
1484 o = conditionals->if_cmds - 1;
1486 if (conditionals->seen_else[o])
1487 fatal (flocp, _("only one `else' per conditional"));
1489 /* Change the state of ignorance. */
1490 switch (conditionals->ignoring[o])
1492 case 0:
1493 /* We've just been interpreting. Never do it again. */
1494 conditionals->ignoring[o] = 2;
1495 break;
1496 case 1:
1497 /* We've never interpreted yet. Maybe this time! */
1498 conditionals->ignoring[o] = 0;
1499 break;
1502 /* It's a simple 'else'. */
1503 if (*line == '\0')
1505 conditionals->seen_else[o] = 1;
1506 goto DONE;
1509 /* The 'else' has extra text. That text must be another conditional
1510 and cannot be an 'else' or 'endif'. */
1512 /* Find the length of the next word. */
1513 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1515 len = p - line;
1517 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1518 if (word1eq("else") || word1eq("endif")
1519 || conditional_line (line, len, flocp) < 0)
1520 EXTRANEOUS ();
1521 else
1523 /* conditional_line() created a new level of conditional.
1524 Raise it back to this level. */
1525 if (conditionals->ignoring[o] < 2)
1526 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1527 --conditionals->if_cmds;
1530 goto DONE;
1533 if (conditionals->allocated == 0)
1535 conditionals->allocated = 5;
1536 conditionals->ignoring = xmalloc (conditionals->allocated);
1537 conditionals->seen_else = xmalloc (conditionals->allocated);
1540 o = conditionals->if_cmds++;
1541 if (conditionals->if_cmds > conditionals->allocated)
1543 conditionals->allocated += 5;
1544 conditionals->ignoring = xrealloc (conditionals->ignoring,
1545 conditionals->allocated);
1546 conditionals->seen_else = xrealloc (conditionals->seen_else,
1547 conditionals->allocated);
1550 /* Record that we have seen an `if...' but no `else' so far. */
1551 conditionals->seen_else[o] = 0;
1553 /* Search through the stack to see if we're already ignoring. */
1554 for (i = 0; i < o; ++i)
1555 if (conditionals->ignoring[i])
1557 /* We are already ignoring, so just push a level to match the next
1558 "else" or "endif", and keep ignoring. We don't want to expand
1559 variables in the condition. */
1560 conditionals->ignoring[o] = 1;
1561 return 1;
1564 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1566 char *var;
1567 struct variable *v;
1568 char *p;
1570 /* Expand the thing we're looking up, so we can use indirect and
1571 constructed variable names. */
1572 var = allocated_variable_expand (line);
1574 /* Make sure there's only one variable name to test. */
1575 p = end_of_token (var);
1576 i = p - var;
1577 p = next_token (p);
1578 if (*p != '\0')
1579 return -1;
1581 var[i] = '\0';
1582 v = lookup_variable (var, i);
1584 conditionals->ignoring[o] =
1585 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1587 free (var);
1589 else
1591 /* "ifeq" or "ifneq". */
1592 char *s1, *s2;
1593 unsigned int l;
1594 char termin = *line == '(' ? ',' : *line;
1596 if (termin != ',' && termin != '"' && termin != '\'')
1597 return -1;
1599 s1 = ++line;
1600 /* Find the end of the first string. */
1601 if (termin == ',')
1603 int count = 0;
1604 for (; *line != '\0'; ++line)
1605 if (*line == '(')
1606 ++count;
1607 else if (*line == ')')
1608 --count;
1609 else if (*line == ',' && count <= 0)
1610 break;
1612 else
1613 while (*line != '\0' && *line != termin)
1614 ++line;
1616 if (*line == '\0')
1617 return -1;
1619 if (termin == ',')
1621 /* Strip blanks after the first string. */
1622 char *p = line++;
1623 while (isblank ((unsigned char)p[-1]))
1624 --p;
1625 *p = '\0';
1627 else
1628 *line++ = '\0';
1630 s2 = variable_expand (s1);
1631 /* We must allocate a new copy of the expanded string because
1632 variable_expand re-uses the same buffer. */
1633 l = strlen (s2);
1634 s1 = alloca (l + 1);
1635 memcpy (s1, s2, l + 1);
1637 if (termin != ',')
1638 /* Find the start of the second string. */
1639 line = next_token (line);
1641 termin = termin == ',' ? ')' : *line;
1642 if (termin != ')' && termin != '"' && termin != '\'')
1643 return -1;
1645 /* Find the end of the second string. */
1646 if (termin == ')')
1648 int count = 0;
1649 s2 = next_token (line);
1650 for (line = s2; *line != '\0'; ++line)
1652 if (*line == '(')
1653 ++count;
1654 else if (*line == ')')
1656 if (count <= 0)
1657 break;
1658 else
1659 --count;
1663 else
1665 ++line;
1666 s2 = line;
1667 while (*line != '\0' && *line != termin)
1668 ++line;
1671 if (*line == '\0')
1672 return -1;
1674 *line = '\0';
1675 line = next_token (++line);
1676 if (*line != '\0')
1677 EXTRANEOUS ();
1679 s2 = variable_expand (s2);
1680 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1683 DONE:
1684 /* Search through the stack to see if we're ignoring. */
1685 for (i = 0; i < conditionals->if_cmds; ++i)
1686 if (conditionals->ignoring[i])
1687 return 1;
1688 return 0;
1691 /* Remove duplicate dependencies in CHAIN. */
1693 static unsigned long
1694 dep_hash_1 (const void *key)
1696 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1699 static unsigned long
1700 dep_hash_2 (const void *key)
1702 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1705 static int
1706 dep_hash_cmp (const void *x, const void *y)
1708 struct dep *dx = (struct dep *) x;
1709 struct dep *dy = (struct dep *) y;
1710 int cmp = strcmp (dep_name (dx), dep_name (dy));
1712 /* If the names are the same but ignore_mtimes are not equal, one of these
1713 is an order-only prerequisite and one isn't. That means that we should
1714 remove the one that isn't and keep the one that is. */
1716 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1717 dx->ignore_mtime = dy->ignore_mtime = 0;
1719 return cmp;
1723 void
1724 uniquize_deps (struct dep *chain)
1726 struct hash_table deps;
1727 register struct dep **depp;
1729 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1731 /* Make sure that no dependencies are repeated. This does not
1732 really matter for the purpose of updating targets, but it
1733 might make some names be listed twice for $^ and $?. */
1735 depp = &chain;
1736 while (*depp)
1738 struct dep *dep = *depp;
1739 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1740 if (HASH_VACANT (*dep_slot))
1742 hash_insert_at (&deps, dep, dep_slot);
1743 depp = &dep->next;
1745 else
1747 /* Don't bother freeing duplicates.
1748 It's dangerous and little benefit accrues. */
1749 *depp = dep->next;
1753 hash_free (&deps, 0);
1756 /* Record target-specific variable values for files FILENAMES.
1757 TWO_COLON is nonzero if a double colon was used.
1759 The links of FILENAMES are freed, and so are any names in it
1760 that are not incorporated into other data structures.
1762 If the target is a pattern, add the variable to the pattern-specific
1763 variable value list. */
1765 static void
1766 record_target_var (struct nameseq *filenames, char *defn,
1767 enum variable_origin origin, struct vmodifiers *vmod,
1768 const struct floc *flocp)
1770 struct nameseq *nextf;
1771 struct variable_set_list *global;
1773 global = current_variable_set_list;
1775 /* If the variable is an append version, store that but treat it as a
1776 normal recursive variable. */
1778 for (; filenames != 0; filenames = nextf)
1780 struct variable *v;
1781 const char *name = filenames->name;
1782 const char *fname;
1783 const char *percent;
1784 struct pattern_var *p;
1786 nextf = filenames->next;
1787 free (filenames);
1789 /* If it's a pattern target, then add it to the pattern-specific
1790 variable list. */
1791 percent = find_percent_cached (&name);
1792 if (percent)
1794 /* Get a reference for this pattern-specific variable struct. */
1795 p = create_pattern_var (name, percent);
1796 p->variable.fileinfo = *flocp;
1797 /* I don't think this can fail since we already determined it was a
1798 variable definition. */
1799 v = assign_variable_definition (&p->variable, defn);
1800 assert (v != 0);
1802 v->origin = origin;
1803 if (v->flavor == f_simple)
1804 v->value = allocated_variable_expand (v->value);
1805 else
1806 v->value = xstrdup (v->value);
1808 fname = p->target;
1810 else
1812 struct file *f;
1814 /* Get a file reference for this file, and initialize it.
1815 We don't want to just call enter_file() because that allocates a
1816 new entry if the file is a double-colon, which we don't want in
1817 this situation. */
1818 f = lookup_file (name);
1819 if (!f)
1820 f = enter_file (strcache_add (name));
1821 else if (f->double_colon)
1822 f = f->double_colon;
1824 initialize_file_variables (f, 1);
1825 fname = f->name;
1827 current_variable_set_list = f->variables;
1828 v = try_variable_definition (flocp, defn, origin, 1);
1829 if (!v)
1830 fatal (flocp, _("Malformed target-specific variable definition"));
1831 current_variable_set_list = global;
1834 /* Set up the variable to be *-specific. */
1835 v->per_target = 1;
1836 v->private_var = vmod->private_v;
1837 v->export = vmod->export_v ? v_export : v_default;
1839 /* If it's not an override, check to see if there was a command-line
1840 setting. If so, reset the value. */
1841 if (v->origin != o_override)
1843 struct variable *gv;
1844 int len = strlen(v->name);
1846 gv = lookup_variable (v->name, len);
1847 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1849 if (v->value != 0)
1850 free (v->value);
1851 v->value = xstrdup (gv->value);
1852 v->origin = gv->origin;
1853 v->recursive = gv->recursive;
1854 v->append = 0;
1860 /* Record a description line for files FILENAMES,
1861 with dependencies DEPS, commands to execute described
1862 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1863 TWO_COLON is nonzero if a double colon was used.
1864 If not nil, PATTERN is the `%' pattern to make this
1865 a static pattern rule, and PATTERN_PERCENT is a pointer
1866 to the `%' within it.
1868 The links of FILENAMES are freed, and so are any names in it
1869 that are not incorporated into other data structures. */
1871 static void
1872 record_files (struct nameseq *filenames, const char *pattern,
1873 const char *pattern_percent, struct dep *deps,
1874 unsigned int cmds_started, char *commands,
1875 unsigned int commands_idx, int two_colon,
1876 const struct floc *flocp)
1878 struct nameseq *nextf;
1879 int implicit = 0;
1880 unsigned int max_targets = 0, target_idx = 0;
1881 const char **targets = 0, **target_percents = 0;
1882 struct commands *cmds;
1884 /* If we've already snapped deps, that means we're in an eval being
1885 resolved after the makefiles have been read in. We can't add more rules
1886 at this time, since they won't get snapped and we'll get core dumps.
1887 See Savannah bug # 12124. */
1888 if (snapped_deps)
1889 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1891 if (commands_idx > 0)
1893 cmds = xmalloc (sizeof (struct commands));
1894 cmds->fileinfo.filenm = flocp->filenm;
1895 cmds->fileinfo.lineno = cmds_started;
1896 cmds->commands = xstrndup (commands, commands_idx);
1897 cmds->command_lines = 0;
1899 else
1900 cmds = 0;
1902 for (; filenames != 0; filenames = nextf)
1904 const char *name = filenames->name;
1905 struct file *f;
1906 struct dep *this = 0;
1907 const char *implicit_percent;
1909 nextf = filenames->next;
1910 free (filenames);
1912 /* Check for special targets. Do it here instead of, say, snap_deps()
1913 so that we can immediately use the value. */
1915 if (streq (name, ".POSIX"))
1916 posix_pedantic = 1;
1917 else if (streq (name, ".SECONDEXPANSION"))
1918 second_expansion = 1;
1920 implicit_percent = find_percent_cached (&name);
1921 implicit |= implicit_percent != 0;
1923 if (implicit)
1925 if (pattern != 0)
1926 fatal (flocp, _("mixed implicit and static pattern rules"));
1928 if (implicit_percent == 0)
1929 fatal (flocp, _("mixed implicit and normal rules"));
1931 if (targets == 0)
1933 max_targets = 5;
1934 targets = xmalloc (5 * sizeof (char *));
1935 target_percents = xmalloc (5 * sizeof (char *));
1936 target_idx = 0;
1938 else if (target_idx == max_targets - 1)
1940 max_targets += 5;
1941 targets = xrealloc (targets, max_targets * sizeof (char *));
1942 target_percents = xrealloc (target_percents,
1943 max_targets * sizeof (char *));
1945 targets[target_idx] = name;
1946 target_percents[target_idx] = implicit_percent;
1947 ++target_idx;
1948 continue;
1951 /* If this is a static pattern rule:
1952 `targets: target%pattern: dep%pattern; cmds',
1953 make sure the pattern matches this target name. */
1954 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1955 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1956 else if (deps)
1958 /* If there are multiple filenames, copy the chain DEPS for all but
1959 the last one. It is not safe for the same deps to go in more
1960 than one place in the database. */
1961 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1962 this->need_2nd_expansion = (second_expansion
1963 && strchr (this->name, '$'));
1966 if (!two_colon)
1968 /* Single-colon. Combine these dependencies
1969 with others in file's existing record, if any. */
1970 f = enter_file (strcache_add (name));
1972 if (f->double_colon)
1973 fatal (flocp,
1974 _("target file `%s' has both : and :: entries"), f->name);
1976 /* If CMDS == F->CMDS, this target was listed in this rule
1977 more than once. Just give a warning since this is harmless. */
1978 if (cmds != 0 && cmds == f->cmds)
1979 error (flocp,
1980 _("target `%s' given more than once in the same rule."),
1981 f->name);
1983 /* Check for two single-colon entries both with commands.
1984 Check is_target so that we don't lose on files such as .c.o
1985 whose commands were preinitialized. */
1986 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1988 error (&cmds->fileinfo,
1989 _("warning: overriding recipe for target `%s'"),
1990 f->name);
1991 error (&f->cmds->fileinfo,
1992 _("warning: ignoring old recipe for target `%s'"),
1993 f->name);
1996 f->is_target = 1;
1998 /* Defining .DEFAULT with no deps or cmds clears it. */
1999 if (f == default_file && this == 0 && cmds == 0)
2000 f->cmds = 0;
2001 if (cmds != 0)
2002 f->cmds = cmds;
2004 /* Defining .SUFFIXES with no dependencies clears out the list of
2005 suffixes. */
2006 if (f == suffix_file && this == 0)
2008 free_dep_chain (f->deps);
2009 f->deps = 0;
2011 else if (this != 0)
2013 /* Add the file's old deps and the new ones in THIS together. */
2015 if (f->deps != 0)
2017 struct dep **d_ptr = &f->deps;
2019 while ((*d_ptr)->next != 0)
2020 d_ptr = &(*d_ptr)->next;
2022 if (cmds != 0)
2024 /* This is the rule with commands, so put its deps
2025 last. The rationale behind this is that $< expands to
2026 the first dep in the chain, and commands use $<
2027 expecting to get the dep that rule specifies. However
2028 the second expansion algorithm reverses the order thus
2029 we need to make it last here. */
2030 (*d_ptr)->next = this;
2031 /* This is a hack. I need a way to communicate to
2032 snap_deps() that the last dependency line in this
2033 file came with commands (so that logic in snap_deps()
2034 can put it in front and all this $< -logic works). I
2035 cannot simply rely on file->cmds being not 0 because
2036 of the cases like the following:
2038 foo: bar
2039 foo:
2042 I am going to temporarily "borrow" UPDATING member in
2043 `struct file' for this. */
2044 f->updating = 1;
2046 else
2048 /* This is a rule without commands. If we already have
2049 a rule with commands and prerequisites (see "hack"
2050 comment above), put these prereqs at the end but
2051 before prereqs from the rule with commands. This way
2052 everything appears in makefile order. */
2053 if (f->updating)
2055 this->next = *d_ptr;
2056 *d_ptr = this;
2058 else
2059 (*d_ptr)->next = this;
2062 else
2063 f->deps = this;
2066 else
2068 /* Double-colon. Make a new record even if there already is one. */
2069 f = lookup_file (name);
2071 /* Check for both : and :: rules. Check is_target so
2072 we don't lose on default suffix rules or makefiles. */
2073 if (f != 0 && f->is_target && !f->double_colon)
2074 fatal (flocp,
2075 _("target file `%s' has both : and :: entries"), f->name);
2076 f = enter_file (strcache_add (name));
2077 /* If there was an existing entry and it was a double-colon entry,
2078 enter_file will have returned a new one, making it the prev
2079 pointer of the old one, and setting its double_colon pointer to
2080 the first one. */
2081 if (f->double_colon == 0)
2082 /* This is the first entry for this name, so we must set its
2083 double_colon pointer to itself. */
2084 f->double_colon = f;
2085 f->is_target = 1;
2086 f->deps = this;
2087 f->cmds = cmds;
2090 /* If this is a static pattern rule, set the stem to the part of its
2091 name that matched the `%' in the pattern, so you can use $* in the
2092 commands. */
2093 if (pattern)
2095 static const char *percent = "%";
2096 char *buffer = variable_expand ("");
2097 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2098 pattern_percent+1, percent+1);
2099 f->stem = strcache_add_len (buffer, o - buffer);
2100 if (this)
2102 this->staticpattern = 1;
2103 this->stem = f->stem;
2107 name = f->name;
2110 if (implicit)
2112 if (deps)
2113 deps->need_2nd_expansion = second_expansion;
2114 create_pattern_rule (targets, target_percents, target_idx,
2115 two_colon, deps, cmds, 1);
2119 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2120 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2121 Quoting backslashes are removed from STRING by compacting it into
2122 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2123 one, or nil if there are none. STOPCHARs inside variable references are
2124 ignored if IGNOREVARS is true.
2126 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2128 static char *
2129 find_char_unquote (char *string, int stop1, int stop2, int blank,
2130 int ignorevars)
2132 unsigned int string_len = 0;
2133 char *p = string;
2135 if (ignorevars)
2136 ignorevars = '$';
2138 while (1)
2140 if (stop2 && blank)
2141 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2142 && ! isblank ((unsigned char) *p))
2143 ++p;
2144 else if (stop2)
2145 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2146 ++p;
2147 else if (blank)
2148 while (*p != '\0' && *p != ignorevars && *p != stop1
2149 && ! isblank ((unsigned char) *p))
2150 ++p;
2151 else
2152 while (*p != '\0' && *p != ignorevars && *p != stop1)
2153 ++p;
2155 if (*p == '\0')
2156 break;
2158 /* If we stopped due to a variable reference, skip over its contents. */
2159 if (*p == ignorevars)
2161 char openparen = p[1];
2163 p += 2;
2165 /* Skip the contents of a non-quoted, multi-char variable ref. */
2166 if (openparen == '(' || openparen == '{')
2168 unsigned int pcount = 1;
2169 char closeparen = (openparen == '(' ? ')' : '}');
2171 while (*p)
2173 if (*p == openparen)
2174 ++pcount;
2175 else if (*p == closeparen)
2176 if (--pcount == 0)
2178 ++p;
2179 break;
2181 ++p;
2185 /* Skipped the variable reference: look for STOPCHARS again. */
2186 continue;
2189 if (p > string && p[-1] == '\\')
2191 /* Search for more backslashes. */
2192 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 memmove (&p[i], &p[i/2], (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 % and handle quoting. */
2221 char *
2222 find_percent (char *pattern)
2224 return find_char_unquote (pattern, '%', 0, 0, 0);
2227 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2228 the % or NULL if no % was found.
2229 This version is used with strings in the string cache: if there's a need to
2230 modify the string a new version will be added to the string cache and
2231 *STRING will be set to that. */
2233 const char *
2234 find_percent_cached (const char **string)
2236 const char *p = *string;
2237 char *new = 0;
2238 int slen;
2240 /* If the first char is a % return now. This lets us avoid extra tests
2241 inside the loop. */
2242 if (*p == '%')
2243 return p;
2245 while (1)
2247 while (*p != '\0' && *p != '%')
2248 ++p;
2250 if (*p == '\0')
2251 break;
2253 /* See if this % is escaped with a backslash; if not we're done. */
2254 if (p[-1] != '\\')
2255 break;
2258 /* Search for more backslashes. */
2259 char *pv;
2260 int i = -2;
2262 while (&p[i] >= *string && p[i] == '\\')
2263 --i;
2264 ++i;
2266 /* At this point we know we'll need to allocate a new string.
2267 Make a copy if we haven't yet done so. */
2268 if (! new)
2270 slen = strlen (*string);
2271 new = alloca (slen + 1);
2272 memcpy (new, *string, slen + 1);
2273 p = new + (p - *string);
2274 *string = new;
2277 /* At this point *string, p, and new all point into the same string.
2278 Get a non-const version of p so we can modify new. */
2279 pv = new + (p - *string);
2281 /* The number of backslashes is now -I.
2282 Copy P over itself to swallow half of them. */
2283 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2284 p += i/2;
2286 /* If the backslashes quoted each other; the % was unquoted. */
2287 if (i % 2 == 0)
2288 break;
2292 /* If we had to change STRING, add it to the strcache. */
2293 if (new)
2295 *string = strcache_add (*string);
2296 p = *string + (p - new);
2299 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2300 return (*p == '\0') ? NULL : p;
2303 /* Find the next line of text in an eval buffer, combining continuation lines
2304 into one line.
2305 Return the number of actual lines read (> 1 if continuation lines).
2306 Returns -1 if there's nothing left in the buffer.
2308 After this function, ebuf->buffer points to the first character of the
2309 line we just found.
2312 /* Read a line of text from a STRING.
2313 Since we aren't really reading from a file, don't bother with linenumbers.
2316 static unsigned long
2317 readstring (struct ebuffer *ebuf)
2319 char *eol;
2321 /* If there is nothing left in this buffer, return 0. */
2322 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2323 return -1;
2325 /* Set up a new starting point for the buffer, and find the end of the
2326 next logical line (taking into account backslash/newline pairs). */
2328 eol = ebuf->buffer = ebuf->bufnext;
2330 while (1)
2332 int backslash = 0;
2333 char *bol = eol;
2334 char *p;
2336 /* Find the next newline. At EOS, stop. */
2337 eol = p = strchr (eol , '\n');
2338 if (!eol)
2340 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2341 return 0;
2344 /* Found a newline; if it's escaped continue; else we're done. */
2345 while (p > bol && *(--p) == '\\')
2346 backslash = !backslash;
2347 if (!backslash)
2348 break;
2349 ++eol;
2352 /* Overwrite the newline char. */
2353 *eol = '\0';
2354 ebuf->bufnext = eol+1;
2356 return 0;
2359 static long
2360 readline (struct ebuffer *ebuf)
2362 char *p;
2363 char *end;
2364 char *start;
2365 long nlines = 0;
2367 /* The behaviors between string and stream buffers are different enough to
2368 warrant different functions. Do the Right Thing. */
2370 if (!ebuf->fp)
2371 return readstring (ebuf);
2373 /* When reading from a file, we always start over at the beginning of the
2374 buffer for each new line. */
2376 p = start = ebuf->bufstart;
2377 end = p + ebuf->size;
2378 *p = '\0';
2380 while (fgets (p, end - p, ebuf->fp) != 0)
2382 char *p2;
2383 unsigned long len;
2384 int backslash;
2386 len = strlen (p);
2387 if (len == 0)
2389 /* This only happens when the first thing on the line is a '\0'.
2390 It is a pretty hopeless case, but (wonder of wonders) Athena
2391 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2392 There is nothing really to be done; we synthesize a newline so
2393 the following line doesn't appear to be part of this line. */
2394 error (&ebuf->floc,
2395 _("warning: NUL character seen; rest of line ignored"));
2396 p[0] = '\n';
2397 len = 1;
2400 /* Jump past the text we just read. */
2401 p += len;
2403 /* If the last char isn't a newline, the whole line didn't fit into the
2404 buffer. Get some more buffer and try again. */
2405 if (p[-1] != '\n')
2406 goto more_buffer;
2408 /* We got a newline, so add one to the count of lines. */
2409 ++nlines;
2411 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2412 /* Check to see if the line was really ended with CRLF; if so ignore
2413 the CR. */
2414 if ((p - start) > 1 && p[-2] == '\r')
2416 --p;
2417 p[-1] = '\n';
2419 #endif
2421 backslash = 0;
2422 for (p2 = p - 2; p2 >= start; --p2)
2424 if (*p2 != '\\')
2425 break;
2426 backslash = !backslash;
2429 if (!backslash)
2431 p[-1] = '\0';
2432 break;
2435 /* It was a backslash/newline combo. If we have more space, read
2436 another line. */
2437 if (end - p >= 80)
2438 continue;
2440 /* We need more space at the end of our buffer, so realloc it.
2441 Make sure to preserve the current offset of p. */
2442 more_buffer:
2444 unsigned long off = p - start;
2445 ebuf->size *= 2;
2446 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2447 p = start + off;
2448 end = start + ebuf->size;
2449 *p = '\0';
2453 if (ferror (ebuf->fp))
2454 pfatal_with_name (ebuf->floc.filenm);
2456 /* If we found some lines, return how many.
2457 If we didn't, but we did find _something_, that indicates we read the last
2458 line of a file with no final newline; return 1.
2459 If we read nothing, we're at EOF; return -1. */
2461 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2464 /* Parse the next "makefile word" from the input buffer, and return info
2465 about it.
2467 A "makefile word" is one of:
2469 w_bogus Should never happen
2470 w_eol End of input
2471 w_static A static word; cannot be expanded
2472 w_variable A word containing one or more variables/functions
2473 w_colon A colon
2474 w_dcolon A double-colon
2475 w_semicolon A semicolon
2476 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2478 Note that this function is only used when reading certain parts of the
2479 makefile. Don't use it where special rules hold sway (RHS of a variable,
2480 in a command list, etc.) */
2482 static enum make_word_type
2483 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2485 enum make_word_type wtype = w_bogus;
2486 char *p = buffer, *beg;
2487 char c;
2489 /* Skip any leading whitespace. */
2490 while (isblank ((unsigned char)*p))
2491 ++p;
2493 beg = p;
2494 c = *(p++);
2495 switch (c)
2497 case '\0':
2498 wtype = w_eol;
2499 break;
2501 case ';':
2502 wtype = w_semicolon;
2503 break;
2505 case '=':
2506 wtype = w_varassign;
2507 break;
2509 case ':':
2510 wtype = w_colon;
2511 switch (*p)
2513 case ':':
2514 ++p;
2515 wtype = w_dcolon;
2516 break;
2518 case '=':
2519 ++p;
2520 wtype = w_varassign;
2521 break;
2523 break;
2525 case '+':
2526 case '?':
2527 if (*p == '=')
2529 ++p;
2530 wtype = w_varassign;
2531 break;
2534 default:
2535 if (delim && strchr (delim, c))
2536 wtype = w_static;
2537 break;
2540 /* Did we find something? If so, return now. */
2541 if (wtype != w_bogus)
2542 goto done;
2544 /* This is some non-operator word. A word consists of the longest
2545 string of characters that doesn't contain whitespace, one of [:=#],
2546 or [?+]=, or one of the chars in the DELIM string. */
2548 /* We start out assuming a static word; if we see a variable we'll
2549 adjust our assumptions then. */
2550 wtype = w_static;
2552 /* We already found the first value of "c", above. */
2553 while (1)
2555 char closeparen;
2556 int count;
2558 switch (c)
2560 case '\0':
2561 case ' ':
2562 case '\t':
2563 case '=':
2564 goto done_word;
2566 case ':':
2567 #ifdef HAVE_DOS_PATHS
2568 /* A word CAN include a colon in its drive spec. The drive
2569 spec is allowed either at the beginning of a word, or as part
2570 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2571 if (!(p - beg >= 2
2572 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2573 && (p - beg == 2 || p[-3] == '(')))
2574 #endif
2575 goto done_word;
2577 case '$':
2578 c = *(p++);
2579 if (c == '$')
2580 break;
2582 /* This is a variable reference, so note that it's expandable.
2583 Then read it to the matching close paren. */
2584 wtype = w_variable;
2586 if (c == '(')
2587 closeparen = ')';
2588 else if (c == '{')
2589 closeparen = '}';
2590 else
2591 /* This is a single-letter variable reference. */
2592 break;
2594 for (count=0; *p != '\0'; ++p)
2596 if (*p == c)
2597 ++count;
2598 else if (*p == closeparen && --count < 0)
2600 ++p;
2601 break;
2604 break;
2606 case '?':
2607 case '+':
2608 if (*p == '=')
2609 goto done_word;
2610 break;
2612 case '\\':
2613 switch (*p)
2615 case ':':
2616 case ';':
2617 case '=':
2618 case '\\':
2619 ++p;
2620 break;
2622 break;
2624 default:
2625 if (delim && strchr (delim, c))
2626 goto done_word;
2627 break;
2630 c = *(p++);
2632 done_word:
2633 --p;
2635 done:
2636 if (startp)
2637 *startp = beg;
2638 if (length)
2639 *length = p - beg;
2640 return wtype;
2643 /* Construct the list of include directories
2644 from the arguments and the default list. */
2646 void
2647 construct_include_path (const char **arg_dirs)
2649 #ifdef VAXC /* just don't ask ... */
2650 stat_t stbuf;
2651 #else
2652 struct stat stbuf;
2653 #endif
2654 const char **dirs;
2655 const char **cpp;
2656 unsigned int idx;
2658 /* Compute the number of pointers we need in the table. */
2659 idx = sizeof (default_include_directories) / sizeof (const char *);
2660 if (arg_dirs)
2661 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2662 ++idx;
2664 #ifdef __MSDOS__
2665 /* Add one for $DJDIR. */
2666 ++idx;
2667 #endif
2669 dirs = xmalloc (idx * sizeof (const char *));
2671 idx = 0;
2672 max_incl_len = 0;
2674 /* First consider any dirs specified with -I switches.
2675 Ignore any that don't exist. Remember the maximum string length. */
2677 if (arg_dirs)
2678 while (*arg_dirs != 0)
2680 const char *dir = *(arg_dirs++);
2681 char *expanded = 0;
2682 int e;
2684 if (dir[0] == '~')
2686 expanded = tilde_expand (dir);
2687 if (expanded != 0)
2688 dir = expanded;
2691 EINTRLOOP (e, stat (dir, &stbuf));
2692 if (e == 0 && S_ISDIR (stbuf.st_mode))
2694 unsigned int len = strlen (dir);
2695 /* If dir name is written with trailing slashes, discard them. */
2696 while (len > 1 && dir[len - 1] == '/')
2697 --len;
2698 if (len > max_incl_len)
2699 max_incl_len = len;
2700 dirs[idx++] = strcache_add_len (dir, len);
2703 if (expanded)
2704 free (expanded);
2707 /* Now add the standard default dirs at the end. */
2709 #ifdef __MSDOS__
2711 /* The environment variable $DJDIR holds the root of the DJGPP directory
2712 tree; add ${DJDIR}/include. */
2713 struct variable *djdir = lookup_variable ("DJDIR", 5);
2715 if (djdir)
2717 unsigned int len = strlen (djdir->value) + 8;
2718 char *defdir = alloca (len + 1);
2720 strcat (strcpy (defdir, djdir->value), "/include");
2721 dirs[idx++] = strcache_add (defdir);
2723 if (len > max_incl_len)
2724 max_incl_len = len;
2727 #endif
2729 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2731 int e;
2733 EINTRLOOP (e, stat (*cpp, &stbuf));
2734 if (e == 0 && S_ISDIR (stbuf.st_mode))
2736 unsigned int len = strlen (*cpp);
2737 /* If dir name is written with trailing slashes, discard them. */
2738 while (len > 1 && (*cpp)[len - 1] == '/')
2739 --len;
2740 if (len > max_incl_len)
2741 max_incl_len = len;
2742 dirs[idx++] = strcache_add_len (*cpp, len);
2746 dirs[idx] = 0;
2748 /* Now add each dir to the .INCLUDE_DIRS variable. */
2750 for (cpp = dirs; *cpp != 0; ++cpp)
2751 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2752 o_default, f_append, 0);
2754 include_directories = dirs;
2757 /* Expand ~ or ~USER at the beginning of NAME.
2758 Return a newly malloc'd string or 0. */
2760 char *
2761 tilde_expand (const char *name)
2763 #ifndef VMS
2764 if (name[1] == '/' || name[1] == '\0')
2766 extern char *getenv ();
2767 char *home_dir;
2768 int is_variable;
2771 /* Turn off --warn-undefined-variables while we expand HOME. */
2772 int save = warn_undefined_variables_flag;
2773 warn_undefined_variables_flag = 0;
2775 home_dir = allocated_variable_expand ("$(HOME)");
2777 warn_undefined_variables_flag = save;
2780 is_variable = home_dir[0] != '\0';
2781 if (!is_variable)
2783 free (home_dir);
2784 home_dir = getenv ("HOME");
2786 # if !defined(_AMIGA) && !defined(WINDOWS32)
2787 if (home_dir == 0 || home_dir[0] == '\0')
2789 extern char *getlogin ();
2790 char *logname = getlogin ();
2791 home_dir = 0;
2792 if (logname != 0)
2794 struct passwd *p = getpwnam (logname);
2795 if (p != 0)
2796 home_dir = p->pw_dir;
2799 # endif /* !AMIGA && !WINDOWS32 */
2800 if (home_dir != 0)
2802 char *new = xstrdup (concat (2, home_dir, name + 1));
2803 if (is_variable)
2804 free (home_dir);
2805 return new;
2808 # if !defined(_AMIGA) && !defined(WINDOWS32)
2809 else
2811 struct passwd *pwent;
2812 char *userend = strchr (name + 1, '/');
2813 if (userend != 0)
2814 *userend = '\0';
2815 pwent = getpwnam (name + 1);
2816 if (pwent != 0)
2818 if (userend == 0)
2819 return xstrdup (pwent->pw_dir);
2820 else
2821 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2823 else if (userend != 0)
2824 *userend = '/';
2826 # endif /* !AMIGA && !WINDOWS32 */
2827 #endif /* !VMS */
2828 return 0;
2831 /* Parse a string into a sequence of filenames represented as a chain of
2832 struct nameseq's and return that chain. Optionally expand the strings via
2833 glob().
2835 The string is passed as STRINGP, the address of a string pointer.
2836 The string pointer is updated to point at the first character
2837 not parsed, which either is a null char or equals STOPCHAR.
2839 SIZE is how big to construct chain elements.
2840 This is useful if we want them actually to be other structures
2841 that have room for additional info.
2843 PREFIX, if non-null, is added to the beginning of each filename.
2845 FLAGS allows one or more of the following bitflags to be set:
2846 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2847 PARSEFS_NOGLOB - Do not expand globbing characters
2848 PARSEFS_EXISTS - Only return globbed files that actually exist
2849 (cannot also set NOGLOB)
2850 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2853 struct nameseq *
2854 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2855 const char *prefix, int flags)
2857 extern void dir_setup_glob (glob_t *glob);
2859 /* tmp points to tmpbuf after the prefix, if any.
2860 tp is the end of the buffer. */
2861 static char *tmpbuf = NULL;
2862 static int tmpbuf_len = 0;
2864 int cachep = (! (flags & PARSEFS_NOCACHE));
2866 struct nameseq *new = 0;
2867 struct nameseq **newp = &new;
2868 #define NEWELT(_n) do { \
2869 const char *__n = (_n); \
2870 *newp = xcalloc (size); \
2871 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2872 newp = &(*newp)->next; \
2873 } while(0)
2875 char *p;
2876 glob_t gl;
2877 char *tp;
2879 #ifdef VMS
2880 # define VMS_COMMA ','
2881 #else
2882 # define VMS_COMMA 0
2883 #endif
2885 if (size < sizeof (struct nameseq))
2886 size = sizeof (struct nameseq);
2888 if (! (flags & PARSEFS_NOGLOB))
2889 dir_setup_glob (&gl);
2891 /* Get enough temporary space to construct the largest possible target. */
2893 int l = strlen (*stringp) + 1;
2894 if (l > tmpbuf_len)
2896 tmpbuf = xrealloc (tmpbuf, l);
2897 tmpbuf_len = l;
2900 tp = tmpbuf;
2902 /* Parse STRING. P will always point to the end of the parsed content. */
2903 p = *stringp;
2904 while (1)
2906 const char *name;
2907 const char **nlist = 0;
2908 char *tildep = 0;
2909 #ifndef NO_ARCHIVES
2910 char *arname = 0;
2911 char *memname = 0;
2912 #endif
2913 char *s;
2914 int nlen;
2915 int i;
2917 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2918 p = next_token (p);
2919 if (*p == '\0' || *p == stopchar)
2920 break;
2922 /* There are names left, so find the end of the next name.
2923 Throughout this iteration S points to the start. */
2924 s = p;
2925 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2926 #ifdef VMS
2927 /* convert comma separated list to space separated */
2928 if (p && *p == ',')
2929 *p =' ';
2930 #endif
2931 #ifdef _AMIGA
2932 if (stopchar == ':' && p && *p == ':'
2933 && !(isspace ((unsigned char)p[1]) || !p[1]
2934 || isspace ((unsigned char)p[-1])))
2935 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2936 #endif
2937 #ifdef HAVE_DOS_PATHS
2938 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2939 first colon which isn't followed by a slash or a backslash.
2940 Note that tokens separated by spaces should be treated as separate
2941 tokens since make doesn't allow path names with spaces */
2942 if (stopchar == ':')
2943 while (p != 0 && !isspace ((unsigned char)*p) &&
2944 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2945 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2946 #endif
2947 if (p == 0)
2948 p = s + strlen (s);
2950 /* Strip leading "this directory" references. */
2951 if (! (flags & PARSEFS_NOSTRIP))
2952 #ifdef VMS
2953 /* Skip leading `[]'s. */
2954 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2955 #else
2956 /* Skip leading `./'s. */
2957 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2958 #endif
2960 /* Skip "./" and all following slashes. */
2961 s += 2;
2962 while (*s == '/')
2963 ++s;
2966 /* Extract the filename just found, and skip it.
2967 Set NAME to the string, and NLEN to its length. */
2969 if (s == p)
2971 /* The name was stripped to empty ("./"). */
2972 #if defined(VMS)
2973 continue;
2974 #elif defined(_AMIGA)
2975 /* PDS-- This cannot be right!! */
2976 tp[0] = '\0';
2977 nlen = 0;
2978 #else
2979 tp[0] = '.';
2980 tp[1] = '/';
2981 tp[2] = '\0';
2982 nlen = 2;
2983 #endif
2985 else
2987 #ifdef VMS
2988 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2989 * to remove this '\' before we can use the filename.
2990 * xstrdup called because S may be read-only string constant.
2992 char *n = tp;
2993 while (s < p)
2995 if (s[0] == '\\' && s[1] == ':')
2996 ++s;
2997 *(n++) = *(s++);
2999 n[0] = '\0';
3000 nlen = strlen (tp);
3001 #else
3002 nlen = p - s;
3003 memcpy (tp, s, nlen);
3004 tp[nlen] = '\0';
3005 #endif
3008 /* At this point, TP points to the element and NLEN is its length. */
3010 #ifndef NO_ARCHIVES
3011 /* If this is the start of an archive group that isn't complete, set up
3012 to add the archive prefix for future files.
3014 TP == TMP means we're not already in an archive group. Ignore
3015 something starting with `(', as that cannot actually be an
3016 archive-member reference (and treating it as such results in an empty
3017 file name, which causes much lossage). Also if it ends in ")" then
3018 it's a complete reference so we don't need to treat it specially. */
3020 if (tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3022 char *n = strchr (tp, '(');
3023 if (n)
3025 /* This is the first element in an open archive group. It looks
3026 like "lib(mem". Remember the close paren. */
3027 nlen -= (n + 1) - tp;
3028 tp = n + 1;
3030 /* If we have just "lib(", part of something like "lib( a b)",
3031 go to the next item. */
3032 if (! nlen)
3033 continue;
3037 /* If we are inside an archive group, make sure it has an end. */
3038 if (tp > tmpbuf)
3040 if (tp[nlen-1] == ')')
3042 /* This is the natural end; reset TP. */
3043 tp = tmpbuf;
3045 /* This is just ")", something like "lib(a b )": skip it. */
3046 if (nlen == 1)
3047 continue;
3049 else
3051 /* Not the end, so add a "fake" end. */
3052 tp[nlen++] = ')';
3053 tp[nlen] = '\0';
3056 #endif
3058 /* If we're not globbing we're done: add it to the end of the chain.
3059 Go to the next item in the string. */
3060 if (flags & PARSEFS_NOGLOB)
3062 NEWELT (concat (2, prefix, tp));
3063 continue;
3066 /* If we get here we know we're doing glob expansion.
3067 TP is a string in tmpbuf. NLEN is no longer used.
3068 We may need to do more work: after this NAME will be set. */
3069 name = tp;
3071 /* Expand tilde if applicable. */
3072 if (tp[0] == '~')
3074 tildep = tilde_expand (tp);
3075 if (tildep != 0)
3076 name = tildep;
3079 #ifndef NO_ARCHIVES
3080 /* If NAME is an archive member reference replace it with the archive
3081 file name, and save the member name in MEMNAME. We will glob on the
3082 archive name and then reattach MEMNAME later. */
3083 if (ar_name (name))
3085 ar_parse_name (name, &arname, &memname);
3086 name = arname;
3088 #endif /* !NO_ARCHIVES */
3090 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3092 case GLOB_NOSPACE:
3093 fatal (NILF, _("virtual memory exhausted"));
3095 case 0:
3096 /* Success. */
3097 i = gl.gl_pathc;
3098 nlist = (const char **)gl.gl_pathv;
3099 break;
3101 case GLOB_NOMATCH:
3102 /* If we want only existing items, skip this one. */
3103 if (flags & PARSEFS_EXISTS)
3105 i = 0;
3106 break;
3108 /* FALLTHROUGH */
3110 default:
3111 /* By default keep this name. */
3112 i = 1;
3113 nlist = &name;
3114 break;
3117 /* For each matched element, add it to the list. */
3118 while (i-- > 0)
3119 #ifndef NO_ARCHIVES
3120 if (memname != 0)
3122 /* Try to glob on MEMNAME within the archive. */
3123 struct nameseq *found = ar_glob (nlist[i], memname, size);
3124 if (! found)
3125 /* No matches. Use MEMNAME as-is. */
3126 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3127 else
3129 /* We got a chain of items. Attach them. */
3130 (*newp)->next = found;
3132 /* Find and set the new end. Massage names if necessary. */
3133 while (1)
3135 if (! cachep)
3136 found->name = xstrdup (concat (2, prefix, name));
3137 else if (prefix)
3138 found->name = strcache_add (concat (2, prefix, name));
3140 if (found->next == 0)
3141 break;
3143 found = found->next;
3145 newp = &found->next;
3148 else
3149 #endif /* !NO_ARCHIVES */
3150 NEWELT (concat (2, prefix, nlist[i]));
3152 globfree (&gl);
3154 #ifndef NO_ARCHIVES
3155 if (arname)
3156 free (arname);
3157 #endif
3159 if (tildep)
3160 free (tildep);
3163 *stringp = p;
3164 return new;