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