Debian Codegraph @

src/read.c

raw symbols SCIP
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
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.
9
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.
13
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/>. */
16
17 #include "makeint.h"
18 #include "globals.h"
19 // debugger include(s)
20 #include "cmd.h"
21
22 #include <assert.h>
23
24 #include "read.h"
25 #include "filedef.h"
26 #include "job.h"
27 #include "os.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
33
34
35 #ifdef WINDOWS32
36 #include <windows.h>
37 #include "sub_proc.h"
38 #else /* !WINDOWS32 */
39 #include <pwd.h>
40 #endif /* !WINDOWS32 */
41
42 /* A 'struct ebuffer' controls the origin of the makefile we are currently
43 eval'ing.
44 */
45
46 struct ebuffer
47 {
48 char *buffer; /* Start of the current line in the buffer. */
49 char *bufnext; /* Start of the next line in the buffer. */
50 char *bufstart; /* Start of the entire buffer. */
51 size_t size; /* Malloc'd size of buffer. */
52 FILE *fp; /* File, or NULL if this is an internal buffer. */
53 gmk_floc floc; /* Info on the file in fp (if any). */
54 };
55
56 /* Track the modifiers we can have on variable assignments */
57
58 struct vmodifiers
59 {
60 unsigned int assign_v:1;
61 unsigned int define_v:1;
62 unsigned int undefine_v:1;
63 unsigned int export_v:1;
64 unsigned int override_v:1;
65 unsigned int private_v:1;
66 };
67
68 /* Types of "words" that can be read in a makefile. */
69 enum make_word_type
70 {
71 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
72 w_varassign, w_ampcolon, w_ampdcolon
73 };
74
75
76 /* A 'struct conditionals' contains the information describing
77 all the active conditionals in a makefile.
78
79 The global variable 'conditionals' contains the conditionals
80 information for the current makefile. It is initialized from
81 the static structure 'toplevel_conditionals' and is later changed
82 to new structures for included makefiles. */
83
84 struct conditionals
85 {
86 unsigned int if_cmds; /* Depth of conditional nesting. */
87 unsigned int allocated; /* Elts allocated in following arrays. */
88 char *ignoring; /* Are we ignoring or interpreting?
89 0=interpreting, 1=not yet interpreted,
90 2=already interpreted */
91 char *seen_else; /* Have we already seen an 'else'? */
92 };
93
94 static struct conditionals toplevel_conditionals;
95 static struct conditionals *conditionals = &toplevel_conditionals;
96
97
98 /* Default directories to search for include files in */
99
100 static const char *default_include_directories[] =
101 {
102 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
103 /* This completely up to the user when they install MSVC or other packages.
104 This is defined as a placeholder. */
105 # define INCLUDEDIR "."
106 #endif
107 INCLUDEDIR,
108 #ifndef _AMIGA
109 "/usr/gnu/include",
110 "/usr/local/include",
111 "/usr/include",
112 #endif
113 0
114 };
115
116 /* List of directories to search for include files in */
117
118 static const char **include_directories;
119
120 /* Maximum length of an element of the above. */
121
122 static size_t max_incl_len;
123
124 extern struct goaldep *eval_makefile (const char *filename, unsigned short flags);
125 static void eval (struct ebuffer *buffer, int flags);
126
127 static long readline (struct ebuffer *ebuf);
128 static void do_undefine (char *name, enum variable_origin origin,
129 struct ebuffer *ebuf);
130 static struct variable *do_define (char *name, enum variable_origin origin,
131 struct ebuffer *ebuf);
132 static int conditional_line (char *line, size_t len, const gmk_floc *flocp);
133 static void record_files (struct nameseq *filenames, int are_also_makes,
134 const char *pattern,
135 const char *pattern_percent, char *depstr,
136 unsigned int cmds_started, char *commands,
137 size_t commands_idx, int two_colon,
138 char *target_description,
139 char prefix, const gmk_floc *flocp);
140 static void record_target_var (struct nameseq *filenames, char *defn,
141 enum variable_origin origin,
142 struct vmodifiers *vmod,
143 const gmk_floc *flocp);
144 static enum make_word_type get_next_mword (char *buffer,
145 char **startp, size_t *length);
146 static void remove_comments (char *line, char **description,
147 char **prev_description, unsigned long lineno);
148 static char *find_map_unquote (char *string, int map);
149 static char *find_char_unquote (char *string, int stop);
150 static char *unescape_char (char *string, int c);
151
152
153 /* Compare a word, both length and contents.
154 P must point to the word to be tested, and WLEN must be the length.
155 */
156 #define word1eq(s) (wlen == CSTRLEN (s) && strneq (s, p, CSTRLEN (s)))
157
158
159 /* Read in all the makefiles and return a chain of targets to rebuild. */
160
161 struct goaldep *
162 read_all_makefiles (const char **makefiles)
163 {
164 unsigned int num_makefiles = 0;
165
166 /* Create *_LIST variables, to hold the makefiles, targets, and variables
167 we will be reading. */
168
169 define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
170
171 if (b_debugger_preread && i_debugger_stepping && !in_debugger)
172 enter_debugger (NULL, NULL, 0, DEBUG_READ_HIT);
173
174 DB (DB_BASIC, (_("Reading makefiles...\n")));
175
176 /* If there's a non-null variable MAKEFILES, its value is a list of
177 files to read first thing. But don't let it prevent reading the
178 default makefiles and don't let the default goal come from there. */
179
180 {
181 char *value;
182 char *name, *p;
183 size_t length;
184
185 {
186 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
187 int save = warn_undefined_variables_flag;
188 warn_undefined_variables_flag = 0;
189
190 value = allocated_variable_expand ("$(MAKEFILES)");
191
192 warn_undefined_variables_flag = save;
193 }
194
195 /* Set NAME to the start of next token and LENGTH to its length.
196 MAKEFILES is updated for finding remaining tokens. */
197 p = value;
198
199 while ((name = find_next_token ((const char **)&p, &length)) != 0)
200 {
201 if (*p != '\0')
202 *p++ = '\0';
203 eval_makefile (strcache_add (name), RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
204 }
205
206 free (value);
207 }
208
209 /* Read makefiles specified with -f switches. */
210
211 if (makefiles != 0)
212 while (*makefiles != 0)
213 {
214 struct goaldep *d = eval_makefile (*makefiles, 0);
215
216 if (errno)
217 perror_with_name ("", *makefiles);
218
219 /* Reuse the storage allocated for the read_file. */
220 *makefiles = dep_name (d);
221 ++num_makefiles;
222 ++makefiles;
223 }
224
225 /* If there were no -f switches, try the default names. */
226
227 if (num_makefiles == 0)
228 {
229 PATH_VAR (current_directory);
230 static const char *default_makefiles[] =
231 { "GNUmakefile", "makefile", "Makefile", 0 };
232 const char **p;
233
234 while (1) {
235 p = default_makefiles;
236 if (getcwd (current_directory, GET_PATH_MAX) == NULL)
237 break;
238 while (*p != 0 && !dir_file_exists_p (current_directory, *p))
239 ++p;
240
241 if (*p != 0)
242 {
243 eval_makefile (*p, 0);
244 if (errno)
245 {
246 perror_with_name ("", *p);
247 p = 0;
248 }
249 else
250 break;
251 }
252
253 /* Do we try looking for Makefile in the parent directory? */
254 if (!search_parent_flag) break;
255 if (0 == strncmp(current_directory, "/", GET_PATH_MAX)) break;
256 if (chdir("..") != 0) break;
257 }
258
259 if (p == 0)
260 {
261 /* No default makefile was found. Add the default makefiles to the
262 'read_files' chain so they will be updated if possible. */
263 struct goaldep *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)
268 {
269 struct goaldep *d = alloc_goaldep ();
270 d->file = enter_file (strcache_add (*p));
271 /* Tell update_goal_chain to bail out as soon as this file is
272 made, and main not to die if we can't make this file. */
273 d->flags = RM_DONTCARE;
274 if (tail == 0)
275 read_makefiles = d;
276 else
277 tail->next = d;
278 tail = d;
279 }
280 if (tail != 0)
281 tail->next = 0;
282 }
283 }
284
285 return read_makefiles;
286 }
287
288 /* Install a new conditional and return the previous one. */
289
290 static struct conditionals *
291 install_conditionals (struct conditionals *new)
292 {
293 struct conditionals *save = conditionals;
294
295 memset (new, '\0', sizeof (*new));
296 conditionals = new;
297
298 return save;
299 }
300
301 /* Free the current conditionals and reinstate a saved one. */
302
303 static void
304 restore_conditionals (struct conditionals *saved)
305 {
306 /* Free any space allocated by conditional_line. */
307 free (conditionals->ignoring);
308 free (conditionals->seen_else);
309
310 /* Restore state. */
311 conditionals = saved;
312 }
313
314 extern struct goaldep *
315 eval_makefile (const char *filename, unsigned short flags)
316 {
317 struct goaldep *deps;
318 struct ebuffer ebuf;
319 const gmk_floc *curfile;
320 char *expanded = 0;
321
322 /* Create a new goaldep entry. */
323 deps = alloc_goaldep ();
324 deps->next = read_makefiles;
325 read_makefiles = deps;
326
327 ebuf.floc.filenm = filename; /* Use the original file name. */
328 ebuf.floc.lineno = 1;
329 ebuf.floc.offset = 0;
330
331 if (ISDB (DB_VERBOSE|DB_READ_MAKEFILES))
332 {
333 printf (_("Reading makefile '%s'"), filename);
334 if (flags & RM_NO_DEFAULT_GOAL)
335 printf (_(" (no default goal)"));
336 if (flags & RM_INCLUDED)
337 printf (_(" (search path)"));
338 if (flags & RM_DONTCARE)
339 printf (_(" (don't care)"));
340 if (flags & RM_NO_TILDE)
341 printf (_(" (no ~ expansion)"));
342 puts ("...");
343 }
344
345 /* First, get a stream to read. */
346
347 /* Expand ~ in FILENAME unless it came from 'include',
348 in which case it was already done. */
349 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
350 {
351 expanded = remake_tilde_expand (filename);
352 if (expanded != 0)
353 filename = expanded;
354 }
355
356 errno = 0;
357 ENULLLOOP (ebuf.fp, fopen (filename, "r"));
358 deps->error = errno;
359
360 /* Check for unrecoverable errors: out of mem or FILE slots. */
361 switch (deps->error)
362 {
363 #ifdef EMFILE
364 case EMFILE:
365 #endif
366 #ifdef ENFILE
367 case ENFILE:
368 #endif
369 case ENOMEM:
370 {
371 const char *err = strerror (deps->error);
372 OS (fatal, reading_file, "%s", err);
373 }
374 }
375
376 /* If the makefile wasn't found and it's either a makefile from
377 the 'MAKEFILES' variable or an included makefile,
378 search the included makefile search path for this makefile. */
379 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
380 {
381 unsigned int i;
382 for (i = 0; include_directories[i] != 0; ++i)
383 {
384 const char *included = concat (3, include_directories[i],
385 "/", filename);
386 ebuf.fp = fopen (included, "r");
387 if (ebuf.fp)
388 {
389 filename = included;
390 break;
391 }
392 }
393 }
394
395 /* Enter the final name for this makefile as a goaldep. */
396 filename = strcache_add (filename);
397 deps->file = lookup_file (filename);
398 if (deps->file == 0)
399 deps->file = enter_file (filename);
400 filename = deps->file->name;
401 deps->flags = flags;
402
403 free (expanded);
404
405 if (ebuf.fp == 0)
406 {
407 /* The makefile can't be read at all, give up entirely.
408 If we did some searching errno has the error from the last attempt,
409 rather from FILENAME itself: recover the more accurate one. */
410 errno = deps->error;
411 deps->file->last_mtime = NONEXISTENT_MTIME;
412 return deps;
413 }
414
415 /* Success; clear errno. */
416 deps->error = 0;
417
418 /* Avoid leaking the makefile to children. */
419 fd_noinherit (fileno (ebuf.fp));
420
421 /* Add this makefile to the list. */
422 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
423 f_append_value, 0);
424
425 if (b_debugger_preread && i_debugger_stepping && !in_debugger) {
426 enter_debugger (NULL, NULL, 0, DEBUG_READ_HIT);
427 }
428
429 /* Evaluate the makefile */
430
431 ebuf.size = 200;
432 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
433
434 curfile = reading_file;
435 reading_file = &ebuf.floc;
436
437 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
438
439 reading_file = curfile;
440 deps->file->nlines = ebuf.floc.lineno;
441
442 fclose (ebuf.fp);
443
444 free (ebuf.bufstart);
445 alloca (0);
446
447 errno = 0;
448 return deps;
449 }
450
451 void
452 eval_buffer (char *buffer, const gmk_floc *flocp)
453 {
454 struct ebuffer ebuf;
455 struct conditionals *saved;
456 struct conditionals new;
457 const gmk_floc *curfile;
458
459 /* Evaluate the buffer */
460
461 ebuf.size = strlen (buffer);
462 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
463 ebuf.fp = NULL;
464
465 if (flocp)
466 ebuf.floc = *flocp;
467 else if (reading_file)
468 ebuf.floc = *reading_file;
469 else
470 {
471 ebuf.floc.filenm = NULL;
472 ebuf.floc.lineno = 1;
473 ebuf.floc.offset = 0;
474 }
475
476 curfile = reading_file;
477 reading_file = &ebuf.floc;
478
479 saved = install_conditionals (&new);
480
481 eval (&ebuf, 1);
482
483 restore_conditionals (saved);
484
485 reading_file = curfile;
486
487 alloca (0);
488 }
489
490 /* Check LINE to see if it's a variable assignment or undefine.
491
492 It might use one of the modifiers "export", "override", "private", or it
493 might be one of the conditional tokens like "ifdef", "include", etc.
494
495 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
496 Returns LINE.
497
498 Returns a pointer to the first non-modifier character, and sets VMOD
499 based on the modifiers found if any, plus V_ASSIGN is 1.
500 */
501 static char *
502 parse_var_assignment (const char *line, struct vmodifiers *vmod)
503 {
504 const char *p;
505 memset (vmod, '\0', sizeof (*vmod));
506
507 /* Find the start of the next token. If there isn't one we're done. */
508 NEXT_TOKEN (line);
509 if (*line == '\0')
510 return (char *) line;
511
512 p = line;
513 while (1)
514 {
515 size_t wlen;
516 const char *p2;
517 struct variable v;
518
519 p2 = parse_variable_definition (p, &v);
520
521 /* If this is a variable assignment, we're done. */
522 if (p2)
523 break;
524
525 /* It's not a variable; see if it's a modifier. */
526 p2 = end_of_token (p);
527 wlen = p2 - p;
528
529 if (word1eq ("export"))
530 vmod->export_v = 1;
531 else if (word1eq ("override"))
532 vmod->override_v = 1;
533 else if (word1eq ("private"))
534 vmod->private_v = 1;
535 else if (word1eq ("define"))
536 {
537 /* We can't have modifiers after 'define' */
538 vmod->define_v = 1;
539 p = next_token (p2);
540 break;
541 }
542 else if (word1eq ("undefine"))
543 {
544 /* We can't have modifiers after 'undefine' */
545 vmod->undefine_v = 1;
546 p = next_token (p2);
547 break;
548 }
549 else
550 /* Not a variable or modifier: this is not a variable assignment. */
551 return (char *) line;
552
553 /* It was a modifier. Try the next word. */
554 p = next_token (p2);
555 if (*p == '\0')
556 return (char *) line;
557 }
558
559 /* Found a variable assignment or undefine. */
560 vmod->assign_v = 1;
561 return (char *)p;
562 }
563
564
565 static unsigned long int target_description_lineno = 0;
566 static unsigned long int prev_target_description_lineno = 0;
567
568 /* Read file FILENAME as a makefile and add its contents to the data base.
569
570 SET_DEFAULT is true if we are allowed to set the default goal. */
571
572 static void
573 eval (struct ebuffer *ebuf, int set_default)
574 {
575 char *collapsed = 0;
576 size_t collapsed_length = 0;
577 size_t commands_len = 200;
578 char *commands;
579 size_t commands_idx = 0;
580 unsigned int cmds_started, tgts_started;
581 int ignoring = 0, in_ignored_define = 0;
582 int no_targets = 0; /* Set when reading a rule without targets. */
583 int also_make_targets = 0; /* Set when reading grouped targets. */
584 struct nameseq *filenames = 0;
585 char *depstr = 0;
586 long nlines = 0;
587 int two_colon = 0;
588 char prefix = cmd_prefix;
589 const char *pattern = 0;
590 const char *pattern_percent;
591 gmk_floc *fstart;
592 gmk_floc fi;
593
594 static char *target_description; /* Place to store most recent
595 * target description */
596 static char *prev_target_description; /* Most of the time, we read
597 two targets before
598 processing the first. I
599 think this happens because
600 the second target signals
601 the end of the first
602 target. As a result, we
603 need to save two
604 descriptions to be able to
605 use the previous
606 description for the first
607 target. For the last target
608 of the file though, EOF
609 signals the end of the
610 target so we don't use
611 prev_target_description. */
612 #define record_waiting_files() \
613 do \
614 { \
615 if (filenames != 0) \
616 { \
617 /* Have we seen two descriptions since this target or one? */ \
618 char *description = target_description_lineno > tgts_started ? \
619 prev_target_description : target_description; \
620 fi.lineno = tgts_started; \
621 fi.offset = 0; \
622 record_files (filenames, also_make_targets, pattern, \
623 pattern_percent, depstr, \
624 cmds_started, commands, commands_idx, two_colon, \
625 description, prefix, &fi); \
626 /* Don't use the target_description values more than once. */ \
627 if (target_description_lineno > tgts_started) \
628 prev_target_description = NULL; \
629 else \
630 target_description = NULL; \
631 filenames = 0; \
632 } \
633 commands_idx = 0; \
634 no_targets = 0; \
635 pattern = 0; \
636 also_make_targets = 0; \
637 } while (0)
638
639 pattern_percent = 0;
640 cmds_started = tgts_started = 1;
641
642 fstart = &ebuf->floc;
643 fi.filenm = ebuf->floc.filenm;
644
645 /* Loop over lines in the file.
646 The strategy is to accumulate target names in FILENAMES, dependencies
647 in DEPS and commands in COMMANDS. These are used to define a rule
648 when the start of the next rule (or eof) is encountered.
649
650 When you see a "continue" in the loop below, that means we are moving on
651 to the next line. If you see record_waiting_files(), then the statement
652 we are parsing also finishes the previous rule. */
653
654 commands = xmalloc (200);
655 prev_target_description = NULL;
656 target_description = NULL;
657
658 while (1)
659 {
660 size_t linelen;
661 char *line;
662 size_t wlen;
663 char *p;
664 char *p2;
665 struct vmodifiers vmod;
666
667 /* At the top of this loop, we are starting a brand new line. */
668 /* Grab the next line to be evaluated */
669 ebuf->floc.lineno += nlines;
670 nlines = readline (ebuf);
671
672 /* If there is nothing left to eval, we're done. */
673 if (nlines < 0)
674 break;
675
676 line = ebuf->buffer;
677
678 /* If this is the first line, check for a UTF-8 BOM and skip it. */
679 if (ebuf->floc.lineno == 1)
680 {
681 unsigned char *ul = (unsigned char *) line;
682 if (ul[0] == 0xEF && ul[1] == 0xBB && ul[2] == 0xBF)
683 {
684 line += 3;
685 if (ISDB(DB_BASIC))
686 {
687 if (ebuf->floc.filenm)
688 printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
689 ebuf->floc.filenm);
690 else
691 printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
692 }
693 }
694 }
695 /* If this line is empty, skip it. */
696 if (line[0] == '\0')
697 continue;
698
699 linelen = strlen (line);
700
701 /* Check for a shell command line first.
702 If it is not one, we can stop treating cmd_prefix specially. */
703 if (line[0] == cmd_prefix)
704 {
705 if (no_targets)
706 /* Ignore the commands in a rule with no targets. */
707 continue;
708
709 /* If there is no preceding rule line, don't treat this line
710 as a command, even though it begins with a recipe prefix.
711 SunOS 4 make appears to behave this way. */
712
713 if (filenames != 0)
714 {
715 if (ignoring)
716 /* Yep, this is a shell command, and we don't care. */
717 continue;
718
719 if (commands_idx == 0)
720 cmds_started = ebuf->floc.lineno;
721
722 /* Append this command line to the line being accumulated.
723 Skip the initial command prefix character. */
724 if (linelen + commands_idx > commands_len)
725 {
726 commands_len = (linelen + commands_idx) * 2;
727 commands = xrealloc (commands, commands_len);
728 }
729 memcpy (&commands[commands_idx], line + 1, linelen - 1);
730 commands_idx += linelen - 1;
731 commands[commands_idx++] = '\n';
732 continue;
733 }
734 }
735
736 /* This line is not a shell command line. Don't worry about whitespace.
737 Get more space if we need it; we don't need to preserve the current
738 contents of the buffer. */
739
740 if (collapsed_length < linelen+1)
741 {
742 collapsed_length = linelen+1;
743 free (collapsed);
744 /* Don't need xrealloc: we don't need to preserve the content. */
745 collapsed = xmalloc (collapsed_length);
746 }
747 strcpy (collapsed, line);
748 /* Collapse continuation lines. */
749 collapse_continuations (collapsed);
750 remove_comments (collapsed, &target_description,
751 &prev_target_description, ebuf->floc.lineno);
752
753 /* Get rid if starting space (including formfeed, vtab, etc.) */
754 p = collapsed;
755 NEXT_TOKEN (p);
756
757 /* See if this is a variable assignment. We need to do this early, to
758 allow variables with names like 'ifdef', 'export', 'private', etc. */
759 p = parse_var_assignment (p, &vmod);
760 if (vmod.assign_v)
761 {
762 struct variable *v;
763 enum variable_origin origin = vmod.override_v ? o_override : o_file;
764
765 /* If we're ignoring then we're done now. */
766 if (ignoring)
767 {
768 if (vmod.define_v)
769 in_ignored_define = 1;
770 continue;
771 }
772
773 /* Variable assignment ends the previous rule. */
774 record_waiting_files ();
775
776 if (vmod.undefine_v)
777 {
778 do_undefine (p, origin, ebuf);
779 continue;
780 }
781 else if (vmod.define_v)
782 v = do_define (p, origin, ebuf);
783 else
784 v = try_variable_definition (fstart, p, origin, 0);
785
786 assert (v != NULL);
787
788 if (vmod.export_v)
789 v->export = v_export;
790 if (vmod.private_v)
791 v->private_var = 1;
792
793 /* This line has been dealt with. */
794 continue;
795 }
796
797 /* If this line is completely empty, ignore it. */
798 if (*p == '\0')
799 continue;
800
801 p2 = end_of_token (p);
802 wlen = p2 - p;
803 NEXT_TOKEN (p2);
804
805 /* If we're in an ignored define, skip this line (but maybe get out). */
806 if (in_ignored_define)
807 {
808 /* See if this is an endef line (plus optional comment). */
809 if (word1eq ("endef") && STOP_SET (*p2, MAP_COMMENT|MAP_NUL))
810 in_ignored_define = 0;
811
812 continue;
813 }
814
815 /* Check for conditional state changes. */
816 {
817 int i = conditional_line (p, wlen, fstart);
818 if (i != -2)
819 {
820 if (i == -1)
821 O (fatal, fstart, _("invalid syntax in conditional"));
822
823 ignoring = i;
824 continue;
825 }
826 }
827
828 /* Nothing to see here... move along. */
829 if (ignoring)
830 continue;
831
832 /* Manage the "export" keyword used outside of variable assignment
833 as well as "unexport". */
834 if (word1eq ("export") || word1eq ("unexport"))
835 {
836 int exporting = *p == 'u' ? 0 : 1;
837
838 /* Export/unexport ends the previous rule. */
839 record_waiting_files ();
840
841 /* (un)export by itself causes everything to be (un)exported. */
842 if (*p2 == '\0')
843 export_all_variables = exporting;
844 else
845 {
846 size_t l;
847 const char *cp;
848 char *ap;
849
850 /* Expand the line so we can use indirect and constructed
851 variable names in an (un)export command. */
852 cp = ap = allocated_variable_expand (p2);
853
854 for (p = find_next_token (&cp, &l); p != 0;
855 p = find_next_token (&cp, &l))
856 {
857 struct variable *v = lookup_variable (p, l);
858 if (v == 0)
859 v = define_variable_global (p, l, "", o_file, 0, fstart);
860 v->export = exporting ? v_export : v_noexport;
861 }
862
863 free (ap);
864 }
865 continue;
866 }
867
868 /* Handle the special syntax for vpath. */
869 if (word1eq ("vpath"))
870 {
871 const char *cp;
872 char *vpat;
873 size_t l;
874
875 /* vpath ends the previous rule. */
876 record_waiting_files ();
877
878 cp = variable_expand (p2);
879 p = find_next_token (&cp, &l);
880 if (p != 0)
881 {
882 vpat = xstrndup (p, l);
883 p = find_next_token (&cp, &l);
884 /* No searchpath means remove all previous
885 selective VPATH's with the same pattern. */
886 }
887 else
888 /* No pattern means remove all previous selective VPATH's. */
889 vpat = 0;
890 construct_vpath_list (vpat, p);
891 free (vpat);
892
893 continue;
894 }
895
896 /* Handle include and variants. */
897 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
898 {
899 /* We have found an 'include' line specifying a nested
900 makefile to be read at this point. */
901 struct conditionals *save;
902 struct conditionals new_conditionals;
903 struct nameseq *files;
904 /* "-include" (vs "include") says no error if the file does not
905 exist. "sinclude" is an alias for this from SGI. */
906 int noerror = (p[0] != 'i');
907
908 /* Include ends the previous rule. */
909 record_waiting_files ();
910
911 p = allocated_variable_expand (p2);
912
913 /* If no filenames, it's a no-op. */
914 if (*p == '\0')
915 {
916 free (p);
917 continue;
918 }
919
920 /* Parse the list of file names. Don't expand archive references! */
921 p2 = p;
922 files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
923 PARSEFS_NOAR);
924 free (p);
925
926 /* Save the state of conditionals and start
927 the included makefile with a clean slate. */
928 save = install_conditionals (&new_conditionals);
929
930 /* Record the rules that are waiting so they will determine
931 the default goal before those in the included makefile. */
932 record_waiting_files ();
933
934 /* Read each included makefile. */
935 while (files != 0)
936 {
937 struct nameseq *next = files->next;
938 unsigned short flags = (RM_INCLUDED | RM_NO_TILDE
939 | (noerror ? RM_DONTCARE : 0)
940 | (set_default ? 0 : RM_NO_DEFAULT_GOAL));
941
942 struct goaldep *d = eval_makefile (files->name, flags);
943
944 if (errno)
945 d->floc = *fstart;
946
947 free_ns (files);
948 files = next;
949 }
950
951 /* Restore conditional state. */
952 restore_conditionals (save);
953
954 continue;
955 }
956
957 /* Handle the load operations. */
958 if (word1eq ("load") || word1eq ("-load"))
959 {
960 /* A 'load' line specifies a dynamic object to load. */
961 struct nameseq *files;
962 int noerror = (p[0] == '-');
963
964 /* Load ends the previous rule. */
965 record_waiting_files ();
966
967 p = allocated_variable_expand (p2);
968
969 /* If no filenames, it's a no-op. */
970 if (*p == '\0')
971 {
972 free (p);
973 continue;
974 }
975
976 /* Parse the list of file names.
977 Don't expand archive references or strip "./" */
978 p2 = p;
979 files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
980 PARSEFS_NOAR);
981 free (p);
982
983 /* Load each file. */
984 while (files != 0)
985 {
986 struct nameseq *next = files->next;
987 const char *name = files->name;
988 struct goaldep *deps;
989 int r;
990
991 /* Load the file. 0 means failure. */
992 r = load_file (&ebuf->floc, &name, noerror);
993 if (! r && ! noerror)
994 OS (fatal, &ebuf->floc, _("%s: failed to load"), name);
995
996 free_ns (files);
997 files = next;
998
999 /* Return of -1 means a special load: don't rebuild it. */
1000 if (r == -1)
1001 continue;
1002
1003 /* It succeeded, so add it to the list "to be rebuilt". */
1004 deps = alloc_goaldep ();
1005 deps->next = read_makefiles;
1006 read_makefiles = deps;
1007 deps->file = lookup_file (name);
1008 if (deps->file == 0)
1009 deps->file = enter_file (name);
1010 deps->file->loaded = 1;
1011 }
1012
1013 continue;
1014 }
1015
1016 /* This line starts with a tab but was not caught above because there
1017 was no preceding target, and the line might have been usable as a
1018 variable definition. But now we know it is definitely lossage. */
1019 if (line[0] == cmd_prefix)
1020 O (fatal, fstart, _("recipe commences before first target"));
1021
1022 /* This line describes some target files. This is complicated by
1023 the existence of target-specific variables, because we can't
1024 expand the entire line until we know if we have one or not. So
1025 we expand the line word by word until we find the first ':',
1026 then check to see if it's a target-specific variable.
1027
1028 In this algorithm, 'lb_next' will point to the beginning of the
1029 unexpanded parts of the input buffer, while 'p2' points to the
1030 parts of the expanded buffer we haven't searched yet. */
1031
1032 {
1033 enum make_word_type wtype;
1034 char *cmdleft, *semip, *lb_next;
1035 size_t plen = 0;
1036 char *colonp;
1037 const char *end, *beg; /* Helpers for whitespace stripping. */
1038
1039 /* Record the previous rule. */
1040
1041 record_waiting_files ();
1042 tgts_started = fstart->lineno;
1043
1044 /* Search the line for an unquoted ; that is not after an
1045 unquoted #. */
1046 cmdleft = find_map_unquote (line, MAP_SEMI|MAP_COMMENT|MAP_VARIABLE);
1047 if (cmdleft != 0 && *cmdleft == '#')
1048 {
1049 /* We found a comment before a semicolon. */
1050 *cmdleft = '\0';
1051 cmdleft = 0;
1052 }
1053 else if (cmdleft != 0)
1054 /* Found one. Cut the line short there before expanding it. */
1055 *(cmdleft++) = '\0';
1056 semip = cmdleft;
1057
1058 collapse_continuations (line);
1059
1060 /* We can't expand the entire line, since if it's a per-target
1061 variable we don't want to expand it. So, walk from the
1062 beginning, expanding as we go, and looking for "interesting"
1063 chars. The first word is always expandable. */
1064 wtype = get_next_mword (line, &lb_next, &wlen);
1065 switch (wtype)
1066 {
1067 case w_eol:
1068 if (cmdleft != 0)
1069 O (fatal, fstart, _("missing rule before recipe"));
1070 /* This line contained something but turned out to be nothing
1071 but whitespace (a comment?). */
1072 continue;
1073
1074 case w_colon:
1075 case w_dcolon:
1076 case w_ampcolon:
1077 case w_ampdcolon:
1078 /* We accept and ignore rules without targets for
1079 compatibility with SunOS 4 make. */
1080 no_targets = 1;
1081 continue;
1082
1083 default:
1084 break;
1085 }
1086
1087 p2 = variable_expand_string (NULL, lb_next, wlen);
1088
1089 while (1)
1090 {
1091 lb_next += wlen;
1092 if (cmdleft == 0)
1093 {
1094 /* Look for a semicolon in the expanded line. */
1095 cmdleft = find_char_unquote (p2, ';');
1096
1097 if (cmdleft != 0)
1098 {
1099 size_t p2_off = p2 - variable_buffer;
1100 size_t cmd_off = cmdleft - variable_buffer;
1101 char *pend = p2 + strlen (p2);
1102
1103 /* Append any remnants of lb, then cut the line short
1104 at the semicolon. */
1105 *cmdleft = '\0';
1106
1107 /* One school of thought says that you shouldn't expand
1108 here, but merely copy, since now you're beyond a ";"
1109 and into a command script. However, the old parser
1110 expanded the whole line, so we continue that for
1111 backwards-compatibility. Also, it wouldn't be
1112 entirely consistent, since we do an unconditional
1113 expand below once we know we don't have a
1114 target-specific variable. */
1115 variable_expand_string (pend, lb_next, SIZE_MAX);
1116 lb_next += strlen (lb_next);
1117 p2 = variable_buffer + p2_off;
1118 cmdleft = variable_buffer + cmd_off + 1;
1119 }
1120 }
1121
1122 colonp = find_char_unquote (p2, ':');
1123
1124 #ifdef HAVE_DOS_PATHS
1125 if (colonp > p2)
1126 /* The drive spec brain-damage strikes again...
1127 Note that the only separators of targets in this context are
1128 whitespace and a left paren. If others are possible, add them
1129 to the string in the call to strchr. */
1130 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
1131 isalpha ((unsigned char) colonp[-1]) &&
1132 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1133 colonp = find_char_unquote (colonp + 1, ':');
1134 #endif
1135
1136 if (colonp)
1137 {
1138 /* If the previous character is '&', back up before '&:' */
1139 if (colonp > p2 && colonp[-1] == '&')
1140 --colonp;
1141
1142 break;
1143 }
1144
1145 wtype = get_next_mword (lb_next, &lb_next, &wlen);
1146 if (wtype == w_eol)
1147 break;
1148
1149 p2 += strlen (p2);
1150 *(p2++) = ' ';
1151 p2 = variable_expand_string (p2, lb_next, wlen);
1152 /* We don't need to worry about cmdleft here, because if it was
1153 found in the variable_buffer the entire buffer has already
1154 been expanded... we'll never get here. */
1155 }
1156
1157 p2 = next_token (variable_buffer);
1158
1159 /* If the word we're looking at is EOL, see if there's _anything_
1160 on the line. If not, a variable expanded to nothing, so ignore
1161 it. If so, we can't parse this line so punt. */
1162 if (wtype == w_eol)
1163 {
1164 if (*p2 == '\0')
1165 continue;
1166
1167 /* There's no need to be ivory-tower about this: check for
1168 one of the most common bugs found in makefiles... */
1169 if (cmd_prefix == '\t' && strneq (line, " ", 8))
1170 O (fatal, fstart, _("missing separator (did you mean TAB instead of 8 spaces?)"));
1171 else
1172 O (fatal, fstart, _("missing separator"));
1173 }
1174
1175 {
1176 char save = *colonp;
1177
1178 /* If we have &:, it specifies that the targets are understood to be
1179 updated/created together by a single invocation of the recipe. */
1180 if (save == '&')
1181 also_make_targets = 1;
1182
1183 /* Make the colon the end-of-string so we know where to stop
1184 looking for targets. Start there again once we're done. */
1185 *colonp = '\0';
1186 filenames = PARSE_SIMPLE_SEQ (&p2, struct nameseq);
1187 *colonp = save;
1188 p2 = colonp + (save == '&');
1189 }
1190
1191 if (!filenames)
1192 {
1193 /* We accept and ignore rules without targets for
1194 compatibility with SunOS 4 make. */
1195 no_targets = 1;
1196 continue;
1197 }
1198 /* This should never be possible; we handled it above. */
1199 assert (*p2 != '\0');
1200 ++p2;
1201
1202 /* Is this a one-colon or two-colon entry? */
1203 two_colon = *p2 == ':';
1204 if (two_colon)
1205 p2++;
1206
1207 /* Test to see if it's a target-specific variable. Copy the rest
1208 of the buffer over, possibly temporarily (we'll expand it later
1209 if it's not a target-specific variable). PLEN saves the length
1210 of the unparsed section of p2, for later. */
1211 if (*lb_next != '\0')
1212 {
1213 size_t l = p2 - variable_buffer;
1214 plen = strlen (p2);
1215 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1216 p2 = variable_buffer + l;
1217 }
1218
1219 p2 = parse_var_assignment (p2, &vmod);
1220 if (vmod.assign_v)
1221 {
1222 /* If there was a semicolon found, add it back, plus anything
1223 after it. */
1224 if (semip)
1225 {
1226 size_t l = p2 - variable_buffer;
1227 *(--semip) = ';';
1228 collapse_continuations (semip);
1229 variable_buffer_output (p2 + strlen (p2),
1230 semip, strlen (semip)+1);
1231 p2 = variable_buffer + l;
1232 }
1233 record_target_var (filenames, p2,
1234 vmod.override_v ? o_override : o_file,
1235 &vmod, fstart);
1236 filenames = 0;
1237 continue;
1238 }
1239
1240 /* This is a normal target, _not_ a target-specific variable.
1241 Unquote any = in the dependency list. */
1242 find_char_unquote (lb_next, '=');
1243
1244 /* Remember the command prefix for this target. */
1245 prefix = cmd_prefix;
1246
1247 /* We have some targets, so don't ignore the following commands. */
1248 no_targets = 0;
1249
1250 /* Expand the dependencies, etc. */
1251 if (*lb_next != '\0')
1252 {
1253 size_t l = p2 - variable_buffer;
1254 variable_expand_string (p2 + plen, lb_next, SIZE_MAX);
1255 p2 = variable_buffer + l;
1256
1257 /* Look for a semicolon in the expanded line. */
1258 if (cmdleft == 0)
1259 {
1260 cmdleft = find_char_unquote (p2, ';');
1261 if (cmdleft != 0)
1262 *(cmdleft++) = '\0';
1263 }
1264 }
1265
1266 /* Is this a static pattern rule: 'target: %targ: %dep; ...'? */
1267 p = strchr (p2, ':');
1268 while (p != 0 && p[-1] == '\\')
1269 {
1270 char *q = &p[-1];
1271 int backslash = 0;
1272 while (*q-- == '\\')
1273 backslash = !backslash;
1274 if (backslash)
1275 p = strchr (p + 1, ':');
1276 else
1277 break;
1278 }
1279 #ifdef HAVE_DOS_PATHS
1280 {
1281 int check_again;
1282 do {
1283 check_again = 0;
1284 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1285 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1286 isalpha ((unsigned char)p[-1]) &&
1287 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1288 p = strchr (p + 1, ':');
1289 check_again = 1;
1290 }
1291 } while (check_again);
1292 }
1293 #endif
1294 if (p != 0)
1295 {
1296 struct nameseq *target;
1297 target = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_COLON, NULL,
1298 PARSEFS_NOGLOB);
1299 ++p2;
1300 if (target == 0)
1301 O (fatal, fstart, _("missing target pattern"));
1302 else if (target->next != 0)
1303 O (fatal, fstart, _("multiple target patterns"));
1304 pattern_percent = find_percent_cached (&target->name);
1305 pattern = target->name;
1306 if (pattern_percent == 0)
1307 O (fatal, fstart, _("target pattern contains no '%%'"));
1308 free_ns (target);
1309 }
1310 else
1311 pattern = 0;
1312
1313 /* Strip leading and trailing whitespaces. */
1314 beg = p2;
1315 end = beg + strlen (beg) - 1;
1316 strip_whitespace (&beg, &end);
1317
1318 /* Put all the prerequisites here; they'll be parsed later. */
1319 if (beg <= end && *beg != '\0')
1320 depstr = xstrndup (beg, end - beg + 1);
1321 else
1322 depstr = 0;
1323
1324 commands_idx = 0;
1325 if (cmdleft != 0)
1326 {
1327 /* Semicolon means rest of line is a command. */
1328 size_t l = strlen (cmdleft);
1329
1330 cmds_started = fstart->lineno;
1331
1332 /* Add this command line to the buffer. */
1333 if (l + 2 > commands_len)
1334 {
1335 commands_len = (l + 2) * 2;
1336 commands = xrealloc (commands, commands_len);
1337 }
1338 memcpy (commands, cmdleft, l);
1339 commands_idx += l;
1340 commands[commands_idx++] = '\n';
1341 }
1342
1343 /* Determine if this target should be made default. We used to do
1344 this in record_files() but because of the delayed target recording
1345 and because preprocessor directives are legal in target's commands
1346 it is too late. Consider this fragment for example:
1347
1348 foo:
1349
1350 ifeq ($(.DEFAULT_GOAL),foo)
1351 ...
1352 endif
1353
1354 Because the target is not recorded until after ifeq directive is
1355 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1356 would expect. Because of this we have to move the logic here. */
1357
1358 if (set_default && default_goal_var->value[0] == '\0')
1359 {
1360 struct dep *d;
1361 struct nameseq *t = filenames;
1362
1363 for (; t != 0; t = t->next)
1364 {
1365 int reject = 0;
1366 const char *name = t->name;
1367
1368 /* We have nothing to do if this is an implicit rule. */
1369 if (strchr (name, '%') != 0)
1370 break;
1371
1372 /* See if this target's name does not start with a '.',
1373 unless it contains a slash. */
1374 if (*name == '.' && strchr (name, '/') == 0
1375 #ifdef HAVE_DOS_PATHS
1376 && strchr (name, '\\') == 0
1377 #endif
1378 )
1379 continue;
1380
1381
1382 /* If this file is a suffix, don't let it be
1383 the default goal file. */
1384 for (d = suffix_file->deps; d != 0; d = d->next)
1385 {
1386 struct dep *d2;
1387 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1388 {
1389 reject = 1;
1390 break;
1391 }
1392 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1393 {
1394 size_t l = strlen (dep_name (d2));
1395 if (!strneq (name, dep_name (d2), l))
1396 continue;
1397 if (streq (name + l, dep_name (d)))
1398 {
1399 reject = 1;
1400 break;
1401 }
1402 }
1403
1404 if (reject)
1405 break;
1406 }
1407
1408 if (!reject)
1409 {
1410 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1411 o_file, 0, NILF);
1412 break;
1413 }
1414 }
1415 }
1416 }
1417 }
1418
1419 #undef word1eq
1420
1421 if (conditionals->if_cmds)
1422 O (fatal, fstart, _("missing 'endif'"));
1423
1424 /* At eof, record the last rule. */
1425 record_waiting_files ();
1426
1427 free (collapsed);
1428 free (commands);
1429 }
1430
1431
1432 /* Remove comments from LINE.
1433 This will also remove backslashes that escape things.
1434 It ignores comment characters that appear inside variable references. */
1435
1436 static void
1437 remove_comments (char *line, char **target_description,
1438 char **prev_target_description, unsigned long lineno)
1439 {
1440 char *comment;
1441
1442 comment = find_map_unquote (line, MAP_COMMENT|MAP_VARIABLE);
1443
1444 if (comment != 0) {
1445 if (0 == strncmp(comment, "#: ", 3) && target_description) {
1446 *prev_target_description = *target_description;
1447 prev_target_description_lineno = target_description_lineno;
1448 *target_description = xstrdup(&comment[3]);
1449 target_description_lineno = lineno;
1450 }
1451 /* Cut off the line at the #. */
1452 *comment = '\0';
1453 }
1454 }
1455
1456 /* Execute a 'undefine' directive.
1457 The undefine line has already been read, and NAME is the name of
1458 the variable to be undefined. */
1459
1460 static void
1461 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1462 {
1463 char *p, *var;
1464
1465 /* Expand the variable name and find the beginning (NAME) and end. */
1466 var = allocated_variable_expand (name);
1467 name = next_token (var);
1468 if (*name == '\0')
1469 O (fatal, &ebuf->floc, _("empty variable name"));
1470 p = name + strlen (name) - 1;
1471 while (p > name && ISBLANK (*p))
1472 --p;
1473 p[1] = '\0';
1474
1475 undefine_variable_global (name, p - name + 1, origin);
1476 free (var);
1477 }
1478
1479 /* Execute a 'define' directive.
1480 The first line has already been read, and NAME is the name of
1481 the variable to be defined. The following lines remain to be read. */
1482
1483 static struct variable *
1484 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1485 {
1486 struct variable *v;
1487 struct variable var;
1488 gmk_floc defstart;
1489 int nlevels = 1;
1490 size_t length = 100;
1491 char *definition = xmalloc (length);
1492 size_t idx = 0;
1493 char *p, *n;
1494
1495 defstart = ebuf->floc;
1496
1497 p = parse_variable_definition (name, &var);
1498 if (p == NULL)
1499 /* No assignment token, so assume recursive. */
1500 var.flavor = f_recursive;
1501 else
1502 {
1503 if (var.value[0] != '\0')
1504 O (error, &defstart, _("extraneous text after 'define' directive"));
1505
1506 /* Chop the string before the assignment token to get the name. */
1507 var.name[var.length] = '\0';
1508 }
1509
1510 /* Expand the variable name and find the beginning (NAME) and end. */
1511 n = allocated_variable_expand (name);
1512 name = next_token (n);
1513 if (name[0] == '\0')
1514 O (fatal, &defstart, _("empty variable name"));
1515 p = name + strlen (name) - 1;
1516 while (p > name && ISBLANK (*p))
1517 --p;
1518 p[1] = '\0';
1519
1520 /* Now read the value of the variable. */
1521 while (1)
1522 {
1523 size_t len;
1524 char *line;
1525 long nlines = readline (ebuf);
1526
1527 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1528 if (nlines < 0)
1529 O (fatal, &defstart, _("missing 'endef', unterminated 'define'"));
1530
1531 ebuf->floc.lineno += nlines;
1532 line = ebuf->buffer;
1533
1534 collapse_continuations (line);
1535
1536 /* If the line doesn't begin with a tab, test to see if it introduces
1537 another define, or ends one. Stop if we find an 'endef' */
1538 if (line[0] != cmd_prefix)
1539 {
1540 p = next_token (line);
1541 len = strlen (p);
1542
1543 /* If this is another 'define', increment the level count. */
1544 if ((len == 6 || (len > 6 && ISBLANK (p[6])))
1545 && strneq (p, "define", 6))
1546 ++nlevels;
1547
1548 /* If this is an 'endef', decrement the count. If it's now 0,
1549 we've found the last one. */
1550 else if ((len == 5 || (len > 5 && ISBLANK (p[5])))
1551 && strneq (p, "endef", 5))
1552 {
1553 p += 5;
1554 remove_comments (p, NULL, NULL, 0);
1555 if (*(next_token (p)) != '\0')
1556 O (error, &ebuf->floc,
1557 _("extraneous text after 'endef' directive"));
1558
1559 if (--nlevels == 0)
1560 break;
1561 }
1562 }
1563
1564 /* Add this line to the variable definition. */
1565 len = strlen (line);
1566 if (idx + len + 1 > length)
1567 {
1568 length = (idx + len) * 2;
1569 definition = xrealloc (definition, length + 1);
1570 }
1571
1572 memcpy (&definition[idx], line, len);
1573 idx += len;
1574 /* Separate lines with a newline. */
1575 definition[idx++] = '\n';
1576 }
1577
1578 /* We've got what we need; define the variable. */
1579 if (idx == 0)
1580 definition[0] = '\0';
1581 else
1582 definition[idx - 1] = '\0';
1583
1584 v = do_variable_definition (&defstart, name,
1585 definition, origin, var.flavor, 0);
1586 free (definition);
1587 free (n);
1588 return (v);
1589 }
1590
1591 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1592 "ifneq", "else" and "endif".
1593 LINE is the input line, with the command as its first word.
1594
1595 FILENAME and LINENO are the filename and line number in the
1596 current makefile. They are used for error messages.
1597
1598 Value is -2 if the line is not a conditional at all,
1599 -1 if the line is an invalid conditional,
1600 0 if following text should be interpreted,
1601 1 if following text should be ignored. */
1602
1603 static int
1604 conditional_line (char *line, size_t len, const gmk_floc *flocp)
1605 {
1606 const char *cmdname;
1607 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1608 unsigned int i;
1609 unsigned int o;
1610
1611 /* Compare a word, both length and contents. */
1612 #define word1eq(s) (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
1613 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1614
1615 /* Make sure this line is a conditional. */
1616 chkword ("ifdef", c_ifdef)
1617 else chkword ("ifndef", c_ifndef)
1618 else chkword ("ifeq", c_ifeq)
1619 else chkword ("ifneq", c_ifneq)
1620 else chkword ("else", c_else)
1621 else chkword ("endif", c_endif)
1622 else
1623 return -2;
1624
1625 /* Found one: skip past it and any whitespace after it. */
1626 line += len;
1627 NEXT_TOKEN (line);
1628
1629 #define EXTRATEXT() OS (error, flocp, _("extraneous text after '%s' directive"), cmdname)
1630 #define EXTRACMD() OS (fatal, flocp, _("extraneous '%s'"), cmdname)
1631
1632 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1633 if (cmdtype == c_endif)
1634 {
1635 if (*line != '\0')
1636 EXTRATEXT ();
1637
1638 if (!conditionals->if_cmds)
1639 EXTRACMD ();
1640
1641 --conditionals->if_cmds;
1642
1643 goto DONE;
1644 }
1645
1646 /* An 'else' statement can either be simple, or it can have another
1647 conditional after it. */
1648 if (cmdtype == c_else)
1649 {
1650 const char *p;
1651
1652 if (!conditionals->if_cmds)
1653 EXTRACMD ();
1654
1655 o = conditionals->if_cmds - 1;
1656
1657 if (conditionals->seen_else[o])
1658 O (fatal, flocp, _("only one 'else' per conditional"));
1659
1660 /* Change the state of ignorance. */
1661 switch (conditionals->ignoring[o])
1662 {
1663 case 0:
1664 /* We've just been interpreting. Never do it again. */
1665 conditionals->ignoring[o] = 2;
1666 break;
1667 case 1:
1668 /* We've never interpreted yet. Maybe this time! */
1669 conditionals->ignoring[o] = 0;
1670 break;
1671 }
1672
1673 /* It's a simple 'else'. */
1674 if (*line == '\0')
1675 {
1676 conditionals->seen_else[o] = 1;
1677 goto DONE;
1678 }
1679
1680 /* The 'else' has extra text. That text must be another conditional
1681 and cannot be an 'else' or 'endif'. */
1682
1683 /* Find the length of the next word. */
1684 for (p = line+1; ! STOP_SET (*p, MAP_SPACE|MAP_NUL); ++p)
1685 ;
1686 len = p - line;
1687
1688 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1689 if (word1eq ("else") || word1eq ("endif")
1690 || conditional_line (line, len, flocp) < 0)
1691 EXTRATEXT ();
1692 else
1693 {
1694 /* conditional_line() created a new level of conditional.
1695 Raise it back to this level. */
1696 if (conditionals->ignoring[o] < 2)
1697 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1698 --conditionals->if_cmds;
1699 }
1700
1701 goto DONE;
1702 }
1703
1704 if (conditionals->allocated == 0)
1705 {
1706 conditionals->allocated = 5;
1707 conditionals->ignoring = xmalloc (conditionals->allocated);
1708 conditionals->seen_else = xmalloc (conditionals->allocated);
1709 }
1710
1711 o = conditionals->if_cmds++;
1712 if (conditionals->if_cmds > conditionals->allocated)
1713 {
1714 conditionals->allocated += 5;
1715 conditionals->ignoring = xrealloc (conditionals->ignoring,
1716 conditionals->allocated);
1717 conditionals->seen_else = xrealloc (conditionals->seen_else,
1718 conditionals->allocated);
1719 }
1720
1721 /* Record that we have seen an 'if...' but no 'else' so far. */
1722 conditionals->seen_else[o] = 0;
1723
1724 /* Search through the stack to see if we're already ignoring. */
1725 for (i = 0; i < o; ++i)
1726 if (conditionals->ignoring[i])
1727 {
1728 /* We are already ignoring, so just push a level to match the next
1729 "else" or "endif", and keep ignoring. We don't want to expand
1730 variables in the condition. */
1731 conditionals->ignoring[o] = 1;
1732 return 1;
1733 }
1734
1735 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1736 {
1737 size_t l;
1738 char *var;
1739 struct variable *v;
1740 char *p;
1741
1742 /* Expand the thing we're looking up, so we can use indirect and
1743 constructed variable names. */
1744 var = allocated_variable_expand (line);
1745
1746 /* Make sure there's only one variable name to test. */
1747 p = end_of_token (var);
1748 l = p - var;
1749 NEXT_TOKEN (p);
1750 if (*p != '\0')
1751 return -1;
1752
1753 var[l] = '\0';
1754 v = lookup_variable (var, l);
1755
1756 conditionals->ignoring[o] =
1757 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1758
1759 free (var);
1760 }
1761 else
1762 {
1763 /* "ifeq" or "ifneq". */
1764 char *s1, *s2;
1765 size_t l;
1766 char termin = *line == '(' ? ',' : *line;
1767
1768 if (termin != ',' && termin != '"' && termin != '\'')
1769 return -1;
1770
1771 s1 = ++line;
1772 /* Find the end of the first string. */
1773 if (termin == ',')
1774 {
1775 int count = 0;
1776 for (; *line != '\0'; ++line)
1777 if (*line == '(')
1778 ++count;
1779 else if (*line == ')')
1780 --count;
1781 else if (*line == ',' && count <= 0)
1782 break;
1783 }
1784 else
1785 while (*line != '\0' && *line != termin)
1786 ++line;
1787
1788 if (*line == '\0')
1789 return -1;
1790
1791 if (termin == ',')
1792 {
1793 /* Strip blanks after the first string. */
1794 char *p = line++;
1795 while (ISBLANK (p[-1]))
1796 --p;
1797 *p = '\0';
1798 }
1799 else
1800 *line++ = '\0';
1801
1802 s2 = variable_expand (s1);
1803 /* We must allocate a new copy of the expanded string because
1804 variable_expand re-uses the same buffer. */
1805 l = strlen (s2);
1806 s1 = alloca (l + 1);
1807 memcpy (s1, s2, l + 1);
1808
1809 if (termin != ',')
1810 /* Find the start of the second string. */
1811 NEXT_TOKEN (line);
1812
1813 termin = termin == ',' ? ')' : *line;
1814 if (termin != ')' && termin != '"' && termin != '\'')
1815 return -1;
1816
1817 /* Find the end of the second string. */
1818 if (termin == ')')
1819 {
1820 int count = 0;
1821 s2 = next_token (line);
1822 for (line = s2; *line != '\0'; ++line)
1823 {
1824 if (*line == '(')
1825 ++count;
1826 else if (*line == ')')
1827 {
1828 if (count <= 0)
1829 break;
1830 else
1831 --count;
1832 }
1833 }
1834 }
1835 else
1836 {
1837 ++line;
1838 s2 = line;
1839 while (*line != '\0' && *line != termin)
1840 ++line;
1841 }
1842
1843 if (*line == '\0')
1844 return -1;
1845
1846 *(line++) = '\0';
1847 NEXT_TOKEN (line);
1848 if (*line != '\0')
1849 EXTRATEXT ();
1850
1851 s2 = variable_expand (s2);
1852 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1853 }
1854
1855 DONE:
1856 /* Search through the stack to see if we're ignoring. */
1857 for (i = 0; i < conditionals->if_cmds; ++i)
1858 if (conditionals->ignoring[i])
1859 return 1;
1860 return 0;
1861 }
1862
1863
1864 /* Record target-specific variable values for files FILENAMES.
1865 TWO_COLON is nonzero if a double colon was used.
1866
1867 The links of FILENAMES are freed, and so are any names in it
1868 that are not incorporated into other data structures.
1869
1870 If the target is a pattern, add the variable to the pattern-specific
1871 variable value list. */
1872
1873 static void
1874 record_target_var (struct nameseq *filenames, char *defn,
1875 enum variable_origin origin, struct vmodifiers *vmod,
1876 const gmk_floc *flocp)
1877 {
1878 struct nameseq *nextf;
1879 struct variable_set_list *global;
1880
1881 global = current_variable_set_list;
1882
1883 /* If the variable is an append version, store that but treat it as a
1884 normal recursive variable. */
1885
1886 for (; filenames != 0; filenames = nextf)
1887 {
1888 struct variable *v;
1889 const char *name = filenames->name;
1890 const char *percent;
1891 struct pattern_var *p;
1892
1893 nextf = filenames->next;
1894 free_ns (filenames);
1895
1896 /* If it's a pattern target, then add it to the pattern-specific
1897 variable list. */
1898 percent = find_percent_cached (&name);
1899 if (percent)
1900 {
1901 /* Get a reference for this pattern-specific variable struct. */
1902 p = create_pattern_var (name, percent);
1903 p->variable.fileinfo = *flocp;
1904 /* I don't think this can fail since we already determined it was a
1905 variable definition. */
1906 v = assign_variable_definition (&p->variable, defn);
1907 assert (v != 0);
1908
1909 v->origin = origin;
1910 if (v->flavor == f_simple)
1911 v->value = allocated_variable_expand (v->value);
1912 else
1913 v->value = xstrdup (v->value);
1914 }
1915 else
1916 {
1917 struct file *f;
1918
1919 /* Get a file reference for this file, and initialize it.
1920 We don't want to just call enter_file() because that allocates a
1921 new entry if the file is a double-colon, which we don't want in
1922 this situation. */
1923 f = lookup_file (name);
1924 if (!f)
1925 f = enter_file (strcache_add (name));
1926 else if (f->double_colon)
1927 f = f->double_colon;
1928
1929 initialize_file_variables (f, 1);
1930
1931 current_variable_set_list = f->variables;
1932 v = try_variable_definition (flocp, defn, origin, 1);
1933 if (!v)
1934 O (fatal, flocp, _("Malformed target-specific variable definition"));
1935 current_variable_set_list = global;
1936 }
1937
1938 /* Set up the variable to be *-specific. */
1939 v->per_target = 1;
1940 v->private_var = vmod->private_v;
1941 v->export = vmod->export_v ? v_export : v_default;
1942
1943 /* If it's not an override, check to see if there was a command-line
1944 setting. If so, reset the value. */
1945 if (v->origin != o_override)
1946 {
1947 struct variable *gv;
1948 size_t len = strlen (v->name);
1949
1950 gv = lookup_variable (v->name, len);
1951 if (gv && v != gv
1952 && (gv->origin == o_env_override || gv->origin == o_command))
1953 {
1954 free (v->value);
1955 v->value = xstrdup (gv->value);
1956 v->origin = gv->origin;
1957 v->recursive = gv->recursive;
1958 v->append = 0;
1959 }
1960 }
1961 }
1962 }
1963
1964 /* Record a description line for files FILENAMES,
1965 with dependencies DEPS, commands to execute described
1966 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1967 TWO_COLON is nonzero if a double colon was used.
1968 If not nil, PATTERN is the '%' pattern to make this
1969 a static pattern rule, and PATTERN_PERCENT is a pointer
1970 to the '%' within it.
1971
1972 The links of FILENAMES are freed, and so are any names in it
1973 that are not incorporated into other data structures. */
1974
1975 static void
1976 record_files (struct nameseq *filenames, int are_also_makes,
1977 const char *pattern,
1978 const char *pattern_percent, char *depstr,
1979 unsigned int cmds_started, char *commands,
1980 size_t commands_idx, int two_colon,
1981 char *target_description,
1982 char prefix, const gmk_floc *flocp)
1983 {
1984 struct commands *cmds;
1985 struct dep *deps;
1986 struct dep *also_make = NULL;
1987 const char *implicit_percent;
1988 const char *name;
1989
1990 /* If we've already snapped deps, that means we're in an eval being
1991 resolved after the makefiles have been read in. We can't add more rules
1992 at this time, since they won't get snapped and we'll get core dumps.
1993 See Savannah bug # 12124. */
1994 if (snapped_deps)
1995 O (fatal, flocp, _("prerequisites cannot be defined in recipes"));
1996
1997 /* Determine if this is a pattern rule or not. */
1998 name = filenames->name;
1999 implicit_percent = find_percent_cached (&name);
2000
2001 /* If there's a recipe, set up a struct for it. */
2002 if (commands_idx > 0)
2003 {
2004 cmds = xmalloc (sizeof (struct commands));
2005 cmds->fileinfo.filenm = flocp->filenm;
2006 cmds->fileinfo.lineno = cmds_started;
2007 cmds->fileinfo.offset = 0;
2008 cmds->commands = xstrndup (commands, commands_idx);
2009 cmds->command_lines = 0;
2010 cmds->recipe_prefix = prefix;
2011 }
2012 else if (are_also_makes)
2013 O (fatal, flocp, _("grouped targets must provide a recipe"));
2014 else
2015 cmds = NULL;
2016
2017 /* If there's a prereq string then parse it--unless it's eligible for 2nd
2018 expansion: if so, snap_deps() will do it. */
2019 if (depstr == 0)
2020 deps = 0;
2021 else
2022 {
2023 depstr = unescape_char (depstr, ':');
2024 if (second_expansion && strchr (depstr, '$'))
2025 {
2026 deps = alloc_dep ();
2027 deps->name = depstr;
2028 deps->need_2nd_expansion = 1;
2029 deps->staticpattern = pattern != 0;
2030 }
2031 else
2032 {
2033 deps = split_prereqs (depstr);
2034 free (depstr);
2035
2036 /* We'll enter static pattern prereqs later when we have the stem.
2037 We don't want to enter pattern rules at all so that we don't
2038 think that they ought to exist (make manual "Implicit Rule Search
2039 Algorithm", item 5c). */
2040 if (! pattern && ! implicit_percent)
2041 deps = enter_prereqs (deps, NULL);
2042 }
2043 }
2044
2045 /* For implicit rules, _all_ the targets must have a pattern. That means we
2046 can test the first one to see if we're working with an implicit rule; if
2047 so we handle it specially. */
2048
2049 if (implicit_percent)
2050 {
2051 struct nameseq *nextf;
2052 const char **targets, **target_pats;
2053 unsigned short c;
2054
2055 if (pattern != 0)
2056 O (fatal, flocp, _("mixed implicit and static pattern rules"));
2057
2058 /* Count the targets to create an array of target names.
2059 We already have the first one. */
2060 nextf = filenames->next;
2061 free_ns (filenames);
2062 filenames = nextf;
2063
2064 for (c = 1; nextf; ++c, nextf = nextf->next)
2065 ;
2066 targets = xmalloc (c * sizeof (const char *));
2067 target_pats = xmalloc (c * sizeof (const char *));
2068
2069 targets[0] = name;
2070 target_pats[0] = implicit_percent;
2071
2072 c = 1;
2073 while (filenames)
2074 {
2075 name = filenames->name;
2076 implicit_percent = find_percent_cached (&name);
2077
2078 if (implicit_percent == 0)
2079 O (fatal, flocp, _("mixed implicit and normal rules"));
2080
2081 targets[c] = name;
2082 target_pats[c] = implicit_percent;
2083 ++c;
2084
2085 nextf = filenames->next;
2086 free_ns (filenames);
2087 filenames = nextf;
2088 }
2089
2090 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
2091
2092 return;
2093 }
2094
2095
2096 /* Walk through each target and create it in the database.
2097 We already set up the first target, above. */
2098 while (1)
2099 {
2100 struct nameseq *nextf = filenames->next;
2101 struct file *f;
2102 struct dep *this = 0;
2103
2104 free_ns (filenames);
2105
2106 /* Check for special targets. Do it here instead of, say, snap_deps()
2107 so that we can immediately use the value. */
2108 if (!posix_pedantic && streq (name, ".POSIX"))
2109 {
2110 posix_pedantic = 1;
2111 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
2112 /* These default values are based on IEEE Std 1003.1-2008.
2113 It requires '-O 1' for [CF]FLAGS, but GCC doesn't allow space
2114 between -O and the number so omit it here. */
2115 define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
2116 define_variable_cname ("CC", "c99", o_default, 0);
2117 define_variable_cname ("CFLAGS", "-O1", o_default, 0);
2118 define_variable_cname ("FC", "fort77", o_default, 0);
2119 define_variable_cname ("FFLAGS", "-O1", o_default, 0);
2120 define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
2121 }
2122 else if (!second_expansion && streq (name, ".SECONDEXPANSION"))
2123 second_expansion = 1;
2124 else if (!one_shell && streq (name, ".ONESHELL"))
2125 one_shell = 1;
2126
2127 /* If this is a static pattern rule:
2128 'targets: target%pattern: prereq%pattern; recipe',
2129 make sure the pattern matches this target name. */
2130 if (pattern && !pattern_matches (pattern, pattern_percent, name))
2131 OS (error, flocp,
2132 _("target '%s' doesn't match the target pattern"), name);
2133 else if (deps)
2134 /* If there are multiple targets, copy the chain DEPS for all but the
2135 last one. It is not safe for the same deps to go in more than one
2136 place in the database. */
2137 this = nextf != 0 ? copy_dep_chain (deps) : deps;
2138
2139 /* Find or create an entry in the file database for this target. */
2140 if (!two_colon)
2141 {
2142 /* Single-colon. Combine this rule with the file's existing record,
2143 if any. */
2144 f = enter_file (strcache_add (name));
2145 f->description = target_description;
2146 f->floc.filenm = flocp->filenm;
2147 f->floc.lineno = flocp->lineno;
2148
2149 if (f->double_colon)
2150 OS (fatal, flocp,
2151 _("target file '%s' has both : and :: entries"), f->name);
2152
2153 /* If CMDS == F->CMDS, this target was listed in this rule
2154 more than once. Just give a warning since this is harmless. */
2155 if (cmds != 0 && cmds == f->cmds)
2156 OS (error, flocp,
2157 _("target '%s' given more than once in the same rule"),
2158 f->name);
2159
2160 /* Check for two single-colon entries both with commands.
2161 Check is_target so that we don't lose on files such as .c.o
2162 whose commands were preinitialized. */
2163 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2164 {
2165 size_t l = strlen (f->name);
2166 error (&cmds->fileinfo, l,
2167 _("warning: overriding recipe for target '%s'"),
2168 f->name);
2169 error (&f->cmds->fileinfo, l,
2170 _("warning: ignoring old recipe for target '%s'"),
2171 f->name);
2172 }
2173
2174 /* Defining .DEFAULT with no deps or cmds clears it. */
2175 if (f == default_file && this == 0 && cmds == 0)
2176 f->cmds = 0;
2177 if (cmds != 0)
2178 f->cmds = cmds;
2179
2180 /* Defining .SUFFIXES with no dependencies clears out the list of
2181 suffixes. */
2182 if (f == suffix_file && this == 0)
2183 {
2184 free_dep_chain (f->deps);
2185 f->deps = 0;
2186 }
2187 }
2188 else
2189 {
2190 /* Double-colon. Make a new record even if there already is one. */
2191 f = lookup_file (name);
2192
2193 /* Check for both : and :: rules. Check is_target so we don't lose
2194 on default suffix rules or makefiles. */
2195 if (f != 0 && f->is_target && !f->double_colon)
2196 OS (fatal, flocp,
2197 _("target file '%s' has both : and :: entries"), f->name);
2198
2199 f = enter_file (strcache_add (name));
2200 f->description = target_description;
2201 f->floc.filenm = flocp->filenm;
2202 f->floc.lineno = flocp->lineno;
2203 /* If there was an existing entry and it was a double-colon entry,
2204 enter_file will have returned a new one, making it the prev
2205 pointer of the old one, and setting its double_colon pointer to
2206 the first one. */
2207 if (f->double_colon == 0)
2208 /* This is the first entry for this name, so we must set its
2209 double_colon pointer to itself. */
2210 f->double_colon = f;
2211
2212 f->cmds = cmds;
2213 }
2214
2215 if (are_also_makes)
2216 {
2217 struct dep *also = alloc_dep();
2218 also->name = f->name;
2219 also->file = f;
2220 also->next = also_make;
2221 also_make = also;
2222 }
2223
2224 f->is_target = 1;
2225
2226 /* If this is a static pattern rule, set the stem to the part of its
2227 name that matched the '%' in the pattern, so you can use $* in the
2228 commands. If we didn't do it before, enter the prereqs now. */
2229 if (pattern)
2230 {
2231 static const char *percent = "%";
2232 char *buffer = variable_expand ("");
2233 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2234 pattern_percent+1, percent+1);
2235 f->stem = strcache_add_len (buffer, o - buffer);
2236 if (this)
2237 {
2238 if (! this->need_2nd_expansion)
2239 this = enter_prereqs (this, f->stem);
2240 else
2241 this->stem = f->stem;
2242 }
2243 }
2244
2245 /* Add the dependencies to this file entry. */
2246 if (this != 0)
2247 {
2248 /* Add the file's old deps and the new ones in THIS together. */
2249 if (f->deps == 0)
2250 f->deps = this;
2251 else if (cmds != 0)
2252 {
2253 struct dep *d = this;
2254
2255 /* If this rule has commands, put these deps first. */
2256 while (d->next != 0)
2257 d = d->next;
2258
2259 d->next = f->deps;
2260 f->deps = this;
2261 }
2262 else
2263 {
2264 struct dep *d = f->deps;
2265
2266 /* A rule without commands: put its prereqs at the end. */
2267 while (d->next != 0)
2268 d = d->next;
2269
2270 d->next = this;
2271 }
2272 }
2273
2274 name = f->name;
2275
2276 /* All done! Set up for the next one. */
2277 if (nextf == 0)
2278 break;
2279
2280 filenames = nextf;
2281
2282 /* Reduce escaped percents. If there are any unescaped it's an error */
2283 name = filenames->name;
2284 if (find_percent_cached (&name))
2285 O (error, flocp,
2286 _("*** mixed implicit and normal rules: deprecated syntax"));
2287 }
2288
2289 /* If there are also-makes, then populate a copy of the also-make list into
2290 each one. For the last file, we take our original also_make list instead
2291 wastefully copying it one more time and freeing it. */
2292 {
2293 struct dep *i;
2294
2295 for (i = also_make; i != NULL; i = i->next)
2296 {
2297 struct file *f = i->file;
2298 struct dep *cpy = i->next ? copy_dep_chain (also_make) : also_make;
2299
2300 if (f->also_make)
2301 {
2302 OS (error, &cmds->fileinfo,
2303 _("warning: overriding group membership for target '%s'"),
2304 f->name);
2305 free_dep_chain (f->also_make);
2306 }
2307
2308 f->also_make = cpy;
2309 }
2310 }
2311 }
2312
2313 /* Search STRING for an unquoted STOPMAP.
2314 Backslashes quote elements from STOPMAP and backslash.
2315 Quoting backslashes are removed from STRING by compacting it into itself.
2316 Returns a pointer to the first unquoted STOPCHAR if there is one, or nil if
2317 there are none.
2318
2319 If MAP_VARIABLE is set, then the complete contents of variable references
2320 are skipped, even if the contain STOPMAP characters. */
2321
2322 static char *
2323 find_map_unquote (char *string, int stopmap)
2324 {
2325 size_t string_len = 0;
2326 char *p = string;
2327
2328 /* Always stop on NUL. */
2329 stopmap |= MAP_NUL;
2330
2331 while (1)
2332 {
2333 while (! STOP_SET (*p, stopmap))
2334 ++p;
2335
2336 if (*p == '\0')
2337 break;
2338
2339 /* If we stopped due to a variable reference, skip over its contents. */
2340 if (*p == '$')
2341 {
2342 char openparen = p[1];
2343
2344 /* Check if '$' is the last character in the string. */
2345 if (openparen == '\0')
2346 break;
2347
2348 p += 2;
2349
2350 /* Skip the contents of a non-quoted, multi-char variable ref. */
2351 if (openparen == '(' || openparen == '{')
2352 {
2353 unsigned int pcount = 1;
2354 char closeparen = (openparen == '(' ? ')' : '}');
2355
2356 while (*p)
2357 {
2358 if (*p == openparen)
2359 ++pcount;
2360 else if (*p == closeparen)
2361 if (--pcount == 0)
2362 {
2363 ++p;
2364 break;
2365 }
2366 ++p;
2367 }
2368 }
2369
2370 /* Skipped the variable reference: look for STOPCHARS again. */
2371 continue;
2372 }
2373
2374 if (p > string && p[-1] == '\\')
2375 {
2376 /* Search for more backslashes. */
2377 int i = -2;
2378 while (&p[i] >= string && p[i] == '\\')
2379 --i;
2380 ++i;
2381 /* Only compute the length if really needed. */
2382 if (string_len == 0)
2383 string_len = strlen (string);
2384 /* The number of backslashes is now -I.
2385 Copy P over itself to swallow half of them. */
2386 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2387 p += i/2;
2388 if (i % 2 == 0)
2389 /* All the backslashes quoted each other; the STOPCHAR was
2390 unquoted. */
2391 return p;
2392
2393 /* The STOPCHAR was quoted by a backslash. Look for another. */
2394 }
2395 else
2396 /* No backslash in sight. */
2397 return p;
2398 }
2399
2400 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2401 return 0;
2402 }
2403
2404 static char *
2405 find_char_unquote (char *string, int stop)
2406 {
2407 size_t string_len = 0;
2408 char *p = string;
2409
2410 while (1)
2411 {
2412 p = strchr(p, stop);
2413
2414 if (!p)
2415 return NULL;
2416
2417 if (p > string && p[-1] == '\\')
2418 {
2419 /* Search for more backslashes. */
2420 int i = -2;
2421 while (&p[i] >= string && p[i] == '\\')
2422 --i;
2423 ++i;
2424 /* Only compute the length if really needed. */
2425 if (string_len == 0)
2426 string_len = strlen (string);
2427 /* The number of backslashes is now -I.
2428 Copy P over itself to swallow half of them. */
2429 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2430 p += i/2;
2431 if (i % 2 == 0)
2432 /* All the backslashes quoted each other; the STOPCHAR was
2433 unquoted. */
2434 return p;
2435
2436 /* The STOPCHAR was quoted by a backslash. Look for another. */
2437 }
2438 else
2439 /* No backslash in sight. */
2440 return p;
2441 }
2442 }
2443
2444 /* Unescape a character in a string. The string is compressed onto itself. */
2445
2446 static char *
2447 unescape_char (char *string, int c)
2448 {
2449 char *p = string;
2450 char *s = string;
2451
2452 while (*s != '\0')
2453 {
2454 if (*s == '\\')
2455 {
2456 char *e = s;
2457 size_t l;
2458
2459 /* We found a backslash. See if it's escaping our character. */
2460 while (*e == '\\')
2461 ++e;
2462 l = e - s;
2463
2464 if (*e != c || l%2 == 0)
2465 {
2466 /* It's not; just take it all without unescaping. */
2467 memmove (p, s, l);
2468 p += l;
2469
2470 /* If we hit the end of the string, we're done. */
2471 if (*e == '\0')
2472 break;
2473 }
2474 else if (l > 1)
2475 {
2476 /* It is, and there's >1 backslash. Take half of them. */
2477 l /= 2;
2478 memmove (p, s, l);
2479 p += l;
2480 }
2481
2482 s = e;
2483 }
2484
2485 *(p++) = *(s++);
2486 }
2487
2488 *p = '\0';
2489 return string;
2490 }
2491
2492 /* Search PATTERN for an unquoted % and handle quoting. */
2493
2494 char *
2495 find_percent (char *pattern)
2496 {
2497 return find_char_unquote (pattern, '%');
2498 }
2499
2500 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2501 the % or NULL if no % was found.
2502 This version is used with strings in the string cache: if there's a need to
2503 modify the string a new version will be added to the string cache and
2504 *STRING will be set to that. */
2505
2506 const char *
2507 find_percent_cached (const char **string)
2508 {
2509 const char *p = *string;
2510 char *new = 0;
2511 size_t slen = 0;
2512
2513 /* If the first char is a % return now. This lets us avoid extra tests
2514 inside the loop. */
2515 if (*p == '%')
2516 return p;
2517
2518 while (1)
2519 {
2520 p = strchr(p, '%');
2521
2522 if (!p)
2523 break;
2524
2525 /* See if this % is escaped with a backslash; if not we're done. */
2526 if (p[-1] != '\\')
2527 break;
2528
2529 {
2530 /* Search for more backslashes. */
2531 char *pv;
2532 int i = -2;
2533
2534 while (&p[i] >= *string && p[i] == '\\')
2535 --i;
2536 ++i;
2537
2538 /* At this point we know we'll need to allocate a new string.
2539 Make a copy if we haven't yet done so. */
2540 if (! new)
2541 {
2542 slen = strlen (*string);
2543 new = alloca (slen + 1);
2544 memcpy (new, *string, slen + 1);
2545 p = new + (p - *string);
2546 *string = new;
2547 }
2548
2549 /* At this point *string, p, and new all point into the same string.
2550 Get a non-const version of p so we can modify new. */
2551 pv = new + (p - *string);
2552
2553 /* The number of backslashes is now -I.
2554 Copy P over itself to swallow half of them. */
2555 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2556 p += i/2;
2557
2558 /* If the backslashes quoted each other; the % was unquoted. */
2559 if (i % 2 == 0)
2560 break;
2561 }
2562 }
2563
2564 /* If we had to change STRING, add it to the strcache. */
2565 if (new)
2566 {
2567 *string = strcache_add (*string);
2568 if (p)
2569 p = *string + (p - new);
2570 }
2571
2572 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2573 return p;
2574 }
2575
2576 /* Find the next line of text in an eval buffer, combining continuation lines
2577 into one line.
2578 Return the number of actual lines read (> 1 if continuation lines).
2579 Returns -1 if there's nothing left in the buffer.
2580
2581 After this function, ebuf->buffer points to the first character of the
2582 line we just found.
2583 */
2584
2585 /* Read a line of text from a STRING.
2586 Since we aren't really reading from a file, don't bother with linenumbers.
2587 */
2588
2589 static long
2590 readstring (struct ebuffer *ebuf)
2591 {
2592 char *eol;
2593
2594 /* If there is nothing left in this buffer, return 0. */
2595 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2596 return -1;
2597
2598 /* Set up a new starting point for the buffer, and find the end of the
2599 next logical line (taking into account backslash/newline pairs). */
2600
2601 eol = ebuf->buffer = ebuf->bufnext;
2602
2603 while (1)
2604 {
2605 int backslash = 0;
2606 const char *bol = eol;
2607 const char *p;
2608
2609 /* Find the next newline. At EOS, stop. */
2610 p = eol = strchr (eol , '\n');
2611 if (!eol)
2612 {
2613 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2614 return 0;
2615 }
2616
2617 /* Found a newline; if it's escaped continue; else we're done. */
2618 while (p > bol && *(--p) == '\\')
2619 backslash = !backslash;
2620 if (!backslash)
2621 break;
2622 ++eol;
2623 }
2624
2625 /* Overwrite the newline char. */
2626 *eol = '\0';
2627 ebuf->bufnext = eol+1;
2628
2629 return 0;
2630 }
2631
2632 static long
2633 readline (struct ebuffer *ebuf)
2634 {
2635 char *p;
2636 char *end;
2637 char *start;
2638 long nlines = 0;
2639
2640 /* The behaviors between string and stream buffers are different enough to
2641 warrant different functions. Do the Right Thing. */
2642
2643 if (!ebuf->fp)
2644 return readstring (ebuf);
2645
2646 /* When reading from a file, we always start over at the beginning of the
2647 buffer for each new line. */
2648
2649 p = start = ebuf->bufstart;
2650 end = p + ebuf->size;
2651 *p = '\0';
2652
2653 while (fgets (p, (int) (end - p), ebuf->fp) != 0)
2654 {
2655 char *p2;
2656 size_t len;
2657 int backslash;
2658
2659 len = strlen (p);
2660 if (len == 0)
2661 {
2662 /* This only happens when the first thing on the line is a '\0'.
2663 It is a pretty hopeless case, but (wonder of wonders) Athena
2664 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2665 There is nothing really to be done; we synthesize a newline so
2666 the following line doesn't appear to be part of this line. */
2667 O (error, &ebuf->floc,
2668 _("warning: NUL character seen; rest of line ignored"));
2669 p[0] = '\n';
2670 len = 1;
2671 }
2672
2673 /* Jump past the text we just read. */
2674 p += len;
2675
2676 /* If the last char isn't a newline, the whole line didn't fit into the
2677 buffer. Get some more buffer and try again. */
2678 if (p[-1] != '\n')
2679 goto more_buffer;
2680
2681 /* We got a newline, so add one to the count of lines. */
2682 ++nlines;
2683
2684 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2685 /* Check to see if the line was really ended with CRLF; if so ignore
2686 the CR. */
2687 if ((p - start) > 1 && p[-2] == '\r')
2688 {
2689 --p;
2690 memmove (p-1, p, strlen (p) + 1);
2691 }
2692 #endif
2693
2694 backslash = 0;
2695 for (p2 = p - 2; p2 >= start; --p2)
2696 {
2697 if (*p2 != '\\')
2698 break;
2699 backslash = !backslash;
2700 }
2701
2702 if (!backslash)
2703 {
2704 p[-1] = '\0';
2705 break;
2706 }
2707
2708 /* It was a backslash/newline combo. If we have more space, read
2709 another line. */
2710 if (end - p >= 80)
2711 continue;
2712
2713 /* We need more space at the end of our buffer, so realloc it.
2714 Make sure to preserve the current offset of p. */
2715 more_buffer:
2716 {
2717 size_t off = p - start;
2718 ebuf->size *= 2;
2719 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2720 p = start + off;
2721 end = start + ebuf->size;
2722 *p = '\0';
2723 }
2724 }
2725
2726 if (ferror (ebuf->fp))
2727 pfatal_with_name (ebuf->floc.filenm);
2728
2729 /* If we found some lines, return how many.
2730 If we didn't, but we did find _something_, that indicates we read the last
2731 line of a file with no final newline; return 1.
2732 If we read nothing, we're at EOF; return -1. */
2733
2734 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2735 }
2736
2737 /* Parse the next "makefile word" from the input buffer, and return info
2738 about it.
2739
2740 A "makefile word" is one of:
2741
2742 w_bogus Should never happen
2743 w_eol End of input
2744 w_static A static word; cannot be expanded
2745 w_variable A word containing one or more variables/functions
2746 w_colon A colon
2747 w_dcolon A double-colon
2748 w_ampcolon An ampersand-colon (&:) token
2749 w_ampdcolon An ampersand-double-colon (&::) token
2750 w_semicolon A semicolon
2751 w_varassign A variable assignment operator (=, :=, ::=, +=, ?=, or !=)
2752
2753 Note that this function is only used when reading certain parts of the
2754 makefile. Don't use it where special rules hold sway (RHS of a variable,
2755 in a command list, etc.) */
2756
2757 static enum make_word_type
2758 get_next_mword (char *buffer, char **startp, size_t *length)
2759 {
2760 enum make_word_type wtype;
2761 char *p = buffer, *beg;
2762 char c;
2763
2764 /* Skip any leading whitespace. */
2765 while (ISBLANK (*p))
2766 ++p;
2767
2768 beg = p;
2769 c = *(p++);
2770
2771 /* Look at the start of the word to see if it's simple. */
2772 switch (c)
2773 {
2774 case '\0':
2775 wtype = w_eol;
2776 goto done;
2777
2778 case ';':
2779 wtype = w_semicolon;
2780 goto done;
2781
2782 case '=':
2783 wtype = w_varassign;
2784 goto done;
2785
2786 case ':':
2787 if (*p == '=')
2788 {
2789 ++p;
2790 wtype = w_varassign; /* := */
2791 }
2792 else if (*p == ':')
2793 {
2794 ++p;
2795 if (p[1] == '=')
2796 {
2797 ++p;
2798 wtype = w_varassign; /* ::= */
2799 }
2800 else
2801 wtype = w_dcolon;
2802 }
2803 else
2804 wtype = w_colon;
2805 goto done;
2806
2807 case '&':
2808 if (*p == ':')
2809 {
2810 ++p;
2811 if (*p != ':')
2812 wtype = w_ampcolon; /* &: */
2813 else
2814 {
2815 ++p;
2816 wtype = w_ampdcolon; /* &:: */
2817 }
2818 goto done;
2819 }
2820 break;
2821
2822 case '+':
2823 case '?':
2824 case '!':
2825 if (*p == '=')
2826 {
2827 ++p;
2828 wtype = w_varassign; /* += or ?= or != */
2829 goto done;
2830 }
2831 break;
2832
2833 default:
2834 break;
2835 }
2836
2837 /* This is some non-operator word. A word consists of the longest
2838 string of characters that doesn't contain whitespace, one of [:=#],
2839 or [?+!]=, or &:. */
2840
2841 /* We start out assuming a static word; if we see a variable we'll
2842 adjust our assumptions then. */
2843 wtype = w_static;
2844
2845 /* We already found the first value of "c", above. */
2846 while (1)
2847 {
2848 char closeparen;
2849 int count;
2850
2851 switch (c)
2852 {
2853 case '\0':
2854 case ' ':
2855 case '\t':
2856 case '=':
2857 goto done_word;
2858
2859 case ':':
2860 #ifdef HAVE_DOS_PATHS
2861 /* A word CAN include a colon in its drive spec. The drive
2862 spec is allowed either at the beginning of a word, or as part
2863 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2864 if ((p - beg == 2 || (p - beg > 2 && p[-3] == '('))
2865 && isalpha ((unsigned char)p[-2]))
2866 break;
2867 #endif
2868 goto done_word;
2869
2870 case '$':
2871 c = *(p++);
2872 if (c == '$')
2873 break;
2874 if (c == '\0')
2875 goto done_word;
2876
2877 /* This is a variable reference, so note that it's expandable.
2878 Then read it to the matching close paren. */
2879 wtype = w_variable;
2880
2881 if (c == '(')
2882 closeparen = ')';
2883 else if (c == '{')
2884 closeparen = '}';
2885 else
2886 /* This is a single-letter variable reference. */
2887 break;
2888
2889 for (count=0; *p != '\0'; ++p)
2890 {
2891 if (*p == c)
2892 ++count;
2893 else if (*p == closeparen && --count < 0)
2894 {
2895 ++p;
2896 break;
2897 }
2898 }
2899 break;
2900
2901 case '?':
2902 case '+':
2903 if (*p == '=')
2904 goto done_word;
2905 break;
2906
2907 case '\\':
2908 switch (*p)
2909 {
2910 case ':':
2911 case ';':
2912 case '=':
2913 case '\\':
2914 ++p;
2915 break;
2916 }
2917 break;
2918
2919 case '&':
2920 if (*p == ':')
2921 goto done_word;
2922 break;
2923
2924 default:
2925 break;
2926 }
2927
2928 c = *(p++);
2929 }
2930 done_word:
2931 --p;
2932
2933 done:
2934 if (startp)
2935 *startp = beg;
2936 if (length)
2937 *length = p - beg;
2938 return wtype;
2939 }
2940
2941 /* Construct the list of include directories
2942 from the arguments and the default list. */
2943
2944 void
2945 construct_include_path (const char **arg_dirs)
2946 {
2947 #ifdef VAXC /* just don't ask ... */
2948 stat_t stbuf;
2949 #else
2950 struct stat stbuf;
2951 #endif
2952 const char **dirs;
2953 const char **cpp;
2954 size_t idx;
2955
2956 /* Compute the number of pointers we need in the table. */
2957 idx = sizeof (default_include_directories) / sizeof (const char *);
2958 if (arg_dirs)
2959 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2960 ++idx;
2961
2962 #ifdef __MSDOS__
2963 /* Add one for $DJDIR. */
2964 ++idx;
2965 #endif
2966
2967 dirs = xmalloc (idx * sizeof (const char *));
2968
2969 idx = 0;
2970 max_incl_len = 0;
2971
2972 /* First consider any dirs specified with -I switches.
2973 Ignore any that don't exist. Remember the maximum string length. */
2974
2975 if (arg_dirs)
2976 while (*arg_dirs != 0)
2977 {
2978 const char *dir = *(arg_dirs++);
2979 char *expanded = 0;
2980 int e;
2981
2982 if (dir[0] == '~')
2983 {
2984 expanded = remake_tilde_expand (dir);
2985 if (expanded != 0)
2986 dir = expanded;
2987 }
2988
2989 EINTRLOOP (e, stat (dir, &stbuf));
2990 if (e == 0 && S_ISDIR (stbuf.st_mode))
2991 {
2992 size_t len = strlen (dir);
2993 /* If dir name is written with trailing slashes, discard them. */
2994 while (len > 1 && dir[len - 1] == '/')
2995 --len;
2996 if (len > max_incl_len)
2997 max_incl_len = len;
2998 dirs[idx++] = strcache_add_len (dir, len);
2999 }
3000
3001 free (expanded);
3002 }
3003
3004 /* Now add the standard default dirs at the end. */
3005
3006 #ifdef __MSDOS__
3007 {
3008 /* The environment variable $DJDIR holds the root of the DJGPP directory
3009 tree; add ${DJDIR}/include. */
3010 struct variable *djdir = lookup_variable ("DJDIR", 5);
3011
3012 if (djdir)
3013 {
3014 size_t len = strlen (djdir->value) + 8;
3015 char *defdir = alloca (len + 1);
3016
3017 strcat (strcpy (defdir, djdir->value), "/include");
3018 dirs[idx++] = strcache_add (defdir);
3019
3020 if (len > max_incl_len)
3021 max_incl_len = len;
3022 }
3023 }
3024 #endif
3025
3026 for (cpp = default_include_directories; *cpp != 0; ++cpp)
3027 {
3028 int e;
3029
3030 EINTRLOOP (e, stat (*cpp, &stbuf));
3031 if (e == 0 && S_ISDIR (stbuf.st_mode))
3032 {
3033 size_t len = strlen (*cpp);
3034 /* If dir name is written with trailing slashes, discard them. */
3035 while (len > 1 && (*cpp)[len - 1] == '/')
3036 --len;
3037 if (len > max_incl_len)
3038 max_incl_len = len;
3039 dirs[idx++] = strcache_add_len (*cpp, len);
3040 }
3041 }
3042
3043 dirs[idx] = 0;
3044
3045 /* Now add each dir to the .INCLUDE_DIRS variable. */
3046
3047 for (cpp = dirs; *cpp != 0; ++cpp)
3048 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
3049 o_default, f_append, 0);
3050
3051 include_directories = dirs;
3052 }
3053
3054 /* Expand ~ or ~USER at the beginning of NAME.
3055 Return a newly malloc'd string or 0. */
3056
3057 char *
3058 remake_tilde_expand (const char *name)
3059 {
3060 if (name[1] == '/' || name[1] == '\0')
3061 {
3062 char *home_dir;
3063 int is_variable;
3064
3065 {
3066 /* Turn off --warn-undefined-variables while we expand HOME. */
3067 int save = warn_undefined_variables_flag;
3068 warn_undefined_variables_flag = 0;
3069
3070 home_dir = allocated_variable_expand ("$(HOME)");
3071
3072 warn_undefined_variables_flag = save;
3073 }
3074
3075 is_variable = home_dir[0] != '\0';
3076 if (!is_variable)
3077 {
3078 free (home_dir);
3079 home_dir = getenv ("HOME");
3080 }
3081 # if !defined(_AMIGA) && !defined(WINDOWS32)
3082 if (home_dir == 0 || home_dir[0] == '\0')
3083 {
3084 char *logname = getlogin ();
3085 home_dir = 0;
3086 if (logname != 0)
3087 {
3088 struct passwd *p = getpwnam (logname);
3089 if (p != 0)
3090 home_dir = p->pw_dir;
3091 }
3092 }
3093 # endif /* !AMIGA && !WINDOWS32 */
3094 if (home_dir != 0)
3095 {
3096 char *new = xstrdup (concat (2, home_dir, name + 1));
3097 if (is_variable)
3098 free (home_dir);
3099 return new;
3100 }
3101 }
3102 # if !defined(_AMIGA) && !defined(WINDOWS32)
3103 else
3104 {
3105 struct passwd *pwent;
3106 char *userend = strchr (name + 1, '/');
3107 if (userend != 0)
3108 *userend = '\0';
3109 pwent = getpwnam (name + 1);
3110 if (pwent != 0)
3111 {
3112 if (userend == 0)
3113 return xstrdup (pwent->pw_dir);
3114 else
3115 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
3116 }
3117 else if (userend != 0)
3118 *userend = '/';
3119 }
3120 # endif /* !AMIGA && !WINDOWS32 */
3121 return 0;
3122 }
3123
3124 /* Parse a string into a sequence of filenames represented as a chain of
3125 struct nameseq's and return that chain. Optionally expand the strings via
3126 glob().
3127
3128 The string is passed as STRINGP, the address of a string pointer.
3129 The string pointer is updated to point at the first character
3130 not parsed, which either is a null char or equals STOPMAP.
3131
3132 SIZE is how large (in bytes) each element in the new chain should be.
3133 This is useful if we want them actually to be other structures
3134 that have room for additional info.
3135
3136 STOPMAP is a map of characters that tell us to stop parsing.
3137
3138 PREFIX, if non-null, is added to the beginning of each filename.
3139
3140 FLAGS allows one or more of the following bitflags to be set:
3141 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
3142 PARSEFS_NOAR - Do not check filenames for archive references
3143 PARSEFS_NOGLOB - Do not expand globbing characters
3144 PARSEFS_EXISTS - Only return globbed files that actually exist
3145 (cannot also set NOGLOB)
3146 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
3147 */
3148
3149 void *
3150 parse_file_seq (char **stringp, size_t size, int stopmap,
3151 const char *prefix, int flags)
3152 {
3153 /* tmp points to tmpbuf after the prefix, if any.
3154 tp is the end of the buffer. */
3155 static char *tmpbuf = NULL;
3156
3157 int cachep = NONE_SET (flags, PARSEFS_NOCACHE);
3158
3159 struct nameseq *new = 0;
3160 struct nameseq **newp = &new;
3161 #define NEWELT(_n) do { \
3162 const char *__n = (_n); \
3163 *newp = xcalloc (size); \
3164 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
3165 newp = &(*newp)->next; \
3166 } while(0)
3167
3168 char *p;
3169 glob_t gl;
3170 char *tp;
3171 int findmap = stopmap|MAP_NUL;
3172
3173 if (NONE_SET (flags, PARSEFS_ONEWORD))
3174 findmap |= MAP_BLANK;
3175
3176 /* Always stop on NUL. */
3177 stopmap |= MAP_NUL;
3178
3179 if (size < sizeof (struct nameseq))
3180 size = sizeof (struct nameseq);
3181
3182 if (NONE_SET (flags, PARSEFS_NOGLOB))
3183 dir_setup_glob (&gl);
3184
3185 /* Get enough temporary space to construct the largest possible target. */
3186 {
3187 static size_t tmpbuf_len = 0;
3188 size_t l = strlen (*stringp) + 1;
3189 if (l > tmpbuf_len)
3190 {
3191 tmpbuf = xrealloc (tmpbuf, l);
3192 tmpbuf_len = l;
3193 }
3194 }
3195 tp = tmpbuf;
3196
3197 /* Parse STRING. P will always point to the end of the parsed content. */
3198 p = *stringp;
3199 while (1)
3200 {
3201 const char *name;
3202 const char **nlist = 0;
3203 char *tildep = 0;
3204 int globme = 1;
3205 #ifndef NO_ARCHIVES
3206 char *arname = 0;
3207 char *memname = 0;
3208 #endif
3209 char *s;
3210 size_t nlen;
3211 int tot, i;
3212
3213 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
3214 NEXT_TOKEN (p);
3215 if (STOP_SET (*p, stopmap))
3216 break;
3217
3218 /* There are names left, so find the end of the next name.
3219 Throughout this iteration S points to the start. */
3220 s = p;
3221 p = find_map_unquote (p, findmap);
3222
3223 #ifdef HAVE_DOS_PATHS
3224 /* If we stopped due to a drive specifier, skip it.
3225 Tokens separated by spaces are treated as separate paths since make
3226 doesn't allow path names with spaces. */
3227 if (p && p == s+1 && p[0] == ':'
3228 && isalpha ((unsigned char)s[0]) && STOP_SET (p[1], MAP_DIRSEP))
3229 p = find_map_unquote (p+1, findmap);
3230 #endif
3231
3232 if (!p)
3233 p = s + strlen (s);
3234
3235 /* Strip leading "this directory" references. */
3236 if (NONE_SET (flags, PARSEFS_NOSTRIP))
3237 /* Skip leading './'s. */
3238 while (p - s > 2 && s[0] == '.' && s[1] == '/')
3239 {
3240 /* Skip "./" and all following slashes. */
3241 s += 2;
3242 while (*s == '/')
3243 ++s;
3244 }
3245
3246 /* Extract the filename just found, and skip it.
3247 Set NAME to the string, and NLEN to its length. */
3248
3249 if (s == p)
3250 {
3251 /* The name was stripped to empty ("./"). */
3252 tp[0] = '.';
3253 tp[1] = '/';
3254 tp[2] = '\0';
3255 nlen = 2;
3256 }
3257 else
3258 {
3259 nlen = p - s;
3260 memcpy (tp, s, nlen);
3261 tp[nlen] = '\0';
3262 }
3263
3264 /* At this point, TP points to the element and NLEN is its length. */
3265
3266 #ifndef NO_ARCHIVES
3267 /* If this is the start of an archive group that isn't complete, set up
3268 to add the archive prefix for future files. A file list like:
3269 "libf.a(x.o y.o z.o)" needs to be expanded as:
3270 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3271
3272 TP == TMP means we're not already in an archive group. Ignore
3273 something starting with '(', as that cannot actually be an
3274 archive-member reference (and treating it as such results in an empty
3275 file name, which causes much lossage). Also if it ends in ")" then
3276 it's a complete reference so we don't need to treat it specially.
3277
3278 Finally, note that archive groups must end with ')' as the last
3279 character, so ensure there's some word ending like that before
3280 considering this an archive group. */
3281 if (NONE_SET (flags, PARSEFS_NOAR)
3282 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3283 {
3284 char *n = strchr (tp, '(');
3285 if (n)
3286 {
3287 /* This looks like the first element in an open archive group.
3288 A valid group MUST have ')' as the last character. */
3289 const char *e = p;
3290 do
3291 {
3292 const char *o = e;
3293 NEXT_TOKEN (e);
3294 /* Find the end of this word. We don't want to unquote and
3295 we don't care about quoting since we're looking for the
3296 last char in the word. */
3297 while (! STOP_SET (*e, findmap))
3298 ++e;
3299 /* If we didn't move, we're done now. */
3300 if (e == o)
3301 break;
3302 if (e[-1] == ')')
3303 {
3304 /* Found the end, so this is the first element in an
3305 open archive group. It looks like "lib(mem".
3306 Reset TP past the open paren. */
3307 nlen -= (n + 1) - tp;
3308 tp = n + 1;
3309
3310 /* We can stop looking now. */
3311 break;
3312 }
3313 }
3314 while (*e != '\0');
3315
3316 /* If we have just "lib(", part of something like "lib( a b)",
3317 go to the next item. */
3318 if (! nlen)
3319 continue;
3320 }
3321 }
3322
3323 /* If we are inside an archive group, make sure it has an end. */
3324 if (tp > tmpbuf)
3325 {
3326 if (tp[nlen-1] == ')')
3327 {
3328 /* This is the natural end; reset TP. */
3329 tp = tmpbuf;
3330
3331 /* This is just ")", something like "lib(a b )": skip it. */
3332 if (nlen == 1)
3333 continue;
3334 }
3335 else
3336 {
3337 /* Not the end, so add a "fake" end. */
3338 tp[nlen++] = ')';
3339 tp[nlen] = '\0';
3340 }
3341 }
3342 #endif
3343
3344 /* If we're not globbing we're done: add it to the end of the chain.
3345 Go to the next item in the string. */
3346 if (ANY_SET (flags, PARSEFS_NOGLOB))
3347 {
3348 NEWELT (concat (2, prefix, tmpbuf));
3349 continue;
3350 }
3351
3352 /* If we get here we know we're doing glob expansion.
3353 TP is a string in tmpbuf. NLEN is no longer used.
3354 We may need to do more work: after this NAME will be set. */
3355 name = tmpbuf;
3356
3357 /* Expand tilde if applicable. */
3358 if (tmpbuf[0] == '~')
3359 {
3360 tildep = remake_tilde_expand (tmpbuf);
3361 if (tildep != 0)
3362 name = tildep;
3363 }
3364
3365 #ifndef NO_ARCHIVES
3366 /* If NAME is an archive member reference replace it with the archive
3367 file name, and save the member name in MEMNAME. We will glob on the
3368 archive name and then reattach MEMNAME later. */
3369 if (NONE_SET (flags, PARSEFS_NOAR) && ar_name (name))
3370 {
3371 ar_parse_name (name, &arname, &memname);
3372 name = arname;
3373 }
3374 #endif /* !NO_ARCHIVES */
3375
3376 /* glob() is expensive: don't call it unless we need to. */
3377 if (NONE_SET (flags, PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3378 {
3379 globme = 0;
3380 tot = 1;
3381 nlist = &name;
3382 }
3383 else
3384 switch (glob (name, GLOB_ALTDIRFUNC, NULL, &gl))
3385 {
3386 case GLOB_NOSPACE:
3387 out_of_memory ();
3388
3389 case 0:
3390 /* Success. */
3391 tot = gl.gl_pathc;
3392 nlist = (const char **)gl.gl_pathv;
3393 break;
3394
3395 case GLOB_NOMATCH:
3396 /* If we want only existing items, skip this one. */
3397 if (ANY_SET (flags, PARSEFS_EXISTS))
3398 {
3399 tot = 0;
3400 break;
3401 }
3402 /* FALLTHROUGH */
3403
3404 default:
3405 /* By default keep this name. */
3406 tot = 1;
3407 nlist = &name;
3408 break;
3409 }
3410
3411 /* For each matched element, add it to the list. */
3412 for (i = 0; i < tot; ++i)
3413 #ifndef NO_ARCHIVES
3414 if (memname != 0)
3415 {
3416 /* Try to glob on MEMNAME within the archive. */
3417 struct nameseq *found = ar_glob (nlist[i], memname, size);
3418 if (! found)
3419 /* No matches. Use MEMNAME as-is. */
3420 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3421 else
3422 {
3423 /* We got a chain of items. Attach them. */
3424 if (*newp)
3425 (*newp)->next = found;
3426 else
3427 *newp = found;
3428
3429 /* Find and set the new end. Massage names if necessary. */
3430 while (1)
3431 {
3432 if (! cachep)
3433 found->name = xstrdup (concat (2, prefix, name));
3434 else if (prefix)
3435 found->name = strcache_add (concat (2, prefix, name));
3436
3437 if (found->next == 0)
3438 break;
3439
3440 found = found->next;
3441 }
3442 newp = &found->next;
3443 }
3444 }
3445 else
3446 #endif /* !NO_ARCHIVES */
3447 NEWELT (concat (2, prefix, nlist[i]));
3448
3449 if (globme)
3450 globfree (&gl);
3451
3452 #ifndef NO_ARCHIVES
3453 free (arname);
3454 #endif
3455
3456 free (tildep);
3457 }
3458
3459 *stringp = p;
3460 return new;
3461 }