Add 'private' variable modifier, feature submitted by Ramon Garcia.
[make.git] / read.c
blobec6d6afc2bbcd6456b294cde694d000faec21d64
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, unsigned int namelen,
140 enum variable_origin origin,
141 struct ebuffer *ebuf);
142 static int conditional_line (char *line, int len, const struct floc *flocp);
143 static void record_files (struct nameseq *filenames, const char *pattern,
144 const char *pattern_percent, struct dep *deps,
145 unsigned int cmds_started, char *commands,
146 unsigned int commands_idx, int two_colon,
147 const struct floc *flocp);
148 static void record_target_var (struct nameseq *filenames, char *defn,
149 enum variable_origin origin,
150 struct vmodifiers *vmod,
151 const struct floc *flocp);
152 static enum make_word_type get_next_mword (char *buffer, char *delim,
153 char **startp, unsigned int *length);
154 static void remove_comments (char *line);
155 static char *find_char_unquote (char *string, int stop1, int stop2,
156 int blank, int ignorevars);
159 /* Compare a word, both length and contents.
160 P must point to the word to be tested, and WLEN must be the length.
162 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
165 /* Read in all the makefiles and return the chain of their names. */
167 struct dep *
168 read_all_makefiles (const char **makefiles)
170 unsigned int num_makefiles = 0;
172 /* Create *_LIST variables, to hold the makefiles, targets, and variables
173 we will be reading. */
175 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
177 DB (DB_BASIC, (_("Reading makefiles...\n")));
179 /* If there's a non-null variable MAKEFILES, its value is a list of
180 files to read first thing. But don't let it prevent reading the
181 default makefiles and don't let the default goal come from there. */
184 char *value;
185 char *name, *p;
186 unsigned int length;
189 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
190 int save = warn_undefined_variables_flag;
191 warn_undefined_variables_flag = 0;
193 value = allocated_variable_expand ("$(MAKEFILES)");
195 warn_undefined_variables_flag = save;
198 /* Set NAME to the start of next token and LENGTH to its length.
199 MAKEFILES is updated for finding remaining tokens. */
200 p = value;
202 while ((name = find_next_token ((const char **)&p, &length)) != 0)
204 if (*p != '\0')
205 *p++ = '\0';
206 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
209 free (value);
212 /* Read makefiles specified with -f switches. */
214 if (makefiles != 0)
215 while (*makefiles != 0)
217 struct dep *tail = read_makefiles;
218 register struct dep *d;
220 if (! eval_makefile (*makefiles, 0))
221 perror_with_name ("", *makefiles);
223 /* Find the right element of read_makefiles. */
224 d = read_makefiles;
225 while (d->next != tail)
226 d = d->next;
228 /* Use the storage read_makefile allocates. */
229 *makefiles = dep_name (d);
230 ++num_makefiles;
231 ++makefiles;
234 /* If there were no -f switches, try the default names. */
236 if (num_makefiles == 0)
238 static char *default_makefiles[] =
239 #ifdef VMS
240 /* all lower case since readdir() (the vms version) 'lowercasifies' */
241 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
242 #else
243 #ifdef _AMIGA
244 { "GNUmakefile", "Makefile", "SMakefile", 0 };
245 #else /* !Amiga && !VMS */
246 { "GNUmakefile", "makefile", "Makefile", 0 };
247 #endif /* AMIGA */
248 #endif /* VMS */
249 register char **p = default_makefiles;
250 while (*p != 0 && !file_exists_p (*p))
251 ++p;
253 if (*p != 0)
255 if (! eval_makefile (*p, 0))
256 perror_with_name ("", *p);
258 else
260 /* No default makefile was found. Add the default makefiles to the
261 `read_makefiles' chain so they will be updated if possible. */
262 struct dep *tail = read_makefiles;
263 /* Add them to the tail, after any MAKEFILES variable makefiles. */
264 while (tail != 0 && tail->next != 0)
265 tail = tail->next;
266 for (p = default_makefiles; *p != 0; ++p)
268 struct dep *d = alloc_dep ();
269 d->file = enter_file (strcache_add (*p));
270 d->file->dontcare = 1;
271 /* Tell update_goal_chain to bail out as soon as this file is
272 made, and main not to die if we can't make this file. */
273 d->changed = RM_DONTCARE;
274 if (tail == 0)
275 read_makefiles = d;
276 else
277 tail->next = d;
278 tail = d;
280 if (tail != 0)
281 tail->next = 0;
285 return read_makefiles;
288 /* Install a new conditional and return the previous one. */
290 static struct conditionals *
291 install_conditionals (struct conditionals *new)
293 struct conditionals *save = conditionals;
295 memset (new, '\0', sizeof (*new));
296 conditionals = new;
298 return save;
301 /* Free the current conditionals and reinstate a saved one. */
303 static void
304 restore_conditionals (struct conditionals *saved)
306 /* Free any space allocated by conditional_line. */
307 if (conditionals->ignoring)
308 free (conditionals->ignoring);
309 if (conditionals->seen_else)
310 free (conditionals->seen_else);
312 /* Restore state. */
313 conditionals = saved;
316 static int
317 eval_makefile (const char *filename, int flags)
319 struct dep *deps;
320 struct ebuffer ebuf;
321 const struct floc *curfile;
322 char *expanded = 0;
323 int makefile_errno;
324 int r;
326 filename = strcache_add (filename);
327 ebuf.floc.filenm = filename;
328 ebuf.floc.lineno = 1;
330 if (ISDB (DB_VERBOSE))
332 printf (_("Reading makefile `%s'"), filename);
333 if (flags & RM_NO_DEFAULT_GOAL)
334 printf (_(" (no default goal)"));
335 if (flags & RM_INCLUDED)
336 printf (_(" (search path)"));
337 if (flags & RM_DONTCARE)
338 printf (_(" (don't care)"));
339 if (flags & RM_NO_TILDE)
340 printf (_(" (no ~ expansion)"));
341 puts ("...");
344 /* First, get a stream to read. */
346 /* Expand ~ in FILENAME unless it came from `include',
347 in which case it was already done. */
348 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
350 expanded = tilde_expand (filename);
351 if (expanded != 0)
352 filename = expanded;
355 ebuf.fp = fopen (filename, "r");
356 /* Save the error code so we print the right message later. */
357 makefile_errno = errno;
359 /* If the makefile wasn't found and it's either a makefile from
360 the `MAKEFILES' variable or an included makefile,
361 search the included makefile search path for this makefile. */
362 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
364 unsigned int i;
365 for (i = 0; include_directories[i] != 0; ++i)
367 const char *included = concat (include_directories[i], "/", 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 /* Add this makefile to the list. */
404 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
405 f_append, 0);
407 /* Evaluate the makefile */
409 ebuf.size = 200;
410 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
412 curfile = reading_file;
413 reading_file = &ebuf.floc;
415 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
417 reading_file = curfile;
419 fclose (ebuf.fp);
421 free (ebuf.bufstart);
422 alloca (0);
423 return r;
427 eval_buffer (char *buffer)
429 struct ebuffer ebuf;
430 struct conditionals *saved;
431 struct conditionals new;
432 const struct floc *curfile;
433 int r;
435 /* Evaluate the buffer */
437 ebuf.size = strlen (buffer);
438 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
439 ebuf.fp = NULL;
441 ebuf.floc = *reading_file;
443 curfile = reading_file;
444 reading_file = &ebuf.floc;
446 saved = install_conditionals (&new);
448 r = eval (&ebuf, 1);
450 restore_conditionals (saved);
452 reading_file = curfile;
454 alloca (0);
455 return r;
458 /* Check LINE to see if it's a variable assignment.
460 It might use one of the modifiers "export", "override", "private", or it
461 might be one of the conditional tokens like "ifdef", "include", etc.
463 If it's not a variable assignment, VMOD.V_ASSIGN is 0. Returns LINE.
465 Returns a pointer to the first non-modifier character, and sets VMOD
466 based on the modifiers found if any, plus V_ASSIGN is 1.
468 char *
469 parse_var_assignment (const char *line, struct vmodifiers *vmod)
471 const char *p;
472 memset (vmod, '\0', sizeof (*vmod));
474 /* Find the start of the next token. If there isn't one we're done. */
475 line = next_token (line);
476 if (*line == '\0')
477 return (char *)line;
479 p = line;
480 while (1)
482 int wlen;
483 const char *p2;
484 enum variable_flavor flavor;
486 p2 = parse_variable_definition (p, &flavor);
488 /* If this is a variable assignment, we're done. */
489 if (p2)
490 break;
492 /* It's not a variable; see if it's a modifier. */
493 p2 = end_of_token (p);
494 wlen = p2 - p;
496 if (word1eq ("export"))
497 vmod->export_v = 1;
498 else if (word1eq ("override"))
499 vmod->override_v = 1;
500 else if (word1eq ("private"))
501 vmod->private_v = 1;
502 else if (word1eq ("define"))
504 /* We can't have modifiers after 'define' */
505 vmod->define_v = 1;
506 p = next_token (p2);
507 break;
509 else
510 /* Not a variable or modifier: this is not a variable assignment. */
511 return (char *)line;
513 /* It was a modifier. Try the next word. */
514 p = next_token (p2);
515 if (*p == '\0')
516 return (char *)line;
519 /* Found a variable assignment. */
520 vmod->assign_v = 1;
521 return (char *)p;
526 /* Read file FILENAME as a makefile and add its contents to the data base.
528 SET_DEFAULT is true if we are allowed to set the default goal. */
531 static int
532 eval (struct ebuffer *ebuf, int set_default)
534 char *collapsed = 0;
535 unsigned int collapsed_length = 0;
536 unsigned int commands_len = 200;
537 char *commands;
538 unsigned int commands_idx = 0;
539 unsigned int cmds_started, tgts_started;
540 int ignoring = 0, in_ignored_define = 0;
541 int no_targets = 0; /* Set when reading a rule without targets. */
542 struct nameseq *filenames = 0;
543 struct dep *deps = 0;
544 long nlines = 0;
545 int two_colon = 0;
546 const char *pattern = 0;
547 const char *pattern_percent;
548 struct floc *fstart;
549 struct floc fi;
551 #define record_waiting_files() \
552 do \
554 if (filenames != 0) \
556 fi.lineno = tgts_started; \
557 record_files (filenames, pattern, pattern_percent, deps, \
558 cmds_started, commands, commands_idx, two_colon, \
559 &fi); \
561 filenames = 0; \
562 commands_idx = 0; \
563 no_targets = 0; \
564 pattern = 0; \
565 } while (0)
567 pattern_percent = 0;
568 cmds_started = tgts_started = 1;
570 fstart = &ebuf->floc;
571 fi.filenm = ebuf->floc.filenm;
573 /* Loop over lines in the file.
574 The strategy is to accumulate target names in FILENAMES, dependencies
575 in DEPS and commands in COMMANDS. These are used to define a rule
576 when the start of the next rule (or eof) is encountered.
578 When you see a "continue" in the loop below, that means we are moving on
579 to the next line _without_ ending any rule that we happen to be working
580 with at the moment. If you see a "goto rule_complete", then the
581 statement we just parsed also finishes the previous rule. */
583 commands = xmalloc (200);
585 while (1)
587 unsigned int linelen;
588 char *line;
589 unsigned int wlen;
590 char *p;
591 char *p2;
592 struct vmodifiers vmod;
594 /* At the top of this loop, we are starting a brand new line. */
595 /* Grab the next line to be evaluated */
596 ebuf->floc.lineno += nlines;
597 nlines = readline (ebuf);
599 /* If there is nothing left to eval, we're done. */
600 if (nlines < 0)
601 break;
603 /* If this line is empty, skip it. */
604 line = ebuf->buffer;
605 if (line[0] == '\0')
606 continue;
608 linelen = strlen (line);
610 /* Check for a shell command line first.
611 If it is not one, we can stop treating tab specially. */
612 if (line[0] == cmd_prefix)
614 if (no_targets)
615 /* Ignore the commands in a rule with no targets. */
616 continue;
618 /* If there is no preceding rule line, don't treat this line
619 as a command, even though it begins with a recipe prefix.
620 SunOS 4 make appears to behave this way. */
622 if (filenames != 0)
624 if (ignoring)
625 /* Yep, this is a shell command, and we don't care. */
626 continue;
628 /* Append this command line to the line being accumulated.
629 Strip command prefix chars that appear after newlines. */
630 if (commands_idx == 0)
631 cmds_started = ebuf->floc.lineno;
633 if (linelen + commands_idx > commands_len)
635 commands_len = (linelen + commands_idx) * 2;
636 commands = xrealloc (commands, commands_len);
638 p = &commands[commands_idx];
639 p2 = line + 1;
640 while (--linelen)
642 ++commands_idx;
643 *(p++) = *p2;
644 if (p2[0] == '\n' && p2[1] == cmd_prefix)
646 ++p2;
647 --linelen;
649 ++p2;
651 *p = '\n';
652 ++commands_idx;
654 continue;
658 /* This line is not a shell command line. Don't worry about whitespace.
659 Get more space if we need it; we don't need to preserve the current
660 contents of the buffer. */
662 if (collapsed_length < linelen+1)
664 collapsed_length = linelen+1;
665 if (collapsed)
666 free (collapsed);
667 /* Don't need xrealloc: we don't need to preserve the content. */
668 collapsed = xmalloc (collapsed_length);
670 strcpy (collapsed, line);
671 /* Collapse continuation lines. */
672 collapse_continuations (collapsed);
673 remove_comments (collapsed);
675 /* See if this is a variable assignment. We need to do this early, to
676 allow variables with names like 'ifdef', 'export', 'private', etc. */
677 p = parse_var_assignment(collapsed, &vmod);
678 if (vmod.assign_v)
680 struct variable *v;
681 enum variable_origin origin = vmod.override_v ? o_override : o_file;
683 /* If we're ignoring then we're done now. */
684 if (ignoring)
686 if (vmod.define_v)
687 in_ignored_define = 1;
688 continue;
691 /* If it's a multi-line define / endef, manage that. */
692 if (vmod.define_v)
694 if (*p == '\0')
695 fatal (fstart, _("empty variable name"));
697 /* Let the variable name be the whole rest of the line,
698 with trailing blanks stripped (comments have already been
699 removed), so it could be a complex variable/function
700 reference that might contain blanks. */
701 p2 = p + strlen (p);
702 while (isblank ((unsigned char)p2[-1]))
703 --p2;
704 v = do_define (p, p2 - p, origin, ebuf);
706 else
708 v = try_variable_definition (fstart, p, origin, 0);
709 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 = multi_glob (parse_file_seq (&p2, '\0',
838 sizeof (struct nameseq),
840 sizeof (struct nameseq));
841 free (p);
843 /* Save the state of conditionals and start
844 the included makefile with a clean slate. */
845 save = install_conditionals (&new_conditionals);
847 /* Record the rules that are waiting so they will determine
848 the default goal before those in the included makefile. */
849 record_waiting_files ();
851 /* Read each included makefile. */
852 while (files != 0)
854 struct nameseq *next = files->next;
855 const char *name = files->name;
856 int r;
858 free (files);
859 files = next;
861 r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
862 | (noerror ? RM_DONTCARE : 0)));
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 = multi_glob (parse_file_seq (&p2, '\0',
1023 sizeof (struct nameseq),
1025 sizeof (struct nameseq));
1026 *p2 = ':';
1028 if (!filenames)
1030 /* We accept and ignore rules without targets for
1031 compatibility with SunOS 4 make. */
1032 no_targets = 1;
1033 continue;
1035 /* This should never be possible; we handled it above. */
1036 assert (*p2 != '\0');
1037 ++p2;
1039 /* Is this a one-colon or two-colon entry? */
1040 two_colon = *p2 == ':';
1041 if (two_colon)
1042 p2++;
1044 /* Test to see if it's a target-specific variable. Copy the rest
1045 of the buffer over, possibly temporarily (we'll expand it later
1046 if it's not a target-specific variable). PLEN saves the length
1047 of the unparsed section of p2, for later. */
1048 if (*lb_next != '\0')
1050 unsigned int l = p2 - variable_buffer;
1051 plen = strlen (p2);
1052 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1053 p2 = variable_buffer + l;
1056 p2 = parse_var_assignment (p2, &vmod);
1057 if (vmod.assign_v)
1059 /* If there was a semicolon found, add it back, plus anything
1060 after it. */
1061 if (semip)
1063 unsigned int l = p - variable_buffer;
1064 *(--semip) = ';';
1065 variable_buffer_output (p2 + strlen (p2),
1066 semip, strlen (semip)+1);
1067 p = variable_buffer + l;
1069 record_target_var (filenames, p2,
1070 vmod.override_v ? o_override : o_file,
1071 &vmod, fstart);
1072 filenames = 0;
1073 continue;
1076 /* This is a normal target, _not_ a target-specific variable.
1077 Unquote any = in the dependency list. */
1078 find_char_unquote (lb_next, '=', 0, 0, 0);
1080 /* We have some targets, so don't ignore the following commands. */
1081 no_targets = 0;
1083 /* Expand the dependencies, etc. */
1084 if (*lb_next != '\0')
1086 unsigned int l = p2 - variable_buffer;
1087 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1088 p2 = variable_buffer + l;
1090 /* Look for a semicolon in the expanded line. */
1091 if (cmdleft == 0)
1093 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1094 if (cmdleft != 0)
1095 *(cmdleft++) = '\0';
1099 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1100 p = strchr (p2, ':');
1101 while (p != 0 && p[-1] == '\\')
1103 register char *q = &p[-1];
1104 register int backslash = 0;
1105 while (*q-- == '\\')
1106 backslash = !backslash;
1107 if (backslash)
1108 p = strchr (p + 1, ':');
1109 else
1110 break;
1112 #ifdef _AMIGA
1113 /* Here, the situation is quite complicated. Let's have a look
1114 at a couple of targets:
1116 install: dev:make
1118 dev:make: make
1120 dev:make:: xyz
1122 The rule is that it's only a target, if there are TWO :'s
1123 OR a space around the :.
1125 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1126 || isspace ((unsigned char)p[-1])))
1127 p = 0;
1128 #endif
1129 #ifdef HAVE_DOS_PATHS
1131 int check_again;
1132 do {
1133 check_again = 0;
1134 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1135 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1136 isalpha ((unsigned char)p[-1]) &&
1137 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1138 p = strchr (p + 1, ':');
1139 check_again = 1;
1141 } while (check_again);
1143 #endif
1144 if (p != 0)
1146 struct nameseq *target;
1147 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
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 some of the logic
1209 here. */
1211 if (**default_goal_name == '\0' && set_default)
1213 const char *name;
1214 struct dep *d;
1215 struct nameseq *t = filenames;
1217 for (; t != 0; t = t->next)
1219 int reject = 0;
1220 name = t->name;
1222 /* We have nothing to do if this is an implicit rule. */
1223 if (strchr (name, '%') != 0)
1224 break;
1226 /* See if this target's name does not start with a `.',
1227 unless it contains a slash. */
1228 if (*name == '.' && strchr (name, '/') == 0
1229 #ifdef HAVE_DOS_PATHS
1230 && strchr (name, '\\') == 0
1231 #endif
1233 continue;
1236 /* If this file is a suffix, don't let it be
1237 the default goal file. */
1238 for (d = suffix_file->deps; d != 0; d = d->next)
1240 register struct dep *d2;
1241 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1243 reject = 1;
1244 break;
1246 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1248 unsigned int l = strlen (dep_name (d2));
1249 if (!strneq (name, dep_name (d2), l))
1250 continue;
1251 if (streq (name + l, dep_name (d)))
1253 reject = 1;
1254 break;
1258 if (reject)
1259 break;
1262 if (!reject)
1264 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1265 o_file, 0, NILF);
1266 break;
1271 continue;
1274 /* We get here except in the case that we just read a rule line.
1275 Record now the last rule we read, so following spurious
1276 commands are properly diagnosed. */
1277 rule_complete:
1278 record_waiting_files ();
1281 #undef word1eq
1283 if (conditionals->if_cmds)
1284 fatal (fstart, _("missing `endif'"));
1286 /* At eof, record the last rule. */
1287 record_waiting_files ();
1289 if (collapsed)
1290 free (collapsed);
1291 free (commands);
1293 return 1;
1297 /* Remove comments from LINE.
1298 This is done by copying the text at LINE onto itself. */
1300 static void
1301 remove_comments (char *line)
1303 char *comment;
1305 comment = find_char_unquote (line, '#', 0, 0, 0);
1307 if (comment != 0)
1308 /* Cut off the line at the #. */
1309 *comment = '\0';
1312 /* Execute a `define' directive.
1313 The first line has already been read, and NAME is the name of
1314 the variable to be defined. The following lines remain to be read. */
1316 static struct variable *
1317 do_define (char *name, unsigned int namelen,
1318 enum variable_origin origin, struct ebuffer *ebuf)
1320 struct floc defstart;
1321 long nlines = 0;
1322 int nlevels = 1;
1323 unsigned int length = 100;
1324 char *definition = xmalloc (length);
1325 unsigned int idx = 0;
1326 char *p;
1328 /* Expand the variable name. */
1329 char *var = alloca (namelen + 1);
1330 memcpy (var, name, namelen);
1331 var[namelen] = '\0';
1332 var = variable_expand (var);
1334 defstart = ebuf->floc;
1336 while (1)
1338 unsigned int len;
1339 char *line;
1341 nlines = readline (ebuf);
1342 ebuf->floc.lineno += nlines;
1344 /* If there is nothing left to eval, we're done. */
1345 if (nlines < 0)
1346 break;
1348 line = ebuf->buffer;
1350 collapse_continuations (line);
1352 /* If the line doesn't begin with a tab, test to see if it introduces
1353 another define, or ends one. */
1355 /* Stop if we find an 'endef' */
1356 if (line[0] != cmd_prefix)
1358 p = next_token (line);
1359 len = strlen (p);
1361 /* If this is another 'define', increment the level count. */
1362 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1363 && strneq (p, "define", 6))
1364 ++nlevels;
1366 /* If this is an 'endef', decrement the count. If it's now 0,
1367 we've found the last one. */
1368 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1369 && strneq (p, "endef", 5))
1371 p += 5;
1372 remove_comments (p);
1373 if (*next_token (p) != '\0')
1374 error (&ebuf->floc,
1375 _("Extraneous text after `endef' directive"));
1377 if (--nlevels == 0)
1379 struct variable *v;
1381 /* Define the variable. */
1382 if (idx == 0)
1383 definition[0] = '\0';
1384 else
1385 definition[idx - 1] = '\0';
1387 /* Always define these variables in the global set. */
1388 v = define_variable_global (var, strlen (var), definition,
1389 origin, 1, &defstart);
1390 free (definition);
1391 return (v);
1396 /* Otherwise 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 /* No `endef'!! */
1411 fatal (&defstart, _("missing `endef', unterminated `define'"));
1414 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1415 "ifneq", "else" and "endif".
1416 LINE is the input line, with the command as its first word.
1418 FILENAME and LINENO are the filename and line number in the
1419 current makefile. They are used for error messages.
1421 Value is -2 if the line is not a conditional at all,
1422 -1 if the line is an invalid conditional,
1423 0 if following text should be interpreted,
1424 1 if following text should be ignored. */
1426 static int
1427 conditional_line (char *line, int len, const struct floc *flocp)
1429 char *cmdname;
1430 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1431 unsigned int i;
1432 unsigned int o;
1434 /* Compare a word, both length and contents. */
1435 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1436 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1438 /* Make sure this line is a conditional. */
1439 chkword ("ifdef", c_ifdef)
1440 else chkword ("ifndef", c_ifndef)
1441 else chkword ("ifeq", c_ifeq)
1442 else chkword ("ifneq", c_ifneq)
1443 else chkword ("else", c_else)
1444 else chkword ("endif", c_endif)
1445 else
1446 return -2;
1448 /* Found one: skip past it and any whitespace after it. */
1449 line = next_token (line + len);
1451 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1453 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1454 if (cmdtype == c_endif)
1456 if (*line != '\0')
1457 EXTRANEOUS ();
1459 if (!conditionals->if_cmds)
1460 fatal (flocp, _("extraneous `%s'"), cmdname);
1462 --conditionals->if_cmds;
1464 goto DONE;
1467 /* An 'else' statement can either be simple, or it can have another
1468 conditional after it. */
1469 if (cmdtype == c_else)
1471 const char *p;
1473 if (!conditionals->if_cmds)
1474 fatal (flocp, _("extraneous `%s'"), cmdname);
1476 o = conditionals->if_cmds - 1;
1478 if (conditionals->seen_else[o])
1479 fatal (flocp, _("only one `else' per conditional"));
1481 /* Change the state of ignorance. */
1482 switch (conditionals->ignoring[o])
1484 case 0:
1485 /* We've just been interpreting. Never do it again. */
1486 conditionals->ignoring[o] = 2;
1487 break;
1488 case 1:
1489 /* We've never interpreted yet. Maybe this time! */
1490 conditionals->ignoring[o] = 0;
1491 break;
1494 /* It's a simple 'else'. */
1495 if (*line == '\0')
1497 conditionals->seen_else[o] = 1;
1498 goto DONE;
1501 /* The 'else' has extra text. That text must be another conditional
1502 and cannot be an 'else' or 'endif'. */
1504 /* Find the length of the next word. */
1505 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1507 len = p - line;
1509 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1510 if (word1eq("else") || word1eq("endif")
1511 || conditional_line (line, len, flocp) < 0)
1512 EXTRANEOUS ();
1513 else
1515 /* conditional_line() created a new level of conditional.
1516 Raise it back to this level. */
1517 if (conditionals->ignoring[o] < 2)
1518 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1519 --conditionals->if_cmds;
1522 goto DONE;
1525 if (conditionals->allocated == 0)
1527 conditionals->allocated = 5;
1528 conditionals->ignoring = xmalloc (conditionals->allocated);
1529 conditionals->seen_else = xmalloc (conditionals->allocated);
1532 o = conditionals->if_cmds++;
1533 if (conditionals->if_cmds > conditionals->allocated)
1535 conditionals->allocated += 5;
1536 conditionals->ignoring = xrealloc (conditionals->ignoring,
1537 conditionals->allocated);
1538 conditionals->seen_else = xrealloc (conditionals->seen_else,
1539 conditionals->allocated);
1542 /* Record that we have seen an `if...' but no `else' so far. */
1543 conditionals->seen_else[o] = 0;
1545 /* Search through the stack to see if we're already ignoring. */
1546 for (i = 0; i < o; ++i)
1547 if (conditionals->ignoring[i])
1549 /* We are already ignoring, so just push a level to match the next
1550 "else" or "endif", and keep ignoring. We don't want to expand
1551 variables in the condition. */
1552 conditionals->ignoring[o] = 1;
1553 return 1;
1556 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1558 char *var;
1559 struct variable *v;
1560 char *p;
1562 /* Expand the thing we're looking up, so we can use indirect and
1563 constructed variable names. */
1564 var = allocated_variable_expand (line);
1566 /* Make sure there's only one variable name to test. */
1567 p = end_of_token (var);
1568 i = p - var;
1569 p = next_token (p);
1570 if (*p != '\0')
1571 return -1;
1573 var[i] = '\0';
1574 v = lookup_variable (var, i);
1576 conditionals->ignoring[o] =
1577 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1579 free (var);
1581 else
1583 /* "ifeq" or "ifneq". */
1584 char *s1, *s2;
1585 unsigned int l;
1586 char termin = *line == '(' ? ',' : *line;
1588 if (termin != ',' && termin != '"' && termin != '\'')
1589 return -1;
1591 s1 = ++line;
1592 /* Find the end of the first string. */
1593 if (termin == ',')
1595 int count = 0;
1596 for (; *line != '\0'; ++line)
1597 if (*line == '(')
1598 ++count;
1599 else if (*line == ')')
1600 --count;
1601 else if (*line == ',' && count <= 0)
1602 break;
1604 else
1605 while (*line != '\0' && *line != termin)
1606 ++line;
1608 if (*line == '\0')
1609 return -1;
1611 if (termin == ',')
1613 /* Strip blanks after the first string. */
1614 char *p = line++;
1615 while (isblank ((unsigned char)p[-1]))
1616 --p;
1617 *p = '\0';
1619 else
1620 *line++ = '\0';
1622 s2 = variable_expand (s1);
1623 /* We must allocate a new copy of the expanded string because
1624 variable_expand re-uses the same buffer. */
1625 l = strlen (s2);
1626 s1 = alloca (l + 1);
1627 memcpy (s1, s2, l + 1);
1629 if (termin != ',')
1630 /* Find the start of the second string. */
1631 line = next_token (line);
1633 termin = termin == ',' ? ')' : *line;
1634 if (termin != ')' && termin != '"' && termin != '\'')
1635 return -1;
1637 /* Find the end of the second string. */
1638 if (termin == ')')
1640 int count = 0;
1641 s2 = next_token (line);
1642 for (line = s2; *line != '\0'; ++line)
1644 if (*line == '(')
1645 ++count;
1646 else if (*line == ')')
1648 if (count <= 0)
1649 break;
1650 else
1651 --count;
1655 else
1657 ++line;
1658 s2 = line;
1659 while (*line != '\0' && *line != termin)
1660 ++line;
1663 if (*line == '\0')
1664 return -1;
1666 *line = '\0';
1667 line = next_token (++line);
1668 if (*line != '\0')
1669 EXTRANEOUS ();
1671 s2 = variable_expand (s2);
1672 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1675 DONE:
1676 /* Search through the stack to see if we're ignoring. */
1677 for (i = 0; i < conditionals->if_cmds; ++i)
1678 if (conditionals->ignoring[i])
1679 return 1;
1680 return 0;
1683 /* Remove duplicate dependencies in CHAIN. */
1685 static unsigned long
1686 dep_hash_1 (const void *key)
1688 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1691 static unsigned long
1692 dep_hash_2 (const void *key)
1694 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1697 static int
1698 dep_hash_cmp (const void *x, const void *y)
1700 struct dep *dx = (struct dep *) x;
1701 struct dep *dy = (struct dep *) y;
1702 int cmp = strcmp (dep_name (dx), dep_name (dy));
1704 /* If the names are the same but ignore_mtimes are not equal, one of these
1705 is an order-only prerequisite and one isn't. That means that we should
1706 remove the one that isn't and keep the one that is. */
1708 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1709 dx->ignore_mtime = dy->ignore_mtime = 0;
1711 return cmp;
1715 void
1716 uniquize_deps (struct dep *chain)
1718 struct hash_table deps;
1719 register struct dep **depp;
1721 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1723 /* Make sure that no dependencies are repeated. This does not
1724 really matter for the purpose of updating targets, but it
1725 might make some names be listed twice for $^ and $?. */
1727 depp = &chain;
1728 while (*depp)
1730 struct dep *dep = *depp;
1731 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1732 if (HASH_VACANT (*dep_slot))
1734 hash_insert_at (&deps, dep, dep_slot);
1735 depp = &dep->next;
1737 else
1739 /* Don't bother freeing duplicates.
1740 It's dangerous and little benefit accrues. */
1741 *depp = dep->next;
1745 hash_free (&deps, 0);
1748 /* Record target-specific variable values for files FILENAMES.
1749 TWO_COLON is nonzero if a double colon was used.
1751 The links of FILENAMES are freed, and so are any names in it
1752 that are not incorporated into other data structures.
1754 If the target is a pattern, add the variable to the pattern-specific
1755 variable value list. */
1757 static void
1758 record_target_var (struct nameseq *filenames, char *defn,
1759 enum variable_origin origin, struct vmodifiers *vmod,
1760 const struct floc *flocp)
1762 struct nameseq *nextf;
1763 struct variable_set_list *global;
1765 global = current_variable_set_list;
1767 /* If the variable is an append version, store that but treat it as a
1768 normal recursive variable. */
1770 for (; filenames != 0; filenames = nextf)
1772 struct variable *v;
1773 const char *name = filenames->name;
1774 const char *fname;
1775 const char *percent;
1776 struct pattern_var *p;
1778 nextf = filenames->next;
1779 free (filenames);
1781 /* If it's a pattern target, then add it to the pattern-specific
1782 variable list. */
1783 percent = find_percent_cached (&name);
1784 if (percent)
1786 /* Get a reference for this pattern-specific variable struct. */
1787 p = create_pattern_var (name, percent);
1788 p->variable.fileinfo = *flocp;
1789 /* I don't think this can fail since we already determined it was a
1790 variable definition. */
1791 v = assign_variable_definition (&p->variable, defn);
1792 assert (v != 0);
1794 if (v->flavor == f_simple)
1795 v->value = allocated_variable_expand (v->value);
1796 else
1797 v->value = xstrdup (v->value);
1799 fname = p->target;
1801 else
1803 struct file *f;
1805 /* Get a file reference for this file, and initialize it.
1806 We don't want to just call enter_file() because that allocates a
1807 new entry if the file is a double-colon, which we don't want in
1808 this situation. */
1809 f = lookup_file (name);
1810 if (!f)
1811 f = enter_file (strcache_add (name));
1812 else if (f->double_colon)
1813 f = f->double_colon;
1815 initialize_file_variables (f, 1);
1816 fname = f->name;
1818 current_variable_set_list = f->variables;
1819 v = try_variable_definition (flocp, defn, origin, 1);
1820 if (!v)
1821 fatal (flocp, _("Malformed target-specific variable definition"));
1822 current_variable_set_list = global;
1825 /* Set up the variable to be *-specific. */
1826 v->origin = origin;
1827 v->per_target = 1;
1828 v->private_var = vmod->private_v;
1829 v->export = vmod->export_v ? v_export : v_default;
1831 /* If it's not an override, check to see if there was a command-line
1832 setting. If so, reset the value. */
1833 if (origin != o_override)
1835 struct variable *gv;
1836 int len = strlen(v->name);
1838 gv = lookup_variable (v->name, len);
1839 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1841 if (v->value != 0)
1842 free (v->value);
1843 v->value = xstrdup (gv->value);
1844 v->origin = gv->origin;
1845 v->recursive = gv->recursive;
1846 v->append = 0;
1852 /* Record a description line for files FILENAMES,
1853 with dependencies DEPS, commands to execute described
1854 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1855 TWO_COLON is nonzero if a double colon was used.
1856 If not nil, PATTERN is the `%' pattern to make this
1857 a static pattern rule, and PATTERN_PERCENT is a pointer
1858 to the `%' within it.
1860 The links of FILENAMES are freed, and so are any names in it
1861 that are not incorporated into other data structures. */
1863 static void
1864 record_files (struct nameseq *filenames, const char *pattern,
1865 const char *pattern_percent, struct dep *deps,
1866 unsigned int cmds_started, char *commands,
1867 unsigned int commands_idx, int two_colon,
1868 const struct floc *flocp)
1870 struct nameseq *nextf;
1871 int implicit = 0;
1872 unsigned int max_targets = 0, target_idx = 0;
1873 const char **targets = 0, **target_percents = 0;
1874 struct commands *cmds;
1876 /* If we've already snapped deps, that means we're in an eval being
1877 resolved after the makefiles have been read in. We can't add more rules
1878 at this time, since they won't get snapped and we'll get core dumps.
1879 See Savannah bug # 12124. */
1880 if (snapped_deps)
1881 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1883 if (commands_idx > 0)
1885 cmds = xmalloc (sizeof (struct commands));
1886 cmds->fileinfo.filenm = flocp->filenm;
1887 cmds->fileinfo.lineno = cmds_started;
1888 cmds->commands = xstrndup (commands, commands_idx);
1889 cmds->command_lines = 0;
1891 else
1892 cmds = 0;
1894 for (; filenames != 0; filenames = nextf)
1896 const char *name = filenames->name;
1897 struct file *f;
1898 struct dep *this = 0;
1899 const char *implicit_percent;
1901 nextf = filenames->next;
1902 free (filenames);
1904 /* Check for special targets. Do it here instead of, say, snap_deps()
1905 so that we can immediately use the value. */
1907 if (streq (name, ".POSIX"))
1908 posix_pedantic = 1;
1909 else if (streq (name, ".SECONDEXPANSION"))
1910 second_expansion = 1;
1912 implicit_percent = find_percent_cached (&name);
1913 implicit |= implicit_percent != 0;
1915 if (implicit)
1917 if (pattern != 0)
1918 fatal (flocp, _("mixed implicit and static pattern rules"));
1920 if (implicit_percent == 0)
1921 fatal (flocp, _("mixed implicit and normal rules"));
1923 if (targets == 0)
1925 max_targets = 5;
1926 targets = xmalloc (5 * sizeof (char *));
1927 target_percents = xmalloc (5 * sizeof (char *));
1928 target_idx = 0;
1930 else if (target_idx == max_targets - 1)
1932 max_targets += 5;
1933 targets = xrealloc (targets, max_targets * sizeof (char *));
1934 target_percents = xrealloc (target_percents,
1935 max_targets * sizeof (char *));
1937 targets[target_idx] = name;
1938 target_percents[target_idx] = implicit_percent;
1939 ++target_idx;
1940 continue;
1943 /* If this is a static pattern rule:
1944 `targets: target%pattern: dep%pattern; cmds',
1945 make sure the pattern matches this target name. */
1946 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1947 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1948 else if (deps)
1950 /* If there are multiple filenames, copy the chain DEPS for all but
1951 the last one. It is not safe for the same deps to go in more
1952 than one place in the database. */
1953 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1954 this->need_2nd_expansion = (second_expansion
1955 && strchr (this->name, '$'));
1958 if (!two_colon)
1960 /* Single-colon. Combine these dependencies
1961 with others in file's existing record, if any. */
1962 f = enter_file (strcache_add (name));
1964 if (f->double_colon)
1965 fatal (flocp,
1966 _("target file `%s' has both : and :: entries"), f->name);
1968 /* If CMDS == F->CMDS, this target was listed in this rule
1969 more than once. Just give a warning since this is harmless. */
1970 if (cmds != 0 && cmds == f->cmds)
1971 error (flocp,
1972 _("target `%s' given more than once in the same rule."),
1973 f->name);
1975 /* Check for two single-colon entries both with commands.
1976 Check is_target so that we don't lose on files such as .c.o
1977 whose commands were preinitialized. */
1978 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1980 error (&cmds->fileinfo,
1981 _("warning: overriding recipe for target `%s'"),
1982 f->name);
1983 error (&f->cmds->fileinfo,
1984 _("warning: ignoring old recipe for target `%s'"),
1985 f->name);
1988 f->is_target = 1;
1990 /* Defining .DEFAULT with no deps or cmds clears it. */
1991 if (f == default_file && this == 0 && cmds == 0)
1992 f->cmds = 0;
1993 if (cmds != 0)
1994 f->cmds = cmds;
1996 /* Defining .SUFFIXES with no dependencies clears out the list of
1997 suffixes. */
1998 if (f == suffix_file && this == 0)
2000 free_dep_chain (f->deps);
2001 f->deps = 0;
2003 else if (this != 0)
2005 /* Add the file's old deps and the new ones in THIS together. */
2007 if (f->deps != 0)
2009 struct dep **d_ptr = &f->deps;
2011 while ((*d_ptr)->next != 0)
2012 d_ptr = &(*d_ptr)->next;
2014 if (cmds != 0)
2015 /* This is the rule with commands, so put its deps
2016 last. The rationale behind this is that $< expands to
2017 the first dep in the chain, and commands use $<
2018 expecting to get the dep that rule specifies. However
2019 the second expansion algorithm reverses the order thus
2020 we need to make it last here. */
2021 (*d_ptr)->next = this;
2022 else
2024 /* This is the rule without commands. Put its
2025 dependencies at the end but before dependencies from
2026 the rule with commands (if any). This way everything
2027 appears in makefile order. */
2029 if (f->cmds != 0)
2031 this->next = *d_ptr;
2032 *d_ptr = this;
2034 else
2035 (*d_ptr)->next = this;
2038 else
2039 f->deps = this;
2041 /* This is a hack. I need a way to communicate to snap_deps()
2042 that the last dependency line in this file came with commands
2043 (so that logic in snap_deps() can put it in front and all
2044 this $< -logic works). I cannot simply rely on file->cmds
2045 being not 0 because of the cases like the following:
2047 foo: bar
2048 foo:
2051 I am going to temporarily "borrow" UPDATING member in
2052 `struct file' for this. */
2054 if (cmds != 0)
2055 f->updating = 1;
2058 else
2060 /* Double-colon. Make a new record even if there already is one. */
2061 f = lookup_file (name);
2063 /* Check for both : and :: rules. Check is_target so
2064 we don't lose on default suffix rules or makefiles. */
2065 if (f != 0 && f->is_target && !f->double_colon)
2066 fatal (flocp,
2067 _("target file `%s' has both : and :: entries"), f->name);
2068 f = enter_file (strcache_add (name));
2069 /* If there was an existing entry and it was a double-colon entry,
2070 enter_file will have returned a new one, making it the prev
2071 pointer of the old one, and setting its double_colon pointer to
2072 the first one. */
2073 if (f->double_colon == 0)
2074 /* This is the first entry for this name, so we must set its
2075 double_colon pointer to itself. */
2076 f->double_colon = f;
2077 f->is_target = 1;
2078 f->deps = this;
2079 f->cmds = cmds;
2082 /* If this is a static pattern rule, set the stem to the part of its
2083 name that matched the `%' in the pattern, so you can use $* in the
2084 commands. */
2085 if (pattern)
2087 static const char *percent = "%";
2088 char *buffer = variable_expand ("");
2089 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2090 pattern_percent+1, percent+1);
2091 f->stem = strcache_add_len (buffer, o - buffer);
2092 if (this)
2094 this->staticpattern = 1;
2095 this->stem = f->stem;
2099 name = f->name;
2101 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2102 if (streq (*default_goal_name, name)
2103 && (default_goal_file == 0
2104 || ! streq (default_goal_file->name, name)))
2105 default_goal_file = f;
2108 if (implicit)
2110 if (deps)
2111 deps->need_2nd_expansion = second_expansion;
2112 create_pattern_rule (targets, target_percents, target_idx,
2113 two_colon, deps, cmds, 1);
2117 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2118 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2119 Quoting backslashes are removed from STRING by compacting it into
2120 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2121 one, or nil if there are none. STOPCHARs inside variable references are
2122 ignored if IGNOREVARS is true.
2124 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2126 static char *
2127 find_char_unquote (char *string, int stop1, int stop2, int blank,
2128 int ignorevars)
2130 unsigned int string_len = 0;
2131 char *p = string;
2133 if (ignorevars)
2134 ignorevars = '$';
2136 while (1)
2138 if (stop2 && blank)
2139 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2140 && ! isblank ((unsigned char) *p))
2141 ++p;
2142 else if (stop2)
2143 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2144 ++p;
2145 else if (blank)
2146 while (*p != '\0' && *p != ignorevars && *p != stop1
2147 && ! isblank ((unsigned char) *p))
2148 ++p;
2149 else
2150 while (*p != '\0' && *p != ignorevars && *p != stop1)
2151 ++p;
2153 if (*p == '\0')
2154 break;
2156 /* If we stopped due to a variable reference, skip over its contents. */
2157 if (*p == ignorevars)
2159 char openparen = p[1];
2161 p += 2;
2163 /* Skip the contents of a non-quoted, multi-char variable ref. */
2164 if (openparen == '(' || openparen == '{')
2166 unsigned int pcount = 1;
2167 char closeparen = (openparen == '(' ? ')' : '}');
2169 while (*p)
2171 if (*p == openparen)
2172 ++pcount;
2173 else if (*p == closeparen)
2174 if (--pcount == 0)
2176 ++p;
2177 break;
2179 ++p;
2183 /* Skipped the variable reference: look for STOPCHARS again. */
2184 continue;
2187 if (p > string && p[-1] == '\\')
2189 /* Search for more backslashes. */
2190 int i = -2;
2191 while (&p[i] >= string && p[i] == '\\')
2192 --i;
2193 ++i;
2194 /* Only compute the length if really needed. */
2195 if (string_len == 0)
2196 string_len = strlen (string);
2197 /* The number of backslashes is now -I.
2198 Copy P over itself to swallow half of them. */
2199 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2200 p += i/2;
2201 if (i % 2 == 0)
2202 /* All the backslashes quoted each other; the STOPCHAR was
2203 unquoted. */
2204 return p;
2206 /* The STOPCHAR was quoted by a backslash. Look for another. */
2208 else
2209 /* No backslash in sight. */
2210 return p;
2213 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2214 return 0;
2217 /* Search PATTERN for an unquoted % and handle quoting. */
2219 char *
2220 find_percent (char *pattern)
2222 return find_char_unquote (pattern, '%', 0, 0, 0);
2225 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2226 the % or NULL if no % was found.
2227 This version is used with strings in the string cache: if there's a need to
2228 modify the string a new version will be added to the string cache and
2229 *STRING will be set to that. */
2231 const char *
2232 find_percent_cached (const char **string)
2234 const char *p = *string;
2235 char *new = 0;
2236 int slen;
2238 /* If the first char is a % return now. This lets us avoid extra tests
2239 inside the loop. */
2240 if (*p == '%')
2241 return p;
2243 while (1)
2245 while (*p != '\0' && *p != '%')
2246 ++p;
2248 if (*p == '\0')
2249 break;
2251 /* See if this % is escaped with a backslash; if not we're done. */
2252 if (p[-1] != '\\')
2253 break;
2256 /* Search for more backslashes. */
2257 char *pv;
2258 int i = -2;
2260 while (&p[i] >= *string && p[i] == '\\')
2261 --i;
2262 ++i;
2264 /* At this point we know we'll need to allocate a new string.
2265 Make a copy if we haven't yet done so. */
2266 if (! new)
2268 slen = strlen (*string);
2269 new = alloca (slen + 1);
2270 memcpy (new, *string, slen + 1);
2271 p = new + (p - *string);
2272 *string = new;
2275 /* At this point *string, p, and new all point into the same string.
2276 Get a non-const version of p so we can modify new. */
2277 pv = new + (p - *string);
2279 /* The number of backslashes is now -I.
2280 Copy P over itself to swallow half of them. */
2281 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2282 p += i/2;
2284 /* If the backslashes quoted each other; the % was unquoted. */
2285 if (i % 2 == 0)
2286 break;
2290 /* If we had to change STRING, add it to the strcache. */
2291 if (new)
2293 *string = strcache_add (*string);
2294 p = *string + (p - new);
2297 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2298 return (*p == '\0') ? NULL : p;
2301 /* Parse a string into a sequence of filenames represented as a
2302 chain of struct nameseq's in reverse order and return that chain.
2304 The string is passed as STRINGP, the address of a string pointer.
2305 The string pointer is updated to point at the first character
2306 not parsed, which either is a null char or equals STOPCHAR.
2308 SIZE is how big to construct chain elements.
2309 This is useful if we want them actually to be other structures
2310 that have room for additional info.
2312 If STRIP is nonzero, strip `./'s off the beginning. */
2314 struct nameseq *
2315 parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2317 struct nameseq *new = 0;
2318 struct nameseq *new1, *lastnew1;
2319 char *p = *stringp;
2321 #ifdef VMS
2322 # define VMS_COMMA ','
2323 #else
2324 # define VMS_COMMA 0
2325 #endif
2327 while (1)
2329 const char *name;
2330 char *q;
2332 /* Skip whitespace; see if any more names are left. */
2333 p = next_token (p);
2334 if (*p == '\0')
2335 break;
2336 if (*p == stopchar)
2337 break;
2339 /* There are, so find the end of the next name. */
2340 q = p;
2341 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2342 #ifdef VMS
2343 /* convert comma separated list to space separated */
2344 if (p && *p == ',')
2345 *p =' ';
2346 #endif
2347 #ifdef _AMIGA
2348 if (stopchar == ':' && p && *p == ':'
2349 && !(isspace ((unsigned char)p[1]) || !p[1]
2350 || isspace ((unsigned char)p[-1])))
2351 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2352 #endif
2353 #ifdef HAVE_DOS_PATHS
2354 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2355 first colon which isn't followed by a slash or a backslash.
2356 Note that tokens separated by spaces should be treated as separate
2357 tokens since make doesn't allow path names with spaces */
2358 if (stopchar == ':')
2359 while (p != 0 && !isspace ((unsigned char)*p) &&
2360 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2361 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2362 #endif
2363 if (p == 0)
2364 p = q + strlen (q);
2366 if (strip)
2367 #ifdef VMS
2368 /* Skip leading `[]'s. */
2369 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2370 #else
2371 /* Skip leading `./'s. */
2372 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2373 #endif
2375 q += 2; /* Skip "./". */
2376 while (q < p && *q == '/')
2377 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2378 ++q;
2381 /* Extract the filename just found, and skip it. */
2383 if (q == p)
2384 /* ".///" was stripped to "". */
2385 #if defined(VMS)
2386 continue;
2387 #elif defined(_AMIGA)
2388 name = "";
2389 #else
2390 name = "./";
2391 #endif
2392 else
2393 #ifdef VMS
2394 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2395 * to remove this '\' before we can use the filename.
2396 * xstrdup called because q may be read-only string constant.
2399 char *qbase = xstrdup (q);
2400 char *pbase = qbase + (p-q);
2401 char *q1 = qbase;
2402 char *q2 = q1;
2403 char *p1 = pbase;
2405 while (q1 != pbase)
2407 if (*q1 == '\\' && *(q1+1) == ':')
2409 q1++;
2410 p1--;
2412 *q2++ = *q1++;
2414 name = strcache_add_len (qbase, p1 - qbase);
2415 free (qbase);
2417 #else
2418 name = strcache_add_len (q, p - q);
2419 #endif
2421 /* Add it to the front of the chain. */
2422 new1 = xmalloc (size);
2423 memset (new1, '\0', size);
2424 new1->name = name;
2425 new1->next = new;
2426 new = new1;
2429 #ifndef NO_ARCHIVES
2431 /* Look for multi-word archive references.
2432 They are indicated by a elt ending with an unmatched `)' and
2433 an elt further down the chain (i.e., previous in the file list)
2434 with an unmatched `(' (e.g., "lib(mem"). */
2436 new1 = new;
2437 lastnew1 = 0;
2438 while (new1 != 0)
2439 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2440 && new1->name[strlen (new1->name) - 1] == ')'
2441 && strchr (new1->name, '(') == 0)
2443 /* NEW1 ends with a `)' but does not contain a `('.
2444 Look back for an elt with an opening `(' but no closing `)'. */
2446 struct nameseq *n = new1->next, *lastn = new1;
2447 char *paren = 0;
2448 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2450 lastn = n;
2451 n = n->next;
2453 if (n != 0
2454 /* Ignore something starting with `(', as that cannot actually
2455 be an archive-member reference (and treating it as such
2456 results in an empty file name, which causes much lossage). */
2457 && n->name[0] != '(')
2459 /* N is the first element in the archive group.
2460 Its name looks like "lib(mem" (with no closing `)'). */
2462 char *libname;
2464 /* Copy "lib(" into LIBNAME. */
2465 ++paren;
2466 libname = alloca (paren - n->name + 1);
2467 memcpy (libname, n->name, paren - n->name);
2468 libname[paren - n->name] = '\0';
2470 if (*paren == '\0')
2472 /* N was just "lib(", part of something like "lib( a b)".
2473 Edit it out of the chain and free its storage. */
2474 lastn->next = n->next;
2475 free (n);
2476 /* LASTN->next is the new stopping elt for the loop below. */
2477 n = lastn->next;
2479 else
2481 /* Replace N's name with the full archive reference. */
2482 n->name = strcache_add (concat (libname, paren, ")"));
2485 if (new1->name[1] == '\0')
2487 /* NEW1 is just ")", part of something like "lib(a b )".
2488 Omit it from the chain and free its storage. */
2489 if (lastnew1 == 0)
2490 new = new1->next;
2491 else
2492 lastnew1->next = new1->next;
2493 lastn = new1;
2494 new1 = new1->next;
2495 free (lastn);
2497 else
2499 /* Replace also NEW1->name, which already has closing `)'. */
2500 new1->name = strcache_add (concat (libname, new1->name, ""));
2501 new1 = new1->next;
2504 /* Trace back from NEW1 (the end of the list) until N
2505 (the beginning of the list), rewriting each name
2506 with the full archive reference. */
2508 while (new1 != n)
2510 new1->name = strcache_add (concat (libname, new1->name, ")"));
2511 lastnew1 = new1;
2512 new1 = new1->next;
2515 else
2517 /* No frobnication happening. Just step down the list. */
2518 lastnew1 = new1;
2519 new1 = new1->next;
2522 else
2524 lastnew1 = new1;
2525 new1 = new1->next;
2528 #endif
2530 *stringp = p;
2531 return new;
2534 /* Find the next line of text in an eval buffer, combining continuation lines
2535 into one line.
2536 Return the number of actual lines read (> 1 if continuation lines).
2537 Returns -1 if there's nothing left in the buffer.
2539 After this function, ebuf->buffer points to the first character of the
2540 line we just found.
2543 /* Read a line of text from a STRING.
2544 Since we aren't really reading from a file, don't bother with linenumbers.
2547 static unsigned long
2548 readstring (struct ebuffer *ebuf)
2550 char *eol;
2552 /* If there is nothing left in this buffer, return 0. */
2553 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2554 return -1;
2556 /* Set up a new starting point for the buffer, and find the end of the
2557 next logical line (taking into account backslash/newline pairs). */
2559 eol = ebuf->buffer = ebuf->bufnext;
2561 while (1)
2563 int backslash = 0;
2564 char *bol = eol;
2565 char *p;
2567 /* Find the next newline. At EOS, stop. */
2568 eol = p = strchr (eol , '\n');
2569 if (!eol)
2571 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2572 return 0;
2575 /* Found a newline; if it's escaped continue; else we're done. */
2576 while (p > bol && *(--p) == '\\')
2577 backslash = !backslash;
2578 if (!backslash)
2579 break;
2580 ++eol;
2583 /* Overwrite the newline char. */
2584 *eol = '\0';
2585 ebuf->bufnext = eol+1;
2587 return 0;
2590 static long
2591 readline (struct ebuffer *ebuf)
2593 char *p;
2594 char *end;
2595 char *start;
2596 long nlines = 0;
2598 /* The behaviors between string and stream buffers are different enough to
2599 warrant different functions. Do the Right Thing. */
2601 if (!ebuf->fp)
2602 return readstring (ebuf);
2604 /* When reading from a file, we always start over at the beginning of the
2605 buffer for each new line. */
2607 p = start = ebuf->bufstart;
2608 end = p + ebuf->size;
2609 *p = '\0';
2611 while (fgets (p, end - p, ebuf->fp) != 0)
2613 char *p2;
2614 unsigned long len;
2615 int backslash;
2617 len = strlen (p);
2618 if (len == 0)
2620 /* This only happens when the first thing on the line is a '\0'.
2621 It is a pretty hopeless case, but (wonder of wonders) Athena
2622 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2623 There is nothing really to be done; we synthesize a newline so
2624 the following line doesn't appear to be part of this line. */
2625 error (&ebuf->floc,
2626 _("warning: NUL character seen; rest of line ignored"));
2627 p[0] = '\n';
2628 len = 1;
2631 /* Jump past the text we just read. */
2632 p += len;
2634 /* If the last char isn't a newline, the whole line didn't fit into the
2635 buffer. Get some more buffer and try again. */
2636 if (p[-1] != '\n')
2637 goto more_buffer;
2639 /* We got a newline, so add one to the count of lines. */
2640 ++nlines;
2642 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2643 /* Check to see if the line was really ended with CRLF; if so ignore
2644 the CR. */
2645 if ((p - start) > 1 && p[-2] == '\r')
2647 --p;
2648 p[-1] = '\n';
2650 #endif
2652 backslash = 0;
2653 for (p2 = p - 2; p2 >= start; --p2)
2655 if (*p2 != '\\')
2656 break;
2657 backslash = !backslash;
2660 if (!backslash)
2662 p[-1] = '\0';
2663 break;
2666 /* It was a backslash/newline combo. If we have more space, read
2667 another line. */
2668 if (end - p >= 80)
2669 continue;
2671 /* We need more space at the end of our buffer, so realloc it.
2672 Make sure to preserve the current offset of p. */
2673 more_buffer:
2675 unsigned long off = p - start;
2676 ebuf->size *= 2;
2677 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2678 p = start + off;
2679 end = start + ebuf->size;
2680 *p = '\0';
2684 if (ferror (ebuf->fp))
2685 pfatal_with_name (ebuf->floc.filenm);
2687 /* If we found some lines, return how many.
2688 If we didn't, but we did find _something_, that indicates we read the last
2689 line of a file with no final newline; return 1.
2690 If we read nothing, we're at EOF; return -1. */
2692 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2695 /* Parse the next "makefile word" from the input buffer, and return info
2696 about it.
2698 A "makefile word" is one of:
2700 w_bogus Should never happen
2701 w_eol End of input
2702 w_static A static word; cannot be expanded
2703 w_variable A word containing one or more variables/functions
2704 w_colon A colon
2705 w_dcolon A double-colon
2706 w_semicolon A semicolon
2707 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2709 Note that this function is only used when reading certain parts of the
2710 makefile. Don't use it where special rules hold sway (RHS of a variable,
2711 in a command list, etc.) */
2713 static enum make_word_type
2714 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2716 enum make_word_type wtype = w_bogus;
2717 char *p = buffer, *beg;
2718 char c;
2720 /* Skip any leading whitespace. */
2721 while (isblank ((unsigned char)*p))
2722 ++p;
2724 beg = p;
2725 c = *(p++);
2726 switch (c)
2728 case '\0':
2729 wtype = w_eol;
2730 break;
2732 case ';':
2733 wtype = w_semicolon;
2734 break;
2736 case '=':
2737 wtype = w_varassign;
2738 break;
2740 case ':':
2741 wtype = w_colon;
2742 switch (*p)
2744 case ':':
2745 ++p;
2746 wtype = w_dcolon;
2747 break;
2749 case '=':
2750 ++p;
2751 wtype = w_varassign;
2752 break;
2754 break;
2756 case '+':
2757 case '?':
2758 if (*p == '=')
2760 ++p;
2761 wtype = w_varassign;
2762 break;
2765 default:
2766 if (delim && strchr (delim, c))
2767 wtype = w_static;
2768 break;
2771 /* Did we find something? If so, return now. */
2772 if (wtype != w_bogus)
2773 goto done;
2775 /* This is some non-operator word. A word consists of the longest
2776 string of characters that doesn't contain whitespace, one of [:=#],
2777 or [?+]=, or one of the chars in the DELIM string. */
2779 /* We start out assuming a static word; if we see a variable we'll
2780 adjust our assumptions then. */
2781 wtype = w_static;
2783 /* We already found the first value of "c", above. */
2784 while (1)
2786 char closeparen;
2787 int count;
2789 switch (c)
2791 case '\0':
2792 case ' ':
2793 case '\t':
2794 case '=':
2795 goto done_word;
2797 case ':':
2798 #ifdef HAVE_DOS_PATHS
2799 /* A word CAN include a colon in its drive spec. The drive
2800 spec is allowed either at the beginning of a word, or as part
2801 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2802 if (!(p - beg >= 2
2803 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2804 && (p - beg == 2 || p[-3] == '(')))
2805 #endif
2806 goto done_word;
2808 case '$':
2809 c = *(p++);
2810 if (c == '$')
2811 break;
2813 /* This is a variable reference, so note that it's expandable.
2814 Then read it to the matching close paren. */
2815 wtype = w_variable;
2817 if (c == '(')
2818 closeparen = ')';
2819 else if (c == '{')
2820 closeparen = '}';
2821 else
2822 /* This is a single-letter variable reference. */
2823 break;
2825 for (count=0; *p != '\0'; ++p)
2827 if (*p == c)
2828 ++count;
2829 else if (*p == closeparen && --count < 0)
2831 ++p;
2832 break;
2835 break;
2837 case '?':
2838 case '+':
2839 if (*p == '=')
2840 goto done_word;
2841 break;
2843 case '\\':
2844 switch (*p)
2846 case ':':
2847 case ';':
2848 case '=':
2849 case '\\':
2850 ++p;
2851 break;
2853 break;
2855 default:
2856 if (delim && strchr (delim, c))
2857 goto done_word;
2858 break;
2861 c = *(p++);
2863 done_word:
2864 --p;
2866 done:
2867 if (startp)
2868 *startp = beg;
2869 if (length)
2870 *length = p - beg;
2871 return wtype;
2874 /* Construct the list of include directories
2875 from the arguments and the default list. */
2877 void
2878 construct_include_path (const char **arg_dirs)
2880 #ifdef VAXC /* just don't ask ... */
2881 stat_t stbuf;
2882 #else
2883 struct stat stbuf;
2884 #endif
2885 const char **dirs;
2886 const char **cpp;
2887 unsigned int idx;
2889 /* Compute the number of pointers we need in the table. */
2890 idx = sizeof (default_include_directories) / sizeof (const char *);
2891 if (arg_dirs)
2892 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2893 ++idx;
2895 #ifdef __MSDOS__
2896 /* Add one for $DJDIR. */
2897 ++idx;
2898 #endif
2900 dirs = xmalloc (idx * sizeof (const char *));
2902 idx = 0;
2903 max_incl_len = 0;
2905 /* First consider any dirs specified with -I switches.
2906 Ignore any that don't exist. Remember the maximum string length. */
2908 if (arg_dirs)
2909 while (*arg_dirs != 0)
2911 const char *dir = *(arg_dirs++);
2912 char *expanded = 0;
2913 int e;
2915 if (dir[0] == '~')
2917 expanded = tilde_expand (dir);
2918 if (expanded != 0)
2919 dir = expanded;
2922 EINTRLOOP (e, stat (dir, &stbuf));
2923 if (e == 0 && S_ISDIR (stbuf.st_mode))
2925 unsigned int len = strlen (dir);
2926 /* If dir name is written with trailing slashes, discard them. */
2927 while (len > 1 && dir[len - 1] == '/')
2928 --len;
2929 if (len > max_incl_len)
2930 max_incl_len = len;
2931 dirs[idx++] = strcache_add_len (dir, len);
2934 if (expanded)
2935 free (expanded);
2938 /* Now add the standard default dirs at the end. */
2940 #ifdef __MSDOS__
2942 /* The environment variable $DJDIR holds the root of the DJGPP directory
2943 tree; add ${DJDIR}/include. */
2944 struct variable *djdir = lookup_variable ("DJDIR", 5);
2946 if (djdir)
2948 unsigned int len = strlen (djdir->value) + 8;
2949 char *defdir = alloca (len + 1);
2951 strcat (strcpy (defdir, djdir->value), "/include");
2952 dirs[idx++] = strcache_add (defdir);
2954 if (len > max_incl_len)
2955 max_incl_len = len;
2958 #endif
2960 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2962 int e;
2964 EINTRLOOP (e, stat (*cpp, &stbuf));
2965 if (e == 0 && S_ISDIR (stbuf.st_mode))
2967 unsigned int len = strlen (*cpp);
2968 /* If dir name is written with trailing slashes, discard them. */
2969 while (len > 1 && (*cpp)[len - 1] == '/')
2970 --len;
2971 if (len > max_incl_len)
2972 max_incl_len = len;
2973 dirs[idx++] = strcache_add_len (*cpp, len);
2977 dirs[idx] = 0;
2979 /* Now add each dir to the .INCLUDE_DIRS variable. */
2981 for (cpp = dirs; *cpp != 0; ++cpp)
2982 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2983 o_default, f_append, 0);
2985 include_directories = dirs;
2988 /* Expand ~ or ~USER at the beginning of NAME.
2989 Return a newly malloc'd string or 0. */
2991 char *
2992 tilde_expand (const char *name)
2994 #ifndef VMS
2995 if (name[1] == '/' || name[1] == '\0')
2997 extern char *getenv ();
2998 char *home_dir;
2999 int is_variable;
3002 /* Turn off --warn-undefined-variables while we expand HOME. */
3003 int save = warn_undefined_variables_flag;
3004 warn_undefined_variables_flag = 0;
3006 home_dir = allocated_variable_expand ("$(HOME)");
3008 warn_undefined_variables_flag = save;
3011 is_variable = home_dir[0] != '\0';
3012 if (!is_variable)
3014 free (home_dir);
3015 home_dir = getenv ("HOME");
3017 # if !defined(_AMIGA) && !defined(WINDOWS32)
3018 if (home_dir == 0 || home_dir[0] == '\0')
3020 extern char *getlogin ();
3021 char *logname = getlogin ();
3022 home_dir = 0;
3023 if (logname != 0)
3025 struct passwd *p = getpwnam (logname);
3026 if (p != 0)
3027 home_dir = p->pw_dir;
3030 # endif /* !AMIGA && !WINDOWS32 */
3031 if (home_dir != 0)
3033 char *new = xstrdup (concat (home_dir, "", name + 1));
3034 if (is_variable)
3035 free (home_dir);
3036 return new;
3039 # if !defined(_AMIGA) && !defined(WINDOWS32)
3040 else
3042 struct passwd *pwent;
3043 char *userend = strchr (name + 1, '/');
3044 if (userend != 0)
3045 *userend = '\0';
3046 pwent = getpwnam (name + 1);
3047 if (pwent != 0)
3049 if (userend == 0)
3050 return xstrdup (pwent->pw_dir);
3051 else
3052 return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
3054 else if (userend != 0)
3055 *userend = '/';
3057 # endif /* !AMIGA && !WINDOWS32 */
3058 #endif /* !VMS */
3059 return 0;
3062 /* Given a chain of struct nameseq's describing a sequence of filenames,
3063 in reverse of the intended order, return a new chain describing the
3064 result of globbing the filenames. The new chain is in forward order.
3065 The links of the old chain are freed or used in the new chain.
3066 Likewise for the names in the old chain.
3068 SIZE is how big to construct chain elements.
3069 This is useful if we want them actually to be other structures
3070 that have room for additional info. */
3072 struct nameseq *
3073 multi_glob (struct nameseq *chain, unsigned int size)
3075 void dir_setup_glob (glob_t *);
3076 struct nameseq *new = 0;
3077 struct nameseq *old;
3078 struct nameseq *nexto;
3079 glob_t gl;
3081 dir_setup_glob (&gl);
3083 for (old = chain; old != 0; old = nexto)
3085 const char *gname;
3086 #ifndef NO_ARCHIVES
3087 char *arname = 0;
3088 char *memname = 0;
3089 #endif
3090 nexto = old->next;
3091 gname = old->name;
3093 if (gname[0] == '~')
3095 char *newname = tilde_expand (old->name);
3096 if (newname != 0)
3097 gname = newname;
3100 #ifndef NO_ARCHIVES
3101 if (ar_name (gname))
3103 /* OLD->name is an archive member reference. Replace it with the
3104 archive file name, and save the member name in MEMNAME. We will
3105 glob on the archive name and then reattach MEMNAME later. */
3106 ar_parse_name (gname, &arname, &memname);
3107 gname = arname;
3109 #endif /* !NO_ARCHIVES */
3111 switch (glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3113 case 0: /* Success. */
3115 int i = gl.gl_pathc;
3116 while (i-- > 0)
3118 #ifndef NO_ARCHIVES
3119 if (memname != 0)
3121 /* Try to glob on MEMNAME within the archive. */
3122 struct nameseq *found
3123 = ar_glob (gl.gl_pathv[i], memname, size);
3124 if (! found)
3126 /* No matches. Use MEMNAME as-is. */
3127 unsigned int alen = strlen (gl.gl_pathv[i]);
3128 unsigned int mlen = strlen (memname);
3129 char *name;
3130 struct nameseq *elt = xmalloc (size);
3131 memset (elt, '\0', size);
3133 name = alloca (alen + 1 + mlen + 2);
3134 memcpy (name, gl.gl_pathv[i], alen);
3135 name[alen] = '(';
3136 memcpy (name+alen+1, memname, mlen);
3137 name[alen + 1 + mlen] = ')';
3138 name[alen + 1 + mlen + 1] = '\0';
3139 elt->name = strcache_add (name);
3140 elt->next = new;
3141 new = elt;
3143 else
3145 /* Find the end of the FOUND chain. */
3146 struct nameseq *f = found;
3147 while (f->next != 0)
3148 f = f->next;
3150 /* Attach the chain being built to the end of the FOUND
3151 chain, and make FOUND the new NEW chain. */
3152 f->next = new;
3153 new = found;
3156 else
3157 #endif /* !NO_ARCHIVES */
3159 struct nameseq *elt = xmalloc (size);
3160 memset (elt, '\0', size);
3161 elt->name = strcache_add (gl.gl_pathv[i]);
3162 elt->next = new;
3163 new = elt;
3166 globfree (&gl);
3167 free (old);
3168 break;
3171 case GLOB_NOSPACE:
3172 fatal (NILF, _("virtual memory exhausted"));
3173 break;
3175 default:
3176 old->next = new;
3177 new = old;
3178 break;
3181 #ifndef NO_ARCHIVES
3182 if (arname)
3183 free (arname);
3184 #endif
3187 return new;