7efca58bc61c74502ce15655502932a9d799e2a5
[platform/upstream/make.git] / src / rule.c
1 /* Pattern and suffix rule internals for GNU Make.
2 Copyright (C) 1988-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this 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
28 static void freerule (struct rule *rule, struct rule *lastrule);
29 \f
30 /* Chain of all pattern rules.  */
31
32 struct rule *pattern_rules;
33
34 /* Pointer to last rule in the chain, so we can add onto the end.  */
35
36 struct rule *last_pattern_rule;
37
38 /* Number of rules in the chain.  */
39
40 unsigned int num_pattern_rules;
41
42 /* Maximum number of target patterns of any pattern rule.  */
43
44 unsigned int max_pattern_targets;
45
46 /* Maximum number of dependencies of any pattern rule.  */
47
48 unsigned int max_pattern_deps;
49
50 /* Maximum length of the name of a dependencies of any pattern rule.  */
51
52 size_t max_pattern_dep_length;
53
54 /* Pointer to structure for the file .SUFFIXES
55    whose dependencies are the suffixes to be searched.  */
56
57 struct file *suffix_file;
58
59 /* Maximum length of a suffix.  */
60
61 static size_t maxsuffix;
62 \f
63 /* Compute the maximum dependency length and maximum number of dependencies of
64    all implicit rules.  Also sets the subdir flag for a rule when appropriate,
65    possibly removing the rule completely when appropriate.
66
67    Add any global EXTRA_PREREQS here as well.  */
68
69 void
70 snap_implicit_rules (void)
71 {
72   char *name = NULL;
73   size_t namelen = 0;
74   struct rule *rule;
75   struct dep *dep;
76   struct dep *prereqs = expand_extra_prereqs (lookup_variable (STRING_SIZE_TUPLE(".EXTRA_PREREQS")));
77   unsigned int pre_deps = 0;
78
79   max_pattern_dep_length = 0;
80
81   for (dep = prereqs; dep; dep = dep->next)
82     {
83       size_t l = strlen (dep_name (dep));
84       if (l > max_pattern_dep_length)
85         max_pattern_dep_length = l;
86       ++pre_deps;
87     }
88
89   num_pattern_rules = max_pattern_targets = max_pattern_deps = 0;
90
91   for (rule = pattern_rules; rule; rule = rule->next)
92     {
93       unsigned int ndeps = pre_deps;
94       struct dep *lastdep = NULL;
95
96       ++num_pattern_rules;
97
98       if (rule->num > max_pattern_targets)
99         max_pattern_targets = rule->num;
100
101       for (dep = rule->deps; dep != 0; dep = dep->next)
102         {
103           const char *dname = dep_name (dep);
104           size_t len = strlen (dname);
105
106 #ifdef VMS
107           const char *p = strrchr (dname, ']');
108           const char *p2;
109           if (p == 0)
110             p = strrchr (dname, ':');
111           p2 = p ? strchr (p, '%') : 0;
112 #else
113           const char *p = strrchr (dname, '/');
114           const char *p2 = p ? strchr (p, '%') : 0;
115 #endif
116           ndeps++;
117
118           if (len > max_pattern_dep_length)
119             max_pattern_dep_length = len;
120
121           if (!dep->next)
122             lastdep = dep;
123
124           if (p2)
125             {
126               /* There is a slash before the % in the dep name.
127                  Extract the directory name.  */
128               if (p == dname)
129                 ++p;
130               if ((size_t) (p - dname) > namelen)
131                 {
132                   namelen = p - dname;
133                   name = xrealloc (name, namelen + 1);
134                 }
135               memcpy (name, dname, p - dname);
136               name[p - dname] = '\0';
137
138               /* In the deps of an implicit rule the 'changed' flag
139                  actually indicates that the dependency is in a
140                  nonexistent subdirectory.  */
141
142               dep->changed = !dir_file_exists_p (name, "");
143             }
144           else
145             /* This dependency does not reside in a subdirectory.  */
146             dep->changed = 0;
147         }
148
149       if (prereqs)
150         {
151           if (lastdep)
152             lastdep->next = copy_dep_chain (prereqs);
153           else
154             rule->deps = copy_dep_chain (prereqs);
155         }
156
157       if (ndeps > max_pattern_deps)
158         max_pattern_deps = ndeps;
159     }
160
161   free (name);
162   free_dep_chain (prereqs);
163 }
164 \f
165 /* Create a pattern rule from a suffix rule.
166    TARGET is the target suffix; SOURCE is the source suffix.
167    CMDS are the commands.
168    If TARGET is nil, it means the target pattern should be '(%.o)'.
169    If SOURCE is nil, it means there should be no deps.  */
170
171 static void
172 convert_suffix_rule (const char *target, const char *source,
173                      struct commands *cmds)
174 {
175   const char **names, **percents;
176   struct dep *deps;
177
178   names = xmalloc (sizeof (const char *));
179   percents = xmalloc (sizeof (const char *));
180
181   if (target == 0)
182     {
183       /* Special case: TARGET being nil means we are defining a '.X.a' suffix
184          rule; the target pattern is always '(%.o)'.  */
185 #ifdef VMS
186       *names = strcache_add_len ("(%.obj)", 7);
187 #else
188       *names = strcache_add_len ("(%.o)", 5);
189 #endif
190       *percents = *names + 1;
191     }
192   else
193     {
194       /* Construct the target name.  */
195       size_t len = strlen (target);
196       char *p = alloca (1 + len + 1);
197       p[0] = '%';
198       memcpy (p + 1, target, len + 1);
199       *names = strcache_add_len (p, len + 1);
200       *percents = *names;
201     }
202
203   if (source == 0)
204     deps = 0;
205   else
206     {
207       /* Construct the dependency name.  */
208       size_t len = strlen (source);
209       char *p = alloca (1 + len + 1);
210       p[0] = '%';
211       memcpy (p + 1, source, len + 1);
212       deps = alloc_dep ();
213       deps->name = strcache_add_len (p, len + 1);
214     }
215
216   create_pattern_rule (names, percents, 1, 0, deps, cmds, 0);
217 }
218
219 /* Convert old-style suffix rules to pattern rules.
220    All rules for the suffixes on the .SUFFIXES list are converted and added to
221    the chain of pattern rules.  */
222
223 void
224 convert_to_pattern (void)
225 {
226   struct dep *d, *d2;
227   char *rulename;
228
229   /* We will compute every potential suffix rule (.x.y) from the list of
230      suffixes in the .SUFFIXES target's dependencies and see if it exists.
231      First find the longest of the suffixes.  */
232
233   maxsuffix = 0;
234   for (d = suffix_file->deps; d != 0; d = d->next)
235     {
236       size_t l = strlen (dep_name (d));
237       if (l > maxsuffix)
238         maxsuffix = l;
239     }
240
241   /* Space to construct the suffix rule target name.  */
242   rulename = alloca ((maxsuffix * 2) + 1);
243
244   for (d = suffix_file->deps; d != 0; d = d->next)
245     {
246       size_t slen;
247
248       /* Make a rule that is just the suffix, with no deps or commands.
249          This rule exists solely to disqualify match-anything rules.  */
250       convert_suffix_rule (dep_name (d), 0, 0);
251
252       if (d->file->cmds != 0)
253         /* Record a pattern for this suffix's null-suffix rule.  */
254         convert_suffix_rule ("", dep_name (d), d->file->cmds);
255
256       /* Add every other suffix to this one and see if it exists as a
257          two-suffix rule.  */
258       slen = strlen (dep_name (d));
259       memcpy (rulename, dep_name (d), slen);
260
261       for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
262         {
263           struct file *f;
264           size_t s2len;
265
266           s2len = strlen (dep_name (d2));
267
268           /* Can't build something from itself.  */
269           if (slen == s2len && streq (dep_name (d), dep_name (d2)))
270             continue;
271
272           memcpy (rulename + slen, dep_name (d2), s2len + 1);
273           f = lookup_file (rulename);
274
275           /* No target, or no commands: it can't be a suffix rule.  */
276           if (f == 0 || f->cmds == 0)
277             continue;
278
279           /* POSIX says that suffix rules can't have prerequisites.
280              In POSIX mode, don't make this a suffix rule.  Previous versions
281              of GNU make did treat this as a suffix rule and ignored the
282              prerequisites, which is bad.  In the future we'll do the same as
283              POSIX, but for now preserve the old behavior and warn about it.  */
284           if (f->deps != 0)
285             {
286               if (posix_pedantic)
287                 continue;
288               error (&f->cmds->fileinfo, 0,
289                      _("warning: ignoring prerequisites on suffix rule definition"));
290             }
291
292           if (s2len == 2 && rulename[slen] == '.' && rulename[slen + 1] == 'a')
293             /* A suffix rule '.X.a:' generates the pattern rule '(%.o): %.X'.
294                It also generates a normal '%.a: %.X' rule below.  */
295             convert_suffix_rule (NULL, /* Indicates '(%.o)'.  */
296                                  dep_name (d),
297                                  f->cmds);
298
299           /* The suffix rule '.X.Y:' is converted
300              to the pattern rule '%.Y: %.X'.  */
301           convert_suffix_rule (dep_name (d2), dep_name (d), f->cmds);
302         }
303     }
304 }
305
306
307 /* Install the pattern rule RULE (whose fields have been filled in) at the end
308    of the list (so that any rules previously defined will take precedence).
309    If this rule duplicates a previous one (identical target and dependencies),
310    the old one is replaced if OVERRIDE is nonzero, otherwise this new one is
311    thrown out.  When an old rule is replaced, the new one is put at the end of
312    the list.  Return nonzero if RULE is used; zero if not.  */
313
314 static int
315 new_pattern_rule (struct rule *rule, int override)
316 {
317   struct rule *r, *lastrule;
318   unsigned int i, j;
319
320   rule->in_use = 0;
321   rule->terminal = 0;
322
323   rule->next = 0;
324
325   /* Search for an identical rule.  */
326   lastrule = 0;
327   for (r = pattern_rules; r != 0; lastrule = r, r = r->next)
328     for (i = 0; i < rule->num; ++i)
329       {
330         for (j = 0; j < r->num; ++j)
331           if (!streq (rule->targets[i], r->targets[j]))
332             break;
333         /* If all the targets matched...  */
334         if (j == r->num)
335           {
336             struct dep *d, *d2;
337             for (d = rule->deps, d2 = r->deps;
338                  d != 0 && d2 != 0; d = d->next, d2 = d2->next)
339               if (!streq (dep_name (d), dep_name (d2)))
340                 break;
341             if (d == 0 && d2 == 0)
342               {
343                 /* All the dependencies matched.  */
344                 if (override)
345                   {
346                     /* Remove the old rule.  */
347                     freerule (r, lastrule);
348                     /* Install the new one.  */
349                     if (pattern_rules == 0)
350                       pattern_rules = rule;
351                     else
352                       last_pattern_rule->next = rule;
353                     last_pattern_rule = rule;
354
355                     /* We got one.  Stop looking.  */
356                     goto matched;
357                   }
358                 else
359                   {
360                     /* The old rule stays intact.  Destroy the new one.  */
361                     freerule (rule, (struct rule *) 0);
362                     return 0;
363                   }
364               }
365           }
366       }
367
368  matched:;
369
370   if (r == 0)
371     {
372       /* There was no rule to replace.  */
373       if (pattern_rules == 0)
374         pattern_rules = rule;
375       else
376         last_pattern_rule->next = rule;
377       last_pattern_rule = rule;
378     }
379
380   return 1;
381 }
382
383
384 /* Install an implicit pattern rule based on the three text strings
385    in the structure P points to.  These strings come from one of
386    the arrays of default implicit pattern rules.
387    TERMINAL specifies what the 'terminal' field of the rule should be.  */
388
389 void
390 install_pattern_rule (struct pspec *p, int terminal)
391 {
392   struct rule *r;
393   const char *ptr;
394
395   r = xmalloc (sizeof (struct rule));
396
397   r->num = 1;
398   r->targets = xmalloc (sizeof (const char *));
399   r->suffixes = xmalloc (sizeof (const char *));
400   r->lens = xmalloc (sizeof (unsigned int));
401
402   r->lens[0] = (unsigned int) strlen (p->target);
403   r->targets[0] = p->target;
404   r->suffixes[0] = find_percent_cached (&r->targets[0]);
405   assert (r->suffixes[0] != NULL);
406   ++r->suffixes[0];
407
408   ptr = p->dep;
409   r->deps = PARSE_SIMPLE_SEQ ((char **)&ptr, struct dep);
410
411   if (new_pattern_rule (r, 0))
412     {
413       r->terminal = terminal ? 1 : 0;
414       r->cmds = xmalloc (sizeof (struct commands));
415       r->cmds->fileinfo.filenm = 0;
416       r->cmds->fileinfo.lineno = 0;
417       r->cmds->fileinfo.offset = 0;
418       /* These will all be string literals, but we malloc space for them
419          anyway because somebody might want to free them later.  */
420       r->cmds->commands = xstrdup (p->commands);
421       r->cmds->command_lines = 0;
422       r->cmds->recipe_prefix = RECIPEPREFIX_DEFAULT;
423     }
424 }
425
426
427 /* Free all the storage used in RULE and take it out of the
428    pattern_rules chain.  LASTRULE is the rule whose next pointer
429    points to RULE.  */
430
431 static void
432 freerule (struct rule *rule, struct rule *lastrule)
433 {
434   struct rule *next = rule->next;
435
436   free_dep_chain (rule->deps);
437
438   /* MSVC erroneously warns without a cast here.  */
439   free ((void *)rule->targets);
440   free ((void *)rule->suffixes);
441   free (rule->lens);
442
443   /* We can't free the storage for the commands because there
444      are ways that they could be in more than one place:
445        * If the commands came from a suffix rule, they could also be in
446        the 'struct file's for other suffix rules or plain targets given
447        on the same makefile line.
448        * If two suffixes that together make a two-suffix rule were each
449        given twice in the .SUFFIXES list, and in the proper order, two
450        identical pattern rules would be created and the second one would
451        be discarded here, but both would contain the same 'struct commands'
452        pointer from the 'struct file' for the suffix rule.  */
453
454   free (rule);
455
456   if (pattern_rules == rule)
457     if (lastrule != 0)
458       abort ();
459     else
460       pattern_rules = next;
461   else if (lastrule != 0)
462     lastrule->next = next;
463   if (last_pattern_rule == rule)
464     last_pattern_rule = lastrule;
465 }
466 \f
467 /* Create a new pattern rule with the targets in the nil-terminated array
468    TARGETS.  TARGET_PERCENTS is an array of pointers to the % in each element
469    of TARGETS.  N is the number of items in the array (not counting the nil
470    element).  The new rule has dependencies DEPS and commands from COMMANDS.
471    It is a terminal rule if TERMINAL is nonzero.  This rule overrides
472    identical rules with different commands if OVERRIDE is nonzero.
473
474    The storage for TARGETS and its elements and TARGET_PERCENTS is used and
475    must not be freed until the rule is destroyed.  */
476
477 void
478 create_pattern_rule (const char **targets, const char **target_percents,
479                      unsigned short n, int terminal, struct dep *deps,
480                      struct commands *commands, int override)
481 {
482   unsigned int i;
483   struct rule *r = xmalloc (sizeof (struct rule));
484
485   r->num = n;
486   r->cmds = commands;
487   r->deps = deps;
488   r->targets = targets;
489   r->suffixes = target_percents;
490   r->lens = xmalloc (n * sizeof (unsigned int));
491
492   for (i = 0; i < n; ++i)
493     {
494       r->lens[i] = (unsigned int) strlen (targets[i]);
495       assert (r->suffixes[i] != NULL);
496       ++r->suffixes[i];
497     }
498
499   if (new_pattern_rule (r, override))
500     r->terminal = terminal ? 1 : 0;
501 }
502 \f
503 /* Print the data base of rules.  */
504
505 static void                     /* Useful to call from gdb.  */
506 print_rule (struct rule *r)
507 {
508   unsigned int i;
509
510   for (i = 0; i < r->num; ++i)
511     {
512       fputs (r->targets[i], stdout);
513       putchar ((i + 1 == r->num) ? ':' : ' ');
514     }
515   if (r->terminal)
516     putchar (':');
517
518   print_prereqs (r->deps);
519
520   if (r->cmds != 0)
521     print_commands (r->cmds);
522 }
523
524 void
525 print_rule_data_base (void)
526 {
527   unsigned int rules, terminal;
528   struct rule *r;
529
530   puts (_("\n# Implicit Rules"));
531
532   rules = terminal = 0;
533   for (r = pattern_rules; r != 0; r = r->next)
534     {
535       ++rules;
536
537       putchar ('\n');
538       print_rule (r);
539
540       if (r->terminal)
541         ++terminal;
542     }
543
544   if (rules == 0)
545     puts (_("\n# No implicit rules."));
546   else
547     {
548       printf (_("\n# %u implicit rules, %u (%.1f%%) terminal."),
549               rules, terminal, (double) terminal / (double) rules * 100.0);
550     }
551
552   if (num_pattern_rules != rules)
553     {
554       /* This can happen if a fatal error was detected while reading the
555          makefiles and thus count_implicit_rule_limits wasn't called yet.  */
556       if (num_pattern_rules != 0)
557         ONN (fatal, NILF, _("BUG: num_pattern_rules is wrong!  %u != %u"),
558              num_pattern_rules, rules);
559     }
560 }