Update the required version of gettext to get new bugfix macros.
[make.git] / read.c
blob677c2333da40161af463f9267bd5022349603327
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 _without_ ending any rule that we happen to be working
599 with at the moment. If you see a "goto rule_complete", then the
600 statement we just parsed also finishes the previous rule. */
602 commands = xmalloc (200);
604 while (1)
606 unsigned int linelen;
607 char *line;
608 unsigned int wlen;
609 char *p;
610 char *p2;
611 struct vmodifiers vmod;
613 /* At the top of this loop, we are starting a brand new line. */
614 /* Grab the next line to be evaluated */
615 ebuf->floc.lineno += nlines;
616 nlines = readline (ebuf);
618 /* If there is nothing left to eval, we're done. */
619 if (nlines < 0)
620 break;
622 line = ebuf->buffer;
624 /* If this is the first line, check for a UTF-8 BOM and skip it. */
625 if (ebuf->floc.lineno == 1 && line[0] == (char)0xEF
626 && line[1] == (char)0xBB && line[2] == (char)0xBF)
628 line += 3;
629 if (ISDB(DB_BASIC))
631 if (ebuf->floc.filenm)
632 printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
633 ebuf->floc.filenm);
634 else
635 printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
639 /* If this line is empty, skip it. */
640 if (line[0] == '\0')
641 continue;
643 linelen = strlen (line);
645 /* Check for a shell command line first.
646 If it is not one, we can stop treating cmd_prefix specially. */
647 if (line[0] == cmd_prefix)
649 if (no_targets)
650 /* Ignore the commands in a rule with no targets. */
651 continue;
653 /* If there is no preceding rule line, don't treat this line
654 as a command, even though it begins with a recipe prefix.
655 SunOS 4 make appears to behave this way. */
657 if (filenames != 0)
659 if (ignoring)
660 /* Yep, this is a shell command, and we don't care. */
661 continue;
663 if (commands_idx == 0)
664 cmds_started = ebuf->floc.lineno;
666 /* Append this command line to the line being accumulated.
667 Skip the initial command prefix character. */
668 if (linelen + commands_idx > commands_len)
670 commands_len = (linelen + commands_idx) * 2;
671 commands = xrealloc (commands, commands_len);
673 memcpy (&commands[commands_idx], line + 1, linelen - 1);
674 commands_idx += linelen - 1;
675 commands[commands_idx++] = '\n';
676 continue;
680 /* This line is not a shell command line. Don't worry about whitespace.
681 Get more space if we need it; we don't need to preserve the current
682 contents of the buffer. */
684 if (collapsed_length < linelen+1)
686 collapsed_length = linelen+1;
687 if (collapsed)
688 free (collapsed);
689 /* Don't need xrealloc: we don't need to preserve the content. */
690 collapsed = xmalloc (collapsed_length);
692 strcpy (collapsed, line);
693 /* Collapse continuation lines. */
694 collapse_continuations (collapsed);
695 remove_comments (collapsed);
697 /* Get rid if starting space (including formfeed, vtab, etc.) */
698 p = collapsed;
699 while (isspace ((unsigned char)*p))
700 ++p;
702 /* See if this is a variable assignment. We need to do this early, to
703 allow variables with names like 'ifdef', 'export', 'private', etc. */
704 p = parse_var_assignment(p, &vmod);
705 if (vmod.assign_v)
707 struct variable *v;
708 enum variable_origin origin = vmod.override_v ? o_override : o_file;
710 /* If we're ignoring then we're done now. */
711 if (ignoring)
713 if (vmod.define_v)
714 in_ignored_define = 1;
715 continue;
718 if (vmod.undefine_v)
720 do_undefine (p, origin, ebuf);
722 /* This line has been dealt with. */
723 goto rule_complete;
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 goto rule_complete;
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 /* (un)export by itself causes everything to be (un)exported. */
783 if (*p2 == '\0')
784 export_all_variables = exporting;
785 else
787 unsigned int l;
788 const char *cp;
789 char *ap;
791 /* Expand the line so we can use indirect and constructed
792 variable names in an (un)export command. */
793 cp = ap = allocated_variable_expand (p2);
795 for (p = find_next_token (&cp, &l); p != 0;
796 p = find_next_token (&cp, &l))
798 struct variable *v = lookup_variable (p, l);
799 if (v == 0)
800 v = define_variable_global (p, l, "", o_file, 0, fstart);
801 v->export = exporting ? v_export : v_noexport;
804 free (ap);
806 goto rule_complete;
809 /* Handle the special syntax for vpath. */
810 if (word1eq ("vpath"))
812 const char *cp;
813 char *vpat;
814 unsigned int l;
815 cp = variable_expand (p2);
816 p = find_next_token (&cp, &l);
817 if (p != 0)
819 vpat = xstrndup (p, l);
820 p = find_next_token (&cp, &l);
821 /* No searchpath means remove all previous
822 selective VPATH's with the same pattern. */
824 else
825 /* No pattern means remove all previous selective VPATH's. */
826 vpat = 0;
827 construct_vpath_list (vpat, p);
828 if (vpat != 0)
829 free (vpat);
831 goto rule_complete;
834 /* Handle include and variants. */
835 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
837 /* We have found an 'include' line specifying a nested
838 makefile to be read at this point. */
839 struct conditionals *save;
840 struct conditionals new_conditionals;
841 struct nameseq *files;
842 /* "-include" (vs "include") says no error if the file does not
843 exist. "sinclude" is an alias for this from SGI. */
844 int noerror = (p[0] != 'i');
846 p = allocated_variable_expand (p2);
848 /* If no filenames, it's a no-op. */
849 if (*p == '\0')
851 free (p);
852 continue;
855 /* Parse the list of file names. Don't expand archive references! */
856 p2 = p;
857 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
858 PARSEFS_NOAR);
859 free (p);
861 /* Save the state of conditionals and start
862 the included makefile with a clean slate. */
863 save = install_conditionals (&new_conditionals);
865 /* Record the rules that are waiting so they will determine
866 the default goal before those in the included makefile. */
867 record_waiting_files ();
869 /* Read each included makefile. */
870 while (files != 0)
872 struct nameseq *next = files->next;
873 const char *name = files->name;
874 int r;
876 free_ns (files);
877 files = next;
879 r = eval_makefile (name,
880 (RM_INCLUDED | RM_NO_TILDE
881 | (noerror ? RM_DONTCARE : 0)
882 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
883 if (!r && !noerror)
884 error (fstart, "%s: %s", name, strerror (errno));
887 /* Restore conditional state. */
888 restore_conditionals (save);
890 goto rule_complete;
893 /* This line starts with a tab but was not caught above because there
894 was no preceding target, and the line might have been usable as a
895 variable definition. But now we know it is definitely lossage. */
896 if (line[0] == cmd_prefix)
897 fatal(fstart, _("recipe commences before first target"));
899 /* This line describes some target files. This is complicated by
900 the existence of target-specific variables, because we can't
901 expand the entire line until we know if we have one or not. So
902 we expand the line word by word until we find the first ':',
903 then check to see if it's a target-specific variable.
905 In this algorithm, 'lb_next' will point to the beginning of the
906 unexpanded parts of the input buffer, while 'p2' points to the
907 parts of the expanded buffer we haven't searched yet. */
910 enum make_word_type wtype;
911 char *cmdleft, *semip, *lb_next;
912 unsigned int plen = 0;
913 char *colonp;
914 const char *end, *beg; /* Helpers for whitespace stripping. */
916 /* Record the previous rule. */
918 record_waiting_files ();
919 tgts_started = fstart->lineno;
921 /* Search the line for an unquoted ; that is not after an
922 unquoted #. */
923 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
924 if (cmdleft != 0 && *cmdleft == '#')
926 /* We found a comment before a semicolon. */
927 *cmdleft = '\0';
928 cmdleft = 0;
930 else if (cmdleft != 0)
931 /* Found one. Cut the line short there before expanding it. */
932 *(cmdleft++) = '\0';
933 semip = cmdleft;
935 collapse_continuations (line);
937 /* We can't expand the entire line, since if it's a per-target
938 variable we don't want to expand it. So, walk from the
939 beginning, expanding as we go, and looking for "interesting"
940 chars. The first word is always expandable. */
941 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
942 switch (wtype)
944 case w_eol:
945 if (cmdleft != 0)
946 fatal(fstart, _("missing rule before recipe"));
947 /* This line contained something but turned out to be nothing
948 but whitespace (a comment?). */
949 continue;
951 case w_colon:
952 case w_dcolon:
953 /* We accept and ignore rules without targets for
954 compatibility with SunOS 4 make. */
955 no_targets = 1;
956 continue;
958 default:
959 break;
962 p2 = variable_expand_string(NULL, lb_next, wlen);
964 while (1)
966 lb_next += wlen;
967 if (cmdleft == 0)
969 /* Look for a semicolon in the expanded line. */
970 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
972 if (cmdleft != 0)
974 unsigned long p2_off = p2 - variable_buffer;
975 unsigned long cmd_off = cmdleft - variable_buffer;
976 char *pend = p2 + strlen(p2);
978 /* Append any remnants of lb, then cut the line short
979 at the semicolon. */
980 *cmdleft = '\0';
982 /* One school of thought says that you shouldn't expand
983 here, but merely copy, since now you're beyond a ";"
984 and into a command script. However, the old parser
985 expanded the whole line, so we continue that for
986 backwards-compatiblity. Also, it wouldn't be
987 entirely consistent, since we do an unconditional
988 expand below once we know we don't have a
989 target-specific variable. */
990 (void)variable_expand_string(pend, lb_next, (long)-1);
991 lb_next += strlen(lb_next);
992 p2 = variable_buffer + p2_off;
993 cmdleft = variable_buffer + cmd_off + 1;
997 colonp = find_char_unquote(p2, ':', 0, 0, 0);
998 #ifdef HAVE_DOS_PATHS
999 /* The drive spec brain-damage strikes again... */
1000 /* Note that the only separators of targets in this context
1001 are whitespace and a left paren. If others are possible,
1002 they should be added to the string in the call to index. */
1003 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
1004 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
1005 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1006 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
1007 #endif
1008 if (colonp != 0)
1009 break;
1011 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
1012 if (wtype == w_eol)
1013 break;
1015 p2 += strlen(p2);
1016 *(p2++) = ' ';
1017 p2 = variable_expand_string(p2, lb_next, wlen);
1018 /* We don't need to worry about cmdleft here, because if it was
1019 found in the variable_buffer the entire buffer has already
1020 been expanded... we'll never get here. */
1023 p2 = next_token (variable_buffer);
1025 /* If the word we're looking at is EOL, see if there's _anything_
1026 on the line. If not, a variable expanded to nothing, so ignore
1027 it. If so, we can't parse this line so punt. */
1028 if (wtype == w_eol)
1030 if (*p2 != '\0')
1031 /* There's no need to be ivory-tower about this: check for
1032 one of the most common bugs found in makefiles... */
1033 fatal (fstart, _("missing separator%s"),
1034 (cmd_prefix == '\t' && !strneq (line, " ", 8))
1035 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1036 continue;
1039 /* Make the colon the end-of-string so we know where to stop
1040 looking for targets. Start there again once we're done. */
1041 *colonp = '\0';
1042 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1043 *colonp = ':';
1044 p2 = colonp;
1046 if (!filenames)
1048 /* We accept and ignore rules without targets for
1049 compatibility with SunOS 4 make. */
1050 no_targets = 1;
1051 continue;
1053 /* This should never be possible; we handled it above. */
1054 assert (*p2 != '\0');
1055 ++p2;
1057 /* Is this a one-colon or two-colon entry? */
1058 two_colon = *p2 == ':';
1059 if (two_colon)
1060 p2++;
1062 /* Test to see if it's a target-specific variable. Copy the rest
1063 of the buffer over, possibly temporarily (we'll expand it later
1064 if it's not a target-specific variable). PLEN saves the length
1065 of the unparsed section of p2, for later. */
1066 if (*lb_next != '\0')
1068 unsigned int l = p2 - variable_buffer;
1069 plen = strlen (p2);
1070 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1071 p2 = variable_buffer + l;
1074 p2 = parse_var_assignment (p2, &vmod);
1075 if (vmod.assign_v)
1077 /* If there was a semicolon found, add it back, plus anything
1078 after it. */
1079 if (semip)
1081 unsigned int l = p2 - variable_buffer;
1082 *(--semip) = ';';
1083 collapse_continuations (semip);
1084 variable_buffer_output (p2 + strlen (p2),
1085 semip, strlen (semip)+1);
1086 p2 = variable_buffer + l;
1088 record_target_var (filenames, p2,
1089 vmod.override_v ? o_override : o_file,
1090 &vmod, fstart);
1091 filenames = 0;
1092 continue;
1095 /* This is a normal target, _not_ a target-specific variable.
1096 Unquote any = in the dependency list. */
1097 find_char_unquote (lb_next, '=', 0, 0, 0);
1099 /* Remember the command prefix for this target. */
1100 prefix = cmd_prefix;
1102 /* We have some targets, so don't ignore the following commands. */
1103 no_targets = 0;
1105 /* Expand the dependencies, etc. */
1106 if (*lb_next != '\0')
1108 unsigned int l = p2 - variable_buffer;
1109 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1110 p2 = variable_buffer + l;
1112 /* Look for a semicolon in the expanded line. */
1113 if (cmdleft == 0)
1115 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1116 if (cmdleft != 0)
1117 *(cmdleft++) = '\0';
1121 /* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
1122 p = strchr (p2, ':');
1123 while (p != 0 && p[-1] == '\\')
1125 char *q = &p[-1];
1126 int backslash = 0;
1127 while (*q-- == '\\')
1128 backslash = !backslash;
1129 if (backslash)
1130 p = strchr (p + 1, ':');
1131 else
1132 break;
1134 #ifdef _AMIGA
1135 /* Here, the situation is quite complicated. Let's have a look
1136 at a couple of targets:
1138 install: dev:make
1140 dev:make: make
1142 dev:make:: xyz
1144 The rule is that it's only a target, if there are TWO :'s
1145 OR a space around the :.
1147 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1148 || isspace ((unsigned char)p[-1])))
1149 p = 0;
1150 #endif
1151 #ifdef HAVE_DOS_PATHS
1153 int check_again;
1154 do {
1155 check_again = 0;
1156 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1157 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1158 isalpha ((unsigned char)p[-1]) &&
1159 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1160 p = strchr (p + 1, ':');
1161 check_again = 1;
1163 } while (check_again);
1165 #endif
1166 if (p != 0)
1168 struct nameseq *target;
1169 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1170 PARSEFS_NOGLOB);
1171 ++p2;
1172 if (target == 0)
1173 fatal (fstart, _("missing target pattern"));
1174 else if (target->next != 0)
1175 fatal (fstart, _("multiple target patterns"));
1176 pattern_percent = find_percent_cached (&target->name);
1177 pattern = target->name;
1178 if (pattern_percent == 0)
1179 fatal (fstart, _("target pattern contains no '%%'"));
1180 free_ns (target);
1182 else
1183 pattern = 0;
1185 /* Strip leading and trailing whitespaces. */
1186 beg = p2;
1187 end = beg + strlen (beg) - 1;
1188 strip_whitespace (&beg, &end);
1190 /* Put all the prerequisites here; they'll be parsed later. */
1191 if (beg <= end && *beg != '\0')
1192 depstr = xstrndup (beg, end - beg + 1);
1193 else
1194 depstr = 0;
1196 commands_idx = 0;
1197 if (cmdleft != 0)
1199 /* Semicolon means rest of line is a command. */
1200 unsigned int l = strlen (cmdleft);
1202 cmds_started = fstart->lineno;
1204 /* Add this command line to the buffer. */
1205 if (l + 2 > commands_len)
1207 commands_len = (l + 2) * 2;
1208 commands = xrealloc (commands, commands_len);
1210 memcpy (commands, cmdleft, l);
1211 commands_idx += l;
1212 commands[commands_idx++] = '\n';
1215 /* Determine if this target should be made default. We used to do
1216 this in record_files() but because of the delayed target recording
1217 and because preprocessor directives are legal in target's commands
1218 it is too late. Consider this fragment for example:
1220 foo:
1222 ifeq ($(.DEFAULT_GOAL),foo)
1224 endif
1226 Because the target is not recorded until after ifeq directive is
1227 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1228 would expect. Because of this we have to move the logic here. */
1230 if (set_default && default_goal_var->value[0] == '\0')
1232 const char *name;
1233 struct dep *d;
1234 struct nameseq *t = filenames;
1236 for (; t != 0; t = t->next)
1238 int reject = 0;
1239 name = t->name;
1241 /* We have nothing to do if this is an implicit rule. */
1242 if (strchr (name, '%') != 0)
1243 break;
1245 /* See if this target's name does not start with a '.',
1246 unless it contains a slash. */
1247 if (*name == '.' && strchr (name, '/') == 0
1248 #ifdef HAVE_DOS_PATHS
1249 && strchr (name, '\\') == 0
1250 #endif
1252 continue;
1255 /* If this file is a suffix, don't let it be
1256 the default goal file. */
1257 for (d = suffix_file->deps; d != 0; d = d->next)
1259 register struct dep *d2;
1260 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1262 reject = 1;
1263 break;
1265 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1267 unsigned int l = strlen (dep_name (d2));
1268 if (!strneq (name, dep_name (d2), l))
1269 continue;
1270 if (streq (name + l, dep_name (d)))
1272 reject = 1;
1273 break;
1277 if (reject)
1278 break;
1281 if (!reject)
1283 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1284 o_file, 0, NILF);
1285 break;
1290 continue;
1293 /* We get here except in the case that we just read a rule line.
1294 Record now the last rule we read, so following spurious
1295 commands are properly diagnosed. */
1296 rule_complete:
1297 record_waiting_files ();
1300 #undef word1eq
1302 if (conditionals->if_cmds)
1303 fatal (fstart, _("missing 'endif'"));
1305 /* At eof, record the last rule. */
1306 record_waiting_files ();
1308 if (collapsed)
1309 free (collapsed);
1310 free (commands);
1314 /* Remove comments from LINE.
1315 This is done by copying the text at LINE onto itself. */
1317 static void
1318 remove_comments (char *line)
1320 char *comment;
1322 comment = find_char_unquote (line, '#', 0, 0, 0);
1324 if (comment != 0)
1325 /* Cut off the line at the #. */
1326 *comment = '\0';
1329 /* Execute a 'undefine' directive.
1330 The undefine line has already been read, and NAME is the name of
1331 the variable to be undefined. */
1333 static void
1334 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1336 char *p, *var;
1338 /* Expand the variable name and find the beginning (NAME) and end. */
1339 var = allocated_variable_expand (name);
1340 name = next_token (var);
1341 if (*name == '\0')
1342 fatal (&ebuf->floc, _("empty variable name"));
1343 p = name + strlen (name) - 1;
1344 while (p > name && isblank ((unsigned char)*p))
1345 --p;
1346 p[1] = '\0';
1348 undefine_variable_global (name, p - name + 1, origin);
1349 free (var);
1352 /* Execute a 'define' directive.
1353 The first line has already been read, and NAME is the name of
1354 the variable to be defined. The following lines remain to be read. */
1356 static struct variable *
1357 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1359 struct variable *v;
1360 struct variable var;
1361 struct floc defstart;
1362 int nlevels = 1;
1363 unsigned int length = 100;
1364 char *definition = xmalloc (length);
1365 unsigned int idx = 0;
1366 char *p, *n;
1368 defstart = ebuf->floc;
1370 p = parse_variable_definition (name, &var);
1371 if (p == NULL)
1372 /* No assignment token, so assume recursive. */
1373 var.flavor = f_recursive;
1374 else
1376 if (var.value[0] != '\0')
1377 error (&defstart, _("extraneous text after 'define' directive"));
1379 /* Chop the string before the assignment token to get the name. */
1380 var.name[var.length] = '\0';
1383 /* Expand the variable name and find the beginning (NAME) and end. */
1384 n = allocated_variable_expand (name);
1385 name = next_token (n);
1386 if (name[0] == '\0')
1387 fatal (&defstart, _("empty variable name"));
1388 p = name + strlen (name) - 1;
1389 while (p > name && isblank ((unsigned char)*p))
1390 --p;
1391 p[1] = '\0';
1393 /* Now read the value of the variable. */
1394 while (1)
1396 unsigned int len;
1397 char *line;
1398 long nlines = readline (ebuf);
1400 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1401 if (nlines < 0)
1402 fatal (&defstart, _("missing 'endef', unterminated 'define'"));
1404 ebuf->floc.lineno += nlines;
1405 line = ebuf->buffer;
1407 collapse_continuations (line);
1409 /* If the line doesn't begin with a tab, test to see if it introduces
1410 another define, or ends one. Stop if we find an 'endef' */
1411 if (line[0] != cmd_prefix)
1413 p = next_token (line);
1414 len = strlen (p);
1416 /* If this is another 'define', increment the level count. */
1417 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1418 && strneq (p, "define", 6))
1419 ++nlevels;
1421 /* If this is an 'endef', decrement the count. If it's now 0,
1422 we've found the last one. */
1423 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1424 && strneq (p, "endef", 5))
1426 p += 5;
1427 remove_comments (p);
1428 if (*(next_token (p)) != '\0')
1429 error (&ebuf->floc,
1430 _("extraneous text after 'endef' directive"));
1432 if (--nlevels == 0)
1433 break;
1437 /* Add this line to the variable definition. */
1438 len = strlen (line);
1439 if (idx + len + 1 > length)
1441 length = (idx + len) * 2;
1442 definition = xrealloc (definition, length + 1);
1445 memcpy (&definition[idx], line, len);
1446 idx += len;
1447 /* Separate lines with a newline. */
1448 definition[idx++] = '\n';
1451 /* We've got what we need; define the variable. */
1452 if (idx == 0)
1453 definition[0] = '\0';
1454 else
1455 definition[idx - 1] = '\0';
1457 v = do_variable_definition (&defstart, name,
1458 definition, origin, var.flavor, 0);
1459 free (definition);
1460 free (n);
1461 return (v);
1464 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1465 "ifneq", "else" and "endif".
1466 LINE is the input line, with the command as its first word.
1468 FILENAME and LINENO are the filename and line number in the
1469 current makefile. They are used for error messages.
1471 Value is -2 if the line is not a conditional at all,
1472 -1 if the line is an invalid conditional,
1473 0 if following text should be interpreted,
1474 1 if following text should be ignored. */
1476 static int
1477 conditional_line (char *line, int len, const struct floc *flocp)
1479 char *cmdname;
1480 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1481 unsigned int i;
1482 unsigned int o;
1484 /* Compare a word, both length and contents. */
1485 #define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
1486 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1488 /* Make sure this line is a conditional. */
1489 chkword ("ifdef", c_ifdef)
1490 else chkword ("ifndef", c_ifndef)
1491 else chkword ("ifeq", c_ifeq)
1492 else chkword ("ifneq", c_ifneq)
1493 else chkword ("else", c_else)
1494 else chkword ("endif", c_endif)
1495 else
1496 return -2;
1498 /* Found one: skip past it and any whitespace after it. */
1499 line = next_token (line + len);
1501 #define EXTRANEOUS() error (flocp, _("Extraneous text after '%s' directive"), cmdname)
1503 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1504 if (cmdtype == c_endif)
1506 if (*line != '\0')
1507 EXTRANEOUS ();
1509 if (!conditionals->if_cmds)
1510 fatal (flocp, _("extraneous '%s'"), cmdname);
1512 --conditionals->if_cmds;
1514 goto DONE;
1517 /* An 'else' statement can either be simple, or it can have another
1518 conditional after it. */
1519 if (cmdtype == c_else)
1521 const char *p;
1523 if (!conditionals->if_cmds)
1524 fatal (flocp, _("extraneous '%s'"), cmdname);
1526 o = conditionals->if_cmds - 1;
1528 if (conditionals->seen_else[o])
1529 fatal (flocp, _("only one 'else' per conditional"));
1531 /* Change the state of ignorance. */
1532 switch (conditionals->ignoring[o])
1534 case 0:
1535 /* We've just been interpreting. Never do it again. */
1536 conditionals->ignoring[o] = 2;
1537 break;
1538 case 1:
1539 /* We've never interpreted yet. Maybe this time! */
1540 conditionals->ignoring[o] = 0;
1541 break;
1544 /* It's a simple 'else'. */
1545 if (*line == '\0')
1547 conditionals->seen_else[o] = 1;
1548 goto DONE;
1551 /* The 'else' has extra text. That text must be another conditional
1552 and cannot be an 'else' or 'endif'. */
1554 /* Find the length of the next word. */
1555 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1557 len = p - line;
1559 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1560 if (word1eq ("else") || word1eq ("endif")
1561 || conditional_line (line, len, flocp) < 0)
1562 EXTRANEOUS ();
1563 else
1565 /* conditional_line() created a new level of conditional.
1566 Raise it back to this level. */
1567 if (conditionals->ignoring[o] < 2)
1568 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1569 --conditionals->if_cmds;
1572 goto DONE;
1575 if (conditionals->allocated == 0)
1577 conditionals->allocated = 5;
1578 conditionals->ignoring = xmalloc (conditionals->allocated);
1579 conditionals->seen_else = xmalloc (conditionals->allocated);
1582 o = conditionals->if_cmds++;
1583 if (conditionals->if_cmds > conditionals->allocated)
1585 conditionals->allocated += 5;
1586 conditionals->ignoring = xrealloc (conditionals->ignoring,
1587 conditionals->allocated);
1588 conditionals->seen_else = xrealloc (conditionals->seen_else,
1589 conditionals->allocated);
1592 /* Record that we have seen an 'if...' but no 'else' so far. */
1593 conditionals->seen_else[o] = 0;
1595 /* Search through the stack to see if we're already ignoring. */
1596 for (i = 0; i < o; ++i)
1597 if (conditionals->ignoring[i])
1599 /* We are already ignoring, so just push a level to match the next
1600 "else" or "endif", and keep ignoring. We don't want to expand
1601 variables in the condition. */
1602 conditionals->ignoring[o] = 1;
1603 return 1;
1606 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1608 char *var;
1609 struct variable *v;
1610 char *p;
1612 /* Expand the thing we're looking up, so we can use indirect and
1613 constructed variable names. */
1614 var = allocated_variable_expand (line);
1616 /* Make sure there's only one variable name to test. */
1617 p = end_of_token (var);
1618 i = p - var;
1619 p = next_token (p);
1620 if (*p != '\0')
1621 return -1;
1623 var[i] = '\0';
1624 v = lookup_variable (var, i);
1626 conditionals->ignoring[o] =
1627 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1629 free (var);
1631 else
1633 /* "ifeq" or "ifneq". */
1634 char *s1, *s2;
1635 unsigned int l;
1636 char termin = *line == '(' ? ',' : *line;
1638 if (termin != ',' && termin != '"' && termin != '\'')
1639 return -1;
1641 s1 = ++line;
1642 /* Find the end of the first string. */
1643 if (termin == ',')
1645 int count = 0;
1646 for (; *line != '\0'; ++line)
1647 if (*line == '(')
1648 ++count;
1649 else if (*line == ')')
1650 --count;
1651 else if (*line == ',' && count <= 0)
1652 break;
1654 else
1655 while (*line != '\0' && *line != termin)
1656 ++line;
1658 if (*line == '\0')
1659 return -1;
1661 if (termin == ',')
1663 /* Strip blanks after the first string. */
1664 char *p = line++;
1665 while (isblank ((unsigned char)p[-1]))
1666 --p;
1667 *p = '\0';
1669 else
1670 *line++ = '\0';
1672 s2 = variable_expand (s1);
1673 /* We must allocate a new copy of the expanded string because
1674 variable_expand re-uses the same buffer. */
1675 l = strlen (s2);
1676 s1 = alloca (l + 1);
1677 memcpy (s1, s2, l + 1);
1679 if (termin != ',')
1680 /* Find the start of the second string. */
1681 line = next_token (line);
1683 termin = termin == ',' ? ')' : *line;
1684 if (termin != ')' && termin != '"' && termin != '\'')
1685 return -1;
1687 /* Find the end of the second string. */
1688 if (termin == ')')
1690 int count = 0;
1691 s2 = next_token (line);
1692 for (line = s2; *line != '\0'; ++line)
1694 if (*line == '(')
1695 ++count;
1696 else if (*line == ')')
1698 if (count <= 0)
1699 break;
1700 else
1701 --count;
1705 else
1707 ++line;
1708 s2 = line;
1709 while (*line != '\0' && *line != termin)
1710 ++line;
1713 if (*line == '\0')
1714 return -1;
1716 *line = '\0';
1717 line = next_token (++line);
1718 if (*line != '\0')
1719 EXTRANEOUS ();
1721 s2 = variable_expand (s2);
1722 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1725 DONE:
1726 /* Search through the stack to see if we're ignoring. */
1727 for (i = 0; i < conditionals->if_cmds; ++i)
1728 if (conditionals->ignoring[i])
1729 return 1;
1730 return 0;
1734 /* Record target-specific variable values for files FILENAMES.
1735 TWO_COLON is nonzero if a double colon was used.
1737 The links of FILENAMES are freed, and so are any names in it
1738 that are not incorporated into other data structures.
1740 If the target is a pattern, add the variable to the pattern-specific
1741 variable value list. */
1743 static void
1744 record_target_var (struct nameseq *filenames, char *defn,
1745 enum variable_origin origin, struct vmodifiers *vmod,
1746 const struct floc *flocp)
1748 struct nameseq *nextf;
1749 struct variable_set_list *global;
1751 global = current_variable_set_list;
1753 /* If the variable is an append version, store that but treat it as a
1754 normal recursive variable. */
1756 for (; filenames != 0; filenames = nextf)
1758 struct variable *v;
1759 const char *name = filenames->name;
1760 const char *percent;
1761 struct pattern_var *p;
1763 nextf = filenames->next;
1764 free_ns (filenames);
1766 /* If it's a pattern target, then add it to the pattern-specific
1767 variable list. */
1768 percent = find_percent_cached (&name);
1769 if (percent)
1771 /* Get a reference for this pattern-specific variable struct. */
1772 p = create_pattern_var (name, percent);
1773 p->variable.fileinfo = *flocp;
1774 /* I don't think this can fail since we already determined it was a
1775 variable definition. */
1776 v = assign_variable_definition (&p->variable, defn);
1777 assert (v != 0);
1779 v->origin = origin;
1780 if (v->flavor == f_simple)
1781 v->value = allocated_variable_expand (v->value);
1782 else
1783 v->value = xstrdup (v->value);
1785 else
1787 struct file *f;
1789 /* Get a file reference for this file, and initialize it.
1790 We don't want to just call enter_file() because that allocates a
1791 new entry if the file is a double-colon, which we don't want in
1792 this situation. */
1793 f = lookup_file (name);
1794 if (!f)
1795 f = enter_file (strcache_add (name));
1796 else if (f->double_colon)
1797 f = f->double_colon;
1799 initialize_file_variables (f, 1);
1801 current_variable_set_list = f->variables;
1802 v = try_variable_definition (flocp, defn, origin, 1);
1803 if (!v)
1804 fatal (flocp, _("Malformed target-specific variable definition"));
1805 current_variable_set_list = global;
1808 /* Set up the variable to be *-specific. */
1809 v->per_target = 1;
1810 v->private_var = vmod->private_v;
1811 v->export = vmod->export_v ? v_export : v_default;
1813 /* If it's not an override, check to see if there was a command-line
1814 setting. If so, reset the value. */
1815 if (v->origin != o_override)
1817 struct variable *gv;
1818 int len = strlen(v->name);
1820 gv = lookup_variable (v->name, len);
1821 if (gv && v != gv
1822 && (gv->origin == o_env_override || gv->origin == o_command))
1824 if (v->value != 0)
1825 free (v->value);
1826 v->value = xstrdup (gv->value);
1827 v->origin = gv->origin;
1828 v->recursive = gv->recursive;
1829 v->append = 0;
1835 /* Record a description line for files FILENAMES,
1836 with dependencies DEPS, commands to execute described
1837 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1838 TWO_COLON is nonzero if a double colon was used.
1839 If not nil, PATTERN is the '%' pattern to make this
1840 a static pattern rule, and PATTERN_PERCENT is a pointer
1841 to the '%' within it.
1843 The links of FILENAMES are freed, and so are any names in it
1844 that are not incorporated into other data structures. */
1846 static void
1847 record_files (struct nameseq *filenames, const char *pattern,
1848 const char *pattern_percent, char *depstr,
1849 unsigned int cmds_started, char *commands,
1850 unsigned int commands_idx, int two_colon,
1851 char prefix, const struct floc *flocp)
1853 struct commands *cmds;
1854 struct dep *deps;
1855 const char *implicit_percent;
1856 const char *name;
1858 /* If we've already snapped deps, that means we're in an eval being
1859 resolved after the makefiles have been read in. We can't add more rules
1860 at this time, since they won't get snapped and we'll get core dumps.
1861 See Savannah bug # 12124. */
1862 if (snapped_deps)
1863 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1865 /* Determine if this is a pattern rule or not. */
1866 name = filenames->name;
1867 implicit_percent = find_percent_cached (&name);
1869 /* If there's a recipe, set up a struct for it. */
1870 if (commands_idx > 0)
1872 cmds = xmalloc (sizeof (struct commands));
1873 cmds->fileinfo.filenm = flocp->filenm;
1874 cmds->fileinfo.lineno = cmds_started;
1875 cmds->commands = xstrndup (commands, commands_idx);
1876 cmds->command_lines = 0;
1877 cmds->recipe_prefix = prefix;
1879 else
1880 cmds = 0;
1882 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1883 expansion: if so, snap_deps() will do it. */
1884 if (depstr == 0)
1885 deps = 0;
1886 else
1888 depstr = unescape_char (depstr, ':');
1889 if (second_expansion && strchr (depstr, '$'))
1891 deps = alloc_dep ();
1892 deps->name = depstr;
1893 deps->need_2nd_expansion = 1;
1894 deps->staticpattern = pattern != 0;
1896 else
1898 deps = split_prereqs (depstr);
1899 free (depstr);
1901 /* We'll enter static pattern prereqs later when we have the stem.
1902 We don't want to enter pattern rules at all so that we don't
1903 think that they ought to exist (make manual "Implicit Rule Search
1904 Algorithm", item 5c). */
1905 if (! pattern && ! implicit_percent)
1906 deps = enter_prereqs (deps, NULL);
1910 /* For implicit rules, _all_ the targets must have a pattern. That means we
1911 can test the first one to see if we're working with an implicit rule; if
1912 so we handle it specially. */
1914 if (implicit_percent)
1916 struct nameseq *nextf;
1917 const char **targets, **target_pats;
1918 unsigned int c;
1920 if (pattern != 0)
1921 fatal (flocp, _("mixed implicit and static pattern rules"));
1923 /* Count the targets to create an array of target names.
1924 We already have the first one. */
1925 nextf = filenames->next;
1926 free_ns (filenames);
1927 filenames = nextf;
1929 for (c = 1; nextf; ++c, nextf = nextf->next)
1931 targets = xmalloc (c * sizeof (const char *));
1932 target_pats = xmalloc (c * sizeof (const char *));
1934 targets[0] = name;
1935 target_pats[0] = implicit_percent;
1937 c = 1;
1938 while (filenames)
1940 name = filenames->name;
1941 implicit_percent = find_percent_cached (&name);
1943 if (implicit_percent == 0)
1944 fatal (flocp, _("mixed implicit and normal rules"));
1946 targets[c] = name;
1947 target_pats[c] = implicit_percent;
1948 ++c;
1950 nextf = filenames->next;
1951 free_ns (filenames);
1952 filenames = nextf;
1955 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1957 return;
1961 /* Walk through each target and create it in the database.
1962 We already set up the first target, above. */
1963 while (1)
1965 struct nameseq *nextf = filenames->next;
1966 struct file *f;
1967 struct dep *this = 0;
1969 free_ns (filenames);
1971 /* Check for special targets. Do it here instead of, say, snap_deps()
1972 so that we can immediately use the value. */
1973 if (streq (name, ".POSIX"))
1975 posix_pedantic = 1;
1976 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1977 /* These default values are based on IEEE Std 1003.1-2008. */
1978 define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
1979 define_variable_cname ("CC", "c99", o_default, 0);
1980 define_variable_cname ("CFLAGS", "-O", o_default, 0);
1981 define_variable_cname ("FC", "fort77", o_default, 0);
1982 define_variable_cname ("FFLAGS", "-O 1", o_default, 0);
1983 define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
1985 else if (streq (name, ".SECONDEXPANSION"))
1986 second_expansion = 1;
1987 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
1988 else if (streq (name, ".ONESHELL"))
1989 one_shell = 1;
1990 #endif
1992 /* If this is a static pattern rule:
1993 'targets: target%pattern: prereq%pattern; recipe',
1994 make sure the pattern matches this target name. */
1995 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1996 error (flocp, _("target '%s' doesn't match the target pattern"), name);
1997 else if (deps)
1998 /* If there are multiple targets, copy the chain DEPS for all but the
1999 last one. It is not safe for the same deps to go in more than one
2000 place in the database. */
2001 this = nextf != 0 ? copy_dep_chain (deps) : deps;
2003 /* Find or create an entry in the file database for this target. */
2004 if (!two_colon)
2006 /* Single-colon. Combine this rule with the file's existing record,
2007 if any. */
2008 f = enter_file (strcache_add (name));
2009 if (f->double_colon)
2010 fatal (flocp,
2011 _("target file '%s' has both : and :: entries"), f->name);
2013 /* If CMDS == F->CMDS, this target was listed in this rule
2014 more than once. Just give a warning since this is harmless. */
2015 if (cmds != 0 && cmds == f->cmds)
2016 error (flocp,
2017 _("target '%s' given more than once in the same rule."),
2018 f->name);
2020 /* Check for two single-colon entries both with commands.
2021 Check is_target so that we don't lose on files such as .c.o
2022 whose commands were preinitialized. */
2023 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2025 error (&cmds->fileinfo,
2026 _("warning: overriding recipe for target '%s'"),
2027 f->name);
2028 error (&f->cmds->fileinfo,
2029 _("warning: ignoring old recipe for target '%s'"),
2030 f->name);
2033 /* Defining .DEFAULT with no deps or cmds clears it. */
2034 if (f == default_file && this == 0 && cmds == 0)
2035 f->cmds = 0;
2036 if (cmds != 0)
2037 f->cmds = cmds;
2039 /* Defining .SUFFIXES with no dependencies clears out the list of
2040 suffixes. */
2041 if (f == suffix_file && this == 0)
2043 free_dep_chain (f->deps);
2044 f->deps = 0;
2047 else
2049 /* Double-colon. Make a new record even if there already is one. */
2050 f = lookup_file (name);
2052 /* Check for both : and :: rules. Check is_target so we don't lose
2053 on default suffix rules or makefiles. */
2054 if (f != 0 && f->is_target && !f->double_colon)
2055 fatal (flocp,
2056 _("target file '%s' has both : and :: entries"), f->name);
2058 f = enter_file (strcache_add (name));
2059 /* If there was an existing entry and it was a double-colon entry,
2060 enter_file will have returned a new one, making it the prev
2061 pointer of the old one, and setting its double_colon pointer to
2062 the first one. */
2063 if (f->double_colon == 0)
2064 /* This is the first entry for this name, so we must set its
2065 double_colon pointer to itself. */
2066 f->double_colon = f;
2068 f->cmds = cmds;
2071 f->is_target = 1;
2073 /* If this is a static pattern rule, set the stem to the part of its
2074 name that matched the '%' in the pattern, so you can use $* in the
2075 commands. If we didn't do it before, enter the prereqs now. */
2076 if (pattern)
2078 static const char *percent = "%";
2079 char *buffer = variable_expand ("");
2080 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2081 pattern_percent+1, percent+1);
2082 f->stem = strcache_add_len (buffer, o - buffer);
2083 if (this)
2085 if (! this->need_2nd_expansion)
2086 this = enter_prereqs (this, f->stem);
2087 else
2088 this->stem = f->stem;
2092 /* Add the dependencies to this file entry. */
2093 if (this != 0)
2095 /* Add the file's old deps and the new ones in THIS together. */
2096 if (f->deps == 0)
2097 f->deps = this;
2098 else if (cmds != 0)
2100 struct dep *d = this;
2102 /* If this rule has commands, put these deps first. */
2103 while (d->next != 0)
2104 d = d->next;
2106 d->next = f->deps;
2107 f->deps = this;
2109 else
2111 struct dep *d = f->deps;
2113 /* A rule without commands: put its prereqs at the end. */
2114 while (d->next != 0)
2115 d = d->next;
2117 d->next = this;
2121 name = f->name;
2123 /* All done! Set up for the next one. */
2124 if (nextf == 0)
2125 break;
2127 filenames = nextf;
2129 /* Reduce escaped percents. If there are any unescaped it's an error */
2130 name = filenames->name;
2131 if (find_percent_cached (&name))
2132 fatal (flocp, _("mixed implicit and normal rules"));
2136 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2137 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2138 Quoting backslashes are removed from STRING by compacting it into
2139 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2140 one, or nil if there are none. STOPCHARs inside variable references are
2141 ignored if IGNOREVARS is true.
2143 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2145 static char *
2146 find_char_unquote (char *string, int stop1, int stop2, int blank,
2147 int ignorevars)
2149 unsigned int string_len = 0;
2150 char *p = string;
2152 if (ignorevars)
2153 ignorevars = '$';
2155 while (1)
2157 if (stop2 && blank)
2158 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2159 && ! isblank ((unsigned char) *p))
2160 ++p;
2161 else if (stop2)
2162 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2163 ++p;
2164 else if (blank)
2165 while (*p != '\0' && *p != ignorevars && *p != stop1
2166 && ! isblank ((unsigned char) *p))
2167 ++p;
2168 else
2169 while (*p != '\0' && *p != ignorevars && *p != stop1)
2170 ++p;
2172 if (*p == '\0')
2173 break;
2175 /* If we stopped due to a variable reference, skip over its contents. */
2176 if (*p == ignorevars)
2178 char openparen = p[1];
2180 p += 2;
2182 /* Skip the contents of a non-quoted, multi-char variable ref. */
2183 if (openparen == '(' || openparen == '{')
2185 unsigned int pcount = 1;
2186 char closeparen = (openparen == '(' ? ')' : '}');
2188 while (*p)
2190 if (*p == openparen)
2191 ++pcount;
2192 else if (*p == closeparen)
2193 if (--pcount == 0)
2195 ++p;
2196 break;
2198 ++p;
2202 /* Skipped the variable reference: look for STOPCHARS again. */
2203 continue;
2206 if (p > string && p[-1] == '\\')
2208 /* Search for more backslashes. */
2209 int i = -2;
2210 while (&p[i] >= string && p[i] == '\\')
2211 --i;
2212 ++i;
2213 /* Only compute the length if really needed. */
2214 if (string_len == 0)
2215 string_len = strlen (string);
2216 /* The number of backslashes is now -I.
2217 Copy P over itself to swallow half of them. */
2218 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2219 p += i/2;
2220 if (i % 2 == 0)
2221 /* All the backslashes quoted each other; the STOPCHAR was
2222 unquoted. */
2223 return p;
2225 /* The STOPCHAR was quoted by a backslash. Look for another. */
2227 else
2228 /* No backslash in sight. */
2229 return p;
2232 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2233 return 0;
2236 /* Unescape a character in a string. The string is compressed onto itself. */
2238 static char *
2239 unescape_char (char *string, int c)
2241 char *p = string;
2242 char *s = string;
2244 while (*s != '\0')
2246 if (*s == '\\')
2248 char *e = s;
2249 int l;
2251 /* We found a backslash. See if it's escaping our character. */
2252 while (*e == '\\')
2253 ++e;
2254 l = e - s;
2256 if (*e != c || l%2 == 0)
2258 /* It's not; just take it all without unescaping. */
2259 memcpy (p, s, l);
2260 p += l;
2262 else if (l > 1)
2264 /* It is, and there's >1 backslash. Take half of them. */
2265 l /= 2;
2266 memcpy (p, s, l);
2267 p += l;
2269 s = e;
2272 *(p++) = *(s++);
2275 *p = '\0';
2276 return string;
2279 /* Search PATTERN for an unquoted % and handle quoting. */
2281 char *
2282 find_percent (char *pattern)
2284 return find_char_unquote (pattern, '%', 0, 0, 0);
2287 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2288 the % or NULL if no % was found.
2289 This version is used with strings in the string cache: if there's a need to
2290 modify the string a new version will be added to the string cache and
2291 *STRING will be set to that. */
2293 const char *
2294 find_percent_cached (const char **string)
2296 const char *p = *string;
2297 char *new = 0;
2298 int slen = 0;
2300 /* If the first char is a % return now. This lets us avoid extra tests
2301 inside the loop. */
2302 if (*p == '%')
2303 return p;
2305 while (1)
2307 while (*p != '\0' && *p != '%')
2308 ++p;
2310 if (*p == '\0')
2311 break;
2313 /* See if this % is escaped with a backslash; if not we're done. */
2314 if (p[-1] != '\\')
2315 break;
2318 /* Search for more backslashes. */
2319 char *pv;
2320 int i = -2;
2322 while (&p[i] >= *string && p[i] == '\\')
2323 --i;
2324 ++i;
2326 /* At this point we know we'll need to allocate a new string.
2327 Make a copy if we haven't yet done so. */
2328 if (! new)
2330 slen = strlen (*string);
2331 new = alloca (slen + 1);
2332 memcpy (new, *string, slen + 1);
2333 p = new + (p - *string);
2334 *string = new;
2337 /* At this point *string, p, and new all point into the same string.
2338 Get a non-const version of p so we can modify new. */
2339 pv = new + (p - *string);
2341 /* The number of backslashes is now -I.
2342 Copy P over itself to swallow half of them. */
2343 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2344 p += i/2;
2346 /* If the backslashes quoted each other; the % was unquoted. */
2347 if (i % 2 == 0)
2348 break;
2352 /* If we had to change STRING, add it to the strcache. */
2353 if (new)
2355 *string = strcache_add (*string);
2356 p = *string + (p - new);
2359 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2360 return (*p == '\0') ? NULL : p;
2363 /* Find the next line of text in an eval buffer, combining continuation lines
2364 into one line.
2365 Return the number of actual lines read (> 1 if continuation lines).
2366 Returns -1 if there's nothing left in the buffer.
2368 After this function, ebuf->buffer points to the first character of the
2369 line we just found.
2372 /* Read a line of text from a STRING.
2373 Since we aren't really reading from a file, don't bother with linenumbers.
2376 static unsigned long
2377 readstring (struct ebuffer *ebuf)
2379 char *eol;
2381 /* If there is nothing left in this buffer, return 0. */
2382 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2383 return -1;
2385 /* Set up a new starting point for the buffer, and find the end of the
2386 next logical line (taking into account backslash/newline pairs). */
2388 eol = ebuf->buffer = ebuf->bufnext;
2390 while (1)
2392 int backslash = 0;
2393 const char *bol = eol;
2394 const char *p;
2396 /* Find the next newline. At EOS, stop. */
2397 p = eol = strchr (eol , '\n');
2398 if (!eol)
2400 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2401 return 0;
2404 /* Found a newline; if it's escaped continue; else we're done. */
2405 while (p > bol && *(--p) == '\\')
2406 backslash = !backslash;
2407 if (!backslash)
2408 break;
2409 ++eol;
2412 /* Overwrite the newline char. */
2413 *eol = '\0';
2414 ebuf->bufnext = eol+1;
2416 return 0;
2419 static long
2420 readline (struct ebuffer *ebuf)
2422 char *p;
2423 char *end;
2424 char *start;
2425 long nlines = 0;
2427 /* The behaviors between string and stream buffers are different enough to
2428 warrant different functions. Do the Right Thing. */
2430 if (!ebuf->fp)
2431 return readstring (ebuf);
2433 /* When reading from a file, we always start over at the beginning of the
2434 buffer for each new line. */
2436 p = start = ebuf->bufstart;
2437 end = p + ebuf->size;
2438 *p = '\0';
2440 while (fgets (p, end - p, ebuf->fp) != 0)
2442 char *p2;
2443 unsigned long len;
2444 int backslash;
2446 len = strlen (p);
2447 if (len == 0)
2449 /* This only happens when the first thing on the line is a '\0'.
2450 It is a pretty hopeless case, but (wonder of wonders) Athena
2451 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2452 There is nothing really to be done; we synthesize a newline so
2453 the following line doesn't appear to be part of this line. */
2454 error (&ebuf->floc,
2455 _("warning: NUL character seen; rest of line ignored"));
2456 p[0] = '\n';
2457 len = 1;
2460 /* Jump past the text we just read. */
2461 p += len;
2463 /* If the last char isn't a newline, the whole line didn't fit into the
2464 buffer. Get some more buffer and try again. */
2465 if (p[-1] != '\n')
2466 goto more_buffer;
2468 /* We got a newline, so add one to the count of lines. */
2469 ++nlines;
2471 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2472 /* Check to see if the line was really ended with CRLF; if so ignore
2473 the CR. */
2474 if ((p - start) > 1 && p[-2] == '\r')
2476 --p;
2477 p[-1] = '\n';
2479 #endif
2481 backslash = 0;
2482 for (p2 = p - 2; p2 >= start; --p2)
2484 if (*p2 != '\\')
2485 break;
2486 backslash = !backslash;
2489 if (!backslash)
2491 p[-1] = '\0';
2492 break;
2495 /* It was a backslash/newline combo. If we have more space, read
2496 another line. */
2497 if (end - p >= 80)
2498 continue;
2500 /* We need more space at the end of our buffer, so realloc it.
2501 Make sure to preserve the current offset of p. */
2502 more_buffer:
2504 unsigned long off = p - start;
2505 ebuf->size *= 2;
2506 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2507 p = start + off;
2508 end = start + ebuf->size;
2509 *p = '\0';
2513 if (ferror (ebuf->fp))
2514 pfatal_with_name (ebuf->floc.filenm);
2516 /* If we found some lines, return how many.
2517 If we didn't, but we did find _something_, that indicates we read the last
2518 line of a file with no final newline; return 1.
2519 If we read nothing, we're at EOF; return -1. */
2521 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2524 /* Parse the next "makefile word" from the input buffer, and return info
2525 about it.
2527 A "makefile word" is one of:
2529 w_bogus Should never happen
2530 w_eol End of input
2531 w_static A static word; cannot be expanded
2532 w_variable A word containing one or more variables/functions
2533 w_colon A colon
2534 w_dcolon A double-colon
2535 w_semicolon A semicolon
2536 w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
2538 Note that this function is only used when reading certain parts of the
2539 makefile. Don't use it where special rules hold sway (RHS of a variable,
2540 in a command list, etc.) */
2542 static enum make_word_type
2543 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2545 enum make_word_type wtype = w_bogus;
2546 char *p = buffer, *beg;
2547 char c;
2549 /* Skip any leading whitespace. */
2550 while (isblank ((unsigned char)*p))
2551 ++p;
2553 beg = p;
2554 c = *(p++);
2555 switch (c)
2557 case '\0':
2558 wtype = w_eol;
2559 break;
2561 case ';':
2562 wtype = w_semicolon;
2563 break;
2565 case '=':
2566 wtype = w_varassign;
2567 break;
2569 case ':':
2570 wtype = w_colon;
2571 switch (*p)
2573 case ':':
2574 ++p;
2575 if (p[1] != '=')
2576 wtype = w_dcolon;
2577 else
2579 wtype = w_varassign;
2580 ++p;
2582 break;
2584 case '=':
2585 ++p;
2586 wtype = w_varassign;
2587 break;
2589 break;
2591 case '+':
2592 case '?':
2593 case '!':
2594 if (*p == '=')
2596 ++p;
2597 wtype = w_varassign;
2598 break;
2601 default:
2602 if (delim && strchr (delim, c))
2603 wtype = w_static;
2604 break;
2607 /* Did we find something? If so, return now. */
2608 if (wtype != w_bogus)
2609 goto done;
2611 /* This is some non-operator word. A word consists of the longest
2612 string of characters that doesn't contain whitespace, one of [:=#],
2613 or [?+!]=, or one of the chars in the DELIM string. */
2615 /* We start out assuming a static word; if we see a variable we'll
2616 adjust our assumptions then. */
2617 wtype = w_static;
2619 /* We already found the first value of "c", above. */
2620 while (1)
2622 char closeparen;
2623 int count;
2625 switch (c)
2627 case '\0':
2628 case ' ':
2629 case '\t':
2630 case '=':
2631 goto done_word;
2633 case ':':
2634 #ifdef HAVE_DOS_PATHS
2635 /* A word CAN include a colon in its drive spec. The drive
2636 spec is allowed either at the beginning of a word, or as part
2637 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2638 if (!(p - beg >= 2
2639 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2640 && (p - beg == 2 || p[-3] == '(')))
2641 #endif
2642 goto done_word;
2644 case '$':
2645 c = *(p++);
2646 if (c == '$')
2647 break;
2649 /* This is a variable reference, so note that it's expandable.
2650 Then read it to the matching close paren. */
2651 wtype = w_variable;
2653 if (c == '(')
2654 closeparen = ')';
2655 else if (c == '{')
2656 closeparen = '}';
2657 else
2658 /* This is a single-letter variable reference. */
2659 break;
2661 for (count=0; *p != '\0'; ++p)
2663 if (*p == c)
2664 ++count;
2665 else if (*p == closeparen && --count < 0)
2667 ++p;
2668 break;
2671 break;
2673 case '?':
2674 case '+':
2675 if (*p == '=')
2676 goto done_word;
2677 break;
2679 case '\\':
2680 switch (*p)
2682 case ':':
2683 case ';':
2684 case '=':
2685 case '\\':
2686 ++p;
2687 break;
2689 break;
2691 default:
2692 if (delim && strchr (delim, c))
2693 goto done_word;
2694 break;
2697 c = *(p++);
2699 done_word:
2700 --p;
2702 done:
2703 if (startp)
2704 *startp = beg;
2705 if (length)
2706 *length = p - beg;
2707 return wtype;
2710 /* Construct the list of include directories
2711 from the arguments and the default list. */
2713 void
2714 construct_include_path (const char **arg_dirs)
2716 #ifdef VAXC /* just don't ask ... */
2717 stat_t stbuf;
2718 #else
2719 struct stat stbuf;
2720 #endif
2721 const char **dirs;
2722 const char **cpp;
2723 unsigned int idx;
2725 /* Compute the number of pointers we need in the table. */
2726 idx = sizeof (default_include_directories) / sizeof (const char *);
2727 if (arg_dirs)
2728 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2729 ++idx;
2731 #ifdef __MSDOS__
2732 /* Add one for $DJDIR. */
2733 ++idx;
2734 #endif
2736 dirs = xmalloc (idx * sizeof (const char *));
2738 idx = 0;
2739 max_incl_len = 0;
2741 /* First consider any dirs specified with -I switches.
2742 Ignore any that don't exist. Remember the maximum string length. */
2744 if (arg_dirs)
2745 while (*arg_dirs != 0)
2747 const char *dir = *(arg_dirs++);
2748 char *expanded = 0;
2749 int e;
2751 if (dir[0] == '~')
2753 expanded = tilde_expand (dir);
2754 if (expanded != 0)
2755 dir = expanded;
2758 EINTRLOOP (e, stat (dir, &stbuf));
2759 if (e == 0 && S_ISDIR (stbuf.st_mode))
2761 unsigned int len = strlen (dir);
2762 /* If dir name is written with trailing slashes, discard them. */
2763 while (len > 1 && dir[len - 1] == '/')
2764 --len;
2765 if (len > max_incl_len)
2766 max_incl_len = len;
2767 dirs[idx++] = strcache_add_len (dir, len);
2770 if (expanded)
2771 free (expanded);
2774 /* Now add the standard default dirs at the end. */
2776 #ifdef __MSDOS__
2778 /* The environment variable $DJDIR holds the root of the DJGPP directory
2779 tree; add ${DJDIR}/include. */
2780 struct variable *djdir = lookup_variable ("DJDIR", 5);
2782 if (djdir)
2784 unsigned int len = strlen (djdir->value) + 8;
2785 char *defdir = alloca (len + 1);
2787 strcat (strcpy (defdir, djdir->value), "/include");
2788 dirs[idx++] = strcache_add (defdir);
2790 if (len > max_incl_len)
2791 max_incl_len = len;
2794 #endif
2796 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2798 int e;
2800 EINTRLOOP (e, stat (*cpp, &stbuf));
2801 if (e == 0 && S_ISDIR (stbuf.st_mode))
2803 unsigned int len = strlen (*cpp);
2804 /* If dir name is written with trailing slashes, discard them. */
2805 while (len > 1 && (*cpp)[len - 1] == '/')
2806 --len;
2807 if (len > max_incl_len)
2808 max_incl_len = len;
2809 dirs[idx++] = strcache_add_len (*cpp, len);
2813 dirs[idx] = 0;
2815 /* Now add each dir to the .INCLUDE_DIRS variable. */
2817 for (cpp = dirs; *cpp != 0; ++cpp)
2818 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2819 o_default, f_append, 0);
2821 include_directories = dirs;
2824 /* Expand ~ or ~USER at the beginning of NAME.
2825 Return a newly malloc'd string or 0. */
2827 char *
2828 tilde_expand (const char *name)
2830 #ifndef VMS
2831 if (name[1] == '/' || name[1] == '\0')
2833 extern char *getenv ();
2834 char *home_dir;
2835 int is_variable;
2838 /* Turn off --warn-undefined-variables while we expand HOME. */
2839 int save = warn_undefined_variables_flag;
2840 warn_undefined_variables_flag = 0;
2842 home_dir = allocated_variable_expand ("$(HOME)");
2844 warn_undefined_variables_flag = save;
2847 is_variable = home_dir[0] != '\0';
2848 if (!is_variable)
2850 free (home_dir);
2851 home_dir = getenv ("HOME");
2853 # if !defined(_AMIGA) && !defined(WINDOWS32)
2854 if (home_dir == 0 || home_dir[0] == '\0')
2856 extern char *getlogin ();
2857 char *logname = getlogin ();
2858 home_dir = 0;
2859 if (logname != 0)
2861 struct passwd *p = getpwnam (logname);
2862 if (p != 0)
2863 home_dir = p->pw_dir;
2866 # endif /* !AMIGA && !WINDOWS32 */
2867 if (home_dir != 0)
2869 char *new = xstrdup (concat (2, home_dir, name + 1));
2870 if (is_variable)
2871 free (home_dir);
2872 return new;
2875 # if !defined(_AMIGA) && !defined(WINDOWS32)
2876 else
2878 struct passwd *pwent;
2879 char *userend = strchr (name + 1, '/');
2880 if (userend != 0)
2881 *userend = '\0';
2882 pwent = getpwnam (name + 1);
2883 if (pwent != 0)
2885 if (userend == 0)
2886 return xstrdup (pwent->pw_dir);
2887 else
2888 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2890 else if (userend != 0)
2891 *userend = '/';
2893 # endif /* !AMIGA && !WINDOWS32 */
2894 #endif /* !VMS */
2895 return 0;
2898 /* Parse a string into a sequence of filenames represented as a chain of
2899 struct nameseq's and return that chain. Optionally expand the strings via
2900 glob().
2902 The string is passed as STRINGP, the address of a string pointer.
2903 The string pointer is updated to point at the first character
2904 not parsed, which either is a null char or equals STOPCHAR.
2906 SIZE is how big to construct chain elements.
2907 This is useful if we want them actually to be other structures
2908 that have room for additional info.
2910 PREFIX, if non-null, is added to the beginning of each filename.
2912 FLAGS allows one or more of the following bitflags to be set:
2913 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2914 PARSEFS_NOAR - Do not check filenames for archive references
2915 PARSEFS_NOGLOB - Do not expand globbing characters
2916 PARSEFS_EXISTS - Only return globbed files that actually exist
2917 (cannot also set NOGLOB)
2918 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2921 void *
2922 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2923 const char *prefix, int flags)
2925 extern void dir_setup_glob (glob_t *glob);
2927 /* tmp points to tmpbuf after the prefix, if any.
2928 tp is the end of the buffer. */
2929 static char *tmpbuf = NULL;
2930 static int tmpbuf_len = 0;
2932 int cachep = (! (flags & PARSEFS_NOCACHE));
2934 struct nameseq *new = 0;
2935 struct nameseq **newp = &new;
2936 #define NEWELT(_n) do { \
2937 const char *__n = (_n); \
2938 *newp = xcalloc (size); \
2939 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2940 newp = &(*newp)->next; \
2941 } while(0)
2943 char *p;
2944 glob_t gl;
2945 char *tp;
2947 #ifdef VMS
2948 # define VMS_COMMA ','
2949 #else
2950 # define VMS_COMMA 0
2951 #endif
2953 if (size < sizeof (struct nameseq))
2954 size = sizeof (struct nameseq);
2956 if (! (flags & PARSEFS_NOGLOB))
2957 dir_setup_glob (&gl);
2959 /* Get enough temporary space to construct the largest possible target. */
2961 int l = strlen (*stringp) + 1;
2962 if (l > tmpbuf_len)
2964 tmpbuf = xrealloc (tmpbuf, l);
2965 tmpbuf_len = l;
2968 tp = tmpbuf;
2970 /* Parse STRING. P will always point to the end of the parsed content. */
2971 p = *stringp;
2972 while (1)
2974 const char *name;
2975 const char **nlist = 0;
2976 char *tildep = 0;
2977 int globme = 1;
2978 #ifndef NO_ARCHIVES
2979 char *arname = 0;
2980 char *memname = 0;
2981 #endif
2982 char *s;
2983 int nlen;
2984 int i;
2986 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2987 p = next_token (p);
2988 if (*p == '\0' || *p == stopchar)
2989 break;
2991 /* There are names left, so find the end of the next name.
2992 Throughout this iteration S points to the start. */
2993 s = p;
2994 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2995 #ifdef VMS
2996 /* convert comma separated list to space separated */
2997 if (p && *p == ',')
2998 *p =' ';
2999 #endif
3000 #ifdef _AMIGA
3001 if (stopchar == ':' && p && *p == ':'
3002 && !(isspace ((unsigned char)p[1]) || !p[1]
3003 || isspace ((unsigned char)p[-1])))
3004 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
3005 #endif
3006 #ifdef HAVE_DOS_PATHS
3007 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
3008 first colon which isn't followed by a slash or a backslash.
3009 Note that tokens separated by spaces should be treated as separate
3010 tokens since make doesn't allow path names with spaces */
3011 if (stopchar == ':')
3012 while (p != 0 && !isspace ((unsigned char)*p) &&
3013 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
3014 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
3015 #endif
3016 if (p == 0)
3017 p = s + strlen (s);
3019 /* Strip leading "this directory" references. */
3020 if (! (flags & PARSEFS_NOSTRIP))
3021 #ifdef VMS
3022 /* Skip leading '[]'s. */
3023 while (p - s > 2 && s[0] == '[' && s[1] == ']')
3024 #else
3025 /* Skip leading './'s. */
3026 while (p - s > 2 && s[0] == '.' && s[1] == '/')
3027 #endif
3029 /* Skip "./" and all following slashes. */
3030 s += 2;
3031 while (*s == '/')
3032 ++s;
3035 /* Extract the filename just found, and skip it.
3036 Set NAME to the string, and NLEN to its length. */
3038 if (s == p)
3040 /* The name was stripped to empty ("./"). */
3041 #if defined(VMS)
3042 continue;
3043 #elif defined(_AMIGA)
3044 /* PDS-- This cannot be right!! */
3045 tp[0] = '\0';
3046 nlen = 0;
3047 #else
3048 tp[0] = '.';
3049 tp[1] = '/';
3050 tp[2] = '\0';
3051 nlen = 2;
3052 #endif
3054 else
3056 #ifdef VMS
3057 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
3058 * to remove this '\' before we can use the filename.
3059 * xstrdup called because S may be read-only string constant.
3061 char *n = tp;
3062 while (s < p)
3064 if (s[0] == '\\' && s[1] == ':')
3065 ++s;
3066 *(n++) = *(s++);
3068 n[0] = '\0';
3069 nlen = strlen (tp);
3070 #else
3071 nlen = p - s;
3072 memcpy (tp, s, nlen);
3073 tp[nlen] = '\0';
3074 #endif
3077 /* At this point, TP points to the element and NLEN is its length. */
3079 #ifndef NO_ARCHIVES
3080 /* If this is the start of an archive group that isn't complete, set up
3081 to add the archive prefix for future files. A file list like:
3082 "libf.a(x.o y.o z.o)" needs to be expanded as:
3083 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3085 TP == TMP means we're not already in an archive group. Ignore
3086 something starting with '(', as that cannot actually be an
3087 archive-member reference (and treating it as such results in an empty
3088 file name, which causes much lossage). Also if it ends in ")" then
3089 it's a complete reference so we don't need to treat it specially.
3091 Finally, note that archive groups must end with ')' as the last
3092 character, so ensure there's some word ending like that before
3093 considering this an archive group. */
3094 if (! (flags & PARSEFS_NOAR)
3095 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3097 char *n = strchr (tp, '(');
3098 if (n)
3100 /* This looks like the first element in an open archive group.
3101 A valid group MUST have ')' as the last character. */
3102 const char *e = p;
3105 const char *o = e;
3106 e = next_token (e);
3107 /* Find the end of this word. We don't want to unquote and
3108 we don't care about quoting since we're looking for the
3109 last char in the word. */
3110 while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3111 && ! isblank ((unsigned char) *e))
3112 ++e;
3113 /* If we didn't move, we're done now. */
3114 if (e == o)
3115 break;
3116 if (e[-1] == ')')
3118 /* Found the end, so this is the first element in an
3119 open archive group. It looks like "lib(mem".
3120 Reset TP past the open paren. */
3121 nlen -= (n + 1) - tp;
3122 tp = n + 1;
3124 /* We can stop looking now. */
3125 break;
3128 while (*e != '\0');
3130 /* If we have just "lib(", part of something like "lib( a b)",
3131 go to the next item. */
3132 if (! nlen)
3133 continue;
3137 /* If we are inside an archive group, make sure it has an end. */
3138 if (tp > tmpbuf)
3140 if (tp[nlen-1] == ')')
3142 /* This is the natural end; reset TP. */
3143 tp = tmpbuf;
3145 /* This is just ")", something like "lib(a b )": skip it. */
3146 if (nlen == 1)
3147 continue;
3149 else
3151 /* Not the end, so add a "fake" end. */
3152 tp[nlen++] = ')';
3153 tp[nlen] = '\0';
3156 #endif
3158 /* If we're not globbing we're done: add it to the end of the chain.
3159 Go to the next item in the string. */
3160 if (flags & PARSEFS_NOGLOB)
3162 NEWELT (concat (2, prefix, tmpbuf));
3163 continue;
3166 /* If we get here we know we're doing glob expansion.
3167 TP is a string in tmpbuf. NLEN is no longer used.
3168 We may need to do more work: after this NAME will be set. */
3169 name = tmpbuf;
3171 /* Expand tilde if applicable. */
3172 if (tmpbuf[0] == '~')
3174 tildep = tilde_expand (tmpbuf);
3175 if (tildep != 0)
3176 name = tildep;
3179 #ifndef NO_ARCHIVES
3180 /* If NAME is an archive member reference replace it with the archive
3181 file name, and save the member name in MEMNAME. We will glob on the
3182 archive name and then reattach MEMNAME later. */
3183 if (! (flags & PARSEFS_NOAR) && ar_name (name))
3185 ar_parse_name (name, &arname, &memname);
3186 name = arname;
3188 #endif /* !NO_ARCHIVES */
3190 /* glob() is expensive: don't call it unless we need to. */
3191 if (!(flags & PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3193 globme = 0;
3194 i = 1;
3195 nlist = &name;
3197 else
3198 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3200 case GLOB_NOSPACE:
3201 fatal (NILF, _("virtual memory exhausted"));
3203 case 0:
3204 /* Success. */
3205 i = gl.gl_pathc;
3206 nlist = (const char **)gl.gl_pathv;
3207 break;
3209 case GLOB_NOMATCH:
3210 /* If we want only existing items, skip this one. */
3211 if (flags & PARSEFS_EXISTS)
3213 i = 0;
3214 break;
3216 /* FALLTHROUGH */
3218 default:
3219 /* By default keep this name. */
3220 i = 1;
3221 nlist = &name;
3222 break;
3225 /* For each matched element, add it to the list. */
3226 while (i-- > 0)
3227 #ifndef NO_ARCHIVES
3228 if (memname != 0)
3230 /* Try to glob on MEMNAME within the archive. */
3231 struct nameseq *found = ar_glob (nlist[i], memname, size);
3232 if (! found)
3233 /* No matches. Use MEMNAME as-is. */
3234 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3235 else
3237 /* We got a chain of items. Attach them. */
3238 if (*newp)
3239 (*newp)->next = found;
3240 else
3241 *newp = found;
3243 /* Find and set the new end. Massage names if necessary. */
3244 while (1)
3246 if (! cachep)
3247 found->name = xstrdup (concat (2, prefix, name));
3248 else if (prefix)
3249 found->name = strcache_add (concat (2, prefix, name));
3251 if (found->next == 0)
3252 break;
3254 found = found->next;
3256 newp = &found->next;
3259 else
3260 #endif /* !NO_ARCHIVES */
3261 NEWELT (concat (2, prefix, nlist[i]));
3263 if (globme)
3264 globfree (&gl);
3266 #ifndef NO_ARCHIVES
3267 if (arname)
3268 free (arname);
3269 #endif
3271 if (tildep)
3272 free (tildep);
3275 *stringp = p;
3276 return new;