* Fixups to the make man page
[make.git] / read.c
blob761e9763b60efc78881a9ec0be943feaf1727fd9
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, 2008, 2009,
4 2010 Free Software 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 undefine_v:1;
66 unsigned int export_v:1;
67 unsigned int override_v:1;
68 unsigned int private_v:1;
71 /* Types of "words" that can be read in a makefile. */
72 enum make_word_type
74 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
75 w_varassign
79 /* A `struct conditionals' contains the information describing
80 all the active conditionals in a makefile.
82 The global variable `conditionals' contains the conditionals
83 information for the current makefile. It is initialized from
84 the static structure `toplevel_conditionals' and is later changed
85 to new structures for included makefiles. */
87 struct conditionals
89 unsigned int if_cmds; /* Depth of conditional nesting. */
90 unsigned int allocated; /* Elts allocated in following arrays. */
91 char *ignoring; /* Are we ignoring or interpreting?
92 0=interpreting, 1=not yet interpreted,
93 2=already interpreted */
94 char *seen_else; /* Have we already seen an `else'? */
97 static struct conditionals toplevel_conditionals;
98 static struct conditionals *conditionals = &toplevel_conditionals;
101 /* Default directories to search for include files in */
103 static const char *default_include_directories[] =
105 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
106 /* This completely up to the user when they install MSVC or other packages.
107 This is defined as a placeholder. */
108 # define INCLUDEDIR "."
109 #endif
110 INCLUDEDIR,
111 #ifndef _AMIGA
112 "/usr/gnu/include",
113 "/usr/local/include",
114 "/usr/include",
115 #endif
119 /* List of directories to search for include files in */
121 static const char **include_directories;
123 /* Maximum length of an element of the above. */
125 static unsigned int max_incl_len;
127 /* The filename and pointer to line number of the
128 makefile currently being read in. */
130 const struct floc *reading_file = 0;
132 /* The chain of makefiles read by read_makefile. */
134 static struct dep *read_makefiles = 0;
136 static int eval_makefile (const char *filename, int flags);
137 static void eval (struct ebuffer *buffer, int flags);
139 static long readline (struct ebuffer *ebuf);
140 static void do_undefine (char *name, enum variable_origin origin,
141 struct ebuffer *ebuf);
142 static struct variable *do_define (char *name, enum variable_origin origin,
143 struct ebuffer *ebuf);
144 static int conditional_line (char *line, int len, const struct floc *flocp);
145 static void record_files (struct nameseq *filenames, const char *pattern,
146 const char *pattern_percent, char *depstr,
147 unsigned int cmds_started, char *commands,
148 unsigned int commands_idx, int two_colon,
149 char prefix, const struct floc *flocp);
150 static void record_target_var (struct nameseq *filenames, char *defn,
151 enum variable_origin origin,
152 struct vmodifiers *vmod,
153 const struct floc *flocp);
154 static enum make_word_type get_next_mword (char *buffer, char *delim,
155 char **startp, unsigned int *length);
156 static void remove_comments (char *line);
157 static char *find_char_unquote (char *string, int stop1, int stop2,
158 int blank, int ignorevars);
161 /* Compare a word, both length and contents.
162 P must point to the word to be tested, and WLEN must be the length.
164 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
167 /* Read in all the makefiles and return the chain of their names. */
169 struct dep *
170 read_all_makefiles (const char **makefiles)
172 unsigned int num_makefiles = 0;
174 /* Create *_LIST variables, to hold the makefiles, targets, and variables
175 we will be reading. */
177 define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
179 DB (DB_BASIC, (_("Reading makefiles...\n")));
181 /* If there's a non-null variable MAKEFILES, its value is a list of
182 files to read first thing. But don't let it prevent reading the
183 default makefiles and don't let the default goal come from there. */
186 char *value;
187 char *name, *p;
188 unsigned int length;
191 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
192 int save = warn_undefined_variables_flag;
193 warn_undefined_variables_flag = 0;
195 value = allocated_variable_expand ("$(MAKEFILES)");
197 warn_undefined_variables_flag = save;
200 /* Set NAME to the start of next token and LENGTH to its length.
201 MAKEFILES is updated for finding remaining tokens. */
202 p = value;
204 while ((name = find_next_token ((const char **)&p, &length)) != 0)
206 if (*p != '\0')
207 *p++ = '\0';
208 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
211 free (value);
214 /* Read makefiles specified with -f switches. */
216 if (makefiles != 0)
217 while (*makefiles != 0)
219 struct dep *tail = read_makefiles;
220 register struct dep *d;
222 if (! eval_makefile (*makefiles, 0))
223 perror_with_name ("", *makefiles);
225 /* Find the right element of read_makefiles. */
226 d = read_makefiles;
227 while (d->next != tail)
228 d = d->next;
230 /* Use the storage read_makefile allocates. */
231 *makefiles = dep_name (d);
232 ++num_makefiles;
233 ++makefiles;
236 /* If there were no -f switches, try the default names. */
238 if (num_makefiles == 0)
240 static char *default_makefiles[] =
241 #ifdef VMS
242 /* all lower case since readdir() (the vms version) 'lowercasifies' */
243 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
244 #else
245 #ifdef _AMIGA
246 { "GNUmakefile", "Makefile", "SMakefile", 0 };
247 #else /* !Amiga && !VMS */
248 { "GNUmakefile", "makefile", "Makefile", 0 };
249 #endif /* AMIGA */
250 #endif /* VMS */
251 register char **p = default_makefiles;
252 while (*p != 0 && !file_exists_p (*p))
253 ++p;
255 if (*p != 0)
257 if (! eval_makefile (*p, 0))
258 perror_with_name ("", *p);
260 else
262 /* No default makefile was found. Add the default makefiles to the
263 `read_makefiles' chain so they will be updated if possible. */
264 struct dep *tail = read_makefiles;
265 /* Add them to the tail, after any MAKEFILES variable makefiles. */
266 while (tail != 0 && tail->next != 0)
267 tail = tail->next;
268 for (p = default_makefiles; *p != 0; ++p)
270 struct dep *d = alloc_dep ();
271 d->file = enter_file (strcache_add (*p));
272 d->dontcare = 1;
273 /* Tell update_goal_chain to bail out as soon as this file is
274 made, and main not to die if we can't make this file. */
275 d->changed = RM_DONTCARE;
276 if (tail == 0)
277 read_makefiles = d;
278 else
279 tail->next = d;
280 tail = d;
282 if (tail != 0)
283 tail->next = 0;
287 return read_makefiles;
290 /* Install a new conditional and return the previous one. */
292 static struct conditionals *
293 install_conditionals (struct conditionals *new)
295 struct conditionals *save = conditionals;
297 memset (new, '\0', sizeof (*new));
298 conditionals = new;
300 return save;
303 /* Free the current conditionals and reinstate a saved one. */
305 static void
306 restore_conditionals (struct conditionals *saved)
308 /* Free any space allocated by conditional_line. */
309 if (conditionals->ignoring)
310 free (conditionals->ignoring);
311 if (conditionals->seen_else)
312 free (conditionals->seen_else);
314 /* Restore state. */
315 conditionals = saved;
318 static int
319 eval_makefile (const char *filename, int flags)
321 struct dep *deps;
322 struct ebuffer ebuf;
323 const struct floc *curfile;
324 char *expanded = 0;
325 int makefile_errno;
327 filename = strcache_add (filename);
328 ebuf.floc.filenm = filename;
329 ebuf.floc.lineno = 1;
331 if (ISDB (DB_VERBOSE))
333 printf (_("Reading makefile `%s'"), filename);
334 if (flags & RM_NO_DEFAULT_GOAL)
335 printf (_(" (no default goal)"));
336 if (flags & RM_INCLUDED)
337 printf (_(" (search path)"));
338 if (flags & RM_DONTCARE)
339 printf (_(" (don't care)"));
340 if (flags & RM_NO_TILDE)
341 printf (_(" (no ~ expansion)"));
342 puts ("...");
345 /* First, get a stream to read. */
347 /* Expand ~ in FILENAME unless it came from `include',
348 in which case it was already done. */
349 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
351 expanded = tilde_expand (filename);
352 if (expanded != 0)
353 filename = expanded;
356 ebuf.fp = fopen (filename, "r");
357 /* Save the error code so we print the right message later. */
358 makefile_errno = errno;
360 /* If the makefile wasn't found and it's either a makefile from
361 the `MAKEFILES' variable or an included makefile,
362 search the included makefile search path for this makefile. */
363 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
365 unsigned int i;
366 for (i = 0; include_directories[i] != 0; ++i)
368 const char *included = concat (3, include_directories[i],
369 "/", filename);
370 ebuf.fp = fopen (included, "r");
371 if (ebuf.fp)
373 filename = strcache_add (included);
374 break;
379 /* Add FILENAME to the chain of read makefiles. */
380 deps = alloc_dep ();
381 deps->next = read_makefiles;
382 read_makefiles = deps;
383 deps->file = lookup_file (filename);
384 if (deps->file == 0)
385 deps->file = enter_file (filename);
386 filename = deps->file->name;
387 deps->changed = flags;
388 if (flags & RM_DONTCARE)
389 deps->dontcare = 1;
391 if (expanded)
392 free (expanded);
394 /* If the makefile can't be found at all, give up entirely. */
396 if (ebuf.fp == 0)
398 /* If we did some searching, errno has the error from the last
399 attempt, rather from FILENAME itself. Restore it in case the
400 caller wants to use it in a message. */
401 errno = makefile_errno;
402 return 0;
405 /* Set close-on-exec to avoid leaking the makefile to children, such as
406 $(shell ...). */
407 #ifdef HAVE_FILENO
408 CLOSE_ON_EXEC (fileno (ebuf.fp));
409 #endif
411 /* Add this makefile to the list. */
412 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
413 f_append, 0);
415 /* Evaluate the makefile */
417 ebuf.size = 200;
418 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
420 curfile = reading_file;
421 reading_file = &ebuf.floc;
423 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
425 reading_file = curfile;
427 fclose (ebuf.fp);
429 free (ebuf.bufstart);
430 alloca (0);
432 return 1;
435 void
436 eval_buffer (char *buffer)
438 struct ebuffer ebuf;
439 struct conditionals *saved;
440 struct conditionals new;
441 const struct floc *curfile;
443 /* Evaluate the buffer */
445 ebuf.size = strlen (buffer);
446 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
447 ebuf.fp = NULL;
449 if (reading_file)
450 ebuf.floc = *reading_file;
451 else
452 ebuf.floc.filenm = NULL;
454 curfile = reading_file;
455 reading_file = &ebuf.floc;
457 saved = install_conditionals (&new);
459 eval (&ebuf, 1);
461 restore_conditionals (saved);
463 reading_file = curfile;
465 alloca (0);
468 /* Check LINE to see if it's a variable assignment or undefine.
470 It might use one of the modifiers "export", "override", "private", or it
471 might be one of the conditional tokens like "ifdef", "include", etc.
473 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
474 Returns LINE.
476 Returns a pointer to the first non-modifier character, and sets VMOD
477 based on the modifiers found if any, plus V_ASSIGN is 1.
479 static char *
480 parse_var_assignment (const char *line, struct vmodifiers *vmod)
482 const char *p;
483 memset (vmod, '\0', sizeof (*vmod));
485 /* Find the start of the next token. If there isn't one we're done. */
486 line = next_token (line);
487 if (*line == '\0')
488 return (char *)line;
490 p = line;
491 while (1)
493 int wlen;
494 const char *p2;
495 enum variable_flavor flavor;
497 p2 = parse_variable_definition (p, &flavor);
499 /* If this is a variable assignment, we're done. */
500 if (p2)
501 break;
503 /* It's not a variable; see if it's a modifier. */
504 p2 = end_of_token (p);
505 wlen = p2 - p;
507 if (word1eq ("export"))
508 vmod->export_v = 1;
509 else if (word1eq ("override"))
510 vmod->override_v = 1;
511 else if (word1eq ("private"))
512 vmod->private_v = 1;
513 else if (word1eq ("define"))
515 /* We can't have modifiers after 'define' */
516 vmod->define_v = 1;
517 p = next_token (p2);
518 break;
520 else if (word1eq ("undefine"))
522 /* We can't have modifiers after 'undefine' */
523 vmod->undefine_v = 1;
524 p = next_token (p2);
525 break;
527 else
528 /* Not a variable or modifier: this is not a variable assignment. */
529 return (char *)line;
531 /* It was a modifier. Try the next word. */
532 p = next_token (p2);
533 if (*p == '\0')
534 return (char *)line;
537 /* Found a variable assignment or undefine. */
538 vmod->assign_v = 1;
539 return (char *)p;
543 /* Read file FILENAME as a makefile and add its contents to the data base.
545 SET_DEFAULT is true if we are allowed to set the default goal. */
547 static void
548 eval (struct ebuffer *ebuf, int set_default)
550 char *collapsed = 0;
551 unsigned int collapsed_length = 0;
552 unsigned int commands_len = 200;
553 char *commands;
554 unsigned int commands_idx = 0;
555 unsigned int cmds_started, tgts_started;
556 int ignoring = 0, in_ignored_define = 0;
557 int no_targets = 0; /* Set when reading a rule without targets. */
558 struct nameseq *filenames = 0;
559 char *depstr = 0;
560 long nlines = 0;
561 int two_colon = 0;
562 char prefix;
563 const char *pattern = 0;
564 const char *pattern_percent;
565 struct floc *fstart;
566 struct floc fi;
568 #define record_waiting_files() \
569 do \
571 if (filenames != 0) \
573 fi.lineno = tgts_started; \
574 record_files (filenames, pattern, pattern_percent, depstr, \
575 cmds_started, commands, commands_idx, two_colon, \
576 prefix, &fi); \
577 filenames = 0; \
579 commands_idx = 0; \
580 no_targets = 0; \
581 pattern = 0; \
582 } while (0)
584 pattern_percent = 0;
585 cmds_started = tgts_started = 1;
587 fstart = &ebuf->floc;
588 fi.filenm = ebuf->floc.filenm;
590 /* Loop over lines in the file.
591 The strategy is to accumulate target names in FILENAMES, dependencies
592 in DEPS and commands in COMMANDS. These are used to define a rule
593 when the start of the next rule (or eof) is encountered.
595 When you see a "continue" in the loop below, that means we are moving on
596 to the next line _without_ ending any rule that we happen to be working
597 with at the moment. If you see a "goto rule_complete", then the
598 statement we just parsed also finishes the previous rule. */
600 commands = xmalloc (200);
602 while (1)
604 unsigned int linelen;
605 char *line;
606 unsigned int wlen;
607 char *p;
608 char *p2;
609 struct vmodifiers vmod;
611 /* At the top of this loop, we are starting a brand new line. */
612 /* Grab the next line to be evaluated */
613 ebuf->floc.lineno += nlines;
614 nlines = readline (ebuf);
616 /* If there is nothing left to eval, we're done. */
617 if (nlines < 0)
618 break;
620 /* If this line is empty, skip it. */
621 line = ebuf->buffer;
622 if (line[0] == '\0')
623 continue;
625 linelen = strlen (line);
627 /* Check for a shell command line first.
628 If it is not one, we can stop treating cmd_prefix specially. */
629 if (line[0] == cmd_prefix)
631 if (no_targets)
632 /* Ignore the commands in a rule with no targets. */
633 continue;
635 /* If there is no preceding rule line, don't treat this line
636 as a command, even though it begins with a recipe prefix.
637 SunOS 4 make appears to behave this way. */
639 if (filenames != 0)
641 if (ignoring)
642 /* Yep, this is a shell command, and we don't care. */
643 continue;
645 if (commands_idx == 0)
646 cmds_started = ebuf->floc.lineno;
648 /* Append this command line to the line being accumulated.
649 Skip the initial command prefix character. */
650 if (linelen + commands_idx > commands_len)
652 commands_len = (linelen + commands_idx) * 2;
653 commands = xrealloc (commands, commands_len);
655 memcpy (&commands[commands_idx], line + 1, linelen - 1);
656 commands_idx += linelen - 1;
657 commands[commands_idx++] = '\n';
658 continue;
662 /* This line is not a shell command line. Don't worry about whitespace.
663 Get more space if we need it; we don't need to preserve the current
664 contents of the buffer. */
666 if (collapsed_length < linelen+1)
668 collapsed_length = linelen+1;
669 if (collapsed)
670 free (collapsed);
671 /* Don't need xrealloc: we don't need to preserve the content. */
672 collapsed = xmalloc (collapsed_length);
674 strcpy (collapsed, line);
675 /* Collapse continuation lines. */
676 collapse_continuations (collapsed);
677 remove_comments (collapsed);
679 /* Get rid if starting space (including formfeed, vtab, etc.) */
680 p = collapsed;
681 while (isspace ((unsigned char)*p))
682 ++p;
684 /* See if this is a variable assignment. We need to do this early, to
685 allow variables with names like 'ifdef', 'export', 'private', etc. */
686 p = parse_var_assignment(p, &vmod);
687 if (vmod.assign_v)
689 struct variable *v;
690 enum variable_origin origin = vmod.override_v ? o_override : o_file;
692 /* If we're ignoring then we're done now. */
693 if (ignoring)
695 if (vmod.define_v)
696 in_ignored_define = 1;
697 continue;
700 if (vmod.undefine_v)
702 do_undefine (p, origin, ebuf);
704 /* This line has been dealt with. */
705 goto rule_complete;
707 else if (vmod.define_v)
708 v = do_define (p, origin, ebuf);
709 else
710 v = try_variable_definition (fstart, p, origin, 0);
712 assert (v != NULL);
714 if (vmod.export_v)
715 v->export = v_export;
716 if (vmod.private_v)
717 v->private_var = 1;
719 /* This line has been dealt with. */
720 goto rule_complete;
723 /* If this line is completely empty, ignore it. */
724 if (*p == '\0')
725 continue;
727 p2 = end_of_token (p);
728 wlen = p2 - p;
729 p2 = next_token (p2);
731 /* If we're in an ignored define, skip this line (but maybe get out). */
732 if (in_ignored_define)
734 /* See if this is an endef line (plus optional comment). */
735 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
736 in_ignored_define = 0;
738 continue;
741 /* Check for conditional state changes. */
743 int i = conditional_line (p, wlen, fstart);
744 if (i != -2)
746 if (i == -1)
747 fatal (fstart, _("invalid syntax in conditional"));
749 ignoring = i;
750 continue;
754 /* Nothing to see here... move along. */
755 if (ignoring)
756 continue;
758 /* Manage the "export" keyword used outside of variable assignment
759 as well as "unexport". */
760 if (word1eq ("export") || word1eq ("unexport"))
762 int exporting = *p == 'u' ? 0 : 1;
764 /* (un)export by itself causes everything to be (un)exported. */
765 if (*p2 == '\0')
766 export_all_variables = exporting;
767 else
769 unsigned int l;
770 const char *cp;
771 char *ap;
773 /* Expand the line so we can use indirect and constructed
774 variable names in an (un)export command. */
775 cp = ap = allocated_variable_expand (p2);
777 for (p = find_next_token (&cp, &l); p != 0;
778 p = find_next_token (&cp, &l))
780 struct variable *v = lookup_variable (p, l);
781 if (v == 0)
782 v = define_variable_loc (p, l, "", o_file, 0, fstart);
783 v->export = exporting ? v_export : v_noexport;
786 free (ap);
788 goto rule_complete;
791 /* Handle the special syntax for vpath. */
792 if (word1eq ("vpath"))
794 const char *cp;
795 char *vpat;
796 unsigned int l;
797 cp = variable_expand (p2);
798 p = find_next_token (&cp, &l);
799 if (p != 0)
801 vpat = xstrndup (p, l);
802 p = find_next_token (&cp, &l);
803 /* No searchpath means remove all previous
804 selective VPATH's with the same pattern. */
806 else
807 /* No pattern means remove all previous selective VPATH's. */
808 vpat = 0;
809 construct_vpath_list (vpat, p);
810 if (vpat != 0)
811 free (vpat);
813 goto rule_complete;
816 /* Handle include and variants. */
817 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
819 /* We have found an `include' line specifying a nested
820 makefile to be read at this point. */
821 struct conditionals *save;
822 struct conditionals new_conditionals;
823 struct nameseq *files;
824 /* "-include" (vs "include") says no error if the file does not
825 exist. "sinclude" is an alias for this from SGI. */
826 int noerror = (p[0] != 'i');
828 p = allocated_variable_expand (p2);
830 /* If no filenames, it's a no-op. */
831 if (*p == '\0')
833 free (p);
834 continue;
837 /* Parse the list of file names. Don't expand archive references! */
838 p2 = p;
839 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
840 PARSEFS_NOAR);
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_ns (files);
859 files = next;
861 r = eval_makefile (name,
862 (RM_INCLUDED | RM_NO_TILDE
863 | (noerror ? RM_DONTCARE : 0)
864 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
865 if (!r && !noerror)
866 error (fstart, "%s: %s", name, strerror (errno));
869 /* Restore conditional state. */
870 restore_conditionals (save);
872 goto rule_complete;
875 /* This line starts with a tab but was not caught above because there
876 was no preceding target, and the line might have been usable as a
877 variable definition. But now we know it is definitely lossage. */
878 if (line[0] == cmd_prefix)
879 fatal(fstart, _("recipe commences before first target"));
881 /* This line describes some target files. This is complicated by
882 the existence of target-specific variables, because we can't
883 expand the entire line until we know if we have one or not. So
884 we expand the line word by word until we find the first `:',
885 then check to see if it's a target-specific variable.
887 In this algorithm, `lb_next' will point to the beginning of the
888 unexpanded parts of the input buffer, while `p2' points to the
889 parts of the expanded buffer we haven't searched yet. */
892 enum make_word_type wtype;
893 char *cmdleft, *semip, *lb_next;
894 unsigned int plen = 0;
895 char *colonp;
896 const char *end, *beg; /* Helpers for whitespace stripping. */
898 /* Record the previous rule. */
900 record_waiting_files ();
901 tgts_started = fstart->lineno;
903 /* Search the line for an unquoted ; that is not after an
904 unquoted #. */
905 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
906 if (cmdleft != 0 && *cmdleft == '#')
908 /* We found a comment before a semicolon. */
909 *cmdleft = '\0';
910 cmdleft = 0;
912 else if (cmdleft != 0)
913 /* Found one. Cut the line short there before expanding it. */
914 *(cmdleft++) = '\0';
915 semip = cmdleft;
917 collapse_continuations (line);
919 /* We can't expand the entire line, since if it's a per-target
920 variable we don't want to expand it. So, walk from the
921 beginning, expanding as we go, and looking for "interesting"
922 chars. The first word is always expandable. */
923 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
924 switch (wtype)
926 case w_eol:
927 if (cmdleft != 0)
928 fatal(fstart, _("missing rule before recipe"));
929 /* This line contained something but turned out to be nothing
930 but whitespace (a comment?). */
931 continue;
933 case w_colon:
934 case w_dcolon:
935 /* We accept and ignore rules without targets for
936 compatibility with SunOS 4 make. */
937 no_targets = 1;
938 continue;
940 default:
941 break;
944 p2 = variable_expand_string(NULL, lb_next, wlen);
946 while (1)
948 lb_next += wlen;
949 if (cmdleft == 0)
951 /* Look for a semicolon in the expanded line. */
952 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
954 if (cmdleft != 0)
956 unsigned long p2_off = p2 - variable_buffer;
957 unsigned long cmd_off = cmdleft - variable_buffer;
958 char *pend = p2 + strlen(p2);
960 /* Append any remnants of lb, then cut the line short
961 at the semicolon. */
962 *cmdleft = '\0';
964 /* One school of thought says that you shouldn't expand
965 here, but merely copy, since now you're beyond a ";"
966 and into a command script. However, the old parser
967 expanded the whole line, so we continue that for
968 backwards-compatiblity. Also, it wouldn't be
969 entirely consistent, since we do an unconditional
970 expand below once we know we don't have a
971 target-specific variable. */
972 (void)variable_expand_string(pend, lb_next, (long)-1);
973 lb_next += strlen(lb_next);
974 p2 = variable_buffer + p2_off;
975 cmdleft = variable_buffer + cmd_off + 1;
979 colonp = find_char_unquote(p2, ':', 0, 0, 0);
980 #ifdef HAVE_DOS_PATHS
981 /* The drive spec brain-damage strikes again... */
982 /* Note that the only separators of targets in this context
983 are whitespace and a left paren. If others are possible,
984 they should be added to the string in the call to index. */
985 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
986 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
987 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
988 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
989 #endif
990 if (colonp != 0)
991 break;
993 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
994 if (wtype == w_eol)
995 break;
997 p2 += strlen(p2);
998 *(p2++) = ' ';
999 p2 = variable_expand_string(p2, lb_next, wlen);
1000 /* We don't need to worry about cmdleft here, because if it was
1001 found in the variable_buffer the entire buffer has already
1002 been expanded... we'll never get here. */
1005 p2 = next_token (variable_buffer);
1007 /* If the word we're looking at is EOL, see if there's _anything_
1008 on the line. If not, a variable expanded to nothing, so ignore
1009 it. If so, we can't parse this line so punt. */
1010 if (wtype == w_eol)
1012 if (*p2 != '\0')
1013 /* There's no need to be ivory-tower about this: check for
1014 one of the most common bugs found in makefiles... */
1015 fatal (fstart, _("missing separator%s"),
1016 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1017 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1018 continue;
1021 /* Make the colon the end-of-string so we know where to stop
1022 looking for targets. */
1023 *colonp = '\0';
1024 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1025 *p2 = ':';
1027 if (!filenames)
1029 /* We accept and ignore rules without targets for
1030 compatibility with SunOS 4 make. */
1031 no_targets = 1;
1032 continue;
1034 /* This should never be possible; we handled it above. */
1035 assert (*p2 != '\0');
1036 ++p2;
1038 /* Is this a one-colon or two-colon entry? */
1039 two_colon = *p2 == ':';
1040 if (two_colon)
1041 p2++;
1043 /* Test to see if it's a target-specific variable. Copy the rest
1044 of the buffer over, possibly temporarily (we'll expand it later
1045 if it's not a target-specific variable). PLEN saves the length
1046 of the unparsed section of p2, for later. */
1047 if (*lb_next != '\0')
1049 unsigned int l = p2 - variable_buffer;
1050 plen = strlen (p2);
1051 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1052 p2 = variable_buffer + l;
1055 p2 = parse_var_assignment (p2, &vmod);
1056 if (vmod.assign_v)
1058 /* If there was a semicolon found, add it back, plus anything
1059 after it. */
1060 if (semip)
1062 unsigned int l = p - variable_buffer;
1063 *(--semip) = ';';
1064 collapse_continuations (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 /* Remember the command prefix for this target. */
1081 prefix = cmd_prefix;
1083 /* We have some targets, so don't ignore the following commands. */
1084 no_targets = 0;
1086 /* Expand the dependencies, etc. */
1087 if (*lb_next != '\0')
1089 unsigned int l = p2 - variable_buffer;
1090 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1091 p2 = variable_buffer + l;
1093 /* Look for a semicolon in the expanded line. */
1094 if (cmdleft == 0)
1096 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1097 if (cmdleft != 0)
1098 *(cmdleft++) = '\0';
1102 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1103 p = strchr (p2, ':');
1104 while (p != 0 && p[-1] == '\\')
1106 char *q = &p[-1];
1107 int backslash = 0;
1108 while (*q-- == '\\')
1109 backslash = !backslash;
1110 if (backslash)
1111 p = strchr (p + 1, ':');
1112 else
1113 break;
1115 #ifdef _AMIGA
1116 /* Here, the situation is quite complicated. Let's have a look
1117 at a couple of targets:
1119 install: dev:make
1121 dev:make: make
1123 dev:make:: xyz
1125 The rule is that it's only a target, if there are TWO :'s
1126 OR a space around the :.
1128 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1129 || isspace ((unsigned char)p[-1])))
1130 p = 0;
1131 #endif
1132 #ifdef HAVE_DOS_PATHS
1134 int check_again;
1135 do {
1136 check_again = 0;
1137 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1138 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1139 isalpha ((unsigned char)p[-1]) &&
1140 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1141 p = strchr (p + 1, ':');
1142 check_again = 1;
1144 } while (check_again);
1146 #endif
1147 if (p != 0)
1149 struct nameseq *target;
1150 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1151 PARSEFS_NOGLOB);
1152 ++p2;
1153 if (target == 0)
1154 fatal (fstart, _("missing target pattern"));
1155 else if (target->next != 0)
1156 fatal (fstart, _("multiple target patterns"));
1157 pattern_percent = find_percent_cached (&target->name);
1158 pattern = target->name;
1159 if (pattern_percent == 0)
1160 fatal (fstart, _("target pattern contains no `%%'"));
1161 free_ns (target);
1163 else
1164 pattern = 0;
1166 /* Strip leading and trailing whitespaces. */
1167 beg = p2;
1168 end = beg + strlen (beg) - 1;
1169 strip_whitespace (&beg, &end);
1171 /* Put all the prerequisites here; they'll be parsed later. */
1172 if (beg <= end && *beg != '\0')
1173 depstr = xstrndup (beg, end - beg + 1);
1174 else
1175 depstr = 0;
1177 commands_idx = 0;
1178 if (cmdleft != 0)
1180 /* Semicolon means rest of line is a command. */
1181 unsigned int l = strlen (cmdleft);
1183 cmds_started = fstart->lineno;
1185 /* Add this command line to the buffer. */
1186 if (l + 2 > commands_len)
1188 commands_len = (l + 2) * 2;
1189 commands = xrealloc (commands, commands_len);
1191 memcpy (commands, cmdleft, l);
1192 commands_idx += l;
1193 commands[commands_idx++] = '\n';
1196 /* Determine if this target should be made default. We used to do
1197 this in record_files() but because of the delayed target recording
1198 and because preprocessor directives are legal in target's commands
1199 it is too late. Consider this fragment for example:
1201 foo:
1203 ifeq ($(.DEFAULT_GOAL),foo)
1205 endif
1207 Because the target is not recorded until after ifeq directive is
1208 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1209 would expect. Because of this we have to move the logic here. */
1211 if (set_default && default_goal_var->value[0] == '\0')
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);
1295 /* Remove comments from LINE.
1296 This is done by copying the text at LINE onto itself. */
1298 static void
1299 remove_comments (char *line)
1301 char *comment;
1303 comment = find_char_unquote (line, '#', 0, 0, 0);
1305 if (comment != 0)
1306 /* Cut off the line at the #. */
1307 *comment = '\0';
1310 /* Execute a `undefine' directive.
1311 The undefine line has already been read, and NAME is the name of
1312 the variable to be undefined. */
1314 static void
1315 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1317 char *p, *var;
1319 /* Expand the variable name and find the beginning (NAME) and end. */
1320 var = allocated_variable_expand (name);
1321 name = next_token (var);
1322 if (*name == '\0')
1323 fatal (&ebuf->floc, _("empty variable name"));
1324 p = name + strlen (name) - 1;
1325 while (p > name && isblank ((unsigned char)*p))
1326 --p;
1327 p[1] = '\0';
1329 undefine_variable_global (name, p - name + 1, origin);
1330 free (var);
1333 /* Execute a `define' directive.
1334 The first line has already been read, and NAME is the name of
1335 the variable to be defined. The following lines remain to be read. */
1337 static struct variable *
1338 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1340 struct variable *v;
1341 enum variable_flavor flavor;
1342 struct floc defstart;
1343 int nlevels = 1;
1344 unsigned int length = 100;
1345 char *definition = xmalloc (length);
1346 unsigned int idx = 0;
1347 char *p, *var;
1349 defstart = ebuf->floc;
1351 p = parse_variable_definition (name, &flavor);
1352 if (p == NULL)
1353 /* No assignment token, so assume recursive. */
1354 flavor = f_recursive;
1355 else
1357 if (*(next_token (p)) != '\0')
1358 error (&defstart, _("extraneous text after `define' directive"));
1360 /* Chop the string before the assignment token to get the name. */
1361 p[flavor == f_recursive ? -1 : -2] = '\0';
1364 /* Expand the variable name and find the beginning (NAME) and end. */
1365 var = allocated_variable_expand (name);
1366 name = next_token (var);
1367 if (*name == '\0')
1368 fatal (&defstart, _("empty variable name"));
1369 p = name + strlen (name) - 1;
1370 while (p > name && isblank ((unsigned char)*p))
1371 --p;
1372 p[1] = '\0';
1374 /* Now read the value of the variable. */
1375 while (1)
1377 unsigned int len;
1378 char *line;
1379 long nlines = readline (ebuf);
1381 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1382 if (nlines < 0)
1383 fatal (&defstart, _("missing `endef', unterminated `define'"));
1385 ebuf->floc.lineno += nlines;
1386 line = ebuf->buffer;
1388 collapse_continuations (line);
1390 /* If the line doesn't begin with a tab, test to see if it introduces
1391 another define, or ends one. Stop if we find an 'endef' */
1392 if (line[0] != cmd_prefix)
1394 p = next_token (line);
1395 len = strlen (p);
1397 /* If this is another 'define', increment the level count. */
1398 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1399 && strneq (p, "define", 6))
1400 ++nlevels;
1402 /* If this is an 'endef', decrement the count. If it's now 0,
1403 we've found the last one. */
1404 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1405 && strneq (p, "endef", 5))
1407 p += 5;
1408 remove_comments (p);
1409 if (*(next_token (p)) != '\0')
1410 error (&ebuf->floc,
1411 _("extraneous text after `endef' directive"));
1413 if (--nlevels == 0)
1414 break;
1418 /* Add this line to the variable definition. */
1419 len = strlen (line);
1420 if (idx + len + 1 > length)
1422 length = (idx + len) * 2;
1423 definition = xrealloc (definition, length + 1);
1426 memcpy (&definition[idx], line, len);
1427 idx += len;
1428 /* Separate lines with a newline. */
1429 definition[idx++] = '\n';
1432 /* We've got what we need; define the variable. */
1433 if (idx == 0)
1434 definition[0] = '\0';
1435 else
1436 definition[idx - 1] = '\0';
1438 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1439 free (definition);
1440 free (var);
1441 return (v);
1444 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1445 "ifneq", "else" and "endif".
1446 LINE is the input line, with the command as its first word.
1448 FILENAME and LINENO are the filename and line number in the
1449 current makefile. They are used for error messages.
1451 Value is -2 if the line is not a conditional at all,
1452 -1 if the line is an invalid conditional,
1453 0 if following text should be interpreted,
1454 1 if following text should be ignored. */
1456 static int
1457 conditional_line (char *line, int len, const struct floc *flocp)
1459 char *cmdname;
1460 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1461 unsigned int i;
1462 unsigned int o;
1464 /* Compare a word, both length and contents. */
1465 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1466 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1468 /* Make sure this line is a conditional. */
1469 chkword ("ifdef", c_ifdef)
1470 else chkword ("ifndef", c_ifndef)
1471 else chkword ("ifeq", c_ifeq)
1472 else chkword ("ifneq", c_ifneq)
1473 else chkword ("else", c_else)
1474 else chkword ("endif", c_endif)
1475 else
1476 return -2;
1478 /* Found one: skip past it and any whitespace after it. */
1479 line = next_token (line + len);
1481 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1483 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1484 if (cmdtype == c_endif)
1486 if (*line != '\0')
1487 EXTRANEOUS ();
1489 if (!conditionals->if_cmds)
1490 fatal (flocp, _("extraneous `%s'"), cmdname);
1492 --conditionals->if_cmds;
1494 goto DONE;
1497 /* An 'else' statement can either be simple, or it can have another
1498 conditional after it. */
1499 if (cmdtype == c_else)
1501 const char *p;
1503 if (!conditionals->if_cmds)
1504 fatal (flocp, _("extraneous `%s'"), cmdname);
1506 o = conditionals->if_cmds - 1;
1508 if (conditionals->seen_else[o])
1509 fatal (flocp, _("only one `else' per conditional"));
1511 /* Change the state of ignorance. */
1512 switch (conditionals->ignoring[o])
1514 case 0:
1515 /* We've just been interpreting. Never do it again. */
1516 conditionals->ignoring[o] = 2;
1517 break;
1518 case 1:
1519 /* We've never interpreted yet. Maybe this time! */
1520 conditionals->ignoring[o] = 0;
1521 break;
1524 /* It's a simple 'else'. */
1525 if (*line == '\0')
1527 conditionals->seen_else[o] = 1;
1528 goto DONE;
1531 /* The 'else' has extra text. That text must be another conditional
1532 and cannot be an 'else' or 'endif'. */
1534 /* Find the length of the next word. */
1535 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1537 len = p - line;
1539 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1540 if (word1eq("else") || word1eq("endif")
1541 || conditional_line (line, len, flocp) < 0)
1542 EXTRANEOUS ();
1543 else
1545 /* conditional_line() created a new level of conditional.
1546 Raise it back to this level. */
1547 if (conditionals->ignoring[o] < 2)
1548 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1549 --conditionals->if_cmds;
1552 goto DONE;
1555 if (conditionals->allocated == 0)
1557 conditionals->allocated = 5;
1558 conditionals->ignoring = xmalloc (conditionals->allocated);
1559 conditionals->seen_else = xmalloc (conditionals->allocated);
1562 o = conditionals->if_cmds++;
1563 if (conditionals->if_cmds > conditionals->allocated)
1565 conditionals->allocated += 5;
1566 conditionals->ignoring = xrealloc (conditionals->ignoring,
1567 conditionals->allocated);
1568 conditionals->seen_else = xrealloc (conditionals->seen_else,
1569 conditionals->allocated);
1572 /* Record that we have seen an `if...' but no `else' so far. */
1573 conditionals->seen_else[o] = 0;
1575 /* Search through the stack to see if we're already ignoring. */
1576 for (i = 0; i < o; ++i)
1577 if (conditionals->ignoring[i])
1579 /* We are already ignoring, so just push a level to match the next
1580 "else" or "endif", and keep ignoring. We don't want to expand
1581 variables in the condition. */
1582 conditionals->ignoring[o] = 1;
1583 return 1;
1586 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1588 char *var;
1589 struct variable *v;
1590 char *p;
1592 /* Expand the thing we're looking up, so we can use indirect and
1593 constructed variable names. */
1594 var = allocated_variable_expand (line);
1596 /* Make sure there's only one variable name to test. */
1597 p = end_of_token (var);
1598 i = p - var;
1599 p = next_token (p);
1600 if (*p != '\0')
1601 return -1;
1603 var[i] = '\0';
1604 v = lookup_variable (var, i);
1606 conditionals->ignoring[o] =
1607 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1609 free (var);
1611 else
1613 /* "ifeq" or "ifneq". */
1614 char *s1, *s2;
1615 unsigned int l;
1616 char termin = *line == '(' ? ',' : *line;
1618 if (termin != ',' && termin != '"' && termin != '\'')
1619 return -1;
1621 s1 = ++line;
1622 /* Find the end of the first string. */
1623 if (termin == ',')
1625 int count = 0;
1626 for (; *line != '\0'; ++line)
1627 if (*line == '(')
1628 ++count;
1629 else if (*line == ')')
1630 --count;
1631 else if (*line == ',' && count <= 0)
1632 break;
1634 else
1635 while (*line != '\0' && *line != termin)
1636 ++line;
1638 if (*line == '\0')
1639 return -1;
1641 if (termin == ',')
1643 /* Strip blanks after the first string. */
1644 char *p = line++;
1645 while (isblank ((unsigned char)p[-1]))
1646 --p;
1647 *p = '\0';
1649 else
1650 *line++ = '\0';
1652 s2 = variable_expand (s1);
1653 /* We must allocate a new copy of the expanded string because
1654 variable_expand re-uses the same buffer. */
1655 l = strlen (s2);
1656 s1 = alloca (l + 1);
1657 memcpy (s1, s2, l + 1);
1659 if (termin != ',')
1660 /* Find the start of the second string. */
1661 line = next_token (line);
1663 termin = termin == ',' ? ')' : *line;
1664 if (termin != ')' && termin != '"' && termin != '\'')
1665 return -1;
1667 /* Find the end of the second string. */
1668 if (termin == ')')
1670 int count = 0;
1671 s2 = next_token (line);
1672 for (line = s2; *line != '\0'; ++line)
1674 if (*line == '(')
1675 ++count;
1676 else if (*line == ')')
1678 if (count <= 0)
1679 break;
1680 else
1681 --count;
1685 else
1687 ++line;
1688 s2 = line;
1689 while (*line != '\0' && *line != termin)
1690 ++line;
1693 if (*line == '\0')
1694 return -1;
1696 *line = '\0';
1697 line = next_token (++line);
1698 if (*line != '\0')
1699 EXTRANEOUS ();
1701 s2 = variable_expand (s2);
1702 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1705 DONE:
1706 /* Search through the stack to see if we're ignoring. */
1707 for (i = 0; i < conditionals->if_cmds; ++i)
1708 if (conditionals->ignoring[i])
1709 return 1;
1710 return 0;
1714 /* Record target-specific variable values for files FILENAMES.
1715 TWO_COLON is nonzero if a double colon was used.
1717 The links of FILENAMES are freed, and so are any names in it
1718 that are not incorporated into other data structures.
1720 If the target is a pattern, add the variable to the pattern-specific
1721 variable value list. */
1723 static void
1724 record_target_var (struct nameseq *filenames, char *defn,
1725 enum variable_origin origin, struct vmodifiers *vmod,
1726 const struct floc *flocp)
1728 struct nameseq *nextf;
1729 struct variable_set_list *global;
1731 global = current_variable_set_list;
1733 /* If the variable is an append version, store that but treat it as a
1734 normal recursive variable. */
1736 for (; filenames != 0; filenames = nextf)
1738 struct variable *v;
1739 const char *name = filenames->name;
1740 const char *fname;
1741 const char *percent;
1742 struct pattern_var *p;
1744 nextf = filenames->next;
1745 free_ns (filenames);
1747 /* If it's a pattern target, then add it to the pattern-specific
1748 variable list. */
1749 percent = find_percent_cached (&name);
1750 if (percent)
1752 /* Get a reference for this pattern-specific variable struct. */
1753 p = create_pattern_var (name, percent);
1754 p->variable.fileinfo = *flocp;
1755 /* I don't think this can fail since we already determined it was a
1756 variable definition. */
1757 v = assign_variable_definition (&p->variable, defn);
1758 assert (v != 0);
1760 v->origin = origin;
1761 if (v->flavor == f_simple)
1762 v->value = allocated_variable_expand (v->value);
1763 else
1764 v->value = xstrdup (v->value);
1766 fname = p->target;
1768 else
1770 struct file *f;
1772 /* Get a file reference for this file, and initialize it.
1773 We don't want to just call enter_file() because that allocates a
1774 new entry if the file is a double-colon, which we don't want in
1775 this situation. */
1776 f = lookup_file (name);
1777 if (!f)
1778 f = enter_file (strcache_add (name));
1779 else if (f->double_colon)
1780 f = f->double_colon;
1782 initialize_file_variables (f, 1);
1783 fname = f->name;
1785 current_variable_set_list = f->variables;
1786 v = try_variable_definition (flocp, defn, origin, 1);
1787 if (!v)
1788 fatal (flocp, _("Malformed target-specific variable definition"));
1789 current_variable_set_list = global;
1792 /* Set up the variable to be *-specific. */
1793 v->per_target = 1;
1794 v->private_var = vmod->private_v;
1795 v->export = vmod->export_v ? v_export : v_default;
1797 /* If it's not an override, check to see if there was a command-line
1798 setting. If so, reset the value. */
1799 if (v->origin != o_override)
1801 struct variable *gv;
1802 int len = strlen(v->name);
1804 gv = lookup_variable (v->name, len);
1805 if (gv && v != gv
1806 && (gv->origin == o_env_override || gv->origin == o_command))
1808 if (v->value != 0)
1809 free (v->value);
1810 v->value = xstrdup (gv->value);
1811 v->origin = gv->origin;
1812 v->recursive = gv->recursive;
1813 v->append = 0;
1819 /* Record a description line for files FILENAMES,
1820 with dependencies DEPS, commands to execute described
1821 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1822 TWO_COLON is nonzero if a double colon was used.
1823 If not nil, PATTERN is the `%' pattern to make this
1824 a static pattern rule, and PATTERN_PERCENT is a pointer
1825 to the `%' within it.
1827 The links of FILENAMES are freed, and so are any names in it
1828 that are not incorporated into other data structures. */
1830 static void
1831 record_files (struct nameseq *filenames, const char *pattern,
1832 const char *pattern_percent, char *depstr,
1833 unsigned int cmds_started, char *commands,
1834 unsigned int commands_idx, int two_colon,
1835 char prefix, const struct floc *flocp)
1837 struct commands *cmds;
1838 struct dep *deps;
1839 const char *implicit_percent;
1840 const char *name;
1842 /* If we've already snapped deps, that means we're in an eval being
1843 resolved after the makefiles have been read in. We can't add more rules
1844 at this time, since they won't get snapped and we'll get core dumps.
1845 See Savannah bug # 12124. */
1846 if (snapped_deps)
1847 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1849 /* Determine if this is a pattern rule or not. */
1850 name = filenames->name;
1851 implicit_percent = find_percent_cached (&name);
1853 /* If there's a recipe, set up a struct for it. */
1854 if (commands_idx > 0)
1856 cmds = xmalloc (sizeof (struct commands));
1857 cmds->fileinfo.filenm = flocp->filenm;
1858 cmds->fileinfo.lineno = cmds_started;
1859 cmds->commands = xstrndup (commands, commands_idx);
1860 cmds->command_lines = 0;
1861 cmds->recipe_prefix = prefix;
1863 else
1864 cmds = 0;
1866 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1867 expansion: if so, snap_deps() will do it. */
1868 if (depstr == 0)
1869 deps = 0;
1870 else if (second_expansion && strchr (depstr, '$'))
1872 deps = alloc_dep ();
1873 deps->name = depstr;
1874 deps->need_2nd_expansion = 1;
1875 deps->staticpattern = pattern != 0;
1877 else
1879 deps = split_prereqs (depstr);
1880 free (depstr);
1882 /* We'll enter static pattern prereqs later when we have the stem. We
1883 don't want to enter pattern rules at all so that we don't think that
1884 they ought to exist (make manual "Implicit Rule Search Algorithm",
1885 item 5c). */
1886 if (! pattern && ! implicit_percent)
1887 deps = enter_prereqs (deps, NULL);
1890 /* For implicit rules, _all_ the targets must have a pattern. That means we
1891 can test the first one to see if we're working with an implicit rule; if
1892 so we handle it specially. */
1894 if (implicit_percent)
1896 struct nameseq *nextf;
1897 const char **targets, **target_pats;
1898 unsigned int c;
1900 if (pattern != 0)
1901 fatal (flocp, _("mixed implicit and static pattern rules"));
1903 /* Count the targets to create an array of target names.
1904 We already have the first one. */
1905 nextf = filenames->next;
1906 free_ns (filenames);
1907 filenames = nextf;
1909 for (c = 1; nextf; ++c, nextf = nextf->next)
1911 targets = xmalloc (c * sizeof (const char *));
1912 target_pats = xmalloc (c * sizeof (const char *));
1914 targets[0] = name;
1915 target_pats[0] = implicit_percent;
1917 c = 1;
1918 while (filenames)
1920 name = filenames->name;
1921 implicit_percent = find_percent_cached (&name);
1923 if (implicit_percent == 0)
1924 fatal (flocp, _("mixed implicit and normal rules"));
1926 targets[c] = name;
1927 target_pats[c] = implicit_percent;
1928 ++c;
1930 nextf = filenames->next;
1931 free_ns (filenames);
1932 filenames = nextf;
1935 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1937 return;
1941 /* Walk through each target and create it in the database.
1942 We already set up the first target, above. */
1943 while (1)
1945 struct nameseq *nextf = filenames->next;
1946 struct file *f;
1947 struct dep *this = 0;
1949 free_ns (filenames);
1951 /* Check for special targets. Do it here instead of, say, snap_deps()
1952 so that we can immediately use the value. */
1953 if (streq (name, ".POSIX"))
1955 posix_pedantic = 1;
1956 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1958 else if (streq (name, ".SECONDEXPANSION"))
1959 second_expansion = 1;
1960 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
1961 else if (streq (name, ".ONESHELL"))
1962 one_shell = 1;
1963 #endif
1965 /* If this is a static pattern rule:
1966 `targets: target%pattern: prereq%pattern; recipe',
1967 make sure the pattern matches this target name. */
1968 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1969 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1970 else if (deps)
1971 /* If there are multiple targets, copy the chain DEPS for all but the
1972 last one. It is not safe for the same deps to go in more than one
1973 place in the database. */
1974 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1976 /* Find or create an entry in the file database for this target. */
1977 if (!two_colon)
1979 /* Single-colon. Combine this rule with the file's existing record,
1980 if any. */
1981 f = enter_file (strcache_add (name));
1982 if (f->double_colon)
1983 fatal (flocp,
1984 _("target file `%s' has both : and :: entries"), f->name);
1986 /* If CMDS == F->CMDS, this target was listed in this rule
1987 more than once. Just give a warning since this is harmless. */
1988 if (cmds != 0 && cmds == f->cmds)
1989 error (flocp,
1990 _("target `%s' given more than once in the same rule."),
1991 f->name);
1993 /* Check for two single-colon entries both with commands.
1994 Check is_target so that we don't lose on files such as .c.o
1995 whose commands were preinitialized. */
1996 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1998 error (&cmds->fileinfo,
1999 _("warning: overriding recipe for target `%s'"),
2000 f->name);
2001 error (&f->cmds->fileinfo,
2002 _("warning: ignoring old recipe for target `%s'"),
2003 f->name);
2006 /* Defining .DEFAULT with no deps or cmds clears it. */
2007 if (f == default_file && this == 0 && cmds == 0)
2008 f->cmds = 0;
2009 if (cmds != 0)
2010 f->cmds = cmds;
2012 /* Defining .SUFFIXES with no dependencies clears out the list of
2013 suffixes. */
2014 if (f == suffix_file && this == 0)
2016 free_dep_chain (f->deps);
2017 f->deps = 0;
2020 else
2022 /* Double-colon. Make a new record even if there already is one. */
2023 f = lookup_file (name);
2025 /* Check for both : and :: rules. Check is_target so we don't lose
2026 on default suffix rules or makefiles. */
2027 if (f != 0 && f->is_target && !f->double_colon)
2028 fatal (flocp,
2029 _("target file `%s' has both : and :: entries"), f->name);
2031 f = enter_file (strcache_add (name));
2032 /* If there was an existing entry and it was a double-colon entry,
2033 enter_file will have returned a new one, making it the prev
2034 pointer of the old one, and setting its double_colon pointer to
2035 the first one. */
2036 if (f->double_colon == 0)
2037 /* This is the first entry for this name, so we must set its
2038 double_colon pointer to itself. */
2039 f->double_colon = f;
2041 f->cmds = cmds;
2044 f->is_target = 1;
2046 /* If this is a static pattern rule, set the stem to the part of its
2047 name that matched the `%' in the pattern, so you can use $* in the
2048 commands. If we didn't do it before, enter the prereqs now. */
2049 if (pattern)
2051 static const char *percent = "%";
2052 char *buffer = variable_expand ("");
2053 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2054 pattern_percent+1, percent+1);
2055 f->stem = strcache_add_len (buffer, o - buffer);
2056 if (this)
2058 if (! this->need_2nd_expansion)
2059 this = enter_prereqs (this, f->stem);
2060 else
2061 this->stem = f->stem;
2065 /* Add the dependencies to this file entry. */
2066 if (this != 0)
2068 /* Add the file's old deps and the new ones in THIS together. */
2069 if (f->deps == 0)
2070 f->deps = this;
2071 else if (cmds != 0)
2073 struct dep *d = this;
2075 /* If this rule has commands, put these deps first. */
2076 while (d->next != 0)
2077 d = d->next;
2079 d->next = f->deps;
2080 f->deps = this;
2082 else
2084 struct dep *d = f->deps;
2086 /* A rule without commands: put its prereqs at the end. */
2087 while (d->next != 0)
2088 d = d->next;
2090 d->next = this;
2094 name = f->name;
2096 /* All done! Set up for the next one. */
2097 if (nextf == 0)
2098 break;
2100 filenames = nextf;
2102 /* Reduce escaped percents. If there are any unescaped it's an error */
2103 name = filenames->name;
2104 if (find_percent_cached (&name))
2105 fatal (flocp, _("mixed implicit and normal rules"));
2109 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2110 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2111 Quoting backslashes are removed from STRING by compacting it into
2112 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2113 one, or nil if there are none. STOPCHARs inside variable references are
2114 ignored if IGNOREVARS is true.
2116 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2118 static char *
2119 find_char_unquote (char *string, int stop1, int stop2, int blank,
2120 int ignorevars)
2122 unsigned int string_len = 0;
2123 char *p = string;
2125 if (ignorevars)
2126 ignorevars = '$';
2128 while (1)
2130 if (stop2 && blank)
2131 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2132 && ! isblank ((unsigned char) *p))
2133 ++p;
2134 else if (stop2)
2135 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2136 ++p;
2137 else if (blank)
2138 while (*p != '\0' && *p != ignorevars && *p != stop1
2139 && ! isblank ((unsigned char) *p))
2140 ++p;
2141 else
2142 while (*p != '\0' && *p != ignorevars && *p != stop1)
2143 ++p;
2145 if (*p == '\0')
2146 break;
2148 /* If we stopped due to a variable reference, skip over its contents. */
2149 if (*p == ignorevars)
2151 char openparen = p[1];
2153 p += 2;
2155 /* Skip the contents of a non-quoted, multi-char variable ref. */
2156 if (openparen == '(' || openparen == '{')
2158 unsigned int pcount = 1;
2159 char closeparen = (openparen == '(' ? ')' : '}');
2161 while (*p)
2163 if (*p == openparen)
2164 ++pcount;
2165 else if (*p == closeparen)
2166 if (--pcount == 0)
2168 ++p;
2169 break;
2171 ++p;
2175 /* Skipped the variable reference: look for STOPCHARS again. */
2176 continue;
2179 if (p > string && p[-1] == '\\')
2181 /* Search for more backslashes. */
2182 int i = -2;
2183 while (&p[i] >= string && p[i] == '\\')
2184 --i;
2185 ++i;
2186 /* Only compute the length if really needed. */
2187 if (string_len == 0)
2188 string_len = strlen (string);
2189 /* The number of backslashes is now -I.
2190 Copy P over itself to swallow half of them. */
2191 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2192 p += i/2;
2193 if (i % 2 == 0)
2194 /* All the backslashes quoted each other; the STOPCHAR was
2195 unquoted. */
2196 return p;
2198 /* The STOPCHAR was quoted by a backslash. Look for another. */
2200 else
2201 /* No backslash in sight. */
2202 return p;
2205 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2206 return 0;
2209 /* Search PATTERN for an unquoted % and handle quoting. */
2211 char *
2212 find_percent (char *pattern)
2214 return find_char_unquote (pattern, '%', 0, 0, 0);
2217 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2218 the % or NULL if no % was found.
2219 This version is used with strings in the string cache: if there's a need to
2220 modify the string a new version will be added to the string cache and
2221 *STRING will be set to that. */
2223 const char *
2224 find_percent_cached (const char **string)
2226 const char *p = *string;
2227 char *new = 0;
2228 int slen = 0;
2230 /* If the first char is a % return now. This lets us avoid extra tests
2231 inside the loop. */
2232 if (*p == '%')
2233 return p;
2235 while (1)
2237 while (*p != '\0' && *p != '%')
2238 ++p;
2240 if (*p == '\0')
2241 break;
2243 /* See if this % is escaped with a backslash; if not we're done. */
2244 if (p[-1] != '\\')
2245 break;
2248 /* Search for more backslashes. */
2249 char *pv;
2250 int i = -2;
2252 while (&p[i] >= *string && p[i] == '\\')
2253 --i;
2254 ++i;
2256 /* At this point we know we'll need to allocate a new string.
2257 Make a copy if we haven't yet done so. */
2258 if (! new)
2260 slen = strlen (*string);
2261 new = alloca (slen + 1);
2262 memcpy (new, *string, slen + 1);
2263 p = new + (p - *string);
2264 *string = new;
2267 /* At this point *string, p, and new all point into the same string.
2268 Get a non-const version of p so we can modify new. */
2269 pv = new + (p - *string);
2271 /* The number of backslashes is now -I.
2272 Copy P over itself to swallow half of them. */
2273 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2274 p += i/2;
2276 /* If the backslashes quoted each other; the % was unquoted. */
2277 if (i % 2 == 0)
2278 break;
2282 /* If we had to change STRING, add it to the strcache. */
2283 if (new)
2285 *string = strcache_add (*string);
2286 p = *string + (p - new);
2289 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2290 return (*p == '\0') ? NULL : p;
2293 /* Find the next line of text in an eval buffer, combining continuation lines
2294 into one line.
2295 Return the number of actual lines read (> 1 if continuation lines).
2296 Returns -1 if there's nothing left in the buffer.
2298 After this function, ebuf->buffer points to the first character of the
2299 line we just found.
2302 /* Read a line of text from a STRING.
2303 Since we aren't really reading from a file, don't bother with linenumbers.
2306 static unsigned long
2307 readstring (struct ebuffer *ebuf)
2309 char *eol;
2311 /* If there is nothing left in this buffer, return 0. */
2312 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2313 return -1;
2315 /* Set up a new starting point for the buffer, and find the end of the
2316 next logical line (taking into account backslash/newline pairs). */
2318 eol = ebuf->buffer = ebuf->bufnext;
2320 while (1)
2322 int backslash = 0;
2323 const char *bol = eol;
2324 const char *p;
2326 /* Find the next newline. At EOS, stop. */
2327 p = eol = strchr (eol , '\n');
2328 if (!eol)
2330 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2331 return 0;
2334 /* Found a newline; if it's escaped continue; else we're done. */
2335 while (p > bol && *(--p) == '\\')
2336 backslash = !backslash;
2337 if (!backslash)
2338 break;
2339 ++eol;
2342 /* Overwrite the newline char. */
2343 *eol = '\0';
2344 ebuf->bufnext = eol+1;
2346 return 0;
2349 static long
2350 readline (struct ebuffer *ebuf)
2352 char *p;
2353 char *end;
2354 char *start;
2355 long nlines = 0;
2357 /* The behaviors between string and stream buffers are different enough to
2358 warrant different functions. Do the Right Thing. */
2360 if (!ebuf->fp)
2361 return readstring (ebuf);
2363 /* When reading from a file, we always start over at the beginning of the
2364 buffer for each new line. */
2366 p = start = ebuf->bufstart;
2367 end = p + ebuf->size;
2368 *p = '\0';
2370 while (fgets (p, end - p, ebuf->fp) != 0)
2372 char *p2;
2373 unsigned long len;
2374 int backslash;
2376 len = strlen (p);
2377 if (len == 0)
2379 /* This only happens when the first thing on the line is a '\0'.
2380 It is a pretty hopeless case, but (wonder of wonders) Athena
2381 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2382 There is nothing really to be done; we synthesize a newline so
2383 the following line doesn't appear to be part of this line. */
2384 error (&ebuf->floc,
2385 _("warning: NUL character seen; rest of line ignored"));
2386 p[0] = '\n';
2387 len = 1;
2390 /* Jump past the text we just read. */
2391 p += len;
2393 /* If the last char isn't a newline, the whole line didn't fit into the
2394 buffer. Get some more buffer and try again. */
2395 if (p[-1] != '\n')
2396 goto more_buffer;
2398 /* We got a newline, so add one to the count of lines. */
2399 ++nlines;
2401 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2402 /* Check to see if the line was really ended with CRLF; if so ignore
2403 the CR. */
2404 if ((p - start) > 1 && p[-2] == '\r')
2406 --p;
2407 p[-1] = '\n';
2409 #endif
2411 backslash = 0;
2412 for (p2 = p - 2; p2 >= start; --p2)
2414 if (*p2 != '\\')
2415 break;
2416 backslash = !backslash;
2419 if (!backslash)
2421 p[-1] = '\0';
2422 break;
2425 /* It was a backslash/newline combo. If we have more space, read
2426 another line. */
2427 if (end - p >= 80)
2428 continue;
2430 /* We need more space at the end of our buffer, so realloc it.
2431 Make sure to preserve the current offset of p. */
2432 more_buffer:
2434 unsigned long off = p - start;
2435 ebuf->size *= 2;
2436 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2437 p = start + off;
2438 end = start + ebuf->size;
2439 *p = '\0';
2443 if (ferror (ebuf->fp))
2444 pfatal_with_name (ebuf->floc.filenm);
2446 /* If we found some lines, return how many.
2447 If we didn't, but we did find _something_, that indicates we read the last
2448 line of a file with no final newline; return 1.
2449 If we read nothing, we're at EOF; return -1. */
2451 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2454 /* Parse the next "makefile word" from the input buffer, and return info
2455 about it.
2457 A "makefile word" is one of:
2459 w_bogus Should never happen
2460 w_eol End of input
2461 w_static A static word; cannot be expanded
2462 w_variable A word containing one or more variables/functions
2463 w_colon A colon
2464 w_dcolon A double-colon
2465 w_semicolon A semicolon
2466 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2468 Note that this function is only used when reading certain parts of the
2469 makefile. Don't use it where special rules hold sway (RHS of a variable,
2470 in a command list, etc.) */
2472 static enum make_word_type
2473 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2475 enum make_word_type wtype = w_bogus;
2476 char *p = buffer, *beg;
2477 char c;
2479 /* Skip any leading whitespace. */
2480 while (isblank ((unsigned char)*p))
2481 ++p;
2483 beg = p;
2484 c = *(p++);
2485 switch (c)
2487 case '\0':
2488 wtype = w_eol;
2489 break;
2491 case ';':
2492 wtype = w_semicolon;
2493 break;
2495 case '=':
2496 wtype = w_varassign;
2497 break;
2499 case ':':
2500 wtype = w_colon;
2501 switch (*p)
2503 case ':':
2504 ++p;
2505 wtype = w_dcolon;
2506 break;
2508 case '=':
2509 ++p;
2510 wtype = w_varassign;
2511 break;
2513 break;
2515 case '+':
2516 case '?':
2517 if (*p == '=')
2519 ++p;
2520 wtype = w_varassign;
2521 break;
2524 default:
2525 if (delim && strchr (delim, c))
2526 wtype = w_static;
2527 break;
2530 /* Did we find something? If so, return now. */
2531 if (wtype != w_bogus)
2532 goto done;
2534 /* This is some non-operator word. A word consists of the longest
2535 string of characters that doesn't contain whitespace, one of [:=#],
2536 or [?+]=, or one of the chars in the DELIM string. */
2538 /* We start out assuming a static word; if we see a variable we'll
2539 adjust our assumptions then. */
2540 wtype = w_static;
2542 /* We already found the first value of "c", above. */
2543 while (1)
2545 char closeparen;
2546 int count;
2548 switch (c)
2550 case '\0':
2551 case ' ':
2552 case '\t':
2553 case '=':
2554 goto done_word;
2556 case ':':
2557 #ifdef HAVE_DOS_PATHS
2558 /* A word CAN include a colon in its drive spec. The drive
2559 spec is allowed either at the beginning of a word, or as part
2560 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2561 if (!(p - beg >= 2
2562 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2563 && (p - beg == 2 || p[-3] == '(')))
2564 #endif
2565 goto done_word;
2567 case '$':
2568 c = *(p++);
2569 if (c == '$')
2570 break;
2572 /* This is a variable reference, so note that it's expandable.
2573 Then read it to the matching close paren. */
2574 wtype = w_variable;
2576 if (c == '(')
2577 closeparen = ')';
2578 else if (c == '{')
2579 closeparen = '}';
2580 else
2581 /* This is a single-letter variable reference. */
2582 break;
2584 for (count=0; *p != '\0'; ++p)
2586 if (*p == c)
2587 ++count;
2588 else if (*p == closeparen && --count < 0)
2590 ++p;
2591 break;
2594 break;
2596 case '?':
2597 case '+':
2598 if (*p == '=')
2599 goto done_word;
2600 break;
2602 case '\\':
2603 switch (*p)
2605 case ':':
2606 case ';':
2607 case '=':
2608 case '\\':
2609 ++p;
2610 break;
2612 break;
2614 default:
2615 if (delim && strchr (delim, c))
2616 goto done_word;
2617 break;
2620 c = *(p++);
2622 done_word:
2623 --p;
2625 done:
2626 if (startp)
2627 *startp = beg;
2628 if (length)
2629 *length = p - beg;
2630 return wtype;
2633 /* Construct the list of include directories
2634 from the arguments and the default list. */
2636 void
2637 construct_include_path (const char **arg_dirs)
2639 #ifdef VAXC /* just don't ask ... */
2640 stat_t stbuf;
2641 #else
2642 struct stat stbuf;
2643 #endif
2644 const char **dirs;
2645 const char **cpp;
2646 unsigned int idx;
2648 /* Compute the number of pointers we need in the table. */
2649 idx = sizeof (default_include_directories) / sizeof (const char *);
2650 if (arg_dirs)
2651 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2652 ++idx;
2654 #ifdef __MSDOS__
2655 /* Add one for $DJDIR. */
2656 ++idx;
2657 #endif
2659 dirs = xmalloc (idx * sizeof (const char *));
2661 idx = 0;
2662 max_incl_len = 0;
2664 /* First consider any dirs specified with -I switches.
2665 Ignore any that don't exist. Remember the maximum string length. */
2667 if (arg_dirs)
2668 while (*arg_dirs != 0)
2670 const char *dir = *(arg_dirs++);
2671 char *expanded = 0;
2672 int e;
2674 if (dir[0] == '~')
2676 expanded = tilde_expand (dir);
2677 if (expanded != 0)
2678 dir = expanded;
2681 EINTRLOOP (e, stat (dir, &stbuf));
2682 if (e == 0 && S_ISDIR (stbuf.st_mode))
2684 unsigned int len = strlen (dir);
2685 /* If dir name is written with trailing slashes, discard them. */
2686 while (len > 1 && dir[len - 1] == '/')
2687 --len;
2688 if (len > max_incl_len)
2689 max_incl_len = len;
2690 dirs[idx++] = strcache_add_len (dir, len);
2693 if (expanded)
2694 free (expanded);
2697 /* Now add the standard default dirs at the end. */
2699 #ifdef __MSDOS__
2701 /* The environment variable $DJDIR holds the root of the DJGPP directory
2702 tree; add ${DJDIR}/include. */
2703 struct variable *djdir = lookup_variable ("DJDIR", 5);
2705 if (djdir)
2707 unsigned int len = strlen (djdir->value) + 8;
2708 char *defdir = alloca (len + 1);
2710 strcat (strcpy (defdir, djdir->value), "/include");
2711 dirs[idx++] = strcache_add (defdir);
2713 if (len > max_incl_len)
2714 max_incl_len = len;
2717 #endif
2719 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2721 int e;
2723 EINTRLOOP (e, stat (*cpp, &stbuf));
2724 if (e == 0 && S_ISDIR (stbuf.st_mode))
2726 unsigned int len = strlen (*cpp);
2727 /* If dir name is written with trailing slashes, discard them. */
2728 while (len > 1 && (*cpp)[len - 1] == '/')
2729 --len;
2730 if (len > max_incl_len)
2731 max_incl_len = len;
2732 dirs[idx++] = strcache_add_len (*cpp, len);
2736 dirs[idx] = 0;
2738 /* Now add each dir to the .INCLUDE_DIRS variable. */
2740 for (cpp = dirs; *cpp != 0; ++cpp)
2741 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2742 o_default, f_append, 0);
2744 include_directories = dirs;
2747 /* Expand ~ or ~USER at the beginning of NAME.
2748 Return a newly malloc'd string or 0. */
2750 char *
2751 tilde_expand (const char *name)
2753 #ifndef VMS
2754 if (name[1] == '/' || name[1] == '\0')
2756 extern char *getenv ();
2757 char *home_dir;
2758 int is_variable;
2761 /* Turn off --warn-undefined-variables while we expand HOME. */
2762 int save = warn_undefined_variables_flag;
2763 warn_undefined_variables_flag = 0;
2765 home_dir = allocated_variable_expand ("$(HOME)");
2767 warn_undefined_variables_flag = save;
2770 is_variable = home_dir[0] != '\0';
2771 if (!is_variable)
2773 free (home_dir);
2774 home_dir = getenv ("HOME");
2776 # if !defined(_AMIGA) && !defined(WINDOWS32)
2777 if (home_dir == 0 || home_dir[0] == '\0')
2779 extern char *getlogin ();
2780 char *logname = getlogin ();
2781 home_dir = 0;
2782 if (logname != 0)
2784 struct passwd *p = getpwnam (logname);
2785 if (p != 0)
2786 home_dir = p->pw_dir;
2789 # endif /* !AMIGA && !WINDOWS32 */
2790 if (home_dir != 0)
2792 char *new = xstrdup (concat (2, home_dir, name + 1));
2793 if (is_variable)
2794 free (home_dir);
2795 return new;
2798 # if !defined(_AMIGA) && !defined(WINDOWS32)
2799 else
2801 struct passwd *pwent;
2802 char *userend = strchr (name + 1, '/');
2803 if (userend != 0)
2804 *userend = '\0';
2805 pwent = getpwnam (name + 1);
2806 if (pwent != 0)
2808 if (userend == 0)
2809 return xstrdup (pwent->pw_dir);
2810 else
2811 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2813 else if (userend != 0)
2814 *userend = '/';
2816 # endif /* !AMIGA && !WINDOWS32 */
2817 #endif /* !VMS */
2818 return 0;
2821 /* Parse a string into a sequence of filenames represented as a chain of
2822 struct nameseq's and return that chain. Optionally expand the strings via
2823 glob().
2825 The string is passed as STRINGP, the address of a string pointer.
2826 The string pointer is updated to point at the first character
2827 not parsed, which either is a null char or equals STOPCHAR.
2829 SIZE is how big to construct chain elements.
2830 This is useful if we want them actually to be other structures
2831 that have room for additional info.
2833 PREFIX, if non-null, is added to the beginning of each filename.
2835 FLAGS allows one or more of the following bitflags to be set:
2836 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2837 PARSEFS_NOAR - Do not check filenames for archive references
2838 PARSEFS_NOGLOB - Do not expand globbing characters
2839 PARSEFS_EXISTS - Only return globbed files that actually exist
2840 (cannot also set NOGLOB)
2841 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2844 void *
2845 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2846 const char *prefix, int flags)
2848 extern void dir_setup_glob (glob_t *glob);
2850 /* tmp points to tmpbuf after the prefix, if any.
2851 tp is the end of the buffer. */
2852 static char *tmpbuf = NULL;
2853 static int tmpbuf_len = 0;
2855 int cachep = (! (flags & PARSEFS_NOCACHE));
2857 struct nameseq *new = 0;
2858 struct nameseq **newp = &new;
2859 #define NEWELT(_n) do { \
2860 const char *__n = (_n); \
2861 *newp = xcalloc (size); \
2862 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2863 newp = &(*newp)->next; \
2864 } while(0)
2866 char *p;
2867 glob_t gl;
2868 char *tp;
2870 #ifdef VMS
2871 # define VMS_COMMA ','
2872 #else
2873 # define VMS_COMMA 0
2874 #endif
2876 if (size < sizeof (struct nameseq))
2877 size = sizeof (struct nameseq);
2879 if (! (flags & PARSEFS_NOGLOB))
2880 dir_setup_glob (&gl);
2882 /* Get enough temporary space to construct the largest possible target. */
2884 int l = strlen (*stringp) + 1;
2885 if (l > tmpbuf_len)
2887 tmpbuf = xrealloc (tmpbuf, l);
2888 tmpbuf_len = l;
2891 tp = tmpbuf;
2893 /* Parse STRING. P will always point to the end of the parsed content. */
2894 p = *stringp;
2895 while (1)
2897 const char *name;
2898 const char **nlist = 0;
2899 char *tildep = 0;
2900 #ifndef NO_ARCHIVES
2901 char *arname = 0;
2902 char *memname = 0;
2903 #endif
2904 char *s;
2905 int nlen;
2906 int i;
2908 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2909 p = next_token (p);
2910 if (*p == '\0' || *p == stopchar)
2911 break;
2913 /* There are names left, so find the end of the next name.
2914 Throughout this iteration S points to the start. */
2915 s = p;
2916 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2917 #ifdef VMS
2918 /* convert comma separated list to space separated */
2919 if (p && *p == ',')
2920 *p =' ';
2921 #endif
2922 #ifdef _AMIGA
2923 if (stopchar == ':' && p && *p == ':'
2924 && !(isspace ((unsigned char)p[1]) || !p[1]
2925 || isspace ((unsigned char)p[-1])))
2926 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2927 #endif
2928 #ifdef HAVE_DOS_PATHS
2929 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2930 first colon which isn't followed by a slash or a backslash.
2931 Note that tokens separated by spaces should be treated as separate
2932 tokens since make doesn't allow path names with spaces */
2933 if (stopchar == ':')
2934 while (p != 0 && !isspace ((unsigned char)*p) &&
2935 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2936 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2937 #endif
2938 if (p == 0)
2939 p = s + strlen (s);
2941 /* Strip leading "this directory" references. */
2942 if (! (flags & PARSEFS_NOSTRIP))
2943 #ifdef VMS
2944 /* Skip leading `[]'s. */
2945 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2946 #else
2947 /* Skip leading `./'s. */
2948 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2949 #endif
2951 /* Skip "./" and all following slashes. */
2952 s += 2;
2953 while (*s == '/')
2954 ++s;
2957 /* Extract the filename just found, and skip it.
2958 Set NAME to the string, and NLEN to its length. */
2960 if (s == p)
2962 /* The name was stripped to empty ("./"). */
2963 #if defined(VMS)
2964 continue;
2965 #elif defined(_AMIGA)
2966 /* PDS-- This cannot be right!! */
2967 tp[0] = '\0';
2968 nlen = 0;
2969 #else
2970 tp[0] = '.';
2971 tp[1] = '/';
2972 tp[2] = '\0';
2973 nlen = 2;
2974 #endif
2976 else
2978 #ifdef VMS
2979 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2980 * to remove this '\' before we can use the filename.
2981 * xstrdup called because S may be read-only string constant.
2983 char *n = tp;
2984 while (s < p)
2986 if (s[0] == '\\' && s[1] == ':')
2987 ++s;
2988 *(n++) = *(s++);
2990 n[0] = '\0';
2991 nlen = strlen (tp);
2992 #else
2993 nlen = p - s;
2994 memcpy (tp, s, nlen);
2995 tp[nlen] = '\0';
2996 #endif
2999 /* At this point, TP points to the element and NLEN is its length. */
3001 #ifndef NO_ARCHIVES
3002 /* If this is the start of an archive group that isn't complete, set up
3003 to add the archive prefix for future files. A file list like:
3004 "libf.a(x.o y.o z.o)" needs to be expanded as:
3005 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3007 TP == TMP means we're not already in an archive group. Ignore
3008 something starting with `(', as that cannot actually be an
3009 archive-member reference (and treating it as such results in an empty
3010 file name, which causes much lossage). Also if it ends in ")" then
3011 it's a complete reference so we don't need to treat it specially.
3013 Finally, note that archive groups must end with ')' as the last
3014 character, so ensure there's some word ending like that before
3015 considering this an archive group. */
3016 if (! (flags & PARSEFS_NOAR)
3017 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3019 char *n = strchr (tp, '(');
3020 if (n)
3022 /* This looks like the first element in an open archive group.
3023 A valid group MUST have ')' as the last character. */
3024 const char *e = p;
3027 e = next_token (e);
3028 /* Find the end of this word. We don't want to unquote and
3029 we don't care about quoting since we're looking for the
3030 last char in the word. */
3031 while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3032 && ! isblank ((unsigned char) *e))
3033 ++e;
3034 if (e[-1] == ')')
3036 /* Found the end, so this is the first element in an
3037 open archive group. It looks like "lib(mem".
3038 Reset TP past the open paren. */
3039 nlen -= (n + 1) - tp;
3040 tp = n + 1;
3042 /* If we have just "lib(", part of something like
3043 "lib( a b)", go to the next item. */
3044 if (! nlen)
3045 continue;
3047 /* We can stop looking now. */
3048 break;
3051 while (*e != '\0');
3055 /* If we are inside an archive group, make sure it has an end. */
3056 if (tp > tmpbuf)
3058 if (tp[nlen-1] == ')')
3060 /* This is the natural end; reset TP. */
3061 tp = tmpbuf;
3063 /* This is just ")", something like "lib(a b )": skip it. */
3064 if (nlen == 1)
3065 continue;
3067 else
3069 /* Not the end, so add a "fake" end. */
3070 tp[nlen++] = ')';
3071 tp[nlen] = '\0';
3074 #endif
3076 /* If we're not globbing we're done: add it to the end of the chain.
3077 Go to the next item in the string. */
3078 if (flags & PARSEFS_NOGLOB)
3080 NEWELT (concat (2, prefix, tmpbuf));
3081 continue;
3084 /* If we get here we know we're doing glob expansion.
3085 TP is a string in tmpbuf. NLEN is no longer used.
3086 We may need to do more work: after this NAME will be set. */
3087 name = tmpbuf;
3089 /* Expand tilde if applicable. */
3090 if (tmpbuf[0] == '~')
3092 tildep = tilde_expand (tmpbuf);
3093 if (tildep != 0)
3094 name = tildep;
3097 #ifndef NO_ARCHIVES
3098 /* If NAME is an archive member reference replace it with the archive
3099 file name, and save the member name in MEMNAME. We will glob on the
3100 archive name and then reattach MEMNAME later. */
3101 if (! (flags & PARSEFS_NOAR) && ar_name (name))
3103 ar_parse_name (name, &arname, &memname);
3104 name = arname;
3106 #endif /* !NO_ARCHIVES */
3108 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3110 case GLOB_NOSPACE:
3111 fatal (NILF, _("virtual memory exhausted"));
3113 case 0:
3114 /* Success. */
3115 i = gl.gl_pathc;
3116 nlist = (const char **)gl.gl_pathv;
3117 break;
3119 case GLOB_NOMATCH:
3120 /* If we want only existing items, skip this one. */
3121 if (flags & PARSEFS_EXISTS)
3123 i = 0;
3124 break;
3126 /* FALLTHROUGH */
3128 default:
3129 /* By default keep this name. */
3130 i = 1;
3131 nlist = &name;
3132 break;
3135 /* For each matched element, add it to the list. */
3136 while (i-- > 0)
3137 #ifndef NO_ARCHIVES
3138 if (memname != 0)
3140 /* Try to glob on MEMNAME within the archive. */
3141 struct nameseq *found = ar_glob (nlist[i], memname, size);
3142 if (! found)
3143 /* No matches. Use MEMNAME as-is. */
3144 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3145 else
3147 /* We got a chain of items. Attach them. */
3148 if (*newp)
3149 (*newp)->next = found;
3150 else
3151 *newp = found;
3153 /* Find and set the new end. Massage names if necessary. */
3154 while (1)
3156 if (! cachep)
3157 found->name = xstrdup (concat (2, prefix, name));
3158 else if (prefix)
3159 found->name = strcache_add (concat (2, prefix, name));
3161 if (found->next == 0)
3162 break;
3164 found = found->next;
3166 newp = &found->next;
3169 else
3170 #endif /* !NO_ARCHIVES */
3171 NEWELT (concat (2, prefix, nlist[i]));
3173 globfree (&gl);
3175 #ifndef NO_ARCHIVES
3176 if (arname)
3177 free (arname);
3178 #endif
3180 if (tildep)
3181 free (tildep);
3184 *stringp = p;
3185 return new;