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