Ninja
build.cc
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "build.h"
16 
17 #include <assert.h>
18 #include <errno.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <functional>
22 
23 #if defined(__SVR4) && defined(__sun)
24 #include <sys/termios.h>
25 #endif
26 
27 #include "build_log.h"
28 #include "clparser.h"
29 #include "debug_flags.h"
30 #include "depfile_parser.h"
31 #include "deps_log.h"
32 #include "disk_interface.h"
33 #include "graph.h"
34 #include "metrics.h"
35 #include "state.h"
36 #include "status.h"
37 #include "subprocess.h"
38 #include "util.h"
39 
40 using namespace std;
41 
42 namespace {
43 
44 /// A CommandRunner that doesn't actually run the commands.
45 struct DryRunCommandRunner : public CommandRunner {
46  virtual ~DryRunCommandRunner() {}
47 
48  // Overridden from CommandRunner:
49  virtual bool CanRunMore() const;
50  virtual bool StartCommand(Edge* edge);
51  virtual bool WaitForCommand(Result* result);
52 
53  private:
54  queue<Edge*> finished_;
55 };
56 
57 bool DryRunCommandRunner::CanRunMore() const {
58  return true;
59 }
60 
61 bool DryRunCommandRunner::StartCommand(Edge* edge) {
62  finished_.push(edge);
63  return true;
64 }
65 
66 bool DryRunCommandRunner::WaitForCommand(Result* result) {
67  if (finished_.empty())
68  return false;
69 
70  result->status = ExitSuccess;
71  result->edge = finished_.front();
72  finished_.pop();
73  return true;
74 }
75 
76 } // namespace
77 
79  : builder_(builder)
80  , command_edges_(0)
81  , wanted_edges_(0)
82 {}
83 
84 void Plan::Reset() {
85  command_edges_ = 0;
86  wanted_edges_ = 0;
87  ready_.clear();
88  want_.clear();
89 }
90 
91 bool Plan::AddTarget(const Node* target, string* err) {
92  return AddSubTarget(target, NULL, err, NULL);
93 }
94 
95 bool Plan::AddSubTarget(const Node* node, const Node* dependent, string* err,
96  set<Edge*>* dyndep_walk) {
97  Edge* edge = node->in_edge();
98  if (!edge) { // Leaf node.
99  if (node->dirty()) {
100  string referenced;
101  if (dependent)
102  referenced = ", needed by '" + dependent->path() + "',";
103  *err = "'" + node->path() + "'" + referenced + " missing "
104  "and no known rule to make it";
105  }
106  return false;
107  }
108 
109  if (edge->outputs_ready())
110  return false; // Don't need to do anything.
111 
112  // If an entry in want_ does not already exist for edge, create an entry which
113  // maps to kWantNothing, indicating that we do not want to build this entry itself.
114  pair<map<Edge*, Want>::iterator, bool> want_ins =
115  want_.insert(make_pair(edge, kWantNothing));
116  Want& want = want_ins.first->second;
117 
118  if (dyndep_walk && want == kWantToFinish)
119  return false; // Don't need to do anything with already-scheduled edge.
120 
121  // If we do need to build edge and we haven't already marked it as wanted,
122  // mark it now.
123  if (node->dirty() && want == kWantNothing) {
124  want = kWantToStart;
125  EdgeWanted(edge);
126  if (!dyndep_walk && edge->AllInputsReady())
127  ScheduleWork(want_ins.first);
128  }
129 
130  if (dyndep_walk)
131  dyndep_walk->insert(edge);
132 
133  if (!want_ins.second)
134  return true; // We've already processed the inputs.
135 
136  for (vector<Node*>::iterator i = edge->inputs_.begin();
137  i != edge->inputs_.end(); ++i) {
138  if (!AddSubTarget(*i, node, err, dyndep_walk) && !err->empty())
139  return false;
140  }
141 
142  return true;
143 }
144 
145 void Plan::EdgeWanted(const Edge* edge) {
146  ++wanted_edges_;
147  if (!edge->is_phony())
148  ++command_edges_;
149 }
150 
152  if (ready_.empty())
153  return NULL;
154  EdgeSet::iterator e = ready_.begin();
155  Edge* edge = *e;
156  ready_.erase(e);
157  return edge;
158 }
159 
160 void Plan::ScheduleWork(map<Edge*, Want>::iterator want_e) {
161  if (want_e->second == kWantToFinish) {
162  // This edge has already been scheduled. We can get here again if an edge
163  // and one of its dependencies share an order-only input, or if a node
164  // duplicates an out edge (see https://github.com/ninja-build/ninja/pull/519).
165  // Avoid scheduling the work again.
166  return;
167  }
168  assert(want_e->second == kWantToStart);
169  want_e->second = kWantToFinish;
170 
171  Edge* edge = want_e->first;
172  Pool* pool = edge->pool();
173  if (pool->ShouldDelayEdge()) {
174  pool->DelayEdge(edge);
175  pool->RetrieveReadyEdges(&ready_);
176  } else {
177  pool->EdgeScheduled(*edge);
178  ready_.insert(edge);
179  }
180 }
181 
182 bool Plan::EdgeFinished(Edge* edge, EdgeResult result, string* err) {
183  map<Edge*, Want>::iterator e = want_.find(edge);
184  assert(e != want_.end());
185  bool directly_wanted = e->second != kWantNothing;
186 
187  // See if this job frees up any delayed jobs.
188  if (directly_wanted)
189  edge->pool()->EdgeFinished(*edge);
190  edge->pool()->RetrieveReadyEdges(&ready_);
191 
192  // The rest of this function only applies to successful commands.
193  if (result != kEdgeSucceeded)
194  return true;
195 
196  if (directly_wanted)
197  --wanted_edges_;
198  want_.erase(e);
199  edge->outputs_ready_ = true;
200 
201  // Check off any nodes we were waiting for with this edge.
202  for (vector<Node*>::iterator o = edge->outputs_.begin();
203  o != edge->outputs_.end(); ++o) {
204  if (!NodeFinished(*o, err))
205  return false;
206  }
207  return true;
208 }
209 
210 bool Plan::NodeFinished(Node* node, string* err) {
211  // If this node provides dyndep info, load it now.
212  if (node->dyndep_pending()) {
213  assert(builder_ && "dyndep requires Plan to have a Builder");
214  // Load the now-clean dyndep file. This will also update the
215  // build plan and schedule any new work that is ready.
216  return builder_->LoadDyndeps(node, err);
217  }
218 
219  // See if we we want any edges from this node.
220  for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
221  oe != node->out_edges().end(); ++oe) {
222  map<Edge*, Want>::iterator want_e = want_.find(*oe);
223  if (want_e == want_.end())
224  continue;
225 
226  // See if the edge is now ready.
227  if (!EdgeMaybeReady(want_e, err))
228  return false;
229  }
230  return true;
231 }
232 
233 bool Plan::EdgeMaybeReady(map<Edge*, Want>::iterator want_e, string* err) {
234  Edge* edge = want_e->first;
235  if (edge->AllInputsReady()) {
236  if (want_e->second != kWantNothing) {
237  ScheduleWork(want_e);
238  } else {
239  // We do not need to build this edge, but we might need to build one of
240  // its dependents.
241  if (!EdgeFinished(edge, kEdgeSucceeded, err))
242  return false;
243  }
244  }
245  return true;
246 }
247 
248 bool Plan::CleanNode(DependencyScan* scan, Node* node, string* err) {
249  node->set_dirty(false);
250 
251  for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
252  oe != node->out_edges().end(); ++oe) {
253  // Don't process edges that we don't actually want.
254  map<Edge*, Want>::iterator want_e = want_.find(*oe);
255  if (want_e == want_.end() || want_e->second == kWantNothing)
256  continue;
257 
258  // Don't attempt to clean an edge if it failed to load deps.
259  if ((*oe)->deps_missing_)
260  continue;
261 
262  // If all non-order-only inputs for this edge are now clean,
263  // we might have changed the dirty state of the outputs.
264  vector<Node*>::iterator
265  begin = (*oe)->inputs_.begin(),
266  end = (*oe)->inputs_.end() - (*oe)->order_only_deps_;
267 #if __cplusplus < 201703L
268 #define MEM_FN mem_fun
269 #else
270 #define MEM_FN mem_fn // mem_fun was removed in C++17.
271 #endif
272  if (find_if(begin, end, MEM_FN(&Node::dirty)) == end) {
273  // Recompute most_recent_input.
274  Node* most_recent_input = NULL;
275  for (vector<Node*>::iterator i = begin; i != end; ++i) {
276  if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime())
277  most_recent_input = *i;
278  }
279 
280  // Now, this edge is dirty if any of the outputs are dirty.
281  // If the edge isn't dirty, clean the outputs and mark the edge as not
282  // wanted.
283  bool outputs_dirty = false;
284  if (!scan->RecomputeOutputsDirty(*oe, most_recent_input,
285  &outputs_dirty, err)) {
286  return false;
287  }
288  if (!outputs_dirty) {
289  for (vector<Node*>::iterator o = (*oe)->outputs_.begin();
290  o != (*oe)->outputs_.end(); ++o) {
291  if (!CleanNode(scan, *o, err))
292  return false;
293  }
294 
295  want_e->second = kWantNothing;
296  --wanted_edges_;
297  if (!(*oe)->is_phony())
298  --command_edges_;
299  }
300  }
301  }
302  return true;
303 }
304 
305 bool Plan::DyndepsLoaded(DependencyScan* scan, const Node* node,
306  const DyndepFile& ddf, string* err) {
307  // Recompute the dirty state of all our direct and indirect dependents now
308  // that our dyndep information has been loaded.
309  if (!RefreshDyndepDependents(scan, node, err))
310  return false;
311 
312  // We loaded dyndep information for those out_edges of the dyndep node that
313  // specify the node in a dyndep binding, but they may not be in the plan.
314  // Starting with those already in the plan, walk newly-reachable portion
315  // of the graph through the dyndep-discovered dependencies.
316 
317  // Find edges in the the build plan for which we have new dyndep info.
318  std::vector<DyndepFile::const_iterator> dyndep_roots;
319  for (DyndepFile::const_iterator oe = ddf.begin(); oe != ddf.end(); ++oe) {
320  Edge* edge = oe->first;
321 
322  // If the edge outputs are ready we do not need to consider it here.
323  if (edge->outputs_ready())
324  continue;
325 
326  map<Edge*, Want>::iterator want_e = want_.find(edge);
327 
328  // If the edge has not been encountered before then nothing already in the
329  // plan depends on it so we do not need to consider the edge yet either.
330  if (want_e == want_.end())
331  continue;
332 
333  // This edge is already in the plan so queue it for the walk.
334  dyndep_roots.push_back(oe);
335  }
336 
337  // Walk dyndep-discovered portion of the graph to add it to the build plan.
338  std::set<Edge*> dyndep_walk;
339  for (std::vector<DyndepFile::const_iterator>::iterator
340  oei = dyndep_roots.begin(); oei != dyndep_roots.end(); ++oei) {
341  DyndepFile::const_iterator oe = *oei;
342  for (vector<Node*>::const_iterator i = oe->second.implicit_inputs_.begin();
343  i != oe->second.implicit_inputs_.end(); ++i) {
344  if (!AddSubTarget(*i, oe->first->outputs_[0], err, &dyndep_walk) &&
345  !err->empty())
346  return false;
347  }
348  }
349 
350  // Add out edges from this node that are in the plan (just as
351  // Plan::NodeFinished would have without taking the dyndep code path).
352  for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
353  oe != node->out_edges().end(); ++oe) {
354  map<Edge*, Want>::iterator want_e = want_.find(*oe);
355  if (want_e == want_.end())
356  continue;
357  dyndep_walk.insert(want_e->first);
358  }
359 
360  // See if any encountered edges are now ready.
361  for (set<Edge*>::iterator wi = dyndep_walk.begin();
362  wi != dyndep_walk.end(); ++wi) {
363  map<Edge*, Want>::iterator want_e = want_.find(*wi);
364  if (want_e == want_.end())
365  continue;
366  if (!EdgeMaybeReady(want_e, err))
367  return false;
368  }
369 
370  return true;
371 }
372 
374  string* err) {
375  // Collect the transitive closure of dependents and mark their edges
376  // as not yet visited by RecomputeDirty.
377  set<Node*> dependents;
378  UnmarkDependents(node, &dependents);
379 
380  // Update the dirty state of all dependents and check if their edges
381  // have become wanted.
382  for (set<Node*>::iterator i = dependents.begin();
383  i != dependents.end(); ++i) {
384  Node* n = *i;
385 
386  // Check if this dependent node is now dirty. Also checks for new cycles.
387  std::vector<Node*> validation_nodes;
388  if (!scan->RecomputeDirty(n, &validation_nodes, err))
389  return false;
390 
391  // Add any validation nodes found during RecomputeDirty as new top level
392  // targets.
393  for (std::vector<Node*>::iterator v = validation_nodes.begin();
394  v != validation_nodes.end(); ++v) {
395  if (Edge* in_edge = (*v)->in_edge()) {
396  if (!in_edge->outputs_ready() &&
397  !AddTarget(*v, err)) {
398  return false;
399  }
400  }
401  }
402  if (!n->dirty())
403  continue;
404 
405  // This edge was encountered before. However, we may not have wanted to
406  // build it if the outputs were not known to be dirty. With dyndep
407  // information an output is now known to be dirty, so we want the edge.
408  Edge* edge = n->in_edge();
409  assert(edge && !edge->outputs_ready());
410  map<Edge*, Want>::iterator want_e = want_.find(edge);
411  assert(want_e != want_.end());
412  if (want_e->second == kWantNothing) {
413  want_e->second = kWantToStart;
414  EdgeWanted(edge);
415  }
416  }
417  return true;
418 }
419 
420 void Plan::UnmarkDependents(const Node* node, set<Node*>* dependents) {
421  for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
422  oe != node->out_edges().end(); ++oe) {
423  Edge* edge = *oe;
424 
425  map<Edge*, Want>::iterator want_e = want_.find(edge);
426  if (want_e == want_.end())
427  continue;
428 
429  if (edge->mark_ != Edge::VisitNone) {
430  edge->mark_ = Edge::VisitNone;
431  for (vector<Node*>::iterator o = edge->outputs_.begin();
432  o != edge->outputs_.end(); ++o) {
433  if (dependents->insert(*o).second)
434  UnmarkDependents(*o, dependents);
435  }
436  }
437  }
438 }
439 
440 void Plan::Dump() const {
441  printf("pending: %d\n", (int)want_.size());
442  for (map<Edge*, Want>::const_iterator e = want_.begin(); e != want_.end(); ++e) {
443  if (e->second != kWantNothing)
444  printf("want ");
445  e->first->Dump();
446  }
447  printf("ready: %d\n", (int)ready_.size());
448 }
449 
451  explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
452  virtual ~RealCommandRunner() {}
453  virtual bool CanRunMore() const;
454  virtual bool StartCommand(Edge* edge);
455  virtual bool WaitForCommand(Result* result);
456  virtual vector<Edge*> GetActiveEdges();
457  virtual void Abort();
458 
461  map<const Subprocess*, Edge*> subproc_to_edge_;
462 };
463 
465  vector<Edge*> edges;
466  for (map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.begin();
467  e != subproc_to_edge_.end(); ++e)
468  edges.push_back(e->second);
469  return edges;
470 }
471 
473  subprocs_.Clear();
474 }
475 
477  size_t subproc_number =
478  subprocs_.running_.size() + subprocs_.finished_.size();
479  return (int)subproc_number < config_.parallelism
480  && ((subprocs_.running_.empty() || config_.max_load_average <= 0.0f)
482 }
483 
485  string command = edge->EvaluateCommand();
486  Subprocess* subproc = subprocs_.Add(command, edge->use_console());
487  if (!subproc)
488  return false;
489  subproc_to_edge_.insert(make_pair(subproc, edge));
490 
491  return true;
492 }
493 
495  Subprocess* subproc;
496  while ((subproc = subprocs_.NextFinished()) == NULL) {
497  bool interrupted = subprocs_.DoWork();
498  if (interrupted)
499  return false;
500  }
501 
502  result->status = subproc->Finish();
503  result->output = subproc->GetOutput();
504 
505  map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.find(subproc);
506  result->edge = e->second;
507  subproc_to_edge_.erase(e);
508 
509  delete subproc;
510  return true;
511 }
512 
513 Builder::Builder(State* state, const BuildConfig& config,
514  BuildLog* build_log, DepsLog* deps_log,
515  DiskInterface* disk_interface, Status *status,
516  int64_t start_time_millis)
517  : state_(state), config_(config), plan_(this), status_(status),
518  start_time_millis_(start_time_millis), disk_interface_(disk_interface),
519  scan_(state, build_log, deps_log, disk_interface,
520  &config_.depfile_parser_options) {
521 }
522 
524  Cleanup();
525 }
526 
528  if (command_runner_.get()) {
529  vector<Edge*> active_edges = command_runner_->GetActiveEdges();
530  command_runner_->Abort();
531 
532  for (vector<Edge*>::iterator e = active_edges.begin();
533  e != active_edges.end(); ++e) {
534  string depfile = (*e)->GetUnescapedDepfile();
535  for (vector<Node*>::iterator o = (*e)->outputs_.begin();
536  o != (*e)->outputs_.end(); ++o) {
537  // Only delete this output if it was actually modified. This is
538  // important for things like the generator where we don't want to
539  // delete the manifest file if we can avoid it. But if the rule
540  // uses a depfile, always delete. (Consider the case where we
541  // need to rebuild an output because of a modified header file
542  // mentioned in a depfile, and the command touches its depfile
543  // but is interrupted before it touches its output file.)
544  string err;
545  TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), &err);
546  if (new_mtime == -1) // Log and ignore Stat() errors.
547  status_->Error("%s", err.c_str());
548  if (!depfile.empty() || (*o)->mtime() != new_mtime)
549  disk_interface_->RemoveFile((*o)->path());
550  }
551  if (!depfile.empty())
552  disk_interface_->RemoveFile(depfile);
553  }
554  }
555 }
556 
557 Node* Builder::AddTarget(const string& name, string* err) {
558  Node* node = state_->LookupNode(name);
559  if (!node) {
560  *err = "unknown target: '" + name + "'";
561  return NULL;
562  }
563  if (!AddTarget(node, err))
564  return NULL;
565  return node;
566 }
567 
568 bool Builder::AddTarget(Node* target, string* err) {
569  std::vector<Node*> validation_nodes;
570  if (!scan_.RecomputeDirty(target, &validation_nodes, err))
571  return false;
572 
573  Edge* in_edge = target->in_edge();
574  if (!in_edge || !in_edge->outputs_ready()) {
575  if (!plan_.AddTarget(target, err)) {
576  return false;
577  }
578  }
579 
580  // Also add any validation nodes found during RecomputeDirty as top level
581  // targets.
582  for (std::vector<Node*>::iterator n = validation_nodes.begin();
583  n != validation_nodes.end(); ++n) {
584  if (Edge* validation_in_edge = (*n)->in_edge()) {
585  if (!validation_in_edge->outputs_ready() &&
586  !plan_.AddTarget(*n, err)) {
587  return false;
588  }
589  }
590  }
591 
592  return true;
593 }
594 
596  return !plan_.more_to_do();
597 }
598 
599 bool Builder::Build(string* err) {
600  assert(!AlreadyUpToDate());
601 
603  int pending_commands = 0;
604  int failures_allowed = config_.failures_allowed;
605 
606  // Set up the command runner if we haven't done so already.
607  if (!command_runner_.get()) {
608  if (config_.dry_run)
609  command_runner_.reset(new DryRunCommandRunner);
610  else
612  }
613 
614  // We are about to start the build process.
616 
617  // This main loop runs the entire build process.
618  // It is structured like this:
619  // First, we attempt to start as many commands as allowed by the
620  // command runner.
621  // Second, we attempt to wait for / reap the next finished command.
622  while (plan_.more_to_do()) {
623  // See if we can start any more commands.
624  if (failures_allowed && command_runner_->CanRunMore()) {
625  if (Edge* edge = plan_.FindWork()) {
626  if (edge->GetBindingBool("generator")) {
627  scan_.build_log()->Close();
628  }
629 
630  if (!StartEdge(edge, err)) {
631  Cleanup();
633  return false;
634  }
635 
636  if (edge->is_phony()) {
637  if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
638  Cleanup();
640  return false;
641  }
642  } else {
643  ++pending_commands;
644  }
645 
646  // We made some progress; go back to the main loop.
647  continue;
648  }
649  }
650 
651  // See if we can reap any finished commands.
652  if (pending_commands) {
653  CommandRunner::Result result;
654  if (!command_runner_->WaitForCommand(&result) ||
655  result.status == ExitInterrupted) {
656  Cleanup();
658  *err = "interrupted by user";
659  return false;
660  }
661 
662  --pending_commands;
663  if (!FinishCommand(&result, err)) {
664  Cleanup();
666  return false;
667  }
668 
669  if (!result.success()) {
670  if (failures_allowed)
671  failures_allowed--;
672  }
673 
674  // We made some progress; start the main loop over.
675  continue;
676  }
677 
678  // If we get here, we cannot make any more progress.
680  if (failures_allowed == 0) {
681  if (config_.failures_allowed > 1)
682  *err = "subcommands failed";
683  else
684  *err = "subcommand failed";
685  } else if (failures_allowed < config_.failures_allowed)
686  *err = "cannot make progress due to previous errors";
687  else
688  *err = "stuck [this is a bug]";
689 
690  return false;
691  }
692 
694  return true;
695 }
696 
697 bool Builder::StartEdge(Edge* edge, string* err) {
698  METRIC_RECORD("StartEdge");
699  if (edge->is_phony())
700  return true;
701 
702  int64_t start_time_millis = GetTimeMillis() - start_time_millis_;
703  running_edges_.insert(make_pair(edge, start_time_millis));
704 
705  status_->BuildEdgeStarted(edge, start_time_millis);
706 
707  // Create directories necessary for outputs.
708  // XXX: this will block; do we care?
709  for (vector<Node*>::iterator o = edge->outputs_.begin();
710  o != edge->outputs_.end(); ++o) {
711  if (!disk_interface_->MakeDirs((*o)->path()))
712  return false;
713  }
714 
715  // Create response file, if needed
716  // XXX: this may also block; do we care?
717  string rspfile = edge->GetUnescapedRspfile();
718  if (!rspfile.empty()) {
719  string content = edge->GetBinding("rspfile_content");
720  if (!disk_interface_->WriteFile(rspfile, content))
721  return false;
722  }
723 
724  // start command computing and run it
725  if (!command_runner_->StartCommand(edge)) {
726  err->assign("command '" + edge->EvaluateCommand() + "' failed.");
727  return false;
728  }
729 
730  return true;
731 }
732 
733 bool Builder::FinishCommand(CommandRunner::Result* result, string* err) {
734  METRIC_RECORD("FinishCommand");
735 
736  Edge* edge = result->edge;
737 
738  // First try to extract dependencies from the result, if any.
739  // This must happen first as it filters the command output (we want
740  // to filter /showIncludes output, even on compile failure) and
741  // extraction itself can fail, which makes the command fail from a
742  // build perspective.
743  vector<Node*> deps_nodes;
744  string deps_type = edge->GetBinding("deps");
745  const string deps_prefix = edge->GetBinding("msvc_deps_prefix");
746  if (!deps_type.empty()) {
747  string extract_err;
748  if (!ExtractDeps(result, deps_type, deps_prefix, &deps_nodes,
749  &extract_err) &&
750  result->success()) {
751  if (!result->output.empty())
752  result->output.append("\n");
753  result->output.append(extract_err);
754  result->status = ExitFailure;
755  }
756  }
757 
758  int64_t start_time_millis, end_time_millis;
759  RunningEdgeMap::iterator it = running_edges_.find(edge);
760  start_time_millis = it->second;
761  end_time_millis = GetTimeMillis() - start_time_millis_;
762  running_edges_.erase(it);
763 
764  status_->BuildEdgeFinished(edge, end_time_millis, result->success(),
765  result->output);
766 
767  // The rest of this function only applies to successful commands.
768  if (!result->success()) {
769  return plan_.EdgeFinished(edge, Plan::kEdgeFailed, err);
770  }
771 
772  // Restat the edge outputs
773  TimeStamp output_mtime = 0;
774  bool restat = edge->GetBindingBool("restat");
775  if (!config_.dry_run) {
776  bool node_cleaned = false;
777 
778  for (vector<Node*>::iterator o = edge->outputs_.begin();
779  o != edge->outputs_.end(); ++o) {
780  TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), err);
781  if (new_mtime == -1)
782  return false;
783  if (new_mtime > output_mtime)
784  output_mtime = new_mtime;
785  if ((*o)->mtime() == new_mtime && restat) {
786  // The rule command did not change the output. Propagate the clean
787  // state through the build graph.
788  // Note that this also applies to nonexistent outputs (mtime == 0).
789  if (!plan_.CleanNode(&scan_, *o, err))
790  return false;
791  node_cleaned = true;
792  }
793  }
794 
795  if (node_cleaned) {
796  TimeStamp restat_mtime = 0;
797  // If any output was cleaned, find the most recent mtime of any
798  // (existing) non-order-only input or the depfile.
799  for (vector<Node*>::iterator i = edge->inputs_.begin();
800  i != edge->inputs_.end() - edge->order_only_deps_; ++i) {
801  TimeStamp input_mtime = disk_interface_->Stat((*i)->path(), err);
802  if (input_mtime == -1)
803  return false;
804  if (input_mtime > restat_mtime)
805  restat_mtime = input_mtime;
806  }
807 
808  string depfile = edge->GetUnescapedDepfile();
809  if (restat_mtime != 0 && deps_type.empty() && !depfile.empty()) {
810  TimeStamp depfile_mtime = disk_interface_->Stat(depfile, err);
811  if (depfile_mtime == -1)
812  return false;
813  if (depfile_mtime > restat_mtime)
814  restat_mtime = depfile_mtime;
815  }
816 
817  // The total number of edges in the plan may have changed as a result
818  // of a restat.
820 
821  output_mtime = restat_mtime;
822  }
823  }
824 
825  if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err))
826  return false;
827 
828  // Delete any left over response file.
829  string rspfile = edge->GetUnescapedRspfile();
830  if (!rspfile.empty() && !g_keep_rsp)
831  disk_interface_->RemoveFile(rspfile);
832 
833  if (scan_.build_log()) {
834  if (!scan_.build_log()->RecordCommand(edge, start_time_millis,
835  end_time_millis, output_mtime)) {
836  *err = string("Error writing to build log: ") + strerror(errno);
837  return false;
838  }
839  }
840 
841  if (!deps_type.empty() && !config_.dry_run) {
842  assert(!edge->outputs_.empty() && "should have been rejected by parser");
843  for (std::vector<Node*>::const_iterator o = edge->outputs_.begin();
844  o != edge->outputs_.end(); ++o) {
845  TimeStamp deps_mtime = disk_interface_->Stat((*o)->path(), err);
846  if (deps_mtime == -1)
847  return false;
848  if (!scan_.deps_log()->RecordDeps(*o, deps_mtime, deps_nodes)) {
849  *err = std::string("Error writing to deps log: ") + strerror(errno);
850  return false;
851  }
852  }
853  }
854  return true;
855 }
856 
858  const string& deps_type,
859  const string& deps_prefix,
860  vector<Node*>* deps_nodes,
861  string* err) {
862  if (deps_type == "msvc") {
863  CLParser parser;
864  string output;
865  if (!parser.Parse(result->output, deps_prefix, &output, err))
866  return false;
867  result->output = output;
868  for (set<string>::iterator i = parser.includes_.begin();
869  i != parser.includes_.end(); ++i) {
870  // ~0 is assuming that with MSVC-parsed headers, it's ok to always make
871  // all backslashes (as some of the slashes will certainly be backslashes
872  // anyway). This could be fixed if necessary with some additional
873  // complexity in IncludesNormalize::Relativize.
874  deps_nodes->push_back(state_->GetNode(*i, ~0u));
875  }
876  } else if (deps_type == "gcc") {
877  string depfile = result->edge->GetUnescapedDepfile();
878  if (depfile.empty()) {
879  *err = string("edge with deps=gcc but no depfile makes no sense");
880  return false;
881  }
882 
883  // Read depfile content. Treat a missing depfile as empty.
884  string content;
885  switch (disk_interface_->ReadFile(depfile, &content, err)) {
886  case DiskInterface::Okay:
887  break;
889  err->clear();
890  break;
892  return false;
893  }
894  if (content.empty())
895  return true;
896 
898  if (!deps.Parse(&content, err))
899  return false;
900 
901  // XXX check depfile matches expected output.
902  deps_nodes->reserve(deps.ins_.size());
903  for (vector<StringPiece>::iterator i = deps.ins_.begin();
904  i != deps.ins_.end(); ++i) {
905  uint64_t slash_bits;
906  CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits);
907  deps_nodes->push_back(state_->GetNode(*i, slash_bits));
908  }
909 
910  if (!g_keep_depfile) {
911  if (disk_interface_->RemoveFile(depfile) < 0) {
912  *err = string("deleting depfile: ") + strerror(errno) + string("\n");
913  return false;
914  }
915  }
916  } else {
917  Fatal("unknown deps type '%s'", deps_type.c_str());
918  }
919 
920  return true;
921 }
922 
923 bool Builder::LoadDyndeps(Node* node, string* err) {
925 
926  // Load the dyndep information provided by this node.
927  DyndepFile ddf;
928  if (!scan_.LoadDyndeps(node, &ddf, err))
929  return false;
930 
931  // Update the build plan to account for dyndep modifications to the graph.
932  if (!plan_.DyndepsLoaded(&scan_, node, ddf, err))
933  return false;
934 
935  // New command edges may have been added to the plan.
937 
938  return true;
939 }
Subprocess * Add(const std::string &command, bool use_console=false)
SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
Definition: subprocess.h:82
bool dyndep_pending() const
Definition: graph.h:101
bool Build(std::string *err)
Run the build.
Definition: build.cc:599
bool RecomputeDirty(Node *node, std::vector< Node *> *validation_nodes, std::string *err)
Update the |dirty_| state of the given nodes by transitively inspecting their input edges...
Definition: graph.cc:50
std::queue< Subprocess * > finished_
Definition: subprocess.h:92
bool RefreshDyndepDependents(DependencyScan *scan, const Node *node, std::string *err)
Definition: build.cc:373
Status * status_
Definition: build.h:223
CommandRunner is an interface that wraps running the build subcommands.
Definition: build.h:136
std::auto_ptr< CommandRunner > command_runner_
Definition: build.h:219
SubprocessSet subprocs_
Definition: build.cc:460
int order_only_deps_
Definition: graph.h:229
bool RecordCommand(Edge *edge, int start_time, int end_time, TimeStamp mtime=0)
Definition: build_log.cc:144
We do not want to build the edge, but we might want to build one of its dependents.
Definition: build.h:100
virtual ~RealCommandRunner()
Definition: build.cc:452
virtual bool WriteFile(const std::string &path, const std::string &contents)=0
Create a file, with the specified name and contents Returns true on success, false on failure...
Builder * builder_
Definition: build.h:124
Store data loaded from one dyndep file.
Definition: dyndep.h:40
Subprocess * NextFinished()
VisitMark mark_
Definition: graph.h:208
double max_load_average
The maximum load average we must not exceed.
Definition: build.h:173
Edge * in_edge() const
Definition: graph.h:104
Parser for the dependency information emitted by gcc&#39;s -M flags.
#define MEM_FN
void EdgeScheduled(const Edge &edge)
informs this Pool that the given edge is committed to be run.
Definition: state.cc:26
Node * GetNode(StringPiece path, uint64_t slash_bits)
Definition: state.cc:96
RunningEdgeMap running_edges_
Definition: build.h:232
bool RecomputeOutputsDirty(Edge *edge, Node *most_recent_input, bool *dirty, std::string *err)
Recompute whether any output of the edge is dirty, if so sets |*dirty|.
Definition: graph.cc:265
The result of waiting for a command.
Definition: build.h:142
virtual void BuildEdgeStarted(const Edge *edge, int64_t start_time_millis)=0
EdgeSet ready_
Definition: build.h:122
void set_dirty(bool dirty)
Definition: graph.h:98
virtual int RemoveFile(const std::string &path)=0
Remove the file named path.
Information about a node in the dependency graph: the file, whether it&#39;s dirty, mtime, etc.
Definition: graph.h:39
Edge * FindWork()
Definition: build.cc:151
virtual bool StartCommand(Edge *edge)
Definition: build.cc:484
bool DyndepsLoaded(DependencyScan *scan, const Node *node, const DyndepFile &ddf, std::string *err)
Update the build plan to account for modifications made to the graph by information loaded from a dyn...
Definition: build.cc:305
bool Parse(std::string *content, std::string *err)
Parse an input file.
bool outputs_ready() const
Definition: graph.h:218
State * state_
Definition: build.h:215
std::string output
Definition: build.h:146
Interface for accessing the disk.
const BuildConfig & config_
Definition: build.h:216
int64_t GetTimeMillis()
Get the current time as relative to some epoch.
Definition: metrics.cc:126
bool g_keep_depfile
Definition: debug_flags.cc:17
Plan(Builder *builder=NULL)
Definition: build.cc:78
bool LoadDyndeps(Node *node, std::string *err) const
Load a dyndep file from the given node&#39;s path and update the build graph with the new information...
std::vector< Node * > outputs_
Definition: graph.h:204
Builder(State *state, const BuildConfig &config, BuildLog *build_log, DepsLog *deps_log, DiskInterface *disk_interface, Status *status, int64_t start_time_millis)
Definition: build.cc:513
bool StartEdge(Edge *edge, std::string *err)
Definition: build.cc:697
void Dump() const
Dumps the current state of the plan.
Definition: build.cc:440
void Close()
Definition: build_log.cc:178
int command_edge_count() const
Number of edges with commands to run.
Definition: build.h:74
An edge in the dependency graph; links between Nodes using Rules.
Definition: graph.h:164
Node * LookupNode(StringPiece path) const
Definition: state.cc:105
Store a log of every command ran for every build.
Definition: build_log.h:43
virtual bool WaitForCommand(Result *result)
Wait for a command to complete, or return false if interrupted.
Definition: build.cc:494
virtual void BuildLoadDyndeps()=0
const BuildConfig & config_
Definition: build.cc:459
const std::string & path() const
Definition: graph.h:86
DiskInterface * disk_interface_
Definition: build.h:237
std::map< Edge *, Want > want_
Keep track of which edges we want to build in this plan.
Definition: build.h:120
ExitStatus Finish()
Returns ExitSuccess on successful process exit, ExitInterrupted if the process was interrupted...
void ScheduleWork(std::map< Edge *, Want >::iterator want_e)
Submits a ready edge as a candidate for execution.
Definition: build.cc:160
bool AddSubTarget(const Node *node, const Node *dependent, std::string *err, std::set< Edge *> *dyndep_walk)
Definition: build.cc:95
Want
Enumerate possible steps we want for an edge.
Definition: build.h:96
As build commands run they can output extra dependency information (e.g.
Definition: deps_log.h:68
signed long long int64_t
A 64-bit integer type.
Definition: win32port.h:28
double GetLoadAverage()
Definition: util.cc:822
bool outputs_ready_
Definition: graph.h:210
int parallelism
Definition: build.h:169
int failures_allowed
Definition: build.h:170
Subprocess wraps a single async subprocess.
Definition: subprocess.h:42
bool RecordDeps(Node *node, TimeStamp mtime, const std::vector< Node *> &nodes)
virtual void PlanHasTotalEdges(int total)=0
~Builder()
Definition: build.cc:523
void Reset()
Reset state. Clears want and ready sets.
Definition: build.cc:84
bool ExtractDeps(CommandRunner::Result *result, const std::string &deps_type, const std::string &deps_prefix, std::vector< Node *> *deps_nodes, std::string *err)
Definition: build.cc:857
std::set< std::string > includes_
Definition: clparser.h:48
virtual vector< Edge * > GetActiveEdges()
Definition: build.cc:464
Node * AddTarget(const std::string &name, std::string *err)
bool dirty() const
Definition: graph.h:97
virtual void Abort()
Definition: build.cc:472
std::vector< StringPiece > ins_
std::string GetUnescapedRspfile() const
Like GetBinding("rspfile"), but without shell escaping.
Definition: graph.cc:510
Abstract interface to object that tracks the status of a build: completion fraction, printing updates.
Definition: status.h:26
int wanted_edges_
Total remaining number of wanted edges.
Definition: build.h:130
map< const Subprocess *, Edge * > subproc_to_edge_
Definition: build.cc:461
DepsLog * deps_log() const
Definition: graph.h:342
ExitStatus status
Definition: build.h:145
BuildLog * build_log() const
Definition: graph.h:335
void DelayEdge(Edge *edge)
adds the given edge to this Pool to be delayed.
Definition: state.cc:36
void Cleanup()
Clean up after interrupted commands by deleting output files.
Definition: build.cc:527
int64_t TimeStamp
Definition: timestamp.h:31
A pool for delayed edges.
Definition: state.h:40
bool EdgeMaybeReady(std::map< Edge *, Want >::iterator want_e, std::string *err)
Definition: build.cc:233
We want to build the edge, but have not yet scheduled it.
Definition: build.h:102
bool ShouldDelayEdge() const
true if the Pool might delay this edge
Definition: state.h:51
int64_t start_time_millis_
Time the build started.
Definition: build.h:235
#define METRIC_RECORD(name)
The primary interface to metrics.
Definition: metrics.h:84
std::vector< Node * > inputs_
Definition: graph.h:203
std::string GetUnescapedDepfile() const
Like GetBinding("depfile"), but without shell escaping.
Definition: graph.cc:500
Builder wraps the build process: starting commands, updating status.
Definition: build.h:178
bool LoadDyndeps(Node *node, std::string *err)
Load the dyndep information provided by the given node.
Definition: build.cc:923
bool EdgeFinished(Edge *edge, EdgeResult result, std::string *err)
Mark an edge as done building (whether it succeeded or failed).
Definition: build.cc:182
std::string GetBinding(const std::string &key) const
Returns the shell-escaped value of |key|.
Definition: graph.cc:491
bool AddTarget(const Node *target, std::string *err)
Add a target to our plan (including all its dependencies).
Definition: build.cc:91
EdgeResult
Definition: build.h:58
void Fatal(const char *msg,...)
Log a fatal message and exit.
Definition: util.cc:65
virtual void BuildStarted()=0
virtual Status ReadFile(const std::string &path, std::string *contents, std::string *err)=0
Read and store in given string.
TimeStamp mtime() const
Definition: graph.h:95
bool NodeFinished(Node *node, std::string *err)
Update plan with knowledge that the given node is up to date.
Definition: build.cc:210
Plan plan_
Definition: build.h:217
virtual void BuildEdgeFinished(Edge *edge, int64_t end_time_millis, bool success, const std::string &output)=0
Visual Studio&#39;s cl.exe requires some massaging to work with Ninja; for example, it emits include info...
Definition: clparser.h:25
DependencyScan manages the process of scanning the files in a graph and updating the dirty/outputs_re...
Definition: graph.h:312
bool Parse(const std::string &output, const std::string &deps_prefix, std::string *filtered_output, std::string *err)
Parse the full output of cl, filling filtered_output with the text that should be printed (if any)...
Definition: clparser.cc:80
virtual void BuildFinished()=0
bool MakeDirs(const std::string &path)
Create all the parent directories for path; like mkdir -p basename path.
const std::string & GetOutput() const
Pool * pool() const
Definition: graph.h:216
std::string EvaluateCommand(bool incl_rsp_file=false) const
Expand all variables in a command and return it as a string.
Definition: graph.cc:481
bool AllInputsReady() const
Return true if all inputs&#39; in-edges are ready.
Definition: graph.cc:374
void EdgeFinished(const Edge &edge)
informs this Pool that the given edge is no longer runnable, and should relinquish its resources back...
Definition: state.cc:31
const std::vector< Edge * > & out_edges() const
Definition: graph.h:110
void CanonicalizePath(string *path, uint64_t *slash_bits)
Definition: util.cc:122
void EdgeWanted(const Edge *edge)
Definition: build.cc:145
Options (e.g. verbosity, parallelism) passed to a build.
Definition: build.h:157
Global state (file status) for a single run.
Definition: state.h:92
bool g_keep_rsp
Definition: debug_flags.cc:19
We want to build the edge, have scheduled it, and are waiting for it to complete. ...
Definition: build.h:105
bool CleanNode(DependencyScan *scan, Node *node, std::string *err)
Clean the given node during the build.
Definition: build.cc:248
unsigned long long uint64_t
Definition: win32port.h:29
virtual bool CanRunMore() const
Definition: build.cc:476
bool is_phony() const
Definition: graph.cc:543
bool use_console() const
Definition: graph.cc:547
bool more_to_do() const
Returns true if there&#39;s more work to be done.
Definition: build.h:53
virtual TimeStamp Stat(const std::string &path, std::string *err) const =0
stat() a file, returning the mtime, or 0 if missing and -1 on other errors.
bool success() const
Definition: build.h:147
bool GetBindingBool(const std::string &key) const
Definition: graph.cc:496
DepfileParserOptions depfile_parser_options
Definition: build.h:174
std::vector< Subprocess * > running_
Definition: subprocess.h:91
bool AlreadyUpToDate() const
Returns true if the build targets are already up to date.
Definition: build.cc:595
bool dry_run
Definition: build.h:168
DependencyScan scan_
Definition: build.h:238
int command_edges_
Total number of edges that have commands (not phony).
Definition: build.h:127
void UnmarkDependents(const Node *node, std::set< Node *> *dependents)
Definition: build.cc:420
virtual void Error(const char *msg,...)=0
bool FinishCommand(CommandRunner::Result *result, std::string *err)
Update status ninja logs following a command termination.
Definition: build.cc:733
void RetrieveReadyEdges(EdgeSet *ready_queue)
Pool will add zero or more edges to the ready_queue.
Definition: state.cc:41
RealCommandRunner(const BuildConfig &config)
Definition: build.cc:451