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