Change make license
[platform/upstream/make.git] / src / remake.c
1 /* Basic dependency engine for GNU Make.
2 Copyright (C) 1988-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include "makeint.h"
18 #include "filedef.h"
19 #include "job.h"
20 #include "commands.h"
21 #include "dep.h"
22 #include "variable.h"
23 #include "debug.h"
24
25 #include <assert.h>
26
27 #ifdef HAVE_FCNTL_H
28 #include <fcntl.h>
29 #else
30 #include <sys/file.h>
31 #endif
32
33 #ifdef VMS
34 #include <starlet.h>
35 #endif
36 #ifdef WINDOWS32
37 #include <io.h>
38 #endif
39
40
41 /* The test for circular dependencies is based on the 'updating' bit in
42    'struct file'.  However, double colon targets have separate 'struct
43    file's; make sure we always use the base of the double colon chain. */
44
45 #define start_updating(_f)  (((_f)->double_colon ? (_f)->double_colon : (_f))\
46                              ->updating = 1)
47 #define finish_updating(_f) (((_f)->double_colon ? (_f)->double_colon : (_f))\
48                              ->updating = 0)
49 #define is_updating(_f)     (((_f)->double_colon ? (_f)->double_colon : (_f))\
50                              ->updating)
51
52
53 /* Incremented when a command is started (under -n, when one would be).  */
54 unsigned int commands_started = 0;
55
56 /* Set to the goal dependency.  Mostly needed for remaking makefiles.  */
57 static struct goaldep *goal_list;
58 static struct dep *goal_dep;
59
60 /* Current value for pruning the scan of the goal chain.
61    All files start with considered == 0.  */
62 static unsigned int considered = 0;
63
64 static enum update_status update_file (struct file *file, unsigned int depth);
65 static enum update_status update_file_1 (struct file *file, unsigned int depth);
66 static enum update_status check_dep (struct file *file, unsigned int depth,
67                                      FILE_TIMESTAMP this_mtime, int *must_make);
68 static enum update_status touch_file (struct file *file);
69 static void remake_file (struct file *file);
70 static FILE_TIMESTAMP name_mtime (const char *name);
71 static const char *library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr);
72
73 \f
74 /* Remake all the goals in the 'struct dep' chain GOALS.  Return -1 if nothing
75    was done, 0 if all goals were updated successfully, or 1 if a goal failed.
76
77    If rebuilding_makefiles is nonzero, these goals are makefiles, so -t, -q,
78    and -n should be disabled for them unless they were also command-line
79    targets, and we should only make one goal at a time and return as soon as
80    one goal whose 'changed' member is nonzero is successfully made.  */
81
82 enum update_status
83 update_goal_chain (struct goaldep *goaldeps)
84 {
85   int t = touch_flag, q = question_flag, n = just_print_flag;
86   enum update_status status = us_none;
87
88   /* Duplicate the chain so we can remove things from it.  */
89
90   struct dep *goals = copy_dep_chain ((struct dep *)goaldeps);
91
92   goal_list = rebuilding_makefiles ? goaldeps : NULL;
93
94 #define MTIME(file) (rebuilding_makefiles ? file_mtime_no_search (file) \
95                      : file_mtime (file))
96
97   /* Start a fresh batch of consideration.  */
98   ++considered;
99
100   /* Update all the goals until they are all finished.  */
101
102   while (goals != 0)
103     {
104       struct dep *g, *lastgoal;
105
106       /* Start jobs that are waiting for the load to go down.  */
107
108       start_waiting_jobs ();
109
110       /* Wait for a child to die.  */
111
112       reap_children (1, 0);
113
114       lastgoal = 0;
115       g = goals;
116       while (g != 0)
117         {
118           /* Iterate over all double-colon entries for this file.  */
119           struct file *file;
120           int stop = 0, any_not_updated = 0;
121
122           goal_dep = g;
123
124           for (file = g->file->double_colon ? g->file->double_colon : g->file;
125                file != NULL;
126                file = file->prev)
127             {
128               unsigned int ocommands_started;
129               enum update_status fail;
130
131               file->dontcare = ANY_SET (g->flags, RM_DONTCARE);
132
133               check_renamed (file);
134               if (rebuilding_makefiles)
135                 {
136                   if (file->cmd_target)
137                     {
138                       touch_flag = t;
139                       question_flag = q;
140                       just_print_flag = n;
141                     }
142                   else
143                     touch_flag = question_flag = just_print_flag = 0;
144                 }
145
146               /* Save the old value of 'commands_started' so we can compare
147                  later.  It will be incremented when any commands are
148                  actually run.  */
149               ocommands_started = commands_started;
150
151               fail = update_file (file, rebuilding_makefiles ? 1 : 0);
152               check_renamed (file);
153
154               /* Set the goal's 'changed' flag if any commands were started
155                  by calling update_file above.  We check this flag below to
156                  decide when to give an "up to date" diagnostic.  */
157               if (commands_started > ocommands_started)
158                 g->changed = 1;
159
160               stop = 0;
161               if ((fail || file->updated) && status < us_question)
162                 {
163                   /* We updated this goal.  Update STATUS and decide whether
164                      to stop.  */
165                   if (file->update_status)
166                     {
167                       /* Updating failed, or -q triggered.  The STATUS value
168                          tells our caller which.  */
169                       status = file->update_status;
170                       /* If -q just triggered, stop immediately.  It doesn't
171                          matter how much more we run, since we already know
172                          the answer to return.  */
173                       stop = (question_flag && !keep_going_flag
174                               && !rebuilding_makefiles);
175                     }
176                   else
177                     {
178                       FILE_TIMESTAMP mtime = MTIME (file);
179                       check_renamed (file);
180
181                       if (file->updated && g->changed &&
182                            mtime != file->mtime_before_update)
183                         {
184                           /* Updating was done.  If this is a makefile and
185                              just_print_flag or question_flag is set (meaning
186                              -n or -q was given and this file was specified
187                              as a command-line target), don't change STATUS.
188                              If STATUS is changed, we will get re-exec'd, and
189                              enter an infinite loop.  */
190                           if (!rebuilding_makefiles
191                               || (!just_print_flag && !question_flag))
192                             status = us_success;
193                           if (rebuilding_makefiles && file->dontcare)
194                             /* This is a default makefile; stop remaking.  */
195                             stop = 1;
196                         }
197                     }
198                 }
199
200               /* Keep track if any double-colon entry is not finished.
201                  When they are all finished, the goal is finished.  */
202               any_not_updated |= !file->updated;
203
204               file->dontcare = 0;
205
206               if (stop)
207                 break;
208             }
209
210           /* Reset FILE since it is null at the end of the loop.  */
211           file = g->file;
212
213           if (stop || !any_not_updated)
214             {
215               /* If we have found nothing whatever to do for the goal,
216                  print a message saying nothing needs doing.  */
217
218               if (!rebuilding_makefiles
219                   /* If the update_status is success, we updated successfully
220                      or not at all.  G->changed will have been set above if
221                      any commands were actually started for this goal.  */
222                   && file->update_status == us_success && !g->changed
223                   /* Never give a message under -s or -q.  */
224                   && !run_silent && !question_flag)
225                 OS (message, 1, ((file->phony || file->cmds == 0)
226                                  ? _("Nothing to be done for '%s'.")
227                                  : _("'%s' is up to date.")),
228                     file->name);
229
230               /* This goal is finished.  Remove it from the chain.  */
231               if (lastgoal == 0)
232                 goals = g->next;
233               else
234                 lastgoal->next = g->next;
235
236               /* Free the storage.  */
237               free (g);
238
239               g = lastgoal == 0 ? goals : lastgoal->next;
240
241               if (stop)
242                 break;
243             }
244           else
245             {
246               lastgoal = g;
247               g = g->next;
248             }
249         }
250
251       /* If we reached the end of the dependency graph update CONSIDERED
252          for the next pass.  */
253       if (g == 0)
254         ++considered;
255     }
256
257   if (rebuilding_makefiles)
258     {
259       touch_flag = t;
260       question_flag = q;
261       just_print_flag = n;
262     }
263
264   return status;
265 }
266 \f
267 /* If we're rebuilding an included makefile that failed, and we care
268    about errors, show an error message the first time.  */
269
270 void
271 show_goal_error (void)
272 {
273   struct goaldep *goal;
274
275   if ((goal_dep->flags & (RM_INCLUDED|RM_DONTCARE)) != RM_INCLUDED)
276     return;
277
278   for (goal = goal_list; goal; goal = goal->next)
279     if (goal_dep->file == goal->file)
280       {
281         if (goal->error)
282           {
283             OSS (error, &goal->floc, "%s: %s",
284                  goal->file->name, strerror ((int)goal->error));
285             goal->error = 0;
286           }
287         return;
288       }
289 }
290 \f
291 /* If FILE is not up to date, execute the commands for it.
292    Return 0 if successful, non-0 if unsuccessful;
293    but with some flag settings, just call 'exit' if unsuccessful.
294
295    DEPTH is the depth in recursions of this function.
296    We increment it during the consideration of our dependencies,
297    then decrement it again after finding out whether this file
298    is out of date.
299
300    If there are multiple double-colon entries for FILE,
301    each is considered in turn.  */
302
303 static enum update_status
304 update_file (struct file *file, unsigned int depth)
305 {
306   enum update_status status = us_success;
307   struct file *f;
308
309   f = file->double_colon ? file->double_colon : file;
310
311   /* Prune the dependency graph: if we've already been here on _this_
312      pass through the dependency graph, we don't have to go any further.
313      We won't reap_children until we start the next pass, so no state
314      change is possible below here until then.  */
315   if (f->considered == considered)
316     {
317       /* Check for the case where a target has been tried and failed but
318          the diagnostics haven't been issued. If we need the diagnostics
319          then we will have to continue. */
320       if (!(f->updated && f->update_status > us_none
321             && !f->dontcare && f->no_diag))
322         {
323           DBF (DB_VERBOSE, _("Pruning file '%s'.\n"));
324           return f->command_state == cs_finished ? f->update_status : us_success;
325         }
326     }
327
328   /* This loop runs until we start commands for a double colon rule, or until
329      the chain is exhausted. */
330   for (; f != 0; f = f->prev)
331     {
332       enum update_status new;
333
334       f->considered = considered;
335
336       new = update_file_1 (f, depth);
337       check_renamed (f);
338
339       /* Clean up any alloca() used during the update.  */
340       alloca (0);
341
342       /* If we got an error, don't bother with double_colon etc.  */
343       if (new && !keep_going_flag)
344         return new;
345
346       if (f->command_state == cs_running
347           || f->command_state == cs_deps_running)
348         /* Don't run other :: rules for this target until
349            this rule is finished.  */
350         return us_success;
351
352       if (new > status)
353         status = new;
354     }
355
356   return status;
357 }
358 \f
359 /* Show a message stating the target failed to build.  */
360
361 static void
362 complain (struct file *file)
363 {
364   /* If this file has no_diag set then it means we tried to update it
365      before in the dontcare mode and failed. The target that actually
366      failed is not necessarily this file but could be one of its direct
367      or indirect dependencies. So traverse this file's dependencies and
368      find the one that actually caused the failure. */
369
370   struct dep *d;
371
372   for (d = file->deps; d != 0; d = d->next)
373     {
374       if (d->file->updated && d->file->update_status > us_none && file->no_diag)
375         {
376           complain (d->file);
377           break;
378         }
379     }
380
381   if (d == 0)
382     {
383       show_goal_error ();
384
385       /* Didn't find any dependencies to complain about. */
386       if (file->parent)
387         {
388           size_t l = strlen (file->name) + strlen (file->parent->name) + 4;
389           const char *m = _("%sNo rule to make target '%s', needed by '%s'%s");
390
391           if (!keep_going_flag)
392             fatal (NILF, l, m, "", file->name, file->parent->name, "");
393
394           error (NILF, l, m, "*** ", file->name, file->parent->name, ".");
395         }
396       else
397         {
398           size_t l = strlen (file->name) + 4;
399           const char *m = _("%sNo rule to make target '%s'%s");
400
401           if (!keep_going_flag)
402             fatal (NILF, l, m, "", file->name, "");
403
404           error (NILF, l, m, "*** ", file->name, ".");
405         }
406
407       file->no_diag = 0;
408     }
409 }
410
411 /* Consider a single 'struct file' and update it as appropriate.
412    Return 0 on success, or non-0 on failure.  */
413
414 static enum update_status
415 update_file_1 (struct file *file, unsigned int depth)
416 {
417   enum update_status dep_status = us_success;
418   FILE_TIMESTAMP this_mtime;
419   int noexist, must_make, deps_changed;
420   struct file *ofile;
421   struct dep *d, *ad;
422   struct dep amake;
423   int running = 0;
424
425   DBF (DB_VERBOSE, _("Considering target file '%s'.\n"));
426
427   if (file->updated)
428     {
429       if (file->update_status > us_none)
430         {
431           DBF (DB_VERBOSE,
432                _("Recently tried and failed to update file '%s'.\n"));
433
434           /* If the file we tried to make is marked no_diag then no message
435              was printed about it when it failed during the makefile rebuild.
436              If we're trying to build it again in the normal rebuild, print a
437              message now.  */
438           if (file->no_diag && !file->dontcare)
439               complain (file);
440
441           return file->update_status;
442         }
443
444       DBF (DB_VERBOSE, _("File '%s' was considered already.\n"));
445       return 0;
446     }
447
448   switch (file->command_state)
449     {
450     case cs_not_started:
451     case cs_deps_running:
452       break;
453     case cs_running:
454       DBF (DB_VERBOSE, _("Still updating file '%s'.\n"));
455       return 0;
456     case cs_finished:
457       DBF (DB_VERBOSE, _("Finished updating file '%s'.\n"));
458       return file->update_status;
459     default:
460       abort ();
461     }
462
463   /* Determine whether the diagnostics will be issued should this update
464      fail. */
465   file->no_diag = file->dontcare;
466
467   ++depth;
468
469   /* Notice recursive update of the same file.  */
470   start_updating (file);
471
472   /* We might change file if we find a different one via vpath;
473      remember this one to turn off updating.  */
474   ofile = file;
475
476   /* Looking at the file's modtime beforehand allows the possibility
477      that its name may be changed by a VPATH search, and thus it may
478      not need an implicit rule.  If this were not done, the file
479      might get implicit commands that apply to its initial name, only
480      to have that name replaced with another found by VPATH search.  */
481
482   this_mtime = file_mtime (file);
483   check_renamed (file);
484   noexist = this_mtime == NONEXISTENT_MTIME;
485   if (noexist)
486     DBF (DB_BASIC, _("File '%s' does not exist.\n"));
487   else if (ORDINARY_MTIME_MIN <= this_mtime && this_mtime <= ORDINARY_MTIME_MAX
488            && file->low_resolution_time)
489     {
490       /* Avoid spurious rebuilds due to low resolution time stamps.  */
491       int ns = FILE_TIMESTAMP_NS (this_mtime);
492       if (ns != 0)
493         OS (error, NILF,
494             _("*** Warning: .LOW_RESOLUTION_TIME file '%s' has a high resolution time stamp"),
495             file->name);
496       this_mtime += FILE_TIMESTAMPS_PER_S - 1 - ns;
497     }
498
499   must_make = noexist;
500
501   /* If file was specified as a target with no commands,
502      come up with some default commands.  */
503
504   if (!file->phony && file->cmds == 0 && !file->tried_implicit)
505     {
506       if (try_implicit_rule (file, depth))
507         DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
508       else
509         DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
510       file->tried_implicit = 1;
511     }
512   if (file->cmds == 0 && !file->is_target
513       && default_file != 0 && default_file->cmds != 0)
514     {
515       DBF (DB_IMPLICIT, _("Using default recipe for '%s'.\n"));
516       file->cmds = default_file->cmds;
517     }
518
519   /* Update all non-intermediate files we depend on, if necessary, and see
520      whether any of them is more recent than this file.  We need to walk our
521      deps, AND the deps of any also_make targets to ensure everything happens
522      in the correct order.  */
523
524   amake.file = file;
525   amake.next = file->also_make;
526   ad = &amake;
527   while (ad)
528     {
529       struct dep *lastd = 0;
530
531       /* Find the deps we're scanning */
532       d = ad->file->deps;
533       ad = ad->next;
534
535       while (d)
536         {
537           enum update_status new;
538           FILE_TIMESTAMP mtime;
539           int maybe_make;
540           int dontcare = 0;
541
542           check_renamed (d->file);
543
544           mtime = file_mtime (d->file);
545           check_renamed (d->file);
546
547           if (is_updating (d->file))
548             {
549               OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
550                    file->name, d->file->name);
551               /* We cannot free D here because our the caller will still have
552                  a reference to it when we were called recursively via
553                  check_dep below.  */
554               if (lastd == 0)
555                 file->deps = d->next;
556               else
557                 lastd->next = d->next;
558               d = d->next;
559               continue;
560             }
561
562           d->file->parent = file;
563           maybe_make = must_make;
564
565           /* Inherit dontcare flag from our parent. */
566           if (rebuilding_makefiles)
567             {
568               dontcare = d->file->dontcare;
569               d->file->dontcare = file->dontcare;
570             }
571
572           new = check_dep (d->file, depth, this_mtime, &maybe_make);
573           if (new > dep_status)
574             dep_status = new;
575
576           /* Restore original dontcare flag. */
577           if (rebuilding_makefiles)
578             d->file->dontcare = dontcare;
579
580           if (! d->ignore_mtime)
581             must_make = maybe_make;
582
583           check_renamed (d->file);
584
585           {
586             struct file *f = d->file;
587             if (f->double_colon)
588               f = f->double_colon;
589             do
590               {
591                 running |= (f->command_state == cs_running
592                             || f->command_state == cs_deps_running);
593                 f = f->prev;
594               }
595             while (f != 0);
596           }
597
598           if (dep_status && !keep_going_flag)
599             break;
600
601           if (!running)
602             /* The prereq is considered changed if the timestamp has changed
603                while it was built, OR it doesn't exist.  */
604             d->changed = ((file_mtime (d->file) != mtime)
605                           || (mtime == NONEXISTENT_MTIME));
606
607           lastd = d;
608           d = d->next;
609         }
610     }
611
612   /* Now we know whether this target needs updating.
613      If it does, update all the intermediate files we depend on.  */
614
615   if (must_make || always_make_flag)
616     {
617       for (d = file->deps; d != 0; d = d->next)
618         if (d->file->intermediate)
619           {
620             enum update_status new;
621             int dontcare = 0;
622
623             FILE_TIMESTAMP mtime = file_mtime (d->file);
624             check_renamed (d->file);
625             d->file->parent = file;
626
627             /* Inherit dontcare flag from our parent. */
628             if (rebuilding_makefiles)
629               {
630                 dontcare = d->file->dontcare;
631                 d->file->dontcare = file->dontcare;
632               }
633
634             /* We may have already considered this file, when we didn't know
635                we'd need to update it.  Force update_file() to consider it and
636                not prune it.  */
637             d->file->considered = 0;
638
639             new = update_file (d->file, depth);
640             if (new > dep_status)
641               dep_status = new;
642
643             /* Restore original dontcare flag. */
644             if (rebuilding_makefiles)
645               d->file->dontcare = dontcare;
646
647             check_renamed (d->file);
648
649             {
650               struct file *f = d->file;
651               if (f->double_colon)
652                 f = f->double_colon;
653               do
654                 {
655                   running |= (f->command_state == cs_running
656                               || f->command_state == cs_deps_running);
657                   f = f->prev;
658                 }
659               while (f != 0);
660             }
661
662             if (dep_status && !keep_going_flag)
663               break;
664
665             if (!running)
666               d->changed = ((file->phony && file->cmds != 0)
667                             || file_mtime (d->file) != mtime);
668           }
669     }
670
671   finish_updating (file);
672   finish_updating (ofile);
673
674   DBF (DB_VERBOSE, _("Finished prerequisites of target file '%s'.\n"));
675
676   if (running)
677     {
678       set_command_state (file, cs_deps_running);
679       --depth;
680       DBF (DB_VERBOSE, _("The prerequisites of '%s' are being made.\n"));
681       return 0;
682     }
683
684   /* If any dependency failed, give up now.  */
685
686   if (dep_status)
687     {
688       /* I'm not sure if we can't just assign dep_status...  */
689       file->update_status = dep_status == us_none ? us_failed : dep_status;
690       notice_finished_file (file);
691
692       --depth;
693
694       DBF (DB_VERBOSE, _("Giving up on target file '%s'.\n"));
695
696       if (depth == 0 && keep_going_flag
697           && !just_print_flag && !question_flag)
698         OS (error, NILF,
699             _("Target '%s' not remade because of errors."), file->name);
700
701       return dep_status;
702     }
703
704   if (file->command_state == cs_deps_running)
705     /* The commands for some deps were running on the last iteration, but
706        they have finished now.  Reset the command_state to not_started to
707        simplify later bookkeeping.  It is important that we do this only
708        when the prior state was cs_deps_running, because that prior state
709        was definitely propagated to FILE's also_make's by set_command_state
710        (called above), but in another state an also_make may have
711        independently changed to finished state, and we would confuse that
712        file's bookkeeping (updated, but not_started is bogus state).  */
713     set_command_state (file, cs_not_started);
714
715   /* Now record which prerequisites are more
716      recent than this file, so we can define $?.  */
717
718   deps_changed = 0;
719   for (d = file->deps; d != 0; d = d->next)
720     {
721       FILE_TIMESTAMP d_mtime = file_mtime (d->file);
722       check_renamed (d->file);
723
724       if (! d->ignore_mtime)
725         {
726 #if 1
727           /* %%% In version 4, remove this code completely to
728            implement not remaking deps if their deps are newer
729            than their parents.  */
730           if (d_mtime == NONEXISTENT_MTIME && !d->file->intermediate)
731             /* We must remake if this dep does not
732                exist and is not intermediate.  */
733             must_make = 1;
734 #endif
735
736           /* Set DEPS_CHANGED if this dep actually changed.  */
737           deps_changed |= d->changed;
738         }
739
740       /* Set D->changed if either this dep actually changed,
741          or its dependent, FILE, is older or does not exist.  */
742       d->changed |= noexist || d_mtime > this_mtime;
743
744       if (!noexist && ISDB (DB_BASIC|DB_VERBOSE))
745         {
746           const char *fmt = 0;
747
748           if (d->ignore_mtime)
749             {
750               if (ISDB (DB_VERBOSE))
751                 fmt = _("Prerequisite '%s' is order-only for target '%s'.\n");
752             }
753           else if (d_mtime == NONEXISTENT_MTIME)
754             {
755               if (ISDB (DB_BASIC))
756                 fmt = _("Prerequisite '%s' of target '%s' does not exist.\n");
757             }
758           else if (d->changed)
759             {
760               if (ISDB (DB_BASIC))
761                 fmt = _("Prerequisite '%s' is newer than target '%s'.\n");
762             }
763           else if (ISDB (DB_VERBOSE))
764             fmt = _("Prerequisite '%s' is older than target '%s'.\n");
765
766           if (fmt)
767             {
768               print_spaces (depth);
769               printf (fmt, dep_name (d), file->name);
770               fflush (stdout);
771             }
772         }
773     }
774
775   /* Here depth returns to the value it had when we were called.  */
776   depth--;
777
778   if (file->double_colon && file->deps == 0)
779     {
780       must_make = 1;
781       DBF (DB_BASIC,
782            _("Target '%s' is double-colon and has no prerequisites.\n"));
783     }
784   else if (!noexist && file->is_target && !deps_changed && file->cmds == 0
785            && !always_make_flag)
786     {
787       must_make = 0;
788       DBF (DB_VERBOSE,
789            _("No recipe for '%s' and no prerequisites actually changed.\n"));
790     }
791   else if (!must_make && file->cmds != 0 && always_make_flag)
792     {
793       must_make = 1;
794       DBF (DB_VERBOSE, _("Making '%s' due to always-make flag.\n"));
795     }
796
797   if (!must_make)
798     {
799       if (ISDB (DB_VERBOSE))
800         {
801           print_spaces (depth);
802           printf (_("No need to remake target '%s'"), file->name);
803           if (!streq (file->name, file->hname))
804               printf (_("; using VPATH name '%s'"), file->hname);
805           puts (".");
806           fflush (stdout);
807         }
808
809       notice_finished_file (file);
810
811       /* Since we don't need to remake the file, convert it to use the
812          VPATH filename if we found one.  hfile will be either the
813          local name if no VPATH or the VPATH name if one was found.  */
814
815       while (file)
816         {
817           file->name = file->hname;
818           file = file->prev;
819         }
820
821       return 0;
822     }
823
824   DBF (DB_BASIC, _("Must remake target '%s'.\n"));
825
826   /* It needs to be remade.  If it's VPATH and not reset via GPATH, toss the
827      VPATH.  */
828   if (!streq (file->name, file->hname))
829     {
830       DB (DB_BASIC, (_("  Ignoring VPATH name '%s'.\n"), file->hname));
831       file->ignore_vpath = 1;
832     }
833
834   /* Now, take appropriate actions to remake the file.  */
835   remake_file (file);
836
837   if (file->command_state != cs_finished)
838     {
839       DBF (DB_VERBOSE, _("Recipe of '%s' is being run.\n"));
840       return 0;
841     }
842
843   switch (file->update_status)
844     {
845     case us_failed:
846       DBF (DB_BASIC, _("Failed to remake target file '%s'.\n"));
847       break;
848     case us_success:
849       DBF (DB_BASIC, _("Successfully remade target file '%s'.\n"));
850       break;
851     case us_question:
852       DBF (DB_BASIC, _("Target file '%s' needs to be remade under -q.\n"));
853       break;
854     case us_none:
855       break;
856     }
857
858   file->updated = 1;
859   return file->update_status;
860 }
861 \f
862 /* Set FILE's 'updated' flag and re-check its mtime and the mtime's of all
863    files listed in its 'also_make' member.  Under -t, this function also
864    touches FILE.
865
866    On return, FILE->update_status will no longer be us_none if it was.  */
867
868 void
869 notice_finished_file (struct file *file)
870 {
871   struct dep *d;
872   int ran = file->command_state == cs_running;
873   int touched = 0;
874
875   file->command_state = cs_finished;
876   file->updated = 1;
877
878   if (touch_flag
879       /* The update status will be:
880            us_success   if 0 or more commands (+ or ${MAKE}) were run and won;
881            us_none      if this target was not remade;
882            >us_none     if some commands were run and lost.
883          We touch the target if it has commands which either were not run
884          or won when they ran (i.e. status is 0).  */
885       && file->update_status == us_success)
886     {
887       if (file->cmds != 0 && file->cmds->any_recurse)
888         {
889           /* If all the command lines were recursive,
890              we don't want to do the touching.  */
891           unsigned int i;
892           for (i = 0; i < file->cmds->ncommand_lines; ++i)
893             if (!(file->cmds->lines_flags[i] & COMMANDS_RECURSE))
894               goto have_nonrecursing;
895         }
896       else
897         {
898         have_nonrecursing:
899           if (file->phony)
900             file->update_status = us_success;
901           /* According to POSIX, -t doesn't affect targets with no cmds.  */
902           else if (file->cmds != 0)
903             {
904               /* Should set file's modification date and do nothing else.  */
905               file->update_status = touch_file (file);
906
907               /* Pretend we ran a real touch command, to suppress the
908                  "'foo' is up to date" message.  */
909               commands_started++;
910
911               /* Request for the timestamp to be updated (and distributed
912                  to the double-colon entries). Simply setting ran=1 would
913                  almost have done the trick, but messes up with the also_make
914                  updating logic below.  */
915               touched = 1;
916             }
917         }
918     }
919
920   if (file->mtime_before_update == UNKNOWN_MTIME)
921     file->mtime_before_update = file->last_mtime;
922
923   if ((ran && !file->phony) || touched)
924     {
925       int i = 0;
926
927       /* If -n, -t, or -q and all the commands are recursive, we ran them so
928          really check the target's mtime again.  Otherwise, assume the target
929          would have been updated. */
930
931       if ((question_flag || just_print_flag || touch_flag) && file->cmds)
932         {
933           for (i = file->cmds->ncommand_lines; i > 0; --i)
934             if (! (file->cmds->lines_flags[i-1] & COMMANDS_RECURSE))
935               break;
936         }
937
938       /* If there were no commands at all, it's always new. */
939
940       else if (file->is_target && file->cmds == 0)
941         i = 1;
942
943       file->last_mtime = i == 0 ? UNKNOWN_MTIME : NEW_MTIME;
944     }
945
946   if (file->double_colon)
947     {
948       /* If this is a double colon rule and it is the last one to be
949          updated, propagate the change of modification time to all the
950          double-colon entries for this file.
951
952          We do it on the last update because it is important to handle
953          individual entries as separate rules with separate timestamps
954          while they are treated as targets and then as one rule with the
955          unified timestamp when they are considered as a prerequisite
956          of some target.  */
957
958       struct file *f;
959       FILE_TIMESTAMP max_mtime = file->last_mtime;
960
961       /* Check that all rules were updated and at the same time find
962          the max timestamp.  We assume UNKNOWN_MTIME is newer then
963          any other value.  */
964       for (f = file->double_colon; f != 0 && f->updated; f = f->prev)
965         if (max_mtime != UNKNOWN_MTIME
966             && (f->last_mtime == UNKNOWN_MTIME || f->last_mtime > max_mtime))
967           max_mtime = f->last_mtime;
968
969       if (f == 0)
970         for (f = file->double_colon; f != 0; f = f->prev)
971           f->last_mtime = max_mtime;
972     }
973
974   if (ran && file->update_status != us_none)
975     /* We actually tried to update FILE, which has
976        updated its also_make's as well (if it worked).
977        If it didn't work, it wouldn't work again for them.
978        So mark them as updated with the same status.  */
979     for (d = file->also_make; d != 0; d = d->next)
980       {
981         d->file->command_state = cs_finished;
982         d->file->updated = 1;
983         d->file->update_status = file->update_status;
984
985         if (ran && !d->file->phony)
986           /* Fetch the new modification time.
987              We do this instead of just invalidating the cached time
988              so that a vpath_search can happen.  Otherwise, it would
989              never be done because the target is already updated.  */
990           f_mtime (d->file, 0);
991       }
992   else if (file->update_status == us_none)
993     /* Nothing was done for FILE, but it needed nothing done.
994        So mark it now as "succeeded".  */
995     file->update_status = us_success;
996 }
997 \f
998 /* Check whether another file (whose mtime is THIS_MTIME) needs updating on
999    account of a dependency which is file FILE.  If it does, store 1 in
1000    *MUST_MAKE_PTR.  In the process, update any non-intermediate files that
1001    FILE depends on (including FILE itself).  Return nonzero if any updating
1002    failed.  */
1003
1004 static enum update_status
1005 check_dep (struct file *file, unsigned int depth,
1006            FILE_TIMESTAMP this_mtime, int *must_make_ptr)
1007 {
1008   struct file *ofile;
1009   struct dep *d;
1010   enum update_status dep_status = us_success;
1011
1012   ++depth;
1013   start_updating (file);
1014
1015   /* We might change file if we find a different one via vpath;
1016      remember this one to turn off updating.  */
1017   ofile = file;
1018
1019   if (file->phony || !file->intermediate)
1020     {
1021       /* If this is a non-intermediate file, update it and record whether it
1022          is newer than THIS_MTIME.  */
1023       FILE_TIMESTAMP mtime;
1024       dep_status = update_file (file, depth);
1025       check_renamed (file);
1026       mtime = file_mtime (file);
1027       check_renamed (file);
1028       if (mtime == NONEXISTENT_MTIME || mtime > this_mtime)
1029         *must_make_ptr = 1;
1030     }
1031   else
1032     {
1033       /* FILE is an intermediate file.  */
1034       FILE_TIMESTAMP mtime;
1035
1036       if (!file->phony && file->cmds == 0 && !file->tried_implicit)
1037         {
1038           if (try_implicit_rule (file, depth))
1039             DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
1040           else
1041             DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
1042           file->tried_implicit = 1;
1043         }
1044       if (file->cmds == 0 && !file->is_target
1045           && default_file != 0 && default_file->cmds != 0)
1046         {
1047           DBF (DB_IMPLICIT, _("Using default commands for '%s'.\n"));
1048           file->cmds = default_file->cmds;
1049         }
1050
1051       check_renamed (file);
1052       mtime = file_mtime (file);
1053       check_renamed (file);
1054       if (mtime != NONEXISTENT_MTIME && mtime > this_mtime)
1055         /* If the intermediate file actually exists and is newer, then we
1056            should remake from it.  */
1057         *must_make_ptr = 1;
1058       else
1059         {
1060           /* Otherwise, update all non-intermediate files we depend on, if
1061              necessary, and see whether any of them is more recent than the
1062              file on whose behalf we are checking.  */
1063           struct dep *ld;
1064           int deps_running = 0;
1065
1066           /* If this target is not running, set it's state so that we check it
1067              fresh.  It could be it was checked as part of an order-only
1068              prerequisite and so wasn't rebuilt then, but should be now.  */
1069           if (file->command_state != cs_running)
1070             {
1071               /* If the target was waiting for a dependency it has to be
1072                  reconsidered, as that dependency might have finished.  */
1073               if (file->command_state == cs_deps_running)
1074                 file->considered = 0;
1075
1076               set_command_state (file, cs_not_started);
1077             }
1078
1079           ld = 0;
1080           d = file->deps;
1081           while (d != 0)
1082             {
1083               enum update_status new;
1084               int maybe_make;
1085
1086               if (is_updating (d->file))
1087                 {
1088                   OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
1089                        file->name, d->file->name);
1090                   if (ld == 0)
1091                     {
1092                       file->deps = d->next;
1093                       free_dep (d);
1094                       d = file->deps;
1095                     }
1096                   else
1097                     {
1098                       ld->next = d->next;
1099                       free_dep (d);
1100                       d = ld->next;
1101                     }
1102                   continue;
1103                 }
1104
1105               d->file->parent = file;
1106               maybe_make = *must_make_ptr;
1107               new = check_dep (d->file, depth, this_mtime, &maybe_make);
1108               if (new > dep_status)
1109                 dep_status = new;
1110
1111               if (! d->ignore_mtime)
1112                 *must_make_ptr = maybe_make;
1113               check_renamed (d->file);
1114               if (dep_status && !keep_going_flag)
1115                 break;
1116
1117               if (d->file->command_state == cs_running
1118                   || d->file->command_state == cs_deps_running)
1119                 deps_running = 1;
1120
1121               ld = d;
1122               d = d->next;
1123             }
1124
1125           if (deps_running)
1126             /* Record that some of FILE's deps are still being made.
1127                This tells the upper levels to wait on processing it until the
1128                commands are finished.  */
1129             set_command_state (file, cs_deps_running);
1130         }
1131     }
1132
1133   finish_updating (file);
1134   finish_updating (ofile);
1135
1136   return dep_status;
1137 }
1138 \f
1139 /* Touch FILE.  Return us_success if successful, us_failed if not.  */
1140
1141 #define TOUCH_ERROR(call) do{ perror_with_name ((call), file->name);    \
1142                               return us_failed; }while(0)
1143
1144 static enum update_status
1145 touch_file (struct file *file)
1146 {
1147   if (!run_silent)
1148     OS (message, 0, "touch %s", file->name);
1149
1150   /* Print-only (-n) takes precedence over touch (-t).  */
1151   if (just_print_flag)
1152     return us_success;
1153
1154 #ifndef NO_ARCHIVES
1155   if (ar_name (file->name))
1156     return ar_touch (file->name) ? us_failed : us_success;
1157   else
1158 #endif
1159     {
1160       int fd;
1161
1162       EINTRLOOP (fd, open (file->name, O_RDWR | O_CREAT, 0666));
1163       if (fd < 0)
1164         TOUCH_ERROR ("touch: open: ");
1165       else
1166         {
1167           struct stat statbuf;
1168           char buf = 'x';
1169           int e;
1170
1171           EINTRLOOP (e, fstat (fd, &statbuf));
1172           if (e < 0)
1173             TOUCH_ERROR ("touch: fstat: ");
1174           /* Rewrite character 0 same as it already is.  */
1175           EINTRLOOP (e, read (fd, &buf, 1));
1176           if (e < 0)
1177             TOUCH_ERROR ("touch: read: ");
1178           {
1179             off_t o;
1180             EINTRLOOP (o, lseek (fd, 0L, 0));
1181             if (o < 0L)
1182               TOUCH_ERROR ("touch: lseek: ");
1183           }
1184           EINTRLOOP (e, write (fd, &buf, 1));
1185           if (e < 0)
1186             TOUCH_ERROR ("touch: write: ");
1187
1188           /* If file length was 0, we just changed it, so change it back.  */
1189           if (statbuf.st_size == 0)
1190             {
1191               (void) close (fd);
1192               EINTRLOOP (fd, open (file->name, O_RDWR | O_TRUNC, 0666));
1193               if (fd < 0)
1194                 TOUCH_ERROR ("touch: open: ");
1195             }
1196           (void) close (fd);
1197         }
1198     }
1199
1200   return us_success;
1201 }
1202 \f
1203 /* Having checked and updated the dependencies of FILE,
1204    do whatever is appropriate to remake FILE itself.
1205    Return the status from executing FILE's commands.  */
1206
1207 static void
1208 remake_file (struct file *file)
1209 {
1210   if (file->cmds == 0)
1211     {
1212       if (file->phony)
1213         /* Phony target.  Pretend it succeeded.  */
1214         file->update_status = us_success;
1215       else if (file->is_target)
1216         /* This is a nonexistent target file we cannot make.
1217            Pretend it was successfully remade.  */
1218         file->update_status = us_success;
1219       else
1220         {
1221           /* This is a dependency file we cannot remake.  Fail.  */
1222           if (!rebuilding_makefiles || !file->dontcare)
1223             complain (file);
1224           file->update_status = us_failed;
1225         }
1226     }
1227   else
1228     {
1229       chop_commands (file->cmds);
1230
1231       /* The normal case: start some commands.  */
1232       if (!touch_flag || file->cmds->any_recurse)
1233         {
1234           execute_file_commands (file);
1235           return;
1236         }
1237
1238       /* This tells notice_finished_file it is ok to touch the file.  */
1239       file->update_status = us_success;
1240     }
1241
1242   /* This does the touching under -t.  */
1243   notice_finished_file (file);
1244 }
1245 \f
1246 /* Return the mtime of a file, given a 'struct file'.
1247    Caches the time in the struct file to avoid excess stat calls.
1248
1249    If the file is not found, and SEARCH is nonzero, VPATH searching and
1250    replacement is done.  If that fails, a library (-lLIBNAME) is tried and
1251    the library's actual name (/lib/libLIBNAME.a, etc.) is substituted into
1252    FILE.  */
1253
1254 FILE_TIMESTAMP
1255 f_mtime (struct file *file, int search)
1256 {
1257   FILE_TIMESTAMP mtime;
1258   unsigned int propagate_timestamp;
1259
1260   /* File's mtime is not known; must get it from the system.  */
1261
1262 #ifndef NO_ARCHIVES
1263   if (ar_name (file->name))
1264     {
1265       /* This file is an archive-member reference.  */
1266
1267       char *arname, *memname;
1268       struct file *arfile;
1269       time_t member_date;
1270
1271       /* Find the archive's name.  */
1272       ar_parse_name (file->name, &arname, &memname);
1273
1274       /* Find the modification time of the archive itself.
1275          Also allow for its name to be changed via VPATH search.  */
1276       arfile = lookup_file (arname);
1277       if (arfile == 0)
1278         arfile = enter_file (strcache_add (arname));
1279       mtime = f_mtime (arfile, search);
1280       check_renamed (arfile);
1281       if (search && strcmp (arfile->hname, arname))
1282         {
1283           /* The archive's name has changed.
1284              Change the archive-member reference accordingly.  */
1285
1286           char *name;
1287           size_t arlen, memlen;
1288
1289           arlen = strlen (arfile->hname);
1290           memlen = strlen (memname);
1291
1292           name = alloca (arlen + 1 + memlen + 2);
1293           memcpy (name, arfile->hname, arlen);
1294           name[arlen] = '(';
1295           memcpy (name + arlen + 1, memname, memlen);
1296           name[arlen + 1 + memlen] = ')';
1297           name[arlen + 1 + memlen + 1] = '\0';
1298
1299           /* If the archive was found with GPATH, make the change permanent;
1300              otherwise defer it until later.  */
1301           if (arfile->name == arfile->hname)
1302             rename_file (file, strcache_add (name));
1303           else
1304             rehash_file (file, strcache_add (name));
1305           check_renamed (file);
1306         }
1307
1308       free (arname);
1309
1310       file->low_resolution_time = 1;
1311
1312       if (mtime == NONEXISTENT_MTIME)
1313         /* The archive doesn't exist, so its members don't exist either.  */
1314         return NONEXISTENT_MTIME;
1315
1316       member_date = ar_member_date (file->hname);
1317       mtime = (member_date == (time_t) -1
1318                ? NONEXISTENT_MTIME
1319                : file_timestamp_cons (file->hname, member_date, 0));
1320     }
1321   else
1322 #endif
1323     {
1324       mtime = name_mtime (file->name);
1325
1326       if (mtime == NONEXISTENT_MTIME && search && !file->ignore_vpath)
1327         {
1328           /* If name_mtime failed, search VPATH.  */
1329           const char *name = vpath_search (file->name, &mtime, NULL, NULL);
1330           if (name
1331               /* Last resort, is it a library (-lxxx)?  */
1332               || (file->name[0] == '-' && file->name[1] == 'l'
1333                   && (name = library_search (file->name, &mtime)) != 0))
1334             {
1335               size_t name_len;
1336
1337               if (mtime != UNKNOWN_MTIME)
1338                 /* vpath_search and library_search store UNKNOWN_MTIME
1339                    if they didn't need to do a stat call for their work.  */
1340                 file->last_mtime = mtime;
1341
1342               /* If we found it in VPATH, see if it's in GPATH too; if so,
1343                  change the name right now; if not, defer until after the
1344                  dependencies are updated. */
1345 #ifndef VMS
1346               name_len = strlen (name) - strlen (file->name) - 1;
1347 #else
1348               name_len = strlen (name) - strlen (file->name);
1349               if (name[name_len - 1] == '/')
1350                   name_len--;
1351 #endif
1352               if (gpath_search (name, name_len))
1353                 {
1354                   rename_file (file, name);
1355                   check_renamed (file);
1356                   return file_mtime (file);
1357                 }
1358
1359               rehash_file (file, name);
1360               check_renamed (file);
1361               /* If the result of a vpath search is -o or -W, preserve it.
1362                  Otherwise, find the mtime of the resulting file.  */
1363               if (mtime != OLD_MTIME && mtime != NEW_MTIME)
1364                 mtime = name_mtime (name);
1365             }
1366         }
1367     }
1368
1369   /* Files can have bogus timestamps that nothing newly made will be
1370      "newer" than.  Updating their dependents could just result in loops.
1371      So notify the user of the anomaly with a warning.
1372
1373      We only need to do this once, for now. */
1374
1375   if (!clock_skew_detected
1376       && mtime != NONEXISTENT_MTIME && mtime != NEW_MTIME
1377       && !file->updated)
1378     {
1379       static FILE_TIMESTAMP adjusted_now;
1380
1381       FILE_TIMESTAMP adjusted_mtime = mtime;
1382
1383 #if defined(WINDOWS32) || defined(__MSDOS__)
1384       /* Experimentation has shown that FAT filesystems can set file times
1385          up to 3 seconds into the future!  Play it safe.  */
1386
1387 #define FAT_ADJ_OFFSET  (FILE_TIMESTAMP) 3
1388
1389       FILE_TIMESTAMP adjustment = FAT_ADJ_OFFSET << FILE_TIMESTAMP_LO_BITS;
1390       if (ORDINARY_MTIME_MIN + adjustment <= adjusted_mtime)
1391         adjusted_mtime -= adjustment;
1392 #elif defined(__EMX__)
1393       /* FAT filesystems round time to the nearest even second!
1394          Allow for any file (NTFS or FAT) to perhaps suffer from this
1395          brain damage.  */
1396       FILE_TIMESTAMP adjustment = (((FILE_TIMESTAMP_S (adjusted_mtime) & 1) == 0
1397                      && FILE_TIMESTAMP_NS (adjusted_mtime) == 0)
1398                     ? (FILE_TIMESTAMP) 1 << FILE_TIMESTAMP_LO_BITS
1399                     : 0);
1400 #endif
1401
1402       /* If the file's time appears to be in the future, update our
1403          concept of the present and try once more.  */
1404       if (adjusted_now < adjusted_mtime)
1405         {
1406           int resolution;
1407           FILE_TIMESTAMP now = file_timestamp_now (&resolution);
1408           adjusted_now = now + (resolution - 1);
1409           if (adjusted_now < adjusted_mtime)
1410             {
1411               double from_now =
1412                 (FILE_TIMESTAMP_S (mtime) - FILE_TIMESTAMP_S (now)
1413                  + ((FILE_TIMESTAMP_NS (mtime) - FILE_TIMESTAMP_NS (now))
1414                     / 1e9));
1415               char from_now_string[100];
1416
1417               if (from_now >= 99 && from_now <= ULONG_MAX)
1418                 sprintf (from_now_string, "%lu", (unsigned long) from_now);
1419               else
1420                 sprintf (from_now_string, "%.2g", from_now);
1421               OSS (error, NILF,
1422                    _("Warning: File '%s' has modification time %s s in the future"),
1423                    file->name, from_now_string);
1424               clock_skew_detected = 1;
1425             }
1426         }
1427     }
1428
1429   /* Store the mtime into all the entries for this file for which it is safe
1430      to do so: avoid propagating timestamps to double-colon rules that haven't
1431      been examined so they're run or not based on the pre-update timestamp.  */
1432   if (file->double_colon)
1433     file = file->double_colon;
1434
1435   propagate_timestamp = file->updated;
1436   do
1437     {
1438       /* If this file is not implicit but it is intermediate then it was
1439          made so by the .INTERMEDIATE target.  If this file has never
1440          been built by us but was found now, it existed before make
1441          started.  So, turn off the intermediate bit so make doesn't
1442          delete it, since it didn't create it.  */
1443       if (mtime != NONEXISTENT_MTIME && file->command_state == cs_not_started
1444           && !file->tried_implicit && file->intermediate)
1445         file->intermediate = 0;
1446
1447       if (file->updated == propagate_timestamp)
1448         file->last_mtime = mtime;
1449       file = file->prev;
1450     }
1451   while (file != 0);
1452
1453   return mtime;
1454 }
1455
1456
1457 /* Return the mtime of the file or archive-member reference NAME.  */
1458
1459 /* First, we check with stat().  If the file does not exist, then we return
1460    NONEXISTENT_MTIME.  If it does, and the symlink check flag is set, then
1461    examine each indirection of the symlink and find the newest mtime.
1462    This causes one duplicate stat() when -L is being used, but the code is
1463    much cleaner.  */
1464
1465 static FILE_TIMESTAMP
1466 name_mtime (const char *name)
1467 {
1468   FILE_TIMESTAMP mtime;
1469   struct stat st;
1470   int e;
1471
1472 #if defined(WINDOWS32)
1473   {
1474     char tem[MAXPATHLEN], *tstart, *tend;
1475     const char *p = name + strlen (name);
1476
1477     /* Remove any trailing slashes and "."/"..".  MS-Windows stat
1478        fails on valid directories if NAME ends in a slash, and we need
1479        to emulate the Posix behavior where stat on "foo/" or "foo/."
1480        succeeds ONLY if "foo" is a directory. */
1481     if (p > name)
1482       {
1483         memcpy (tem, name, p - name + 1);
1484         tstart = tem;
1485         if (tstart[1] == ':')
1486           tstart += 2;
1487         tend = tem + (p - name - 1);
1488         if (*tend == '.' && tend > tstart)
1489           tend--;
1490         if (*tend == '.' && tend > tstart)
1491           tend--;
1492         for ( ; tend > tstart && (*tend == '/' || *tend == '\\'); tend--)
1493           *tend = '\0';
1494       }
1495     else
1496       {
1497         tem[0] = '\0';
1498         tend = &tem[0];
1499       }
1500
1501     e = stat (tem, &st);
1502     if (e == 0 && !_S_ISDIR (st.st_mode) && tend < tem + (p - name - 1))
1503       {
1504         errno = ENOTDIR;
1505         e = -1;
1506       }
1507   }
1508 #else
1509   EINTRLOOP (e, stat (name, &st));
1510 #endif
1511   if (e == 0)
1512     mtime = FILE_TIMESTAMP_STAT_MODTIME (name, st);
1513   else if (errno == ENOENT || errno == ENOTDIR)
1514     mtime = NONEXISTENT_MTIME;
1515   else
1516     {
1517       perror_with_name ("stat: ", name);
1518       return NONEXISTENT_MTIME;
1519     }
1520
1521   /* If we get here we either found it, or it doesn't exist.
1522      If it doesn't exist see if we can use a symlink mtime instead.  */
1523
1524 #ifdef MAKE_SYMLINKS
1525 #ifndef S_ISLNK
1526 # define S_ISLNK(_m)     (((_m)&S_IFMT)==S_IFLNK)
1527 #endif
1528   if (check_symlink_flag && strlen (name) <= GET_PATH_MAX)
1529     {
1530       PATH_VAR (lpath);
1531
1532       /* Check each symbolic link segment (if any).  Find the latest mtime
1533          amongst all of them (and the target file of course).
1534          Note that we have already successfully dereferenced all the links
1535          above.  So, if we run into any error trying to lstat(), or
1536          readlink(), or whatever, something bizarre-o happened.  Just give up
1537          and use whatever mtime we've already computed at that point.  */
1538       strcpy (lpath, name);
1539       while (1)
1540         {
1541           FILE_TIMESTAMP ltime;
1542           PATH_VAR (lbuf);
1543           long llen;
1544           char *p;
1545
1546           EINTRLOOP (e, lstat (lpath, &st));
1547           if (e)
1548             {
1549               /* Just take what we have so far.  */
1550               if (errno != ENOENT && errno != ENOTDIR)
1551                 perror_with_name ("lstat: ", lpath);
1552               break;
1553             }
1554
1555           /* If this is not a symlink, we're done (we started with the real
1556              file's mtime so we don't need to test it again).  */
1557           if (!S_ISLNK (st.st_mode))
1558             break;
1559
1560           /* If this mtime is newer than what we had, keep the new one.  */
1561           ltime = FILE_TIMESTAMP_STAT_MODTIME (lpath, st);
1562           if (ltime > mtime)
1563             mtime = ltime;
1564
1565           /* Set up to check the file pointed to by this link.  */
1566           EINTRLOOP (llen, readlink (lpath, lbuf, GET_PATH_MAX));
1567           if (llen < 0)
1568             {
1569               /* Eh?  Just take what we have.  */
1570               perror_with_name ("readlink: ", lpath);
1571               break;
1572             }
1573           lbuf[llen] = '\0';
1574
1575           /* If the target is fully-qualified or the source is just a
1576              filename, then the new path is the target.  Otherwise it's the
1577              source directory plus the target.  */
1578           if (lbuf[0] == '/' || (p = strrchr (lpath, '/')) == NULL)
1579             strcpy (lpath, lbuf);
1580           else if ((p - lpath) + llen + 2 > GET_PATH_MAX)
1581             /* Eh?  Path too long!  Again, just go with what we have.  */
1582             break;
1583           else
1584             /* Create the next step in the symlink chain.  */
1585             strcpy (p+1, lbuf);
1586         }
1587     }
1588 #endif
1589
1590   return mtime;
1591 }
1592
1593
1594 /* Search for a library file specified as -lLIBNAME, searching for a
1595    suitable library file in the system library directories and the VPATH
1596    directories.  */
1597
1598 static const char *
1599 library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr)
1600 {
1601   static const char *dirs[] =
1602     {
1603 #ifndef _AMIGA
1604       "/lib",
1605       "/usr/lib",
1606 #endif
1607 #if defined(WINDOWS32) && !defined(LIBDIR)
1608 /*
1609  * This is completely up to the user at product install time. Just define
1610  * a placeholder.
1611  */
1612 #define LIBDIR "."
1613 #endif
1614       LIBDIR,                   /* Defined by configuration.  */
1615       0
1616     };
1617
1618   const char *file = 0;
1619   char *libpatterns;
1620   FILE_TIMESTAMP mtime;
1621
1622   /* Loop variables for the libpatterns value.  */
1623   char *p;
1624   const char *p2;
1625   size_t len;
1626   size_t liblen;
1627
1628   /* Information about the earliest (in the vpath sequence) match.  */
1629   unsigned int best_vpath = 0, best_path = 0;
1630
1631   const char **dp;
1632
1633   libpatterns = xstrdup (variable_expand ("$(.LIBPATTERNS)"));
1634
1635   /* Skip the '-l'.  */
1636   lib += 2;
1637   liblen = strlen (lib);
1638
1639   /* Loop through all the patterns in .LIBPATTERNS, and search on each one.
1640      To implement the linker-compatible behavior we have to search through
1641      all entries in .LIBPATTERNS and choose the "earliest" one.  */
1642   p2 = libpatterns;
1643   while ((p = find_next_token (&p2, &len)) != 0)
1644     {
1645       static char *buf = NULL;
1646       static size_t buflen = 0;
1647       static size_t libdir_maxlen = 0;
1648       static unsigned int std_dirs = 0;
1649       char *libbuf = variable_expand ("");
1650
1651       /* Expand the pattern using LIB as a replacement.  */
1652       {
1653         char c = p[len];
1654         char *p3, *p4;
1655
1656         p[len] = '\0';
1657         p3 = find_percent (p);
1658         if (!p3)
1659           {
1660             /* Give a warning if there is no pattern.  */
1661             OS (error, NILF,
1662                 _(".LIBPATTERNS element '%s' is not a pattern"), p);
1663             p[len] = c;
1664             continue;
1665           }
1666         p4 = variable_buffer_output (libbuf, p, p3-p);
1667         p4 = variable_buffer_output (p4, lib, liblen);
1668         p4 = variable_buffer_output (p4, p3+1, len - (p3-p));
1669         p[len] = c;
1670       }
1671
1672       /* Look first for 'libNAME.a' in the current directory.  */
1673       mtime = name_mtime (libbuf);
1674       if (mtime != NONEXISTENT_MTIME)
1675         {
1676           if (mtime_ptr != 0)
1677             *mtime_ptr = mtime;
1678           file = strcache_add (libbuf);
1679           /* This by definition will have the best index, so stop now.  */
1680           break;
1681         }
1682
1683       /* Now try VPATH search on that.  */
1684
1685       {
1686         unsigned int vpath_index, path_index;
1687         const char* f = vpath_search (libbuf, mtime_ptr ? &mtime : NULL,
1688                                       &vpath_index, &path_index);
1689         if (f)
1690           {
1691             /* If we have a better match, record it.  */
1692             if (file == 0 ||
1693                 vpath_index < best_vpath ||
1694                 (vpath_index == best_vpath && path_index < best_path))
1695               {
1696                 file = f;
1697                 best_vpath = vpath_index;
1698                 best_path = path_index;
1699
1700                 if (mtime_ptr != 0)
1701                   *mtime_ptr = mtime;
1702               }
1703           }
1704       }
1705
1706       /* Now try the standard set of directories.  */
1707
1708       if (!buflen)
1709         {
1710           for (dp = dirs; *dp != 0; ++dp)
1711             {
1712               size_t l = strlen (*dp);
1713               if (l > libdir_maxlen)
1714                 libdir_maxlen = l;
1715               std_dirs++;
1716             }
1717           buflen = strlen (libbuf);
1718           buf = xmalloc (libdir_maxlen + buflen + 2);
1719         }
1720       else if (buflen < strlen (libbuf))
1721         {
1722           buflen = strlen (libbuf);
1723           buf = xrealloc (buf, libdir_maxlen + buflen + 2);
1724         }
1725
1726       {
1727         /* Use the last std_dirs index for standard directories. This
1728            was it will always be greater than the VPATH index.  */
1729         unsigned int vpath_index = ~((unsigned int)0) - std_dirs;
1730
1731         for (dp = dirs; *dp != 0; ++dp)
1732           {
1733             sprintf (buf, "%s/%s", *dp, libbuf);
1734             mtime = name_mtime (buf);
1735             if (mtime != NONEXISTENT_MTIME)
1736               {
1737                 if (file == 0 || vpath_index < best_vpath)
1738                   {
1739                     file = strcache_add (buf);
1740                     best_vpath = vpath_index;
1741
1742                     if (mtime_ptr != 0)
1743                       *mtime_ptr = mtime;
1744                   }
1745               }
1746
1747             vpath_index++;
1748           }
1749       }
1750
1751     }
1752
1753   free (libpatterns);
1754   return file;
1755 }