(Goals): Say that only first target in first rule is default goal.
[make.git] / read.c
blob6b7d12213d18b20835b3728be24c1af199aa5d6e
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "commands.h"
21 #include "dep.h"
22 #include "file.h"
23 #include "variable.h"
25 /* This is POSIX.2, but most systems using -DPOSIX probably don't have it. */
26 #ifdef HAVE_GLOB_H
27 #include <glob.h>
28 #else
29 #include "glob/glob.h"
30 #endif
32 #include <pwd.h>
33 struct passwd *getpwnam ();
36 static int read_makefile ();
37 static unsigned int readline (), do_define ();
38 static int conditional_line ();
39 static void record_files ();
40 static char *find_semicolon ();
43 /* A `struct linebuffer' is a structure which holds a line of text.
44 `readline' reads a line from a stream into a linebuffer
45 and works regardless of the length of the line. */
47 struct linebuffer
49 /* Note: This is the number of bytes malloc'ed for `buffer'
50 It does not indicate `buffer's real length.
51 Instead, a null char indicates end-of-string. */
52 unsigned int size;
53 char *buffer;
56 #define initbuffer(lb) (lb)->buffer = (char *) xmalloc ((lb)->size = 200)
57 #define freebuffer(lb) free ((lb)->buffer)
60 /* A `struct conditionals' contains the information describing
61 all the active conditionals in a makefile.
63 The global variable `conditionals' contains the conditionals
64 information for the current makefile. It is initialized from
65 the static structure `toplevel_conditionals' and is later changed
66 to new structures for included makefiles. */
68 struct conditionals
70 unsigned int if_cmds; /* Depth of conditional nesting. */
71 unsigned int allocated; /* Elts allocated in following arrays. */
72 char *ignoring; /* Are we ignoring or interepreting? */
73 char *seen_else; /* Have we already seen an `else'? */
76 static struct conditionals toplevel_conditionals;
77 static struct conditionals *conditionals = &toplevel_conditionals;
80 /* Default directories to search for include files in */
82 static char *default_include_directories[] =
84 INCLUDEDIR,
85 "/usr/gnu/include",
86 "/usr/local/include",
87 "/usr/include",
91 /* List of directories to search for include files in */
93 static char **include_directories;
95 /* Maximum length of an element of the above. */
97 static unsigned int max_incl_len;
99 /* The filename and pointer to line number of the
100 makefile currently being read in. */
102 char *reading_filename;
103 unsigned int *reading_lineno_ptr;
105 /* The chain of makefiles read by read_makefile. */
107 static struct dep *read_makefiles = 0;
109 /* Read in all the makefiles and return the chain of their names. */
111 struct dep *
112 read_all_makefiles (makefiles)
113 char **makefiles;
115 unsigned int num_makefiles = 0;
117 if (debug_flag)
118 puts ("Reading makefiles...");
120 /* If there's a non-null variable MAKEFILES, its value is a list of
121 files to read first thing. But don't let it prevent reading the
122 default makefiles and don't let the default goal come from there. */
125 char *value;
126 char *name, *p;
127 unsigned int length;
130 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
131 int save = warn_undefined_variables_flag;
132 warn_undefined_variables_flag = 0;
134 value = allocated_variable_expand ("$(MAKEFILES)");
136 warn_undefined_variables_flag = save;
139 /* Set NAME to the start of next token and LENGTH to its length.
140 MAKEFILES is updated for finding remaining tokens. */
141 p = value;
142 while ((name = find_next_token (&p, &length)) != 0)
144 if (*p != '\0')
145 *p++ = '\0';
146 (void) read_makefile (name,
147 RM_NO_DEFAULT_GOAL | RM_INCLUDED | RM_DONTCARE);
150 free (value);
153 /* Read makefiles specified with -f switches. */
155 if (makefiles != 0)
156 while (*makefiles != 0)
158 struct dep *tail = read_makefiles;
159 register struct dep *d;
161 if (! read_makefile (*makefiles, 0))
162 perror_with_name ("", *makefiles);
164 /* Find the right element of read_makefiles. */
165 d = read_makefiles;
166 while (d->next != tail)
167 d = d->next;
169 /* Use the storage read_makefile allocates. */
170 *makefiles = dep_name (d);
171 ++num_makefiles;
172 ++makefiles;
175 /* If there were no -f switches, try the default names. */
177 if (num_makefiles == 0)
179 static char *default_makefiles[] =
180 { "GNUmakefile", "makefile", "Makefile", 0 };
181 register char **p = default_makefiles;
182 while (*p != 0 && !file_exists_p (*p))
183 ++p;
185 if (*p != 0)
187 if (! read_makefile (*p, 0))
188 perror_with_name ("", *p);
190 else
192 /* No default makefile was found. Add the default makefiles to the
193 `read_makefiles' chain so they will be updated if possible. */
194 struct dep *tail = read_makefiles;
195 for (p = default_makefiles; *p != 0; ++p)
197 struct dep *d = (struct dep *) xmalloc (sizeof (struct dep));
198 d->name = 0;
199 d->file = enter_file (*p);
200 d->file->dontcare = 1;
201 /* Tell update_goal_chain to bail out as soon as this file is
202 made, and main not to die if we can't make this file. */
203 d->changed = RM_DONTCARE;
204 if (tail == 0)
205 read_makefiles = d;
206 else
207 tail->next = d;
208 tail = d;
210 if (tail != 0)
211 tail->next = 0;
215 return read_makefiles;
218 /* Read file FILENAME as a makefile and add its contents to the data base.
220 FLAGS contains bits as above.
222 FILENAME is added to the `read_makefiles' chain.
224 Returns 1 if a file was found and read, 0 if not. */
226 static int
227 read_makefile (filename, flags)
228 char *filename;
229 int flags;
231 static char *collapsed = 0;
232 static unsigned int collapsed_length = 0;
233 register FILE *infile;
234 struct linebuffer lb;
235 unsigned int commands_len = 200;
236 char *commands = (char *) xmalloc (200);
237 unsigned int commands_idx = 0;
238 unsigned int commands_started;
239 register char *p;
240 char *p2;
241 int ignoring = 0, in_ignored_define = 0;
242 int no_targets = 0; /* Set when reading a rule without targets. */
244 struct nameseq *filenames = 0;
245 struct dep *deps;
246 unsigned int lineno = 1;
247 unsigned int nlines = 0;
248 int two_colon;
249 char *pattern = 0, *pattern_percent;
251 int makefile_errno;
253 #define record_waiting_files() \
254 do \
256 if (filenames != 0) \
257 record_files (filenames, pattern, pattern_percent, deps, \
258 commands_started, commands, commands_idx, \
259 two_colon, filename, lineno, \
260 !(flags & RM_NO_DEFAULT_GOAL)); \
261 filenames = 0; \
262 commands_idx = 0; \
263 pattern = 0; \
264 } while (0)
266 #ifdef lint /* Suppress `used before set' messages. */
267 two_colon = 0;
268 #endif
270 if (debug_flag)
272 printf ("Reading makefile `%s'", filename);
273 if (flags & RM_NO_DEFAULT_GOAL)
274 printf (" (no default goal)");
275 if (flags & RM_INCLUDED)
276 printf (" (search path)");
277 if (flags & RM_DONTCARE)
278 printf (" (don't care)");
279 if (flags & RM_NO_TILDE)
280 printf (" (no ~ expansion)");
281 puts ("...");
284 /* First, get a stream to read. */
286 /* Expand ~ in FILENAME unless it came from `include',
287 in which case it was already done. */
288 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
290 char *expanded = tilde_expand (filename);
291 /* This is a possible memory leak, but I don't care. */
292 if (expanded != 0)
293 filename = expanded;
296 infile = fopen (filename, "r");
297 /* Save the error code so we print the right message later. */
298 makefile_errno = errno;
300 /* If the makefile wasn't found and it's either a makefile from
301 the `MAKEFILES' variable or an included makefile,
302 search the included makefile search path for this makefile. */
304 if (infile == 0 && (flags & RM_INCLUDED) && *filename != '/')
306 register unsigned int i;
307 for (i = 0; include_directories[i] != 0; ++i)
309 char *name = concat (include_directories[i], "/", filename);
310 infile = fopen (name, "r");
311 if (infile == 0)
312 free (name);
313 else
315 filename = name;
316 break;
321 /* Add FILENAME to the chain of read makefiles. */
322 deps = (struct dep *) xmalloc (sizeof (struct dep));
323 deps->next = read_makefiles;
324 read_makefiles = deps;
325 deps->name = 0;
326 deps->file = lookup_file (filename);
327 if (deps->file == 0)
329 deps->file = enter_file (savestring (filename, strlen (filename)));
330 if (flags & RM_DONTCARE)
331 deps->file->dontcare = 1;
333 filename = deps->file->name;
334 deps->changed = flags;
335 deps = 0;
337 /* If the makefile can't be found at all, give up entirely. */
339 if (infile == 0)
341 /* If we did some searching, errno has the error from the last
342 attempt, rather from FILENAME itself. Restore it in case the
343 caller wants to use it in a message. */
344 errno = makefile_errno;
345 return 0;
348 reading_filename = filename;
349 reading_lineno_ptr = &lineno;
351 /* Loop over lines in the file.
352 The strategy is to accumulate target names in FILENAMES, dependencies
353 in DEPS and commands in COMMANDS. These are used to define a rule
354 when the start of the next rule (or eof) is encountered. */
356 initbuffer (&lb);
358 while (!feof (infile))
360 lineno += nlines;
361 nlines = readline (&lb, infile, filename, lineno);
363 /* Check for a shell command line first.
364 If it is not one, we can stop treating tab specially. */
365 if (lb.buffer[0] == '\t')
367 /* This line is a probably shell command. */
368 unsigned int len;
370 if (no_targets)
371 /* Ignore the commands in a rule with no targets. */
372 continue;
374 /* If there is no preceding rule line, don't treat this line
375 as a command, even though it begins with a tab character.
376 SunOS 4 make appears to behave this way. */
378 if (filenames != 0)
380 if (ignoring)
381 /* Yep, this is a shell command, and we don't care. */
382 continue;
384 /* Append this command line to the line being accumulated. */
385 p = lb.buffer;
386 if (commands_idx == 0)
387 commands_started = lineno;
388 len = strlen (p);
389 if (len + 1 + commands_idx > commands_len)
391 commands_len = (len + 1 + commands_idx) * 2;
392 commands = (char *) xrealloc (commands, commands_len);
394 bcopy (p, &commands[commands_idx], len);
395 commands_idx += len;
396 commands[commands_idx++] = '\n';
398 continue;
402 /* This line is not a shell command line. Don't worry about tabs. */
404 if (collapsed_length < lb.size)
406 collapsed_length = lb.size;
407 if (collapsed != 0)
408 free (collapsed);
409 collapsed = (char *) xmalloc (collapsed_length);
411 strcpy (collapsed, lb.buffer);
412 /* Collapse continuation lines. */
413 collapse_continuations (collapsed);
414 remove_comments (collapsed);
416 /* strncmp is first to avoid dereferencing out into space. */
417 #define word1eq(s, l) (!strncmp (s, p, l) \
418 && (p[l] == '\0' || isblank (p[l])))
419 p = collapsed;
420 while (isspace (*p))
421 ++p;
422 if (*p == '\0')
423 /* This line is completely empty. */
424 continue;
426 /* We must first check for conditional and `define' directives before
427 ignoring anything, since they control what we will do with
428 following lines. */
430 if (!in_ignored_define
431 && (word1eq ("ifdef", 5) || word1eq ("ifndef", 6)
432 || word1eq ("ifeq", 4) || word1eq ("ifneq", 5)
433 || word1eq ("else", 4) || word1eq ("endif", 5)))
435 int i = conditional_line (p, filename, lineno);
436 if (i >= 0)
437 ignoring = i;
438 else
439 makefile_fatal (filename, lineno,
440 "invalid syntax in conditional");
441 continue;
443 else if (word1eq ("endef", 5))
445 if (in_ignored_define)
446 in_ignored_define = 0;
447 else
448 makefile_fatal (filename, lineno, "extraneous `endef'");
449 continue;
451 else if (word1eq ("define", 6))
453 if (ignoring)
454 in_ignored_define = 1;
455 else
457 p2 = next_token (p + 6);
458 /* Let the variable name be the whole rest of the line,
459 with trailing blanks stripped (comments have already been
460 removed), so it could be a complex variable/function
461 reference that might contain blanks. */
462 p = index (p2, '\0');
463 while (isblank (p[-1]))
464 --p;
465 lineno = do_define (p2, p - p2, o_file,
466 lineno, infile, filename);
468 continue;
470 else if (word1eq ("override", 8))
472 p2 = next_token (p + 8);
473 if (p2 == 0)
474 makefile_error (filename, lineno, "empty `override' directive");
475 if (!strncmp (p2, "define", 6) && (isblank (p2[6]) || p2[6] == '\0'))
477 if (ignoring)
478 in_ignored_define = 1;
479 else
481 p2 = next_token (p2 + 6);
482 /* Let the variable name be the whole rest of the line,
483 with trailing blanks stripped (comments have already been
484 removed), so it could be a complex variable/function
485 reference that might contain blanks. */
486 p = index (p2, '\0');
487 while (isblank (p[-1]))
488 --p;
489 lineno = do_define (p2, p - p2, o_override,
490 lineno, infile, filename);
493 else if (!ignoring
494 && !try_variable_definition (filename, lineno,
495 p2, o_override))
496 makefile_error (filename, lineno, "empty `override' directive");
498 continue;
501 if (ignoring)
502 /* Ignore the line. We continue here so conditionals
503 can appear in the middle of a rule. */
504 continue;
505 else if (word1eq ("export", 6))
507 struct variable *v;
508 p2 = next_token (p + 6);
509 if (*p2 == '\0')
510 export_all_variables = 1;
511 v = try_variable_definition (filename, lineno, p2, o_file);
512 if (v != 0)
513 v->export = v_export;
514 else
516 unsigned int len;
517 for (p = find_next_token (&p2, &len); p != 0;
518 p = find_next_token (&p2, &len))
520 v = lookup_variable (p, len);
521 if (v == 0)
522 v = define_variable (p, len, "", o_file, 0);
523 v->export = v_export;
527 else if (word1eq ("unexport", 8))
529 unsigned int len;
530 struct variable *v;
531 p2 = next_token (p + 8);
532 if (*p2 == '\0')
533 export_all_variables = 0;
534 for (p = find_next_token (&p2, &len); p != 0;
535 p = find_next_token (&p2, &len))
537 v = lookup_variable (p, len);
538 if (v == 0)
539 v = define_variable (p, len, "", o_file, 0);
540 v->export = v_noexport;
543 else if (word1eq ("include", 7) || word1eq ("-include", 8))
545 /* We have found an `include' line specifying a nested
546 makefile to be read at this point. */
547 struct conditionals *save, new_conditionals;
548 struct nameseq *files;
549 /* "-include" (vs "include") says no
550 error if the file does not exist. */
551 int noerror = p[0] == '-';
553 p = allocated_variable_expand (next_token (p + (noerror ? 9 : 8)));
554 if (*p == '\0')
556 makefile_error (filename, lineno,
557 "no file name for `%sinclude'",
558 noerror ? "-" : "");
559 continue;
562 /* Parse the list of file names. */
563 p2 = p;
564 files = multi_glob (parse_file_seq (&p2, '\0',
565 sizeof (struct nameseq),
567 sizeof (struct nameseq));
568 free (p);
570 /* Save the state of conditionals and start
571 the included makefile with a clean slate. */
572 save = conditionals;
573 bzero ((char *) &new_conditionals, sizeof new_conditionals);
574 conditionals = &new_conditionals;
576 /* Record the rules that are waiting so they will determine
577 the default goal before those in the included makefile. */
578 record_waiting_files ();
580 /* Read each included makefile. */
581 while (files != 0)
583 struct nameseq *next = files->next;
584 char *name = files->name;
585 free (files);
586 files = next;
588 if (! read_makefile (name, (RM_INCLUDED | RM_NO_TILDE
589 | (noerror ? RM_DONTCARE : 0)))
590 && ! noerror)
591 makefile_error (filename, lineno,
592 "%s: %s", name, strerror (errno));
595 /* Free any space allocated by conditional_line. */
596 if (conditionals->ignoring)
597 free (conditionals->ignoring);
598 if (conditionals->seen_else)
599 free (conditionals->seen_else);
601 /* Restore state. */
602 conditionals = save;
603 reading_filename = filename;
604 reading_lineno_ptr = &lineno;
606 else if (word1eq ("vpath", 5))
608 char *pattern;
609 unsigned int len;
610 p2 = variable_expand (p + 5);
611 p = find_next_token (&p2, &len);
612 if (p != 0)
614 pattern = savestring (p, len);
615 p = find_next_token (&p2, &len);
616 /* No searchpath means remove all previous
617 selective VPATH's with the same pattern. */
619 else
620 /* No pattern means remove all previous selective VPATH's. */
621 pattern = 0;
622 construct_vpath_list (pattern, p);
623 if (pattern != 0)
624 free (pattern);
626 #undef word1eq
627 else if (try_variable_definition (filename, lineno, p, o_file))
628 /* This line has been dealt with. */
630 else if (lb.buffer[0] == '\t')
632 p = lb.buffer;
633 while (isblank (*p))
634 ++p;
635 if (*p == '\0')
636 /* The line is completely blank; that is harmless. */
637 continue;
638 /* This line starts with a tab but was not caught above
639 because there was no preceding target, and the line
640 might have been usable as a variable definition.
641 But now it is definitely lossage. */
642 makefile_fatal (filename, lineno,
643 "commands commence before first target");
645 else
647 /* This line describes some target files. */
649 char *cmdleft;
651 /* Record the previous rule. */
653 record_waiting_files ();
655 /* Look for a semicolon in the unexpanded line. */
656 cmdleft = find_semicolon (lb.buffer);
657 if (cmdleft != 0)
658 /* Found one. Cut the line short there before expanding it. */
659 *cmdleft = '\0';
661 collapse_continuations (lb.buffer);
663 /* Expand variable and function references before doing anything
664 else so that special characters can be inside variables. */
665 p = variable_expand (lb.buffer);
667 if (cmdleft == 0)
668 /* Look for a semicolon in the expanded line. */
669 cmdleft = find_semicolon (p);
671 if (cmdleft != 0)
672 /* Cut the line short at the semicolon. */
673 *cmdleft = '\0';
675 /* Remove comments from the line. */
676 remove_comments (p);
678 p2 = next_token (p);
679 if (*p2 == '\0')
681 if (cmdleft != 0)
682 makefile_fatal (filename, lineno,
683 "missing rule before commands");
684 else
685 /* This line contained a variable reference that
686 expanded to nothing but whitespace. */
687 continue;
689 else if (*p2 == ':')
691 /* We accept and ignore rules without targets for
692 compatibility with SunOS 4 make. */
693 no_targets = 1;
694 continue;
697 filenames = multi_glob (parse_file_seq (&p2, ':',
698 sizeof (struct nameseq),
700 sizeof (struct nameseq));
701 if (*p2++ == '\0')
702 makefile_fatal (filename, lineno, "missing separator");
703 /* Is this a one-colon or two-colon entry? */
704 two_colon = *p2 == ':';
705 if (two_colon)
706 p2++;
708 /* We have some targets, so don't ignore the following commands. */
709 no_targets = 0;
711 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
712 p = index (p2, ':');
713 while (p != 0 && p[-1] == '\\')
715 register char *q = &p[-1];
716 register int backslash = 0;
717 while (*q-- == '\\')
718 backslash = !backslash;
719 if (backslash)
720 p = index (p + 1, ':');
721 else
722 break;
724 if (p != 0)
726 struct nameseq *target;
727 target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
728 ++p2;
729 if (target == 0)
730 makefile_fatal (filename, lineno, "missing target pattern");
731 else if (target->next != 0)
732 makefile_fatal (filename, lineno, "multiple target patterns");
733 pattern = target->name;
734 pattern_percent = find_percent (pattern);
735 if (pattern_percent == 0)
736 makefile_fatal (filename, lineno,
737 "target pattern contains no `%%'");
739 else
740 pattern = 0;
742 /* Parse the dependencies. */
743 deps = (struct dep *)
744 multi_glob (parse_file_seq (&p2, '\0', sizeof (struct dep), 1),
745 sizeof (struct dep));
747 commands_idx = 0;
748 if (cmdleft != 0)
750 /* Semicolon means rest of line is a command. */
751 unsigned int len = strlen (cmdleft + 1);
753 commands_started = lineno;
755 /* Add this command line to the buffer. */
756 if (len + 2 > commands_len)
758 commands_len = (len + 2) * 2;
759 commands = (char *) xrealloc (commands, commands_len);
761 bcopy (cmdleft + 1, commands, len);
762 commands_idx += len;
763 commands[commands_idx++] = '\n';
766 continue;
769 /* We get here except in the case that we just read a rule line.
770 Record now the last rule we read, so following spurious
771 commands are properly diagnosed. */
772 record_waiting_files ();
773 no_targets = 0;
776 if (conditionals->if_cmds)
777 makefile_fatal (filename, lineno, "missing `endif'");
779 /* At eof, record the last rule. */
780 record_waiting_files ();
782 freebuffer (&lb);
783 free ((char *) commands);
784 fclose (infile);
786 reading_filename = 0;
787 reading_lineno_ptr = 0;
789 return 1;
792 /* Execute a `define' directive.
793 The first line has already been read, and NAME is the name of
794 the variable to be defined. The following lines remain to be read.
795 LINENO, INFILE and FILENAME refer to the makefile being read.
796 The value returned is LINENO, updated for lines read here. */
798 static unsigned int
799 do_define (name, namelen, origin, lineno, infile, filename)
800 char *name;
801 unsigned int namelen;
802 enum variable_origin origin;
803 unsigned int lineno;
804 FILE *infile;
805 char *filename;
807 struct linebuffer lb;
808 unsigned int nlines = 0;
809 unsigned int length = 100;
810 char *definition = (char *) xmalloc (100);
811 register unsigned int idx = 0;
812 register char *p;
814 /* Expand the variable name. */
815 char *var = (char *) alloca (namelen + 1);
816 bcopy (name, var, namelen);
817 var[namelen] = '\0';
818 var = variable_expand (var);
820 initbuffer (&lb);
821 while (!feof (infile))
823 lineno += nlines;
824 nlines = readline (&lb, infile, filename, lineno);
826 collapse_continuations (lb.buffer);
828 p = next_token (lb.buffer);
829 if ((p[5] == '\0' || isblank (p[5])) && !strncmp (p, "endef", 5))
831 p += 5;
832 remove_comments (p);
833 if (*next_token (p) != '\0')
834 makefile_error (filename, lineno,
835 "Extraneous text after `endef' directive");
836 /* Define the variable. */
837 if (idx == 0)
838 definition[0] = '\0';
839 else
840 definition[idx - 1] = '\0';
841 (void) define_variable (var, strlen (var), definition, origin, 1);
842 free (definition);
843 freebuffer (&lb);
844 return lineno;
846 else
848 unsigned int len = strlen (lb.buffer);
850 /* Increase the buffer size if necessary. */
851 if (idx + len + 1 > length)
853 length = (idx + len) * 2;
854 definition = (char *) xrealloc (definition, length + 1);
857 bcopy (lb.buffer, &definition[idx], len);
858 idx += len;
859 /* Separate lines with a newline. */
860 definition[idx++] = '\n';
864 /* No `endef'!! */
865 makefile_fatal (filename, lineno, "missing `endef', unterminated `define'");
867 /* NOTREACHED */
868 return 0;
871 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
872 "ifneq", "else" and "endif".
873 LINE is the input line, with the command as its first word.
875 FILENAME and LINENO are the filename and line number in the
876 current makefile. They are used for error messages.
878 Value is -1 if the line is invalid,
879 0 if following text should be interpreted,
880 1 if following text should be ignored. */
882 static int
883 conditional_line (line, filename, lineno)
884 char *line;
885 char *filename;
886 unsigned int lineno;
888 int notdef;
889 char *cmdname;
890 register unsigned int i;
892 if (*line == 'i')
894 /* It's an "if..." command. */
895 notdef = line[2] == 'n';
896 if (notdef)
898 cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
899 line += cmdname[3] == 'd' ? 7 : 6;
901 else
903 cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
904 line += cmdname[2] == 'd' ? 6 : 5;
907 else
909 /* It's an "else" or "endif" command. */
910 notdef = line[1] == 'n';
911 cmdname = notdef ? "endif" : "else";
912 line += notdef ? 5 : 4;
915 line = next_token (line);
917 if (*cmdname == 'e')
919 if (*line != '\0')
920 makefile_error (filename, lineno,
921 "Extraneous text after `%s' directive",
922 cmdname);
923 /* "Else" or "endif". */
924 if (conditionals->if_cmds == 0)
925 makefile_fatal (filename, lineno, "extraneous `%s'", cmdname);
926 /* NOTDEF indicates an `endif' command. */
927 if (notdef)
928 --conditionals->if_cmds;
929 else if (conditionals->seen_else[conditionals->if_cmds - 1])
930 makefile_fatal (filename, lineno, "only one `else' per conditional");
931 else
933 /* Toggle the state of ignorance. */
934 conditionals->ignoring[conditionals->if_cmds - 1]
935 = !conditionals->ignoring[conditionals->if_cmds - 1];
936 /* Record that we have seen an `else' in this conditional.
937 A second `else' will be erroneous. */
938 conditionals->seen_else[conditionals->if_cmds - 1] = 1;
940 for (i = 0; i < conditionals->if_cmds; ++i)
941 if (conditionals->ignoring[i])
942 return 1;
943 return 0;
946 if (conditionals->allocated == 0)
948 conditionals->allocated = 5;
949 conditionals->ignoring = (char *) xmalloc (conditionals->allocated);
950 conditionals->seen_else = (char *) xmalloc (conditionals->allocated);
953 ++conditionals->if_cmds;
954 if (conditionals->if_cmds > conditionals->allocated)
956 conditionals->allocated += 5;
957 conditionals->ignoring = (char *)
958 xrealloc (conditionals->ignoring, conditionals->allocated);
959 conditionals->seen_else = (char *)
960 xrealloc (conditionals->seen_else, conditionals->allocated);
963 /* Record that we have seen an `if...' but no `else' so far. */
964 conditionals->seen_else[conditionals->if_cmds - 1] = 0;
966 /* Search through the stack to see if we're already ignoring. */
967 for (i = 0; i < conditionals->if_cmds - 1; ++i)
968 if (conditionals->ignoring[i])
970 /* We are already ignoring, so just push a level
971 to match the next "else" or "endif", and keep ignoring.
972 We don't want to expand variables in the condition. */
973 conditionals->ignoring[conditionals->if_cmds - 1] = 1;
974 return 1;
977 if (cmdname[notdef ? 3 : 2] == 'd')
979 /* "Ifdef" or "ifndef". */
980 struct variable *v;
981 register char *p = end_of_token (line);
982 i = p - line;
983 p = next_token (p);
984 if (*p != '\0')
985 return -1;
986 v = lookup_variable (line, i);
987 conditionals->ignoring[conditionals->if_cmds - 1]
988 = (v != 0 && *v->value != '\0') == notdef;
990 else
992 /* "Ifeq" or "ifneq". */
993 char *s1, *s2;
994 unsigned int len;
995 char termin = *line == '(' ? ',' : *line;
997 if (termin != ',' && termin != '"' && termin != '\'')
998 return -1;
1000 s1 = ++line;
1001 /* Find the end of the first string. */
1002 if (termin == ',')
1004 register int count = 0;
1005 for (; *line != '\0'; ++line)
1006 if (*line == '(')
1007 ++count;
1008 else if (*line == ')')
1009 --count;
1010 else if (*line == ',' && count <= 0)
1011 break;
1013 else
1014 while (*line != '\0' && *line != termin)
1015 ++line;
1017 if (*line == '\0')
1018 return -1;
1020 *line++ = '\0';
1022 s2 = variable_expand (s1);
1023 /* We must allocate a new copy of the expanded string because
1024 variable_expand re-uses the same buffer. */
1025 len = strlen (s2);
1026 s1 = (char *) alloca (len + 1);
1027 bcopy (s2, s1, len + 1);
1029 if (termin != ',')
1030 /* Find the start of the second string. */
1031 line = next_token (line);
1033 termin = termin == ',' ? ')' : *line;
1034 if (termin != ')' && termin != '"' && termin != '\'')
1035 return -1;
1037 /* Find the end of the second string. */
1038 if (termin == ')')
1040 register int count = 0;
1041 s2 = next_token (line);
1042 for (line = s2; *line != '\0'; ++line)
1044 if (*line == '(')
1045 ++count;
1046 else if (*line == ')')
1047 if (count <= 0)
1048 break;
1049 else
1050 --count;
1053 else
1055 ++line;
1056 s2 = line;
1057 while (*line != '\0' && *line != termin)
1058 ++line;
1061 if (*line == '\0')
1062 return -1;
1064 *line = '\0';
1065 line = next_token (++line);
1066 if (*line != '\0')
1067 makefile_error (filename, lineno,
1068 "Extraneous text after `%s' directive",
1069 cmdname);
1071 s2 = variable_expand (s2);
1072 conditionals->ignoring[conditionals->if_cmds - 1]
1073 = streq (s1, s2) == notdef;
1076 /* Search through the stack to see if we're ignoring. */
1077 for (i = 0; i < conditionals->if_cmds; ++i)
1078 if (conditionals->ignoring[i])
1079 return 1;
1080 return 0;
1083 /* Remove duplicate dependencies in CHAIN. */
1085 void
1086 uniquize_deps (chain)
1087 struct dep *chain;
1089 register struct dep *d;
1091 /* Make sure that no dependencies are repeated. This does not
1092 really matter for the purpose of updating targets, but it
1093 might make some names be listed twice for $^ and $?. */
1095 for (d = chain; d != 0; d = d->next)
1097 struct dep *last, *next;
1099 last = d;
1100 next = d->next;
1101 while (next != 0)
1102 if (streq (dep_name (d), dep_name (next)))
1104 struct dep *n = next->next;
1105 last->next = n;
1106 if (next->name != 0 && next->name != d->name)
1107 free (next->name);
1108 if (next != d)
1109 free ((char *) next);
1110 next = n;
1112 else
1114 last = next;
1115 next = next->next;
1120 /* Record a description line for files FILENAMES,
1121 with dependencies DEPS, commands to execute described
1122 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1123 TWO_COLON is nonzero if a double colon was used.
1124 If not nil, PATTERN is the `%' pattern to make this
1125 a static pattern rule, and PATTERN_PERCENT is a pointer
1126 to the `%' within it.
1128 The links of FILENAMES are freed, and so are any names in it
1129 that are not incorporated into other data structures. */
1131 static void
1132 record_files (filenames, pattern, pattern_percent, deps, commands_started,
1133 commands, commands_idx, two_colon, filename, lineno, set_default)
1134 struct nameseq *filenames;
1135 char *pattern, *pattern_percent;
1136 struct dep *deps;
1137 unsigned int commands_started;
1138 char *commands;
1139 unsigned int commands_idx;
1140 int two_colon;
1141 char *filename;
1142 unsigned int lineno;
1143 int set_default;
1145 struct nameseq *nextf;
1146 int implicit = 0;
1147 unsigned int max_targets, target_idx;
1148 char **targets = 0, **target_percents = 0;
1149 struct commands *cmds;
1151 if (commands_idx > 0)
1153 cmds = (struct commands *) xmalloc (sizeof (struct commands));
1154 cmds->filename = filename;
1155 cmds->lineno = commands_started;
1156 cmds->commands = savestring (commands, commands_idx);
1157 cmds->command_lines = 0;
1159 else
1160 cmds = 0;
1162 for (; filenames != 0; filenames = nextf)
1164 register char *name = filenames->name;
1165 register struct file *f;
1166 register struct dep *d;
1167 struct dep *this;
1168 char *implicit_percent;
1170 nextf = filenames->next;
1171 free ((char *) filenames);
1173 implicit_percent = find_percent (name);
1174 implicit |= implicit_percent != 0;
1176 if (implicit && pattern != 0)
1177 makefile_fatal (filename, lineno,
1178 "mixed implicit and static pattern rules");
1180 if (implicit && implicit_percent == 0)
1181 makefile_fatal (filename, lineno, "mixed implicit and normal rules");
1183 if (implicit)
1185 if (targets == 0)
1187 max_targets = 5;
1188 targets = (char **) xmalloc (5 * sizeof (char *));
1189 target_percents = (char **) xmalloc (5 * sizeof (char *));
1190 target_idx = 0;
1192 else if (target_idx == max_targets - 1)
1194 max_targets += 5;
1195 targets = (char **) xrealloc ((char *) targets,
1196 max_targets * sizeof (char *));
1197 target_percents
1198 = (char **) xrealloc ((char *) target_percents,
1199 max_targets * sizeof (char *));
1201 targets[target_idx] = name;
1202 target_percents[target_idx] = implicit_percent;
1203 ++target_idx;
1204 continue;
1207 /* If there are multiple filenames, copy the chain DEPS
1208 for all but the last one. It is not safe for the same deps
1209 to go in more than one place in the data base. */
1210 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1212 if (pattern != 0)
1213 /* If this is an extended static rule:
1214 `targets: target%pattern: dep%pattern; cmds',
1215 translate each dependency pattern into a plain filename
1216 using the target pattern and this target's name. */
1217 if (!pattern_matches (pattern, pattern_percent, name))
1219 /* Give a warning if the rule is meaningless. */
1220 makefile_error (filename, lineno,
1221 "target `%s' doesn't match the target pattern",
1222 name);
1223 this = 0;
1225 else
1227 /* We use patsubst_expand to do the work of translating
1228 the target pattern, the target's name and the dependencies'
1229 patterns into plain dependency names. */
1230 char *buffer = variable_expand ("");
1232 for (d = this; d != 0; d = d->next)
1234 char *o;
1235 char *percent = find_percent (d->name);
1236 if (percent == 0)
1237 continue;
1238 o = patsubst_expand (buffer, name, pattern, d->name,
1239 pattern_percent, percent);
1240 free (d->name);
1241 d->name = savestring (buffer, o - buffer);
1245 if (!two_colon)
1247 /* Single-colon. Combine these dependencies
1248 with others in file's existing record, if any. */
1249 f = enter_file (name);
1251 if (f->double_colon)
1252 makefile_fatal (filename, lineno,
1253 "target file `%s' has both : and :: entries",
1254 f->name);
1256 /* If CMDS == F->CMDS, this target was listed in this rule
1257 more than once. Just give a warning since this is harmless. */
1258 if (cmds != 0 && cmds == f->cmds)
1259 makefile_error
1260 (filename, lineno,
1261 "target `%s' given more than once in the same rule.",
1262 f->name);
1264 /* Check for two single-colon entries both with commands.
1265 Check is_target so that we don't lose on files such as .c.o
1266 whose commands were preinitialized. */
1267 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1269 makefile_error (cmds->filename, cmds->lineno,
1270 "warning: overriding commands for target `%s'",
1271 f->name);
1272 makefile_error (f->cmds->filename, f->cmds->lineno,
1273 "warning: ignoring old commands for target `%s'",
1274 f->name);
1277 f->is_target = 1;
1279 /* Defining .DEFAULT with no deps or cmds clears it. */
1280 if (f == default_file && this == 0 && cmds == 0)
1281 f->cmds = 0;
1282 if (cmds != 0)
1283 f->cmds = cmds;
1284 /* Defining .SUFFIXES with no dependencies
1285 clears out the list of suffixes. */
1286 if (f == suffix_file && this == 0)
1288 d = f->deps;
1289 while (d != 0)
1291 struct dep *nextd = d->next;
1292 free (d->name);
1293 free (d);
1294 d = nextd;
1296 f->deps = 0;
1298 else if (f->deps != 0)
1300 /* Add the file's old deps and the new ones in THIS together. */
1302 struct dep *firstdeps, *moredeps;
1303 if (cmds != 0)
1305 /* This is the rule with commands, so put its deps first.
1306 The rationale behind this is that $< expands to the
1307 first dep in the chain, and commands use $< expecting
1308 to get the dep that rule specifies. */
1309 firstdeps = this;
1310 moredeps = f->deps;
1312 else
1314 /* Append the new deps to the old ones. */
1315 firstdeps = f->deps;
1316 moredeps = this;
1319 if (firstdeps == 0)
1320 firstdeps = moredeps;
1321 else
1323 d = firstdeps;
1324 while (d->next != 0)
1325 d = d->next;
1326 d->next = moredeps;
1329 f->deps = firstdeps;
1331 else
1332 f->deps = this;
1334 /* If this is a static pattern rule, set the file's stem to
1335 the part of its name that matched the `%' in the pattern,
1336 so you can use $* in the commands. */
1337 if (pattern != 0)
1339 static char *percent = "%";
1340 char *buffer = variable_expand ("");
1341 char *o = patsubst_expand (buffer, name, pattern, percent,
1342 pattern_percent, percent);
1343 f->stem = savestring (buffer, o - buffer);
1346 else
1348 /* Double-colon. Make a new record
1349 even if the file already has one. */
1350 f = lookup_file (name);
1351 /* Check for both : and :: rules. Check is_target so
1352 we don't lose on default suffix rules or makefiles. */
1353 if (f != 0 && f->is_target && !f->double_colon)
1354 makefile_fatal (filename, lineno,
1355 "target file `%s' has both : and :: entries",
1356 f->name);
1357 f = enter_file (name);
1358 /* If there was an existing entry and it was a double-colon
1359 entry, enter_file will have returned a new one, making it the
1360 prev pointer of the old one, and setting its double_colon
1361 pointer to the first one. */
1362 if (f->double_colon == 0)
1363 /* This is the first entry for this name, so we must
1364 set its double_colon pointer to itself. */
1365 f->double_colon = f;
1366 f->is_target = 1;
1367 f->deps = this;
1368 f->cmds = cmds;
1371 /* Free name if not needed further. */
1372 if (f != 0 && name != f->name
1373 && (name < f->name || name > f->name + strlen (f->name)))
1375 free (name);
1376 name = f->name;
1379 /* See if this is first target seen whose name does
1380 not start with a `.', unless it contains a slash. */
1381 if (default_goal_file == 0 && set_default
1382 && (*name != '.' || index (name, '/') != 0))
1384 int reject = 0;
1386 /* If this file is a suffix, don't
1387 let it be the default goal file. */
1389 for (d = suffix_file->deps; d != 0; d = d->next)
1391 register struct dep *d2;
1392 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1394 reject = 1;
1395 break;
1397 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1399 register unsigned int len = strlen (dep_name (d2));
1400 if (strncmp (name, dep_name (d2), len))
1401 continue;
1402 if (streq (name + len, dep_name (d)))
1404 reject = 1;
1405 break;
1408 if (reject)
1409 break;
1412 if (!reject)
1413 default_goal_file = f;
1417 if (implicit)
1419 targets[target_idx] = 0;
1420 target_percents[target_idx] = 0;
1421 create_pattern_rule (targets, target_percents, two_colon, deps, cmds, 1);
1422 free ((char *) target_percents);
1426 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
1427 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
1428 Quoting backslashes are removed from STRING by compacting it into
1429 itself. Returns a pointer to the first unquoted STOPCHAR if there is
1430 one, or nil if there are none. */
1432 char *
1433 find_char_unquote (string, stopchar, blank)
1434 char *string;
1435 int stopchar;
1436 int blank;
1438 unsigned int string_len = strlen (string);
1439 register char *p = string;
1441 while (1)
1443 if (blank)
1445 while (*p != '\0' && *p != stopchar && !isblank (*p))
1446 ++p;
1447 if (*p == '\0')
1448 break;
1450 else
1452 p = index (p, stopchar);
1453 if (p == 0)
1454 break;
1456 if (p > string && p[-1] == '\\')
1458 /* Search for more backslashes. */
1459 register int i = -2;
1460 while (&p[i] >= string && p[i] == '\\')
1461 --i;
1462 ++i;
1463 /* The number of backslashes is now -I.
1464 Copy P over itself to swallow half of them. */
1465 bcopy (&p[i / 2], &p[i], (string_len - (p - string)) - (i / 2) + 1);
1466 p += i / 2;
1467 if (i % 2 == 0)
1468 /* All the backslashes quoted each other; the STOPCHAR was
1469 unquoted. */
1470 return p;
1472 /* The STOPCHAR was quoted by a backslash. Look for another. */
1474 else
1475 /* No backslash in sight. */
1476 return p;
1479 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
1480 return 0;
1483 /* Search PATTERN for an unquoted %. */
1485 char *
1486 find_percent (pattern)
1487 char *pattern;
1489 return find_char_unquote (pattern, '%', 0);
1492 /* Search STRING for an unquoted ; that is not after an unquoted #. */
1494 static char *
1495 find_semicolon (string)
1496 char *string;
1498 return (find_char_unquote (string, '#', 0) == 0
1499 ? find_char_unquote (string, ';', 0) : 0);
1502 /* Parse a string into a sequence of filenames represented as a
1503 chain of struct nameseq's in reverse order and return that chain.
1505 The string is passed as STRINGP, the address of a string pointer.
1506 The string pointer is updated to point at the first character
1507 not parsed, which either is a null char or equals STOPCHAR.
1509 SIZE is how big to construct chain elements.
1510 This is useful if we want them actually to be other structures
1511 that have room for additional info.
1513 If STRIP is nonzero, strip `./'s off the beginning. */
1515 struct nameseq *
1516 parse_file_seq (stringp, stopchar, size, strip)
1517 char **stringp;
1518 char stopchar;
1519 unsigned int size;
1520 int strip;
1522 register struct nameseq *new = 0;
1523 register struct nameseq *new1, *lastnew1;
1524 register char *p = *stringp;
1525 char *q;
1526 char *name;
1528 while (1)
1530 /* Skip whitespace; see if any more names are left. */
1531 p = next_token (p);
1532 if (*p == '\0')
1533 break;
1534 if (*p == stopchar)
1535 break;
1536 /* Yes, find end of next name. */
1537 q = p;
1538 p = find_char_unquote (q, stopchar, 1);
1539 if (p == 0)
1540 p = q + strlen (q);
1542 if (strip)
1543 /* Skip leading `./'s. */
1544 while (p - q > 2 && q[0] == '.' && q[1] == '/')
1546 q += 2; /* Skip "./". */
1547 while (q < p && *q == '/')
1548 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
1549 ++q;
1552 /* Extract the filename just found, and skip it. */
1554 if (q == p)
1555 /* ".///" was stripped to "". */
1556 name = savestring ("./", 2);
1557 else
1558 name = savestring (q, p - q);
1560 /* Add it to the front of the chain. */
1561 new1 = (struct nameseq *) xmalloc (size);
1562 new1->name = name;
1563 new1->next = new;
1564 new = new1;
1567 #ifndef NO_ARCHIVES
1569 /* Look for multi-word archive references.
1570 They are indicated by a elt ending with an unmatched `)' and
1571 an elt further down the chain (i.e., previous in the file list)
1572 with an unmatched `(' (e.g., "lib(mem"). */
1574 for (new1 = new, lastnew1 = 0; new1 != 0; lastnew1 = new1, new1 = new1->next)
1575 if (new1->name[0] != '(' /* Don't catch "(%)" and suchlike. */
1576 && new1->name[strlen (new1->name) - 1] == ')'
1577 && index (new1->name, '(') == 0)
1579 /* NEW1 ends with a `)' but does not contain a `('.
1580 Look back for an elt with an opening `(' but no closing `)'. */
1582 struct nameseq *n = new1->next, *lastn = new1;
1583 char *paren;
1584 while (n != 0 && (paren = index (n->name, '(')) == 0)
1586 lastn = n;
1587 n = n->next;
1589 if (n != 0
1590 /* Ignore something starting with `(', as that cannot actually
1591 be an archive-member reference (and treating it as such
1592 results in an empty file name, which causes much lossage). */
1593 && n->name[0] != '(')
1595 /* N is the first element in the archive group.
1596 Its name looks like "lib(mem" (with no closing `)'). */
1598 char *libname;
1600 /* Copy "lib(" into LIBNAME. */
1601 ++paren;
1602 libname = (char *) alloca (paren - n->name + 1);
1603 bcopy (n->name, libname, paren - n->name);
1604 libname[paren - n->name] = '\0';
1606 if (*paren == '\0')
1608 /* N was just "lib(", part of something like "lib( a b)".
1609 Edit it out of the chain and free its storage. */
1610 lastn->next = n->next;
1611 free (n->name);
1612 free ((char *) n);
1613 /* LASTN->next is the new stopping elt for the loop below. */
1614 n = lastn->next;
1616 else
1618 /* Replace N's name with the full archive reference. */
1619 name = concat (libname, paren, ")");
1620 free (n->name);
1621 n->name = name;
1624 if (new1->name[1] == '\0')
1626 /* NEW1 is just ")", part of something like "lib(a b )".
1627 Omit it from the chain and free its storage. */
1628 if (lastnew1 == 0)
1629 new = new1->next;
1630 else
1631 lastnew1->next = new1->next;
1632 lastn = new1;
1633 new1 = new1->next;
1634 free (lastn->name);
1635 free ((char *) lastn);
1637 else
1639 /* Replace also NEW1->name, which already has closing `)'. */
1640 name = concat (libname, new1->name, "");
1641 free (new1->name);
1642 new1->name = name;
1643 new1 = new1->next;
1646 /* Trace back from NEW1 (the end of the list) until N
1647 (the beginning of the list), rewriting each name
1648 with the full archive reference. */
1650 while (new1 != n)
1652 name = concat (libname, new1->name, ")");
1653 free (new1->name);
1654 new1->name = name;
1655 new1 = new1->next;
1658 if (new1 == 0)
1659 /* We might have slurped up the whole list,
1660 and continuing the loop would dereference NEW1. */
1661 break;
1665 #endif
1667 *stringp = p;
1668 return new;
1671 /* Read a line of text from STREAM into LINEBUFFER.
1672 Combine continuation lines into one line.
1673 Return the number of actual lines read (> 1 if hacked continuation lines).
1676 static unsigned int
1677 readline (linebuffer, stream, filename, lineno)
1678 struct linebuffer *linebuffer;
1679 FILE *stream;
1680 char *filename;
1681 unsigned int lineno;
1683 char *buffer = linebuffer->buffer;
1684 register char *p = linebuffer->buffer;
1685 register char *end = p + linebuffer->size;
1686 register int len, lastlen = 0;
1687 register char *p2;
1688 register unsigned int nlines = 0;
1689 register int backslash;
1691 *p = '\0';
1693 while (fgets (p, end - p, stream) != 0)
1695 len = strlen (p);
1696 if (len == 0)
1698 /* This only happens when the first thing on the line is a '\0'.
1699 It is a pretty hopeless case, but (wonder of wonders) Athena
1700 lossage strikes again! (xmkmf puts NULs in its makefiles.)
1701 There is nothing really to be done; we synthesize a newline so
1702 the following line doesn't appear to be part of this line. */
1703 makefile_error (filename, lineno,
1704 "warning: NUL character seen; rest of line ignored");
1705 p[0] = '\n';
1706 len = 1;
1709 p += len;
1710 if (p[-1] != '\n')
1712 /* Probably ran out of buffer space. */
1713 register unsigned int p_off = p - buffer;
1714 linebuffer->size *= 2;
1715 buffer = (char *) xrealloc (buffer, linebuffer->size);
1716 p = buffer + p_off;
1717 end = buffer + linebuffer->size;
1718 linebuffer->buffer = buffer;
1719 *p = '\0';
1720 lastlen = len;
1721 continue;
1724 ++nlines;
1726 if (len == 1 && p > buffer)
1727 /* P is pointing at a newline and it's the beginning of
1728 the buffer returned by the last fgets call. However,
1729 it is not necessarily the beginning of a line if P is
1730 pointing past the beginning of the holding buffer.
1731 If the buffer was just enlarged (right before the newline),
1732 we must account for that, so we pretend that the two lines
1733 were one line. */
1734 len += lastlen;
1735 lastlen = len;
1736 backslash = 0;
1737 for (p2 = p - 2; --len > 0; --p2)
1739 if (*p2 == '\\')
1740 backslash = !backslash;
1741 else
1742 break;
1745 if (!backslash)
1747 p[-1] = '\0';
1748 break;
1751 if (end - p <= 1)
1753 /* Enlarge the buffer. */
1754 register unsigned int p_off = p - buffer;
1755 linebuffer->size *= 2;
1756 buffer = (char *) xrealloc (buffer, linebuffer->size);
1757 p = buffer + p_off;
1758 end = buffer + linebuffer->size;
1759 linebuffer->buffer = buffer;
1763 if (ferror (stream))
1764 pfatal_with_name (filename);
1766 return nlines;
1769 /* Construct the list of include directories
1770 from the arguments and the default list. */
1772 void
1773 construct_include_path (arg_dirs)
1774 char **arg_dirs;
1776 register unsigned int i;
1777 struct stat stbuf;
1779 /* Table to hold the dirs. */
1781 register unsigned int defsize = (sizeof (default_include_directories)
1782 / sizeof (default_include_directories[0]));
1783 register unsigned int max = 5;
1784 register char **dirs = (char **) xmalloc ((5 + defsize) * sizeof (char *));
1785 register unsigned int idx = 0;
1787 /* First consider any dirs specified with -I switches.
1788 Ignore dirs that don't exist. */
1790 if (arg_dirs != 0)
1791 while (*arg_dirs != 0)
1793 char *dir = *arg_dirs++;
1795 if (dir[0] == '~')
1797 char *expanded = tilde_expand (dir);
1798 if (expanded != 0)
1799 dir = expanded;
1802 if (safe_stat (dir, &stbuf) == 0 && S_ISDIR (stbuf.st_mode))
1804 if (idx == max - 1)
1806 max += 5;
1807 dirs = (char **)
1808 xrealloc ((char *) dirs, (max + defsize) * sizeof (char *));
1810 dirs[idx++] = dir;
1812 else if (dir != arg_dirs[-1])
1813 free (dir);
1816 /* Now add at the end the standard default dirs. */
1818 for (i = 0; default_include_directories[i] != 0; ++i)
1819 if (safe_stat (default_include_directories[i], &stbuf) == 0
1820 && S_ISDIR (stbuf.st_mode))
1821 dirs[idx++] = default_include_directories[i];
1823 dirs[idx] = 0;
1825 /* Now compute the maximum length of any name in it. */
1827 max_incl_len = 0;
1828 for (i = 0; i < idx; ++i)
1830 unsigned int len = strlen (dirs[i]);
1831 /* If dir name is written with a trailing slash, discard it. */
1832 if (dirs[i][len - 1] == '/')
1833 /* We can't just clobber a null in because it may have come from
1834 a literal string and literal strings may not be writable. */
1835 dirs[i] = savestring (dirs[i], len - 1);
1836 if (len > max_incl_len)
1837 max_incl_len = len;
1840 include_directories = dirs;
1843 /* Expand ~ or ~USER at the beginning of NAME.
1844 Return a newly malloc'd string or 0. */
1846 char *
1847 tilde_expand (name)
1848 char *name;
1850 if (name[1] == '/' || name[1] == '\0')
1852 extern char *getenv ();
1853 char *home_dir;
1854 int is_variable;
1857 /* Turn off --warn-undefined-variables while we expand HOME. */
1858 int save = warn_undefined_variables_flag;
1859 warn_undefined_variables_flag = 0;
1861 home_dir = allocated_variable_expand ("$(HOME)");
1863 warn_undefined_variables_flag = save;
1866 is_variable = home_dir[0] != '\0';
1867 if (!is_variable)
1869 free (home_dir);
1870 home_dir = getenv ("HOME");
1872 if (home_dir == 0 || home_dir[0] == '\0')
1874 extern char *getlogin ();
1875 char *name = getlogin ();
1876 home_dir = 0;
1877 if (name != 0)
1879 struct passwd *p = getpwnam (name);
1880 if (p != 0)
1881 home_dir = p->pw_dir;
1884 if (home_dir != 0)
1886 char *new = concat (home_dir, "", name + 1);
1887 if (is_variable)
1888 free (home_dir);
1889 return new;
1892 else
1894 struct passwd *pwent;
1895 char *userend = index (name + 1, '/');
1896 if (userend != 0)
1897 *userend = '\0';
1898 pwent = getpwnam (name + 1);
1899 if (pwent != 0)
1901 if (userend == 0)
1902 return savestring (pwent->pw_dir, strlen (pwent->pw_dir));
1903 else
1904 return concat (pwent->pw_dir, "/", userend + 1);
1906 else if (userend != 0)
1907 *userend = '/';
1910 return 0;
1913 /* Given a chain of struct nameseq's describing a sequence of filenames,
1914 in reverse of the intended order, return a new chain describing the
1915 result of globbing the filenames. The new chain is in forward order.
1916 The links of the old chain are freed or used in the new chain.
1917 Likewise for the names in the old chain.
1919 SIZE is how big to construct chain elements.
1920 This is useful if we want them actually to be other structures
1921 that have room for additional info. */
1923 struct nameseq *
1924 multi_glob (chain, size)
1925 struct nameseq *chain;
1926 unsigned int size;
1928 register struct nameseq *new = 0;
1929 register struct nameseq *old;
1930 struct nameseq *nexto;
1932 for (old = chain; old != 0; old = nexto)
1934 glob_t gl;
1935 #ifndef NO_ARCHIVES
1936 char *memname;
1937 #endif
1939 nexto = old->next;
1941 if (old->name[0] == '~')
1943 char *newname = tilde_expand (old->name);
1944 if (newname != 0)
1946 free (old->name);
1947 old->name = newname;
1951 #ifndef NO_ARCHIVES
1952 if (ar_name (old->name))
1954 /* OLD->name is an archive member reference.
1955 Replace it with the archive file name,
1956 and save the member name in MEMNAME.
1957 We will glob on the archive name and then
1958 reattach MEMNAME later. */
1959 char *arname;
1960 ar_parse_name (old->name, &arname, &memname);
1961 free (old->name);
1962 old->name = arname;
1964 else
1965 memname = 0;
1966 #endif
1968 switch (glob (old->name, GLOB_NOCHECK, NULL, &gl))
1970 case 0: /* Success. */
1972 register int i = gl.gl_pathc;
1973 while (i-- > 0)
1975 #ifndef NO_ARCHIVES
1976 if (memname != 0)
1978 /* Try to glob on MEMNAME within the archive. */
1979 struct nameseq *found
1980 = ar_glob (gl.gl_pathv[i], memname, size);
1981 if (found == 0)
1983 /* No matches. Use MEMNAME as-is. */
1984 struct nameseq *elt
1985 = (struct nameseq *) xmalloc (size);
1986 unsigned int alen = strlen (gl.gl_pathv[i]);
1987 unsigned int mlen = strlen (memname);
1988 elt->name = (char *) xmalloc (alen + 1 + mlen + 2);
1989 bcopy (gl.gl_pathv[i], elt->name, alen);
1990 elt->name[alen] = '(';
1991 bcopy (memname, &elt->name[alen + 1], mlen);
1992 elt->name[alen + 1 + mlen] = ')';
1993 elt->name[alen + 1 + mlen + 1] = '\0';
1994 elt->next = new;
1995 new = elt;
1997 else
1999 /* Find the end of the FOUND chain. */
2000 struct nameseq *f = found;
2001 while (f->next != 0)
2002 f = f->next;
2004 /* Attach the chain being built to the end of the FOUND
2005 chain, and make FOUND the new NEW chain. */
2006 f->next = new;
2007 new = found;
2010 free (memname);
2012 else
2013 #endif
2015 struct nameseq *elt = (struct nameseq *) xmalloc (size);
2016 elt->name = savestring (gl.gl_pathv[i],
2017 strlen (gl.gl_pathv[i]));
2018 elt->next = new;
2019 new = elt;
2022 globfree (&gl);
2023 free (old->name);
2024 free (old);
2025 break;
2028 case GLOB_NOSPACE:
2029 fatal ("virtual memory exhausted");
2030 break;
2032 default:
2033 old->next = new;
2034 new = old;
2035 break;
2039 return new;