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

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

PATH_KBUILD and PATH_KBUILD_BIN improvements. Avoid LOCALEDIR, ALIASDIR, LIBDIR and INCLUDEDIR.

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