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 #ifdef CONFIG_WITH_DOT_MUST_MAKE
68 static int call_must_make_target_var (struct file *file, unsigned int depth);
69 #endif
70 #ifdef CONFIG_WITH_DOT_IS_CHANGED
71 static int call_is_changed_target_var (struct file *file);
72 #endif
73 static int touch_file (struct file *file);
74 static void remake_file (struct file *file);
75 static FILE_TIMESTAMP name_mtime (const char *name);
76 static const char *library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr);
77 
78 
79 /* Remake all the goals in the `struct dep' chain GOALS.  Return -1 if nothing
80    was done, 0 if all goals were updated successfully, or 1 if a goal failed.
81 
82    If rebuilding_makefiles is nonzero, these goals are makefiles, so -t, -q,
83    and -n should be disabled for them unless they were also command-line
84    targets, and we should only make one goal at a time and return as soon as
85    one goal whose `changed' member is nonzero is successfully made.  */
86 
87 int
update_goal_chain(struct dep * goals)88 update_goal_chain (struct dep *goals)
89 {
90   int t = touch_flag, q = question_flag, n = just_print_flag;
91   int status = -1;
92 
93 #define	MTIME(file) (rebuilding_makefiles ? file_mtime_no_search (file) \
94 		     : file_mtime (file))
95 
96   /* Duplicate the chain so we can remove things from it.  */
97 
98   goals = copy_dep_chain (goals);
99 
100   {
101     /* Clear the `changed' flag of each goal in the chain.
102        We will use the flag below to notice when any commands
103        have actually been run for a target.  When no commands
104        have been run, we give an "up to date" diagnostic.  */
105 
106     struct dep *g;
107     for (g = goals; g != 0; g = g->next)
108       g->changed = 0;
109   }
110 
111   /* All files start with the considered bit 0, so the global value is 1.  */
112   considered = 1;
113 
114   /* Update all the goals until they are all finished.  */
115 
116   while (goals != 0)
117     {
118       register struct dep *g, *lastgoal;
119 
120       /* Start jobs that are waiting for the load to go down.  */
121 
122       start_waiting_jobs ();
123 
124       /* Wait for a child to die.  */
125 
126       reap_children (1, 0);
127 
128       lastgoal = 0;
129       g = goals;
130       while (g != 0)
131 	{
132 	  /* Iterate over all double-colon entries for this file.  */
133 	  struct file *file;
134 	  int stop = 0, any_not_updated = 0;
135 
136 	  for (file = g->file->double_colon ? g->file->double_colon : g->file;
137 	       file != NULL;
138 	       file = file->prev)
139 	    {
140 	      unsigned int ocommands_started;
141 	      int x;
142 
143               file->dontcare = g->dontcare;
144 
145 	      check_renamed (file);
146 	      if (rebuilding_makefiles)
147 		{
148 		  if (file->cmd_target)
149 		    {
150 		      touch_flag = t;
151 		      question_flag = q;
152 		      just_print_flag = n;
153 		    }
154 		  else
155 		    touch_flag = question_flag = just_print_flag = 0;
156 		}
157 
158 	      /* Save the old value of `commands_started' so we can compare
159 		 later.  It will be incremented when any commands are
160 		 actually run.  */
161 	      ocommands_started = commands_started;
162 
163 	      x = update_file (file, rebuilding_makefiles ? 1 : 0);
164 	      check_renamed (file);
165 
166 	      /* Set the goal's `changed' flag if any commands were started
167 		 by calling update_file above.  We check this flag below to
168 		 decide when to give an "up to date" diagnostic.  */
169               if (commands_started > ocommands_started)
170                 g->changed = 1;
171 
172               /* If we updated a file and STATUS was not already 1, set it to
173                  1 if updating failed, or to 0 if updating succeeded.  Leave
174                  STATUS as it is if no updating was done.  */
175 
176 	      stop = 0;
177 	      if ((x != 0 || file->updated) && status < 1)
178                 {
179                   if (file->update_status != 0)
180                     {
181                       /* Updating failed, or -q triggered.  The STATUS value
182                          tells our caller which.  */
183                       status = file->update_status;
184                       /* If -q just triggered, stop immediately.  It doesn't
185                          matter how much more we run, since we already know
186                          the answer to return.  */
187                       stop = (question_flag && !keep_going_flag
188                               && !rebuilding_makefiles);
189                     }
190                   else
191                     {
192                       FILE_TIMESTAMP mtime = MTIME (file);
193                       check_renamed (file);
194 
195                       if (file->updated && g->changed &&
196                            mtime != file->mtime_before_update)
197                         {
198                           /* Updating was done.  If this is a makefile and
199                              just_print_flag or question_flag is set (meaning
200                              -n or -q was given and this file was specified
201                              as a command-line target), don't change STATUS.
202                              If STATUS is changed, we will get re-exec'd, and
203                              enter an infinite loop.  */
204                           if (!rebuilding_makefiles
205                               || (!just_print_flag && !question_flag))
206                             status = 0;
207                           if (rebuilding_makefiles && file->dontcare)
208                             /* This is a default makefile; stop remaking.  */
209                             stop = 1;
210                         }
211                     }
212                 }
213 
214 	      /* Keep track if any double-colon entry is not finished.
215                  When they are all finished, the goal is finished.  */
216 	      any_not_updated |= !file->updated;
217 
218               file->dontcare = 0;
219 
220 	      if (stop)
221 		break;
222 	    }
223 
224 	  /* Reset FILE since it is null at the end of the loop.  */
225 	  file = g->file;
226 
227 	  if (stop || !any_not_updated)
228 	    {
229 	      /* If we have found nothing whatever to do for the goal,
230 		 print a message saying nothing needs doing.  */
231 
232 	      if (!rebuilding_makefiles
233 		  /* If the update_status is zero, we updated successfully
234 		     or not at all.  G->changed will have been set above if
235 		     any commands were actually started for this goal.  */
236 		  && file->update_status == 0 && !g->changed
237 		  /* Never give a message under -s or -q.  */
238 		  && !silent_flag && !question_flag)
239 		message (1, ((file->phony || file->cmds == 0)
240 			     ? _("Nothing to be done for `%s'.")
241 			     : _("`%s' is up to date.")),
242 			 file->name);
243 
244 	      /* This goal is finished.  Remove it from the chain.  */
245 	      if (lastgoal == 0)
246 		goals = g->next;
247 	      else
248 		lastgoal->next = g->next;
249 
250 	      /* Free the storage.  */
251 #ifndef CONFIG_WITH_ALLOC_CACHES
252 	      free (g);
253 #else
254               free_dep (g);
255 #endif
256 
257 	      g = lastgoal == 0 ? goals : lastgoal->next;
258 
259 	      if (stop)
260 		break;
261 	    }
262 	  else
263 	    {
264 	      lastgoal = g;
265 	      g = g->next;
266 	    }
267 	}
268 
269       /* If we reached the end of the dependency graph toggle the considered
270          flag for the next pass.  */
271       if (g == 0)
272         considered = !considered;
273     }
274 
275   if (rebuilding_makefiles)
276     {
277       touch_flag = t;
278       question_flag = q;
279       just_print_flag = n;
280     }
281 
282   return status;
283 }
284 
285 /* If FILE is not up to date, execute the commands for it.
286    Return 0 if successful, 1 if unsuccessful;
287    but with some flag settings, just call `exit' if unsuccessful.
288 
289    DEPTH is the depth in recursions of this function.
290    We increment it during the consideration of our dependencies,
291    then decrement it again after finding out whether this file
292    is out of date.
293 
294    If there are multiple double-colon entries for FILE,
295    each is considered in turn.  */
296 
297 static int
update_file(struct file * file,unsigned int depth)298 update_file (struct file *file, unsigned int depth)
299 {
300   register int status = 0;
301   register struct file *f;
302 
303   f = file->double_colon ? file->double_colon : file;
304 
305   /* Prune the dependency graph: if we've already been here on _this_
306      pass through the dependency graph, we don't have to go any further.
307      We won't reap_children until we start the next pass, so no state
308      change is possible below here until then.  */
309   if (f->considered == considered)
310     {
311       /* Check for the case where a target has been tried and failed but
312          the diagnostics hasn't been issued. If we need the diagnostics
313          then we will have to continue. */
314       if (!(f->updated && f->update_status > 0 && !f->dontcare && f->no_diag))
315         {
316           DBF (DB_VERBOSE, _("Pruning file `%s'.\n"));
317           return f->command_state == cs_finished ? f->update_status : 0;
318         }
319     }
320 
321   /* This loop runs until we start commands for a double colon rule, or until
322      the chain is exhausted. */
323   for (; f != 0; f = f->prev)
324     {
325       f->considered = considered;
326 
327       status |= update_file_1 (f, depth);
328       check_renamed (f);
329 
330       /* Clean up any alloca() used during the update.  */
331       alloca (0);
332 
333       /* If we got an error, don't bother with double_colon etc.  */
334       if (status != 0 && !keep_going_flag)
335         return status;
336 
337       if (f->command_state == cs_running
338           || f->command_state == cs_deps_running)
339         {
340 	  /* Don't run the other :: rules for this
341 	     file until this rule is finished.  */
342           status = 0;
343           break;
344         }
345     }
346 
347   /* Process the remaining rules in the double colon chain so they're marked
348      considered.  Start their prerequisites, too.  */
349   if (file->double_colon)
350     for (; f != 0 ; f = f->prev)
351       {
352         struct dep *d;
353 
354         f->considered = considered;
355 
356         for (d = f->deps; d != 0; d = d->next)
357           status |= update_file (d->file, depth + 1);
358       }
359 
360   return status;
361 }
362 
363 /* Show a message stating the target failed to build.  */
364 
365 static void
complain(struct file * file)366 complain (struct file *file)
367 {
368   const char *msg_noparent
369     = _("%sNo rule to make target `%s'%s");
370   const char *msg_parent
371     = _("%sNo rule to make target `%s', needed by `%s'%s");
372 
373   /* If this file has no_diag set then it means we tried to update it
374      before in the dontcare mode and failed. The target that actually
375      failed is not necessarily this file but could be one of its direct
376      or indirect dependencies. So traverse this file's dependencies and
377      find the one that actually caused the failure. */
378 
379   struct dep *d;
380 
381   for (d = file->deps; d != 0; d = d->next)
382     {
383       if (d->file->updated && d->file->update_status > 0 && file->no_diag)
384         {
385           complain (d->file);
386           break;
387         }
388     }
389 
390   if (d == 0)
391     {
392       /* Didn't find any dependencies to complain about. */
393 
394 #ifdef KMK
395       /* jokes */
396       if (!keep_going_flag && file->parent == 0)
397         {
398           const char *msg_joke = 0;
399           extern struct dep *goals;
400 
401           /* classics */
402           if (!strcmp (file->name, "fire")
403            || !strcmp (file->name, "Fire"))
404             msg_joke = "No matches.\n";
405           else if (!strcmp (file->name, "love")
406                 || !strcmp (file->name, "Love")
407                 || !strcmp (file->name, "peace")
408                 || !strcmp (file->name, "Peace"))
409             msg_joke = "Not war.\n";
410           else if (!strcmp (file->name, "war"))
411             msg_joke = "Don't know how to make war.\n";
412 
413           /* http://xkcd.com/149/ - GNU Make bug #23273. */
414           else if ((   !strcmp (file->name, "me")
415                     && goals != 0
416                     && !strcmp (dep_name(goals), "me")
417                     && goals->next != 0
418                     && !strcmp (dep_name(goals->next), "a")
419                     && goals->next->next != 0)
420                 || !strncmp (file->name, "me a ", 5))
421             msg_joke =
422 # ifdef HAVE_UNISTD_H
423                    getuid () == 0 ? "Okay.\n" :
424 # endif
425                        "What? Make it yourself!\n";
426           if (msg_joke)
427             {
428               fputs (msg_joke, stderr);
429               die (2);
430             }
431         }
432 #endif /* KMK */
433 
434       if (!keep_going_flag)
435         {
436           if (file->parent == 0)
437             fatal (NILF, msg_noparent, "", file->name, "");
438 
439           fatal (NILF, msg_parent, "", file->name, file->parent->name, "");
440         }
441 
442       if (file->parent == 0)
443         error (NILF, msg_noparent, "*** ", file->name, ".");
444       else
445         error (NILF, msg_parent, "*** ", file->name, file->parent->name, ".");
446 
447       file->no_diag = 0;
448     }
449 }
450 
451 /* Consider a single `struct file' and update it as appropriate.  */
452 
453 static int
update_file_1(struct file * file,unsigned int depth)454 update_file_1 (struct file *file, unsigned int depth)
455 {
456   FILE_TIMESTAMP this_mtime;
457   int noexist, must_make, deps_changed;
458   int dep_status = 0;
459   struct file *ofile;
460   struct dep *d, *ad;
461   struct dep amake;
462   int running = 0;
463 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
464   struct file *org_file;
465   struct file *req_file;
466   struct file *f2, *f3;
467 
468   /* Secondary target expansion leaves renamed files around, skip any rename
469      files to simplify multi target handling. */
470 
471   check_renamed(file);
472 
473   /* Remember the request file and find the primary multi target file. Always
474      work on the primary file in a multi target recipe.  */
475 
476   req_file = file;
477   org_file = file;
478   if (file->multi_head != NULL)
479     {
480       if (file->multi_head == file)
481         DBS (DB_VERBOSE, (_("Considering target file `%s'  (multi head).\n"), file->name));
482       else
483         {
484           org_file = file = file->multi_head;
485           DBS (DB_VERBOSE, (_("Considering target file `%s' -> multi head `%s'.\n"),
486                               req_file->name, file->name));
487           assert (file->multi_head == file);
488         }
489     }
490   else
491 #endif /* CONFIG_WITH_EXPLICIT_MULTITARGET */
492     DBF (DB_VERBOSE, _("Considering target file `%s'.\n"));
493 
494   if (file->updated)
495     {
496       if (file->update_status > 0)
497 	{
498 	  DBF (DB_VERBOSE,
499                _("Recently tried and failed to update file `%s'.\n"));
500 
501           /* If the file we tried to make is marked no_diag then no message
502              was printed about it when it failed during the makefile rebuild.
503              If we're trying to build it again in the normal rebuild, print a
504              message now.  */
505           if (file->no_diag && !file->dontcare)
506               complain (file);
507 
508 	  return file->update_status;
509 	}
510 
511       DBF (DB_VERBOSE, _("File `%s' was considered already.\n"));
512       return 0;
513     }
514 
515   switch (file->command_state)
516     {
517     case cs_not_started:
518     case cs_deps_running:
519       break;
520     case cs_running:
521       DBF (DB_VERBOSE, _("Still updating file `%s'.\n"));
522       return 0;
523     case cs_finished:
524       DBF (DB_VERBOSE, _("Finished updating file `%s'.\n"));
525       return file->update_status;
526     default:
527       abort ();
528     }
529 
530   /* Determine whether the diagnostics will be issued should this update
531      fail. */
532   file->no_diag = file->dontcare;
533 
534   ++depth;
535 
536   /* Notice recursive update of the same file.  */
537   start_updating (file);
538 
539   /* We might change file if we find a different one via vpath;
540      remember this one to turn off updating.  */
541   ofile = file;
542 
543   /* Looking at the file's modtime beforehand allows the possibility
544      that its name may be changed by a VPATH search, and thus it may
545      not need an implicit rule.  If this were not done, the file
546      might get implicit commands that apply to its initial name, only
547      to have that name replaced with another found by VPATH search.
548 
549      For multi target files check the other files and use the time
550      of the oldest / non-existing file. */
551 
552 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
553   this_mtime = file_mtime (file);
554   check_renamed (file);
555   f3 = file;
556   for (f2 = file->multi_next;
557        f2 != NULL && this_mtime != NONEXISTENT_MTIME;
558        f2 = f2->multi_next)
559     if (!f2->multi_maybe)
560       {
561         FILE_TIMESTAMP second_mtime = file_mtime (f2);
562         if (second_mtime < this_mtime)
563           {
564             this_mtime = second_mtime;
565             f3 = f2;
566           }
567       }
568     /** @todo this isn't sufficient, need to introduce a truly optional type and
569      *        make |+ ignore mtime. let's hope that doesn't break too much... */
570     /* If the requested file doesn't exist, always do a remake in the
571        hope that it is recreated even if it's "maybe" target. */
572     else if (f2 == req_file && file_mtime (f2) == NONEXISTENT_MTIME)
573       {
574         this_mtime = NONEXISTENT_MTIME;
575         f3 = f2;
576         break;
577       }
578   check_renamed (f3);
579   noexist = this_mtime == NONEXISTENT_MTIME;
580   if (noexist)
581     DBS (DB_BASIC, (_("File `%s' does not exist.\n"), f3->name));
582 #else /* !CONFIG_WITH_EXPLICIT_MULTITARGET */
583   this_mtime = file_mtime (file);
584   check_renamed (file);
585   noexist = this_mtime == NONEXISTENT_MTIME;
586   if (noexist)
587     DBF (DB_BASIC, _("File `%s' does not exist.\n"));
588 #endif /* !CONFIG_WITH_EXPLICIT_MULTITARGET */
589   else if (ORDINARY_MTIME_MIN <= this_mtime && this_mtime <= ORDINARY_MTIME_MAX
590 	   && file->low_resolution_time)
591     {
592       /* Avoid spurious rebuilds due to low resolution time stamps.  */
593       int ns = FILE_TIMESTAMP_NS (this_mtime);
594       if (ns != 0)
595 	error (NILF, _("*** Warning: .LOW_RESOLUTION_TIME file `%s' has a high resolution time stamp"),
596 	       file->name);
597       this_mtime += FILE_TIMESTAMPS_PER_S - 1 - ns;
598     }
599 
600   must_make = noexist;
601 
602   /* If file was specified as a target with no commands,
603      come up with some default commands.  */
604 
605   if (!file->phony && file->cmds == 0 && !file->tried_implicit)
606     {
607       if (try_implicit_rule (file, depth))
608 	DBF (DB_IMPLICIT, _("Found an implicit rule for `%s'.\n"));
609       else
610 	DBF (DB_IMPLICIT, _("No implicit rule found for `%s'.\n"));
611       file->tried_implicit = 1;
612     }
613   if (file->cmds == 0 && !file->is_target
614       && default_file != 0 && default_file->cmds != 0)
615     {
616       DBF (DB_IMPLICIT, _("Using default recipe for `%s'.\n"));
617       file->cmds = default_file->cmds;
618     }
619 
620   /* Update all non-intermediate files we depend on, if necessary, and see
621      whether any of them is more recent than this file.  We need to walk our
622      deps, AND the deps of any also_make targets to ensure everything happens
623      in the correct order.
624 
625      bird: For explicit multitarget rules we must iterate all the output
626      files to get the correct picture.  The special .MUST_MAKE
627      target variable call is also done from this context. */
628 
629 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
630  assert (file == org_file);
631  for (f2 = file; f2; file = f2 = f2->multi_next)
632  {
633 #endif
634   amake.file = file;
635   amake.next = file->also_make;
636   ad = &amake;
637   while (ad)
638     {
639       struct dep *lastd = 0;
640 
641       /* Find the deps we're scanning */
642       d = ad->file->deps;
643       ad = ad->next;
644 
645       while (d)
646         {
647           FILE_TIMESTAMP mtime;
648           int maybe_make;
649           int dontcare = 0;
650 
651           check_renamed (d->file);
652 
653           mtime = file_mtime (d->file);
654           check_renamed (d->file);
655 
656           if (is_updating (d->file))
657             {
658 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
659               /* silently ignore the order-only dep hack. */
660               if (file->multi_maybe && d->file == org_file)
661                 {
662                   lastd = d;
663                   d = d->next;
664                   continue;
665                 }
666 #endif
667 
668               error (NILF, _("Circular %s <- %s dependency dropped."),
669                      file->name, d->file->name);
670               /* We cannot free D here because our the caller will still have
671                  a reference to it when we were called recursively via
672                  check_dep below.  */
673               if (lastd == 0)
674                 file->deps = d->next;
675               else
676                 lastd->next = d->next;
677               d = d->next;
678               continue;
679             }
680 
681           d->file->parent = file;
682           maybe_make = must_make;
683 
684           /* Inherit dontcare flag from our parent. */
685           if (rebuilding_makefiles)
686             {
687               dontcare = d->file->dontcare;
688               d->file->dontcare = file->dontcare;
689             }
690 
691           dep_status |= check_dep (d->file, depth, this_mtime, &maybe_make);
692 
693           /* Restore original dontcare flag. */
694           if (rebuilding_makefiles)
695             d->file->dontcare = dontcare;
696 
697           if (! d->ignore_mtime)
698             must_make = maybe_make;
699 
700           check_renamed (d->file);
701 
702           {
703             register struct file *f = d->file;
704             if (f->double_colon)
705               f = f->double_colon;
706             do
707               {
708                 running |= (f->command_state == cs_running
709                             || f->command_state == cs_deps_running);
710                 f = f->prev;
711               }
712             while (f != 0);
713           }
714 
715           if (dep_status != 0 && !keep_going_flag)
716             break;
717 
718           if (!running)
719             /* The prereq is considered changed if the timestamp has changed while
720                it was built, OR it doesn't exist.  */
721             d->changed = ((file_mtime (d->file) != mtime)
722                           || (mtime == NONEXISTENT_MTIME));
723 
724           lastd = d;
725           d = d->next;
726         }
727     }
728 
729 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
730     if (dep_status != 0 && !keep_going_flag)
731       break;
732   }
733   file = org_file;
734 #endif
735 
736 #ifdef CONFIG_WITH_DOT_MUST_MAKE
737   /* Check with the .MUST_MAKE target variable if it's
738      not already decided to make the file.  */
739 
740 # ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
741   if (!must_make)
742     for (f2 = org_file; f2 && !must_make; f2 = f2->multi_next)
743       must_make = call_must_make_target_var (f2, depth);
744 # else
745   if (!must_make)
746     must_make = call_must_make_target_var (file, depth);
747 # endif
748 #endif /* CONFIG_WITH_DOT_MUST_MAKE */
749 
750   /* Now we know whether this target needs updating.
751      If it does, update all the intermediate files we depend on.  */
752 
753   if (must_make || always_make_flag)
754     {
755 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
756       for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
757 #endif
758         for (d = file->deps; d != 0; d = d->next)
759           if (d->file->intermediate)
760             {
761               int dontcare = 0;
762 
763               FILE_TIMESTAMP mtime = file_mtime (d->file);
764               check_renamed (d->file);
765               d->file->parent = file;
766 
767               /* Inherit dontcare flag from our parent. */
768               if (rebuilding_makefiles)
769                 {
770                   dontcare = d->file->dontcare;
771                   d->file->dontcare = file->dontcare;
772                 }
773 
774 
775               dep_status |= update_file (d->file, depth);
776 
777               /* Restore original dontcare flag. */
778               if (rebuilding_makefiles)
779                 d->file->dontcare = dontcare;
780 
781               check_renamed (d->file);
782 
783               {
784                 register struct file *f = d->file;
785                 if (f->double_colon)
786           	f = f->double_colon;
787                 do
788           	{
789           	  running |= (f->command_state == cs_running
790           	              || f->command_state == cs_deps_running);
791           	  f = f->prev;
792           	}
793                 while (f != 0);
794               }
795 
796               if (dep_status != 0 && !keep_going_flag)
797                 break;
798 
799               if (!running)
800                 d->changed = ((file->phony && file->cmds != 0)
801           	            || file_mtime (d->file) != mtime);
802             }
803 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
804       file = org_file;
805 #endif
806     }
807 
808   finish_updating (file);
809   finish_updating (ofile);
810 
811   DBF (DB_VERBOSE, _("Finished prerequisites of target file `%s'.\n"));
812 
813   if (running)
814     {
815       set_command_state (file, cs_deps_running);
816       --depth;
817       DBF (DB_VERBOSE, _("The prerequisites of `%s' are being made.\n"));
818       return 0;
819     }
820 
821   /* If any dependency failed, give up now.  */
822 
823   if (dep_status != 0)
824     {
825       file->update_status = dep_status;
826       notice_finished_file (file);
827 
828       --depth;
829 
830       DBF (DB_VERBOSE, _("Giving up on target file `%s'.\n"));
831 
832       if (depth == 0 && keep_going_flag
833 	  && !just_print_flag && !question_flag)
834 	error (NILF,
835                _("Target `%s' not remade because of errors."), file->name);
836 
837       return dep_status;
838     }
839 
840   if (file->command_state == cs_deps_running)
841     /* The commands for some deps were running on the last iteration, but
842        they have finished now.  Reset the command_state to not_started to
843        simplify later bookkeeping.  It is important that we do this only
844        when the prior state was cs_deps_running, because that prior state
845        was definitely propagated to FILE's also_make's by set_command_state
846        (called above), but in another state an also_make may have
847        independently changed to finished state, and we would confuse that
848        file's bookkeeping (updated, but not_started is bogus state).  */
849     set_command_state (file, cs_not_started);
850 
851   /* Now record which prerequisites are more
852      recent than this file, so we can define $?.  */
853 
854   deps_changed = 0;
855 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
856   for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
857 #endif
858     for (d = file->deps; d != 0; d = d->next)
859       {
860         FILE_TIMESTAMP d_mtime = file_mtime (d->file);
861 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
862         if (d->file == file && file->multi_maybe)
863           continue;
864 #endif
865         check_renamed (d->file);
866 
867         if (! d->ignore_mtime)
868           {
869 #if 1
870             /* %%% In version 4, remove this code completely to
871              implement not remaking deps if their deps are newer
872              than their parents.  */
873             if (d_mtime == NONEXISTENT_MTIME && !d->file->intermediate)
874               /* We must remake if this dep does not
875                  exist and is not intermediate.  */
876               must_make = 1;
877 #endif
878 
879             /* Set DEPS_CHANGED if this dep actually changed.  */
880             deps_changed |= d->changed;
881           }
882 
883         /* Set D->changed if either this dep actually changed,
884            or its dependent, FILE, is older or does not exist.  */
885         d->changed |= noexist || d_mtime > this_mtime;
886 
887         if (!noexist && ISDB (DB_BASIC|DB_VERBOSE))
888           {
889             const char *fmt = 0;
890 
891             if (d->ignore_mtime)
892               {
893                 if (ISDB (DB_VERBOSE))
894                   fmt = _("Prerequisite `%s' is order-only for target `%s'.\n");
895               }
896             else if (d_mtime == NONEXISTENT_MTIME)
897               {
898                 if (ISDB (DB_BASIC))
899                   fmt = _("Prerequisite `%s' of target `%s' does not exist.\n");
900               }
901             else if (d->changed)
902               {
903                 if (ISDB (DB_BASIC))
904                   fmt = _("Prerequisite `%s' is newer than target `%s'.\n");
905               }
906             else if (ISDB (DB_VERBOSE))
907               fmt = _("Prerequisite `%s' is older than target `%s'.\n");
908 
909             if (fmt)
910               {
911                 print_spaces (depth);
912                 printf (fmt, dep_name (d), file->name);
913                 fflush (stdout);
914               }
915           }
916       }
917 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
918   file = org_file;
919 #endif
920 
921   /* Here depth returns to the value it had when we were called.  */
922   depth--;
923 
924   if (file->double_colon && file->deps == 0)
925     {
926       must_make = 1;
927       DBF (DB_BASIC,
928            _("Target `%s' is double-colon and has no prerequisites.\n"));
929     }
930   else if (!noexist && file->is_target && !deps_changed && file->cmds == 0
931            && !always_make_flag)
932     {
933       must_make = 0;
934       DBF (DB_VERBOSE,
935            _("No recipe for `%s' and no prerequisites actually changed.\n"));
936     }
937   else if (!must_make && file->cmds != 0 && always_make_flag)
938     {
939       must_make = 1;
940       DBF (DB_VERBOSE, _("Making `%s' due to always-make flag.\n"));
941     }
942 
943   if (!must_make)
944     {
945       if (ISDB (DB_VERBOSE))
946         {
947           print_spaces (depth);
948           printf (_("No need to remake target `%s'"), file->name);
949           if (!streq (file->name, file->hname))
950               printf (_("; using VPATH name `%s'"), file->hname);
951           puts (".");
952           fflush (stdout);
953         }
954 
955       notice_finished_file (file);
956 
957       /* Since we don't need to remake the file, convert it to use the
958          VPATH filename if we found one.  hfile will be either the
959          local name if no VPATH or the VPATH name if one was found.  */
960 
961       while (file)
962         {
963           file->name = file->hname;
964           file = file->prev;
965         }
966 
967       return 0;
968     }
969 
970   DBF (DB_BASIC, _("Must remake target `%s'.\n"));
971 
972   /* It needs to be remade.  If it's VPATH and not reset via GPATH, toss the
973      VPATH.  */
974   if (!streq(file->name, file->hname))
975     {
976       DB (DB_BASIC, (_("  Ignoring VPATH name `%s'.\n"), file->hname));
977       file->ignore_vpath = 1;
978     }
979 
980   /* Now, take appropriate actions to remake the file.  */
981   remake_file (file);
982 
983   if (file->command_state != cs_finished)
984     {
985       DBF (DB_VERBOSE, _("Recipe of `%s' is being run.\n"));
986       return 0;
987     }
988 
989   switch (file->update_status)
990     {
991     case 2:
992       DBF (DB_BASIC, _("Failed to remake target file `%s'.\n"));
993       break;
994     case 0:
995       DBF (DB_BASIC, _("Successfully remade target file `%s'.\n"));
996       break;
997     case 1:
998       DBF (DB_BASIC, _("Target file `%s' needs remade under -q.\n"));
999       break;
1000     default:
1001       assert (file->update_status >= 0 && file->update_status <= 2);
1002       break;
1003     }
1004 
1005   file->updated = 1;
1006   return file->update_status;
1007 }
1008 #ifdef CONFIG_WITH_DOT_MUST_MAKE
1009 
1010 /* Consider the .MUST_MAKE target variable if present.
1011 
1012    Returns 1 if must remake, 0 if not.
1013 
1014    The deal is that .MUST_MAKE returns non-zero if it thinks the target needs
1015    updating.  We have to initialize file variables (for the sake of pattern
1016    vars) and set the most important file variables before calling (expanding)
1017    the .MUST_MAKE variable.
1018 
1019    The file variables keeping the dependency lists, $+, $^, $? and $| are not
1020    available at this point because $? depends on things happening after we've
1021    decided to make the file.  So, to keep things simple all 4 of them are
1022    undefined in this call.  */
1023 static int
call_must_make_target_var(struct file * file,unsigned int depth)1024 call_must_make_target_var (struct file *file, unsigned int depth)
1025 {
1026   struct variable *var;
1027   unsigned char ch;
1028   const char *str;
1029 
1030   if (file->variables)
1031     {
1032       var = lookup_variable_in_set (".MUST_MAKE", sizeof (".MUST_MAKE") - 1,
1033                                     file->variables->set);
1034       if (var)
1035         {
1036           initialize_file_variables (file, 0);
1037           set_file_variables (file, 1 /* called early, no dep lists please */);
1038 
1039           str = variable_expand_for_file_2 (NULL,
1040                                             var->value, var->value_length,
1041                                             file, NULL);
1042 
1043           /* Stripped string should be non-zero.  */
1044 
1045           ch = *str;
1046           while (isspace (ch))
1047             ch = *++str;
1048 
1049           if (ch != '\0')
1050             {
1051               if (ISDB (DB_BASIC))
1052                 {
1053                   print_spaces (depth);
1054                   printf (_(".MUST_MAKE returned `%s' for target `%s'.\n"),
1055                           str, file->name);
1056                 }
1057               return 1;
1058             }
1059         }
1060     }
1061   return 0;
1062 }
1063 #endif /* CONFIG_WITH_DOT_MUST_MAKE */
1064 #ifdef CONFIG_WITH_DOT_IS_CHANGED
1065 
1066 /* Consider the .IS_CHANGED target variable if present.
1067 
1068    Returns 1 if the file should be considered modified, 0 if not.
1069 
1070    The calling context and restrictions are the same as for .MUST_MAKE.
1071    Make uses the information from this 'function' for determining whether to
1072    make a file which lists this as a prerequisite.  So, this is the feature you
1073    use to check MD5 sums, file sizes, time stamps and the like with data from
1074    a previous run.
1075 
1076    FIXME: Would be nice to know which file is currently being considered.
1077    FIXME: Is currently not invoked for intermediate files.  */
1078 static int
call_is_changed_target_var(struct file * file)1079 call_is_changed_target_var (struct file *file)
1080 {
1081   struct variable *var;
1082   unsigned char ch;
1083   const char *str;
1084 
1085   if (file->variables)
1086     {
1087       var = lookup_variable_in_set (".IS_CHANGED", sizeof (".IS_CHANGED") - 1,
1088                                     file->variables->set);
1089       if (var)
1090         {
1091           initialize_file_variables (file, 0);
1092           set_file_variables (file, 1 /* called early, no dep lists please */);
1093 
1094           str = variable_expand_for_file_2 (NULL,
1095                                             var->value, var->value_length,
1096                                             file, NULL);
1097 
1098           /* stripped string should be non-zero.  */
1099           do
1100             ch = *str++;
1101           while (isspace (ch));
1102 
1103           return (ch != '\0');
1104         }
1105     }
1106   return 0;
1107 }
1108 #endif /* CONFIG_WITH_DOT_IS_CHANGED */
1109 
1110 /* Set FILE's `updated' flag and re-check its mtime and the mtime's of all
1111    files listed in its `also_make' member.  Under -t, this function also
1112    touches FILE.
1113 
1114    On return, FILE->update_status will no longer be -1 if it was.  */
1115 
1116 void
notice_finished_file(struct file * file)1117 notice_finished_file (struct file *file)
1118 {
1119 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1120   struct file *f2;
1121 #endif
1122   struct dep *d;
1123   int ran = file->command_state == cs_running;
1124   int touched = 0;
1125   DB (DB_JOBS, (_("notice_finished_file - entering: file=%p `%s' update_status=%d command_state=%d\n"), /* bird */
1126                   (void *) file, file->name, file->update_status, file->command_state));
1127 
1128   file->command_state = cs_finished;
1129   file->updated = 1;
1130 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1131   if (file->multi_head)
1132     {
1133       assert (file == file->multi_head);
1134       for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1135         {
1136           f2->command_state = cs_finished;
1137           f2->updated = 1;
1138         }
1139     }
1140 #endif
1141 
1142 #ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
1143   /* update not_parallel if the file was flagged for that. */
1144   if (   ran
1145       && (file->command_flags & (COMMANDS_NOTPARALLEL | COMMANDS_NO_COMMANDS))
1146          == COMMANDS_NOTPARALLEL)
1147     {
1148       DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s') [notice_finished_file]\n"), not_parallel,
1149                    not_parallel - 1, (void *) file, file->name));
1150       assert(not_parallel >= 1);
1151       --not_parallel;
1152     }
1153 #endif
1154 
1155   if (touch_flag
1156       /* The update status will be:
1157 		-1	if this target was not remade;
1158 		0	if 0 or more commands (+ or ${MAKE}) were run and won;
1159 		1	if some commands were run and lost.
1160 	 We touch the target if it has commands which either were not run
1161 	 or won when they ran (i.e. status is 0).  */
1162       && file->update_status == 0)
1163     {
1164       if (file->cmds != 0 && file->cmds->any_recurse)
1165 	{
1166 	  /* If all the command lines were recursive,
1167 	     we don't want to do the touching.  */
1168 	  unsigned int i;
1169 	  for (i = 0; i < file->cmds->ncommand_lines; ++i)
1170 	    if (!(file->cmds->lines_flags[i] & COMMANDS_RECURSE))
1171 	      goto have_nonrecursing;
1172 	}
1173       else
1174 	{
1175 	have_nonrecursing:
1176 	  if (file->phony)
1177 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1178             {
1179               file->update_status = 0;
1180               if (file->multi_head)
1181                 for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1182                   f2->update_status = 0;
1183             }
1184 #else
1185 	    file->update_status = 0;
1186 #endif
1187           /* According to POSIX, -t doesn't affect targets with no cmds.  */
1188 	  else if (file->cmds != 0)
1189             {
1190               /* Should set file's modification date and do nothing else.  */
1191               file->update_status = touch_file (file);
1192 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1193               if (file->multi_head)
1194                 for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1195                   {
1196                     /* figure out this, touch if it exist ignore otherwise? */
1197                   }
1198 #endif
1199 
1200               /* Pretend we ran a real touch command, to suppress the
1201                  "`foo' is up to date" message.  */
1202               commands_started++;
1203 
1204               /* Request for the timestamp to be updated (and distributed
1205                  to the double-colon entries). Simply setting ran=1 would
1206                  almost have done the trick, but messes up with the also_make
1207                  updating logic below.  */
1208               touched = 1;
1209             }
1210 	}
1211     }
1212 
1213   if (file->mtime_before_update == UNKNOWN_MTIME)
1214     file->mtime_before_update = file->last_mtime;
1215 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1216   if (file->multi_head)
1217     for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1218       if (f2->mtime_before_update == UNKNOWN_MTIME)
1219         f2->mtime_before_update = f2->last_mtime;
1220 #endif
1221 
1222   if ((ran && !file->phony) || touched)
1223     {
1224       int i = 0;
1225 
1226       /* If -n, -t, or -q and all the commands are recursive, we ran them so
1227          really check the target's mtime again.  Otherwise, assume the target
1228          would have been updated. */
1229 
1230       if ((question_flag || just_print_flag || touch_flag) && file->cmds)
1231         {
1232           for (i = file->cmds->ncommand_lines; i > 0; --i)
1233             if (! (file->cmds->lines_flags[i-1] & COMMANDS_RECURSE))
1234               break;
1235         }
1236 
1237       /* If there were no commands at all, it's always new. */
1238 
1239       else if (file->is_target && file->cmds == 0)
1240 	i = 1;
1241 
1242       file->last_mtime = i == 0 ? UNKNOWN_MTIME : NEW_MTIME;
1243 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1244       if (file->multi_head)
1245         for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1246           file->last_mtime = i == 0 ? UNKNOWN_MTIME : NEW_MTIME; /*??*/
1247 #endif
1248     }
1249 
1250   if (file->double_colon)
1251     {
1252       /* If this is a double colon rule and it is the last one to be
1253          updated, propagate the change of modification time to all the
1254          double-colon entries for this file.
1255 
1256          We do it on the last update because it is important to handle
1257          individual entries as separate rules with separate timestamps
1258          while they are treated as targets and then as one rule with the
1259          unified timestamp when they are considered as a prerequisite
1260          of some target.  */
1261 
1262       struct file *f;
1263       FILE_TIMESTAMP max_mtime = file->last_mtime;
1264 
1265       /* Check that all rules were updated and at the same time find
1266          the max timestamp.  We assume UNKNOWN_MTIME is newer then
1267          any other value.  */
1268       for (f = file->double_colon; f != 0 && f->updated; f = f->prev)
1269         if (max_mtime != UNKNOWN_MTIME
1270             && (f->last_mtime == UNKNOWN_MTIME || f->last_mtime > max_mtime))
1271           max_mtime = f->last_mtime;
1272 
1273       if (f == 0)
1274         for (f = file->double_colon; f != 0; f = f->prev)
1275           f->last_mtime = max_mtime;
1276     }
1277 
1278   if (ran && file->update_status != -1)
1279 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1280     {
1281 #endif
1282       /* We actually tried to update FILE, which has
1283          updated its also_make's as well (if it worked).
1284          If it didn't work, it wouldn't work again for them.
1285          So mark them as updated with the same status.  */
1286       for (d = file->also_make; d != 0; d = d->next)
1287         {
1288           d->file->command_state = cs_finished;
1289           d->file->updated = 1;
1290           d->file->update_status = file->update_status;
1291 
1292           if (ran && !d->file->phony)
1293             /* Fetch the new modification time.
1294                We do this instead of just invalidating the cached time
1295                so that a vpath_search can happen.  Otherwise, it would
1296                never be done because the target is already updated.  */
1297             f_mtime (d->file, 0);
1298         }
1299 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1300       /* Same as above but for explicit multi target rules. */
1301       if (file->multi_head)
1302         for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1303           {
1304             f2->update_status = file->update_status;
1305             if (!f2->phony)
1306               f_mtime (f2, 0);
1307           }
1308     }
1309 #endif
1310   else if (file->update_status == -1)
1311 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1312     {
1313       /* Nothing was done for FILE, but it needed nothing done.
1314          So mark it now as "succeeded".  */
1315       file->update_status = 0;
1316       if (file->multi_head)
1317         for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
1318           f2->update_status = 0;
1319     }
1320 #else
1321     /* Nothing was done for FILE, but it needed nothing done.
1322        So mark it now as "succeeded".  */
1323     file->update_status = 0;
1324 #endif
1325 
1326 #ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
1327     /* We're done with this command, so free the memory held by the chopped
1328        command lines. Saves heap for the compilers & linkers. */
1329     if (file->cmds && file->cmds->command_lines)
1330       free_chopped_commands (file->cmds);
1331 #endif
1332 }
1333 
1334 /* Check whether another file (whose mtime is THIS_MTIME) needs updating on
1335    account of a dependency which is file FILE.  If it does, store 1 in
1336    *MUST_MAKE_PTR.  In the process, update any non-intermediate files that
1337    FILE depends on (including FILE itself).  Return nonzero if any updating
1338    failed.  */
1339 
1340 static int
check_dep(struct file * file,unsigned int depth,FILE_TIMESTAMP this_mtime,int * must_make_ptr)1341 check_dep (struct file *file, unsigned int depth,
1342            FILE_TIMESTAMP this_mtime, int *must_make_ptr)
1343 {
1344   struct file *ofile;
1345   struct dep *d;
1346   int dep_status = 0;
1347 
1348   ++depth;
1349   start_updating (file);
1350 
1351   /* We might change file if we find a different one via vpath;
1352      remember this one to turn off updating.  */
1353   ofile = file;
1354 
1355   if (file->phony || !file->intermediate)
1356     {
1357       /* If this is a non-intermediate file, update it and record whether it
1358          is newer than THIS_MTIME.  */
1359       FILE_TIMESTAMP mtime;
1360       dep_status = update_file (file, depth);
1361       check_renamed (file);
1362       mtime = file_mtime (file);
1363       check_renamed (file);
1364       if (mtime == NONEXISTENT_MTIME || mtime > this_mtime)
1365 	*must_make_ptr = 1;
1366 #ifdef CONFIG_WITH_DOT_IS_CHANGED
1367       else if (   *must_make_ptr == 0
1368                && call_is_changed_target_var (file))
1369         *must_make_ptr = 1;
1370 #endif /* CONFIG_WITH_DOT_IS_CHANGED */
1371     }
1372   else
1373     {
1374       /* FILE is an intermediate file.  */
1375       FILE_TIMESTAMP mtime;
1376 
1377       if (!file->phony && file->cmds == 0 && !file->tried_implicit)
1378 	{
1379 	  if (try_implicit_rule (file, depth))
1380 	    DBF (DB_IMPLICIT, _("Found an implicit rule for `%s'.\n"));
1381 	  else
1382 	    DBF (DB_IMPLICIT, _("No implicit rule found for `%s'.\n"));
1383 	  file->tried_implicit = 1;
1384 	}
1385       if (file->cmds == 0 && !file->is_target
1386 	  && default_file != 0 && default_file->cmds != 0)
1387 	{
1388 	  DBF (DB_IMPLICIT, _("Using default commands for `%s'.\n"));
1389 	  file->cmds = default_file->cmds;
1390 	}
1391 
1392       check_renamed (file);
1393       mtime = file_mtime (file);
1394       check_renamed (file);
1395       if (mtime != NONEXISTENT_MTIME && mtime > this_mtime)
1396         /* If the intermediate file actually exists and is newer, then we
1397            should remake from it.  */
1398 	*must_make_ptr = 1;
1399       else
1400 	{
1401           /* Otherwise, update all non-intermediate files we depend on, if
1402              necessary, and see whether any of them is more recent than the
1403              file on whose behalf we are checking.  */
1404 	  struct dep *ld;
1405           int deps_running = 0;
1406 
1407           /* If this target is not running, set it's state so that we check it
1408              fresh.  It could be it was checked as part of an order-only
1409              prerequisite and so wasn't rebuilt then, but should be now.  */
1410           if (file->command_state != cs_running)
1411             set_command_state (file, cs_not_started);
1412 
1413 	  ld = 0;
1414 	  d = file->deps;
1415 	  while (d != 0)
1416 	    {
1417               int maybe_make;
1418 
1419 	      if (is_updating (d->file))
1420 		{
1421 		  error (NILF, _("Circular %s <- %s dependency dropped."),
1422 			 file->name, d->file->name);
1423 		  if (ld == 0)
1424 		    {
1425 		      file->deps = d->next;
1426                       free_dep (d);
1427 		      d = file->deps;
1428 		    }
1429 		  else
1430 		    {
1431 		      ld->next = d->next;
1432                       free_dep (d);
1433 		      d = ld->next;
1434 		    }
1435 		  continue;
1436 		}
1437 
1438 	      d->file->parent = file;
1439               maybe_make = *must_make_ptr;
1440 	      dep_status |= check_dep (d->file, depth, this_mtime,
1441                                        &maybe_make);
1442               if (! d->ignore_mtime)
1443                 *must_make_ptr = maybe_make;
1444 	      check_renamed (d->file);
1445 	      if (dep_status != 0 && !keep_going_flag)
1446 		break;
1447 
1448 	      if (d->file->command_state == cs_running
1449 		  || d->file->command_state == cs_deps_running)
1450 		deps_running = 1;
1451 
1452 	      ld = d;
1453 	      d = d->next;
1454 	    }
1455 
1456           if (deps_running)
1457             /* Record that some of FILE's deps are still being made.
1458                This tells the upper levels to wait on processing it until the
1459                commands are finished.  */
1460             set_command_state (file, cs_deps_running);
1461 	}
1462     }
1463 
1464   finish_updating (file);
1465   finish_updating (ofile);
1466 
1467   return dep_status;
1468 }
1469 
1470 /* Touch FILE.  Return zero if successful, one if not.  */
1471 
1472 #define TOUCH_ERROR(call) return (perror_with_name (call, file->name), 1)
1473 
1474 static int
touch_file(struct file * file)1475 touch_file (struct file *file)
1476 {
1477   if (!silent_flag)
1478     message (0, "touch %s", file->name);
1479 
1480 #ifndef	NO_ARCHIVES
1481   if (ar_name (file->name))
1482     return ar_touch (file->name);
1483   else
1484 #endif
1485     {
1486       int fd = open (file->name, O_RDWR | O_CREAT, 0666);
1487 
1488       if (fd < 0)
1489 	TOUCH_ERROR ("touch: open: ");
1490       else
1491 	{
1492 	  struct stat statbuf;
1493 	  char buf = 'x';
1494           int e;
1495 
1496           EINTRLOOP (e, fstat (fd, &statbuf));
1497 	  if (e < 0)
1498 	    TOUCH_ERROR ("touch: fstat: ");
1499 	  /* Rewrite character 0 same as it already is.  */
1500 	  if (read (fd, &buf, 1) < 0)
1501 	    TOUCH_ERROR ("touch: read: ");
1502 	  if (lseek (fd, 0L, 0) < 0L)
1503 	    TOUCH_ERROR ("touch: lseek: ");
1504 	  if (write (fd, &buf, 1) < 0)
1505 	    TOUCH_ERROR ("touch: write: ");
1506 	  /* If file length was 0, we just
1507 	     changed it, so change it back.  */
1508 	  if (statbuf.st_size == 0)
1509 	    {
1510 	      (void) close (fd);
1511 	      fd = open (file->name, O_RDWR | O_TRUNC, 0666);
1512 	      if (fd < 0)
1513 		TOUCH_ERROR ("touch: open: ");
1514 	    }
1515 	  (void) close (fd);
1516 	}
1517     }
1518 
1519   return 0;
1520 }
1521 
1522 /* Having checked and updated the dependencies of FILE,
1523    do whatever is appropriate to remake FILE itself.
1524    Return the status from executing FILE's commands.  */
1525 
1526 static void
remake_file(struct file * file)1527 remake_file (struct file *file)
1528 {
1529 #ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
1530   assert(file->multi_head == NULL || file->multi_head == file);
1531 #endif
1532 
1533   if (file->cmds == 0)
1534     {
1535       if (file->phony)
1536 	/* Phony target.  Pretend it succeeded.  */
1537 	file->update_status = 0;
1538       else if (file->is_target)
1539 	/* This is a nonexistent target file we cannot make.
1540 	   Pretend it was successfully remade.  */
1541 	file->update_status = 0;
1542       else
1543         {
1544           /* This is a dependency file we cannot remake.  Fail.  */
1545           if (!rebuilding_makefiles || !file->dontcare)
1546             complain (file);
1547           file->update_status = 2;
1548         }
1549     }
1550   else
1551     {
1552       chop_commands (file->cmds);
1553 
1554       /* The normal case: start some commands.  */
1555       if (!touch_flag || file->cmds->any_recurse)
1556 	{
1557 	  execute_file_commands (file);
1558 	  return;
1559 	}
1560 
1561       /* This tells notice_finished_file it is ok to touch the file.  */
1562       file->update_status = 0;
1563     }
1564 
1565   /* This does the touching under -t.  */
1566   notice_finished_file (file);
1567 }
1568 
1569 /* Return the mtime of a file, given a `struct file'.
1570    Caches the time in the struct file to avoid excess stat calls.
1571 
1572    If the file is not found, and SEARCH is nonzero, VPATH searching and
1573    replacement is done.  If that fails, a library (-lLIBNAME) is tried and
1574    the library's actual name (/lib/libLIBNAME.a, etc.) is substituted into
1575    FILE.  */
1576 
1577 FILE_TIMESTAMP
f_mtime(struct file * file,int search)1578 f_mtime (struct file *file, int search)
1579 {
1580   FILE_TIMESTAMP mtime;
1581 
1582   /* File's mtime is not known; must get it from the system.  */
1583 
1584 #ifndef	NO_ARCHIVES
1585   if (ar_name (file->name))
1586     {
1587       /* This file is an archive-member reference.  */
1588 
1589       char *arname, *memname;
1590       struct file *arfile;
1591       time_t member_date;
1592 
1593       /* Find the archive's name.  */
1594       ar_parse_name (file->name, &arname, &memname);
1595 
1596       /* Find the modification time of the archive itself.
1597 	 Also allow for its name to be changed via VPATH search.  */
1598       arfile = lookup_file (arname);
1599       if (arfile == 0)
1600         arfile = enter_file (strcache_add (arname));
1601       mtime = f_mtime (arfile, search);
1602       check_renamed (arfile);
1603       if (search && strcmp (arfile->hname, arname))
1604 	{
1605 	  /* The archive's name has changed.
1606 	     Change the archive-member reference accordingly.  */
1607 
1608           char *name;
1609 	  unsigned int arlen, memlen;
1610 
1611 	  arlen = strlen (arfile->hname);
1612 	  memlen = strlen (memname);
1613 
1614 	  name = xmalloc (arlen + 1 + memlen + 2);
1615 	  memcpy (name, arfile->hname, arlen);
1616 	  name[arlen] = '(';
1617 	  memcpy (name + arlen + 1, memname, memlen);
1618 	  name[arlen + 1 + memlen] = ')';
1619 	  name[arlen + 1 + memlen + 1] = '\0';
1620 
1621           /* If the archive was found with GPATH, make the change permanent;
1622              otherwise defer it until later.  */
1623           if (arfile->name == arfile->hname)
1624             rename_file (file, name);
1625           else
1626             rehash_file (file, name);
1627           check_renamed (file);
1628 	}
1629 
1630       free (arname);
1631 
1632       file->low_resolution_time = 1;
1633 
1634       if (mtime == NONEXISTENT_MTIME)
1635 	/* The archive doesn't exist, so its members don't exist either.  */
1636 	return NONEXISTENT_MTIME;
1637 
1638       member_date = ar_member_date (file->hname);
1639       mtime = (member_date == (time_t) -1
1640                ? NONEXISTENT_MTIME
1641                : file_timestamp_cons (file->hname, member_date, 0));
1642     }
1643   else
1644 #endif
1645     {
1646       mtime = name_mtime (file->name);
1647 
1648       if (mtime == NONEXISTENT_MTIME && search && !file->ignore_vpath)
1649 	{
1650 	  /* If name_mtime failed, search VPATH.  */
1651 	  const char *name = vpath_search (file->name, &mtime, NULL, NULL);
1652 	  if (name
1653 	      /* Last resort, is it a library (-lxxx)?  */
1654 	      || (file->name[0] == '-' && file->name[1] == 'l'
1655 		  && (name = library_search (file->name, &mtime)) != 0))
1656 	    {
1657 	      if (mtime != UNKNOWN_MTIME)
1658 		/* vpath_search and library_search store UNKNOWN_MTIME
1659 		   if they didn't need to do a stat call for their work.  */
1660 		file->last_mtime = mtime;
1661 
1662               /* If we found it in VPATH, see if it's in GPATH too; if so,
1663                  change the name right now; if not, defer until after the
1664                  dependencies are updated. */
1665               if (gpath_search (name, strlen(name) - strlen(file->name) - 1))
1666                 {
1667                   rename_file (file, name);
1668                   check_renamed (file);
1669                   return file_mtime (file);
1670                 }
1671 
1672 	      rehash_file (file, name);
1673 	      check_renamed (file);
1674               /* If the result of a vpath search is -o or -W, preserve it.
1675                  Otherwise, find the mtime of the resulting file.  */
1676               if (mtime != OLD_MTIME && mtime != NEW_MTIME)
1677                 mtime = name_mtime (name);
1678 	    }
1679 	}
1680     }
1681 
1682   /* Files can have bogus timestamps that nothing newly made will be
1683      "newer" than.  Updating their dependents could just result in loops.
1684      So notify the user of the anomaly with a warning.
1685 
1686      We only need to do this once, for now. */
1687 
1688   if (!clock_skew_detected
1689       && mtime != NONEXISTENT_MTIME && mtime != NEW_MTIME
1690       && !file->updated)
1691     {
1692       static FILE_TIMESTAMP adjusted_now;
1693 
1694       FILE_TIMESTAMP adjusted_mtime = mtime;
1695 
1696 #if defined(WINDOWS32) || defined(__MSDOS__)
1697       /* Experimentation has shown that FAT filesystems can set file times
1698          up to 3 seconds into the future!  Play it safe.  */
1699 
1700 #define FAT_ADJ_OFFSET  (FILE_TIMESTAMP) 3
1701 
1702       FILE_TIMESTAMP adjustment = FAT_ADJ_OFFSET << FILE_TIMESTAMP_LO_BITS;
1703       if (ORDINARY_MTIME_MIN + adjustment <= adjusted_mtime)
1704         adjusted_mtime -= adjustment;
1705 #elif defined(__EMX__)
1706       /* FAT filesystems round time to the nearest even second!
1707          Allow for any file (NTFS or FAT) to perhaps suffer from this
1708          brain damage.  */
1709       FILE_TIMESTAMP adjustment = (((FILE_TIMESTAMP_S (adjusted_mtime) & 1) == 0
1710                      && FILE_TIMESTAMP_NS (adjusted_mtime) == 0)
1711                     ? (FILE_TIMESTAMP) 1 << FILE_TIMESTAMP_LO_BITS
1712                     : 0);
1713 #endif
1714 
1715       /* If the file's time appears to be in the future, update our
1716          concept of the present and try once more.  */
1717       if (adjusted_now < adjusted_mtime)
1718         {
1719           int resolution;
1720           FILE_TIMESTAMP now = file_timestamp_now (&resolution);
1721           adjusted_now = now + (resolution - 1);
1722           if (adjusted_now < adjusted_mtime)
1723             {
1724 #ifdef NO_FLOAT
1725               error (NILF, _("Warning: File `%s' has modification time in the future"),
1726                      file->name);
1727 #else
1728               double from_now =
1729                 (FILE_TIMESTAMP_S (mtime) - FILE_TIMESTAMP_S (now)
1730                  + ((FILE_TIMESTAMP_NS (mtime) - FILE_TIMESTAMP_NS (now))
1731                     / 1e9));
1732               char from_now_string[100];
1733 
1734               if (from_now >= 99 && from_now <= ULONG_MAX)
1735                 sprintf (from_now_string, "%lu", (unsigned long) from_now);
1736               else
1737                 sprintf (from_now_string, "%.2g", from_now);
1738               error (NILF, _("Warning: File `%s' has modification time %s s in the future"),
1739                      file->name, from_now_string);
1740 #endif
1741               clock_skew_detected = 1;
1742             }
1743         }
1744     }
1745 
1746   /* Store the mtime into all the entries for this file.  */
1747   if (file->double_colon)
1748     file = file->double_colon;
1749 
1750   do
1751     {
1752       /* If this file is not implicit but it is intermediate then it was
1753 	 made so by the .INTERMEDIATE target.  If this file has never
1754 	 been built by us but was found now, it existed before make
1755 	 started.  So, turn off the intermediate bit so make doesn't
1756 	 delete it, since it didn't create it.  */
1757       if (mtime != NONEXISTENT_MTIME && file->command_state == cs_not_started
1758 	  && file->command_state == cs_not_started
1759 	  && !file->tried_implicit && file->intermediate)
1760 	file->intermediate = 0;
1761 
1762       file->last_mtime = mtime;
1763       file = file->prev;
1764     }
1765   while (file != 0);
1766 
1767   return mtime;
1768 }
1769 
1770 
1771 /* Return the mtime of the file or archive-member reference NAME.  */
1772 
1773 /* First, we check with stat().  If the file does not exist, then we return
1774    NONEXISTENT_MTIME.  If it does, and the symlink check flag is set, then
1775    examine each indirection of the symlink and find the newest mtime.
1776    This causes one duplicate stat() when -L is being used, but the code is
1777    much cleaner.  */
1778 
1779 static FILE_TIMESTAMP
name_mtime(const char * name)1780 name_mtime (const char *name)
1781 {
1782   FILE_TIMESTAMP mtime;
1783   struct stat st;
1784   int e;
1785 
1786 #if defined(KMK) && defined(KBUILD_OS_WINDOWS)
1787   extern int stat_only_mtime(const char *pszPath, struct stat *pStat);
1788   e = stat_only_mtime (name, &st);
1789 #else
1790   EINTRLOOP (e, stat (name, &st));
1791 #endif
1792   if (e == 0)
1793     mtime = FILE_TIMESTAMP_STAT_MODTIME (name, st);
1794   else if (errno == ENOENT || errno == ENOTDIR)
1795     mtime = NONEXISTENT_MTIME;
1796   else
1797     {
1798       perror_with_name ("stat: ", name);
1799       return NONEXISTENT_MTIME;
1800     }
1801 
1802   /* If we get here we either found it, or it doesn't exist.
1803      If it doesn't exist see if we can use a symlink mtime instead.  */
1804 
1805 #ifdef MAKE_SYMLINKS
1806 #ifndef S_ISLNK
1807 # define S_ISLNK(_m)     (((_m)&S_IFMT)==S_IFLNK)
1808 #endif
1809   if (check_symlink_flag)
1810     {
1811       PATH_VAR (lpath);
1812 
1813       /* Check each symbolic link segment (if any).  Find the latest mtime
1814          amongst all of them (and the target file of course).
1815          Note that we have already successfully dereferenced all the links
1816          above.  So, if we run into any error trying to lstat(), or
1817          readlink(), or whatever, something bizarre-o happened.  Just give up
1818          and use whatever mtime we've already computed at that point.  */
1819       strcpy (lpath, name);
1820       while (1)
1821         {
1822           FILE_TIMESTAMP ltime;
1823           PATH_VAR (lbuf);
1824           long llen;
1825           char *p;
1826 
1827           EINTRLOOP (e, lstat (lpath, &st));
1828           if (e)
1829             {
1830               /* Just take what we have so far.  */
1831               if (errno != ENOENT && errno != ENOTDIR)
1832                 perror_with_name ("lstat: ", lpath);
1833               break;
1834             }
1835 
1836           /* If this is not a symlink, we're done (we started with the real
1837              file's mtime so we don't need to test it again).  */
1838           if (!S_ISLNK (st.st_mode))
1839             break;
1840 
1841           /* If this mtime is newer than what we had, keep the new one.  */
1842           ltime = FILE_TIMESTAMP_STAT_MODTIME (lpath, st);
1843           if (ltime > mtime)
1844             mtime = ltime;
1845 
1846           /* Set up to check the file pointed to by this link.  */
1847           EINTRLOOP (llen, readlink (lpath, lbuf, GET_PATH_MAX));
1848           if (llen < 0)
1849             {
1850               /* Eh?  Just take what we have.  */
1851               perror_with_name ("readlink: ", lpath);
1852               break;
1853             }
1854           lbuf[llen] = '\0';
1855 
1856           /* If the target is fully-qualified or the source is just a
1857              filename, then the new path is the target.  Otherwise it's the
1858              source directory plus the target.  */
1859           if (lbuf[0] == '/' || (p = strrchr (lpath, '/')) == NULL)
1860             strcpy (lpath, lbuf);
1861           else if ((p - lpath) + llen + 2 > GET_PATH_MAX)
1862             /* Eh?  Path too long!  Again, just go with what we have.  */
1863             break;
1864           else
1865             /* Create the next step in the symlink chain.  */
1866             strcpy (p+1, lbuf);
1867         }
1868     }
1869 #endif
1870 
1871   return mtime;
1872 }
1873 
1874 
1875 /* Search for a library file specified as -lLIBNAME, searching for a
1876    suitable library file in the system library directories and the VPATH
1877    directories.  */
1878 
1879 static const char *
library_search(const char * lib,FILE_TIMESTAMP * mtime_ptr)1880 library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr)
1881 {
1882   static char *dirs[] =
1883     {
1884 #ifdef KMK
1885       ".",
1886 #else /* !KMK */
1887 #ifndef _AMIGA
1888       "/lib",
1889       "/usr/lib",
1890 #endif
1891 #if defined(WINDOWS32) && !defined(LIBDIR)
1892 /*
1893  * This is completely up to the user at product install time. Just define
1894  * a placeholder.
1895  */
1896 #define LIBDIR "."
1897 #endif
1898 # ifdef LIBDIR      /* bird */
1899       LIBDIR,			/* Defined by configuration.  */
1900 # else              /* bird */
1901       ".",          /* bird */
1902 # endif             /* bird */
1903 #endif /* !KMK */
1904       0
1905     };
1906 
1907   const char *file = 0;
1908   char *libpatterns;
1909   FILE_TIMESTAMP mtime;
1910 
1911   /* Loop variables for the libpatterns value.  */
1912   char *p;
1913   const char *p2;
1914   unsigned int len;
1915   unsigned int liblen;
1916 
1917   /* Information about the earliest (in the vpath sequence) match.  */
1918   unsigned int best_vpath = 0, best_path = 0; /* bird: gcc maybe used uninitialized (both) */
1919   unsigned int std_dirs = 0;
1920 
1921   char **dp;
1922 
1923   libpatterns = xstrdup (variable_expand ("$(.LIBPATTERNS)"));
1924 
1925   /* Skip the '-l'.  */
1926   lib += 2;
1927   liblen = strlen (lib);
1928 
1929   /* Loop through all the patterns in .LIBPATTERNS, and search on each one.
1930      To implement the linker-compatible behavior we have to search through
1931      all entries in .LIBPATTERNS and choose the "earliest" one.  */
1932   p2 = libpatterns;
1933   while ((p = find_next_token (&p2, &len)) != 0)
1934     {
1935       static char *buf = NULL;
1936       static unsigned int buflen = 0;
1937       static int libdir_maxlen = -1;
1938       char *libbuf = variable_expand ("");
1939       const size_t libbuf_offset = libbuf - variable_buffer; /* bird */
1940 
1941       /* Expand the pattern using LIB as a replacement.  */
1942       {
1943 	char c = p[len];
1944 	char *p3, *p4;
1945 
1946 	p[len] = '\0';
1947 	p3 = find_percent (p);
1948 	if (!p3)
1949 	  {
1950 	    /* Give a warning if there is no pattern.  */
1951 	    error (NILF, _(".LIBPATTERNS element `%s' is not a pattern"), p);
1952             p[len] = c;
1953 	    continue;
1954 	  }
1955 	p4 = variable_buffer_output (libbuf, p, p3-p);
1956 	p4 = variable_buffer_output (p4, lib, liblen);
1957 	p4 = variable_buffer_output (p4, p3+1, len - (p3-p));
1958 	p[len] = c;
1959 	libbuf = variable_buffer + libbuf_offset; /* bird - variable_buffer may have been reallocated. */
1960       }
1961 
1962       /* Look first for `libNAME.a' in the current directory.  */
1963       mtime = name_mtime (libbuf);
1964       if (mtime != NONEXISTENT_MTIME)
1965 	{
1966 	  if (mtime_ptr != 0)
1967 	    *mtime_ptr = mtime;
1968 	  file = strcache_add (libbuf);
1969           /* This by definition will have the best index, so stop now.  */
1970           break;
1971 	}
1972 
1973       /* Now try VPATH search on that.  */
1974 
1975       {
1976         unsigned int vpath_index, path_index;
1977         const char* f = vpath_search (libbuf, mtime_ptr ? &mtime : NULL,
1978                                       &vpath_index, &path_index);
1979         if (f)
1980           {
1981             /* If we have a better match, record it.  */
1982             if (file == 0 ||
1983                 vpath_index < best_vpath ||
1984                 (vpath_index == best_vpath && path_index < best_path))
1985               {
1986                 file = f;
1987                 best_vpath = vpath_index;
1988                 best_path = path_index;
1989 
1990                 if (mtime_ptr != 0)
1991                   *mtime_ptr = mtime;
1992               }
1993           }
1994       }
1995 
1996       /* Now try the standard set of directories.  */
1997 
1998       if (!buflen)
1999         {
2000           for (dp = dirs; *dp != 0; ++dp)
2001             {
2002               int l = strlen (*dp);
2003               if (l > libdir_maxlen)
2004                 libdir_maxlen = l;
2005               std_dirs++;
2006             }
2007           buflen = strlen (libbuf);
2008           buf = xmalloc(libdir_maxlen + buflen + 2);
2009         }
2010       else if (buflen < strlen (libbuf))
2011         {
2012           buflen = strlen (libbuf);
2013           buf = xrealloc (buf, libdir_maxlen + buflen + 2);
2014         }
2015 
2016       {
2017         /* Use the last std_dirs index for standard directories. This
2018            was it will always be greater than the VPATH index.  */
2019         unsigned int vpath_index = ~((unsigned int)0) - std_dirs;
2020 
2021         for (dp = dirs; *dp != 0; ++dp)
2022 	  {
2023             sprintf (buf, "%s/%s", *dp, libbuf);
2024             mtime = name_mtime (buf);
2025             if (mtime != NONEXISTENT_MTIME)
2026 	      {
2027                 if (file == 0 || vpath_index < best_vpath)
2028                   {
2029                     file = strcache_add (buf);
2030                     best_vpath = vpath_index;
2031 
2032                     if (mtime_ptr != 0)
2033                       *mtime_ptr = mtime;
2034                   }
2035               }
2036 
2037             vpath_index++;
2038           }
2039       }
2040 
2041     }
2042 
2043   free (libpatterns);
2044   return file;
2045 }
2046