1 /* Implicit rule searching for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
6 
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
11 
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 
16 You should have received a copy of the GNU General Public License along with
17 this program.  If not, see <http://www.gnu.org/licenses/>.  */
18 
19 #include "make.h"
20 #include "filedef.h"
21 #include "rule.h"
22 #include "dep.h"
23 #include "debug.h"
24 #include "variable.h"
25 #include "job.h"      /* struct child, used inside commands.h */
26 #include "commands.h" /* set_file_variables */
27 
28 static int pattern_search (struct file *file, int archive,
29                            unsigned int depth, unsigned int recursions);
30 
31 /* For a FILE which has no commands specified, try to figure out some
32    from the implicit pattern rules.
33    Returns 1 if a suitable implicit rule was found,
34    after modifying FILE to contain the appropriate commands and deps,
35    or returns 0 if no implicit rule was found.  */
36 
37 int
try_implicit_rule(struct file * file,unsigned int depth)38 try_implicit_rule (struct file *file, unsigned int depth)
39 {
40   DBF (DB_IMPLICIT, _("Looking for an implicit rule for `%s'.\n"));
41 
42   /* The order of these searches was previously reversed.  My logic now is
43      that since the non-archive search uses more information in the target
44      (the archive search omits the archive name), it is more specific and
45      should come first.  */
46 
47   if (pattern_search (file, 0, depth, 0))
48     return 1;
49 
50 #ifndef NO_ARCHIVES
51   /* If this is an archive member reference, use just the
52      archive member name to search for implicit rules.  */
53   if (ar_name (file->name))
54     {
55       DBF (DB_IMPLICIT,
56            _("Looking for archive-member implicit rule for `%s'.\n"));
57       if (pattern_search (file, 1, depth, 0))
58         return 1;
59     }
60 #endif
61 
62   return 0;
63 }
64 
65 
66 /* Scans the BUFFER for the next word with whitespace as a separator.
67    Returns the pointer to the beginning of the word. LENGTH hold the
68    length of the word.  */
69 
70 static const char *
get_next_word(const char * buffer,unsigned int * length)71 get_next_word (const char *buffer, unsigned int *length)
72 {
73   const char *p = buffer, *beg;
74   char c;
75 
76   /* Skip any leading whitespace.  */
77   while (isblank ((unsigned char)*p))
78     ++p;
79 
80   beg = p;
81   c = *(p++);
82 
83   if (c == '\0')
84     {
85       if (length)   /* bird: shut up gcc. */
86         *length = 0;
87       return 0;
88     }
89 
90 
91   /* We already found the first value of "c", above.  */
92   while (1)
93     {
94       char closeparen;
95       int count;
96 
97       switch (c)
98         {
99         case '\0':
100         case ' ':
101         case '\t':
102           goto done_word;
103 
104         case '$':
105           c = *(p++);
106           if (c == '$')
107             break;
108 
109           /* This is a variable reference, so read it to the matching
110              close paren.  */
111 
112           if (c == '(')
113             closeparen = ')';
114           else if (c == '{')
115             closeparen = '}';
116           else
117             /* This is a single-letter variable reference.  */
118             break;
119 
120           for (count = 0; *p != '\0'; ++p)
121             {
122               if (*p == c)
123                 ++count;
124               else if (*p == closeparen && --count < 0)
125                 {
126                   ++p;
127                   break;
128                 }
129             }
130           break;
131 
132         case '|':
133           goto done;
134 
135         default:
136           break;
137         }
138 
139       c = *(p++);
140     }
141  done_word:
142   --p;
143 
144  done:
145   if (length)
146     *length = p - beg;
147 
148   return beg;
149 }
150 
151 /* This structure stores information about the expanded prerequisites for a
152    pattern rule.  NAME is always set to the strcache'd name of the prereq.
153    FILE and PATTERN will be set for intermediate files only.  IGNORE_MTIME is
154    copied from the prerequisite we expanded.
155  */
156 struct patdeps
157   {
158     const char *name;
159     const char *pattern;
160     struct file *file;
161     unsigned int ignore_mtime : 1;
162   };
163 
164 /* This structure stores information about pattern rules that we need
165    to try.
166 */
167 struct tryrule
168   {
169     struct rule *rule;
170 
171     /* Index of the target in this rule that matched the file. */
172     unsigned int matches;
173 
174     /* Stem length for this match. */
175     unsigned int stemlen;
176 
177     /* Definition order of this rule. Used to implement stable sort.*/
178     unsigned int order;
179 
180     /* Nonzero if the LASTSLASH logic was used in matching this rule. */
181     char checked_lastslash;
182   };
183 
184 int
stemlen_compare(const void * v1,const void * v2)185 stemlen_compare (const void *v1, const void *v2)
186 {
187   const struct tryrule *r1 = v1;
188   const struct tryrule *r2 = v2;
189   int r = r1->stemlen - r2->stemlen;
190   return r != 0 ? r : (int)(r1->order - r2->order);
191 }
192 
193 /* Search the pattern rules for a rule with an existing dependency to make
194    FILE.  If a rule is found, the appropriate commands and deps are put in FILE
195    and 1 is returned.  If not, 0 is returned.
196 
197    If ARCHIVE is nonzero, FILE->name is of the form "LIB(MEMBER)".  A rule for
198    "(MEMBER)" will be searched for, and "(MEMBER)" will not be chopped up into
199    directory and filename parts.
200 
201    If an intermediate file is found by pattern search, the intermediate file
202    is set up as a target by the recursive call and is also made a dependency
203    of FILE.
204 
205    DEPTH is used for debugging messages.  */
206 
207 static int
pattern_search(struct file * file,int archive,unsigned int depth,unsigned int recursions)208 pattern_search (struct file *file, int archive,
209                 unsigned int depth, unsigned int recursions)
210 {
211   /* Filename we are searching for a rule for.  */
212   const char *filename = archive ? strchr (file->name, '(') : file->name;
213 
214   /* Length of FILENAME.  */
215   unsigned int namelen = strlen (filename);
216 
217   /* The last slash in FILENAME (or nil if there is none).  */
218   const char *lastslash;
219 
220   /* This is a file-object used as an argument in
221      recursive calls.  It never contains any data
222      except during a recursive call.  */
223   struct file *int_file = 0;
224 
225   /* List of dependencies found recursively.  */
226   struct patdeps *deplist
227     = xmalloc (max_pattern_deps * sizeof (struct patdeps));
228   struct patdeps *pat = deplist;
229 
230   /* All the prerequisites actually found for a rule, after expansion.  */
231   struct dep *deps;
232 
233   /* Names of possible dependencies are constructed in this buffer.  */
234   char *depname = alloca (namelen + max_pattern_dep_length);
235 
236   /* The start and length of the stem of FILENAME for the current rule.  */
237   const char *stem = 0;
238   unsigned int stemlen = 0;
239   unsigned int fullstemlen = 0;
240 
241   /* Buffer in which we store all the rules that are possibly applicable.  */
242   struct tryrule *tryrules = xmalloc (num_pattern_rules * max_pattern_targets
243                                       * sizeof (struct tryrule));
244 
245   /* Number of valid elements in TRYRULES.  */
246   unsigned int nrules;
247 
248   /* The index in TRYRULES of the rule we found.  */
249   unsigned int foundrule;
250 
251   /* Nonzero if should consider intermediate files as dependencies.  */
252   int intermed_ok;
253 
254   /* Nonzero if we have initialized file variables for this target.  */
255   int file_vars_initialized = 0;
256 
257   /* Nonzero if we have matched a pattern-rule target
258      that is not just `%'.  */
259   int specific_rule_matched = 0;
260 
261   struct dep dep_simple;
262 
263   unsigned int ri;  /* uninit checks OK */
264   struct rule *rule;
265 
266   char *pathdir = NULL;
267   unsigned long pathlen;
268 
269   PATH_VAR (stem_str); /* @@ Need to get rid of stem, stemlen, etc. */
270 
271 #ifndef NO_ARCHIVES
272   if (archive || ar_name (filename))
273     lastslash = 0;
274   else
275 #endif
276     {
277       /* Set LASTSLASH to point at the last slash in FILENAME
278          but not counting any slash at the end.  (foo/bar/ counts as
279          bar/ in directory foo/, not empty in directory foo/bar/.)  */
280 #ifdef VMS
281       lastslash = strrchr (filename, ']');
282       if (lastslash == 0)
283         lastslash = strrchr (filename, ':');
284 #else
285       lastslash = strrchr (filename, '/');
286 #ifdef HAVE_DOS_PATHS
287       /* Handle backslashes (possibly mixed with forward slashes)
288          and the case of "d:file".  */
289       {
290         char *bslash = strrchr (filename, '\\');
291         if (lastslash == 0 || bslash > lastslash)
292           lastslash = bslash;
293         if (lastslash == 0 && filename[0] && filename[1] == ':')
294           lastslash = filename + 1;
295       }
296 #endif
297 #endif
298       if (lastslash != 0 && lastslash[1] == '\0')
299         lastslash = 0;
300     }
301 
302   pathlen = lastslash - filename + 1;
303 
304   /* First see which pattern rules match this target and may be considered.
305      Put them in TRYRULES.  */
306 
307   nrules = 0;
308   for (rule = pattern_rules; rule != 0; rule = rule->next)
309     {
310       unsigned int ti;
311 
312       /* If the pattern rule has deps but no commands, ignore it.
313          Users cancel built-in rules by redefining them without commands.  */
314       if (rule->deps != 0 && rule->cmds == 0)
315         continue;
316 
317       /* If this rule is in use by a parent pattern_search,
318          don't use it here.  */
319       if (rule->in_use)
320         {
321           DBS (DB_IMPLICIT, (_("Avoiding implicit rule recursion.\n")));
322           continue;
323         }
324 
325       for (ti = 0; ti < rule->num; ++ti)
326         {
327           const char *target = rule->targets[ti];
328           const char *suffix = rule->suffixes[ti];
329           int check_lastslash;
330 
331           /* Rules that can match any filename and are not terminal
332              are ignored if we're recursing, so that they cannot be
333              intermediate files.  */
334           if (recursions > 0 && target[1] == '\0' && !rule->terminal)
335             continue;
336 
337           if (rule->lens[ti] > namelen)
338             /* It can't possibly match.  */
339             continue;
340 
341           /* From the lengths of the filename and the pattern parts,
342              find the stem: the part of the filename that matches the %.  */
343           stem = filename + (suffix - target - 1);
344           stemlen = namelen - rule->lens[ti] + 1;
345 
346           /* Set CHECK_LASTSLASH if FILENAME contains a directory
347              prefix and the target pattern does not contain a slash.  */
348 
349           check_lastslash = 0;
350           if (lastslash)
351             {
352 #ifdef VMS
353               check_lastslash = (strchr (target, ']') == 0
354                                  && strchr (target, ':') == 0);
355 #else
356               check_lastslash = strchr (target, '/') == 0;
357 #ifdef HAVE_DOS_PATHS
358               /* Didn't find it yet: check for DOS-type directories.  */
359               if (check_lastslash)
360                 {
361                   char *b = strchr (target, '\\');
362                   check_lastslash = !(b || (target[0] && target[1] == ':'));
363                 }
364 #endif
365 #endif
366             }
367           if (check_lastslash)
368             {
369               /* If so, don't include the directory prefix in STEM here.  */
370               if (pathlen > stemlen)
371                 continue;
372               stemlen -= pathlen;
373               stem += pathlen;
374             }
375 
376           /* Check that the rule pattern matches the text before the stem.  */
377           if (check_lastslash)
378             {
379               if (stem > (lastslash + 1)
380                   && !strneq (target, lastslash + 1, stem - lastslash - 1))
381                 continue;
382             }
383           else if (stem > filename
384                    && !strneq (target, filename, stem - filename))
385             continue;
386 
387           /* Check that the rule pattern matches the text after the stem.
388              We could test simply use streq, but this way we compare the
389              first two characters immediately.  This saves time in the very
390              common case where the first character matches because it is a
391              period.  */
392           if (*suffix != stem[stemlen]
393               || (*suffix != '\0' && !streq (&suffix[1], &stem[stemlen + 1])))
394             continue;
395 
396           /* Record if we match a rule that not all filenames will match.  */
397           if (target[1] != '\0')
398             specific_rule_matched = 1;
399 
400           /* A rule with no dependencies and no commands exists solely to set
401              specific_rule_matched when it matches.  Don't try to use it.  */
402           if (rule->deps == 0 && rule->cmds == 0)
403             continue;
404 
405           /* Record this rule in TRYRULES and the index of the matching
406              target in MATCHES.  If several targets of the same rule match,
407              that rule will be in TRYRULES more than once.  */
408           tryrules[nrules].rule = rule;
409 	  tryrules[nrules].matches = ti;
410           tryrules[nrules].stemlen = stemlen + (check_lastslash ? pathlen : 0);
411           tryrules[nrules].order = nrules;
412 	  tryrules[nrules].checked_lastslash = check_lastslash;
413           ++nrules;
414         }
415     }
416 
417   /* Bail out early if we haven't found any rules. */
418   if (nrules == 0)
419     goto done;
420 
421   /* Sort the rules to place matches with the shortest stem first. This
422      way the most specific rules will be tried first. */
423   if (nrules > 1)
424     qsort (tryrules, nrules, sizeof (struct tryrule), stemlen_compare);
425 
426   /* If we have found a matching rule that won't match all filenames,
427      retroactively reject any non-"terminal" rules that do always match.  */
428   if (specific_rule_matched)
429     for (ri = 0; ri < nrules; ++ri)
430       if (!tryrules[ri].rule->terminal)
431         {
432           unsigned int j;
433           for (j = 0; j < tryrules[ri].rule->num; ++j)
434             if (tryrules[ri].rule->targets[j][1] == '\0')
435               {
436                 tryrules[ri].rule = 0;
437                 break;
438               }
439         }
440 
441   /* Try each rule once without intermediate files, then once with them.  */
442   for (intermed_ok = 0; intermed_ok < 2; ++intermed_ok)
443     {
444       pat = deplist;
445 
446       /* Try each pattern rule till we find one that applies.  If it does,
447          expand its dependencies (as substituted) and chain them in DEPS.  */
448       for (ri = 0; ri < nrules; ri++)
449         {
450           struct dep *dep;
451           int check_lastslash;
452           unsigned int failed = 0;
453           int file_variables_set = 0;
454           unsigned int deps_found = 0;
455           /* NPTR points to the part of the prereq we haven't processed.  */
456           const char *nptr = 0;
457           const char *dir = NULL;
458           int order_only = 0;
459           unsigned int matches;
460 
461           rule = tryrules[ri].rule;
462 
463           /* RULE is nil when we discover that a rule, already placed in
464              TRYRULES, should not be applied.  */
465           if (rule == 0)
466             continue;
467 
468           /* Reject any terminal rules if we're looking to make intermediate
469              files.  */
470           if (intermed_ok && rule->terminal)
471             continue;
472 
473           /* From the lengths of the filename and the matching pattern parts,
474              find the stem: the part of the filename that matches the %.  */
475           matches = tryrules[ri].matches;
476           stem = filename + (rule->suffixes[matches]
477                              - rule->targets[matches]) - 1;
478           stemlen = (namelen - rule->lens[matches]) + 1;
479           check_lastslash = tryrules[ri].checked_lastslash;
480           if (check_lastslash)
481             {
482               stem += pathlen;
483               stemlen -= pathlen;
484 
485               /* We need to add the directory prefix, so set it up.  */
486               if (! pathdir)
487                 {
488                   pathdir = alloca (pathlen + 1);
489                   memcpy (pathdir, filename, pathlen);
490                   pathdir[pathlen] = '\0';
491                 }
492               dir = pathdir;
493             }
494 
495           DBS (DB_IMPLICIT, (_("Trying pattern rule with stem `%.*s'.\n"),
496                              (int) stemlen, stem));
497 
498           strncpy (stem_str, stem, stemlen);
499           stem_str[stemlen] = '\0';
500 
501           /* If there are no prerequisites, then this rule matches.  */
502           if (rule->deps == 0)
503             break;
504 
505           /* Temporary assign STEM to file->stem (needed to set file
506              variables below).   */
507           file->stem = stem_str;
508 
509           /* Mark this rule as in use so a recursive pattern_search won't try
510              to use it.  */
511           rule->in_use = 1;
512 
513           /* Try each prerequisite; see if it exists or can be created.  We'll
514              build a list of prereq info in DEPLIST.  Due to 2nd expansion we
515              may have to process multiple prereqs for a single dep entry.  */
516 
517           pat = deplist;
518           dep = rule->deps;
519           nptr = dep_name (dep);
520           while (1)
521             {
522               struct dep *dl, *d;
523               char *p;
524 
525               /* If we're out of name to parse, start the next prereq.  */
526               if (! nptr)
527                 {
528                   dep = dep->next;
529                   if (dep == 0)
530                     break;
531                   nptr = dep_name (dep);
532                 }
533 
534               /* If we don't need a second expansion, just replace the %.  */
535               if (! dep->need_2nd_expansion)
536                 {
537                   dep_simple = *dep;
538                   dep_simple.next = 0;
539                   p = strchr (nptr, '%');
540                   if (p == 0)
541                     dep_simple.name = nptr;
542                   else
543                     {
544                       char *o = depname;
545                       if (check_lastslash)
546                         {
547                           memcpy (o, filename, pathlen);
548                           o += pathlen;
549                         }
550                       memcpy (o, nptr, p - nptr);
551                       o += p - nptr;
552                       memcpy (o, stem_str, stemlen);
553                       o += stemlen;
554                       strcpy (o, p + 1);
555                       dep_simple.name = strcache_add (depname);
556                     }
557                   dl = &dep_simple;
558 
559                   /* We've used up this dep, so next time get a new one.  */
560                   nptr = 0;
561                   ++deps_found;
562                 }
563 
564               /* We have to perform second expansion on this prereq.  In an
565                  ideal world we would take the dependency line, substitute the
566                  stem, re-expand the whole line and chop it into individual
567                  prerequisites.  Unfortunately this won't work because of the
568                  "check_lastslash" twist.  Instead, we will have to go word by
569                  word, taking $()'s into account.  For each word we will
570                  substitute the stem, re-expand, chop it up, and, if
571                  check_lastslash != 0, add the directory part to each
572                  resulting prerequisite.  */
573               else
574                 {
575                   int add_dir = 0;
576                   unsigned int len;
577 
578                   nptr = get_next_word (nptr, &len);
579                   if (nptr == 0)
580                     continue;
581 
582                   /* See this is a transition to order-only prereqs.  */
583                   if (! order_only && len == 1 && nptr[0] == '|')
584                     {
585                       order_only = 1;
586                       nptr += len;
587                       continue;
588                     }
589 
590                   /* If the dependency name has %, substitute the stem.  If we
591                      just replace % with the stem value then later, when we do
592                      the 2nd expansion, we will re-expand this stem value
593                      again.  This is not good if you have certain characters
594                      in your stem (like $).
595 
596                      Instead, we will replace % with $* and allow the second
597                      expansion to take care of it for us.  This way (since $*
598                      is a simple variable) there won't be additional
599                      re-expansion of the stem.  */
600 
601                   p = lindex (nptr, nptr + len, '%');
602                   if (p == 0)
603                     {
604                       memcpy (depname, nptr, len);
605                       depname[len] = '\0';
606                     }
607                   else
608                     {
609                       unsigned int i = p - nptr;
610                       memcpy (depname, nptr, i);
611                       memcpy (depname + i, "$*", 2);
612                       memcpy (depname + i + 2, p + 1, len - i - 1);
613                       depname[len + 2 - 1] = '\0';
614 
615                       if (check_lastslash)
616                         add_dir = 1;
617                     }
618 
619                   /* Initialize and set file variables if we haven't already
620                      done so. */
621                   if (!file_vars_initialized)
622                     {
623                       initialize_file_variables (file, 0);
624 #if defined(CONFIG_WITH_COMMANDS_FUNC) || defined (CONFIG_WITH_DOT_MUST_MAKE)
625                       set_file_variables (file, 0 /* real call */);
626 #else
627                       set_file_variables (file);
628 #endif
629                       file_vars_initialized = 1;
630                     }
631                   /* Update the stem value in $* for this rule.  */
632                   else if (!file_variables_set)
633                     {
634                       define_variable_for_file (
635                         "*", 1, file->stem, o_automatic, 0, file);
636                       file_variables_set = 1;
637                     }
638 
639                   /* Perform the 2nd expansion.  */
640                   p = variable_expand_for_file (depname, file);
641 
642                   /* Parse the expanded string. */
643                   dl = PARSE_FILE_SEQ (&p, struct dep, order_only ? '\0' : '|',
644                                        add_dir ? dir : NULL, 0);
645 
646                   for (d = dl; d != NULL; d = d->next)
647                     {
648                       ++deps_found;
649                       if (order_only)
650                         d->ignore_mtime = 1;
651                     }
652 
653                   /* Set up for the next word.  */
654                   nptr += len;
655                 }
656 
657               /* If there are more than max_pattern_deps prerequisites (due to
658                  2nd expansion), reset it and realloc the arrays.  */
659 
660               if (deps_found > max_pattern_deps)
661                 {
662                   unsigned int l = pat - deplist;
663                   deplist = xrealloc (deplist,
664                                       deps_found * sizeof (struct patdeps));
665                   pat = deplist + l;
666                   max_pattern_deps = deps_found;
667                 }
668 
669               /* Go through the nameseq and handle each as a prereq name.  */
670               for (d = dl; d != 0; d = d->next)
671                 {
672                   struct dep *expl_d;
673                   int is_rule = d->name == dep_name (dep);
674 
675                   if (file_impossible_p (d->name))
676                     {
677                       /* If this prereq has already been ruled "impossible",
678                          then the rule fails.  Don't bother trying it on the
679                          second pass either since we know that will fail.  */
680                       DBS (DB_IMPLICIT,
681                            (is_rule
682                             ? _("Rejecting impossible rule prerequisite `%s'.\n")
683                             : _("Rejecting impossible implicit prerequisite `%s'.\n"),
684                             d->name));
685                       tryrules[ri].rule = 0;
686 
687                       failed = 1;
688                       break;
689                     }
690 
691                   memset (pat, '\0', sizeof (struct patdeps));
692                   pat->ignore_mtime = d->ignore_mtime;
693 
694                   DBS (DB_IMPLICIT,
695                        (is_rule
696                         ? _("Trying rule prerequisite `%s'.\n")
697                         : _("Trying implicit prerequisite `%s'.\n"), d->name));
698 
699                   /* If this prereq is also explicitly mentioned for FILE,
700                      skip all tests below since it must be built no matter
701                      which implicit rule we choose. */
702 
703                   for (expl_d = file->deps; expl_d != 0; expl_d = expl_d->next)
704                     if (streq (dep_name (expl_d), d->name))
705                       break;
706                   if (expl_d != 0)
707                     {
708                       (pat++)->name = d->name;
709                       continue;
710                     }
711 
712                   /* The DEP->changed flag says that this dependency resides
713                      in a nonexistent directory.  So we normally can skip
714                      looking for the file.  However, if CHECK_LASTSLASH is
715                      set, then the dependency file we are actually looking for
716                      is in a different directory (the one gotten by prepending
717                      FILENAME's directory), so it might actually exist.  */
718 
719                   /* @@ dep->changed check is disabled. */
720                   if (lookup_file (d->name) != 0
721                       /*|| ((!dep->changed || check_lastslash) && */
722                       || file_exists_p (d->name))
723                     {
724                       (pat++)->name = d->name;
725                       continue;
726                     }
727 
728                   /* This code, given FILENAME = "lib/foo.o", dependency name
729                      "lib/foo.c", and VPATH=src, searches for
730                      "src/lib/foo.c".  */
731                   {
732                     const char *vname = vpath_search (d->name, 0, NULL, NULL);
733                     if (vname)
734                       {
735                         DBS (DB_IMPLICIT,
736                              (_("Found prerequisite `%s' as VPATH `%s'\n"),
737                               d->name, vname));
738                         (pat++)->name = d->name;
739                         continue;
740                       }
741                   }
742 
743                   /* We could not find the file in any place we should look.
744                      Try to make this dependency as an intermediate file, but
745                      only on the second pass.  */
746 
747                   if (intermed_ok)
748                     {
749                       DBS (DB_IMPLICIT,
750                            (_("Looking for a rule with intermediate file `%s'.\n"),
751                             d->name));
752 
753                       if (int_file == 0)
754                         int_file = alloca (sizeof (struct file));
755                       memset (int_file, '\0', sizeof (struct file));
756                       int_file->name = d->name;
757 
758                       if (pattern_search (int_file,
759                                           0,
760                                           depth + 1,
761                                           recursions + 1))
762                         {
763                           pat->pattern = int_file->name;
764                           int_file->name = d->name;
765                           pat->file = int_file;
766                           (pat++)->name = d->name;
767                           int_file = 0;
768                           continue;
769                         }
770 
771                       /* If we have tried to find P as an intermediate file
772                          and failed, mark that name as impossible so we won't
773                          go through the search again later.  */
774                       if (int_file->variables)
775                         free_variable_set (int_file->variables);
776                       if (int_file->pat_variables)
777                         free_variable_set (int_file->pat_variables);
778                       file_impossible (d->name);
779                     }
780 
781                   /* A dependency of this rule does not exist. Therefore, this
782                      rule fails.  */
783                   failed = 1;
784                   break;
785                 }
786 
787               /* Free the ns chain.  */
788               if (dl != &dep_simple)
789                 free_dep_chain (dl);
790 
791               if (failed)
792                 break;
793             }
794 
795           /* Reset the stem in FILE. */
796 
797           file->stem = 0;
798 
799           /* This rule is no longer `in use' for recursive searches.  */
800           rule->in_use = 0;
801 
802           if (! failed)
803             /* This pattern rule does apply.  Stop looking for one.  */
804             break;
805 
806           /* This pattern rule does not apply. If some of its dependencies
807              succeeded, free the data structure describing them.  */
808           /* free_idep_chain (deps); */
809           deps = 0;
810         }
811 
812       /* If we found an applicable rule without intermediate files, don't try
813          with them.  */
814       if (ri < nrules)
815         break;
816 
817       rule = 0;
818     }
819 
820   /* RULE is nil if the loop went through the list but everything failed.  */
821   if (rule == 0)
822     goto done;
823 
824   foundrule = ri;
825 
826   /* If we are recursing, store the pattern that matched FILENAME in
827      FILE->name for use in upper levels.  */
828 
829   if (recursions > 0)
830     /* Kludge-o-matic */
831     file->name = rule->targets[tryrules[foundrule].matches];
832 
833   /* DEPLIST lists the prerequisites for the rule we found.  This includes the
834      intermediate files, if any.  Convert them into entries on the deps-chain
835      of FILE.  */
836 
837   while (pat-- > deplist)
838     {
839       struct dep *dep;
840       const char *s;
841 
842       if (pat->file != 0)
843         {
844           /* If we need to use an intermediate file, make sure it is entered
845              as a target, with the info that was found for it in the recursive
846              pattern_search call.  We know that the intermediate file did not
847              already exist as a target; therefore we can assume that the deps
848              and cmds of F below are null before we change them.  */
849 
850           struct file *imf = pat->file;
851           struct file *f = lookup_file (imf->name);
852 
853           /* We don't want to delete an intermediate file that happened
854              to be a prerequisite of some (other) target. Mark it as
855              precious.  */
856           if (f != 0)
857             f->precious = 1;
858           else
859             f = enter_file (imf->name);
860 
861           f->deps = imf->deps;
862           f->cmds = imf->cmds;
863           f->stem = imf->stem;
864           f->variables = imf->variables;
865           f->pat_variables = imf->pat_variables;
866           f->pat_searched = imf->pat_searched;
867           f->also_make = imf->also_make;
868           f->is_target = 1;
869           f->intermediate = 1;
870           f->tried_implicit = 1;
871 
872           imf = lookup_file (pat->pattern);
873           if (imf != 0 && imf->precious)
874             f->precious = 1;
875 
876           for (dep = f->deps; dep != 0; dep = dep->next)
877             {
878               dep->file = enter_file (dep->name);
879               dep->name = 0;
880               dep->file->tried_implicit |= dep->changed;
881             }
882         }
883 
884       dep = alloc_dep ();
885       dep->ignore_mtime = pat->ignore_mtime;
886       s = strcache_add (pat->name);
887       if (recursions)
888         dep->name = s;
889       else
890         {
891           dep->file = lookup_file (s);
892           if (dep->file == 0)
893             dep->file = enter_file (s);
894         }
895 
896       if (pat->file == 0 && tryrules[foundrule].rule->terminal)
897         {
898           /* If the file actually existed (was not an intermediate file), and
899              the rule that found it was a terminal one, then we want to mark
900              the found file so that it will not have implicit rule search done
901              for it.  If we are not entering a `struct file' for it now, we
902              indicate this with the `changed' flag.  */
903           if (dep->file == 0)
904             dep->changed = 1;
905           else
906             dep->file->tried_implicit = 1;
907         }
908 
909       dep->next = file->deps;
910       file->deps = dep;
911     }
912 
913   if (!tryrules[foundrule].checked_lastslash)
914     {
915       /* Always allocate new storage, since STEM might be on the stack for an
916          intermediate file.  */
917       file->stem = strcache_add_len (stem, stemlen);
918       fullstemlen = stemlen;
919     }
920   else
921     {
922       int dirlen = (lastslash + 1) - filename;
923       char *sp;
924 
925       /* We want to prepend the directory from
926          the original FILENAME onto the stem.  */
927       fullstemlen = dirlen + stemlen;
928       sp = alloca (fullstemlen + 1);
929       memcpy (sp, filename, dirlen);
930       memcpy (sp + dirlen, stem, stemlen);
931       sp[fullstemlen] = '\0';
932 #ifndef CONFIG_WITH_VALUE_LENGTH
933       file->stem = strcache_add (sp);
934 #else
935       file->stem = strcache_add_len (sp, fullstemlen);
936 #endif
937     }
938 
939   file->cmds = rule->cmds;
940   file->is_target = 1;
941 
942   /* Set precious flag. */
943   {
944     struct file *f = lookup_file (rule->targets[tryrules[foundrule].matches]);
945     if (f && f->precious)
946       file->precious = 1;
947   }
948 
949   /* If this rule builds other targets, too, put the others into FILE's
950      `also_make' member.  */
951 
952   if (rule->num > 1)
953     for (ri = 0; ri < rule->num; ++ri)
954       if (ri != tryrules[foundrule].matches)
955         {
956           char *nm = alloca (rule->lens[ri] + fullstemlen + 1);
957           char *p = nm;
958           struct file *f;
959           struct dep *new = alloc_dep ();
960 
961           /* GKM FIMXE: handle '|' here too */
962           memcpy (p, rule->targets[ri],
963                   rule->suffixes[ri] - rule->targets[ri] - 1);
964           p += rule->suffixes[ri] - rule->targets[ri] - 1;
965           memcpy (p, file->stem, fullstemlen);
966           p += fullstemlen;
967           memcpy (p, rule->suffixes[ri],
968                   rule->lens[ri] - (rule->suffixes[ri] - rule->targets[ri])+1);
969           new->name = strcache_add (nm);
970           new->file = enter_file (new->name);
971           new->next = file->also_make;
972 
973           /* Set precious flag. */
974           f = lookup_file (rule->targets[ri]);
975           if (f && f->precious)
976             new->file->precious = 1;
977 
978           /* Set the is_target flag so that this file is not treated as
979              intermediate by the pattern rule search algorithm and
980              file_exists_p cannot pick it up yet.  */
981           new->file->is_target = 1;
982 
983           file->also_make = new;
984         }
985 
986  done:
987   free (tryrules);
988   free (deplist);
989 
990   return rule != 0;
991 }
992