1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988-2022 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
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 <https://www.gnu.org/licenses/>. */
35 #else /* !WINDOWS32 */
40 struct passwd *getpwnam (char *name);
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 size_t size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 floc floc; /* Info on the file in fp (if any). */
59 /* Track the modifiers we can have on variable assignments */
63 unsigned int assign_v:1;
64 unsigned int define_v:1;
65 unsigned int undefine_v:1;
66 unsigned int override_v:1;
67 unsigned int private_v:1;
68 enum variable_export export_v ENUM_BITFIELD (2);
71 /* Types of "words" that can be read in a makefile. */
74 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
75 w_varassign, w_ampcolon, w_ampdcolon
79 /* A 'struct conditionals' contains the information describing
80 all the active conditionals in a makefile.
82 The global variable 'conditionals' contains the conditionals
83 information for the current makefile. It is initialized from
84 the static structure 'toplevel_conditionals' and is later changed
85 to new structures for included makefiles. */
89 unsigned int if_cmds; /* Depth of conditional nesting. */
90 unsigned int allocated; /* Elts allocated in following arrays. */
91 char *ignoring; /* Are we ignoring or interpreting?
92 0=interpreting, 1=not yet interpreted,
93 2=already interpreted */
94 char *seen_else; /* Have we already seen an 'else'? */
97 static struct conditionals toplevel_conditionals;
98 static struct conditionals *conditionals = &toplevel_conditionals;
101 /* Default directories to search for include files in */
103 static const char *default_include_directories[] =
105 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
106 /* This completely up to the user when they install MSVC or other packages.
107 This is defined as a placeholder. */
108 # define INCLUDEDIR "."
110 #if defined(INCLUDEDIR)
115 "/usr/local/include",
121 /* List of directories to search for include files in */
123 static const char **include_directories;
125 /* Maximum length of an element of the above. */
127 static size_t max_incl_len;
129 /* The filename and pointer to line number of the
130 makefile currently being read in. */
132 const floc *reading_file = 0;
134 /* The chain of files read by read_all_makefiles. */
136 static struct goaldep *read_files = 0;
138 static struct goaldep *eval_makefile (const char *filename, unsigned short flags);
139 static void eval (struct ebuffer *buffer, int flags);
141 static long readline (struct ebuffer *ebuf);
142 static void do_undefine (char *name, enum variable_origin origin,
143 struct ebuffer *ebuf);
144 static struct variable *do_define (char *name, enum variable_origin origin,
145 struct ebuffer *ebuf);
146 static int conditional_line (char *line, size_t len, const floc *flocp);
147 static void check_specials (struct nameseq *filep, int set_default);
148 static void check_special_file (struct file *filep, const floc *flocp);
149 static void record_files (struct nameseq *filenames, int are_also_makes,
151 const char *pattern_percent, char *depstr,
152 unsigned int cmds_started, char *commands,
153 size_t commands_idx, int two_colon,
154 char prefix, const floc *flocp);
155 static void record_target_var (struct nameseq *filenames, char *defn,
156 enum variable_origin origin,
157 struct vmodifiers *vmod,
159 static enum make_word_type get_next_mword (char *buffer,
160 char **startp, size_t *length);
161 static void remove_comments (char *line);
162 static char *find_map_unquote (char *string, int map);
163 static char *find_char_unquote (char *string, int stop);
164 static char *unescape_char (char *string, int c);
167 /* Compare a word, both length and contents.
168 P must point to the word to be tested, and WLEN must be the length. */
169 #define word1eq(s) (wlen == CSTRLEN (s) && memcmp (s, p, CSTRLEN (s)) == 0)
172 /* Read in all the makefiles and return a chain of targets to rebuild. */
175 read_all_makefiles (const char **makefiles)
177 unsigned int num_makefiles = 0;
179 /* Create *_LIST variables, to hold the makefiles, targets, and variables
180 we will be reading. */
182 define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
184 DB (DB_BASIC, (_("Reading makefiles...\n")));
186 /* If there's a non-null variable MAKEFILES, its value is a list of
187 files to read first thing. But don't let it prevent reading the
188 default makefiles and don't let the default goal come from there. */
196 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
197 int save = warn_undefined_variables_flag;
198 warn_undefined_variables_flag = 0;
200 value = allocated_variable_expand ("$(MAKEFILES)");
202 warn_undefined_variables_flag = save;
205 /* Set NAME to the start of next token and LENGTH to its length.
206 MAKEFILES is updated for finding remaining tokens. */
209 while ((name = find_next_token ((const char **)&p, &length)) != 0)
213 eval_makefile (strcache_add (name), RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
219 /* Read makefiles specified with -f switches. */
222 while (*makefiles != 0)
224 struct goaldep *d = eval_makefile (*makefiles, 0);
227 perror_with_name ("", *makefiles);
229 /* Reuse the storage allocated for the read_file. */
230 *makefiles = dep_name (d);
235 /* If there were no -f switches, try the default names. */
237 if (num_makefiles == 0)
239 static const char *default_makefiles[] =
241 /* all lower case since readdir() (the vms version) 'lowercasifies' */
242 /* TODO: Above is not always true, this needs more work */
243 { "makefile.vms", "gnumakefile", "makefile", 0 };
246 { "GNUmakefile", "Makefile", "SMakefile", 0 };
247 #else /* !Amiga && !VMS */
249 { "GNUmakefile", "makefile", "Makefile", "makefile.mak", 0 };
250 #else /* !Amiga && !VMS && !WINDOWS32 */
251 { "GNUmakefile", "makefile", "Makefile", 0 };
252 #endif /* !Amiga && !VMS && !WINDOWS32 */
255 const char **p = default_makefiles;
256 while (*p != 0 && !file_exists_p (*p))
261 eval_makefile (*p, 0);
263 perror_with_name ("", *p);
267 /* No default makefile was found. Add the default makefiles to the
268 'read_files' chain so they will be updated if possible. */
269 for (p = default_makefiles; *p != 0; ++p)
271 struct goaldep *d = alloc_goaldep ();
272 d->file = enter_file (strcache_add (*p));
273 /* Tell update_goal_chain to bail out as soon as this file is
274 made, and main not to die if we can't make this file. */
275 d->flags = RM_DONTCARE;
276 d->next = read_files;
285 /* Install a new conditional and return the previous one. */
287 static struct conditionals *
288 install_conditionals (struct conditionals *new)
290 struct conditionals *save = conditionals;
292 memset (new, '\0', sizeof (*new));
298 /* Free the current conditionals and reinstate a saved one. */
301 restore_conditionals (struct conditionals *saved)
303 /* Free any space allocated by conditional_line. */
304 free (conditionals->ignoring);
305 free (conditionals->seen_else);
308 conditionals = saved;
311 static struct goaldep *
312 eval_makefile (const char *filename, unsigned short flags)
314 struct goaldep *deps;
319 /* Create a new goaldep entry. */
320 deps = alloc_goaldep ();
321 deps->next = read_files;
324 ebuf.floc.filenm = filename; /* Use the original file name. */
325 ebuf.floc.lineno = 1;
326 ebuf.floc.offset = 0;
328 if (ISDB (DB_VERBOSE))
330 printf (_("Reading makefile '%s'"), filename);
331 if (flags & RM_NO_DEFAULT_GOAL)
332 printf (_(" (no default goal)"));
333 if (flags & RM_INCLUDED)
334 printf (_(" (search path)"));
335 if (flags & RM_DONTCARE)
336 printf (_(" (don't care)"));
337 if (flags & RM_NO_TILDE)
338 printf (_(" (no ~ expansion)"));
342 /* First, get a stream to read. */
344 /* Expand ~ in FILENAME unless it came from 'include',
345 in which case it was already done. */
346 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
348 expanded = tilde_expand (filename);
354 ENULLLOOP (ebuf.fp, fopen (filename, "r"));
357 /* Check for unrecoverable errors: out of mem or FILE slots. */
368 const char *err = strerror (deps->error);
369 OS (fatal, reading_file, "%s", err);
373 /* If the makefile wasn't found and it's either a makefile from the
374 'MAKEFILES' variable or an included makefile, search the included
375 makefile search path for this makefile. */
376 if (ebuf.fp == NULL && deps->error == ENOENT && (flags & RM_INCLUDED)
377 && *filename != '/' && include_directories)
380 for (dir = include_directories; *dir != NULL; ++dir)
382 const char *included = concat (3, *dir, "/", filename);
384 ENULLLOOP(ebuf.fp, fopen (included, "r"));
399 /* Enter the final name for this makefile as a goaldep. */
400 filename = strcache_add (filename);
401 deps->file = lookup_file (filename);
403 deps->file = enter_file (filename);
404 filename = deps->file->name;
411 /* The makefile can't be read at all, give up entirely.
412 If we did some searching errno has the error from the last attempt,
413 rather from FILENAME itself: recover the more accurate one. */
415 deps->file->last_mtime = NONEXISTENT_MTIME;
419 /* Success; clear errno. */
422 /* If we tried and failed to read the included file before but this
423 time we succeeded, reset the last mtime. */
424 if (deps->file->last_mtime == NONEXISTENT_MTIME)
425 deps->file->last_mtime = 0;
427 /* Avoid leaking the makefile to children. */
428 fd_noinherit (fileno (ebuf.fp));
430 /* Add this makefile to the list. */
431 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
434 /* Evaluate the makefile */
437 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
439 curfile = reading_file;
440 reading_file = &ebuf.floc;
442 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
444 reading_file = curfile;
448 free (ebuf.bufstart);
456 eval_buffer (char *buffer, const floc *flocp)
459 struct conditionals *saved;
460 struct conditionals new;
463 /* Evaluate the buffer */
465 ebuf.size = strlen (buffer);
466 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
471 else if (reading_file)
472 ebuf.floc = *reading_file;
475 ebuf.floc.filenm = NULL;
476 ebuf.floc.lineno = 1;
477 ebuf.floc.offset = 0;
480 curfile = reading_file;
481 reading_file = &ebuf.floc;
483 saved = install_conditionals (&new);
487 restore_conditionals (saved);
489 reading_file = curfile;
494 /* Check LINE to see if it's a variable assignment or undefine.
496 It might use one of the modifiers "export", "override", "private", or it
497 might be one of the conditional tokens like "ifdef", "include", etc.
499 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
502 Returns a pointer to the first non-modifier character, and sets VMOD
503 based on the modifiers found if any, plus V_ASSIGN is 1.
506 parse_var_assignment (const char *line, int targvar, struct vmodifiers *vmod)
509 memset (vmod, '\0', sizeof (*vmod));
511 /* Find the start of the next token. If there isn't one we're done. */
514 return (char *) line;
523 p2 = parse_variable_definition (p, &v);
525 /* If this is a variable assignment, we're done. */
529 /* It's not a variable; see if it's a modifier. */
530 p2 = end_of_token (p);
533 if (word1eq ("export"))
534 vmod->export_v = v_export;
535 else if (word1eq ("unexport"))
536 vmod->export_v = v_noexport;
537 else if (word1eq ("override"))
538 vmod->override_v = 1;
539 else if (word1eq ("private"))
541 else if (!targvar && word1eq ("define"))
543 /* We can't have modifiers after 'define' */
548 else if (!targvar && word1eq ("undefine"))
550 /* We can't have modifiers after 'undefine' */
551 vmod->undefine_v = 1;
556 /* Not a variable or modifier: this is not a variable assignment. */
557 return (char *) line;
559 /* It was a modifier. Try the next word. */
562 return (char *) line;
565 /* Found a variable assignment or undefine. */
571 /* Read file FILENAME as a makefile and add its contents to the data base.
573 SET_DEFAULT is true if we are allowed to set the default goal. */
576 eval (struct ebuffer *ebuf, int set_default)
579 size_t collapsed_length = 0;
580 size_t commands_len = 200;
582 size_t commands_idx = 0;
583 unsigned int cmds_started, tgts_started;
584 int ignoring = 0, in_ignored_define = 0;
585 int no_targets = 0; /* Set when reading a rule without targets. */
586 int also_make_targets = 0; /* Set when reading grouped targets. */
587 struct nameseq *filenames = 0;
591 char prefix = cmd_prefix;
592 const char *pattern = 0;
593 const char *pattern_percent;
597 #define record_waiting_files() \
600 if (filenames != 0) \
602 fi.lineno = tgts_started; \
604 record_files (filenames, also_make_targets, pattern, \
605 pattern_percent, depstr, \
606 cmds_started, commands, commands_idx, two_colon, \
613 also_make_targets = 0; \
617 cmds_started = tgts_started = 1;
619 fstart = &ebuf->floc;
620 fi.filenm = ebuf->floc.filenm;
622 /* Loop over lines in the file.
623 The strategy is to accumulate target names in FILENAMES, dependencies
624 in DEPS and commands in COMMANDS. These are used to define a rule
625 when the start of the next rule (or eof) is encountered.
627 When you see a "continue" in the loop below, that means we are moving on
628 to the next line. If you see record_waiting_files(), then the statement
629 we are parsing also finishes the previous rule. */
631 commands = xmalloc (200);
640 struct vmodifiers vmod;
642 /* At the top of this loop, we are starting a brand new line. */
643 /* Grab the next line to be evaluated */
644 ebuf->floc.lineno += nlines;
645 nlines = readline (ebuf);
647 /* If there is nothing left to eval, we're done. */
653 /* If this is the first line, check for a UTF-8 BOM and skip it. */
654 if (ebuf->floc.lineno == 1)
656 unsigned char *ul = (unsigned char *) line;
657 if (ul[0] == 0xEF && ul[1] == 0xBB && ul[2] == 0xBF)
662 if (ebuf->floc.filenm)
663 printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
666 printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
670 /* If this line is empty, skip it. */
674 linelen = strlen (line);
676 /* Check for a shell command line first.
677 If it is not one, we can stop treating cmd_prefix specially. */
678 if (line[0] == cmd_prefix)
681 /* Ignore the commands in a rule with no targets. */
684 /* If there is no preceding rule line, don't treat this line
685 as a command, even though it begins with a recipe prefix.
686 SunOS 4 make appears to behave this way. */
691 /* Yep, this is a shell command, and we don't care. */
694 if (commands_idx == 0)
695 cmds_started = ebuf->floc.lineno;
697 /* Append this command line to the line being accumulated.
698 Skip the initial command prefix character. */
699 if (linelen + commands_idx > commands_len)
701 commands_len = (linelen + commands_idx) * 2;
702 commands = xrealloc (commands, commands_len);
704 memcpy (&commands[commands_idx], line + 1, linelen - 1);
705 commands_idx += linelen - 1;
706 commands[commands_idx++] = '\n';
711 /* This line is not a shell command line. Don't worry about whitespace.
712 Get more space if we need it; we don't need to preserve the current
713 contents of the buffer. */
715 if (collapsed_length < linelen+1)
717 collapsed_length = linelen+1;
719 /* Don't need xrealloc: we don't need to preserve the content. */
720 collapsed = xmalloc (collapsed_length);
722 strcpy (collapsed, line);
723 /* Collapse continuation lines. */
724 collapse_continuations (collapsed);
725 remove_comments (collapsed);
727 /* Get rid if starting space (including formfeed, vtab, etc.) */
731 /* See if this is a variable assignment. We need to do this early, to
732 allow variables with names like 'ifdef', 'export', 'private', etc. */
733 p = parse_var_assignment (p, 0, &vmod);
737 enum variable_origin origin = vmod.override_v ? o_override : o_file;
739 /* If we're ignoring then we're done now. */
743 in_ignored_define = 1;
747 /* Variable assignment ends the previous rule. */
748 record_waiting_files ();
752 do_undefine (p, origin, ebuf);
755 else if (vmod.define_v)
756 v = do_define (p, origin, ebuf);
758 v = try_variable_definition (fstart, p, origin, 0);
762 if (vmod.export_v != v_default)
763 v->export = vmod.export_v;
767 /* This line has been dealt with. */
771 /* If this line is completely empty, ignore it. */
775 p2 = end_of_token (p);
779 /* If we're in an ignored define, skip this line (but maybe get out). */
780 if (in_ignored_define)
782 /* See if this is an endef line (plus optional comment). */
783 if (word1eq ("endef") && STOP_SET (*p2, MAP_COMMENT|MAP_NUL))
784 in_ignored_define = 0;
789 /* Check for conditional state changes. */
791 int i = conditional_line (p, wlen, fstart);
795 O (fatal, fstart, _("invalid syntax in conditional"));
802 /* Nothing to see here... move along. */
806 /* Manage the "export" keyword used outside of variable assignment
807 as well as "unexport". */
808 if (word1eq ("export") || word1eq ("unexport"))
810 int exporting = *p == 'u' ? 0 : 1;
812 /* Export/unexport ends the previous rule. */
813 record_waiting_files ();
815 /* (un)export by itself causes everything to be (un)exported. */
817 export_all_variables = exporting;
824 /* Expand the line so we can use indirect and constructed
825 variable names in an (un)export command. */
826 cp = ap = allocated_variable_expand (p2);
828 for (p = find_next_token (&cp, &l); p != 0;
829 p = find_next_token (&cp, &l))
831 struct variable *v = lookup_variable (p, l);
833 v = define_variable_global (p, l, "", o_file, 0, fstart);
834 v->export = exporting ? v_export : v_noexport;
842 /* Handle the special syntax for vpath. */
843 if (word1eq ("vpath"))
849 /* vpath ends the previous rule. */
850 record_waiting_files ();
852 cp = variable_expand (p2);
853 p = find_next_token (&cp, &l);
856 vpat = xstrndup (p, l);
857 p = find_next_token (&cp, &l);
858 /* No searchpath means remove all previous
859 selective VPATH's with the same pattern. */
862 /* No pattern means remove all previous selective VPATH's. */
864 construct_vpath_list (vpat, p);
870 /* Handle include and variants. */
871 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
873 /* We have found an 'include' line specifying a nested
874 makefile to be read at this point. */
875 struct conditionals *save;
876 struct conditionals new_conditionals;
877 struct nameseq *files;
878 /* "-include" (vs "include") says no error if the file does not
879 exist. "sinclude" is an alias for this from SGI. */
880 int noerror = (p[0] != 'i');
882 /* Include ends the previous rule. */
883 record_waiting_files ();
885 p = allocated_variable_expand (p2);
887 /* If no filenames, it's a no-op. */
894 /* Parse the list of file names. Don't expand archive references! */
896 files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
900 /* Save the state of conditionals and start
901 the included makefile with a clean slate. */
902 save = install_conditionals (&new_conditionals);
904 /* Record the rules that are waiting so they will determine
905 the default goal before those in the included makefile. */
906 record_waiting_files ();
908 /* Read each included makefile. */
911 struct nameseq *next = files->next;
912 unsigned short flags = (RM_INCLUDED | RM_NO_TILDE
913 | (noerror ? RM_DONTCARE : 0)
914 | (set_default ? 0 : RM_NO_DEFAULT_GOAL));
916 struct goaldep *d = eval_makefile (files->name, flags);
923 /* Restore conditional state. */
924 restore_conditionals (save);
929 /* Handle the load operations. */
930 if (word1eq ("load") || word1eq ("-load"))
932 /* A 'load' line specifies a dynamic object to load. */
933 struct nameseq *files;
934 int noerror = (p[0] == '-');
936 /* Load ends the previous rule. */
937 record_waiting_files ();
939 p = allocated_variable_expand (p2);
941 /* If no filenames, it's a no-op. */
948 /* Parse the list of file names.
949 Don't expand archive references or strip "./" */
951 files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
955 /* Load each file. */
958 struct nameseq *next = files->next;
959 const char *name = files->name;
960 struct goaldep *deps;
965 struct file file = {0};
967 /* Load the file. 0 means failure. */
968 r = load_file (&ebuf->floc, &file, noerror);
969 if (! r && ! noerror)
970 OS (fatal, &ebuf->floc, _("%s: failed to load"), name);
974 f = lookup_file (name);
976 f = enter_file (name);
983 /* Return of -1 means don't ever try to rebuild. */
987 /* Otherwise add it to the list to be rebuilt. */
988 deps = alloc_goaldep ();
989 deps->next = read_files;
990 deps->floc = ebuf->floc;
998 /* This line starts with a tab but was not caught above because there
999 was no preceding target, and the line might have been usable as a
1000 variable definition. But now we know it is definitely lossage. */
1001 if (line[0] == cmd_prefix)
1002 O (fatal, fstart, _("recipe commences before first target"));
1004 /* This line describes some target files. This is complicated by
1005 the existence of target-specific variables, because we can't
1006 expand the entire line until we know if we have one or not. So
1007 we expand the line word by word until we find the first ':',
1008 then check to see if it's a target-specific variable.
1010 In this algorithm, 'lb_next' will point to the beginning of the
1011 unexpanded parts of the input buffer, while 'p2' points to the
1012 parts of the expanded buffer we haven't searched yet. */
1015 enum make_word_type wtype;
1016 char *cmdleft, *semip = 0, *lb_next;
1019 const char *end, *beg; /* Helpers for whitespace stripping. */
1021 /* Record the previous rule. */
1023 record_waiting_files ();
1024 tgts_started = fstart->lineno;
1026 /* Search the line for an unquoted ; that is not after an
1028 cmdleft = find_map_unquote (line, MAP_SEMI|MAP_COMMENT|MAP_VARIABLE);
1029 if (cmdleft != 0 && *cmdleft == '#')
1031 /* We found a comment before a semicolon. */
1035 else if (cmdleft != 0)
1037 /* Found one. Cut the line short there before expanding it. */
1042 collapse_continuations (line);
1044 /* We can't expand the entire line, since if it's a per-target
1045 variable we don't want to expand it. So, walk from the
1046 beginning, expanding as we go, and looking for "interesting"
1047 chars. The first word is always expandable. */
1048 wtype = get_next_mword (line, &lb_next, &wlen);
1053 O (fatal, fstart, _("missing rule before recipe"));
1054 /* This line contained something but turned out to be nothing
1055 but whitespace (a comment?). */
1062 /* We accept and ignore rules without targets for
1063 compatibility with SunOS 4 make. */
1071 p2 = variable_expand_string (NULL, lb_next, wlen);
1078 /* Look for a semicolon in the expanded line. */
1079 cmdleft = find_char_unquote (p2, ';');
1083 size_t p2_off = p2 - variable_buffer;
1084 size_t cmd_off = cmdleft - variable_buffer;
1085 char *pend = p2 + strlen (p2);
1087 /* Append any remnants of lb, then cut the line short
1088 at the semicolon. */
1091 /* One school of thought says that you shouldn't expand
1092 here, but merely copy, since now you're beyond a ";"
1093 and into a command script. However, the old parser
1094 expanded the whole line, so we continue that for
1095 backwards-compatibility. Also, it wouldn't be
1096 entirely consistent, since we do an unconditional
1097 expand below once we know we don't have a
1098 target-specific variable. */
1099 variable_expand_string (pend, lb_next, SIZE_MAX);
1100 lb_next += strlen (lb_next);
1101 p2 = variable_buffer + p2_off;
1102 cmdleft = variable_buffer + cmd_off + 1;
1106 colonp = find_char_unquote (p2, ':');
1108 #ifdef HAVE_DOS_PATHS
1110 /* The drive spec brain-damage strikes again...
1111 Note that the only separators of targets in this context are
1112 whitespace and a left paren. If others are possible, add them
1113 to the string in the call to strchr. */
1114 while (colonp && ISDIRSEP (colonp[1]) &&
1115 isalpha ((unsigned char) colonp[-1]) &&
1116 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1117 colonp = find_char_unquote (colonp + 1, ':');
1122 /* If the previous character is '&', back up before '&:' */
1123 if (colonp > p2 && colonp[-1] == '&')
1129 wtype = get_next_mword (lb_next, &lb_next, &wlen);
1135 p2 = variable_expand_string (p2, lb_next, wlen);
1136 /* We don't need to worry about cmdleft here, because if it was
1137 found in the variable_buffer the entire buffer has already
1138 been expanded... we'll never get here. */
1141 p2 = next_token (variable_buffer);
1143 /* If the word we're looking at is EOL, see if there's _anything_
1144 on the line. If not, a variable expanded to nothing, so ignore
1145 it. If so, we can't parse this line so punt. */
1151 /* There's no need to be ivory-tower about this: check for
1152 one of the most common bugs found in makefiles... */
1153 if (cmd_prefix == '\t' && strneq (line, " ", 8))
1154 O (fatal, fstart, _("missing separator (did you mean TAB instead of 8 spaces?)"));
1156 O (fatal, fstart, _("missing separator"));
1160 char save = *colonp;
1162 /* If we have &:, it specifies that the targets are understood to be
1163 updated/created together by a single invocation of the recipe. */
1165 also_make_targets = 1;
1167 /* Make the colon the end-of-string so we know where to stop
1168 looking for targets. Start there again once we're done. */
1170 filenames = PARSE_SIMPLE_SEQ (&p2, struct nameseq);
1172 p2 = colonp + (save == '&');
1177 /* We accept and ignore rules without targets for
1178 compatibility with SunOS 4 make. */
1182 /* This should never be possible; we handled it above. */
1183 assert (*p2 != '\0');
1186 /* Is this a one-colon or two-colon entry? */
1187 two_colon = *p2 == ':';
1191 /* Test to see if it's a target-specific variable. Copy the rest
1192 of the buffer over, possibly temporarily (we'll expand it later
1193 if it's not a target-specific variable). PLEN saves the length
1194 of the unparsed section of p2, for later. */
1195 if (*lb_next != '\0')
1197 size_t l = p2 - variable_buffer;
1199 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1200 p2 = variable_buffer + l;
1203 p2 = parse_var_assignment (p2, 1, &vmod);
1206 /* If there was a semicolon found, add it back, plus anything
1210 size_t l = p2 - variable_buffer;
1212 collapse_continuations (semip);
1213 variable_buffer_output (p2 + strlen (p2),
1214 semip, strlen (semip)+1);
1215 p2 = variable_buffer + l;
1217 record_target_var (filenames, p2,
1218 vmod.override_v ? o_override : o_file,
1224 /* This is a normal target, _not_ a target-specific variable.
1225 Unquote any = in the dependency list. */
1226 find_char_unquote (lb_next, '=');
1228 /* Remember the command prefix for this target. */
1229 prefix = cmd_prefix;
1231 /* We have some targets, so don't ignore the following commands. */
1234 /* Expand the dependencies, etc. */
1235 if (*lb_next != '\0')
1237 size_t l = p2 - variable_buffer;
1238 variable_expand_string (p2 + plen, lb_next, SIZE_MAX);
1239 p2 = variable_buffer + l;
1241 /* Look for a semicolon in the expanded line. */
1244 cmdleft = find_char_unquote (p2, ';');
1246 *(cmdleft++) = '\0';
1250 /* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
1251 p = strchr (p2, ':');
1252 while (p != 0 && p[-1] == '\\')
1256 while (*q-- == '\\')
1257 backslash = !backslash;
1259 p = strchr (p + 1, ':');
1264 /* Here, the situation is quite complicated. Let's have a look
1265 at a couple of targets:
1273 The rule is that it's only a target, if there are TWO :'s
1274 OR a space around the :.
1276 if (p && !(ISSPACE (p[1]) || !p[1] || ISSPACE (p[-1])))
1279 #ifdef HAVE_DOS_PATHS
1284 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1285 if (p != 0 && ISDIRSEP (p[1]) && isalpha ((unsigned char)p[-1]) &&
1286 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1287 p = strchr (p + 1, ':');
1290 } while (check_again);
1295 struct nameseq *target;
1296 target = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_COLON, NULL,
1300 O (fatal, fstart, _("missing target pattern"));
1301 else if (target->next != 0)
1302 O (fatal, fstart, _("multiple target patterns"));
1303 pattern_percent = find_percent_cached (&target->name);
1304 pattern = target->name;
1305 if (pattern_percent == 0)
1306 O (fatal, fstart, _("target pattern contains no '%%'"));
1312 /* Strip leading and trailing whitespaces. */
1314 end = beg + strlen (beg) - 1;
1315 strip_whitespace (&beg, &end);
1317 /* Put all the prerequisites here; they'll be parsed later. */
1318 if (beg <= end && *beg != '\0')
1319 depstr = xstrndup (beg, end - beg + 1);
1326 /* Semicolon means rest of line is a command. */
1327 size_t l = strlen (cmdleft);
1329 cmds_started = fstart->lineno;
1331 /* Add this command line to the buffer. */
1332 if (l + 2 > commands_len)
1334 commands_len = (l + 2) * 2;
1335 commands = xrealloc (commands, commands_len);
1337 memcpy (commands, cmdleft, l);
1339 commands[commands_idx++] = '\n';
1342 check_specials (filenames, set_default);
1348 if (conditionals->if_cmds)
1349 O (fatal, fstart, _("missing 'endif'"));
1351 /* At eof, record the last rule. */
1352 record_waiting_files ();
1359 /* Remove comments from LINE.
1360 This will also remove backslashes that escape things.
1361 It ignores comment characters that appear inside variable references. */
1364 remove_comments (char *line)
1368 comment = find_map_unquote (line, MAP_COMMENT|MAP_VARIABLE);
1371 /* Cut off the line at the #. */
1375 /* Execute a 'undefine' directive.
1376 The undefine line has already been read, and NAME is the name of
1377 the variable to be undefined. */
1380 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1384 /* Expand the variable name and find the beginning (NAME) and end. */
1385 var = allocated_variable_expand (name);
1386 name = next_token (var);
1388 O (fatal, &ebuf->floc, _("empty variable name"));
1389 p = name + strlen (name) - 1;
1390 while (p > name && ISBLANK (*p))
1394 undefine_variable_global (name, p - name + 1, origin);
1398 /* Execute a 'define' directive.
1399 The first line has already been read, and NAME is the name of
1400 the variable to be defined. The following lines remain to be read. */
1402 static struct variable *
1403 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1406 struct variable var;
1409 size_t length = 100;
1410 char *definition = xmalloc (length);
1414 defstart = ebuf->floc;
1416 p = parse_variable_definition (name, &var);
1418 /* No assignment token, so assume recursive. */
1419 var.flavor = f_recursive;
1422 if (var.value[0] != '\0')
1423 O (error, &defstart, _("extraneous text after 'define' directive"));
1425 /* Chop the string before the assignment token to get the name. */
1426 var.name[var.length] = '\0';
1429 /* Expand the variable name and find the beginning (NAME) and end. */
1430 n = allocated_variable_expand (name);
1431 name = next_token (n);
1432 if (name[0] == '\0')
1433 O (fatal, &defstart, _("empty variable name"));
1434 p = name + strlen (name) - 1;
1435 while (p > name && ISBLANK (*p))
1439 /* Now read the value of the variable. */
1444 long nlines = readline (ebuf);
1446 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1448 O (fatal, &defstart, _("missing 'endef', unterminated 'define'"));
1450 ebuf->floc.lineno += nlines;
1451 line = ebuf->buffer;
1453 collapse_continuations (line);
1455 /* If the line doesn't begin with a tab, test to see if it introduces
1456 another define, or ends one. Stop if we find an 'endef' */
1457 if (line[0] != cmd_prefix)
1459 p = next_token (line);
1462 /* If this is another 'define', increment the level count. */
1463 if ((len == 6 || (len > 6 && ISBLANK (p[6])))
1464 && strneq (p, "define", 6))
1467 /* If this is an 'endef', decrement the count. If it's now 0,
1468 we've found the last one. */
1469 else if ((len == 5 || (len > 5 && ISBLANK (p[5])))
1470 && strneq (p, "endef", 5))
1473 remove_comments (p);
1474 if (*(next_token (p)) != '\0')
1475 O (error, &ebuf->floc,
1476 _("extraneous text after 'endef' directive"));
1483 /* Add this line to the variable definition. */
1484 len = strlen (line);
1485 if (idx + len + 1 > length)
1487 length = (idx + len) * 2;
1488 definition = xrealloc (definition, length + 1);
1491 memcpy (&definition[idx], line, len);
1493 /* Separate lines with a newline. */
1494 definition[idx++] = '\n';
1497 /* We've got what we need; define the variable. */
1499 definition[0] = '\0';
1501 definition[idx - 1] = '\0';
1503 v = do_variable_definition (&defstart, name,
1504 definition, origin, var.flavor, 0);
1510 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1511 "ifneq", "else" and "endif".
1512 LINE is the input line, with the command as its first word.
1514 FILENAME and LINENO are the filename and line number in the
1515 current makefile. They are used for error messages.
1517 Value is -2 if the line is not a conditional at all,
1518 -1 if the line is an invalid conditional,
1519 0 if following text should be interpreted,
1520 1 if following text should be ignored. */
1523 conditional_line (char *line, size_t len, const floc *flocp)
1525 const char *cmdname;
1526 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1530 /* Compare a word, both length and contents. */
1531 #define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
1532 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1534 /* Make sure this line is a conditional. */
1535 chkword ("ifdef", c_ifdef)
1536 else chkword ("ifndef", c_ifndef)
1537 else chkword ("ifeq", c_ifeq)
1538 else chkword ("ifneq", c_ifneq)
1539 else chkword ("else", c_else)
1540 else chkword ("endif", c_endif)
1544 /* Found one: skip past it and any whitespace after it. */
1548 #define EXTRATEXT() OS (error, flocp, _("extraneous text after '%s' directive"), cmdname)
1549 #define EXTRACMD() OS (fatal, flocp, _("extraneous '%s'"), cmdname)
1551 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1552 if (cmdtype == c_endif)
1557 if (!conditionals->if_cmds)
1560 --conditionals->if_cmds;
1565 /* An 'else' statement can either be simple, or it can have another
1566 conditional after it. */
1567 if (cmdtype == c_else)
1571 if (!conditionals->if_cmds)
1574 o = conditionals->if_cmds - 1;
1576 if (conditionals->seen_else[o])
1577 O (fatal, flocp, _("only one 'else' per conditional"));
1579 /* Change the state of ignorance. */
1580 switch (conditionals->ignoring[o])
1583 /* We've just been interpreting. Never do it again. */
1584 conditionals->ignoring[o] = 2;
1587 /* We've never interpreted yet. Maybe this time! */
1588 conditionals->ignoring[o] = 0;
1592 /* It's a simple 'else'. */
1595 conditionals->seen_else[o] = 1;
1599 /* The 'else' has extra text. That text must be another conditional
1600 and cannot be an 'else' or 'endif'. */
1602 /* Find the length of the next word. */
1603 for (p = line+1; ! STOP_SET (*p, MAP_SPACE|MAP_NUL); ++p)
1607 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1608 if (word1eq ("else") || word1eq ("endif")
1609 || conditional_line (line, len, flocp) < 0)
1613 /* conditional_line() created a new level of conditional.
1614 Raise it back to this level. */
1615 if (conditionals->ignoring[o] < 2)
1616 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1617 --conditionals->if_cmds;
1623 if (conditionals->allocated == 0)
1625 conditionals->allocated = 5;
1626 conditionals->ignoring = xmalloc (conditionals->allocated);
1627 conditionals->seen_else = xmalloc (conditionals->allocated);
1630 o = conditionals->if_cmds++;
1631 if (conditionals->if_cmds > conditionals->allocated)
1633 conditionals->allocated += 5;
1634 conditionals->ignoring = xrealloc (conditionals->ignoring,
1635 conditionals->allocated);
1636 conditionals->seen_else = xrealloc (conditionals->seen_else,
1637 conditionals->allocated);
1640 /* Record that we have seen an 'if...' but no 'else' so far. */
1641 conditionals->seen_else[o] = 0;
1643 /* Search through the stack to see if we're already ignoring. */
1644 for (i = 0; i < o; ++i)
1645 if (conditionals->ignoring[i])
1647 /* We are already ignoring, so just push a level to match the next
1648 "else" or "endif", and keep ignoring. We don't want to expand
1649 variables in the condition. */
1650 conditionals->ignoring[o] = 1;
1654 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1661 /* Expand the thing we're looking up, so we can use indirect and
1662 constructed variable names. */
1663 var = allocated_variable_expand (line);
1665 /* Make sure there's only one variable name to test. */
1666 p = end_of_token (var);
1673 v = lookup_variable (var, l);
1675 conditionals->ignoring[o] =
1676 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1682 /* "ifeq" or "ifneq". */
1685 char termin = *line == '(' ? ',' : *line;
1687 if (termin != ',' && termin != '"' && termin != '\'')
1691 /* Find the end of the first string. */
1695 for (; *line != '\0'; ++line)
1698 else if (*line == ')')
1700 else if (*line == ',' && count <= 0)
1704 while (*line != '\0' && *line != termin)
1712 /* Strip blanks after the first string. */
1714 while (ISBLANK (p[-1]))
1721 s2 = variable_expand (s1);
1722 /* We must allocate a new copy of the expanded string because
1723 variable_expand re-uses the same buffer. */
1725 s1 = alloca (l + 1);
1726 memcpy (s1, s2, l + 1);
1729 /* Find the start of the second string. */
1732 termin = termin == ',' ? ')' : *line;
1733 if (termin != ')' && termin != '"' && termin != '\'')
1736 /* Find the end of the second string. */
1740 s2 = next_token (line);
1741 for (line = s2; *line != '\0'; ++line)
1745 else if (*line == ')')
1758 while (*line != '\0' && *line != termin)
1770 s2 = variable_expand (s2);
1771 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1775 /* Search through the stack to see if we're ignoring. */
1776 for (i = 0; i < conditionals->if_cmds; ++i)
1777 if (conditionals->ignoring[i])
1783 /* Record target-specific variable values for files FILENAMES.
1784 TWO_COLON is nonzero if a double colon was used.
1786 The links of FILENAMES are freed, and so are any names in it
1787 that are not incorporated into other data structures.
1789 If the target is a pattern, add the variable to the pattern-specific
1790 variable value list. */
1793 record_target_var (struct nameseq *filenames, char *defn,
1794 enum variable_origin origin, struct vmodifiers *vmod,
1797 struct nameseq *nextf;
1798 struct variable_set_list *global;
1800 global = current_variable_set_list;
1802 /* If the variable is an append version, store that but treat it as a
1803 normal recursive variable. */
1805 for (; filenames != 0; filenames = nextf)
1808 const char *name = filenames->name;
1809 const char *percent;
1810 struct pattern_var *p;
1812 nextf = filenames->next;
1813 free_ns (filenames);
1815 /* If it's a pattern target, then add it to the pattern-specific
1817 percent = find_percent_cached (&name);
1820 /* Get a reference for this pattern-specific variable struct. */
1821 p = create_pattern_var (name, percent);
1822 p->variable.fileinfo = *flocp;
1823 /* I don't think this can fail since we already determined it was a
1824 variable definition. */
1825 v = assign_variable_definition (&p->variable, defn);
1829 if (v->flavor == f_simple)
1830 v->value = allocated_variable_expand (v->value);
1832 v->value = xstrdup (v->value);
1838 /* Get a file reference for this file, and initialize it.
1839 We don't want to just call enter_file() because that allocates a
1840 new entry if the file is a double-colon, which we don't want in
1842 f = lookup_file (name);
1844 f = enter_file (strcache_add (name));
1845 else if (f->double_colon)
1846 f = f->double_colon;
1848 initialize_file_variables (f, 1);
1850 current_variable_set_list = f->variables;
1851 v = try_variable_definition (flocp, defn, origin, 1);
1853 O (fatal, flocp, _("Malformed target-specific variable definition"));
1854 current_variable_set_list = global;
1857 /* Set up the variable to be *-specific. */
1859 v->private_var = vmod->private_v;
1860 if (vmod->export_v != v_default)
1861 v->export = vmod->export_v;
1863 /* If it's not an override, check to see if there was a command-line
1864 setting. If so, reset the value. */
1865 if (v->origin != o_override)
1867 struct variable *gv;
1868 size_t len = strlen (v->name);
1870 gv = lookup_variable (v->name, len);
1872 && (gv->origin == o_env_override || gv->origin == o_command))
1875 v->value = xstrdup (gv->value);
1876 v->origin = gv->origin;
1877 v->recursive = gv->recursive;
1885 /* Check for special targets. We used to do this in record_files() but that's
1886 too late: by the time we get there we'll have already parsed the next line
1887 and it have been mis-parsed because these special targets haven't been
1891 check_specials (struct nameseq *files, int set_default)
1895 for (t = files; t != NULL; t = t->next)
1897 const char* nm = t->name;
1899 if (!posix_pedantic && streq (nm, ".POSIX"))
1902 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1903 /* These default values are based on IEEE Std 1003.1-2008.
1904 It requires '-O 1' for [CF]FLAGS, but GCC doesn't allow
1905 space between -O and the number so omit it here. */
1906 define_variable_cname ("CC", "c99", o_default, 0);
1907 define_variable_cname ("CFLAGS", "-O1", o_default, 0);
1908 define_variable_cname ("FC", "fort77", o_default, 0);
1909 define_variable_cname ("FFLAGS", "-O1", o_default, 0);
1910 define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
1911 define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
1915 if (!second_expansion && streq (nm, ".SECONDEXPANSION"))
1917 second_expansion = 1;
1921 #if !defined (__MSDOS__) && !defined (__EMX__)
1922 if (!one_shell && streq (nm, ".ONESHELL"))
1929 /* Determine if this target should be made default. */
1931 if (set_default && default_goal_var->value[0] == '\0')
1936 /* We have nothing to do if this is an implicit rule. */
1937 if (strchr (nm, '%') != 0)
1940 /* See if this target's name does not start with a '.',
1941 unless it contains a slash. */
1942 if (*nm == '.' && strchr (nm, '/') == 0
1943 #ifdef HAVE_DOS_PATHS
1944 && strchr (nm, '\\') == 0
1949 /* If this file is a suffix, it can't be the default goal file. */
1950 for (d = suffix_file->deps; d != 0; d = d->next)
1953 if (*dep_name (d) != '.' && streq (nm, dep_name (d)))
1958 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1960 size_t l = strlen (dep_name (d2));
1961 if (!strneq (nm, dep_name (d2), l))
1963 if (streq (nm + l, dep_name (d)))
1975 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1981 /* Check for special targets. We used to do this in record_files() but that's
1982 too late: by the time we get there we'll have already parsed the next line
1983 and it have been mis-parsed because these special targets haven't been
1987 check_special_file (struct file *file, const floc *flocp)
1989 if (streq (file->name, ".WAIT"))
1991 static unsigned int wpre = 0, wcmd = 0;
1993 if (!wpre && file->deps)
1995 O (error, flocp, _(".WAIT should not have prerequisites"));
1999 if (!wcmd && file->cmds)
2001 O (error, flocp, _(".WAIT should not have commands"));
2009 /* Record a description line for files FILENAMES,
2010 with dependencies DEPS, commands to execute described
2011 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
2012 TWO_COLON is nonzero if a double colon was used.
2013 If not nil, PATTERN is the '%' pattern to make this
2014 a static pattern rule, and PATTERN_PERCENT is a pointer
2015 to the '%' within it.
2017 The links of FILENAMES are freed, and so are any names in it
2018 that are not incorporated into other data structures. */
2021 record_files (struct nameseq *filenames, int are_also_makes,
2022 const char *pattern,
2023 const char *pattern_percent, char *depstr,
2024 unsigned int cmds_started, char *commands,
2025 size_t commands_idx, int two_colon,
2026 char prefix, const floc *flocp)
2028 struct commands *cmds;
2030 struct dep *also_make = NULL;
2031 const char *implicit_percent;
2034 /* If we've already snapped deps, that means we're in an eval being
2035 resolved after the makefiles have been read in. We can't add more rules
2036 at this time, since they won't get snapped and we'll get core dumps.
2037 See Savannah bug # 12124. */
2039 O (fatal, flocp, _("prerequisites cannot be defined in recipes"));
2041 /* Determine if this is a pattern rule or not. */
2042 name = filenames->name;
2043 implicit_percent = find_percent_cached (&name);
2045 /* If there's a recipe, set up a struct for it. */
2046 if (commands_idx > 0)
2048 cmds = xmalloc (sizeof (struct commands));
2049 cmds->fileinfo.filenm = flocp->filenm;
2050 cmds->fileinfo.lineno = cmds_started;
2051 cmds->fileinfo.offset = 0;
2052 cmds->commands = xstrndup (commands, commands_idx);
2053 cmds->command_lines = 0;
2054 cmds->recipe_prefix = prefix;
2056 else if (are_also_makes)
2057 O (fatal, flocp, _("grouped targets must provide a recipe"));
2061 /* If there's a prereq string then parse it--unless it's eligible for 2nd
2062 expansion: if so, snap_deps() will do it. */
2067 depstr = unescape_char (depstr, ':');
2068 if (second_expansion && strchr (depstr, '$'))
2070 deps = alloc_dep ();
2071 deps->name = depstr;
2072 deps->need_2nd_expansion = 1;
2073 deps->staticpattern = pattern != 0;
2077 deps = split_prereqs (depstr);
2080 /* We'll enter static pattern prereqs later when we have the stem.
2081 We don't want to enter pattern rules at all so that we don't
2082 think that they ought to exist (make manual "Implicit Rule Search
2083 Algorithm", item 5c). */
2084 if (! pattern && ! implicit_percent)
2085 deps = enter_prereqs (deps, NULL);
2089 /* For implicit rules, _all_ the targets must have a pattern. That means we
2090 can test the first one to see if we're working with an implicit rule; if
2091 so we handle it specially. */
2093 if (implicit_percent)
2095 struct nameseq *nextf;
2096 const char **targets, **target_pats;
2100 O (fatal, flocp, _("mixed implicit and static pattern rules"));
2102 /* Count the targets to create an array of target names.
2103 We already have the first one. */
2104 nextf = filenames->next;
2105 free_ns (filenames);
2108 for (c = 1; nextf; ++c, nextf = nextf->next)
2110 targets = xmalloc (c * sizeof (const char *));
2111 target_pats = xmalloc (c * sizeof (const char *));
2114 target_pats[0] = implicit_percent;
2119 name = filenames->name;
2120 implicit_percent = find_percent_cached (&name);
2122 if (implicit_percent == 0)
2123 O (fatal, flocp, _("mixed implicit and normal rules"));
2126 target_pats[c] = implicit_percent;
2129 nextf = filenames->next;
2130 free_ns (filenames);
2134 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
2140 /* Walk through each target and create it in the database.
2141 We already set up the first target, above. */
2144 struct nameseq *nextf = filenames->next;
2146 struct dep *this = 0;
2148 free_ns (filenames);
2150 /* If this is a static pattern rule:
2151 'targets: target%pattern: prereq%pattern; recipe',
2152 make sure the pattern matches this target name. */
2153 if (pattern && !pattern_matches (pattern, pattern_percent, name))
2155 _("target '%s' doesn't match the target pattern"), name);
2157 /* If there are multiple targets, copy the chain DEPS for all but the
2158 last one. It is not safe for the same deps to go in more than one
2159 place in the database. */
2160 this = nextf != 0 ? copy_dep_chain (deps) : deps;
2162 /* Find or create an entry in the file database for this target. */
2165 /* Single-colon. Combine this rule with the file's existing record,
2167 f = enter_file (strcache_add (name));
2168 if (f->double_colon)
2170 _("target file '%s' has both : and :: entries"), f->name);
2172 /* If CMDS == F->CMDS, this target was listed in this rule
2173 more than once. Just give a warning since this is harmless. */
2174 if (cmds != 0 && cmds == f->cmds)
2176 _("target '%s' given more than once in the same rule"),
2179 /* Check for two single-colon entries both with commands.
2180 Check is_target so that we don't lose on files such as .c.o
2181 whose commands were preinitialized. */
2182 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2184 size_t l = strlen (f->name);
2185 error (&cmds->fileinfo, l,
2186 _("warning: overriding recipe for target '%s'"),
2188 error (&f->cmds->fileinfo, l,
2189 _("warning: ignoring old recipe for target '%s'"),
2193 /* Defining .DEFAULT with no deps or cmds clears it. */
2194 if (f == default_file && this == 0 && cmds == 0)
2199 /* Defining .SUFFIXES with no dependencies clears out the list of
2201 if (f == suffix_file && this == 0)
2203 free_dep_chain (f->deps);
2206 /* This file is explicitly mentioned as a target. There is no need
2207 to set is_explicit in the case of double colon below, because an
2208 implicit double colon rule only applies when the prerequisite
2209 exists. A prerequisite which exists is not intermediate anyway. */
2214 /* Double-colon. Make a new record even if there already is one. */
2215 f = lookup_file (name);
2217 /* Check for both : and :: rules. Check is_target so we don't lose
2218 on default suffix rules or makefiles. */
2219 if (f != 0 && f->is_target && !f->double_colon)
2221 _("target file '%s' has both : and :: entries"), f->name);
2223 f = enter_file (strcache_add (name));
2224 /* If there was an existing entry and it was a double-colon entry,
2225 enter_file will have returned a new one, making it the prev
2226 pointer of the old one, and setting its double_colon pointer to
2228 if (f->double_colon == 0)
2229 /* This is the first entry for this name, so we must set its
2230 double_colon pointer to itself. */
2231 f->double_colon = f;
2238 struct dep *also = alloc_dep();
2239 also->name = f->name;
2241 also->next = also_make;
2247 /* If this is a static pattern rule, set the stem to the part of its
2248 name that matched the '%' in the pattern, so you can use $* in the
2249 commands. If we didn't do it before, enter the prereqs now. */
2252 static const char *percent = "%";
2253 char *o = patsubst_expand_pat (variable_buffer, name, pattern,
2254 percent, pattern_percent+1, percent+1);
2255 f->stem = strcache_add_len (variable_buffer, o - variable_buffer);
2258 if (! this->need_2nd_expansion)
2259 this = enter_prereqs (this, f->stem);
2261 this->stem = f->stem;
2265 /* Add the dependencies to this file entry. */
2268 /* Add the file's old deps and the new ones in THIS together. */
2273 struct dep *d = this;
2275 /* If this rule has commands, put these deps first. */
2276 while (d->next != 0)
2284 struct dep *d = f->deps;
2286 /* A rule without commands: put its prereqs at the end. */
2287 while (d->next != 0)
2296 check_special_file (f, flocp);
2298 /* All done! Set up for the next one. */
2304 /* Reduce escaped percents. If there are any unescaped it's an error */
2305 name = filenames->name;
2306 if (find_percent_cached (&name))
2308 _("*** mixed implicit and normal rules: deprecated syntax"));
2311 /* If there are also-makes, then populate a copy of the also-make list into
2312 each one. For the last file, we take our original also_make list instead
2313 wastefully copying it one more time and freeing it. */
2317 for (i = also_make; i != NULL; i = i->next)
2319 struct file *f = i->file;
2320 struct dep *cpy = i->next ? copy_dep_chain (also_make) : also_make;
2324 OS (error, &cmds->fileinfo,
2325 _("warning: overriding group membership for target '%s'"),
2327 free_dep_chain (f->also_make);
2335 /* Search STRING for an unquoted STOPMAP.
2336 Backslashes quote elements from STOPMAP and backslash.
2337 Quoting backslashes are removed from STRING by compacting it into itself.
2338 Returns a pointer to the first unquoted STOPCHAR if there is one, or nil if
2341 If MAP_VARIABLE is set, then the complete contents of variable references
2342 are skipped, even if the contain STOPMAP characters. */
2345 find_map_unquote (char *string, int stopmap)
2347 size_t string_len = 0;
2350 /* Always stop on NUL. */
2355 while (! STOP_SET (*p, stopmap))
2361 /* If we stopped due to a variable reference, skip over its contents. */
2364 char openparen = p[1];
2366 /* Check if '$' is the last character in the string. */
2367 if (openparen == '\0')
2372 /* Skip the contents of a non-quoted, multi-char variable ref. */
2373 if (openparen == '(' || openparen == '{')
2375 unsigned int pcount = 1;
2376 char closeparen = (openparen == '(' ? ')' : '}');
2380 if (*p == openparen)
2382 else if (*p == closeparen)
2392 /* Skipped the variable reference: look for STOPCHARS again. */
2396 if (p > string && p[-1] == '\\')
2398 /* Search for more backslashes. */
2400 while (&p[i] >= string && p[i] == '\\')
2403 /* Only compute the length if really needed. */
2404 if (string_len == 0)
2405 string_len = strlen (string);
2406 /* The number of backslashes is now -I.
2407 Copy P over itself to swallow half of them. */
2409 /* Avoid arithmetic conversion of negative values to unsigned. */
2411 memmove (&p[i], &p[i/2], (string_len - (p - string)) + hi + 1);
2415 /* All the backslashes quoted each other; the STOPCHAR was
2419 /* The STOPCHAR was quoted by a backslash. Look for another. */
2422 /* No backslash in sight. */
2426 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2431 find_char_unquote (char *string, int stop)
2433 size_t string_len = 0;
2438 p = strchr(p, stop);
2443 if (p > string && p[-1] == '\\')
2445 /* Search for more backslashes. */
2447 while (&p[i] >= string && p[i] == '\\')
2450 /* Only compute the length if really needed. */
2451 if (string_len == 0)
2452 string_len = strlen (string);
2453 /* The number of backslashes is now -I.
2454 Copy P over itself to swallow half of them. */
2456 /* Avoid arithmetic conversion of negative values to unsigned. */
2458 memmove (&p[i], &p[i/2], (string_len - (p - string)) + hi + 1);
2462 /* All the backslashes quoted each other; the STOPCHAR was
2466 /* The STOPCHAR was quoted by a backslash. Look for another. */
2469 /* No backslash in sight. */
2474 /* Unescape a character in a string. The string is compressed onto itself. */
2477 unescape_char (char *string, int c)
2489 /* We found a backslash. See if it's escaping our character. */
2494 if (*e != c || l%2 == 0)
2496 /* It's not; just take it all without unescaping. */
2500 /* If we hit the end of the string, we're done. */
2506 /* It is, and there's >1 backslash. Take half of them. */
2522 /* Search PATTERN for an unquoted % and handle quoting. */
2525 find_percent (char *pattern)
2527 return find_char_unquote (pattern, '%');
2530 /* Return a pointer to the first unescaped %, or NULL if there isn't one.
2531 Compress any escape chars up to the first unescaped %, but not afterward.
2532 This version is used with strings in the string cache: if there's a need to
2533 modify the string to handle escape chars a new version will be added to the
2534 string cache and *STRING will be set to that. */
2537 find_percent_cached (const char **string)
2539 const char *p = strchr (*string, '%');
2543 /* If there is no % or there is but it's not escaped, reuse this string. */
2544 if (!p || p == *string || p[-1] != '\\')
2547 /* We must create a new cached string with backslashes compressed. */
2548 slen = strlen (*string);
2549 new = alloca (slen + 1);
2550 memcpy (new, *string, slen + 1);
2551 np = new + (p - *string);
2555 /* Remember where the percent is. */
2559 /* This % is preceded by a backslash; search for more backslashes. */
2560 while (&np[i] >= new && np[i] == '\\')
2564 /* The number of backslashes is -I. Copy the string over itself to
2565 swallow half of them. */
2567 /* Avoid arithmetic conversion of negative values to unsigned. */
2569 memmove (&pp[i], &pp[i/2], (slen - (pp - new)) + hi + 1);
2572 /* Update SLEN and set NP to point after the %. */
2576 /* If all backslashes quoted each other then % was unquoted. */
2580 np = strchr (np, '%');
2582 while (np && np[-1] == '\\');
2584 /* Add the new string to the strcache. */
2585 *string = strcache_add (new);
2587 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2588 return np ? *string + (np - new) : NULL;
2591 /* Find the next line of text in an eval buffer, combining continuation lines
2593 Return the number of actual lines read (> 1 if continuation lines).
2594 Returns -1 if there's nothing left in the buffer.
2596 After this function, ebuf->buffer points to the first character of the
2600 /* Read a line of text from a STRING.
2601 Since we aren't really reading from a file, don't bother with linenumbers.
2605 readstring (struct ebuffer *ebuf)
2609 /* If there is nothing left in this buffer, return 0. */
2610 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2613 /* Set up a new starting point for the buffer, and find the end of the
2614 next logical line (taking into account backslash/newline pairs). */
2616 eol = ebuf->buffer = ebuf->bufnext;
2621 const char *bol = eol;
2624 /* Find the next newline. At EOS, stop. */
2625 p = eol = strchr (eol , '\n');
2628 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2632 /* Found a newline; if it's escaped continue; else we're done. */
2633 while (p > bol && *(--p) == '\\')
2634 backslash = !backslash;
2640 /* Overwrite the newline char. */
2642 ebuf->bufnext = eol+1;
2648 readline (struct ebuffer *ebuf)
2655 /* The behaviors between string and stream buffers are different enough to
2656 warrant different functions. Do the Right Thing. */
2659 return readstring (ebuf);
2661 /* When reading from a file, we always start over at the beginning of the
2662 buffer for each new line. */
2664 p = start = ebuf->bufstart;
2665 end = p + ebuf->size;
2668 while (fgets (p, (int) (end - p), ebuf->fp) != 0)
2677 /* This only happens when the first thing on the line is a '\0'.
2678 It is a pretty hopeless case, but (wonder of wonders) Athena
2679 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2680 There is nothing really to be done; we synthesize a newline so
2681 the following line doesn't appear to be part of this line. */
2682 O (error, &ebuf->floc,
2683 _("warning: NUL character seen; rest of line ignored"));
2688 /* Jump past the text we just read. */
2691 /* If the last char isn't a newline, the whole line didn't fit into the
2692 buffer. Get some more buffer and try again. */
2696 /* We got a newline, so add one to the count of lines. */
2699 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2700 /* Check to see if the line was really ended with CRLF; if so ignore
2702 if ((p - start) > 1 && p[-2] == '\r')
2705 memmove (p-1, p, strlen (p) + 1);
2710 for (p2 = p - 2; p2 >= start; --p2)
2714 backslash = !backslash;
2723 /* It was a backslash/newline combo. If we have more space, read
2728 /* We need more space at the end of our buffer, so realloc it.
2729 Make sure to preserve the current offset of p. */
2732 size_t off = p - start;
2734 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2736 end = start + ebuf->size;
2741 if (ferror (ebuf->fp))
2742 pfatal_with_name (ebuf->floc.filenm);
2744 /* If we found some lines, return how many.
2745 If we didn't, but we did find _something_, that indicates we read the last
2746 line of a file with no final newline; return 1.
2747 If we read nothing, we're at EOF; return -1. */
2749 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2752 /* Parse the next "makefile word" from the input buffer, and return info
2755 A "makefile word" is one of:
2757 w_bogus Should never happen
2759 w_static A static word; cannot be expanded
2760 w_variable A word containing one or more variables/functions
2762 w_dcolon A double-colon
2763 w_ampcolon An ampersand-colon (&:) token
2764 w_ampdcolon An ampersand-double-colon (&::) token
2765 w_semicolon A semicolon
2766 w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
2768 Note that this function is only used when reading certain parts of the
2769 makefile. Don't use it where special rules hold sway (RHS of a variable,
2770 in a command list, etc.) */
2772 static enum make_word_type
2773 get_next_mword (char *buffer, char **startp, size_t *length)
2775 enum make_word_type wtype;
2776 char *p = buffer, *beg;
2779 /* Skip any leading whitespace. */
2780 while (ISSPACE (*p))
2786 /* Look at the start of the word to see if it's simple. */
2794 wtype = w_semicolon;
2798 wtype = w_varassign;
2805 wtype = w_varassign; /* := */
2813 wtype = w_varassign; /* ::= */
2827 wtype = w_ampcolon; /* &: */
2831 wtype = w_ampdcolon; /* &:: */
2843 wtype = w_varassign; /* += or ?= or != */
2852 /* This is some non-operator word. A word consists of the longest
2853 string of characters that doesn't contain whitespace, one of [:=#],
2854 or [?+!]=, or &:. */
2856 /* We start out assuming a static word; if we see a variable we'll
2857 adjust our assumptions then. */
2860 /* We already found the first value of "c", above. */
2866 if (END_OF_TOKEN (c))
2875 #ifdef HAVE_DOS_PATHS
2876 /* A word CAN include a colon in its drive spec. The drive
2877 spec is allowed either at the beginning of a word, or as part
2878 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2879 if ((p - beg == 2 || (p - beg > 2 && p[-3] == '('))
2880 && isalpha ((unsigned char)p[-2]))
2892 /* This is a variable reference, so note that it's expandable.
2893 Then read it to the matching close paren. */
2901 /* This is a single-letter variable reference. */
2904 for (count=0; *p != '\0'; ++p)
2908 else if (*p == closeparen && --count < 0)
2956 /* Construct the list of include directories
2957 from the arguments and the default list. */
2960 construct_include_path (const char **arg_dirs)
2962 #ifdef VAXC /* just don't ask ... */
2972 /* Compute the number of pointers we need in the table. */
2973 idx = sizeof (default_include_directories) / sizeof (const char *);
2975 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2979 /* Add one for $DJDIR. */
2983 dirs = xmalloc (idx * sizeof (const char *));
2988 /* First consider any dirs specified with -I switches.
2989 Ignore any that don't exist. Restart if we find "-".
2990 Remember the maximum string length. */
2993 while (*arg_dirs != 0)
2995 const char *dir = *(arg_dirs++);
2999 if (dir[0] == '-' && dir[1] == '\0')
3009 expanded = tilde_expand (dir);
3014 EINTRLOOP (e, stat (dir, &stbuf));
3015 if (e == 0 && S_ISDIR (stbuf.st_mode))
3017 size_t len = strlen (dir);
3018 /* If dir name is written with trailing slashes, discard them. */
3019 while (len > 1 && dir[len - 1] == '/')
3021 if (len > max_incl_len)
3023 dirs[idx++] = strcache_add_len (dir, len);
3029 /* Now add the standard default dirs at the end. */
3033 /* The environment variable $DJDIR holds the root of the DJGPP directory
3034 tree; add ${DJDIR}/include. */
3035 struct variable *djdir = lookup_variable ("DJDIR", 5);
3039 size_t len = strlen (djdir->value) + 8;
3040 char *defdir = alloca (len + 1);
3042 strcat (strcpy (defdir, djdir->value), "/include");
3043 dirs[idx++] = strcache_add (defdir);
3045 if (len > max_incl_len)
3049 for (cpp = default_include_directories; *cpp != 0; ++cpp)
3053 EINTRLOOP (e, stat (*cpp, &stbuf));
3054 if (e == 0 && S_ISDIR (stbuf.st_mode))
3056 size_t len = strlen (*cpp);
3057 /* If dir name is written with trailing slashes, discard them. */
3058 while (len > 1 && (*cpp)[len - 1] == '/')
3060 if (len > max_incl_len)
3062 dirs[idx++] = strcache_add_len (*cpp, len);
3069 /* Now add each dir to the .INCLUDE_DIRS variable. */
3071 do_variable_definition (NILF, ".INCLUDE_DIRS", "", o_default, f_simple, 0);
3072 for (cpp = dirs; *cpp != 0; ++cpp)
3073 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
3074 o_default, f_append, 0);
3076 free ((void *) include_directories);
3077 include_directories = dirs;
3080 /* Expand ~ or ~USER at the beginning of NAME.
3081 Return a newly malloc'd string or 0. */
3084 tilde_expand (const char *name)
3087 if (name[1] == '/' || name[1] == '\0')
3093 /* Turn off --warn-undefined-variables while we expand HOME. */
3094 int save = warn_undefined_variables_flag;
3095 warn_undefined_variables_flag = 0;
3097 home_dir = allocated_variable_expand ("$(HOME)");
3099 warn_undefined_variables_flag = save;
3102 is_variable = home_dir[0] != '\0';
3106 home_dir = getenv ("HOME");
3108 # if !defined(_AMIGA) && !defined(WINDOWS32)
3109 if (home_dir == 0 || home_dir[0] == '\0')
3111 char *logname = getlogin ();
3115 struct passwd *p = getpwnam (logname);
3117 home_dir = p->pw_dir;
3120 # endif /* !AMIGA && !WINDOWS32 */
3123 char *new = xstrdup (concat (2, home_dir, name + 1));
3129 # if !defined(_AMIGA) && !defined(WINDOWS32)
3132 struct passwd *pwent;
3133 char *userend = strchr (name + 1, '/');
3136 pwent = getpwnam (name + 1);
3140 return xstrdup (pwent->pw_dir);
3143 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
3145 else if (userend != 0)
3148 # endif /* !AMIGA && !WINDOWS32 */
3153 /* Parse a string into a sequence of filenames represented as a chain of
3154 struct nameseq's and return that chain. Optionally expand the strings via
3157 The string is passed as STRINGP, the address of a string pointer.
3158 The string pointer is updated to point at the first character
3159 not parsed, which either is a null char or equals STOPMAP.
3161 SIZE is how large (in bytes) each element in the new chain should be.
3162 This is useful if we want them actually to be other structures
3163 that have room for additional info.
3165 STOPMAP is a map of characters that tell us to stop parsing.
3167 PREFIX, if non-null, is added to the beginning of each filename.
3169 FLAGS allows one or more of the following bitflags to be set:
3170 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
3171 PARSEFS_NOAR - Do not check filenames for archive references
3172 PARSEFS_NOGLOB - Do not expand globbing characters
3173 PARSEFS_EXISTS - Only return globbed files that actually exist
3174 (cannot also set NOGLOB)
3175 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
3176 PARSEFS_ONEWORD - Don't break the sequence on whitespace
3177 PARSEFS_WAIT - Assume struct dep and handle .WAIT
3181 parse_file_seq (char **stringp, size_t size, int stopmap,
3182 const char *prefix, int flags)
3184 /* tmp points to tmpbuf after the prefix, if any.
3185 tp is the end of the buffer. */
3186 static char *tmpbuf = NULL;
3188 int cachep = NONE_SET (flags, PARSEFS_NOCACHE);
3190 struct nameseq *new = 0;
3191 struct nameseq **newp = &new;
3192 #define NEWELT(_n) do { \
3193 struct nameseq *_ns = xcalloc (size); \
3194 const char *__n = (_n); \
3195 _ns->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
3197 ((struct dep*)_ns)->wait_here = 1; \
3201 newp = &_ns->next; \
3207 int findmap = stopmap|MAP_VMSCOMMA|MAP_NUL;
3210 if (NONE_SET (flags, PARSEFS_ONEWORD))
3211 findmap |= MAP_BLANK;
3213 /* Always stop on NUL. */
3216 if (size < sizeof (struct nameseq))
3217 size = sizeof (struct nameseq);
3219 if (NONE_SET (flags, PARSEFS_NOGLOB))
3220 dir_setup_glob (&gl);
3222 /* Get enough temporary space to construct the largest possible target. */
3224 static size_t tmpbuf_len = 0;
3225 size_t l = strlen (*stringp) + 1;
3228 tmpbuf = xrealloc (tmpbuf, l);
3234 /* Parse STRING. P will always point to the end of the parsed content. */
3239 const char **nlist = 0;
3250 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
3252 if (STOP_SET (*p, stopmap))
3255 /* There are names left, so find the end of the next name.
3256 Throughout this iteration S points to the start. */
3258 p = find_map_unquote (p, findmap);
3261 /* convert comma separated list to space separated */
3266 /* If we stopped due to a device name, skip it. */
3267 if (p && p != s+1 && p[0] == ':')
3268 p = find_map_unquote (p+1, findmap);
3270 #ifdef HAVE_DOS_PATHS
3271 /* If we stopped due to a drive specifier, skip it.
3272 Tokens separated by spaces are treated as separate paths since make
3273 doesn't allow path names with spaces. */
3274 if (p && p == s+1 && p[0] == ':'
3275 && isalpha ((unsigned char)s[0]) && ISDIRSEP (p[1]))
3276 p = find_map_unquote (p+1, findmap);
3282 if (ANY_SET (flags, PARSEFS_WAIT) && p - s == CSTRLEN (".WAIT")
3283 && memcmp (s, ".WAIT", CSTRLEN (".WAIT")) == 0)
3285 /* Note that we found a .WAIT for the next dep but skip it. */
3290 /* Strip leading "this directory" references. */
3291 if (NONE_SET (flags, PARSEFS_NOSTRIP))
3293 /* Skip leading '[]'s. should only be one set or bug somewhere else */
3294 if (p - s > 2 && s[0] == '[' && s[1] == ']')
3296 /* Skip leading '<>'s. should only be one set or bug somewhere else */
3297 if (p - s > 2 && s[0] == '<' && s[1] == '>')
3300 /* Skip leading './'s. */
3301 while (p - s > 2 && s[0] == '.' && s[1] == '/')
3303 /* Skip "./" and all following slashes. */
3309 /* Extract the filename just found, and skip it.
3310 Set NAME to the string, and NLEN to its length. */
3314 /* The name was stripped to empty ("./"). */
3316 /* PDS-- This cannot be right!! */
3329 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
3330 * to remove this '\' before we can use the filename.
3331 * xstrdup called because S may be read-only string constant.
3336 if (s[0] == '\\' && s[1] == ':')
3344 memcpy (tp, s, nlen);
3349 /* At this point, TP points to the element and NLEN is its length. */
3352 /* If this is the start of an archive group that isn't complete, set up
3353 to add the archive prefix for future files. A file list like:
3354 "libf.a(x.o y.o z.o)" needs to be expanded as:
3355 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3357 TP == TMP means we're not already in an archive group. Ignore
3358 something starting with '(', as that cannot actually be an
3359 archive-member reference (and treating it as such results in an empty
3360 file name, which causes much lossage). Also if it ends in ")" then
3361 it's a complete reference so we don't need to treat it specially.
3363 Finally, note that archive groups must end with ')' as the last
3364 character, so ensure there's some word ending like that before
3365 considering this an archive group. */
3366 if (NONE_SET (flags, PARSEFS_NOAR)
3367 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3369 char *n = strchr (tp, '(');
3372 /* This looks like the first element in an open archive group.
3373 A valid group MUST have ')' as the last character. */
3379 /* Find the end of this word. We don't want to unquote and
3380 we don't care about quoting since we're looking for the
3381 last char in the word. */
3382 while (! STOP_SET (*e, findmap))
3384 /* If we didn't move, we're done now. */
3389 /* Found the end, so this is the first element in an
3390 open archive group. It looks like "lib(mem".
3391 Reset TP past the open paren. */
3392 nlen -= (n + 1) - tp;
3395 /* We can stop looking now. */
3401 /* If we have just "lib(", part of something like "lib( a b)",
3402 go to the next item. */
3408 /* If we are inside an archive group, make sure it has an end. */
3411 if (tp[nlen-1] == ')')
3413 /* This is the natural end; reset TP. */
3416 /* This is just ")", something like "lib(a b )": skip it. */
3422 /* Not the end, so add a "fake" end. */
3429 /* If we're not globbing we're done: add it to the end of the chain.
3430 Go to the next item in the string. */
3431 if (ANY_SET (flags, PARSEFS_NOGLOB))
3433 NEWELT (concat (2, prefix, tmpbuf));
3437 /* If we get here we know we're doing glob expansion.
3438 TP is a string in tmpbuf. NLEN is no longer used.
3439 We may need to do more work: after this NAME will be set. */
3442 /* Expand tilde if applicable. */
3443 if (tmpbuf[0] == '~')
3445 tildep = tilde_expand (tmpbuf);
3451 /* If NAME is an archive member reference replace it with the archive
3452 file name, and save the member name in MEMNAME. We will glob on the
3453 archive name and then reattach MEMNAME later. */
3454 if (NONE_SET (flags, PARSEFS_NOAR) && ar_name (name))
3456 ar_parse_name (name, &arname, &memname);
3459 #endif /* !NO_ARCHIVES */
3461 /* glob() is expensive: don't call it unless we need to. */
3462 if (NONE_SET (flags, PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3469 switch (glob (name, GLOB_ALTDIRFUNC, NULL, &gl))
3477 nlist = (const char **)gl.gl_pathv;
3481 /* If we want only existing items, skip this one. */
3482 if (ANY_SET (flags, PARSEFS_EXISTS))
3490 /* By default keep this name. */
3496 /* For each matched element, add it to the list. */
3497 for (i = 0; i < tot; ++i)
3501 /* Try to glob on MEMNAME within the archive. */
3502 struct nameseq *found = ar_glob (nlist[i], memname, size);
3504 /* No matches. Use MEMNAME as-is. */
3505 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3508 /* We got a chain of items. Attach them. */
3510 (*newp)->next = found;
3514 /* Find and set the new end. Massage names if necessary. */
3518 found->name = xstrdup (concat (2, prefix, name));
3520 found->name = strcache_add (concat (2, prefix, name));
3522 if (found->next == 0)
3525 found = found->next;
3527 newp = &found->next;
3531 #endif /* !NO_ARCHIVES */
3532 NEWELT (concat (2, prefix, nlist[i]));