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

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

Merged with the 2007-05-23 CVS. Added rsort and fixed a couple of windows build issues.

  • Property svn:eol-style set to native
File size: 92.6 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 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2189 pattern_percent+1, percent+1);
2190 f->stem = strcache_add_len (buffer, o - buffer);
2191 if (this)
2192 {
2193 this->staticpattern = 1;
2194 this->stem = f->stem;
2195 }
2196 }
2197
2198 name = f->name;
2199
2200 /* If this target is a default target, update DEFAULT_GOAL_FILE. */
2201 if (streq (*default_goal_name, name)
2202 && (default_goal_file == 0
2203 || ! streq (default_goal_file->name, name)))
2204 default_goal_file = f;
2205 }
2206
2207 if (implicit)
2208 {
2209 if (deps)
2210 deps->need_2nd_expansion = second_expansion;
2211 create_pattern_rule (targets, target_percents, target_idx,
2212 two_colon, deps, cmds, 1);
2213 }
2214}
2215
2216
2217/* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2218 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2219 Quoting backslashes are removed from STRING by compacting it into
2220 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2221 one, or nil if there are none. STOPCHARs inside variable references are
2222 ignored if IGNOREVARS is true.
2223
2224 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2225
2226static char *
2227find_char_unquote (char *string, int stop1, int stop2, int blank,
2228 int ignorevars)
2229{
2230 unsigned int string_len = 0;
2231 char *p = string;
2232 register int ch; /* bird: 'optimiziations' */
2233
2234 if (ignorevars)
2235 ignorevars = '$';
2236
2237 while (1)
2238 {
2239 if (stop2 && blank)
2240 while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1 && ch != stop2
2241 && ! isblank ((unsigned char) ch))
2242 ++p;
2243 else if (stop2)
2244 while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1 && ch != stop2)
2245 ++p;
2246 else if (blank)
2247 while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1
2248 && ! isblank ((unsigned char) ch))
2249 ++p;
2250 else
2251 while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1)
2252 ++p;
2253
2254 if (ch == '\0')
2255 break;
2256
2257 /* If we stopped due to a variable reference, skip over its contents. */
2258 if (ch == ignorevars)
2259 {
2260 char openparen = p[1];
2261
2262 p += 2;
2263
2264 /* Skip the contents of a non-quoted, multi-char variable ref. */
2265 if (openparen == '(' || openparen == '{')
2266 {
2267 unsigned int pcount = 1;
2268 char closeparen = (openparen == '(' ? ')' : '}');
2269
2270 while ((ch = *p))
2271 {
2272 if (ch == openparen)
2273 ++pcount;
2274 else if (ch == closeparen)
2275 if (--pcount == 0)
2276 {
2277 ++p;
2278 break;
2279 }
2280 ++p;
2281 }
2282 }
2283
2284 /* Skipped the variable reference: look for STOPCHARS again. */
2285 continue;
2286 }
2287
2288 if (p > string && p[-1] == '\\')
2289 {
2290 /* Search for more backslashes. */
2291 int i = -2;
2292 while (&p[i] >= string && p[i] == '\\')
2293 --i;
2294 ++i;
2295 /* Only compute the length if really needed. */
2296 if (string_len == 0)
2297 string_len = strlen (string);
2298 /* The number of backslashes is now -I.
2299 Copy P over itself to swallow half of them. */
2300 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2301 p += i/2;
2302 if (i % 2 == 0)
2303 /* All the backslashes quoted each other; the STOPCHAR was
2304 unquoted. */
2305 return p;
2306
2307 /* The STOPCHAR was quoted by a backslash. Look for another. */
2308 }
2309 else
2310 /* No backslash in sight. */
2311 return p;
2312 }
2313
2314 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2315 return 0;
2316}
2317
2318/* Search PATTERN for an unquoted % and handle quoting. */
2319
2320char *
2321find_percent (char *pattern)
2322{
2323 return find_char_unquote (pattern, '%', 0, 0, 0);
2324}
2325
2326/* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2327 the % or NULL if no % was found.
2328 This version is used with strings in the string cache: if there's a need to
2329 modify the string a new version will be added to the string cache and
2330 *STRING will be set to that. */
2331
2332const char *
2333find_percent_cached (const char **string)
2334{
2335 const char *p = *string;
2336 char *new = 0;
2337 int slen;
2338
2339 /* If the first char is a % return now. This lets us avoid extra tests
2340 inside the loop. */
2341 if (*p == '%')
2342 return p;
2343
2344 while (1)
2345 {
2346 while (*p != '\0' && *p != '%')
2347 ++p;
2348
2349 if (*p == '\0')
2350 break;
2351
2352 /* See if this % is escaped with a backslash; if not we're done. */
2353 if (p[-1] != '\\')
2354 break;
2355
2356 {
2357 /* Search for more backslashes. */
2358 char *pv;
2359 int i = -2;
2360
2361 while (&p[i] >= *string && p[i] == '\\')
2362 --i;
2363 ++i;
2364
2365 /* At this point we know we'll need to allocate a new string.
2366 Make a copy if we haven't yet done so. */
2367 if (! new)
2368 {
2369 slen = strlen (*string);
2370 new = alloca (slen + 1);
2371 memcpy (new, *string, slen + 1);
2372 p = new + (p - *string);
2373 *string = new;
2374 }
2375
2376 /* At this point *string, p, and new all point into the same string.
2377 Get a non-const version of p so we can modify new. */
2378 pv = new + (p - *string);
2379
2380 /* The number of backslashes is now -I.
2381 Copy P over itself to swallow half of them. */
2382 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2383 p += i/2;
2384
2385 /* If the backslashes quoted each other; the % was unquoted. */
2386 if (i % 2 == 0)
2387 break;
2388 }
2389 }
2390
2391 /* If we had to change STRING, add it to the strcache. */
2392 if (new)
2393 {
2394 *string = strcache_add (*string);
2395 p = *string + (p - new);
2396 }
2397
2398 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2399 return (*p == '\0') ? NULL : p;
2400}
2401
2402
2403/* Parse a string into a sequence of filenames represented as a
2404 chain of struct nameseq's in reverse order and return that chain.
2405
2406 The string is passed as STRINGP, the address of a string pointer.
2407 The string pointer is updated to point at the first character
2408 not parsed, which either is a null char or equals STOPCHAR.
2409
2410 SIZE is how big to construct chain elements.
2411 This is useful if we want them actually to be other structures
2412 that have room for additional info.
2413
2414 If STRIP is nonzero, strip `./'s off the beginning. */
2415
2416struct nameseq *
2417parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
2418{
2419 struct nameseq *new = 0;
2420 struct nameseq *new1;
2421#ifndef NO_ARCHIVES /* bird: MSC warning */
2422 struct nameseq *lastnew1;
2423#endif
2424 char *p = *stringp;
2425
2426#ifdef VMS
2427# define VMS_COMMA ','
2428#else
2429# define VMS_COMMA 0
2430#endif
2431
2432 while (1)
2433 {
2434 const char *name;
2435 char *q;
2436
2437 /* Skip whitespace; see if any more names are left. */
2438 p = next_token (p);
2439 if (*p == '\0')
2440 break;
2441 if (*p == stopchar)
2442 break;
2443
2444 /* There are, so find the end of the next name. */
2445 q = p;
2446 p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
2447#ifdef VMS
2448 /* convert comma separated list to space separated */
2449 if (p && *p == ',')
2450 *p =' ';
2451#endif
2452#ifdef _AMIGA
2453 if (stopchar == ':' && p && *p == ':'
2454 && !(isspace ((unsigned char)p[1]) || !p[1]
2455 || isspace ((unsigned char)p[-1])))
2456 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2457#endif
2458#ifdef HAVE_DOS_PATHS
2459 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2460 first colon which isn't followed by a slash or a backslash.
2461 Note that tokens separated by spaces should be treated as separate
2462 tokens since make doesn't allow path names with spaces */
2463 if (stopchar == ':')
2464 while (p != 0 && !isspace ((unsigned char)*p) &&
2465 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2466 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2467#endif
2468 if (p == 0)
2469 p = q + strlen (q);
2470
2471 if (strip)
2472#ifdef VMS
2473 /* Skip leading `[]'s. */
2474 while (p - q > 2 && q[0] == '[' && q[1] == ']')
2475#else
2476 /* Skip leading `./'s. */
2477 while (p - q > 2 && q[0] == '.' && q[1] == '/')
2478#endif
2479 {
2480 q += 2; /* Skip "./". */
2481 while (q < p && *q == '/')
2482 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
2483 ++q;
2484 }
2485
2486 /* Extract the filename just found, and skip it. */
2487
2488 if (q == p)
2489 /* ".///" was stripped to "". */
2490#if defined(VMS)
2491 continue;
2492#elif defined(_AMIGA)
2493 name = "";
2494#else
2495 name = "./";
2496#endif
2497 else
2498#ifdef VMS
2499/* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2500 * to remove this '\' before we can use the filename.
2501 * Savestring called because q may be read-only string constant.
2502 */
2503 {
2504 char *qbase = xstrdup (q);
2505 char *pbase = qbase + (p-q);
2506 char *q1 = qbase;
2507 char *q2 = q1;
2508 char *p1 = pbase;
2509
2510 while (q1 != pbase)
2511 {
2512 if (*q1 == '\\' && *(q1+1) == ':')
2513 {
2514 q1++;
2515 p1--;
2516 }
2517 *q2++ = *q1++;
2518 }
2519 name = strcache_add_len (qbase, p1 - qbase);
2520 free (qbase);
2521 }
2522#else
2523 name = strcache_add_len (q, p - q);
2524#endif
2525
2526 /* Add it to the front of the chain. */
2527 new1 = xmalloc (size);
2528 new1->name = name;
2529 new1->next = new;
2530 new = new1;
2531 }
2532
2533#ifndef NO_ARCHIVES
2534
2535 /* Look for multi-word archive references.
2536 They are indicated by a elt ending with an unmatched `)' and
2537 an elt further down the chain (i.e., previous in the file list)
2538 with an unmatched `(' (e.g., "lib(mem"). */
2539
2540 new1 = new;
2541 lastnew1 = 0;
2542 while (new1 != 0)
2543 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
2544 && new1->name[strlen (new1->name) - 1] == ')'
2545 && strchr (new1->name, '(') == 0)
2546 {
2547 /* NEW1 ends with a `)' but does not contain a `('.
2548 Look back for an elt with an opening `(' but no closing `)'. */
2549
2550 struct nameseq *n = new1->next, *lastn = new1;
2551 char *paren = 0;
2552 while (n != 0 && (paren = strchr (n->name, '(')) == 0)
2553 {
2554 lastn = n;
2555 n = n->next;
2556 }
2557 if (n != 0
2558 /* Ignore something starting with `(', as that cannot actually
2559 be an archive-member reference (and treating it as such
2560 results in an empty file name, which causes much lossage). */
2561 && n->name[0] != '(')
2562 {
2563 /* N is the first element in the archive group.
2564 Its name looks like "lib(mem" (with no closing `)'). */
2565
2566 char *libname;
2567
2568 /* Copy "lib(" into LIBNAME. */
2569 ++paren;
2570 libname = alloca (paren - n->name + 1);
2571 memcpy (libname, n->name, paren - n->name);
2572 libname[paren - n->name] = '\0';
2573
2574 if (*paren == '\0')
2575 {
2576 /* N was just "lib(", part of something like "lib( a b)".
2577 Edit it out of the chain and free its storage. */
2578 lastn->next = n->next;
2579 free (n);
2580 /* LASTN->next is the new stopping elt for the loop below. */
2581 n = lastn->next;
2582 }
2583 else
2584 {
2585 /* Replace N's name with the full archive reference. */
2586 n->name = strcache_add (concat (libname, paren, ")"));
2587 }
2588
2589 if (new1->name[1] == '\0')
2590 {
2591 /* NEW1 is just ")", part of something like "lib(a b )".
2592 Omit it from the chain and free its storage. */
2593 if (lastnew1 == 0)
2594 new = new1->next;
2595 else
2596 lastnew1->next = new1->next;
2597 lastn = new1;
2598 new1 = new1->next;
2599 free (lastn);
2600 }
2601 else
2602 {
2603 /* Replace also NEW1->name, which already has closing `)'. */
2604 new1->name = strcache_add (concat (libname, new1->name, ""));
2605 new1 = new1->next;
2606 }
2607
2608 /* Trace back from NEW1 (the end of the list) until N
2609 (the beginning of the list), rewriting each name
2610 with the full archive reference. */
2611
2612 while (new1 != n)
2613 {
2614 new1->name = strcache_add (concat (libname, new1->name, ")"));
2615 lastnew1 = new1;
2616 new1 = new1->next;
2617 }
2618 }
2619 else
2620 {
2621 /* No frobnication happening. Just step down the list. */
2622 lastnew1 = new1;
2623 new1 = new1->next;
2624 }
2625 }
2626 else
2627 {
2628 lastnew1 = new1;
2629 new1 = new1->next;
2630 }
2631
2632#endif
2633
2634 *stringp = p;
2635 return new;
2636}
2637
2638
2639/* Find the next line of text in an eval buffer, combining continuation lines
2640 into one line.
2641 Return the number of actual lines read (> 1 if continuation lines).
2642 Returns -1 if there's nothing left in the buffer.
2643
2644 After this function, ebuf->buffer points to the first character of the
2645 line we just found.
2646 */
2647
2648/* Read a line of text from a STRING.
2649 Since we aren't really reading from a file, don't bother with linenumbers.
2650 */
2651
2652static unsigned long
2653readstring (struct ebuffer *ebuf)
2654{
2655 char *eol;
2656
2657 /* If there is nothing left in this buffer, return 0. */
2658 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2659 return -1;
2660
2661 /* Set up a new starting point for the buffer, and find the end of the
2662 next logical line (taking into account backslash/newline pairs). */
2663
2664 eol = ebuf->buffer = ebuf->bufnext;
2665
2666 while (1)
2667 {
2668 int backslash = 0;
2669 char *bol = eol;
2670 char *p;
2671
2672 /* Find the next newline. At EOS, stop. */
2673 eol = p = strchr (eol , '\n');
2674 if (!eol)
2675 {
2676 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2677 return 0;
2678 }
2679
2680 /* Found a newline; if it's escaped continue; else we're done. */
2681 while (p > bol && *(--p) == '\\')
2682 backslash = !backslash;
2683 if (!backslash)
2684 break;
2685 ++eol;
2686 }
2687
2688 /* Overwrite the newline char. */
2689 *eol = '\0';
2690 ebuf->bufnext = eol+1;
2691
2692 return 0;
2693}
2694
2695static long
2696readline (struct ebuffer *ebuf)
2697{
2698 char *p;
2699 char *end;
2700 char *start;
2701 long nlines = 0;
2702
2703 /* The behaviors between string and stream buffers are different enough to
2704 warrant different functions. Do the Right Thing. */
2705
2706 if (!ebuf->fp)
2707 return readstring (ebuf);
2708
2709 /* When reading from a file, we always start over at the beginning of the
2710 buffer for each new line. */
2711
2712 p = start = ebuf->bufstart;
2713 end = p + ebuf->size;
2714 *p = '\0';
2715
2716 while (fgets (p, end - p, ebuf->fp) != 0)
2717 {
2718 char *p2;
2719 unsigned long len;
2720 int backslash;
2721
2722 len = strlen (p);
2723 if (len == 0)
2724 {
2725 /* This only happens when the first thing on the line is a '\0'.
2726 It is a pretty hopeless case, but (wonder of wonders) Athena
2727 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2728 There is nothing really to be done; we synthesize a newline so
2729 the following line doesn't appear to be part of this line. */
2730 error (&ebuf->floc,
2731 _("warning: NUL character seen; rest of line ignored"));
2732 p[0] = '\n';
2733 len = 1;
2734 }
2735
2736 /* Jump past the text we just read. */
2737 p += len;
2738
2739 /* If the last char isn't a newline, the whole line didn't fit into the
2740 buffer. Get some more buffer and try again. */
2741 if (p[-1] != '\n')
2742 goto more_buffer;
2743
2744 /* We got a newline, so add one to the count of lines. */
2745 ++nlines;
2746
2747#if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2748 /* Check to see if the line was really ended with CRLF; if so ignore
2749 the CR. */
2750 if ((p - start) > 1 && p[-2] == '\r')
2751 {
2752 --p;
2753 p[-1] = '\n';
2754 }
2755#endif
2756
2757 backslash = 0;
2758 for (p2 = p - 2; p2 >= start; --p2)
2759 {
2760 if (*p2 != '\\')
2761 break;
2762 backslash = !backslash;
2763 }
2764
2765 if (!backslash)
2766 {
2767 p[-1] = '\0';
2768 break;
2769 }
2770
2771 /* It was a backslash/newline combo. If we have more space, read
2772 another line. */
2773 if (end - p >= 80)
2774 continue;
2775
2776 /* We need more space at the end of our buffer, so realloc it.
2777 Make sure to preserve the current offset of p. */
2778 more_buffer:
2779 {
2780 unsigned long off = p - start;
2781 ebuf->size *= 2;
2782 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2783 p = start + off;
2784 end = start + ebuf->size;
2785 *p = '\0';
2786 }
2787 }
2788
2789 if (ferror (ebuf->fp))
2790 pfatal_with_name (ebuf->floc.filenm);
2791
2792 /* If we found some lines, return how many.
2793 If we didn't, but we did find _something_, that indicates we read the last
2794 line of a file with no final newline; return 1.
2795 If we read nothing, we're at EOF; return -1. */
2796
2797 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2798}
2799
2800
2801/* Parse the next "makefile word" from the input buffer, and return info
2802 about it.
2803
2804 A "makefile word" is one of:
2805
2806 w_bogus Should never happen
2807 w_eol End of input
2808 w_static A static word; cannot be expanded
2809 w_variable A word containing one or more variables/functions
2810 w_colon A colon
2811 w_dcolon A double-colon
2812 w_semicolon A semicolon
2813 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2814
2815 Note that this function is only used when reading certain parts of the
2816 makefile. Don't use it where special rules hold sway (RHS of a variable,
2817 in a command list, etc.) */
2818
2819static enum make_word_type
2820get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2821{
2822 enum make_word_type wtype = w_bogus;
2823 char *p = buffer, *beg;
2824 char c;
2825
2826 /* Skip any leading whitespace. */
2827 while (isblank ((unsigned char)*p))
2828 ++p;
2829
2830 beg = p;
2831 c = *(p++);
2832 switch (c)
2833 {
2834 case '\0':
2835 wtype = w_eol;
2836 break;
2837
2838 case ';':
2839 wtype = w_semicolon;
2840 break;
2841
2842 case '=':
2843 wtype = w_varassign;
2844 break;
2845
2846 case ':':
2847 wtype = w_colon;
2848 switch (*p)
2849 {
2850 case ':':
2851 ++p;
2852 wtype = w_dcolon;
2853 break;
2854
2855 case '=':
2856 ++p;
2857 wtype = w_varassign;
2858 break;
2859 }
2860 break;
2861
2862 case '+':
2863 case '?':
2864 if (*p == '=')
2865 {
2866 ++p;
2867 wtype = w_varassign;
2868 break;
2869 }
2870
2871 default:
2872 if (delim && strchr (delim, c))
2873 wtype = w_static;
2874 break;
2875 }
2876
2877 /* Did we find something? If so, return now. */
2878 if (wtype != w_bogus)
2879 goto done;
2880
2881 /* This is some non-operator word. A word consists of the longest
2882 string of characters that doesn't contain whitespace, one of [:=#],
2883 or [?+]=, or one of the chars in the DELIM string. */
2884
2885 /* We start out assuming a static word; if we see a variable we'll
2886 adjust our assumptions then. */
2887 wtype = w_static;
2888
2889 /* We already found the first value of "c", above. */
2890 while (1)
2891 {
2892 char closeparen;
2893 int count;
2894
2895 switch (c)
2896 {
2897 case '\0':
2898 case ' ':
2899 case '\t':
2900 case '=':
2901 goto done_word;
2902
2903 case ':':
2904#ifdef HAVE_DOS_PATHS
2905 /* A word CAN include a colon in its drive spec. The drive
2906 spec is allowed either at the beginning of a word, or as part
2907 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2908 if (!(p - beg >= 2
2909 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2910 && (p - beg == 2 || p[-3] == '(')))
2911#endif
2912 goto done_word;
2913
2914 case '$':
2915 c = *(p++);
2916 if (c == '$')
2917 break;
2918
2919 /* This is a variable reference, so note that it's expandable.
2920 Then read it to the matching close paren. */
2921 wtype = w_variable;
2922
2923 if (c == '(')
2924 closeparen = ')';
2925 else if (c == '{')
2926 closeparen = '}';
2927 else
2928 /* This is a single-letter variable reference. */
2929 break;
2930
2931 for (count=0; *p != '\0'; ++p)
2932 {
2933 if (*p == c)
2934 ++count;
2935 else if (*p == closeparen && --count < 0)
2936 {
2937 ++p;
2938 break;
2939 }
2940 }
2941 break;
2942
2943 case '?':
2944 case '+':
2945 if (*p == '=')
2946 goto done_word;
2947 break;
2948
2949 case '\\':
2950 switch (*p)
2951 {
2952 case ':':
2953 case ';':
2954 case '=':
2955 case '\\':
2956 ++p;
2957 break;
2958 }
2959 break;
2960
2961 default:
2962 if (delim && strchr (delim, c))
2963 goto done_word;
2964 break;
2965 }
2966
2967 c = *(p++);
2968 }
2969 done_word:
2970 --p;
2971
2972 done:
2973 if (startp)
2974 *startp = beg;
2975 if (length)
2976 *length = p - beg;
2977 return wtype;
2978}
2979
2980
2981/* Construct the list of include directories
2982 from the arguments and the default list. */
2983
2984void
2985construct_include_path (const char **arg_dirs)
2986{
2987#ifdef VAXC /* just don't ask ... */
2988 stat_t stbuf;
2989#else
2990 struct stat stbuf;
2991#endif
2992 const char **dirs;
2993 const char **cpp;
2994 unsigned int idx;
2995
2996 /* Compute the number of pointers we need in the table. */
2997 idx = sizeof (default_include_directories) / sizeof (const char *);
2998 if (arg_dirs)
2999 for (cpp = arg_dirs; *cpp != 0; ++cpp)
3000 ++idx;
3001
3002#ifdef __MSDOS__
3003 /* Add one for $DJDIR. */
3004 ++idx;
3005#endif
3006
3007 dirs = xmalloc (idx * sizeof (const char *));
3008
3009 idx = 0;
3010 max_incl_len = 0;
3011
3012 /* First consider any dirs specified with -I switches.
3013 Ignore any that don't exist. Remember the maximum string length. */
3014
3015 if (arg_dirs)
3016 while (*arg_dirs != 0)
3017 {
3018 const char *dir = *(arg_dirs++);
3019 char *expanded = 0;
3020 int e;
3021
3022 if (dir[0] == '~')
3023 {
3024 expanded = tilde_expand (dir);
3025 if (expanded != 0)
3026 dir = expanded;
3027 }
3028
3029 EINTRLOOP (e, stat (dir, &stbuf));
3030 if (e == 0 && S_ISDIR (stbuf.st_mode))
3031 {
3032 unsigned int len = strlen (dir);
3033 /* If dir name is written with trailing slashes, discard them. */
3034 while (len > 1 && dir[len - 1] == '/')
3035 --len;
3036 if (len > max_incl_len)
3037 max_incl_len = len;
3038 dirs[idx++] = strcache_add_len (dir, len);
3039 }
3040
3041 if (expanded)
3042 free (expanded);
3043 }
3044
3045 /* Now add the standard default dirs at the end. */
3046
3047#ifdef __MSDOS__
3048 {
3049 /* The environment variable $DJDIR holds the root of the DJGPP directory
3050 tree; add ${DJDIR}/include. */
3051 struct variable *djdir = lookup_variable ("DJDIR", 5);
3052
3053 if (djdir)
3054 {
3055 unsigned int len = strlen (djdir->value) + 8;
3056 char *defdir = alloca (len + 1);
3057
3058 strcat (strcpy (defdir, djdir->value), "/include");
3059 dirs[idx++] = strcache_add (defdir);
3060
3061 if (len > max_incl_len)
3062 max_incl_len = len;
3063 }
3064 }
3065#endif
3066
3067 for (cpp = default_include_directories; *cpp != 0; ++cpp)
3068 {
3069 int e;
3070
3071 EINTRLOOP (e, stat (*cpp, &stbuf));
3072 if (e == 0 && S_ISDIR (stbuf.st_mode))
3073 {
3074 unsigned int len = strlen (*cpp);
3075 /* If dir name is written with trailing slashes, discard them. */
3076 while (len > 1 && (*cpp)[len - 1] == '/')
3077 --len;
3078 if (len > max_incl_len)
3079 max_incl_len = len;
3080 dirs[idx++] = strcache_add_len (*cpp, len - 1);
3081 }
3082 }
3083
3084 dirs[idx] = 0;
3085
3086 /* Now add each dir to the .INCLUDE_DIRS variable. */
3087
3088 for (cpp = dirs; *cpp != 0; ++cpp)
3089 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
3090 o_default, f_append, 0);
3091
3092 include_directories = dirs;
3093}
3094
3095
3096/* Expand ~ or ~USER at the beginning of NAME.
3097 Return a newly malloc'd string or 0. */
3098
3099char *
3100tilde_expand (const char *name)
3101{
3102#ifndef VMS
3103 if (name[1] == '/' || name[1] == '\0')
3104 {
3105 extern char *getenv ();
3106 char *home_dir;
3107 int is_variable;
3108
3109 {
3110 /* Turn off --warn-undefined-variables while we expand HOME. */
3111 int save = warn_undefined_variables_flag;
3112 warn_undefined_variables_flag = 0;
3113
3114 home_dir = allocated_variable_expand ("$(HOME)");
3115
3116 warn_undefined_variables_flag = save;
3117 }
3118
3119 is_variable = home_dir[0] != '\0';
3120 if (!is_variable)
3121 {
3122 free (home_dir);
3123 home_dir = getenv ("HOME");
3124 }
3125# if !defined(_AMIGA) && !defined(WINDOWS32)
3126 if (home_dir == 0 || home_dir[0] == '\0')
3127 {
3128 extern char *getlogin ();
3129 char *logname = getlogin ();
3130 home_dir = 0;
3131 if (logname != 0)
3132 {
3133 struct passwd *p = getpwnam (logname);
3134 if (p != 0)
3135 home_dir = p->pw_dir;
3136 }
3137 }
3138# endif /* !AMIGA && !WINDOWS32 */
3139 if (home_dir != 0)
3140 {
3141 char *new = xstrdup (concat (home_dir, "", name + 1));
3142 if (is_variable)
3143 free (home_dir);
3144 return new;
3145 }
3146 }
3147# if !defined(_AMIGA) && !defined(WINDOWS32)
3148 else
3149 {
3150 struct passwd *pwent;
3151 char *userend = strchr (name + 1, '/');
3152 if (userend != 0)
3153 *userend = '\0';
3154 pwent = getpwnam (name + 1);
3155 if (pwent != 0)
3156 {
3157 if (userend == 0)
3158 return xstrdup (pwent->pw_dir);
3159 else
3160 return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
3161 }
3162 else if (userend != 0)
3163 *userend = '/';
3164 }
3165# endif /* !AMIGA && !WINDOWS32 */
3166#endif /* !VMS */
3167 return 0;
3168}
3169
3170/* Given a chain of struct nameseq's describing a sequence of filenames,
3171 in reverse of the intended order, return a new chain describing the
3172 result of globbing the filenames. The new chain is in forward order.
3173 The links of the old chain are freed or used in the new chain.
3174 Likewise for the names in the old chain.
3175
3176 SIZE is how big to construct chain elements.
3177 This is useful if we want them actually to be other structures
3178 that have room for additional info. */
3179
3180struct nameseq *
3181multi_glob (struct nameseq *chain, unsigned int size)
3182{
3183 void dir_setup_glob (glob_t *);
3184 struct nameseq *new = 0;
3185 struct nameseq *old;
3186 struct nameseq *nexto;
3187 glob_t gl;
3188#if defined(KMK) || defined(__EMX__) /* speed optimization */
3189 int rc;
3190#endif
3191
3192 dir_setup_glob (&gl);
3193
3194 for (old = chain; old != 0; old = nexto)
3195 {
3196 const char *gname;
3197#ifndef NO_ARCHIVES
3198 char *arname = 0;
3199 char *memname = 0;
3200#endif
3201 nexto = old->next;
3202 gname = old->name;
3203
3204 if (gname[0] == '~')
3205 {
3206 char *newname = tilde_expand (old->name);
3207 if (newname != 0)
3208 gname = newname;
3209 }
3210
3211#ifndef NO_ARCHIVES
3212 if (ar_name (gname))
3213 {
3214 /* OLD->name is an archive member reference. Replace it with the
3215 archive file name, and save the member name in MEMNAME. We will
3216 glob on the archive name and then reattach MEMNAME later. */
3217 ar_parse_name (gname, &arname, &memname);
3218 gname = arname;
3219 }
3220#endif /* !NO_ARCHIVES */
3221
3222#if defined(KMK) || defined(__EMX__) /* speed optimization */
3223 if (!strpbrk(gname, "*?["))
3224 {
3225 gl.gl_pathc = 1;
3226 gl.gl_pathv = (char *)&gname;
3227 rc = 0;
3228 }
3229 else
3230 rc = glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl);
3231 switch (rc)
3232#else
3233 switch (glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
3234#endif
3235 {
3236 case 0: /* Success. */
3237 {
3238 int i = gl.gl_pathc;
3239 while (i-- > 0)
3240 {
3241#ifndef NO_ARCHIVES
3242 if (memname != 0)
3243 {
3244 /* Try to glob on MEMNAME within the archive. */
3245 struct nameseq *found
3246 = ar_glob (gl.gl_pathv[i], memname, size);
3247 if (! found)
3248 {
3249 /* No matches. Use MEMNAME as-is. */
3250 unsigned int alen = strlen (gl.gl_pathv[i]);
3251 unsigned int mlen = strlen (memname);
3252 char *name;
3253 struct nameseq *elt = xmalloc (size);
3254 memset (elt, '\0', size);
3255
3256 name = alloca (alen + 1 + mlen + 2);
3257 memcpy (name, gl.gl_pathv[i], alen);
3258 name[alen] = '(';
3259 memcpy (name+alen+1, memname, mlen);
3260 name[alen + 1 + mlen] = ')';
3261 name[alen + 1 + mlen + 1] = '\0';
3262 elt->name = strcache_add (name);
3263 elt->next = new;
3264 new = elt;
3265 }
3266 else
3267 {
3268 /* Find the end of the FOUND chain. */
3269 struct nameseq *f = found;
3270 while (f->next != 0)
3271 f = f->next;
3272
3273 /* Attach the chain being built to the end of the FOUND
3274 chain, and make FOUND the new NEW chain. */
3275 f->next = new;
3276 new = found;
3277 }
3278 }
3279 else
3280#endif /* !NO_ARCHIVES */
3281 {
3282 struct nameseq *elt = xmalloc (size);
3283 memset (elt, '\0', size);
3284 elt->name = strcache_add (gl.gl_pathv[i]);
3285 elt->next = new;
3286 new = elt;
3287 }
3288 }
3289#if defined(KMK) || defined(__EMX__) /* speed optimization */
3290 if (gl.gl_pathv != &gname)
3291#endif
3292 globfree (&gl);
3293 free (old);
3294 break;
3295 }
3296
3297 case GLOB_NOSPACE:
3298 fatal (NILF, _("virtual memory exhausted"));
3299 break;
3300
3301 default:
3302 old->next = new;
3303 new = old;
3304 break;
3305 }
3306
3307#ifndef NO_ARCHIVES
3308 if (arname)
3309 free (arname);
3310#endif
3311 }
3312
3313 return new;
3314}
Note: See TracBrowser for help on using the repository browser.