1 /* Target file management 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 "debug.h"
27 #include "hash.h"
28 
29 
30 /* Remember whether snap_deps has been invoked: we need this to be sure we
31    don't add new rules (via $(eval ...)) afterwards.  In the future it would
32    be nice to support this, but it means we'd need to re-run snap_deps() or
33    at least its functionality... it might mean changing snap_deps() to be run
34    per-file, so we can invoke it after the eval... or remembering which files
35    in the hash have been snapped (a new boolean flag?) and having snap_deps()
36    only work on files which have not yet been snapped. */
37 int snapped_deps = 0;
38 
39 /* Hash table of files the makefile knows how to make.  */
40 
41 static unsigned long
file_hash_1(const void * key)42 file_hash_1 (const void *key)
43 {
44   return_ISTRING_HASH_1 (((struct file const *) key)->hname);
45 }
46 
47 static unsigned long
file_hash_2(const void * key)48 file_hash_2 (const void *key)
49 {
50   return_ISTRING_HASH_2 (((struct file const *) key)->hname);
51 }
52 
53 static int
file_hash_cmp(const void * x,const void * y)54 file_hash_cmp (const void *x, const void *y)
55 {
56   return_ISTRING_COMPARE (((struct file const *) x)->hname,
57                           ((struct file const *) y)->hname);
58 }
59 
60 static struct hash_table files;
61 
62 /* Whether or not .SECONDARY with no prerequisites was given.  */
63 static int all_secondary = 0;
64 
65 /* Access the hash table of all file records.
66    lookup_file  given a name, return the struct file * for that name,
67                 or nil if there is none.
68 */
69 
70 struct file *
lookup_file(const char * name)71 lookup_file (const char *name)
72 {
73   struct file *f;
74   struct file file_key;
75 #ifdef VMS
76   int want_vmsify;
77 #ifndef WANT_CASE_SENSITIVE_TARGETS
78   char *lname;
79 #endif
80 #endif
81 
82   assert (*name != '\0');
83 
84   /* This is also done in parse_file_seq, so this is redundant
85      for names read from makefiles.  It is here for names passed
86      on the command line.  */
87 #ifdef VMS
88    want_vmsify = (strpbrk (name, "]>:^") != NULL);
89 # ifndef WANT_CASE_SENSITIVE_TARGETS
90   if (*name != '.')
91     {
92       const char *n;
93       char *ln;
94       lname = xstrdup (name);
95       for (n = name, ln = lname; *n != '\0'; ++n, ++ln)
96         *ln = isupper ((unsigned char)*n) ? tolower ((unsigned char)*n) : *n;
97       *ln = '\0';
98       name = lname;
99     }
100 # endif
101 
102   while (name[0] == '[' && name[1] == ']' && name[2] != '\0')
103       name += 2;
104   while (name[0] == '<' && name[1] == '>' && name[2] != '\0')
105       name += 2;
106 #endif
107   while (name[0] == '.'
108 #ifdef HAVE_DOS_PATHS
109          && (name[1] == '/' || name[1] == '\\')
110 #else
111          && name[1] == '/'
112 #endif
113          && name[2] != '\0')
114     {
115       name += 2;
116       while (*name == '/'
117 #ifdef HAVE_DOS_PATHS
118              || *name == '\\'
119 #endif
120              )
121         /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
122         ++name;
123     }
124 
125   if (*name == '\0')
126     {
127       /* It was all slashes after a dot.  */
128 #if defined(_AMIGA)
129       name = "";
130 #else
131       name = "./";
132 #endif
133 #if defined(VMS)
134       /* TODO - This section is probably not needed. */
135       if (want_vmsify)
136         name = "[]";
137 #endif
138     }
139   file_key.hname = name;
140   f = hash_find_item (&files, &file_key);
141 #if defined(VMS) && !defined(WANT_CASE_SENSITIVE_TARGETS)
142   if (*name != '.')
143     free (lname);
144 #endif
145 
146   return f;
147 }
148 
149 /* Look up a file record for file NAME and return it.
150    Create a new record if one doesn't exist.  NAME will be stored in the
151    new record so it should be constant or in the strcache etc.
152  */
153 
154 struct file *
enter_file(const char * name)155 enter_file (const char *name)
156 {
157   struct file *f;
158   struct file *new;
159   struct file **file_slot;
160   struct file file_key;
161 
162   assert (*name != '\0');
163   assert (! verify_flag || strcache_iscached (name));
164 
165 #if defined(VMS) && !defined(WANT_CASE_SENSITIVE_TARGETS)
166   if (*name != '.')
167     {
168       const char *n;
169       char *lname, *ln;
170       lname = xstrdup (name);
171       for (n = name, ln = lname; *n != '\0'; ++n, ++ln)
172         if (isupper ((unsigned char)*n))
173           *ln = tolower ((unsigned char)*n);
174         else
175           *ln = *n;
176 
177       *ln = '\0';
178       name = strcache_add (lname);
179       free (lname);
180     }
181 #endif
182 
183   file_key.hname = name;
184   file_slot = (struct file **) hash_find_slot (&files, &file_key);
185   f = *file_slot;
186   if (! HASH_VACANT (f) && !f->double_colon)
187     {
188       f->builtin = 0;
189       return f;
190     }
191 
192   new = xcalloc (sizeof (struct file));
193   new->name = new->hname = name;
194   new->update_status = us_none;
195 
196   if (HASH_VACANT (f))
197     {
198       new->last = new;
199       hash_insert_at (&files, new, file_slot);
200     }
201   else
202     {
203       /* There is already a double-colon entry for this file.  */
204       new->double_colon = f;
205       f->last->prev = new;
206       f->last = new;
207     }
208 
209   return new;
210 }
211 
212 /* Rehash FILE to NAME.  This is not as simple as resetting
213    the 'hname' member, since it must be put in a new hash bucket,
214    and possibly merged with an existing file called NAME.  */
215 
216 void
rehash_file(struct file * from_file,const char * to_hname)217 rehash_file (struct file *from_file, const char *to_hname)
218 {
219   struct file file_key;
220   struct file **file_slot;
221   struct file *to_file;
222   struct file *deleted_file;
223   struct file *f;
224 
225   /* If it's already that name, we're done.  */
226   from_file->builtin = 0;
227   file_key.hname = to_hname;
228   if (! file_hash_cmp (from_file, &file_key))
229     return;
230 
231   /* Find the end of the renamed list for the "from" file.  */
232   file_key.hname = from_file->hname;
233   while (from_file->renamed != 0)
234     from_file = from_file->renamed;
235   if (file_hash_cmp (from_file, &file_key))
236     /* hname changed unexpectedly!! */
237     abort ();
238 
239   /* Remove the "from" file from the hash.  */
240   deleted_file = hash_delete (&files, from_file);
241   if (deleted_file != from_file)
242     /* from_file isn't the one stored in files */
243     abort ();
244 
245   /* Find where the newly renamed file will go in the hash.  */
246   file_key.hname = to_hname;
247   file_slot = (struct file **) hash_find_slot (&files, &file_key);
248   to_file = *file_slot;
249 
250   /* Change the hash name for this file.  */
251   from_file->hname = to_hname;
252   for (f = from_file->double_colon; f != 0; f = f->prev)
253     f->hname = to_hname;
254 
255   /* If the new name doesn't exist yet just set it to the renamed file.  */
256   if (HASH_VACANT (to_file))
257     {
258       hash_insert_at (&files, from_file, file_slot);
259       return;
260     }
261 
262   /* TO_FILE already exists under TO_HNAME.
263      We must retain TO_FILE and merge FROM_FILE into it.  */
264 
265   if (from_file->cmds != 0)
266     {
267       if (to_file->cmds == 0)
268         to_file->cmds = from_file->cmds;
269       else if (from_file->cmds != to_file->cmds)
270         {
271           size_t l = strlen (from_file->name);
272           /* We have two sets of commands.  We will go with the
273              one given in the rule explicitly mentioning this name,
274              but give a message to let the user know what's going on.  */
275           if (to_file->cmds->fileinfo.filenm != 0)
276             error (&from_file->cmds->fileinfo,
277                    l + strlen (to_file->cmds->fileinfo.filenm) + INTSTR_LENGTH,
278                    _("Recipe was specified for file '%s' at %s:%lu,"),
279                    from_file->name, to_file->cmds->fileinfo.filenm,
280                    to_file->cmds->fileinfo.lineno);
281           else
282             error (&from_file->cmds->fileinfo, l,
283                    _("Recipe for file '%s' was found by implicit rule search,"),
284                    from_file->name);
285           l += strlen (to_hname);
286           error (&from_file->cmds->fileinfo, l,
287                  _("but '%s' is now considered the same file as '%s'."),
288                  from_file->name, to_hname);
289           error (&from_file->cmds->fileinfo, l,
290                  _("Recipe for '%s' will be ignored in favor of the one for '%s'."),
291                  to_hname, from_file->name);
292         }
293     }
294 
295   /* Merge the dependencies of the two files.  */
296 
297   if (to_file->deps == 0)
298     to_file->deps = from_file->deps;
299   else
300     {
301       struct dep *deps = to_file->deps;
302       while (deps->next != 0)
303         deps = deps->next;
304       deps->next = from_file->deps;
305     }
306 
307   merge_variable_set_lists (&to_file->variables, from_file->variables);
308 
309   if (to_file->double_colon && from_file->is_target && !from_file->double_colon)
310     OSS (fatal, NILF, _("can't rename single-colon '%s' to double-colon '%s'"),
311          from_file->name, to_hname);
312   if (!to_file->double_colon  && from_file->double_colon)
313     {
314       if (to_file->is_target)
315         OSS (fatal, NILF,
316              _("can't rename double-colon '%s' to single-colon '%s'"),
317              from_file->name, to_hname);
318       else
319         to_file->double_colon = from_file->double_colon;
320     }
321 
322   if (from_file->last_mtime > to_file->last_mtime)
323     /* %%% Kludge so -W wins on a file that gets vpathized.  */
324     to_file->last_mtime = from_file->last_mtime;
325 
326   to_file->mtime_before_update = from_file->mtime_before_update;
327 
328 #define MERGE(field) to_file->field |= from_file->field
329   MERGE (precious);
330   MERGE (tried_implicit);
331   MERGE (updating);
332   MERGE (updated);
333   MERGE (is_target);
334   MERGE (cmd_target);
335   MERGE (phony);
336   MERGE (loaded);
337   MERGE (ignore_vpath);
338 #undef MERGE
339 
340   to_file->builtin = 0;
341   from_file->renamed = to_file;
342 }
343 
344 /* Rename FILE to NAME.  This is not as simple as resetting
345    the 'name' member, since it must be put in a new hash bucket,
346    and possibly merged with an existing file called NAME.  */
347 
348 void
rename_file(struct file * from_file,const char * to_hname)349 rename_file (struct file *from_file, const char *to_hname)
350 {
351   rehash_file (from_file, to_hname);
352   while (from_file)
353     {
354       from_file->name = from_file->hname;
355       from_file = from_file->prev;
356     }
357 }
358 
359 /* Remove all nonprecious intermediate files.
360    If SIG is nonzero, this was caused by a fatal signal,
361    meaning that a different message will be printed, and
362    the message will go to stderr rather than stdout.  */
363 
364 void
remove_intermediates(int sig)365 remove_intermediates (int sig)
366 {
367   struct file **file_slot;
368   struct file **file_end;
369   int doneany = 0;
370 
371   /* If there's no way we will ever remove anything anyway, punt early.  */
372   if (question_flag || touch_flag || all_secondary)
373     return;
374 
375   if (sig && just_print_flag)
376     return;
377 
378   file_slot = (struct file **) files.ht_vec;
379   file_end = file_slot + files.ht_size;
380   for ( ; file_slot < file_end; file_slot++)
381     if (! HASH_VACANT (*file_slot))
382       {
383         struct file *f = *file_slot;
384         /* Is this file eligible for automatic deletion?
385            Yes, IFF: it's marked intermediate, it's not secondary, it wasn't
386            given on the command line, and it's either a -include makefile or
387            it's not precious.  */
388         if (f->intermediate && (f->dontcare || !f->precious)
389             && !f->secondary && !f->cmd_target)
390           {
391             int status;
392             if (f->update_status == us_none)
393               /* If nothing would have created this file yet,
394                  don't print an "rm" command for it.  */
395               continue;
396             if (just_print_flag)
397               status = 0;
398             else
399               {
400                 status = unlink (f->name);
401                 if (status < 0 && errno == ENOENT)
402                   continue;
403               }
404             if (!f->dontcare)
405               {
406                 if (sig)
407                   OS (error, NILF,
408                       _("*** Deleting intermediate file '%s'"), f->name);
409                 else
410                   {
411                     if (! doneany)
412                       DB (DB_BASIC, (_("Removing intermediate files...\n")));
413                     if (!run_silent)
414                       {
415                         if (! doneany)
416                           {
417                             fputs ("rm ", stdout);
418                             doneany = 1;
419                           }
420                         else
421                           putchar (' ');
422                         fputs (f->name, stdout);
423                         fflush (stdout);
424                       }
425                   }
426                 if (status < 0)
427                   perror_with_name ("unlink: ", f->name);
428               }
429           }
430       }
431 
432   if (doneany && !sig)
433     {
434       putchar ('\n');
435       fflush (stdout);
436     }
437 }
438 
439 /* Given a string containing prerequisites (fully expanded), break it up into
440    a struct dep list.  Enter each of these prereqs into the file database.
441  */
442 struct dep *
split_prereqs(char * p)443 split_prereqs (char *p)
444 {
445   struct dep *new = PARSE_FILE_SEQ (&p, struct dep, MAP_PIPE, NULL,
446                                     PARSEFS_NONE);
447 
448   if (*p)
449     {
450       /* Files that follow '|' are "order-only" prerequisites that satisfy the
451          dependency by existing: their modification times are irrelevant.  */
452       struct dep *ood;
453 
454       ++p;
455       ood = PARSE_SIMPLE_SEQ (&p, struct dep);
456 
457       if (! new)
458         new = ood;
459       else
460         {
461           struct dep *dp;
462           for (dp = new; dp->next != NULL; dp = dp->next)
463             ;
464           dp->next = ood;
465         }
466 
467       for (; ood != NULL; ood = ood->next)
468         ood->ignore_mtime = 1;
469     }
470 
471   return new;
472 }
473 
474 /* Given a list of prerequisites, enter them into the file database.
475    If STEM is set then first expand patterns using STEM.  */
476 struct dep *
enter_prereqs(struct dep * deps,const char * stem)477 enter_prereqs (struct dep *deps, const char *stem)
478 {
479   struct dep *d1;
480 
481   if (deps == 0)
482     return 0;
483 
484   /* If we have a stem, expand the %'s.  We use patsubst_expand to translate
485      the prerequisites' patterns into plain prerequisite names.  */
486   if (stem)
487     {
488       const char *pattern = "%";
489       char *buffer = variable_expand ("");
490       struct dep *dp = deps, *dl = 0;
491 
492       while (dp != 0)
493         {
494           char *percent;
495           size_t nl = strlen (dp->name) + 1;
496           char *nm = alloca (nl);
497           memcpy (nm, dp->name, nl);
498           percent = find_percent (nm);
499           if (percent)
500             {
501               char *o;
502 
503               /* We have to handle empty stems specially, because that
504                  would be equivalent to $(patsubst %,dp->name,) which
505                  will always be empty.  */
506               if (stem[0] == '\0')
507                 {
508                   memmove (percent, percent+1, strlen (percent));
509                   o = variable_buffer_output (buffer, nm, strlen (nm) + 1);
510                 }
511               else
512                 o = patsubst_expand_pat (buffer, stem, pattern, nm,
513                                          pattern+1, percent+1);
514 
515               /* If the name expanded to the empty string, ignore it.  */
516               if (buffer[0] == '\0')
517                 {
518                   struct dep *df = dp;
519                   if (dp == deps)
520                     dp = deps = deps->next;
521                   else
522                     dp = dl->next = dp->next;
523                   free_dep (df);
524                   continue;
525                 }
526 
527               /* Save the name.  */
528               dp->name = strcache_add_len (buffer, o - buffer);
529             }
530           dp->stem = stem;
531           dp->staticpattern = 1;
532           dl = dp;
533           dp = dp->next;
534         }
535     }
536 
537   /* Enter them as files, unless they need a 2nd expansion.  */
538   for (d1 = deps; d1 != 0; d1 = d1->next)
539     {
540       if (d1->need_2nd_expansion)
541         continue;
542 
543       d1->file = lookup_file (d1->name);
544       if (d1->file == 0)
545         d1->file = enter_file (d1->name);
546       d1->staticpattern = 0;
547       d1->name = 0;
548     }
549 
550   return deps;
551 }
552 
553 /* Expand and parse each dependency line. */
554 static void
expand_deps(struct file * f)555 expand_deps (struct file *f)
556 {
557   struct dep *d;
558   struct dep **dp;
559   const char *file_stem = f->stem;
560   int initialized = 0;
561 
562   f->updating = 0;
563 
564   /* Walk through the dependencies.  For any dependency that needs 2nd
565      expansion, expand it then insert the result into the list.  */
566   dp = &f->deps;
567   d = f->deps;
568   while (d != 0)
569     {
570       char *p;
571       struct dep *new, *next;
572       char *name = (char *)d->name;
573 
574       if (! d->name || ! d->need_2nd_expansion)
575         {
576           /* This one is all set already.  */
577           dp = &d->next;
578           d = d->next;
579           continue;
580         }
581 
582       /* If it's from a static pattern rule, convert the patterns into
583          "$*" so they'll expand properly.  */
584       if (d->staticpattern)
585         {
586           char *o = variable_expand ("");
587           o = subst_expand (o, name, "%", "$*", 1, 2, 0);
588           *o = '\0';
589           free (name);
590           d->name = name = xstrdup (variable_buffer);
591           d->staticpattern = 0;
592         }
593 
594       /* We're going to do second expansion so initialize file variables for
595          the file. Since the stem for static pattern rules comes from
596          individual dep lines, we will temporarily set f->stem to d->stem.  */
597       if (!initialized)
598         {
599           initialize_file_variables (f, 0);
600           initialized = 1;
601         }
602 
603       if (d->stem != 0)
604         f->stem = d->stem;
605 
606       set_file_variables (f);
607 
608       p = variable_expand_for_file (d->name, f);
609 
610       if (d->stem != 0)
611         f->stem = file_stem;
612 
613       /* At this point we don't need the name anymore: free it.  */
614       free (name);
615 
616       /* Parse the prerequisites and enter them into the file database.  */
617       new = enter_prereqs (split_prereqs (p), d->stem);
618 
619       /* If there were no prereqs here (blank!) then throw this one out.  */
620       if (new == 0)
621         {
622           *dp = d->next;
623           free_dep (d);
624           d = *dp;
625           continue;
626         }
627 
628       /* Add newly parsed prerequisites.  */
629       next = d->next;
630       *dp = new;
631       for (dp = &new->next, d = new->next; d != 0; dp = &d->next, d = d->next)
632         ;
633       *dp = next;
634       d = *dp;
635     }
636 }
637 
638 /* Add extra prereqs to the file in question.  */
639 
640 struct dep *
expand_extra_prereqs(const struct variable * extra)641 expand_extra_prereqs (const struct variable *extra)
642 {
643   struct dep *d;
644   struct dep *prereqs = extra ? split_prereqs (variable_expand (extra->value)) : NULL;
645 
646   for (d = prereqs; d; d = d->next)
647     {
648       d->file = lookup_file (d->name);
649       if (!d->file)
650         d->file = enter_file (d->name);
651       d->name = NULL;
652       d->ignore_automatic_vars = 1;
653     }
654 
655   return prereqs;
656 }
657 
658 /* Perform per-file snap operations. */
659 
660 static void
snap_file(const void * item,void * arg)661 snap_file (const void *item, void *arg)
662 {
663   struct file *f = (struct file*)item;
664   struct dep *prereqs = NULL;
665 
666   /* If we're not doing second expansion then reset updating.  */
667   if (!second_expansion)
668     f->updating = 0;
669 
670   /* If .SECONDARY is set with no deps, mark all targets as intermediate.  */
671   if (all_secondary)
672     f->intermediate = 1;
673 
674   /* If .EXTRA_PREREQS is set, add them as ignored by automatic variables.  */
675   if (f->variables)
676     prereqs = expand_extra_prereqs (lookup_variable_in_set (STRING_SIZE_TUPLE(".EXTRA_PREREQS"), f->variables->set));
677 
678   else if (f->is_target)
679     prereqs = copy_dep_chain (arg);
680 
681   if (prereqs)
682     {
683       struct dep *d;
684       for (d = prereqs; d; d = d->next)
685         if (streq (f->name, dep_name (d)))
686           /* Skip circular dependencies.  */
687           break;
688 
689       if (d)
690         /* We broke early: must have found a circular dependency.  */
691         free_dep_chain (prereqs);
692       else if (!f->deps)
693         f->deps = prereqs;
694       else
695         {
696           d = f->deps;
697           while (d->next)
698             d = d->next;
699           d->next = prereqs;
700         }
701     }
702 }
703 
704 /* For each dependency of each file, make the 'struct dep' point
705    at the appropriate 'struct file' (which may have to be created).
706 
707    Also mark the files depended on by .PRECIOUS, .PHONY, .SILENT,
708    and various other special targets.  */
709 
710 void
snap_deps(void)711 snap_deps (void)
712 {
713   struct file *f;
714   struct file *f2;
715   struct dep *d;
716 
717   /* Remember that we've done this.  Once we start snapping deps we can no
718      longer define new targets.  */
719   snapped_deps = 1;
720 
721   /* Perform second expansion and enter each dependency name as a file.  We
722      must use hash_dump() here because within these loops we likely add new
723      files to the table, possibly causing an in-situ table expansion.
724 
725      We only need to do this if second_expansion has been defined; if it
726      hasn't then all deps were expanded as the makefile was read in.  If we
727      ever change make to be able to unset .SECONDARY_EXPANSION this will have
728      to change.  */
729 
730   if (second_expansion)
731     {
732       struct file **file_slot_0 = (struct file **) hash_dump (&files, 0, 0);
733       struct file **file_end = file_slot_0 + files.ht_fill;
734       struct file **file_slot;
735       const char *suffixes;
736 
737       /* Expand .SUFFIXES: its prerequisites are used for $$* calc.  */
738       f = lookup_file (".SUFFIXES");
739       suffixes = f ? f->name : 0;
740       for (; f != 0; f = f->prev)
741         expand_deps (f);
742 
743       /* For every target that's not .SUFFIXES, expand its prerequisites.  */
744 
745       for (file_slot = file_slot_0; file_slot < file_end; file_slot++)
746         for (f = *file_slot; f != 0; f = f->prev)
747           if (f->name != suffixes)
748             expand_deps (f);
749       free (file_slot_0);
750     }
751 
752   /* Now manage all the special targets.  */
753 
754   for (f = lookup_file (".PRECIOUS"); f != 0; f = f->prev)
755     for (d = f->deps; d != 0; d = d->next)
756       for (f2 = d->file; f2 != 0; f2 = f2->prev)
757         f2->precious = 1;
758 
759   for (f = lookup_file (".LOW_RESOLUTION_TIME"); f != 0; f = f->prev)
760     for (d = f->deps; d != 0; d = d->next)
761       for (f2 = d->file; f2 != 0; f2 = f2->prev)
762         f2->low_resolution_time = 1;
763 
764   for (f = lookup_file (".PHONY"); f != 0; f = f->prev)
765     for (d = f->deps; d != 0; d = d->next)
766       for (f2 = d->file; f2 != 0; f2 = f2->prev)
767         {
768           /* Mark this file as phony nonexistent target.  */
769           f2->phony = 1;
770           f2->is_target = 1;
771           f2->last_mtime = NONEXISTENT_MTIME;
772           f2->mtime_before_update = NONEXISTENT_MTIME;
773         }
774 
775   for (f = lookup_file (".INTERMEDIATE"); f != 0; f = f->prev)
776     /* Mark .INTERMEDIATE deps as intermediate files.  */
777     for (d = f->deps; d != 0; d = d->next)
778       for (f2 = d->file; f2 != 0; f2 = f2->prev)
779         f2->intermediate = 1;
780     /* .INTERMEDIATE with no deps does nothing.
781        Marking all files as intermediates is useless since the goal targets
782        would be deleted after they are built.  */
783 
784   for (f = lookup_file (".SECONDARY"); f != 0; f = f->prev)
785     /* Mark .SECONDARY deps as both intermediate and secondary.  */
786     if (f->deps)
787       for (d = f->deps; d != 0; d = d->next)
788         for (f2 = d->file; f2 != 0; f2 = f2->prev)
789           f2->intermediate = f2->secondary = 1;
790     /* .SECONDARY with no deps listed marks *all* files that way.  */
791     else
792       all_secondary = 1;
793 
794   f = lookup_file (".EXPORT_ALL_VARIABLES");
795   if (f != 0 && f->is_target)
796     export_all_variables = 1;
797 
798   f = lookup_file (".IGNORE");
799   if (f != 0 && f->is_target)
800     {
801       if (f->deps == 0)
802         ignore_errors_flag = 1;
803       else
804         for (d = f->deps; d != 0; d = d->next)
805           for (f2 = d->file; f2 != 0; f2 = f2->prev)
806             f2->command_flags |= COMMANDS_NOERROR;
807     }
808 
809   f = lookup_file (".SILENT");
810   if (f != 0 && f->is_target)
811     {
812       if (f->deps == 0)
813         run_silent = 1;
814       else
815         for (d = f->deps; d != 0; d = d->next)
816           for (f2 = d->file; f2 != 0; f2 = f2->prev)
817             f2->command_flags |= COMMANDS_SILENT;
818     }
819 
820   f = lookup_file (".NOTPARALLEL");
821   if (f != 0 && f->is_target)
822     not_parallel = 1;
823 
824   {
825     struct dep *prereqs = expand_extra_prereqs (lookup_variable (STRING_SIZE_TUPLE(".EXTRA_PREREQS")));
826 
827     /* Perform per-file snap operations.  */
828     hash_map_arg(&files, snap_file, prereqs);
829 
830     free_dep_chain (prereqs);
831   }
832 
833 #ifndef NO_MINUS_C_MINUS_O
834   /* If .POSIX was defined, remove OUTPUT_OPTION to comply.  */
835   /* This needs more work: what if the user sets this in the makefile?
836   if (posix_pedantic)
837     define_variable_cname ("OUTPUT_OPTION", "", o_default, 1);
838   */
839 #endif
840 }
841 
842 /* Set the 'command_state' member of FILE and all its 'also_make's.
843    Don't decrease the state of also_make's (e.g., don't downgrade a 'running'
844    also_make to a 'deps_running' also_make).  */
845 
846 void
set_command_state(struct file * file,enum cmd_state state)847 set_command_state (struct file *file, enum cmd_state state)
848 {
849   struct dep *d;
850 
851   file->command_state = state;
852 
853   for (d = file->also_make; d != 0; d = d->next)
854     if (state > d->file->command_state)
855       d->file->command_state = state;
856 }
857 
858 /* Convert an external file timestamp to internal form.  */
859 
860 FILE_TIMESTAMP
file_timestamp_cons(const char * fname,time_t stamp,long int ns)861 file_timestamp_cons (const char *fname, time_t stamp, long int ns)
862 {
863   int offset = ORDINARY_MTIME_MIN + (FILE_TIMESTAMP_HI_RES ? ns : 0);
864   FILE_TIMESTAMP s = stamp;
865   FILE_TIMESTAMP product = (FILE_TIMESTAMP) s << FILE_TIMESTAMP_LO_BITS;
866   FILE_TIMESTAMP ts = product + offset;
867 
868   if (! (s <= FILE_TIMESTAMP_S (ORDINARY_MTIME_MAX)
869          && product <= ts && ts <= ORDINARY_MTIME_MAX))
870     {
871       char buf[FILE_TIMESTAMP_PRINT_LEN_BOUND + 1];
872       const char *f = fname ? fname : _("Current time");
873       ts = s <= OLD_MTIME ? ORDINARY_MTIME_MIN : ORDINARY_MTIME_MAX;
874       file_timestamp_sprintf (buf, ts);
875       OSS (error, NILF,
876            _("%s: Timestamp out of range; substituting %s"), f, buf);
877     }
878 
879   return ts;
880 }
881 
882 /* Return the current time as a file timestamp, setting *RESOLUTION to
883    its resolution.  */
884 FILE_TIMESTAMP
file_timestamp_now(int * resolution)885 file_timestamp_now (int *resolution)
886 {
887   int r;
888   time_t s;
889   int ns;
890 
891   /* Don't bother with high-resolution clocks if file timestamps have
892      only one-second resolution.  The code below should work, but it's
893      not worth the hassle of debugging it on hosts where it fails.  */
894 #if FILE_TIMESTAMP_HI_RES
895 # if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
896   {
897     struct timespec timespec;
898     if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
899       {
900         r = 1;
901         s = timespec.tv_sec;
902         ns = timespec.tv_nsec;
903         goto got_time;
904       }
905   }
906 # endif
907 # if HAVE_GETTIMEOFDAY
908   {
909     struct timeval timeval;
910     if (gettimeofday (&timeval, 0) == 0)
911       {
912         r = 1000;
913         s = timeval.tv_sec;
914         ns = timeval.tv_usec * 1000;
915         goto got_time;
916       }
917   }
918 # endif
919 #endif
920 
921   r = 1000000000;
922   s = time ((time_t *) 0);
923   ns = 0;
924 
925 #if FILE_TIMESTAMP_HI_RES
926  got_time:
927 #endif
928   *resolution = r;
929   return file_timestamp_cons (0, s, ns);
930 }
931 
932 /* Place into the buffer P a printable representation of the file
933    timestamp TS.  */
934 void
file_timestamp_sprintf(char * p,FILE_TIMESTAMP ts)935 file_timestamp_sprintf (char *p, FILE_TIMESTAMP ts)
936 {
937   time_t t = FILE_TIMESTAMP_S (ts);
938   struct tm *tm = localtime (&t);
939 
940   if (tm)
941     sprintf (p, "%04d-%02d-%02d %02d:%02d:%02d",
942              tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
943              tm->tm_hour, tm->tm_min, tm->tm_sec);
944   else if (t < 0)
945     sprintf (p, "%ld", (long) t);
946   else
947     sprintf (p, "%lu", (unsigned long) t);
948   p += strlen (p);
949 
950   /* Append nanoseconds as a fraction, but remove trailing zeros.  We don't
951      know the actual timestamp resolution, since clock_getres applies only to
952      local times, whereas this timestamp might come from a remote filesystem.
953      So removing trailing zeros is the best guess that we can do.  */
954   sprintf (p, ".%09d", FILE_TIMESTAMP_NS (ts));
955   p += strlen (p) - 1;
956   while (*p == '0')
957     p--;
958   p += *p != '.';
959 
960   *p = '\0';
961 }
962 
963 /* Print the data base of files.  */
964 
965 void
print_prereqs(const struct dep * deps)966 print_prereqs (const struct dep *deps)
967 {
968   const struct dep *ood = 0;
969 
970   /* Print all normal dependencies; note any order-only deps.  */
971   for (; deps != 0; deps = deps->next)
972     if (! deps->ignore_mtime)
973       printf (" %s", dep_name (deps));
974     else if (! ood)
975       ood = deps;
976 
977   /* Print order-only deps, if we have any.  */
978   if (ood)
979     {
980       printf (" | %s", dep_name (ood));
981       for (ood = ood->next; ood != 0; ood = ood->next)
982         if (ood->ignore_mtime)
983           printf (" %s", dep_name (ood));
984     }
985 
986   putchar ('\n');
987 }
988 
989 static void
print_file(const void * item)990 print_file (const void *item)
991 {
992   const struct file *f = item;
993 
994   /* If we're not using builtin targets, don't show them.
995 
996      Ideally we'd be able to delete them altogether but currently there's no
997      facility to ever delete a file once it's been added.  */
998   if (no_builtin_rules_flag && f->builtin)
999     return;
1000 
1001   putchar ('\n');
1002 
1003   if (f->cmds && f->cmds->recipe_prefix != cmd_prefix)
1004     {
1005       fputs (".RECIPEPREFIX = ", stdout);
1006       cmd_prefix = f->cmds->recipe_prefix;
1007       if (cmd_prefix != RECIPEPREFIX_DEFAULT)
1008         putchar (cmd_prefix);
1009       putchar ('\n');
1010     }
1011 
1012   if (f->variables != 0)
1013     print_target_variables (f);
1014 
1015   if (!f->is_target)
1016     puts (_("# Not a target:"));
1017   printf ("%s:%s", f->name, f->double_colon ? ":" : "");
1018   print_prereqs (f->deps);
1019 
1020   if (f->precious)
1021     puts (_("#  Precious file (prerequisite of .PRECIOUS)."));
1022   if (f->phony)
1023     puts (_("#  Phony target (prerequisite of .PHONY)."));
1024   if (f->cmd_target)
1025     puts (_("#  Command line target."));
1026   if (f->dontcare)
1027     puts (_("#  A default, MAKEFILES, or -include/sinclude makefile."));
1028   if (f->builtin)
1029     puts (_("#  Builtin rule"));
1030   puts (f->tried_implicit
1031         ? _("#  Implicit rule search has been done.")
1032         : _("#  Implicit rule search has not been done."));
1033   if (f->stem != 0)
1034     printf (_("#  Implicit/static pattern stem: '%s'\n"), f->stem);
1035   if (f->intermediate)
1036     puts (_("#  File is an intermediate prerequisite."));
1037   if (f->also_make != 0)
1038     {
1039       const struct dep *d;
1040       fputs (_("#  Also makes:"), stdout);
1041       for (d = f->also_make; d != 0; d = d->next)
1042         printf (" %s", dep_name (d));
1043       putchar ('\n');
1044     }
1045   if (f->last_mtime == UNKNOWN_MTIME)
1046     puts (_("#  Modification time never checked."));
1047   else if (f->last_mtime == NONEXISTENT_MTIME)
1048     puts (_("#  File does not exist."));
1049   else if (f->last_mtime == OLD_MTIME)
1050     puts (_("#  File is very old."));
1051   else
1052     {
1053       char buf[FILE_TIMESTAMP_PRINT_LEN_BOUND + 1];
1054       file_timestamp_sprintf (buf, f->last_mtime);
1055       printf (_("#  Last modified %s\n"), buf);
1056     }
1057   puts (f->updated
1058         ? _("#  File has been updated.") : _("#  File has not been updated."));
1059   switch (f->command_state)
1060     {
1061     case cs_running:
1062       puts (_("#  Recipe currently running (THIS IS A BUG)."));
1063       break;
1064     case cs_deps_running:
1065       puts (_("#  Dependencies recipe running (THIS IS A BUG)."));
1066       break;
1067     case cs_not_started:
1068     case cs_finished:
1069       switch (f->update_status)
1070         {
1071         case us_none:
1072           break;
1073         case us_success:
1074           puts (_("#  Successfully updated."));
1075           break;
1076         case us_question:
1077           assert (question_flag);
1078           puts (_("#  Needs to be updated (-q is set)."));
1079           break;
1080         case us_failed:
1081           puts (_("#  Failed to be updated."));
1082           break;
1083         }
1084       break;
1085     default:
1086       puts (_("#  Invalid value in 'command_state' member!"));
1087       fflush (stdout);
1088       fflush (stderr);
1089       abort ();
1090     }
1091 
1092   if (f->variables != 0)
1093     print_file_variables (f);
1094 
1095   if (f->cmds != 0)
1096     print_commands (f->cmds);
1097 
1098   if (f->prev)
1099     print_file ((const void *) f->prev);
1100 }
1101 
1102 void
print_file_data_base(void)1103 print_file_data_base (void)
1104 {
1105   puts (_("\n# Files"));
1106 
1107   hash_map (&files, print_file);
1108 
1109   fputs (_("\n# files hash-table stats:\n# "), stdout);
1110   hash_print_stats (&files, stdout);
1111 }
1112 
1113 /* Verify the integrity of the data base of files.  */
1114 
1115 #define VERIFY_CACHED(_p,_n) \
1116     do{                                                                       \
1117         if (_p->_n && _p->_n[0] && !strcache_iscached (_p->_n))               \
1118           error (NULL, strlen (_p->name) + CSTRLEN (# _n) + strlen (_p->_n),  \
1119                  _("%s: Field '%s' not cached: %s"), _p->name, # _n, _p->_n); \
1120     }while(0)
1121 
1122 static void
verify_file(const void * item)1123 verify_file (const void *item)
1124 {
1125   const struct file *f = item;
1126   const struct dep *d;
1127 
1128   VERIFY_CACHED (f, name);
1129   VERIFY_CACHED (f, hname);
1130   VERIFY_CACHED (f, vpath);
1131   VERIFY_CACHED (f, stem);
1132 
1133   /* Check the deps.  */
1134   for (d = f->deps; d != 0; d = d->next)
1135     {
1136       if (! d->need_2nd_expansion)
1137         VERIFY_CACHED (d, name);
1138       VERIFY_CACHED (d, stem);
1139     }
1140 }
1141 
1142 void
verify_file_data_base(void)1143 verify_file_data_base (void)
1144 {
1145   hash_map (&files, verify_file);
1146 }
1147 
1148 #define EXPANSION_INCREMENT(_l)  ((((_l) / 500) + 1) * 500)
1149 
1150 char *
build_target_list(char * value)1151 build_target_list (char *value)
1152 {
1153   static unsigned long last_targ_count = 0;
1154 
1155   if (files.ht_fill != last_targ_count)
1156     {
1157       size_t max = EXPANSION_INCREMENT (strlen (value));
1158       size_t len;
1159       char *p;
1160       struct file **fp = (struct file **) files.ht_vec;
1161       struct file **end = &fp[files.ht_size];
1162 
1163       /* Make sure we have at least MAX bytes in the allocated buffer.  */
1164       value = xrealloc (value, max);
1165 
1166       p = value;
1167       len = 0;
1168       for (; fp < end; ++fp)
1169         if (!HASH_VACANT (*fp) && (*fp)->is_target)
1170           {
1171             struct file *f = *fp;
1172             size_t l = strlen (f->name);
1173 
1174             len += l + 1;
1175             if (len > max)
1176               {
1177                 size_t off = p - value;
1178 
1179                 max += EXPANSION_INCREMENT (l + 1);
1180                 value = xrealloc (value, max);
1181                 p = &value[off];
1182               }
1183 
1184             memcpy (p, f->name, l);
1185             p += l;
1186             *(p++) = ' ';
1187           }
1188       *(p-1) = '\0';
1189 
1190       last_targ_count = files.ht_fill;
1191     }
1192 
1193   return value;
1194 }
1195 
1196 void
init_hash_files(void)1197 init_hash_files (void)
1198 {
1199   hash_init (&files, 1000, file_hash_1, file_hash_2, file_hash_cmp);
1200 }
1201 
1202 /* EOF */
1203