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