Savannah bug #37179: Use alternate shared library syntax for MacOS.
[make.git] / read.c
blob8478c8d73c94b3935a55994c404a30201a813019
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 /* If this line is empty, skip it. */
623 line = ebuf->buffer;
624 if (line[0] == '\0')
625 continue;
627 linelen = strlen (line);
629 /* Check for a shell command line first.
630 If it is not one, we can stop treating cmd_prefix specially. */
631 if (line[0] == cmd_prefix)
633 if (no_targets)
634 /* Ignore the commands in a rule with no targets. */
635 continue;
637 /* If there is no preceding rule line, don't treat this line
638 as a command, even though it begins with a recipe prefix.
639 SunOS 4 make appears to behave this way. */
641 if (filenames != 0)
643 if (ignoring)
644 /* Yep, this is a shell command, and we don't care. */
645 continue;
647 if (commands_idx == 0)
648 cmds_started = ebuf->floc.lineno;
650 /* Append this command line to the line being accumulated.
651 Skip the initial command prefix character. */
652 if (linelen + commands_idx > commands_len)
654 commands_len = (linelen + commands_idx) * 2;
655 commands = xrealloc (commands, commands_len);
657 memcpy (&commands[commands_idx], line + 1, linelen - 1);
658 commands_idx += linelen - 1;
659 commands[commands_idx++] = '\n';
660 continue;
664 /* This line is not a shell command line. Don't worry about whitespace.
665 Get more space if we need it; we don't need to preserve the current
666 contents of the buffer. */
668 if (collapsed_length < linelen+1)
670 collapsed_length = linelen+1;
671 if (collapsed)
672 free (collapsed);
673 /* Don't need xrealloc: we don't need to preserve the content. */
674 collapsed = xmalloc (collapsed_length);
676 strcpy (collapsed, line);
677 /* Collapse continuation lines. */
678 collapse_continuations (collapsed);
679 remove_comments (collapsed);
681 /* Get rid if starting space (including formfeed, vtab, etc.) */
682 p = collapsed;
683 while (isspace ((unsigned char)*p))
684 ++p;
686 /* See if this is a variable assignment. We need to do this early, to
687 allow variables with names like 'ifdef', 'export', 'private', etc. */
688 p = parse_var_assignment(p, &vmod);
689 if (vmod.assign_v)
691 struct variable *v;
692 enum variable_origin origin = vmod.override_v ? o_override : o_file;
694 /* If we're ignoring then we're done now. */
695 if (ignoring)
697 if (vmod.define_v)
698 in_ignored_define = 1;
699 continue;
702 if (vmod.undefine_v)
704 do_undefine (p, origin, ebuf);
706 /* This line has been dealt with. */
707 goto rule_complete;
709 else if (vmod.define_v)
710 v = do_define (p, origin, ebuf);
711 else
712 v = try_variable_definition (fstart, p, origin, 0);
714 assert (v != NULL);
716 if (vmod.export_v)
717 v->export = v_export;
718 if (vmod.private_v)
719 v->private_var = 1;
721 /* This line has been dealt with. */
722 goto rule_complete;
725 /* If this line is completely empty, ignore it. */
726 if (*p == '\0')
727 continue;
729 p2 = end_of_token (p);
730 wlen = p2 - p;
731 p2 = next_token (p2);
733 /* If we're in an ignored define, skip this line (but maybe get out). */
734 if (in_ignored_define)
736 /* See if this is an endef line (plus optional comment). */
737 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
738 in_ignored_define = 0;
740 continue;
743 /* Check for conditional state changes. */
745 int i = conditional_line (p, wlen, fstart);
746 if (i != -2)
748 if (i == -1)
749 fatal (fstart, _("invalid syntax in conditional"));
751 ignoring = i;
752 continue;
756 /* Nothing to see here... move along. */
757 if (ignoring)
758 continue;
760 /* Manage the "export" keyword used outside of variable assignment
761 as well as "unexport". */
762 if (word1eq ("export") || word1eq ("unexport"))
764 int exporting = *p == 'u' ? 0 : 1;
766 /* (un)export by itself causes everything to be (un)exported. */
767 if (*p2 == '\0')
768 export_all_variables = exporting;
769 else
771 unsigned int l;
772 const char *cp;
773 char *ap;
775 /* Expand the line so we can use indirect and constructed
776 variable names in an (un)export command. */
777 cp = ap = allocated_variable_expand (p2);
779 for (p = find_next_token (&cp, &l); p != 0;
780 p = find_next_token (&cp, &l))
782 struct variable *v = lookup_variable (p, l);
783 if (v == 0)
784 v = define_variable_global (p, l, "", o_file, 0, fstart);
785 v->export = exporting ? v_export : v_noexport;
788 free (ap);
790 goto rule_complete;
793 /* Handle the special syntax for vpath. */
794 if (word1eq ("vpath"))
796 const char *cp;
797 char *vpat;
798 unsigned int l;
799 cp = variable_expand (p2);
800 p = find_next_token (&cp, &l);
801 if (p != 0)
803 vpat = xstrndup (p, l);
804 p = find_next_token (&cp, &l);
805 /* No searchpath means remove all previous
806 selective VPATH's with the same pattern. */
808 else
809 /* No pattern means remove all previous selective VPATH's. */
810 vpat = 0;
811 construct_vpath_list (vpat, p);
812 if (vpat != 0)
813 free (vpat);
815 goto rule_complete;
818 /* Handle include and variants. */
819 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
821 /* We have found an 'include' line specifying a nested
822 makefile to be read at this point. */
823 struct conditionals *save;
824 struct conditionals new_conditionals;
825 struct nameseq *files;
826 /* "-include" (vs "include") says no error if the file does not
827 exist. "sinclude" is an alias for this from SGI. */
828 int noerror = (p[0] != 'i');
830 p = allocated_variable_expand (p2);
832 /* If no filenames, it's a no-op. */
833 if (*p == '\0')
835 free (p);
836 continue;
839 /* Parse the list of file names. Don't expand archive references! */
840 p2 = p;
841 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
842 PARSEFS_NOAR);
843 free (p);
845 /* Save the state of conditionals and start
846 the included makefile with a clean slate. */
847 save = install_conditionals (&new_conditionals);
849 /* Record the rules that are waiting so they will determine
850 the default goal before those in the included makefile. */
851 record_waiting_files ();
853 /* Read each included makefile. */
854 while (files != 0)
856 struct nameseq *next = files->next;
857 const char *name = files->name;
858 int r;
860 free_ns (files);
861 files = next;
863 r = eval_makefile (name,
864 (RM_INCLUDED | RM_NO_TILDE
865 | (noerror ? RM_DONTCARE : 0)
866 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
867 if (!r && !noerror)
868 error (fstart, "%s: %s", name, strerror (errno));
871 /* Restore conditional state. */
872 restore_conditionals (save);
874 goto rule_complete;
877 /* This line starts with a tab but was not caught above because there
878 was no preceding target, and the line might have been usable as a
879 variable definition. But now we know it is definitely lossage. */
880 if (line[0] == cmd_prefix)
881 fatal(fstart, _("recipe commences before first target"));
883 /* This line describes some target files. This is complicated by
884 the existence of target-specific variables, because we can't
885 expand the entire line until we know if we have one or not. So
886 we expand the line word by word until we find the first ':',
887 then check to see if it's a target-specific variable.
889 In this algorithm, 'lb_next' will point to the beginning of the
890 unexpanded parts of the input buffer, while 'p2' points to the
891 parts of the expanded buffer we haven't searched yet. */
894 enum make_word_type wtype;
895 char *cmdleft, *semip, *lb_next;
896 unsigned int plen = 0;
897 char *colonp;
898 const char *end, *beg; /* Helpers for whitespace stripping. */
900 /* Record the previous rule. */
902 record_waiting_files ();
903 tgts_started = fstart->lineno;
905 /* Search the line for an unquoted ; that is not after an
906 unquoted #. */
907 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
908 if (cmdleft != 0 && *cmdleft == '#')
910 /* We found a comment before a semicolon. */
911 *cmdleft = '\0';
912 cmdleft = 0;
914 else if (cmdleft != 0)
915 /* Found one. Cut the line short there before expanding it. */
916 *(cmdleft++) = '\0';
917 semip = cmdleft;
919 collapse_continuations (line);
921 /* We can't expand the entire line, since if it's a per-target
922 variable we don't want to expand it. So, walk from the
923 beginning, expanding as we go, and looking for "interesting"
924 chars. The first word is always expandable. */
925 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
926 switch (wtype)
928 case w_eol:
929 if (cmdleft != 0)
930 fatal(fstart, _("missing rule before recipe"));
931 /* This line contained something but turned out to be nothing
932 but whitespace (a comment?). */
933 continue;
935 case w_colon:
936 case w_dcolon:
937 /* We accept and ignore rules without targets for
938 compatibility with SunOS 4 make. */
939 no_targets = 1;
940 continue;
942 default:
943 break;
946 p2 = variable_expand_string(NULL, lb_next, wlen);
948 while (1)
950 lb_next += wlen;
951 if (cmdleft == 0)
953 /* Look for a semicolon in the expanded line. */
954 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
956 if (cmdleft != 0)
958 unsigned long p2_off = p2 - variable_buffer;
959 unsigned long cmd_off = cmdleft - variable_buffer;
960 char *pend = p2 + strlen(p2);
962 /* Append any remnants of lb, then cut the line short
963 at the semicolon. */
964 *cmdleft = '\0';
966 /* One school of thought says that you shouldn't expand
967 here, but merely copy, since now you're beyond a ";"
968 and into a command script. However, the old parser
969 expanded the whole line, so we continue that for
970 backwards-compatiblity. Also, it wouldn't be
971 entirely consistent, since we do an unconditional
972 expand below once we know we don't have a
973 target-specific variable. */
974 (void)variable_expand_string(pend, lb_next, (long)-1);
975 lb_next += strlen(lb_next);
976 p2 = variable_buffer + p2_off;
977 cmdleft = variable_buffer + cmd_off + 1;
981 colonp = find_char_unquote(p2, ':', 0, 0, 0);
982 #ifdef HAVE_DOS_PATHS
983 /* The drive spec brain-damage strikes again... */
984 /* Note that the only separators of targets in this context
985 are whitespace and a left paren. If others are possible,
986 they should be added to the string in the call to index. */
987 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
988 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
989 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
990 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
991 #endif
992 if (colonp != 0)
993 break;
995 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
996 if (wtype == w_eol)
997 break;
999 p2 += strlen(p2);
1000 *(p2++) = ' ';
1001 p2 = variable_expand_string(p2, lb_next, wlen);
1002 /* We don't need to worry about cmdleft here, because if it was
1003 found in the variable_buffer the entire buffer has already
1004 been expanded... we'll never get here. */
1007 p2 = next_token (variable_buffer);
1009 /* If the word we're looking at is EOL, see if there's _anything_
1010 on the line. If not, a variable expanded to nothing, so ignore
1011 it. If so, we can't parse this line so punt. */
1012 if (wtype == w_eol)
1014 if (*p2 != '\0')
1015 /* There's no need to be ivory-tower about this: check for
1016 one of the most common bugs found in makefiles... */
1017 fatal (fstart, _("missing separator%s"),
1018 (cmd_prefix == '\t' && !strneq (line, " ", 8))
1019 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1020 continue;
1023 /* Make the colon the end-of-string so we know where to stop
1024 looking for targets. Start there again once we're done. */
1025 *colonp = '\0';
1026 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1027 *colonp = ':';
1028 p2 = colonp;
1030 if (!filenames)
1032 /* We accept and ignore rules without targets for
1033 compatibility with SunOS 4 make. */
1034 no_targets = 1;
1035 continue;
1037 /* This should never be possible; we handled it above. */
1038 assert (*p2 != '\0');
1039 ++p2;
1041 /* Is this a one-colon or two-colon entry? */
1042 two_colon = *p2 == ':';
1043 if (two_colon)
1044 p2++;
1046 /* Test to see if it's a target-specific variable. Copy the rest
1047 of the buffer over, possibly temporarily (we'll expand it later
1048 if it's not a target-specific variable). PLEN saves the length
1049 of the unparsed section of p2, for later. */
1050 if (*lb_next != '\0')
1052 unsigned int l = p2 - variable_buffer;
1053 plen = strlen (p2);
1054 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1055 p2 = variable_buffer + l;
1058 p2 = parse_var_assignment (p2, &vmod);
1059 if (vmod.assign_v)
1061 /* If there was a semicolon found, add it back, plus anything
1062 after it. */
1063 if (semip)
1065 unsigned int l = p - variable_buffer;
1066 *(--semip) = ';';
1067 collapse_continuations (semip);
1068 variable_buffer_output (p2 + strlen (p2),
1069 semip, strlen (semip)+1);
1070 p = variable_buffer + l;
1072 record_target_var (filenames, p2,
1073 vmod.override_v ? o_override : o_file,
1074 &vmod, fstart);
1075 filenames = 0;
1076 continue;
1079 /* This is a normal target, _not_ a target-specific variable.
1080 Unquote any = in the dependency list. */
1081 find_char_unquote (lb_next, '=', 0, 0, 0);
1083 /* Remember the command prefix for this target. */
1084 prefix = cmd_prefix;
1086 /* We have some targets, so don't ignore the following commands. */
1087 no_targets = 0;
1089 /* Expand the dependencies, etc. */
1090 if (*lb_next != '\0')
1092 unsigned int l = p2 - variable_buffer;
1093 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1094 p2 = variable_buffer + l;
1096 /* Look for a semicolon in the expanded line. */
1097 if (cmdleft == 0)
1099 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1100 if (cmdleft != 0)
1101 *(cmdleft++) = '\0';
1105 /* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
1106 p = strchr (p2, ':');
1107 while (p != 0 && p[-1] == '\\')
1109 char *q = &p[-1];
1110 int backslash = 0;
1111 while (*q-- == '\\')
1112 backslash = !backslash;
1113 if (backslash)
1114 p = strchr (p + 1, ':');
1115 else
1116 break;
1118 #ifdef _AMIGA
1119 /* Here, the situation is quite complicated. Let's have a look
1120 at a couple of targets:
1122 install: dev:make
1124 dev:make: make
1126 dev:make:: xyz
1128 The rule is that it's only a target, if there are TWO :'s
1129 OR a space around the :.
1131 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1132 || isspace ((unsigned char)p[-1])))
1133 p = 0;
1134 #endif
1135 #ifdef HAVE_DOS_PATHS
1137 int check_again;
1138 do {
1139 check_again = 0;
1140 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1141 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1142 isalpha ((unsigned char)p[-1]) &&
1143 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1144 p = strchr (p + 1, ':');
1145 check_again = 1;
1147 } while (check_again);
1149 #endif
1150 if (p != 0)
1152 struct nameseq *target;
1153 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1154 PARSEFS_NOGLOB);
1155 ++p2;
1156 if (target == 0)
1157 fatal (fstart, _("missing target pattern"));
1158 else if (target->next != 0)
1159 fatal (fstart, _("multiple target patterns"));
1160 pattern_percent = find_percent_cached (&target->name);
1161 pattern = target->name;
1162 if (pattern_percent == 0)
1163 fatal (fstart, _("target pattern contains no '%%'"));
1164 free_ns (target);
1166 else
1167 pattern = 0;
1169 /* Strip leading and trailing whitespaces. */
1170 beg = p2;
1171 end = beg + strlen (beg) - 1;
1172 strip_whitespace (&beg, &end);
1174 /* Put all the prerequisites here; they'll be parsed later. */
1175 if (beg <= end && *beg != '\0')
1176 depstr = xstrndup (beg, end - beg + 1);
1177 else
1178 depstr = 0;
1180 commands_idx = 0;
1181 if (cmdleft != 0)
1183 /* Semicolon means rest of line is a command. */
1184 unsigned int l = strlen (cmdleft);
1186 cmds_started = fstart->lineno;
1188 /* Add this command line to the buffer. */
1189 if (l + 2 > commands_len)
1191 commands_len = (l + 2) * 2;
1192 commands = xrealloc (commands, commands_len);
1194 memcpy (commands, cmdleft, l);
1195 commands_idx += l;
1196 commands[commands_idx++] = '\n';
1199 /* Determine if this target should be made default. We used to do
1200 this in record_files() but because of the delayed target recording
1201 and because preprocessor directives are legal in target's commands
1202 it is too late. Consider this fragment for example:
1204 foo:
1206 ifeq ($(.DEFAULT_GOAL),foo)
1208 endif
1210 Because the target is not recorded until after ifeq directive is
1211 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1212 would expect. Because of this we have to move the logic here. */
1214 if (set_default && default_goal_var->value[0] == '\0')
1216 const char *name;
1217 struct dep *d;
1218 struct nameseq *t = filenames;
1220 for (; t != 0; t = t->next)
1222 int reject = 0;
1223 name = t->name;
1225 /* We have nothing to do if this is an implicit rule. */
1226 if (strchr (name, '%') != 0)
1227 break;
1229 /* See if this target's name does not start with a '.',
1230 unless it contains a slash. */
1231 if (*name == '.' && strchr (name, '/') == 0
1232 #ifdef HAVE_DOS_PATHS
1233 && strchr (name, '\\') == 0
1234 #endif
1236 continue;
1239 /* If this file is a suffix, don't let it be
1240 the default goal file. */
1241 for (d = suffix_file->deps; d != 0; d = d->next)
1243 register struct dep *d2;
1244 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1246 reject = 1;
1247 break;
1249 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1251 unsigned int l = strlen (dep_name (d2));
1252 if (!strneq (name, dep_name (d2), l))
1253 continue;
1254 if (streq (name + l, dep_name (d)))
1256 reject = 1;
1257 break;
1261 if (reject)
1262 break;
1265 if (!reject)
1267 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1268 o_file, 0, NILF);
1269 break;
1274 continue;
1277 /* We get here except in the case that we just read a rule line.
1278 Record now the last rule we read, so following spurious
1279 commands are properly diagnosed. */
1280 rule_complete:
1281 record_waiting_files ();
1284 #undef word1eq
1286 if (conditionals->if_cmds)
1287 fatal (fstart, _("missing 'endif'"));
1289 /* At eof, record the last rule. */
1290 record_waiting_files ();
1292 if (collapsed)
1293 free (collapsed);
1294 free (commands);
1298 /* Remove comments from LINE.
1299 This is done by copying the text at LINE onto itself. */
1301 static void
1302 remove_comments (char *line)
1304 char *comment;
1306 comment = find_char_unquote (line, '#', 0, 0, 0);
1308 if (comment != 0)
1309 /* Cut off the line at the #. */
1310 *comment = '\0';
1313 /* Execute a 'undefine' directive.
1314 The undefine line has already been read, and NAME is the name of
1315 the variable to be undefined. */
1317 static void
1318 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1320 char *p, *var;
1322 /* Expand the variable name and find the beginning (NAME) and end. */
1323 var = allocated_variable_expand (name);
1324 name = next_token (var);
1325 if (*name == '\0')
1326 fatal (&ebuf->floc, _("empty variable name"));
1327 p = name + strlen (name) - 1;
1328 while (p > name && isblank ((unsigned char)*p))
1329 --p;
1330 p[1] = '\0';
1332 undefine_variable_global (name, p - name + 1, origin);
1333 free (var);
1336 /* Execute a 'define' directive.
1337 The first line has already been read, and NAME is the name of
1338 the variable to be defined. The following lines remain to be read. */
1340 static struct variable *
1341 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1343 struct variable *v;
1344 struct variable var;
1345 struct floc defstart;
1346 int nlevels = 1;
1347 unsigned int length = 100;
1348 char *definition = xmalloc (length);
1349 unsigned int idx = 0;
1350 char *p, *n;
1352 defstart = ebuf->floc;
1354 p = parse_variable_definition (name, &var);
1355 if (p == NULL)
1356 /* No assignment token, so assume recursive. */
1357 var.flavor = f_recursive;
1358 else
1360 if (var.value[0] != '\0')
1361 error (&defstart, _("extraneous text after 'define' directive"));
1363 /* Chop the string before the assignment token to get the name. */
1364 var.name[var.length] = '\0';
1367 /* Expand the variable name and find the beginning (NAME) and end. */
1368 n = allocated_variable_expand (name);
1369 name = next_token (n);
1370 if (name[0] == '\0')
1371 fatal (&defstart, _("empty variable name"));
1372 p = name + strlen (name) - 1;
1373 while (p > name && isblank ((unsigned char)*p))
1374 --p;
1375 p[1] = '\0';
1377 /* Now read the value of the variable. */
1378 while (1)
1380 unsigned int len;
1381 char *line;
1382 long nlines = readline (ebuf);
1384 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1385 if (nlines < 0)
1386 fatal (&defstart, _("missing 'endef', unterminated 'define'"));
1388 ebuf->floc.lineno += nlines;
1389 line = ebuf->buffer;
1391 collapse_continuations (line);
1393 /* If the line doesn't begin with a tab, test to see if it introduces
1394 another define, or ends one. Stop if we find an 'endef' */
1395 if (line[0] != cmd_prefix)
1397 p = next_token (line);
1398 len = strlen (p);
1400 /* If this is another 'define', increment the level count. */
1401 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1402 && strneq (p, "define", 6))
1403 ++nlevels;
1405 /* If this is an 'endef', decrement the count. If it's now 0,
1406 we've found the last one. */
1407 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1408 && strneq (p, "endef", 5))
1410 p += 5;
1411 remove_comments (p);
1412 if (*(next_token (p)) != '\0')
1413 error (&ebuf->floc,
1414 _("extraneous text after 'endef' directive"));
1416 if (--nlevels == 0)
1417 break;
1421 /* Add this line to the variable definition. */
1422 len = strlen (line);
1423 if (idx + len + 1 > length)
1425 length = (idx + len) * 2;
1426 definition = xrealloc (definition, length + 1);
1429 memcpy (&definition[idx], line, len);
1430 idx += len;
1431 /* Separate lines with a newline. */
1432 definition[idx++] = '\n';
1435 /* We've got what we need; define the variable. */
1436 if (idx == 0)
1437 definition[0] = '\0';
1438 else
1439 definition[idx - 1] = '\0';
1441 v = do_variable_definition (&defstart, name,
1442 definition, origin, var.flavor, 0);
1443 free (definition);
1444 free (n);
1445 return (v);
1448 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1449 "ifneq", "else" and "endif".
1450 LINE is the input line, with the command as its first word.
1452 FILENAME and LINENO are the filename and line number in the
1453 current makefile. They are used for error messages.
1455 Value is -2 if the line is not a conditional at all,
1456 -1 if the line is an invalid conditional,
1457 0 if following text should be interpreted,
1458 1 if following text should be ignored. */
1460 static int
1461 conditional_line (char *line, int len, const struct floc *flocp)
1463 char *cmdname;
1464 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1465 unsigned int i;
1466 unsigned int o;
1468 /* Compare a word, both length and contents. */
1469 #define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
1470 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1472 /* Make sure this line is a conditional. */
1473 chkword ("ifdef", c_ifdef)
1474 else chkword ("ifndef", c_ifndef)
1475 else chkword ("ifeq", c_ifeq)
1476 else chkword ("ifneq", c_ifneq)
1477 else chkword ("else", c_else)
1478 else chkword ("endif", c_endif)
1479 else
1480 return -2;
1482 /* Found one: skip past it and any whitespace after it. */
1483 line = next_token (line + len);
1485 #define EXTRANEOUS() error (flocp, _("Extraneous text after '%s' directive"), cmdname)
1487 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1488 if (cmdtype == c_endif)
1490 if (*line != '\0')
1491 EXTRANEOUS ();
1493 if (!conditionals->if_cmds)
1494 fatal (flocp, _("extraneous '%s'"), cmdname);
1496 --conditionals->if_cmds;
1498 goto DONE;
1501 /* An 'else' statement can either be simple, or it can have another
1502 conditional after it. */
1503 if (cmdtype == c_else)
1505 const char *p;
1507 if (!conditionals->if_cmds)
1508 fatal (flocp, _("extraneous '%s'"), cmdname);
1510 o = conditionals->if_cmds - 1;
1512 if (conditionals->seen_else[o])
1513 fatal (flocp, _("only one 'else' per conditional"));
1515 /* Change the state of ignorance. */
1516 switch (conditionals->ignoring[o])
1518 case 0:
1519 /* We've just been interpreting. Never do it again. */
1520 conditionals->ignoring[o] = 2;
1521 break;
1522 case 1:
1523 /* We've never interpreted yet. Maybe this time! */
1524 conditionals->ignoring[o] = 0;
1525 break;
1528 /* It's a simple 'else'. */
1529 if (*line == '\0')
1531 conditionals->seen_else[o] = 1;
1532 goto DONE;
1535 /* The 'else' has extra text. That text must be another conditional
1536 and cannot be an 'else' or 'endif'. */
1538 /* Find the length of the next word. */
1539 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1541 len = p - line;
1543 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1544 if (word1eq ("else") || word1eq ("endif")
1545 || conditional_line (line, len, flocp) < 0)
1546 EXTRANEOUS ();
1547 else
1549 /* conditional_line() created a new level of conditional.
1550 Raise it back to this level. */
1551 if (conditionals->ignoring[o] < 2)
1552 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1553 --conditionals->if_cmds;
1556 goto DONE;
1559 if (conditionals->allocated == 0)
1561 conditionals->allocated = 5;
1562 conditionals->ignoring = xmalloc (conditionals->allocated);
1563 conditionals->seen_else = xmalloc (conditionals->allocated);
1566 o = conditionals->if_cmds++;
1567 if (conditionals->if_cmds > conditionals->allocated)
1569 conditionals->allocated += 5;
1570 conditionals->ignoring = xrealloc (conditionals->ignoring,
1571 conditionals->allocated);
1572 conditionals->seen_else = xrealloc (conditionals->seen_else,
1573 conditionals->allocated);
1576 /* Record that we have seen an 'if...' but no 'else' so far. */
1577 conditionals->seen_else[o] = 0;
1579 /* Search through the stack to see if we're already ignoring. */
1580 for (i = 0; i < o; ++i)
1581 if (conditionals->ignoring[i])
1583 /* We are already ignoring, so just push a level to match the next
1584 "else" or "endif", and keep ignoring. We don't want to expand
1585 variables in the condition. */
1586 conditionals->ignoring[o] = 1;
1587 return 1;
1590 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1592 char *var;
1593 struct variable *v;
1594 char *p;
1596 /* Expand the thing we're looking up, so we can use indirect and
1597 constructed variable names. */
1598 var = allocated_variable_expand (line);
1600 /* Make sure there's only one variable name to test. */
1601 p = end_of_token (var);
1602 i = p - var;
1603 p = next_token (p);
1604 if (*p != '\0')
1605 return -1;
1607 var[i] = '\0';
1608 v = lookup_variable (var, i);
1610 conditionals->ignoring[o] =
1611 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1613 free (var);
1615 else
1617 /* "ifeq" or "ifneq". */
1618 char *s1, *s2;
1619 unsigned int l;
1620 char termin = *line == '(' ? ',' : *line;
1622 if (termin != ',' && termin != '"' && termin != '\'')
1623 return -1;
1625 s1 = ++line;
1626 /* Find the end of the first string. */
1627 if (termin == ',')
1629 int count = 0;
1630 for (; *line != '\0'; ++line)
1631 if (*line == '(')
1632 ++count;
1633 else if (*line == ')')
1634 --count;
1635 else if (*line == ',' && count <= 0)
1636 break;
1638 else
1639 while (*line != '\0' && *line != termin)
1640 ++line;
1642 if (*line == '\0')
1643 return -1;
1645 if (termin == ',')
1647 /* Strip blanks after the first string. */
1648 char *p = line++;
1649 while (isblank ((unsigned char)p[-1]))
1650 --p;
1651 *p = '\0';
1653 else
1654 *line++ = '\0';
1656 s2 = variable_expand (s1);
1657 /* We must allocate a new copy of the expanded string because
1658 variable_expand re-uses the same buffer. */
1659 l = strlen (s2);
1660 s1 = alloca (l + 1);
1661 memcpy (s1, s2, l + 1);
1663 if (termin != ',')
1664 /* Find the start of the second string. */
1665 line = next_token (line);
1667 termin = termin == ',' ? ')' : *line;
1668 if (termin != ')' && termin != '"' && termin != '\'')
1669 return -1;
1671 /* Find the end of the second string. */
1672 if (termin == ')')
1674 int count = 0;
1675 s2 = next_token (line);
1676 for (line = s2; *line != '\0'; ++line)
1678 if (*line == '(')
1679 ++count;
1680 else if (*line == ')')
1682 if (count <= 0)
1683 break;
1684 else
1685 --count;
1689 else
1691 ++line;
1692 s2 = line;
1693 while (*line != '\0' && *line != termin)
1694 ++line;
1697 if (*line == '\0')
1698 return -1;
1700 *line = '\0';
1701 line = next_token (++line);
1702 if (*line != '\0')
1703 EXTRANEOUS ();
1705 s2 = variable_expand (s2);
1706 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1709 DONE:
1710 /* Search through the stack to see if we're ignoring. */
1711 for (i = 0; i < conditionals->if_cmds; ++i)
1712 if (conditionals->ignoring[i])
1713 return 1;
1714 return 0;
1718 /* Record target-specific variable values for files FILENAMES.
1719 TWO_COLON is nonzero if a double colon was used.
1721 The links of FILENAMES are freed, and so are any names in it
1722 that are not incorporated into other data structures.
1724 If the target is a pattern, add the variable to the pattern-specific
1725 variable value list. */
1727 static void
1728 record_target_var (struct nameseq *filenames, char *defn,
1729 enum variable_origin origin, struct vmodifiers *vmod,
1730 const struct floc *flocp)
1732 struct nameseq *nextf;
1733 struct variable_set_list *global;
1735 global = current_variable_set_list;
1737 /* If the variable is an append version, store that but treat it as a
1738 normal recursive variable. */
1740 for (; filenames != 0; filenames = nextf)
1742 struct variable *v;
1743 const char *name = filenames->name;
1744 const char *fname;
1745 const char *percent;
1746 struct pattern_var *p;
1748 nextf = filenames->next;
1749 free_ns (filenames);
1751 /* If it's a pattern target, then add it to the pattern-specific
1752 variable list. */
1753 percent = find_percent_cached (&name);
1754 if (percent)
1756 /* Get a reference for this pattern-specific variable struct. */
1757 p = create_pattern_var (name, percent);
1758 p->variable.fileinfo = *flocp;
1759 /* I don't think this can fail since we already determined it was a
1760 variable definition. */
1761 v = assign_variable_definition (&p->variable, defn);
1762 assert (v != 0);
1764 v->origin = origin;
1765 if (v->flavor == f_simple)
1766 v->value = allocated_variable_expand (v->value);
1767 else
1768 v->value = xstrdup (v->value);
1770 fname = p->target;
1772 else
1774 struct file *f;
1776 /* Get a file reference for this file, and initialize it.
1777 We don't want to just call enter_file() because that allocates a
1778 new entry if the file is a double-colon, which we don't want in
1779 this situation. */
1780 f = lookup_file (name);
1781 if (!f)
1782 f = enter_file (strcache_add (name));
1783 else if (f->double_colon)
1784 f = f->double_colon;
1786 initialize_file_variables (f, 1);
1787 fname = f->name;
1789 current_variable_set_list = f->variables;
1790 v = try_variable_definition (flocp, defn, origin, 1);
1791 if (!v)
1792 fatal (flocp, _("Malformed target-specific variable definition"));
1793 current_variable_set_list = global;
1796 /* Set up the variable to be *-specific. */
1797 v->per_target = 1;
1798 v->private_var = vmod->private_v;
1799 v->export = vmod->export_v ? v_export : v_default;
1801 /* If it's not an override, check to see if there was a command-line
1802 setting. If so, reset the value. */
1803 if (v->origin != o_override)
1805 struct variable *gv;
1806 int len = strlen(v->name);
1808 gv = lookup_variable (v->name, len);
1809 if (gv && v != gv
1810 && (gv->origin == o_env_override || gv->origin == o_command))
1812 if (v->value != 0)
1813 free (v->value);
1814 v->value = xstrdup (gv->value);
1815 v->origin = gv->origin;
1816 v->recursive = gv->recursive;
1817 v->append = 0;
1823 /* Record a description line for files FILENAMES,
1824 with dependencies DEPS, commands to execute described
1825 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1826 TWO_COLON is nonzero if a double colon was used.
1827 If not nil, PATTERN is the '%' pattern to make this
1828 a static pattern rule, and PATTERN_PERCENT is a pointer
1829 to the '%' within it.
1831 The links of FILENAMES are freed, and so are any names in it
1832 that are not incorporated into other data structures. */
1834 static void
1835 record_files (struct nameseq *filenames, const char *pattern,
1836 const char *pattern_percent, char *depstr,
1837 unsigned int cmds_started, char *commands,
1838 unsigned int commands_idx, int two_colon,
1839 char prefix, const struct floc *flocp)
1841 struct commands *cmds;
1842 struct dep *deps;
1843 const char *implicit_percent;
1844 const char *name;
1846 /* If we've already snapped deps, that means we're in an eval being
1847 resolved after the makefiles have been read in. We can't add more rules
1848 at this time, since they won't get snapped and we'll get core dumps.
1849 See Savannah bug # 12124. */
1850 if (snapped_deps)
1851 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1853 /* Determine if this is a pattern rule or not. */
1854 name = filenames->name;
1855 implicit_percent = find_percent_cached (&name);
1857 /* If there's a recipe, set up a struct for it. */
1858 if (commands_idx > 0)
1860 cmds = xmalloc (sizeof (struct commands));
1861 cmds->fileinfo.filenm = flocp->filenm;
1862 cmds->fileinfo.lineno = cmds_started;
1863 cmds->commands = xstrndup (commands, commands_idx);
1864 cmds->command_lines = 0;
1865 cmds->recipe_prefix = prefix;
1867 else
1868 cmds = 0;
1870 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1871 expansion: if so, snap_deps() will do it. */
1872 if (depstr == 0)
1873 deps = 0;
1874 else
1876 depstr = unescape_char (depstr, ':');
1877 if (second_expansion && strchr (depstr, '$'))
1879 deps = alloc_dep ();
1880 deps->name = depstr;
1881 deps->need_2nd_expansion = 1;
1882 deps->staticpattern = pattern != 0;
1884 else
1886 deps = split_prereqs (depstr);
1887 free (depstr);
1889 /* We'll enter static pattern prereqs later when we have the stem.
1890 We don't want to enter pattern rules at all so that we don't
1891 think that they ought to exist (make manual "Implicit Rule Search
1892 Algorithm", item 5c). */
1893 if (! pattern && ! implicit_percent)
1894 deps = enter_prereqs (deps, NULL);
1898 /* For implicit rules, _all_ the targets must have a pattern. That means we
1899 can test the first one to see if we're working with an implicit rule; if
1900 so we handle it specially. */
1902 if (implicit_percent)
1904 struct nameseq *nextf;
1905 const char **targets, **target_pats;
1906 unsigned int c;
1908 if (pattern != 0)
1909 fatal (flocp, _("mixed implicit and static pattern rules"));
1911 /* Count the targets to create an array of target names.
1912 We already have the first one. */
1913 nextf = filenames->next;
1914 free_ns (filenames);
1915 filenames = nextf;
1917 for (c = 1; nextf; ++c, nextf = nextf->next)
1919 targets = xmalloc (c * sizeof (const char *));
1920 target_pats = xmalloc (c * sizeof (const char *));
1922 targets[0] = name;
1923 target_pats[0] = implicit_percent;
1925 c = 1;
1926 while (filenames)
1928 name = filenames->name;
1929 implicit_percent = find_percent_cached (&name);
1931 if (implicit_percent == 0)
1932 fatal (flocp, _("mixed implicit and normal rules"));
1934 targets[c] = name;
1935 target_pats[c] = implicit_percent;
1936 ++c;
1938 nextf = filenames->next;
1939 free_ns (filenames);
1940 filenames = nextf;
1943 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1945 return;
1949 /* Walk through each target and create it in the database.
1950 We already set up the first target, above. */
1951 while (1)
1953 struct nameseq *nextf = filenames->next;
1954 struct file *f;
1955 struct dep *this = 0;
1957 free_ns (filenames);
1959 /* Check for special targets. Do it here instead of, say, snap_deps()
1960 so that we can immediately use the value. */
1961 if (streq (name, ".POSIX"))
1963 posix_pedantic = 1;
1964 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1965 /* These default values are based on IEEE Std 1003.1-2008. */
1966 define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
1967 define_variable_cname ("CC", "c99", o_default, 0);
1968 define_variable_cname ("CFLAGS", "-O", o_default, 0);
1969 define_variable_cname ("FC", "fort77", o_default, 0);
1970 define_variable_cname ("FFLAGS", "-O 1", o_default, 0);
1971 define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
1973 else if (streq (name, ".SECONDEXPANSION"))
1974 second_expansion = 1;
1975 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
1976 else if (streq (name, ".ONESHELL"))
1977 one_shell = 1;
1978 #endif
1980 /* If this is a static pattern rule:
1981 'targets: target%pattern: prereq%pattern; recipe',
1982 make sure the pattern matches this target name. */
1983 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1984 error (flocp, _("target '%s' doesn't match the target pattern"), name);
1985 else if (deps)
1986 /* If there are multiple targets, copy the chain DEPS for all but the
1987 last one. It is not safe for the same deps to go in more than one
1988 place in the database. */
1989 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1991 /* Find or create an entry in the file database for this target. */
1992 if (!two_colon)
1994 /* Single-colon. Combine this rule with the file's existing record,
1995 if any. */
1996 f = enter_file (strcache_add (name));
1997 if (f->double_colon)
1998 fatal (flocp,
1999 _("target file '%s' has both : and :: entries"), f->name);
2001 /* If CMDS == F->CMDS, this target was listed in this rule
2002 more than once. Just give a warning since this is harmless. */
2003 if (cmds != 0 && cmds == f->cmds)
2004 error (flocp,
2005 _("target '%s' given more than once in the same rule."),
2006 f->name);
2008 /* Check for two single-colon entries both with commands.
2009 Check is_target so that we don't lose on files such as .c.o
2010 whose commands were preinitialized. */
2011 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2013 error (&cmds->fileinfo,
2014 _("warning: overriding recipe for target '%s'"),
2015 f->name);
2016 error (&f->cmds->fileinfo,
2017 _("warning: ignoring old recipe for target '%s'"),
2018 f->name);
2021 /* Defining .DEFAULT with no deps or cmds clears it. */
2022 if (f == default_file && this == 0 && cmds == 0)
2023 f->cmds = 0;
2024 if (cmds != 0)
2025 f->cmds = cmds;
2027 /* Defining .SUFFIXES with no dependencies clears out the list of
2028 suffixes. */
2029 if (f == suffix_file && this == 0)
2031 free_dep_chain (f->deps);
2032 f->deps = 0;
2035 else
2037 /* Double-colon. Make a new record even if there already is one. */
2038 f = lookup_file (name);
2040 /* Check for both : and :: rules. Check is_target so we don't lose
2041 on default suffix rules or makefiles. */
2042 if (f != 0 && f->is_target && !f->double_colon)
2043 fatal (flocp,
2044 _("target file '%s' has both : and :: entries"), f->name);
2046 f = enter_file (strcache_add (name));
2047 /* If there was an existing entry and it was a double-colon entry,
2048 enter_file will have returned a new one, making it the prev
2049 pointer of the old one, and setting its double_colon pointer to
2050 the first one. */
2051 if (f->double_colon == 0)
2052 /* This is the first entry for this name, so we must set its
2053 double_colon pointer to itself. */
2054 f->double_colon = f;
2056 f->cmds = cmds;
2059 f->is_target = 1;
2061 /* If this is a static pattern rule, set the stem to the part of its
2062 name that matched the '%' in the pattern, so you can use $* in the
2063 commands. If we didn't do it before, enter the prereqs now. */
2064 if (pattern)
2066 static const char *percent = "%";
2067 char *buffer = variable_expand ("");
2068 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2069 pattern_percent+1, percent+1);
2070 f->stem = strcache_add_len (buffer, o - buffer);
2071 if (this)
2073 if (! this->need_2nd_expansion)
2074 this = enter_prereqs (this, f->stem);
2075 else
2076 this->stem = f->stem;
2080 /* Add the dependencies to this file entry. */
2081 if (this != 0)
2083 /* Add the file's old deps and the new ones in THIS together. */
2084 if (f->deps == 0)
2085 f->deps = this;
2086 else if (cmds != 0)
2088 struct dep *d = this;
2090 /* If this rule has commands, put these deps first. */
2091 while (d->next != 0)
2092 d = d->next;
2094 d->next = f->deps;
2095 f->deps = this;
2097 else
2099 struct dep *d = f->deps;
2101 /* A rule without commands: put its prereqs at the end. */
2102 while (d->next != 0)
2103 d = d->next;
2105 d->next = this;
2109 name = f->name;
2111 /* All done! Set up for the next one. */
2112 if (nextf == 0)
2113 break;
2115 filenames = nextf;
2117 /* Reduce escaped percents. If there are any unescaped it's an error */
2118 name = filenames->name;
2119 if (find_percent_cached (&name))
2120 fatal (flocp, _("mixed implicit and normal rules"));
2124 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2125 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2126 Quoting backslashes are removed from STRING by compacting it into
2127 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2128 one, or nil if there are none. STOPCHARs inside variable references are
2129 ignored if IGNOREVARS is true.
2131 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2133 static char *
2134 find_char_unquote (char *string, int stop1, int stop2, int blank,
2135 int ignorevars)
2137 unsigned int string_len = 0;
2138 char *p = string;
2140 if (ignorevars)
2141 ignorevars = '$';
2143 while (1)
2145 if (stop2 && blank)
2146 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2147 && ! isblank ((unsigned char) *p))
2148 ++p;
2149 else if (stop2)
2150 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2151 ++p;
2152 else if (blank)
2153 while (*p != '\0' && *p != ignorevars && *p != stop1
2154 && ! isblank ((unsigned char) *p))
2155 ++p;
2156 else
2157 while (*p != '\0' && *p != ignorevars && *p != stop1)
2158 ++p;
2160 if (*p == '\0')
2161 break;
2163 /* If we stopped due to a variable reference, skip over its contents. */
2164 if (*p == ignorevars)
2166 char openparen = p[1];
2168 p += 2;
2170 /* Skip the contents of a non-quoted, multi-char variable ref. */
2171 if (openparen == '(' || openparen == '{')
2173 unsigned int pcount = 1;
2174 char closeparen = (openparen == '(' ? ')' : '}');
2176 while (*p)
2178 if (*p == openparen)
2179 ++pcount;
2180 else if (*p == closeparen)
2181 if (--pcount == 0)
2183 ++p;
2184 break;
2186 ++p;
2190 /* Skipped the variable reference: look for STOPCHARS again. */
2191 continue;
2194 if (p > string && p[-1] == '\\')
2196 /* Search for more backslashes. */
2197 int i = -2;
2198 while (&p[i] >= string && p[i] == '\\')
2199 --i;
2200 ++i;
2201 /* Only compute the length if really needed. */
2202 if (string_len == 0)
2203 string_len = strlen (string);
2204 /* The number of backslashes is now -I.
2205 Copy P over itself to swallow half of them. */
2206 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2207 p += i/2;
2208 if (i % 2 == 0)
2209 /* All the backslashes quoted each other; the STOPCHAR was
2210 unquoted. */
2211 return p;
2213 /* The STOPCHAR was quoted by a backslash. Look for another. */
2215 else
2216 /* No backslash in sight. */
2217 return p;
2220 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2221 return 0;
2224 /* Unescape a character in a string. The string is compressed onto itself. */
2226 static char *
2227 unescape_char (char *string, int c)
2229 char *p = string;
2230 char *s = string;
2232 while (*s != '\0')
2234 if (*s == '\\')
2236 char *e = s;
2237 int l;
2239 /* We found a backslash. See if it's escaping our character. */
2240 while (*e == '\\')
2241 ++e;
2242 l = e - s;
2244 if (*e != c || l%2 == 0)
2245 /* It's not; just take it all without unescaping. */
2246 memcpy (p, s, l);
2247 else if (l > 1)
2249 /* It is, and there's >1 backslash. Take half of them. */
2250 l /= 2;
2251 memcpy (p, s, l);
2253 s = e;
2254 p += l;
2257 *(p++) = *(s++);
2260 *p = '\0';
2261 return string;
2264 /* Search PATTERN for an unquoted % and handle quoting. */
2266 char *
2267 find_percent (char *pattern)
2269 return find_char_unquote (pattern, '%', 0, 0, 0);
2272 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2273 the % or NULL if no % was found.
2274 This version is used with strings in the string cache: if there's a need to
2275 modify the string a new version will be added to the string cache and
2276 *STRING will be set to that. */
2278 const char *
2279 find_percent_cached (const char **string)
2281 const char *p = *string;
2282 char *new = 0;
2283 int slen = 0;
2285 /* If the first char is a % return now. This lets us avoid extra tests
2286 inside the loop. */
2287 if (*p == '%')
2288 return p;
2290 while (1)
2292 while (*p != '\0' && *p != '%')
2293 ++p;
2295 if (*p == '\0')
2296 break;
2298 /* See if this % is escaped with a backslash; if not we're done. */
2299 if (p[-1] != '\\')
2300 break;
2303 /* Search for more backslashes. */
2304 char *pv;
2305 int i = -2;
2307 while (&p[i] >= *string && p[i] == '\\')
2308 --i;
2309 ++i;
2311 /* At this point we know we'll need to allocate a new string.
2312 Make a copy if we haven't yet done so. */
2313 if (! new)
2315 slen = strlen (*string);
2316 new = alloca (slen + 1);
2317 memcpy (new, *string, slen + 1);
2318 p = new + (p - *string);
2319 *string = new;
2322 /* At this point *string, p, and new all point into the same string.
2323 Get a non-const version of p so we can modify new. */
2324 pv = new + (p - *string);
2326 /* The number of backslashes is now -I.
2327 Copy P over itself to swallow half of them. */
2328 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2329 p += i/2;
2331 /* If the backslashes quoted each other; the % was unquoted. */
2332 if (i % 2 == 0)
2333 break;
2337 /* If we had to change STRING, add it to the strcache. */
2338 if (new)
2340 *string = strcache_add (*string);
2341 p = *string + (p - new);
2344 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2345 return (*p == '\0') ? NULL : p;
2348 /* Find the next line of text in an eval buffer, combining continuation lines
2349 into one line.
2350 Return the number of actual lines read (> 1 if continuation lines).
2351 Returns -1 if there's nothing left in the buffer.
2353 After this function, ebuf->buffer points to the first character of the
2354 line we just found.
2357 /* Read a line of text from a STRING.
2358 Since we aren't really reading from a file, don't bother with linenumbers.
2361 static unsigned long
2362 readstring (struct ebuffer *ebuf)
2364 char *eol;
2366 /* If there is nothing left in this buffer, return 0. */
2367 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2368 return -1;
2370 /* Set up a new starting point for the buffer, and find the end of the
2371 next logical line (taking into account backslash/newline pairs). */
2373 eol = ebuf->buffer = ebuf->bufnext;
2375 while (1)
2377 int backslash = 0;
2378 const char *bol = eol;
2379 const char *p;
2381 /* Find the next newline. At EOS, stop. */
2382 p = eol = strchr (eol , '\n');
2383 if (!eol)
2385 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2386 return 0;
2389 /* Found a newline; if it's escaped continue; else we're done. */
2390 while (p > bol && *(--p) == '\\')
2391 backslash = !backslash;
2392 if (!backslash)
2393 break;
2394 ++eol;
2397 /* Overwrite the newline char. */
2398 *eol = '\0';
2399 ebuf->bufnext = eol+1;
2401 return 0;
2404 static long
2405 readline (struct ebuffer *ebuf)
2407 char *p;
2408 char *end;
2409 char *start;
2410 long nlines = 0;
2412 /* The behaviors between string and stream buffers are different enough to
2413 warrant different functions. Do the Right Thing. */
2415 if (!ebuf->fp)
2416 return readstring (ebuf);
2418 /* When reading from a file, we always start over at the beginning of the
2419 buffer for each new line. */
2421 p = start = ebuf->bufstart;
2422 end = p + ebuf->size;
2423 *p = '\0';
2425 while (fgets (p, end - p, ebuf->fp) != 0)
2427 char *p2;
2428 unsigned long len;
2429 int backslash;
2431 len = strlen (p);
2432 if (len == 0)
2434 /* This only happens when the first thing on the line is a '\0'.
2435 It is a pretty hopeless case, but (wonder of wonders) Athena
2436 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2437 There is nothing really to be done; we synthesize a newline so
2438 the following line doesn't appear to be part of this line. */
2439 error (&ebuf->floc,
2440 _("warning: NUL character seen; rest of line ignored"));
2441 p[0] = '\n';
2442 len = 1;
2445 /* Jump past the text we just read. */
2446 p += len;
2448 /* If the last char isn't a newline, the whole line didn't fit into the
2449 buffer. Get some more buffer and try again. */
2450 if (p[-1] != '\n')
2451 goto more_buffer;
2453 /* We got a newline, so add one to the count of lines. */
2454 ++nlines;
2456 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2457 /* Check to see if the line was really ended with CRLF; if so ignore
2458 the CR. */
2459 if ((p - start) > 1 && p[-2] == '\r')
2461 --p;
2462 p[-1] = '\n';
2464 #endif
2466 backslash = 0;
2467 for (p2 = p - 2; p2 >= start; --p2)
2469 if (*p2 != '\\')
2470 break;
2471 backslash = !backslash;
2474 if (!backslash)
2476 p[-1] = '\0';
2477 break;
2480 /* It was a backslash/newline combo. If we have more space, read
2481 another line. */
2482 if (end - p >= 80)
2483 continue;
2485 /* We need more space at the end of our buffer, so realloc it.
2486 Make sure to preserve the current offset of p. */
2487 more_buffer:
2489 unsigned long off = p - start;
2490 ebuf->size *= 2;
2491 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2492 p = start + off;
2493 end = start + ebuf->size;
2494 *p = '\0';
2498 if (ferror (ebuf->fp))
2499 pfatal_with_name (ebuf->floc.filenm);
2501 /* If we found some lines, return how many.
2502 If we didn't, but we did find _something_, that indicates we read the last
2503 line of a file with no final newline; return 1.
2504 If we read nothing, we're at EOF; return -1. */
2506 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2509 /* Parse the next "makefile word" from the input buffer, and return info
2510 about it.
2512 A "makefile word" is one of:
2514 w_bogus Should never happen
2515 w_eol End of input
2516 w_static A static word; cannot be expanded
2517 w_variable A word containing one or more variables/functions
2518 w_colon A colon
2519 w_dcolon A double-colon
2520 w_semicolon A semicolon
2521 w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
2523 Note that this function is only used when reading certain parts of the
2524 makefile. Don't use it where special rules hold sway (RHS of a variable,
2525 in a command list, etc.) */
2527 static enum make_word_type
2528 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2530 enum make_word_type wtype = w_bogus;
2531 char *p = buffer, *beg;
2532 char c;
2534 /* Skip any leading whitespace. */
2535 while (isblank ((unsigned char)*p))
2536 ++p;
2538 beg = p;
2539 c = *(p++);
2540 switch (c)
2542 case '\0':
2543 wtype = w_eol;
2544 break;
2546 case ';':
2547 wtype = w_semicolon;
2548 break;
2550 case '=':
2551 wtype = w_varassign;
2552 break;
2554 case ':':
2555 wtype = w_colon;
2556 switch (*p)
2558 case ':':
2559 ++p;
2560 if (p[1] != '=')
2561 wtype = w_dcolon;
2562 else
2564 wtype = w_varassign;
2565 ++p;
2567 break;
2569 case '=':
2570 ++p;
2571 wtype = w_varassign;
2572 break;
2574 break;
2576 case '+':
2577 case '?':
2578 case '!':
2579 if (*p == '=')
2581 ++p;
2582 wtype = w_varassign;
2583 break;
2586 default:
2587 if (delim && strchr (delim, c))
2588 wtype = w_static;
2589 break;
2592 /* Did we find something? If so, return now. */
2593 if (wtype != w_bogus)
2594 goto done;
2596 /* This is some non-operator word. A word consists of the longest
2597 string of characters that doesn't contain whitespace, one of [:=#],
2598 or [?+!]=, or one of the chars in the DELIM string. */
2600 /* We start out assuming a static word; if we see a variable we'll
2601 adjust our assumptions then. */
2602 wtype = w_static;
2604 /* We already found the first value of "c", above. */
2605 while (1)
2607 char closeparen;
2608 int count;
2610 switch (c)
2612 case '\0':
2613 case ' ':
2614 case '\t':
2615 case '=':
2616 goto done_word;
2618 case ':':
2619 #ifdef HAVE_DOS_PATHS
2620 /* A word CAN include a colon in its drive spec. The drive
2621 spec is allowed either at the beginning of a word, or as part
2622 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2623 if (!(p - beg >= 2
2624 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2625 && (p - beg == 2 || p[-3] == '(')))
2626 #endif
2627 goto done_word;
2629 case '$':
2630 c = *(p++);
2631 if (c == '$')
2632 break;
2634 /* This is a variable reference, so note that it's expandable.
2635 Then read it to the matching close paren. */
2636 wtype = w_variable;
2638 if (c == '(')
2639 closeparen = ')';
2640 else if (c == '{')
2641 closeparen = '}';
2642 else
2643 /* This is a single-letter variable reference. */
2644 break;
2646 for (count=0; *p != '\0'; ++p)
2648 if (*p == c)
2649 ++count;
2650 else if (*p == closeparen && --count < 0)
2652 ++p;
2653 break;
2656 break;
2658 case '?':
2659 case '+':
2660 if (*p == '=')
2661 goto done_word;
2662 break;
2664 case '\\':
2665 switch (*p)
2667 case ':':
2668 case ';':
2669 case '=':
2670 case '\\':
2671 ++p;
2672 break;
2674 break;
2676 default:
2677 if (delim && strchr (delim, c))
2678 goto done_word;
2679 break;
2682 c = *(p++);
2684 done_word:
2685 --p;
2687 done:
2688 if (startp)
2689 *startp = beg;
2690 if (length)
2691 *length = p - beg;
2692 return wtype;
2695 /* Construct the list of include directories
2696 from the arguments and the default list. */
2698 void
2699 construct_include_path (const char **arg_dirs)
2701 #ifdef VAXC /* just don't ask ... */
2702 stat_t stbuf;
2703 #else
2704 struct stat stbuf;
2705 #endif
2706 const char **dirs;
2707 const char **cpp;
2708 unsigned int idx;
2710 /* Compute the number of pointers we need in the table. */
2711 idx = sizeof (default_include_directories) / sizeof (const char *);
2712 if (arg_dirs)
2713 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2714 ++idx;
2716 #ifdef __MSDOS__
2717 /* Add one for $DJDIR. */
2718 ++idx;
2719 #endif
2721 dirs = xmalloc (idx * sizeof (const char *));
2723 idx = 0;
2724 max_incl_len = 0;
2726 /* First consider any dirs specified with -I switches.
2727 Ignore any that don't exist. Remember the maximum string length. */
2729 if (arg_dirs)
2730 while (*arg_dirs != 0)
2732 const char *dir = *(arg_dirs++);
2733 char *expanded = 0;
2734 int e;
2736 if (dir[0] == '~')
2738 expanded = tilde_expand (dir);
2739 if (expanded != 0)
2740 dir = expanded;
2743 EINTRLOOP (e, stat (dir, &stbuf));
2744 if (e == 0 && S_ISDIR (stbuf.st_mode))
2746 unsigned int len = strlen (dir);
2747 /* If dir name is written with trailing slashes, discard them. */
2748 while (len > 1 && dir[len - 1] == '/')
2749 --len;
2750 if (len > max_incl_len)
2751 max_incl_len = len;
2752 dirs[idx++] = strcache_add_len (dir, len);
2755 if (expanded)
2756 free (expanded);
2759 /* Now add the standard default dirs at the end. */
2761 #ifdef __MSDOS__
2763 /* The environment variable $DJDIR holds the root of the DJGPP directory
2764 tree; add ${DJDIR}/include. */
2765 struct variable *djdir = lookup_variable ("DJDIR", 5);
2767 if (djdir)
2769 unsigned int len = strlen (djdir->value) + 8;
2770 char *defdir = alloca (len + 1);
2772 strcat (strcpy (defdir, djdir->value), "/include");
2773 dirs[idx++] = strcache_add (defdir);
2775 if (len > max_incl_len)
2776 max_incl_len = len;
2779 #endif
2781 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2783 int e;
2785 EINTRLOOP (e, stat (*cpp, &stbuf));
2786 if (e == 0 && S_ISDIR (stbuf.st_mode))
2788 unsigned int len = strlen (*cpp);
2789 /* If dir name is written with trailing slashes, discard them. */
2790 while (len > 1 && (*cpp)[len - 1] == '/')
2791 --len;
2792 if (len > max_incl_len)
2793 max_incl_len = len;
2794 dirs[idx++] = strcache_add_len (*cpp, len);
2798 dirs[idx] = 0;
2800 /* Now add each dir to the .INCLUDE_DIRS variable. */
2802 for (cpp = dirs; *cpp != 0; ++cpp)
2803 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2804 o_default, f_append, 0);
2806 include_directories = dirs;
2809 /* Expand ~ or ~USER at the beginning of NAME.
2810 Return a newly malloc'd string or 0. */
2812 char *
2813 tilde_expand (const char *name)
2815 #ifndef VMS
2816 if (name[1] == '/' || name[1] == '\0')
2818 extern char *getenv ();
2819 char *home_dir;
2820 int is_variable;
2823 /* Turn off --warn-undefined-variables while we expand HOME. */
2824 int save = warn_undefined_variables_flag;
2825 warn_undefined_variables_flag = 0;
2827 home_dir = allocated_variable_expand ("$(HOME)");
2829 warn_undefined_variables_flag = save;
2832 is_variable = home_dir[0] != '\0';
2833 if (!is_variable)
2835 free (home_dir);
2836 home_dir = getenv ("HOME");
2838 # if !defined(_AMIGA) && !defined(WINDOWS32)
2839 if (home_dir == 0 || home_dir[0] == '\0')
2841 extern char *getlogin ();
2842 char *logname = getlogin ();
2843 home_dir = 0;
2844 if (logname != 0)
2846 struct passwd *p = getpwnam (logname);
2847 if (p != 0)
2848 home_dir = p->pw_dir;
2851 # endif /* !AMIGA && !WINDOWS32 */
2852 if (home_dir != 0)
2854 char *new = xstrdup (concat (2, home_dir, name + 1));
2855 if (is_variable)
2856 free (home_dir);
2857 return new;
2860 # if !defined(_AMIGA) && !defined(WINDOWS32)
2861 else
2863 struct passwd *pwent;
2864 char *userend = strchr (name + 1, '/');
2865 if (userend != 0)
2866 *userend = '\0';
2867 pwent = getpwnam (name + 1);
2868 if (pwent != 0)
2870 if (userend == 0)
2871 return xstrdup (pwent->pw_dir);
2872 else
2873 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2875 else if (userend != 0)
2876 *userend = '/';
2878 # endif /* !AMIGA && !WINDOWS32 */
2879 #endif /* !VMS */
2880 return 0;
2883 /* Parse a string into a sequence of filenames represented as a chain of
2884 struct nameseq's and return that chain. Optionally expand the strings via
2885 glob().
2887 The string is passed as STRINGP, the address of a string pointer.
2888 The string pointer is updated to point at the first character
2889 not parsed, which either is a null char or equals STOPCHAR.
2891 SIZE is how big to construct chain elements.
2892 This is useful if we want them actually to be other structures
2893 that have room for additional info.
2895 PREFIX, if non-null, is added to the beginning of each filename.
2897 FLAGS allows one or more of the following bitflags to be set:
2898 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2899 PARSEFS_NOAR - Do not check filenames for archive references
2900 PARSEFS_NOGLOB - Do not expand globbing characters
2901 PARSEFS_EXISTS - Only return globbed files that actually exist
2902 (cannot also set NOGLOB)
2903 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2906 void *
2907 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2908 const char *prefix, int flags)
2910 extern void dir_setup_glob (glob_t *glob);
2912 /* tmp points to tmpbuf after the prefix, if any.
2913 tp is the end of the buffer. */
2914 static char *tmpbuf = NULL;
2915 static int tmpbuf_len = 0;
2917 int cachep = (! (flags & PARSEFS_NOCACHE));
2919 struct nameseq *new = 0;
2920 struct nameseq **newp = &new;
2921 #define NEWELT(_n) do { \
2922 const char *__n = (_n); \
2923 *newp = xcalloc (size); \
2924 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2925 newp = &(*newp)->next; \
2926 } while(0)
2928 char *p;
2929 glob_t gl;
2930 char *tp;
2932 #ifdef VMS
2933 # define VMS_COMMA ','
2934 #else
2935 # define VMS_COMMA 0
2936 #endif
2938 if (size < sizeof (struct nameseq))
2939 size = sizeof (struct nameseq);
2941 if (! (flags & PARSEFS_NOGLOB))
2942 dir_setup_glob (&gl);
2944 /* Get enough temporary space to construct the largest possible target. */
2946 int l = strlen (*stringp) + 1;
2947 if (l > tmpbuf_len)
2949 tmpbuf = xrealloc (tmpbuf, l);
2950 tmpbuf_len = l;
2953 tp = tmpbuf;
2955 /* Parse STRING. P will always point to the end of the parsed content. */
2956 p = *stringp;
2957 while (1)
2959 const char *name;
2960 const char **nlist = 0;
2961 char *tildep = 0;
2962 int globme = 1;
2963 #ifndef NO_ARCHIVES
2964 char *arname = 0;
2965 char *memname = 0;
2966 #endif
2967 char *s;
2968 int nlen;
2969 int i;
2971 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2972 p = next_token (p);
2973 if (*p == '\0' || *p == stopchar)
2974 break;
2976 /* There are names left, so find the end of the next name.
2977 Throughout this iteration S points to the start. */
2978 s = p;
2979 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2980 #ifdef VMS
2981 /* convert comma separated list to space separated */
2982 if (p && *p == ',')
2983 *p =' ';
2984 #endif
2985 #ifdef _AMIGA
2986 if (stopchar == ':' && p && *p == ':'
2987 && !(isspace ((unsigned char)p[1]) || !p[1]
2988 || isspace ((unsigned char)p[-1])))
2989 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2990 #endif
2991 #ifdef HAVE_DOS_PATHS
2992 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2993 first colon which isn't followed by a slash or a backslash.
2994 Note that tokens separated by spaces should be treated as separate
2995 tokens since make doesn't allow path names with spaces */
2996 if (stopchar == ':')
2997 while (p != 0 && !isspace ((unsigned char)*p) &&
2998 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2999 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
3000 #endif
3001 if (p == 0)
3002 p = s + strlen (s);
3004 /* Strip leading "this directory" references. */
3005 if (! (flags & PARSEFS_NOSTRIP))
3006 #ifdef VMS
3007 /* Skip leading '[]'s. */
3008 while (p - s > 2 && s[0] == '[' && s[1] == ']')
3009 #else
3010 /* Skip leading './'s. */
3011 while (p - s > 2 && s[0] == '.' && s[1] == '/')
3012 #endif
3014 /* Skip "./" and all following slashes. */
3015 s += 2;
3016 while (*s == '/')
3017 ++s;
3020 /* Extract the filename just found, and skip it.
3021 Set NAME to the string, and NLEN to its length. */
3023 if (s == p)
3025 /* The name was stripped to empty ("./"). */
3026 #if defined(VMS)
3027 continue;
3028 #elif defined(_AMIGA)
3029 /* PDS-- This cannot be right!! */
3030 tp[0] = '\0';
3031 nlen = 0;
3032 #else
3033 tp[0] = '.';
3034 tp[1] = '/';
3035 tp[2] = '\0';
3036 nlen = 2;
3037 #endif
3039 else
3041 #ifdef VMS
3042 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
3043 * to remove this '\' before we can use the filename.
3044 * xstrdup called because S may be read-only string constant.
3046 char *n = tp;
3047 while (s < p)
3049 if (s[0] == '\\' && s[1] == ':')
3050 ++s;
3051 *(n++) = *(s++);
3053 n[0] = '\0';
3054 nlen = strlen (tp);
3055 #else
3056 nlen = p - s;
3057 memcpy (tp, s, nlen);
3058 tp[nlen] = '\0';
3059 #endif
3062 /* At this point, TP points to the element and NLEN is its length. */
3064 #ifndef NO_ARCHIVES
3065 /* If this is the start of an archive group that isn't complete, set up
3066 to add the archive prefix for future files. A file list like:
3067 "libf.a(x.o y.o z.o)" needs to be expanded as:
3068 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3070 TP == TMP means we're not already in an archive group. Ignore
3071 something starting with '(', as that cannot actually be an
3072 archive-member reference (and treating it as such results in an empty
3073 file name, which causes much lossage). Also if it ends in ")" then
3074 it's a complete reference so we don't need to treat it specially.
3076 Finally, note that archive groups must end with ')' as the last
3077 character, so ensure there's some word ending like that before
3078 considering this an archive group. */
3079 if (! (flags & PARSEFS_NOAR)
3080 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3082 char *n = strchr (tp, '(');
3083 if (n)
3085 /* This looks like the first element in an open archive group.
3086 A valid group MUST have ')' as the last character. */
3087 const char *e = p;
3090 const char *o = e;
3091 e = next_token (e);
3092 /* Find the end of this word. We don't want to unquote and
3093 we don't care about quoting since we're looking for the
3094 last char in the word. */
3095 while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3096 && ! isblank ((unsigned char) *e))
3097 ++e;
3098 /* If we didn't move, we're done now. */
3099 if (e == o)
3100 break;
3101 if (e[-1] == ')')
3103 /* Found the end, so this is the first element in an
3104 open archive group. It looks like "lib(mem".
3105 Reset TP past the open paren. */
3106 nlen -= (n + 1) - tp;
3107 tp = n + 1;
3109 /* We can stop looking now. */
3110 break;
3113 while (*e != '\0');
3115 /* If we have just "lib(", part of something like "lib( a b)",
3116 go to the next item. */
3117 if (! nlen)
3118 continue;
3122 /* If we are inside an archive group, make sure it has an end. */
3123 if (tp > tmpbuf)
3125 if (tp[nlen-1] == ')')
3127 /* This is the natural end; reset TP. */
3128 tp = tmpbuf;
3130 /* This is just ")", something like "lib(a b )": skip it. */
3131 if (nlen == 1)
3132 continue;
3134 else
3136 /* Not the end, so add a "fake" end. */
3137 tp[nlen++] = ')';
3138 tp[nlen] = '\0';
3141 #endif
3143 /* If we're not globbing we're done: add it to the end of the chain.
3144 Go to the next item in the string. */
3145 if (flags & PARSEFS_NOGLOB)
3147 NEWELT (concat (2, prefix, tmpbuf));
3148 continue;
3151 /* If we get here we know we're doing glob expansion.
3152 TP is a string in tmpbuf. NLEN is no longer used.
3153 We may need to do more work: after this NAME will be set. */
3154 name = tmpbuf;
3156 /* Expand tilde if applicable. */
3157 if (tmpbuf[0] == '~')
3159 tildep = tilde_expand (tmpbuf);
3160 if (tildep != 0)
3161 name = tildep;
3164 #ifndef NO_ARCHIVES
3165 /* If NAME is an archive member reference replace it with the archive
3166 file name, and save the member name in MEMNAME. We will glob on the
3167 archive name and then reattach MEMNAME later. */
3168 if (! (flags & PARSEFS_NOAR) && ar_name (name))
3170 ar_parse_name (name, &arname, &memname);
3171 name = arname;
3173 #endif /* !NO_ARCHIVES */
3175 /* glob() is expensive: don't call it unless we need to. */
3176 if (!(flags & PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3178 globme = 0;
3179 i = 1;
3180 nlist = &name;
3182 else
3183 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3185 case GLOB_NOSPACE:
3186 fatal (NILF, _("virtual memory exhausted"));
3188 case 0:
3189 /* Success. */
3190 i = gl.gl_pathc;
3191 nlist = (const char **)gl.gl_pathv;
3192 break;
3194 case GLOB_NOMATCH:
3195 /* If we want only existing items, skip this one. */
3196 if (flags & PARSEFS_EXISTS)
3198 i = 0;
3199 break;
3201 /* FALLTHROUGH */
3203 default:
3204 /* By default keep this name. */
3205 i = 1;
3206 nlist = &name;
3207 break;
3210 /* For each matched element, add it to the list. */
3211 while (i-- > 0)
3212 #ifndef NO_ARCHIVES
3213 if (memname != 0)
3215 /* Try to glob on MEMNAME within the archive. */
3216 struct nameseq *found = ar_glob (nlist[i], memname, size);
3217 if (! found)
3218 /* No matches. Use MEMNAME as-is. */
3219 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3220 else
3222 /* We got a chain of items. Attach them. */
3223 if (*newp)
3224 (*newp)->next = found;
3225 else
3226 *newp = found;
3228 /* Find and set the new end. Massage names if necessary. */
3229 while (1)
3231 if (! cachep)
3232 found->name = xstrdup (concat (2, prefix, name));
3233 else if (prefix)
3234 found->name = strcache_add (concat (2, prefix, name));
3236 if (found->next == 0)
3237 break;
3239 found = found->next;
3241 newp = &found->next;
3244 else
3245 #endif /* !NO_ARCHIVES */
3246 NEWELT (concat (2, prefix, nlist[i]));
3248 if (globme)
3249 globfree (&gl);
3251 #ifndef NO_ARCHIVES
3252 if (arname)
3253 free (arname);
3254 #endif
3256 if (tildep)
3257 free (tildep);
3260 *stringp = p;
3261 return new;