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