Implement new "load" directive.
[make.git] / read.c
blob912ca71cf8f4d7a215eaaf199081928ea56208a6
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988-2012 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include "make.h"
19 #include <assert.h>
21 #include <glob.h>
23 #include "dep.h"
24 #include "filedef.h"
25 #include "job.h"
26 #include "commands.h"
27 #include "variable.h"
28 #include "rule.h"
29 #include "debug.h"
30 #include "hash.h"
33 #ifndef WINDOWS32
34 #ifndef _AMIGA
35 #ifndef VMS
36 #include <pwd.h>
37 #else
38 struct passwd *getpwnam (char *name);
39 #endif
40 #endif
41 #endif /* !WINDOWS32 */
43 /* A 'struct ebuffer' controls the origin of the makefile we are currently
44 eval'ing.
47 struct ebuffer
49 char *buffer; /* Start of the current line in the buffer. */
50 char *bufnext; /* Start of the next line in the buffer. */
51 char *bufstart; /* Start of the entire buffer. */
52 unsigned int size; /* Malloc'd size of buffer. */
53 FILE *fp; /* File, or NULL if this is an internal buffer. */
54 struct floc floc; /* Info on the file in fp (if any). */
57 /* Track the modifiers we can have on variable assignments */
59 struct vmodifiers
61 unsigned int assign_v:1;
62 unsigned int define_v:1;
63 unsigned int undefine_v:1;
64 unsigned int export_v:1;
65 unsigned int override_v:1;
66 unsigned int private_v:1;
69 /* Types of "words" that can be read in a makefile. */
70 enum make_word_type
72 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
73 w_varassign
77 /* A 'struct conditionals' contains the information describing
78 all the active conditionals in a makefile.
80 The global variable 'conditionals' contains the conditionals
81 information for the current makefile. It is initialized from
82 the static structure 'toplevel_conditionals' and is later changed
83 to new structures for included makefiles. */
85 struct conditionals
87 unsigned int if_cmds; /* Depth of conditional nesting. */
88 unsigned int allocated; /* Elts allocated in following arrays. */
89 char *ignoring; /* Are we ignoring or interpreting?
90 0=interpreting, 1=not yet interpreted,
91 2=already interpreted */
92 char *seen_else; /* Have we already seen an 'else'? */
95 static struct conditionals toplevel_conditionals;
96 static struct conditionals *conditionals = &toplevel_conditionals;
99 /* Default directories to search for include files in */
101 static const char *default_include_directories[] =
103 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
104 /* This completely up to the user when they install MSVC or other packages.
105 This is defined as a placeholder. */
106 # define INCLUDEDIR "."
107 #endif
108 INCLUDEDIR,
109 #ifndef _AMIGA
110 "/usr/gnu/include",
111 "/usr/local/include",
112 "/usr/include",
113 #endif
117 /* List of directories to search for include files in */
119 static const char **include_directories;
121 /* Maximum length of an element of the above. */
123 static unsigned int max_incl_len;
125 /* The filename and pointer to line number of the
126 makefile currently being read in. */
128 const struct floc *reading_file = 0;
130 /* The chain of makefiles read by read_makefile. */
132 static struct dep *read_makefiles = 0;
134 static int eval_makefile (const char *filename, int flags);
135 static void eval (struct ebuffer *buffer, int flags);
137 static long readline (struct ebuffer *ebuf);
138 static void do_undefine (char *name, enum variable_origin origin,
139 struct ebuffer *ebuf);
140 static struct variable *do_define (char *name, 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, char *depstr,
145 unsigned int cmds_started, char *commands,
146 unsigned int commands_idx, int two_colon,
147 char prefix, 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);
157 static char *unescape_char (char *string, int c);
160 /* Compare a word, both length and contents.
161 P must point to the word to be tested, and WLEN must be the length.
163 #define word1eq(s) (wlen == CSTRLEN (s) && strneq (s, p, CSTRLEN (s)))
166 /* Read in all the makefiles and return the chain of their names. */
168 struct dep *
169 read_all_makefiles (const char **makefiles)
171 unsigned int num_makefiles = 0;
173 /* Create *_LIST variables, to hold the makefiles, targets, and variables
174 we will be reading. */
176 define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
178 DB (DB_BASIC, (_("Reading makefiles...\n")));
180 /* If there's a non-null variable MAKEFILES, its value is a list of
181 files to read first thing. But don't let it prevent reading the
182 default makefiles and don't let the default goal come from there. */
185 char *value;
186 char *name, *p;
187 unsigned int length;
190 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
191 int save = warn_undefined_variables_flag;
192 warn_undefined_variables_flag = 0;
194 value = allocated_variable_expand ("$(MAKEFILES)");
196 warn_undefined_variables_flag = save;
199 /* Set NAME to the start of next token and LENGTH to its length.
200 MAKEFILES is updated for finding remaining tokens. */
201 p = value;
203 while ((name = find_next_token ((const char **)&p, &length)) != 0)
205 if (*p != '\0')
206 *p++ = '\0';
207 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
210 free (value);
213 /* Read makefiles specified with -f switches. */
215 if (makefiles != 0)
216 while (*makefiles != 0)
218 struct dep *tail = read_makefiles;
219 register struct dep *d;
221 if (! eval_makefile (*makefiles, 0))
222 perror_with_name ("", *makefiles);
224 /* Find the right element of read_makefiles. */
225 d = read_makefiles;
226 while (d->next != tail)
227 d = d->next;
229 /* Use the storage read_makefile allocates. */
230 *makefiles = dep_name (d);
231 ++num_makefiles;
232 ++makefiles;
235 /* If there were no -f switches, try the default names. */
237 if (num_makefiles == 0)
239 static char *default_makefiles[] =
240 #ifdef VMS
241 /* all lower case since readdir() (the vms version) 'lowercasifies' */
242 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
243 #else
244 #ifdef _AMIGA
245 { "GNUmakefile", "Makefile", "SMakefile", 0 };
246 #else /* !Amiga && !VMS */
247 { "GNUmakefile", "makefile", "Makefile", 0 };
248 #endif /* AMIGA */
249 #endif /* VMS */
250 register char **p = default_makefiles;
251 while (*p != 0 && !file_exists_p (*p))
252 ++p;
254 if (*p != 0)
256 if (! eval_makefile (*p, 0))
257 perror_with_name ("", *p);
259 else
261 /* No default makefile was found. Add the default makefiles to the
262 'read_makefiles' chain so they will be updated if possible. */
263 struct dep *tail = read_makefiles;
264 /* Add them to the tail, after any MAKEFILES variable makefiles. */
265 while (tail != 0 && tail->next != 0)
266 tail = tail->next;
267 for (p = default_makefiles; *p != 0; ++p)
269 struct dep *d = alloc_dep ();
270 d->file = enter_file (strcache_add (*p));
271 d->dontcare = 1;
272 /* Tell update_goal_chain to bail out as soon as this file is
273 made, and main not to die if we can't make this file. */
274 d->changed = RM_DONTCARE;
275 if (tail == 0)
276 read_makefiles = d;
277 else
278 tail->next = d;
279 tail = d;
281 if (tail != 0)
282 tail->next = 0;
286 return read_makefiles;
289 /* Install a new conditional and return the previous one. */
291 static struct conditionals *
292 install_conditionals (struct conditionals *new)
294 struct conditionals *save = conditionals;
296 memset (new, '\0', sizeof (*new));
297 conditionals = new;
299 return save;
302 /* Free the current conditionals and reinstate a saved one. */
304 static void
305 restore_conditionals (struct conditionals *saved)
307 /* Free any space allocated by conditional_line. */
308 if (conditionals->ignoring)
309 free (conditionals->ignoring);
310 if (conditionals->seen_else)
311 free (conditionals->seen_else);
313 /* Restore state. */
314 conditionals = saved;
317 static int
318 eval_makefile (const char *filename, int flags)
320 struct dep *deps;
321 struct ebuffer ebuf;
322 const struct floc *curfile;
323 char *expanded = 0;
324 int makefile_errno;
326 ebuf.floc.filenm = filename; /* Use the original file name. */
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 = included;
372 break;
377 /* Now we have the final name for this makefile. Enter it into
378 the cache. */
379 filename = strcache_add (filename);
381 /* Add FILENAME to the chain of read makefiles. */
382 deps = alloc_dep ();
383 deps->next = read_makefiles;
384 read_makefiles = deps;
385 deps->file = lookup_file (filename);
386 if (deps->file == 0)
387 deps->file = enter_file (filename);
388 filename = deps->file->name;
389 deps->changed = flags;
390 if (flags & RM_DONTCARE)
391 deps->dontcare = 1;
393 if (expanded)
394 free (expanded);
396 /* If the makefile can't be found at all, give up entirely. */
398 if (ebuf.fp == 0)
400 /* If we did some searching, errno has the error from the last
401 attempt, rather from FILENAME itself. Restore it in case the
402 caller wants to use it in a message. */
403 errno = makefile_errno;
404 return 0;
407 /* Set close-on-exec to avoid leaking the makefile to children, such as
408 $(shell ...). */
409 #ifdef HAVE_FILENO
410 CLOSE_ON_EXEC (fileno (ebuf.fp));
411 #endif
413 /* Add this makefile to the list. */
414 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
415 f_append, 0);
417 /* Evaluate the makefile */
419 ebuf.size = 200;
420 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
422 curfile = reading_file;
423 reading_file = &ebuf.floc;
425 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
427 reading_file = curfile;
429 fclose (ebuf.fp);
431 free (ebuf.bufstart);
432 alloca (0);
434 return 1;
437 void
438 eval_buffer (char *buffer)
440 struct ebuffer ebuf;
441 struct conditionals *saved;
442 struct conditionals new;
443 const struct floc *curfile;
445 /* Evaluate the buffer */
447 ebuf.size = strlen (buffer);
448 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
449 ebuf.fp = NULL;
451 if (reading_file)
452 ebuf.floc = *reading_file;
453 else
454 ebuf.floc.filenm = NULL;
456 curfile = reading_file;
457 reading_file = &ebuf.floc;
459 saved = install_conditionals (&new);
461 eval (&ebuf, 1);
463 restore_conditionals (saved);
465 reading_file = curfile;
467 alloca (0);
470 /* Check LINE to see if it's a variable assignment or undefine.
472 It might use one of the modifiers "export", "override", "private", or it
473 might be one of the conditional tokens like "ifdef", "include", etc.
475 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
476 Returns LINE.
478 Returns a pointer to the first non-modifier character, and sets VMOD
479 based on the modifiers found if any, plus V_ASSIGN is 1.
481 static char *
482 parse_var_assignment (const char *line, struct vmodifiers *vmod)
484 const char *p;
485 memset (vmod, '\0', sizeof (*vmod));
487 /* Find the start of the next token. If there isn't one we're done. */
488 line = next_token (line);
489 if (*line == '\0')
490 return (char *)line;
492 p = line;
493 while (1)
495 int wlen;
496 const char *p2;
497 struct variable v;
499 p2 = parse_variable_definition (p, &v);
501 /* If this is a variable assignment, we're done. */
502 if (p2)
503 break;
505 /* It's not a variable; see if it's a modifier. */
506 p2 = end_of_token (p);
507 wlen = p2 - p;
509 if (word1eq ("export"))
510 vmod->export_v = 1;
511 else if (word1eq ("override"))
512 vmod->override_v = 1;
513 else if (word1eq ("private"))
514 vmod->private_v = 1;
515 else if (word1eq ("define"))
517 /* We can't have modifiers after 'define' */
518 vmod->define_v = 1;
519 p = next_token (p2);
520 break;
522 else if (word1eq ("undefine"))
524 /* We can't have modifiers after 'undefine' */
525 vmod->undefine_v = 1;
526 p = next_token (p2);
527 break;
529 else
530 /* Not a variable or modifier: this is not a variable assignment. */
531 return (char *)line;
533 /* It was a modifier. Try the next word. */
534 p = next_token (p2);
535 if (*p == '\0')
536 return (char *)line;
539 /* Found a variable assignment or undefine. */
540 vmod->assign_v = 1;
541 return (char *)p;
545 /* Read file FILENAME as a makefile and add its contents to the data base.
547 SET_DEFAULT is true if we are allowed to set the default goal. */
549 static void
550 eval (struct ebuffer *ebuf, int set_default)
552 char *collapsed = 0;
553 unsigned int collapsed_length = 0;
554 unsigned int commands_len = 200;
555 char *commands;
556 unsigned int commands_idx = 0;
557 unsigned int cmds_started, tgts_started;
558 int ignoring = 0, in_ignored_define = 0;
559 int no_targets = 0; /* Set when reading a rule without targets. */
560 struct nameseq *filenames = 0;
561 char *depstr = 0;
562 long nlines = 0;
563 int two_colon = 0;
564 char prefix = cmd_prefix;
565 const char *pattern = 0;
566 const char *pattern_percent;
567 struct floc *fstart;
568 struct floc fi;
570 #define record_waiting_files() \
571 do \
573 if (filenames != 0) \
575 fi.lineno = tgts_started; \
576 record_files (filenames, pattern, pattern_percent, depstr, \
577 cmds_started, commands, commands_idx, two_colon, \
578 prefix, &fi); \
579 filenames = 0; \
581 commands_idx = 0; \
582 no_targets = 0; \
583 pattern = 0; \
584 } while (0)
586 pattern_percent = 0;
587 cmds_started = tgts_started = 1;
589 fstart = &ebuf->floc;
590 fi.filenm = ebuf->floc.filenm;
592 /* Loop over lines in the file.
593 The strategy is to accumulate target names in FILENAMES, dependencies
594 in DEPS and commands in COMMANDS. These are used to define a rule
595 when the start of the next rule (or eof) is encountered.
597 When you see a "continue" in the loop below, that means we are moving on
598 to the next line. If you see record_waiting_files(), then the statement
599 we are parsing also finishes the previous rule. */
601 commands = xmalloc (200);
603 while (1)
605 unsigned int linelen;
606 char *line;
607 unsigned int wlen;
608 char *p;
609 char *p2;
610 struct vmodifiers vmod;
612 /* At the top of this loop, we are starting a brand new line. */
613 /* Grab the next line to be evaluated */
614 ebuf->floc.lineno += nlines;
615 nlines = readline (ebuf);
617 /* If there is nothing left to eval, we're done. */
618 if (nlines < 0)
619 break;
621 line = ebuf->buffer;
623 /* If this is the first line, check for a UTF-8 BOM and skip it. */
624 if (ebuf->floc.lineno == 1 && line[0] == (char)0xEF
625 && line[1] == (char)0xBB && line[2] == (char)0xBF)
627 line += 3;
628 if (ISDB(DB_BASIC))
630 if (ebuf->floc.filenm)
631 printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
632 ebuf->floc.filenm);
633 else
634 printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
638 /* If this line is empty, skip it. */
639 if (line[0] == '\0')
640 continue;
642 linelen = strlen (line);
644 /* Check for a shell command line first.
645 If it is not one, we can stop treating cmd_prefix specially. */
646 if (line[0] == cmd_prefix)
648 if (no_targets)
649 /* Ignore the commands in a rule with no targets. */
650 continue;
652 /* If there is no preceding rule line, don't treat this line
653 as a command, even though it begins with a recipe prefix.
654 SunOS 4 make appears to behave this way. */
656 if (filenames != 0)
658 if (ignoring)
659 /* Yep, this is a shell command, and we don't care. */
660 continue;
662 if (commands_idx == 0)
663 cmds_started = ebuf->floc.lineno;
665 /* Append this command line to the line being accumulated.
666 Skip the initial command prefix character. */
667 if (linelen + commands_idx > commands_len)
669 commands_len = (linelen + commands_idx) * 2;
670 commands = xrealloc (commands, commands_len);
672 memcpy (&commands[commands_idx], line + 1, linelen - 1);
673 commands_idx += linelen - 1;
674 commands[commands_idx++] = '\n';
675 continue;
679 /* This line is not a shell command line. Don't worry about whitespace.
680 Get more space if we need it; we don't need to preserve the current
681 contents of the buffer. */
683 if (collapsed_length < linelen+1)
685 collapsed_length = linelen+1;
686 if (collapsed)
687 free (collapsed);
688 /* Don't need xrealloc: we don't need to preserve the content. */
689 collapsed = xmalloc (collapsed_length);
691 strcpy (collapsed, line);
692 /* Collapse continuation lines. */
693 collapse_continuations (collapsed);
694 remove_comments (collapsed);
696 /* Get rid if starting space (including formfeed, vtab, etc.) */
697 p = collapsed;
698 while (isspace ((unsigned char)*p))
699 ++p;
701 /* See if this is a variable assignment. We need to do this early, to
702 allow variables with names like 'ifdef', 'export', 'private', etc. */
703 p = parse_var_assignment(p, &vmod);
704 if (vmod.assign_v)
706 struct variable *v;
707 enum variable_origin origin = vmod.override_v ? o_override : o_file;
709 /* Variable assignment ends the previous rule. */
710 record_waiting_files ();
712 /* If we're ignoring then we're done now. */
713 if (ignoring)
715 if (vmod.define_v)
716 in_ignored_define = 1;
717 continue;
720 if (vmod.undefine_v)
722 do_undefine (p, origin, ebuf);
723 continue;
725 else if (vmod.define_v)
726 v = do_define (p, origin, ebuf);
727 else
728 v = try_variable_definition (fstart, p, origin, 0);
730 assert (v != NULL);
732 if (vmod.export_v)
733 v->export = v_export;
734 if (vmod.private_v)
735 v->private_var = 1;
737 /* This line has been dealt with. */
738 continue;
741 /* If this line is completely empty, ignore it. */
742 if (*p == '\0')
743 continue;
745 p2 = end_of_token (p);
746 wlen = p2 - p;
747 p2 = next_token (p2);
749 /* If we're in an ignored define, skip this line (but maybe get out). */
750 if (in_ignored_define)
752 /* See if this is an endef line (plus optional comment). */
753 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
754 in_ignored_define = 0;
756 continue;
759 /* Check for conditional state changes. */
761 int i = conditional_line (p, wlen, fstart);
762 if (i != -2)
764 if (i == -1)
765 fatal (fstart, _("invalid syntax in conditional"));
767 ignoring = i;
768 continue;
772 /* Nothing to see here... move along. */
773 if (ignoring)
774 continue;
776 /* Manage the "export" keyword used outside of variable assignment
777 as well as "unexport". */
778 if (word1eq ("export") || word1eq ("unexport"))
780 int exporting = *p == 'u' ? 0 : 1;
782 /* Export/unexport ends the previous rule. */
783 record_waiting_files ();
785 /* (un)export by itself causes everything to be (un)exported. */
786 if (*p2 == '\0')
787 export_all_variables = exporting;
788 else
790 unsigned int l;
791 const char *cp;
792 char *ap;
794 /* Expand the line so we can use indirect and constructed
795 variable names in an (un)export command. */
796 cp = ap = allocated_variable_expand (p2);
798 for (p = find_next_token (&cp, &l); p != 0;
799 p = find_next_token (&cp, &l))
801 struct variable *v = lookup_variable (p, l);
802 if (v == 0)
803 v = define_variable_global (p, l, "", o_file, 0, fstart);
804 v->export = exporting ? v_export : v_noexport;
807 free (ap);
809 continue;
812 /* Handle the special syntax for vpath. */
813 if (word1eq ("vpath"))
815 const char *cp;
816 char *vpat;
817 unsigned int l;
819 /* vpath ends the previous rule. */
820 record_waiting_files ();
822 cp = variable_expand (p2);
823 p = find_next_token (&cp, &l);
824 if (p != 0)
826 vpat = xstrndup (p, l);
827 p = find_next_token (&cp, &l);
828 /* No searchpath means remove all previous
829 selective VPATH's with the same pattern. */
831 else
832 /* No pattern means remove all previous selective VPATH's. */
833 vpat = 0;
834 construct_vpath_list (vpat, p);
835 if (vpat != 0)
836 free (vpat);
838 continue;
841 /* Handle include and variants. */
842 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
844 /* We have found an 'include' line specifying a nested
845 makefile to be read at this point. */
846 struct conditionals *save;
847 struct conditionals new_conditionals;
848 struct nameseq *files;
849 /* "-include" (vs "include") says no error if the file does not
850 exist. "sinclude" is an alias for this from SGI. */
851 int noerror = (p[0] != 'i');
853 /* Include ends the previous rule. */
854 record_waiting_files ();
856 p = allocated_variable_expand (p2);
858 /* If no filenames, it's a no-op. */
859 if (*p == '\0')
861 free (p);
862 continue;
865 /* Parse the list of file names. Don't expand archive references! */
866 p2 = p;
867 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
868 PARSEFS_NOAR);
869 free (p);
871 /* Save the state of conditionals and start
872 the included makefile with a clean slate. */
873 save = install_conditionals (&new_conditionals);
875 /* Record the rules that are waiting so they will determine
876 the default goal before those in the included makefile. */
877 record_waiting_files ();
879 /* Read each included makefile. */
880 while (files != 0)
882 struct nameseq *next = files->next;
883 const char *name = files->name;
884 int r;
886 free_ns (files);
887 files = next;
889 r = eval_makefile (name,
890 (RM_INCLUDED | RM_NO_TILDE
891 | (noerror ? RM_DONTCARE : 0)
892 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
893 if (!r && !noerror)
894 error (fstart, "%s: %s", name, strerror (errno));
897 /* Restore conditional state. */
898 restore_conditionals (save);
900 continue;
903 /* Handle the load operations. */
904 if (word1eq ("load") || word1eq ("-load"))
906 /* A 'load' line specifies a dynamic object to load. */
907 struct nameseq *files;
908 int noerror = (p[0] == '-');
910 /* Load ends the previous rule. */
911 record_waiting_files ();
913 p = allocated_variable_expand (p2);
915 /* If no filenames, it's a no-op. */
916 if (*p == '\0')
918 free (p);
919 continue;
922 /* Parse the list of file names.
923 Don't expand archive references or strip "./" */
924 p2 = p;
925 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
926 PARSEFS_NOAR|PARSEFS_NOSTRIP);
927 free (p);
929 /* Load each file. */
930 while (files != 0)
932 struct nameseq *next = files->next;
933 const char *name = files->name;
935 free_ns (files);
936 files = next;
938 if (! load_file (&ebuf->floc, name, noerror) && ! noerror)
939 fatal (&ebuf->floc, _("%s: failed to load"), name);
942 continue;
945 /* This line starts with a tab but was not caught above because there
946 was no preceding target, and the line might have been usable as a
947 variable definition. But now we know it is definitely lossage. */
948 if (line[0] == cmd_prefix)
949 fatal(fstart, _("recipe commences before first target"));
951 /* This line describes some target files. This is complicated by
952 the existence of target-specific variables, because we can't
953 expand the entire line until we know if we have one or not. So
954 we expand the line word by word until we find the first ':',
955 then check to see if it's a target-specific variable.
957 In this algorithm, 'lb_next' will point to the beginning of the
958 unexpanded parts of the input buffer, while 'p2' points to the
959 parts of the expanded buffer we haven't searched yet. */
962 enum make_word_type wtype;
963 char *cmdleft, *semip, *lb_next;
964 unsigned int plen = 0;
965 char *colonp;
966 const char *end, *beg; /* Helpers for whitespace stripping. */
968 /* Record the previous rule. */
970 record_waiting_files ();
971 tgts_started = fstart->lineno;
973 /* Search the line for an unquoted ; that is not after an
974 unquoted #. */
975 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
976 if (cmdleft != 0 && *cmdleft == '#')
978 /* We found a comment before a semicolon. */
979 *cmdleft = '\0';
980 cmdleft = 0;
982 else if (cmdleft != 0)
983 /* Found one. Cut the line short there before expanding it. */
984 *(cmdleft++) = '\0';
985 semip = cmdleft;
987 collapse_continuations (line);
989 /* We can't expand the entire line, since if it's a per-target
990 variable we don't want to expand it. So, walk from the
991 beginning, expanding as we go, and looking for "interesting"
992 chars. The first word is always expandable. */
993 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
994 switch (wtype)
996 case w_eol:
997 if (cmdleft != 0)
998 fatal(fstart, _("missing rule before recipe"));
999 /* This line contained something but turned out to be nothing
1000 but whitespace (a comment?). */
1001 continue;
1003 case w_colon:
1004 case w_dcolon:
1005 /* We accept and ignore rules without targets for
1006 compatibility with SunOS 4 make. */
1007 no_targets = 1;
1008 continue;
1010 default:
1011 break;
1014 p2 = variable_expand_string(NULL, lb_next, wlen);
1016 while (1)
1018 lb_next += wlen;
1019 if (cmdleft == 0)
1021 /* Look for a semicolon in the expanded line. */
1022 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1024 if (cmdleft != 0)
1026 unsigned long p2_off = p2 - variable_buffer;
1027 unsigned long cmd_off = cmdleft - variable_buffer;
1028 char *pend = p2 + strlen(p2);
1030 /* Append any remnants of lb, then cut the line short
1031 at the semicolon. */
1032 *cmdleft = '\0';
1034 /* One school of thought says that you shouldn't expand
1035 here, but merely copy, since now you're beyond a ";"
1036 and into a command script. However, the old parser
1037 expanded the whole line, so we continue that for
1038 backwards-compatiblity. Also, it wouldn't be
1039 entirely consistent, since we do an unconditional
1040 expand below once we know we don't have a
1041 target-specific variable. */
1042 (void)variable_expand_string(pend, lb_next, (long)-1);
1043 lb_next += strlen(lb_next);
1044 p2 = variable_buffer + p2_off;
1045 cmdleft = variable_buffer + cmd_off + 1;
1049 colonp = find_char_unquote(p2, ':', 0, 0, 0);
1050 #ifdef HAVE_DOS_PATHS
1051 /* The drive spec brain-damage strikes again... */
1052 /* Note that the only separators of targets in this context
1053 are whitespace and a left paren. If others are possible,
1054 they should be added to the string in the call to index. */
1055 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
1056 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
1057 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1058 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
1059 #endif
1060 if (colonp != 0)
1061 break;
1063 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
1064 if (wtype == w_eol)
1065 break;
1067 p2 += strlen(p2);
1068 *(p2++) = ' ';
1069 p2 = variable_expand_string(p2, lb_next, wlen);
1070 /* We don't need to worry about cmdleft here, because if it was
1071 found in the variable_buffer the entire buffer has already
1072 been expanded... we'll never get here. */
1075 p2 = next_token (variable_buffer);
1077 /* If the word we're looking at is EOL, see if there's _anything_
1078 on the line. If not, a variable expanded to nothing, so ignore
1079 it. If so, we can't parse this line so punt. */
1080 if (wtype == w_eol)
1082 if (*p2 != '\0')
1083 /* There's no need to be ivory-tower about this: check for
1084 one of the most common bugs found in makefiles... */
1085 fatal (fstart, _("missing separator%s"),
1086 (cmd_prefix == '\t' && !strneq (line, " ", 8))
1087 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1088 continue;
1091 /* Make the colon the end-of-string so we know where to stop
1092 looking for targets. Start there again once we're done. */
1093 *colonp = '\0';
1094 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1095 *colonp = ':';
1096 p2 = colonp;
1098 if (!filenames)
1100 /* We accept and ignore rules without targets for
1101 compatibility with SunOS 4 make. */
1102 no_targets = 1;
1103 continue;
1105 /* This should never be possible; we handled it above. */
1106 assert (*p2 != '\0');
1107 ++p2;
1109 /* Is this a one-colon or two-colon entry? */
1110 two_colon = *p2 == ':';
1111 if (two_colon)
1112 p2++;
1114 /* Test to see if it's a target-specific variable. Copy the rest
1115 of the buffer over, possibly temporarily (we'll expand it later
1116 if it's not a target-specific variable). PLEN saves the length
1117 of the unparsed section of p2, for later. */
1118 if (*lb_next != '\0')
1120 unsigned int l = p2 - variable_buffer;
1121 plen = strlen (p2);
1122 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1123 p2 = variable_buffer + l;
1126 p2 = parse_var_assignment (p2, &vmod);
1127 if (vmod.assign_v)
1129 /* If there was a semicolon found, add it back, plus anything
1130 after it. */
1131 if (semip)
1133 unsigned int l = p2 - variable_buffer;
1134 *(--semip) = ';';
1135 collapse_continuations (semip);
1136 variable_buffer_output (p2 + strlen (p2),
1137 semip, strlen (semip)+1);
1138 p2 = variable_buffer + l;
1140 record_target_var (filenames, p2,
1141 vmod.override_v ? o_override : o_file,
1142 &vmod, fstart);
1143 filenames = 0;
1144 continue;
1147 /* This is a normal target, _not_ a target-specific variable.
1148 Unquote any = in the dependency list. */
1149 find_char_unquote (lb_next, '=', 0, 0, 0);
1151 /* Remember the command prefix for this target. */
1152 prefix = cmd_prefix;
1154 /* We have some targets, so don't ignore the following commands. */
1155 no_targets = 0;
1157 /* Expand the dependencies, etc. */
1158 if (*lb_next != '\0')
1160 unsigned int l = p2 - variable_buffer;
1161 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1162 p2 = variable_buffer + l;
1164 /* Look for a semicolon in the expanded line. */
1165 if (cmdleft == 0)
1167 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1168 if (cmdleft != 0)
1169 *(cmdleft++) = '\0';
1173 /* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
1174 p = strchr (p2, ':');
1175 while (p != 0 && p[-1] == '\\')
1177 char *q = &p[-1];
1178 int backslash = 0;
1179 while (*q-- == '\\')
1180 backslash = !backslash;
1181 if (backslash)
1182 p = strchr (p + 1, ':');
1183 else
1184 break;
1186 #ifdef _AMIGA
1187 /* Here, the situation is quite complicated. Let's have a look
1188 at a couple of targets:
1190 install: dev:make
1192 dev:make: make
1194 dev:make:: xyz
1196 The rule is that it's only a target, if there are TWO :'s
1197 OR a space around the :.
1199 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1200 || isspace ((unsigned char)p[-1])))
1201 p = 0;
1202 #endif
1203 #ifdef HAVE_DOS_PATHS
1205 int check_again;
1206 do {
1207 check_again = 0;
1208 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1209 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1210 isalpha ((unsigned char)p[-1]) &&
1211 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1212 p = strchr (p + 1, ':');
1213 check_again = 1;
1215 } while (check_again);
1217 #endif
1218 if (p != 0)
1220 struct nameseq *target;
1221 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1222 PARSEFS_NOGLOB);
1223 ++p2;
1224 if (target == 0)
1225 fatal (fstart, _("missing target pattern"));
1226 else if (target->next != 0)
1227 fatal (fstart, _("multiple target patterns"));
1228 pattern_percent = find_percent_cached (&target->name);
1229 pattern = target->name;
1230 if (pattern_percent == 0)
1231 fatal (fstart, _("target pattern contains no '%%'"));
1232 free_ns (target);
1234 else
1235 pattern = 0;
1237 /* Strip leading and trailing whitespaces. */
1238 beg = p2;
1239 end = beg + strlen (beg) - 1;
1240 strip_whitespace (&beg, &end);
1242 /* Put all the prerequisites here; they'll be parsed later. */
1243 if (beg <= end && *beg != '\0')
1244 depstr = xstrndup (beg, end - beg + 1);
1245 else
1246 depstr = 0;
1248 commands_idx = 0;
1249 if (cmdleft != 0)
1251 /* Semicolon means rest of line is a command. */
1252 unsigned int l = strlen (cmdleft);
1254 cmds_started = fstart->lineno;
1256 /* Add this command line to the buffer. */
1257 if (l + 2 > commands_len)
1259 commands_len = (l + 2) * 2;
1260 commands = xrealloc (commands, commands_len);
1262 memcpy (commands, cmdleft, l);
1263 commands_idx += l;
1264 commands[commands_idx++] = '\n';
1267 /* Determine if this target should be made default. We used to do
1268 this in record_files() but because of the delayed target recording
1269 and because preprocessor directives are legal in target's commands
1270 it is too late. Consider this fragment for example:
1272 foo:
1274 ifeq ($(.DEFAULT_GOAL),foo)
1276 endif
1278 Because the target is not recorded until after ifeq directive is
1279 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1280 would expect. Because of this we have to move the logic here. */
1282 if (set_default && default_goal_var->value[0] == '\0')
1284 const char *name;
1285 struct dep *d;
1286 struct nameseq *t = filenames;
1288 for (; t != 0; t = t->next)
1290 int reject = 0;
1291 name = t->name;
1293 /* We have nothing to do if this is an implicit rule. */
1294 if (strchr (name, '%') != 0)
1295 break;
1297 /* See if this target's name does not start with a '.',
1298 unless it contains a slash. */
1299 if (*name == '.' && strchr (name, '/') == 0
1300 #ifdef HAVE_DOS_PATHS
1301 && strchr (name, '\\') == 0
1302 #endif
1304 continue;
1307 /* If this file is a suffix, don't let it be
1308 the default goal file. */
1309 for (d = suffix_file->deps; d != 0; d = d->next)
1311 register struct dep *d2;
1312 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1314 reject = 1;
1315 break;
1317 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1319 unsigned int l = strlen (dep_name (d2));
1320 if (!strneq (name, dep_name (d2), l))
1321 continue;
1322 if (streq (name + l, dep_name (d)))
1324 reject = 1;
1325 break;
1329 if (reject)
1330 break;
1333 if (!reject)
1335 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1336 o_file, 0, NILF);
1337 break;
1342 continue;
1345 /* We get here except in the case that we just read a rule line.
1346 Record now the last rule we read, so following spurious
1347 commands are properly diagnosed. */
1348 record_waiting_files ();
1351 #undef word1eq
1353 if (conditionals->if_cmds)
1354 fatal (fstart, _("missing 'endif'"));
1356 /* At eof, record the last rule. */
1357 record_waiting_files ();
1359 if (collapsed)
1360 free (collapsed);
1361 free (commands);
1365 /* Remove comments from LINE.
1366 This is done by copying the text at LINE onto itself. */
1368 static void
1369 remove_comments (char *line)
1371 char *comment;
1373 comment = find_char_unquote (line, '#', 0, 0, 0);
1375 if (comment != 0)
1376 /* Cut off the line at the #. */
1377 *comment = '\0';
1380 /* Execute a 'undefine' directive.
1381 The undefine line has already been read, and NAME is the name of
1382 the variable to be undefined. */
1384 static void
1385 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1387 char *p, *var;
1389 /* Expand the variable name and find the beginning (NAME) and end. */
1390 var = allocated_variable_expand (name);
1391 name = next_token (var);
1392 if (*name == '\0')
1393 fatal (&ebuf->floc, _("empty variable name"));
1394 p = name + strlen (name) - 1;
1395 while (p > name && isblank ((unsigned char)*p))
1396 --p;
1397 p[1] = '\0';
1399 undefine_variable_global (name, p - name + 1, origin);
1400 free (var);
1403 /* Execute a 'define' directive.
1404 The first line has already been read, and NAME is the name of
1405 the variable to be defined. The following lines remain to be read. */
1407 static struct variable *
1408 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1410 struct variable *v;
1411 struct variable var;
1412 struct floc defstart;
1413 int nlevels = 1;
1414 unsigned int length = 100;
1415 char *definition = xmalloc (length);
1416 unsigned int idx = 0;
1417 char *p, *n;
1419 defstart = ebuf->floc;
1421 p = parse_variable_definition (name, &var);
1422 if (p == NULL)
1423 /* No assignment token, so assume recursive. */
1424 var.flavor = f_recursive;
1425 else
1427 if (var.value[0] != '\0')
1428 error (&defstart, _("extraneous text after 'define' directive"));
1430 /* Chop the string before the assignment token to get the name. */
1431 var.name[var.length] = '\0';
1434 /* Expand the variable name and find the beginning (NAME) and end. */
1435 n = allocated_variable_expand (name);
1436 name = next_token (n);
1437 if (name[0] == '\0')
1438 fatal (&defstart, _("empty variable name"));
1439 p = name + strlen (name) - 1;
1440 while (p > name && isblank ((unsigned char)*p))
1441 --p;
1442 p[1] = '\0';
1444 /* Now read the value of the variable. */
1445 while (1)
1447 unsigned int len;
1448 char *line;
1449 long nlines = readline (ebuf);
1451 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1452 if (nlines < 0)
1453 fatal (&defstart, _("missing 'endef', unterminated 'define'"));
1455 ebuf->floc.lineno += nlines;
1456 line = ebuf->buffer;
1458 collapse_continuations (line);
1460 /* If the line doesn't begin with a tab, test to see if it introduces
1461 another define, or ends one. Stop if we find an 'endef' */
1462 if (line[0] != cmd_prefix)
1464 p = next_token (line);
1465 len = strlen (p);
1467 /* If this is another 'define', increment the level count. */
1468 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1469 && strneq (p, "define", 6))
1470 ++nlevels;
1472 /* If this is an 'endef', decrement the count. If it's now 0,
1473 we've found the last one. */
1474 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1475 && strneq (p, "endef", 5))
1477 p += 5;
1478 remove_comments (p);
1479 if (*(next_token (p)) != '\0')
1480 error (&ebuf->floc,
1481 _("extraneous text after 'endef' directive"));
1483 if (--nlevels == 0)
1484 break;
1488 /* Add this line to the variable definition. */
1489 len = strlen (line);
1490 if (idx + len + 1 > length)
1492 length = (idx + len) * 2;
1493 definition = xrealloc (definition, length + 1);
1496 memcpy (&definition[idx], line, len);
1497 idx += len;
1498 /* Separate lines with a newline. */
1499 definition[idx++] = '\n';
1502 /* We've got what we need; define the variable. */
1503 if (idx == 0)
1504 definition[0] = '\0';
1505 else
1506 definition[idx - 1] = '\0';
1508 v = do_variable_definition (&defstart, name,
1509 definition, origin, var.flavor, 0);
1510 free (definition);
1511 free (n);
1512 return (v);
1515 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1516 "ifneq", "else" and "endif".
1517 LINE is the input line, with the command as its first word.
1519 FILENAME and LINENO are the filename and line number in the
1520 current makefile. They are used for error messages.
1522 Value is -2 if the line is not a conditional at all,
1523 -1 if the line is an invalid conditional,
1524 0 if following text should be interpreted,
1525 1 if following text should be ignored. */
1527 static int
1528 conditional_line (char *line, int len, const struct floc *flocp)
1530 char *cmdname;
1531 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1532 unsigned int i;
1533 unsigned int o;
1535 /* Compare a word, both length and contents. */
1536 #define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
1537 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1539 /* Make sure this line is a conditional. */
1540 chkword ("ifdef", c_ifdef)
1541 else chkword ("ifndef", c_ifndef)
1542 else chkword ("ifeq", c_ifeq)
1543 else chkword ("ifneq", c_ifneq)
1544 else chkword ("else", c_else)
1545 else chkword ("endif", c_endif)
1546 else
1547 return -2;
1549 /* Found one: skip past it and any whitespace after it. */
1550 line = next_token (line + len);
1552 #define EXTRANEOUS() error (flocp, _("Extraneous text after '%s' directive"), cmdname)
1554 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1555 if (cmdtype == c_endif)
1557 if (*line != '\0')
1558 EXTRANEOUS ();
1560 if (!conditionals->if_cmds)
1561 fatal (flocp, _("extraneous '%s'"), cmdname);
1563 --conditionals->if_cmds;
1565 goto DONE;
1568 /* An 'else' statement can either be simple, or it can have another
1569 conditional after it. */
1570 if (cmdtype == c_else)
1572 const char *p;
1574 if (!conditionals->if_cmds)
1575 fatal (flocp, _("extraneous '%s'"), cmdname);
1577 o = conditionals->if_cmds - 1;
1579 if (conditionals->seen_else[o])
1580 fatal (flocp, _("only one 'else' per conditional"));
1582 /* Change the state of ignorance. */
1583 switch (conditionals->ignoring[o])
1585 case 0:
1586 /* We've just been interpreting. Never do it again. */
1587 conditionals->ignoring[o] = 2;
1588 break;
1589 case 1:
1590 /* We've never interpreted yet. Maybe this time! */
1591 conditionals->ignoring[o] = 0;
1592 break;
1595 /* It's a simple 'else'. */
1596 if (*line == '\0')
1598 conditionals->seen_else[o] = 1;
1599 goto DONE;
1602 /* The 'else' has extra text. That text must be another conditional
1603 and cannot be an 'else' or 'endif'. */
1605 /* Find the length of the next word. */
1606 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1608 len = p - line;
1610 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1611 if (word1eq ("else") || word1eq ("endif")
1612 || conditional_line (line, len, flocp) < 0)
1613 EXTRANEOUS ();
1614 else
1616 /* conditional_line() created a new level of conditional.
1617 Raise it back to this level. */
1618 if (conditionals->ignoring[o] < 2)
1619 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1620 --conditionals->if_cmds;
1623 goto DONE;
1626 if (conditionals->allocated == 0)
1628 conditionals->allocated = 5;
1629 conditionals->ignoring = xmalloc (conditionals->allocated);
1630 conditionals->seen_else = xmalloc (conditionals->allocated);
1633 o = conditionals->if_cmds++;
1634 if (conditionals->if_cmds > conditionals->allocated)
1636 conditionals->allocated += 5;
1637 conditionals->ignoring = xrealloc (conditionals->ignoring,
1638 conditionals->allocated);
1639 conditionals->seen_else = xrealloc (conditionals->seen_else,
1640 conditionals->allocated);
1643 /* Record that we have seen an 'if...' but no 'else' so far. */
1644 conditionals->seen_else[o] = 0;
1646 /* Search through the stack to see if we're already ignoring. */
1647 for (i = 0; i < o; ++i)
1648 if (conditionals->ignoring[i])
1650 /* We are already ignoring, so just push a level to match the next
1651 "else" or "endif", and keep ignoring. We don't want to expand
1652 variables in the condition. */
1653 conditionals->ignoring[o] = 1;
1654 return 1;
1657 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1659 char *var;
1660 struct variable *v;
1661 char *p;
1663 /* Expand the thing we're looking up, so we can use indirect and
1664 constructed variable names. */
1665 var = allocated_variable_expand (line);
1667 /* Make sure there's only one variable name to test. */
1668 p = end_of_token (var);
1669 i = p - var;
1670 p = next_token (p);
1671 if (*p != '\0')
1672 return -1;
1674 var[i] = '\0';
1675 v = lookup_variable (var, i);
1677 conditionals->ignoring[o] =
1678 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1680 free (var);
1682 else
1684 /* "ifeq" or "ifneq". */
1685 char *s1, *s2;
1686 unsigned int l;
1687 char termin = *line == '(' ? ',' : *line;
1689 if (termin != ',' && termin != '"' && termin != '\'')
1690 return -1;
1692 s1 = ++line;
1693 /* Find the end of the first string. */
1694 if (termin == ',')
1696 int count = 0;
1697 for (; *line != '\0'; ++line)
1698 if (*line == '(')
1699 ++count;
1700 else if (*line == ')')
1701 --count;
1702 else if (*line == ',' && count <= 0)
1703 break;
1705 else
1706 while (*line != '\0' && *line != termin)
1707 ++line;
1709 if (*line == '\0')
1710 return -1;
1712 if (termin == ',')
1714 /* Strip blanks after the first string. */
1715 char *p = line++;
1716 while (isblank ((unsigned char)p[-1]))
1717 --p;
1718 *p = '\0';
1720 else
1721 *line++ = '\0';
1723 s2 = variable_expand (s1);
1724 /* We must allocate a new copy of the expanded string because
1725 variable_expand re-uses the same buffer. */
1726 l = strlen (s2);
1727 s1 = alloca (l + 1);
1728 memcpy (s1, s2, l + 1);
1730 if (termin != ',')
1731 /* Find the start of the second string. */
1732 line = next_token (line);
1734 termin = termin == ',' ? ')' : *line;
1735 if (termin != ')' && termin != '"' && termin != '\'')
1736 return -1;
1738 /* Find the end of the second string. */
1739 if (termin == ')')
1741 int count = 0;
1742 s2 = next_token (line);
1743 for (line = s2; *line != '\0'; ++line)
1745 if (*line == '(')
1746 ++count;
1747 else if (*line == ')')
1749 if (count <= 0)
1750 break;
1751 else
1752 --count;
1756 else
1758 ++line;
1759 s2 = line;
1760 while (*line != '\0' && *line != termin)
1761 ++line;
1764 if (*line == '\0')
1765 return -1;
1767 *line = '\0';
1768 line = next_token (++line);
1769 if (*line != '\0')
1770 EXTRANEOUS ();
1772 s2 = variable_expand (s2);
1773 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1776 DONE:
1777 /* Search through the stack to see if we're ignoring. */
1778 for (i = 0; i < conditionals->if_cmds; ++i)
1779 if (conditionals->ignoring[i])
1780 return 1;
1781 return 0;
1785 /* Record target-specific variable values for files FILENAMES.
1786 TWO_COLON is nonzero if a double colon was used.
1788 The links of FILENAMES are freed, and so are any names in it
1789 that are not incorporated into other data structures.
1791 If the target is a pattern, add the variable to the pattern-specific
1792 variable value list. */
1794 static void
1795 record_target_var (struct nameseq *filenames, char *defn,
1796 enum variable_origin origin, struct vmodifiers *vmod,
1797 const struct floc *flocp)
1799 struct nameseq *nextf;
1800 struct variable_set_list *global;
1802 global = current_variable_set_list;
1804 /* If the variable is an append version, store that but treat it as a
1805 normal recursive variable. */
1807 for (; filenames != 0; filenames = nextf)
1809 struct variable *v;
1810 const char *name = filenames->name;
1811 const char *percent;
1812 struct pattern_var *p;
1814 nextf = filenames->next;
1815 free_ns (filenames);
1817 /* If it's a pattern target, then add it to the pattern-specific
1818 variable list. */
1819 percent = find_percent_cached (&name);
1820 if (percent)
1822 /* Get a reference for this pattern-specific variable struct. */
1823 p = create_pattern_var (name, percent);
1824 p->variable.fileinfo = *flocp;
1825 /* I don't think this can fail since we already determined it was a
1826 variable definition. */
1827 v = assign_variable_definition (&p->variable, defn);
1828 assert (v != 0);
1830 v->origin = origin;
1831 if (v->flavor == f_simple)
1832 v->value = allocated_variable_expand (v->value);
1833 else
1834 v->value = xstrdup (v->value);
1836 else
1838 struct file *f;
1840 /* Get a file reference for this file, and initialize it.
1841 We don't want to just call enter_file() because that allocates a
1842 new entry if the file is a double-colon, which we don't want in
1843 this situation. */
1844 f = lookup_file (name);
1845 if (!f)
1846 f = enter_file (strcache_add (name));
1847 else if (f->double_colon)
1848 f = f->double_colon;
1850 initialize_file_variables (f, 1);
1852 current_variable_set_list = f->variables;
1853 v = try_variable_definition (flocp, defn, origin, 1);
1854 if (!v)
1855 fatal (flocp, _("Malformed target-specific variable definition"));
1856 current_variable_set_list = global;
1859 /* Set up the variable to be *-specific. */
1860 v->per_target = 1;
1861 v->private_var = vmod->private_v;
1862 v->export = vmod->export_v ? v_export : v_default;
1864 /* If it's not an override, check to see if there was a command-line
1865 setting. If so, reset the value. */
1866 if (v->origin != o_override)
1868 struct variable *gv;
1869 int len = strlen(v->name);
1871 gv = lookup_variable (v->name, len);
1872 if (gv && v != gv
1873 && (gv->origin == o_env_override || gv->origin == o_command))
1875 if (v->value != 0)
1876 free (v->value);
1877 v->value = xstrdup (gv->value);
1878 v->origin = gv->origin;
1879 v->recursive = gv->recursive;
1880 v->append = 0;
1886 /* Record a description line for files FILENAMES,
1887 with dependencies DEPS, commands to execute described
1888 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1889 TWO_COLON is nonzero if a double colon was used.
1890 If not nil, PATTERN is the '%' pattern to make this
1891 a static pattern rule, and PATTERN_PERCENT is a pointer
1892 to the '%' within it.
1894 The links of FILENAMES are freed, and so are any names in it
1895 that are not incorporated into other data structures. */
1897 static void
1898 record_files (struct nameseq *filenames, const char *pattern,
1899 const char *pattern_percent, char *depstr,
1900 unsigned int cmds_started, char *commands,
1901 unsigned int commands_idx, int two_colon,
1902 char prefix, const struct floc *flocp)
1904 struct commands *cmds;
1905 struct dep *deps;
1906 const char *implicit_percent;
1907 const char *name;
1909 /* If we've already snapped deps, that means we're in an eval being
1910 resolved after the makefiles have been read in. We can't add more rules
1911 at this time, since they won't get snapped and we'll get core dumps.
1912 See Savannah bug # 12124. */
1913 if (snapped_deps)
1914 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1916 /* Determine if this is a pattern rule or not. */
1917 name = filenames->name;
1918 implicit_percent = find_percent_cached (&name);
1920 /* If there's a recipe, set up a struct for it. */
1921 if (commands_idx > 0)
1923 cmds = xmalloc (sizeof (struct commands));
1924 cmds->fileinfo.filenm = flocp->filenm;
1925 cmds->fileinfo.lineno = cmds_started;
1926 cmds->commands = xstrndup (commands, commands_idx);
1927 cmds->command_lines = 0;
1928 cmds->recipe_prefix = prefix;
1930 else
1931 cmds = 0;
1933 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1934 expansion: if so, snap_deps() will do it. */
1935 if (depstr == 0)
1936 deps = 0;
1937 else
1939 depstr = unescape_char (depstr, ':');
1940 if (second_expansion && strchr (depstr, '$'))
1942 deps = alloc_dep ();
1943 deps->name = depstr;
1944 deps->need_2nd_expansion = 1;
1945 deps->staticpattern = pattern != 0;
1947 else
1949 deps = split_prereqs (depstr);
1950 free (depstr);
1952 /* We'll enter static pattern prereqs later when we have the stem.
1953 We don't want to enter pattern rules at all so that we don't
1954 think that they ought to exist (make manual "Implicit Rule Search
1955 Algorithm", item 5c). */
1956 if (! pattern && ! implicit_percent)
1957 deps = enter_prereqs (deps, NULL);
1961 /* For implicit rules, _all_ the targets must have a pattern. That means we
1962 can test the first one to see if we're working with an implicit rule; if
1963 so we handle it specially. */
1965 if (implicit_percent)
1967 struct nameseq *nextf;
1968 const char **targets, **target_pats;
1969 unsigned int c;
1971 if (pattern != 0)
1972 fatal (flocp, _("mixed implicit and static pattern rules"));
1974 /* Count the targets to create an array of target names.
1975 We already have the first one. */
1976 nextf = filenames->next;
1977 free_ns (filenames);
1978 filenames = nextf;
1980 for (c = 1; nextf; ++c, nextf = nextf->next)
1982 targets = xmalloc (c * sizeof (const char *));
1983 target_pats = xmalloc (c * sizeof (const char *));
1985 targets[0] = name;
1986 target_pats[0] = implicit_percent;
1988 c = 1;
1989 while (filenames)
1991 name = filenames->name;
1992 implicit_percent = find_percent_cached (&name);
1994 if (implicit_percent == 0)
1995 fatal (flocp, _("mixed implicit and normal rules"));
1997 targets[c] = name;
1998 target_pats[c] = implicit_percent;
1999 ++c;
2001 nextf = filenames->next;
2002 free_ns (filenames);
2003 filenames = nextf;
2006 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
2008 return;
2012 /* Walk through each target and create it in the database.
2013 We already set up the first target, above. */
2014 while (1)
2016 struct nameseq *nextf = filenames->next;
2017 struct file *f;
2018 struct dep *this = 0;
2020 free_ns (filenames);
2022 /* Check for special targets. Do it here instead of, say, snap_deps()
2023 so that we can immediately use the value. */
2024 if (streq (name, ".POSIX"))
2026 posix_pedantic = 1;
2027 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
2028 /* These default values are based on IEEE Std 1003.1-2008. */
2029 define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
2030 define_variable_cname ("CC", "c99", o_default, 0);
2031 define_variable_cname ("CFLAGS", "-O", o_default, 0);
2032 define_variable_cname ("FC", "fort77", o_default, 0);
2033 define_variable_cname ("FFLAGS", "-O 1", o_default, 0);
2034 define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
2036 else if (streq (name, ".SECONDEXPANSION"))
2037 second_expansion = 1;
2038 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
2039 else if (streq (name, ".ONESHELL"))
2040 one_shell = 1;
2041 #endif
2043 /* If this is a static pattern rule:
2044 'targets: target%pattern: prereq%pattern; recipe',
2045 make sure the pattern matches this target name. */
2046 if (pattern && !pattern_matches (pattern, pattern_percent, name))
2047 error (flocp, _("target '%s' doesn't match the target pattern"), name);
2048 else if (deps)
2049 /* If there are multiple targets, copy the chain DEPS for all but the
2050 last one. It is not safe for the same deps to go in more than one
2051 place in the database. */
2052 this = nextf != 0 ? copy_dep_chain (deps) : deps;
2054 /* Find or create an entry in the file database for this target. */
2055 if (!two_colon)
2057 /* Single-colon. Combine this rule with the file's existing record,
2058 if any. */
2059 f = enter_file (strcache_add (name));
2060 if (f->double_colon)
2061 fatal (flocp,
2062 _("target file '%s' has both : and :: entries"), f->name);
2064 /* If CMDS == F->CMDS, this target was listed in this rule
2065 more than once. Just give a warning since this is harmless. */
2066 if (cmds != 0 && cmds == f->cmds)
2067 error (flocp,
2068 _("target '%s' given more than once in the same rule."),
2069 f->name);
2071 /* Check for two single-colon entries both with commands.
2072 Check is_target so that we don't lose on files such as .c.o
2073 whose commands were preinitialized. */
2074 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2076 error (&cmds->fileinfo,
2077 _("warning: overriding recipe for target '%s'"),
2078 f->name);
2079 error (&f->cmds->fileinfo,
2080 _("warning: ignoring old recipe for target '%s'"),
2081 f->name);
2084 /* Defining .DEFAULT with no deps or cmds clears it. */
2085 if (f == default_file && this == 0 && cmds == 0)
2086 f->cmds = 0;
2087 if (cmds != 0)
2088 f->cmds = cmds;
2090 /* Defining .SUFFIXES with no dependencies clears out the list of
2091 suffixes. */
2092 if (f == suffix_file && this == 0)
2094 free_dep_chain (f->deps);
2095 f->deps = 0;
2098 else
2100 /* Double-colon. Make a new record even if there already is one. */
2101 f = lookup_file (name);
2103 /* Check for both : and :: rules. Check is_target so we don't lose
2104 on default suffix rules or makefiles. */
2105 if (f != 0 && f->is_target && !f->double_colon)
2106 fatal (flocp,
2107 _("target file '%s' has both : and :: entries"), f->name);
2109 f = enter_file (strcache_add (name));
2110 /* If there was an existing entry and it was a double-colon entry,
2111 enter_file will have returned a new one, making it the prev
2112 pointer of the old one, and setting its double_colon pointer to
2113 the first one. */
2114 if (f->double_colon == 0)
2115 /* This is the first entry for this name, so we must set its
2116 double_colon pointer to itself. */
2117 f->double_colon = f;
2119 f->cmds = cmds;
2122 f->is_target = 1;
2124 /* If this is a static pattern rule, set the stem to the part of its
2125 name that matched the '%' in the pattern, so you can use $* in the
2126 commands. If we didn't do it before, enter the prereqs now. */
2127 if (pattern)
2129 static const char *percent = "%";
2130 char *buffer = variable_expand ("");
2131 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2132 pattern_percent+1, percent+1);
2133 f->stem = strcache_add_len (buffer, o - buffer);
2134 if (this)
2136 if (! this->need_2nd_expansion)
2137 this = enter_prereqs (this, f->stem);
2138 else
2139 this->stem = f->stem;
2143 /* Add the dependencies to this file entry. */
2144 if (this != 0)
2146 /* Add the file's old deps and the new ones in THIS together. */
2147 if (f->deps == 0)
2148 f->deps = this;
2149 else if (cmds != 0)
2151 struct dep *d = this;
2153 /* If this rule has commands, put these deps first. */
2154 while (d->next != 0)
2155 d = d->next;
2157 d->next = f->deps;
2158 f->deps = this;
2160 else
2162 struct dep *d = f->deps;
2164 /* A rule without commands: put its prereqs at the end. */
2165 while (d->next != 0)
2166 d = d->next;
2168 d->next = this;
2172 name = f->name;
2174 /* All done! Set up for the next one. */
2175 if (nextf == 0)
2176 break;
2178 filenames = nextf;
2180 /* Reduce escaped percents. If there are any unescaped it's an error */
2181 name = filenames->name;
2182 if (find_percent_cached (&name))
2183 fatal (flocp, _("mixed implicit and normal rules"));
2187 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2188 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2189 Quoting backslashes are removed from STRING by compacting it into
2190 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2191 one, or nil if there are none. STOPCHARs inside variable references are
2192 ignored if IGNOREVARS is true.
2194 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2196 static char *
2197 find_char_unquote (char *string, int stop1, int stop2, int blank,
2198 int ignorevars)
2200 unsigned int string_len = 0;
2201 char *p = string;
2203 if (ignorevars)
2204 ignorevars = '$';
2206 while (1)
2208 if (stop2 && blank)
2209 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2210 && ! isblank ((unsigned char) *p))
2211 ++p;
2212 else if (stop2)
2213 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2214 ++p;
2215 else if (blank)
2216 while (*p != '\0' && *p != ignorevars && *p != stop1
2217 && ! isblank ((unsigned char) *p))
2218 ++p;
2219 else
2220 while (*p != '\0' && *p != ignorevars && *p != stop1)
2221 ++p;
2223 if (*p == '\0')
2224 break;
2226 /* If we stopped due to a variable reference, skip over its contents. */
2227 if (*p == ignorevars)
2229 char openparen = p[1];
2231 p += 2;
2233 /* Skip the contents of a non-quoted, multi-char variable ref. */
2234 if (openparen == '(' || openparen == '{')
2236 unsigned int pcount = 1;
2237 char closeparen = (openparen == '(' ? ')' : '}');
2239 while (*p)
2241 if (*p == openparen)
2242 ++pcount;
2243 else if (*p == closeparen)
2244 if (--pcount == 0)
2246 ++p;
2247 break;
2249 ++p;
2253 /* Skipped the variable reference: look for STOPCHARS again. */
2254 continue;
2257 if (p > string && p[-1] == '\\')
2259 /* Search for more backslashes. */
2260 int i = -2;
2261 while (&p[i] >= string && p[i] == '\\')
2262 --i;
2263 ++i;
2264 /* Only compute the length if really needed. */
2265 if (string_len == 0)
2266 string_len = strlen (string);
2267 /* The number of backslashes is now -I.
2268 Copy P over itself to swallow half of them. */
2269 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2270 p += i/2;
2271 if (i % 2 == 0)
2272 /* All the backslashes quoted each other; the STOPCHAR was
2273 unquoted. */
2274 return p;
2276 /* The STOPCHAR was quoted by a backslash. Look for another. */
2278 else
2279 /* No backslash in sight. */
2280 return p;
2283 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2284 return 0;
2287 /* Unescape a character in a string. The string is compressed onto itself. */
2289 static char *
2290 unescape_char (char *string, int c)
2292 char *p = string;
2293 char *s = string;
2295 while (*s != '\0')
2297 if (*s == '\\')
2299 char *e = s;
2300 int l;
2302 /* We found a backslash. See if it's escaping our character. */
2303 while (*e == '\\')
2304 ++e;
2305 l = e - s;
2307 if (*e != c || l%2 == 0)
2309 /* It's not; just take it all without unescaping. */
2310 memcpy (p, s, l);
2311 p += l;
2313 else if (l > 1)
2315 /* It is, and there's >1 backslash. Take half of them. */
2316 l /= 2;
2317 memcpy (p, s, l);
2318 p += l;
2320 s = e;
2323 *(p++) = *(s++);
2326 *p = '\0';
2327 return string;
2330 /* Search PATTERN for an unquoted % and handle quoting. */
2332 char *
2333 find_percent (char *pattern)
2335 return find_char_unquote (pattern, '%', 0, 0, 0);
2338 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2339 the % or NULL if no % was found.
2340 This version is used with strings in the string cache: if there's a need to
2341 modify the string a new version will be added to the string cache and
2342 *STRING will be set to that. */
2344 const char *
2345 find_percent_cached (const char **string)
2347 const char *p = *string;
2348 char *new = 0;
2349 int slen = 0;
2351 /* If the first char is a % return now. This lets us avoid extra tests
2352 inside the loop. */
2353 if (*p == '%')
2354 return p;
2356 while (1)
2358 while (*p != '\0' && *p != '%')
2359 ++p;
2361 if (*p == '\0')
2362 break;
2364 /* See if this % is escaped with a backslash; if not we're done. */
2365 if (p[-1] != '\\')
2366 break;
2369 /* Search for more backslashes. */
2370 char *pv;
2371 int i = -2;
2373 while (&p[i] >= *string && p[i] == '\\')
2374 --i;
2375 ++i;
2377 /* At this point we know we'll need to allocate a new string.
2378 Make a copy if we haven't yet done so. */
2379 if (! new)
2381 slen = strlen (*string);
2382 new = alloca (slen + 1);
2383 memcpy (new, *string, slen + 1);
2384 p = new + (p - *string);
2385 *string = new;
2388 /* At this point *string, p, and new all point into the same string.
2389 Get a non-const version of p so we can modify new. */
2390 pv = new + (p - *string);
2392 /* The number of backslashes is now -I.
2393 Copy P over itself to swallow half of them. */
2394 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2395 p += i/2;
2397 /* If the backslashes quoted each other; the % was unquoted. */
2398 if (i % 2 == 0)
2399 break;
2403 /* If we had to change STRING, add it to the strcache. */
2404 if (new)
2406 *string = strcache_add (*string);
2407 p = *string + (p - new);
2410 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2411 return (*p == '\0') ? NULL : p;
2414 /* Find the next line of text in an eval buffer, combining continuation lines
2415 into one line.
2416 Return the number of actual lines read (> 1 if continuation lines).
2417 Returns -1 if there's nothing left in the buffer.
2419 After this function, ebuf->buffer points to the first character of the
2420 line we just found.
2423 /* Read a line of text from a STRING.
2424 Since we aren't really reading from a file, don't bother with linenumbers.
2427 static unsigned long
2428 readstring (struct ebuffer *ebuf)
2430 char *eol;
2432 /* If there is nothing left in this buffer, return 0. */
2433 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2434 return -1;
2436 /* Set up a new starting point for the buffer, and find the end of the
2437 next logical line (taking into account backslash/newline pairs). */
2439 eol = ebuf->buffer = ebuf->bufnext;
2441 while (1)
2443 int backslash = 0;
2444 const char *bol = eol;
2445 const char *p;
2447 /* Find the next newline. At EOS, stop. */
2448 p = eol = strchr (eol , '\n');
2449 if (!eol)
2451 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2452 return 0;
2455 /* Found a newline; if it's escaped continue; else we're done. */
2456 while (p > bol && *(--p) == '\\')
2457 backslash = !backslash;
2458 if (!backslash)
2459 break;
2460 ++eol;
2463 /* Overwrite the newline char. */
2464 *eol = '\0';
2465 ebuf->bufnext = eol+1;
2467 return 0;
2470 static long
2471 readline (struct ebuffer *ebuf)
2473 char *p;
2474 char *end;
2475 char *start;
2476 long nlines = 0;
2478 /* The behaviors between string and stream buffers are different enough to
2479 warrant different functions. Do the Right Thing. */
2481 if (!ebuf->fp)
2482 return readstring (ebuf);
2484 /* When reading from a file, we always start over at the beginning of the
2485 buffer for each new line. */
2487 p = start = ebuf->bufstart;
2488 end = p + ebuf->size;
2489 *p = '\0';
2491 while (fgets (p, end - p, ebuf->fp) != 0)
2493 char *p2;
2494 unsigned long len;
2495 int backslash;
2497 len = strlen (p);
2498 if (len == 0)
2500 /* This only happens when the first thing on the line is a '\0'.
2501 It is a pretty hopeless case, but (wonder of wonders) Athena
2502 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2503 There is nothing really to be done; we synthesize a newline so
2504 the following line doesn't appear to be part of this line. */
2505 error (&ebuf->floc,
2506 _("warning: NUL character seen; rest of line ignored"));
2507 p[0] = '\n';
2508 len = 1;
2511 /* Jump past the text we just read. */
2512 p += len;
2514 /* If the last char isn't a newline, the whole line didn't fit into the
2515 buffer. Get some more buffer and try again. */
2516 if (p[-1] != '\n')
2517 goto more_buffer;
2519 /* We got a newline, so add one to the count of lines. */
2520 ++nlines;
2522 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2523 /* Check to see if the line was really ended with CRLF; if so ignore
2524 the CR. */
2525 if ((p - start) > 1 && p[-2] == '\r')
2527 --p;
2528 p[-1] = '\n';
2530 #endif
2532 backslash = 0;
2533 for (p2 = p - 2; p2 >= start; --p2)
2535 if (*p2 != '\\')
2536 break;
2537 backslash = !backslash;
2540 if (!backslash)
2542 p[-1] = '\0';
2543 break;
2546 /* It was a backslash/newline combo. If we have more space, read
2547 another line. */
2548 if (end - p >= 80)
2549 continue;
2551 /* We need more space at the end of our buffer, so realloc it.
2552 Make sure to preserve the current offset of p. */
2553 more_buffer:
2555 unsigned long off = p - start;
2556 ebuf->size *= 2;
2557 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2558 p = start + off;
2559 end = start + ebuf->size;
2560 *p = '\0';
2564 if (ferror (ebuf->fp))
2565 pfatal_with_name (ebuf->floc.filenm);
2567 /* If we found some lines, return how many.
2568 If we didn't, but we did find _something_, that indicates we read the last
2569 line of a file with no final newline; return 1.
2570 If we read nothing, we're at EOF; return -1. */
2572 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2575 /* Parse the next "makefile word" from the input buffer, and return info
2576 about it.
2578 A "makefile word" is one of:
2580 w_bogus Should never happen
2581 w_eol End of input
2582 w_static A static word; cannot be expanded
2583 w_variable A word containing one or more variables/functions
2584 w_colon A colon
2585 w_dcolon A double-colon
2586 w_semicolon A semicolon
2587 w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
2589 Note that this function is only used when reading certain parts of the
2590 makefile. Don't use it where special rules hold sway (RHS of a variable,
2591 in a command list, etc.) */
2593 static enum make_word_type
2594 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2596 enum make_word_type wtype = w_bogus;
2597 char *p = buffer, *beg;
2598 char c;
2600 /* Skip any leading whitespace. */
2601 while (isblank ((unsigned char)*p))
2602 ++p;
2604 beg = p;
2605 c = *(p++);
2606 switch (c)
2608 case '\0':
2609 wtype = w_eol;
2610 break;
2612 case ';':
2613 wtype = w_semicolon;
2614 break;
2616 case '=':
2617 wtype = w_varassign;
2618 break;
2620 case ':':
2621 wtype = w_colon;
2622 switch (*p)
2624 case ':':
2625 ++p;
2626 if (p[1] != '=')
2627 wtype = w_dcolon;
2628 else
2630 wtype = w_varassign;
2631 ++p;
2633 break;
2635 case '=':
2636 ++p;
2637 wtype = w_varassign;
2638 break;
2640 break;
2642 case '+':
2643 case '?':
2644 case '!':
2645 if (*p == '=')
2647 ++p;
2648 wtype = w_varassign;
2649 break;
2652 default:
2653 if (delim && strchr (delim, c))
2654 wtype = w_static;
2655 break;
2658 /* Did we find something? If so, return now. */
2659 if (wtype != w_bogus)
2660 goto done;
2662 /* This is some non-operator word. A word consists of the longest
2663 string of characters that doesn't contain whitespace, one of [:=#],
2664 or [?+!]=, or one of the chars in the DELIM string. */
2666 /* We start out assuming a static word; if we see a variable we'll
2667 adjust our assumptions then. */
2668 wtype = w_static;
2670 /* We already found the first value of "c", above. */
2671 while (1)
2673 char closeparen;
2674 int count;
2676 switch (c)
2678 case '\0':
2679 case ' ':
2680 case '\t':
2681 case '=':
2682 goto done_word;
2684 case ':':
2685 #ifdef HAVE_DOS_PATHS
2686 /* A word CAN include a colon in its drive spec. The drive
2687 spec is allowed either at the beginning of a word, or as part
2688 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2689 if (!(p - beg >= 2
2690 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2691 && (p - beg == 2 || p[-3] == '(')))
2692 #endif
2693 goto done_word;
2695 case '$':
2696 c = *(p++);
2697 if (c == '$')
2698 break;
2700 /* This is a variable reference, so note that it's expandable.
2701 Then read it to the matching close paren. */
2702 wtype = w_variable;
2704 if (c == '(')
2705 closeparen = ')';
2706 else if (c == '{')
2707 closeparen = '}';
2708 else
2709 /* This is a single-letter variable reference. */
2710 break;
2712 for (count=0; *p != '\0'; ++p)
2714 if (*p == c)
2715 ++count;
2716 else if (*p == closeparen && --count < 0)
2718 ++p;
2719 break;
2722 break;
2724 case '?':
2725 case '+':
2726 if (*p == '=')
2727 goto done_word;
2728 break;
2730 case '\\':
2731 switch (*p)
2733 case ':':
2734 case ';':
2735 case '=':
2736 case '\\':
2737 ++p;
2738 break;
2740 break;
2742 default:
2743 if (delim && strchr (delim, c))
2744 goto done_word;
2745 break;
2748 c = *(p++);
2750 done_word:
2751 --p;
2753 done:
2754 if (startp)
2755 *startp = beg;
2756 if (length)
2757 *length = p - beg;
2758 return wtype;
2761 /* Construct the list of include directories
2762 from the arguments and the default list. */
2764 void
2765 construct_include_path (const char **arg_dirs)
2767 #ifdef VAXC /* just don't ask ... */
2768 stat_t stbuf;
2769 #else
2770 struct stat stbuf;
2771 #endif
2772 const char **dirs;
2773 const char **cpp;
2774 unsigned int idx;
2776 /* Compute the number of pointers we need in the table. */
2777 idx = sizeof (default_include_directories) / sizeof (const char *);
2778 if (arg_dirs)
2779 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2780 ++idx;
2782 #ifdef __MSDOS__
2783 /* Add one for $DJDIR. */
2784 ++idx;
2785 #endif
2787 dirs = xmalloc (idx * sizeof (const char *));
2789 idx = 0;
2790 max_incl_len = 0;
2792 /* First consider any dirs specified with -I switches.
2793 Ignore any that don't exist. Remember the maximum string length. */
2795 if (arg_dirs)
2796 while (*arg_dirs != 0)
2798 const char *dir = *(arg_dirs++);
2799 char *expanded = 0;
2800 int e;
2802 if (dir[0] == '~')
2804 expanded = tilde_expand (dir);
2805 if (expanded != 0)
2806 dir = expanded;
2809 EINTRLOOP (e, stat (dir, &stbuf));
2810 if (e == 0 && S_ISDIR (stbuf.st_mode))
2812 unsigned int len = strlen (dir);
2813 /* If dir name is written with trailing slashes, discard them. */
2814 while (len > 1 && dir[len - 1] == '/')
2815 --len;
2816 if (len > max_incl_len)
2817 max_incl_len = len;
2818 dirs[idx++] = strcache_add_len (dir, len);
2821 if (expanded)
2822 free (expanded);
2825 /* Now add the standard default dirs at the end. */
2827 #ifdef __MSDOS__
2829 /* The environment variable $DJDIR holds the root of the DJGPP directory
2830 tree; add ${DJDIR}/include. */
2831 struct variable *djdir = lookup_variable ("DJDIR", 5);
2833 if (djdir)
2835 unsigned int len = strlen (djdir->value) + 8;
2836 char *defdir = alloca (len + 1);
2838 strcat (strcpy (defdir, djdir->value), "/include");
2839 dirs[idx++] = strcache_add (defdir);
2841 if (len > max_incl_len)
2842 max_incl_len = len;
2845 #endif
2847 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2849 int e;
2851 EINTRLOOP (e, stat (*cpp, &stbuf));
2852 if (e == 0 && S_ISDIR (stbuf.st_mode))
2854 unsigned int len = strlen (*cpp);
2855 /* If dir name is written with trailing slashes, discard them. */
2856 while (len > 1 && (*cpp)[len - 1] == '/')
2857 --len;
2858 if (len > max_incl_len)
2859 max_incl_len = len;
2860 dirs[idx++] = strcache_add_len (*cpp, len);
2864 dirs[idx] = 0;
2866 /* Now add each dir to the .INCLUDE_DIRS variable. */
2868 for (cpp = dirs; *cpp != 0; ++cpp)
2869 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2870 o_default, f_append, 0);
2872 include_directories = dirs;
2875 /* Expand ~ or ~USER at the beginning of NAME.
2876 Return a newly malloc'd string or 0. */
2878 char *
2879 tilde_expand (const char *name)
2881 #ifndef VMS
2882 if (name[1] == '/' || name[1] == '\0')
2884 extern char *getenv ();
2885 char *home_dir;
2886 int is_variable;
2889 /* Turn off --warn-undefined-variables while we expand HOME. */
2890 int save = warn_undefined_variables_flag;
2891 warn_undefined_variables_flag = 0;
2893 home_dir = allocated_variable_expand ("$(HOME)");
2895 warn_undefined_variables_flag = save;
2898 is_variable = home_dir[0] != '\0';
2899 if (!is_variable)
2901 free (home_dir);
2902 home_dir = getenv ("HOME");
2904 # if !defined(_AMIGA) && !defined(WINDOWS32)
2905 if (home_dir == 0 || home_dir[0] == '\0')
2907 extern char *getlogin ();
2908 char *logname = getlogin ();
2909 home_dir = 0;
2910 if (logname != 0)
2912 struct passwd *p = getpwnam (logname);
2913 if (p != 0)
2914 home_dir = p->pw_dir;
2917 # endif /* !AMIGA && !WINDOWS32 */
2918 if (home_dir != 0)
2920 char *new = xstrdup (concat (2, home_dir, name + 1));
2921 if (is_variable)
2922 free (home_dir);
2923 return new;
2926 # if !defined(_AMIGA) && !defined(WINDOWS32)
2927 else
2929 struct passwd *pwent;
2930 char *userend = strchr (name + 1, '/');
2931 if (userend != 0)
2932 *userend = '\0';
2933 pwent = getpwnam (name + 1);
2934 if (pwent != 0)
2936 if (userend == 0)
2937 return xstrdup (pwent->pw_dir);
2938 else
2939 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2941 else if (userend != 0)
2942 *userend = '/';
2944 # endif /* !AMIGA && !WINDOWS32 */
2945 #endif /* !VMS */
2946 return 0;
2949 /* Parse a string into a sequence of filenames represented as a chain of
2950 struct nameseq's and return that chain. Optionally expand the strings via
2951 glob().
2953 The string is passed as STRINGP, the address of a string pointer.
2954 The string pointer is updated to point at the first character
2955 not parsed, which either is a null char or equals STOPCHAR.
2957 SIZE is how big to construct chain elements.
2958 This is useful if we want them actually to be other structures
2959 that have room for additional info.
2961 PREFIX, if non-null, is added to the beginning of each filename.
2963 FLAGS allows one or more of the following bitflags to be set:
2964 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2965 PARSEFS_NOAR - Do not check filenames for archive references
2966 PARSEFS_NOGLOB - Do not expand globbing characters
2967 PARSEFS_EXISTS - Only return globbed files that actually exist
2968 (cannot also set NOGLOB)
2969 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2972 void *
2973 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2974 const char *prefix, int flags)
2976 extern void dir_setup_glob (glob_t *glob);
2978 /* tmp points to tmpbuf after the prefix, if any.
2979 tp is the end of the buffer. */
2980 static char *tmpbuf = NULL;
2981 static int tmpbuf_len = 0;
2983 int cachep = (! (flags & PARSEFS_NOCACHE));
2985 struct nameseq *new = 0;
2986 struct nameseq **newp = &new;
2987 #define NEWELT(_n) do { \
2988 const char *__n = (_n); \
2989 *newp = xcalloc (size); \
2990 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2991 newp = &(*newp)->next; \
2992 } while(0)
2994 char *p;
2995 glob_t gl;
2996 char *tp;
2998 #ifdef VMS
2999 # define VMS_COMMA ','
3000 #else
3001 # define VMS_COMMA 0
3002 #endif
3004 if (size < sizeof (struct nameseq))
3005 size = sizeof (struct nameseq);
3007 if (! (flags & PARSEFS_NOGLOB))
3008 dir_setup_glob (&gl);
3010 /* Get enough temporary space to construct the largest possible target. */
3012 int l = strlen (*stringp) + 1;
3013 if (l > tmpbuf_len)
3015 tmpbuf = xrealloc (tmpbuf, l);
3016 tmpbuf_len = l;
3019 tp = tmpbuf;
3021 /* Parse STRING. P will always point to the end of the parsed content. */
3022 p = *stringp;
3023 while (1)
3025 const char *name;
3026 const char **nlist = 0;
3027 char *tildep = 0;
3028 int globme = 1;
3029 #ifndef NO_ARCHIVES
3030 char *arname = 0;
3031 char *memname = 0;
3032 #endif
3033 char *s;
3034 int nlen;
3035 int i;
3037 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
3038 p = next_token (p);
3039 if (*p == '\0' || *p == stopchar)
3040 break;
3042 /* There are names left, so find the end of the next name.
3043 Throughout this iteration S points to the start. */
3044 s = p;
3045 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
3046 #ifdef VMS
3047 /* convert comma separated list to space separated */
3048 if (p && *p == ',')
3049 *p =' ';
3050 #endif
3051 #ifdef _AMIGA
3052 if (stopchar == ':' && p && *p == ':'
3053 && !(isspace ((unsigned char)p[1]) || !p[1]
3054 || isspace ((unsigned char)p[-1])))
3055 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
3056 #endif
3057 #ifdef HAVE_DOS_PATHS
3058 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
3059 first colon which isn't followed by a slash or a backslash.
3060 Note that tokens separated by spaces should be treated as separate
3061 tokens since make doesn't allow path names with spaces */
3062 if (stopchar == ':')
3063 while (p != 0 && !isspace ((unsigned char)*p) &&
3064 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
3065 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
3066 #endif
3067 if (p == 0)
3068 p = s + strlen (s);
3070 /* Strip leading "this directory" references. */
3071 if (! (flags & PARSEFS_NOSTRIP))
3072 #ifdef VMS
3073 /* Skip leading '[]'s. */
3074 while (p - s > 2 && s[0] == '[' && s[1] == ']')
3075 #else
3076 /* Skip leading './'s. */
3077 while (p - s > 2 && s[0] == '.' && s[1] == '/')
3078 #endif
3080 /* Skip "./" and all following slashes. */
3081 s += 2;
3082 while (*s == '/')
3083 ++s;
3086 /* Extract the filename just found, and skip it.
3087 Set NAME to the string, and NLEN to its length. */
3089 if (s == p)
3091 /* The name was stripped to empty ("./"). */
3092 #if defined(VMS)
3093 continue;
3094 #elif defined(_AMIGA)
3095 /* PDS-- This cannot be right!! */
3096 tp[0] = '\0';
3097 nlen = 0;
3098 #else
3099 tp[0] = '.';
3100 tp[1] = '/';
3101 tp[2] = '\0';
3102 nlen = 2;
3103 #endif
3105 else
3107 #ifdef VMS
3108 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
3109 * to remove this '\' before we can use the filename.
3110 * xstrdup called because S may be read-only string constant.
3112 char *n = tp;
3113 while (s < p)
3115 if (s[0] == '\\' && s[1] == ':')
3116 ++s;
3117 *(n++) = *(s++);
3119 n[0] = '\0';
3120 nlen = strlen (tp);
3121 #else
3122 nlen = p - s;
3123 memcpy (tp, s, nlen);
3124 tp[nlen] = '\0';
3125 #endif
3128 /* At this point, TP points to the element and NLEN is its length. */
3130 #ifndef NO_ARCHIVES
3131 /* If this is the start of an archive group that isn't complete, set up
3132 to add the archive prefix for future files. A file list like:
3133 "libf.a(x.o y.o z.o)" needs to be expanded as:
3134 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3136 TP == TMP means we're not already in an archive group. Ignore
3137 something starting with '(', as that cannot actually be an
3138 archive-member reference (and treating it as such results in an empty
3139 file name, which causes much lossage). Also if it ends in ")" then
3140 it's a complete reference so we don't need to treat it specially.
3142 Finally, note that archive groups must end with ')' as the last
3143 character, so ensure there's some word ending like that before
3144 considering this an archive group. */
3145 if (! (flags & PARSEFS_NOAR)
3146 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3148 char *n = strchr (tp, '(');
3149 if (n)
3151 /* This looks like the first element in an open archive group.
3152 A valid group MUST have ')' as the last character. */
3153 const char *e = p;
3156 const char *o = e;
3157 e = next_token (e);
3158 /* Find the end of this word. We don't want to unquote and
3159 we don't care about quoting since we're looking for the
3160 last char in the word. */
3161 while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3162 && ! isblank ((unsigned char) *e))
3163 ++e;
3164 /* If we didn't move, we're done now. */
3165 if (e == o)
3166 break;
3167 if (e[-1] == ')')
3169 /* Found the end, so this is the first element in an
3170 open archive group. It looks like "lib(mem".
3171 Reset TP past the open paren. */
3172 nlen -= (n + 1) - tp;
3173 tp = n + 1;
3175 /* We can stop looking now. */
3176 break;
3179 while (*e != '\0');
3181 /* If we have just "lib(", part of something like "lib( a b)",
3182 go to the next item. */
3183 if (! nlen)
3184 continue;
3188 /* If we are inside an archive group, make sure it has an end. */
3189 if (tp > tmpbuf)
3191 if (tp[nlen-1] == ')')
3193 /* This is the natural end; reset TP. */
3194 tp = tmpbuf;
3196 /* This is just ")", something like "lib(a b )": skip it. */
3197 if (nlen == 1)
3198 continue;
3200 else
3202 /* Not the end, so add a "fake" end. */
3203 tp[nlen++] = ')';
3204 tp[nlen] = '\0';
3207 #endif
3209 /* If we're not globbing we're done: add it to the end of the chain.
3210 Go to the next item in the string. */
3211 if (flags & PARSEFS_NOGLOB)
3213 NEWELT (concat (2, prefix, tmpbuf));
3214 continue;
3217 /* If we get here we know we're doing glob expansion.
3218 TP is a string in tmpbuf. NLEN is no longer used.
3219 We may need to do more work: after this NAME will be set. */
3220 name = tmpbuf;
3222 /* Expand tilde if applicable. */
3223 if (tmpbuf[0] == '~')
3225 tildep = tilde_expand (tmpbuf);
3226 if (tildep != 0)
3227 name = tildep;
3230 #ifndef NO_ARCHIVES
3231 /* If NAME is an archive member reference replace it with the archive
3232 file name, and save the member name in MEMNAME. We will glob on the
3233 archive name and then reattach MEMNAME later. */
3234 if (! (flags & PARSEFS_NOAR) && ar_name (name))
3236 ar_parse_name (name, &arname, &memname);
3237 name = arname;
3239 #endif /* !NO_ARCHIVES */
3241 /* glob() is expensive: don't call it unless we need to. */
3242 if (!(flags & PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3244 globme = 0;
3245 i = 1;
3246 nlist = &name;
3248 else
3249 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3251 case GLOB_NOSPACE:
3252 fatal (NILF, _("virtual memory exhausted"));
3254 case 0:
3255 /* Success. */
3256 i = gl.gl_pathc;
3257 nlist = (const char **)gl.gl_pathv;
3258 break;
3260 case GLOB_NOMATCH:
3261 /* If we want only existing items, skip this one. */
3262 if (flags & PARSEFS_EXISTS)
3264 i = 0;
3265 break;
3267 /* FALLTHROUGH */
3269 default:
3270 /* By default keep this name. */
3271 i = 1;
3272 nlist = &name;
3273 break;
3276 /* For each matched element, add it to the list. */
3277 while (i-- > 0)
3278 #ifndef NO_ARCHIVES
3279 if (memname != 0)
3281 /* Try to glob on MEMNAME within the archive. */
3282 struct nameseq *found = ar_glob (nlist[i], memname, size);
3283 if (! found)
3284 /* No matches. Use MEMNAME as-is. */
3285 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3286 else
3288 /* We got a chain of items. Attach them. */
3289 if (*newp)
3290 (*newp)->next = found;
3291 else
3292 *newp = found;
3294 /* Find and set the new end. Massage names if necessary. */
3295 while (1)
3297 if (! cachep)
3298 found->name = xstrdup (concat (2, prefix, name));
3299 else if (prefix)
3300 found->name = strcache_add (concat (2, prefix, name));
3302 if (found->next == 0)
3303 break;
3305 found = found->next;
3307 newp = &found->next;
3310 else
3311 #endif /* !NO_ARCHIVES */
3312 NEWELT (concat (2, prefix, nlist[i]));
3314 if (globme)
3315 globfree (&gl);
3317 #ifndef NO_ARCHIVES
3318 if (arname)
3319 free (arname);
3320 #endif
3322 if (tildep)
3323 free (tildep);
3326 *stringp = p;
3327 return new;