VirtualBox

source: kBuild/vendor/gnumake/current/read.c@ 3138

Last change on this file since 3138 was 3138, checked in by bird, 7 years ago

Imported make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6) from https://git.savannah.gnu.org/git/make.git.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette