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