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