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