source: trunk/src/gmakenew/read.c@ 910

Last change on this file since 910 was 910, checked in by bird, 18 years ago

Fixed a few potential variable_buffer realloc problems.

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