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 "debug_flags.h"
29 #include "depfile_parser.h"
30 #include "deps_log.h"
31 #include "disk_interface.h"
32 #include "graph.h"
33 #include "msvc_helper.h"
34 #include "state.h"
35 #include "subprocess.h"
36 #include "util.h"
37 
38 namespace {
39 
40 /// A CommandRunner that doesn't actually run the commands.
41 struct DryRunCommandRunner : public CommandRunner {
42  virtual ~DryRunCommandRunner() {}
43 
44  // Overridden from CommandRunner:
45  virtual bool CanRunMore();
46  virtual bool StartCommand(Edge* edge);
47  virtual bool WaitForCommand(Result* result);
48 
49  private:
50  queue<Edge*> finished_;
51 };
52 
53 bool DryRunCommandRunner::CanRunMore() {
54  return true;
55 }
56 
57 bool DryRunCommandRunner::StartCommand(Edge* edge) {
58  finished_.push(edge);
59  return true;
60 }
61 
62 bool DryRunCommandRunner::WaitForCommand(Result* result) {
63  if (finished_.empty())
64  return false;
65 
66  result->status = ExitSuccess;
67  result->edge = finished_.front();
68  finished_.pop();
69  return true;
70 }
71 
72 } // namespace
73 
75  : config_(config),
76  start_time_millis_(GetTimeMillis()),
77  started_edges_(0), finished_edges_(0), total_edges_(0),
78  progress_status_format_(NULL),
79  overall_rate_(), current_rate_(config.parallelism) {
80 
81  // Don't do anything fancy in verbose mode.
84 
85  progress_status_format_ = getenv("NINJA_STATUS");
87  progress_status_format_ = "[%s/%t] ";
88 }
89 
91  total_edges_ = total;
92 }
93 
95  int start_time = (int)(GetTimeMillis() - start_time_millis_);
96  running_edges_.insert(make_pair(edge, start_time));
98 
99  PrintStatus(edge);
100 
101  if (edge->use_console())
103 }
104 
106  bool success,
107  const string& output,
108  int* start_time,
109  int* end_time) {
110  int64_t now = GetTimeMillis();
111  ++finished_edges_;
112 
113  RunningEdgeMap::iterator i = running_edges_.find(edge);
114  *start_time = i->second;
115  *end_time = (int)(now - start_time_millis_);
116  running_edges_.erase(i);
117 
118  if (edge->use_console())
119  printer_.SetConsoleLocked(false);
120 
122  return;
123 
124  if (!edge->use_console() && printer_.is_smart_terminal())
125  PrintStatus(edge);
126 
127  // Print the command that is spewing before printing its output.
128  if (!success)
129  printer_.PrintOnNewLine("FAILED: " + edge->EvaluateCommand() + "\n");
130 
131  if (!output.empty()) {
132  // ninja sets stdout and stderr of subprocesses to a pipe, to be able to
133  // check if the output is empty. Some compilers, e.g. clang, check
134  // isatty(stderr) to decide if they should print colored output.
135  // To make it possible to use colored output with ninja, subprocesses should
136  // be run with a flag that forces them to always print color escape codes.
137  // To make sure these escape codes don't show up in a file if ninja's output
138  // is piped to a file, ninja strips ansi escape codes again if it's not
139  // writing to a |smart_terminal_|.
140  // (Launching subprocesses in pseudo ttys doesn't work because there are
141  // only a few hundred available on some systems, and ninja can launch
142  // thousands of parallel compile commands.)
143  // TODO: There should be a flag to disable escape code stripping.
144  string final_output;
146  final_output = StripAnsiEscapeCodes(output);
147  else
148  final_output = output;
149  printer_.PrintOnNewLine(final_output);
150  }
151 }
152 
154  printer_.SetConsoleLocked(false);
156 }
157 
159  const char* progress_status_format) const {
160  string out;
161  char buf[32];
162  int percent;
163  for (const char* s = progress_status_format; *s != '\0'; ++s) {
164  if (*s == '%') {
165  ++s;
166  switch (*s) {
167  case '%':
168  out.push_back('%');
169  break;
170 
171  // Started edges.
172  case 's':
173  snprintf(buf, sizeof(buf), "%d", started_edges_);
174  out += buf;
175  break;
176 
177  // Total edges.
178  case 't':
179  snprintf(buf, sizeof(buf), "%d", total_edges_);
180  out += buf;
181  break;
182 
183  // Running edges.
184  case 'r':
185  snprintf(buf, sizeof(buf), "%d", started_edges_ - finished_edges_);
186  out += buf;
187  break;
188 
189  // Unstarted edges.
190  case 'u':
191  snprintf(buf, sizeof(buf), "%d", total_edges_ - started_edges_);
192  out += buf;
193  break;
194 
195  // Finished edges.
196  case 'f':
197  snprintf(buf, sizeof(buf), "%d", finished_edges_);
198  out += buf;
199  break;
200 
201  // Overall finished edges per second.
202  case 'o':
204  snprinfRate(overall_rate_.rate(), buf, "%.1f");
205  out += buf;
206  break;
207 
208  // Current rate, average over the last '-j' jobs.
209  case 'c':
211  snprinfRate(current_rate_.rate(), buf, "%.1f");
212  out += buf;
213  break;
214 
215  // Percentage
216  case 'p':
217  percent = (100 * started_edges_) / total_edges_;
218  snprintf(buf, sizeof(buf), "%3i%%", percent);
219  out += buf;
220  break;
221 
222  case 'e': {
223  double elapsed = overall_rate_.Elapsed();
224  snprintf(buf, sizeof(buf), "%.3f", elapsed);
225  out += buf;
226  break;
227  }
228 
229  default:
230  Fatal("unknown placeholder '%%%c' in $NINJA_STATUS", *s);
231  return "";
232  }
233  } else {
234  out.push_back(*s);
235  }
236  }
237 
238  return out;
239 }
240 
243  return;
244 
245  bool force_full_command = config_.verbosity == BuildConfig::VERBOSE;
246 
247  string to_print = edge->GetBinding("description");
248  if (to_print.empty() || force_full_command)
249  to_print = edge->GetBinding("command");
250 
251  if (finished_edges_ == 0) {
254  }
255  to_print = FormatProgressStatus(progress_status_format_) + to_print;
256 
257  printer_.Print(to_print,
258  force_full_command ? LinePrinter::FULL : LinePrinter::ELIDE);
259 }
260 
261 Plan::Plan() : command_edges_(0), wanted_edges_(0) {}
262 
263 bool Plan::AddTarget(Node* node, string* err) {
264  vector<Node*> stack;
265  return AddSubTarget(node, &stack, err);
266 }
267 
268 bool Plan::AddSubTarget(Node* node, vector<Node*>* stack, string* err) {
269  Edge* edge = node->in_edge();
270  if (!edge) { // Leaf node.
271  if (node->dirty()) {
272  string referenced;
273  if (!stack->empty())
274  referenced = ", needed by '" + stack->back()->path() + "',";
275  *err = "'" + node->path() + "'" + referenced + " missing "
276  "and no known rule to make it";
277  }
278  return false;
279  }
280 
281  if (CheckDependencyCycle(node, stack, err))
282  return false;
283 
284  if (edge->outputs_ready())
285  return false; // Don't need to do anything.
286 
287  // If an entry in want_ does not already exist for edge, create an entry which
288  // maps to false, indicating that we do not want to build this entry itself.
289  pair<map<Edge*, bool>::iterator, bool> want_ins =
290  want_.insert(make_pair(edge, false));
291  bool& want = want_ins.first->second;
292 
293  // If we do need to build edge and we haven't already marked it as wanted,
294  // mark it now.
295  if (node->dirty() && !want) {
296  want = true;
297  ++wanted_edges_;
298  if (edge->AllInputsReady())
299  ScheduleWork(edge);
300  if (!edge->is_phony())
301  ++command_edges_;
302  }
303 
304  if (!want_ins.second)
305  return true; // We've already processed the inputs.
306 
307  stack->push_back(node);
308  for (vector<Node*>::iterator i = edge->inputs_.begin();
309  i != edge->inputs_.end(); ++i) {
310  if (!AddSubTarget(*i, stack, err) && !err->empty())
311  return false;
312  }
313  assert(stack->back() == node);
314  stack->pop_back();
315 
316  return true;
317 }
318 
319 bool Plan::CheckDependencyCycle(Node* node, vector<Node*>* stack, string* err) {
320  vector<Node*>::reverse_iterator ri =
321  find(stack->rbegin(), stack->rend(), node);
322  if (ri == stack->rend())
323  return false;
324 
325  // Add this node onto the stack to make it clearer where the loop
326  // is.
327  stack->push_back(node);
328 
329  vector<Node*>::iterator start = find(stack->begin(), stack->end(), node);
330  *err = "dependency cycle: ";
331  for (vector<Node*>::iterator i = start; i != stack->end(); ++i) {
332  if (i != start)
333  err->append(" -> ");
334  err->append((*i)->path());
335  }
336  return true;
337 }
338 
340  if (ready_.empty())
341  return NULL;
342  set<Edge*>::iterator i = ready_.begin();
343  Edge* edge = *i;
344  ready_.erase(i);
345  return edge;
346 }
347 
349  Pool* pool = edge->pool();
350  if (pool->ShouldDelayEdge()) {
351  // The graph is not completely clean. Some Nodes have duplicate Out edges.
352  // We need to explicitly ignore these here, otherwise their work will get
353  // scheduled twice (see https://github.com/martine/ninja/pull/519)
354  if (ready_.count(edge)) {
355  return;
356  }
357  pool->DelayEdge(edge);
358  pool->RetrieveReadyEdges(&ready_);
359  } else {
360  pool->EdgeScheduled(*edge);
361  ready_.insert(edge);
362  }
363 }
364 
366  edge->pool()->EdgeFinished(*edge);
367  edge->pool()->RetrieveReadyEdges(&ready_);
368 }
369 
371  map<Edge*, bool>::iterator i = want_.find(edge);
372  assert(i != want_.end());
373  if (i->second)
374  --wanted_edges_;
375  want_.erase(i);
376  edge->outputs_ready_ = true;
377 
378  // See if this job frees up any delayed jobs
379  ResumeDelayedJobs(edge);
380 
381  // Check off any nodes we were waiting for with this edge.
382  for (vector<Node*>::iterator i = edge->outputs_.begin();
383  i != edge->outputs_.end(); ++i) {
384  NodeFinished(*i);
385  }
386 }
387 
389  // See if we we want any edges from this node.
390  for (vector<Edge*>::const_iterator i = node->out_edges().begin();
391  i != node->out_edges().end(); ++i) {
392  map<Edge*, bool>::iterator want_i = want_.find(*i);
393  if (want_i == want_.end())
394  continue;
395 
396  // See if the edge is now ready.
397  if ((*i)->AllInputsReady()) {
398  if (want_i->second) {
399  ScheduleWork(*i);
400  } else {
401  // We do not need to build this edge, but we might need to build one of
402  // its dependents.
403  EdgeFinished(*i);
404  }
405  }
406  }
407 }
408 
409 void Plan::CleanNode(DependencyScan* scan, Node* node) {
410  node->set_dirty(false);
411 
412  for (vector<Edge*>::const_iterator ei = node->out_edges().begin();
413  ei != node->out_edges().end(); ++ei) {
414  // Don't process edges that we don't actually want.
415  map<Edge*, bool>::iterator want_i = want_.find(*ei);
416  if (want_i == want_.end() || !want_i->second)
417  continue;
418 
419  // Don't attempt to clean an edge if it failed to load deps.
420  if ((*ei)->deps_missing_)
421  continue;
422 
423  // If all non-order-only inputs for this edge are now clean,
424  // we might have changed the dirty state of the outputs.
425  vector<Node*>::iterator
426  begin = (*ei)->inputs_.begin(),
427  end = (*ei)->inputs_.end() - (*ei)->order_only_deps_;
428  if (find_if(begin, end, mem_fun(&Node::dirty)) == end) {
429  // Recompute most_recent_input.
430  Node* most_recent_input = NULL;
431  for (vector<Node*>::iterator ni = begin; ni != end; ++ni) {
432  if (!most_recent_input || (*ni)->mtime() > most_recent_input->mtime())
433  most_recent_input = *ni;
434  }
435 
436  // Now, this edge is dirty if any of the outputs are dirty.
437  // If the edge isn't dirty, clean the outputs and mark the edge as not
438  // wanted.
439  if (!scan->RecomputeOutputsDirty(*ei, most_recent_input)) {
440  for (vector<Node*>::iterator ni = (*ei)->outputs_.begin();
441  ni != (*ei)->outputs_.end(); ++ni) {
442  CleanNode(scan, *ni);
443  }
444 
445  want_i->second = false;
446  --wanted_edges_;
447  if (!(*ei)->is_phony())
448  --command_edges_;
449  }
450  }
451  }
452 }
453 
454 void Plan::Dump() {
455  printf("pending: %d\n", (int)want_.size());
456  for (map<Edge*, bool>::iterator i = want_.begin(); i != want_.end(); ++i) {
457  if (i->second)
458  printf("want ");
459  i->first->Dump();
460  }
461  printf("ready: %d\n", (int)ready_.size());
462 }
463 
465  explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
466  virtual ~RealCommandRunner() {}
467  virtual bool CanRunMore();
468  virtual bool StartCommand(Edge* edge);
469  virtual bool WaitForCommand(Result* result);
470  virtual vector<Edge*> GetActiveEdges();
471  virtual void Abort();
472 
475  map<Subprocess*, Edge*> subproc_to_edge_;
476 };
477 
479  vector<Edge*> edges;
480  for (map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.begin();
481  i != subproc_to_edge_.end(); ++i)
482  edges.push_back(i->second);
483  return edges;
484 }
485 
487  subprocs_.Clear();
488 }
489 
491  return ((int)subprocs_.running_.size()) < config_.parallelism
492  && ((subprocs_.running_.empty() || config_.max_load_average <= 0.0f)
494 }
495 
497  string command = edge->EvaluateCommand();
498  Subprocess* subproc = subprocs_.Add(command, edge->use_console());
499  if (!subproc)
500  return false;
501  subproc_to_edge_.insert(make_pair(subproc, edge));
502 
503  return true;
504 }
505 
507  Subprocess* subproc;
508  while ((subproc = subprocs_.NextFinished()) == NULL) {
509  bool interrupted = subprocs_.DoWork();
510  if (interrupted)
511  return false;
512  }
513 
514  result->status = subproc->Finish();
515  result->output = subproc->GetOutput();
516 
517  map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);
518  result->edge = i->second;
519  subproc_to_edge_.erase(i);
520 
521  delete subproc;
522  return true;
523 }
524 
525 Builder::Builder(State* state, const BuildConfig& config,
526  BuildLog* build_log, DepsLog* deps_log,
527  DiskInterface* disk_interface)
528  : state_(state), config_(config), disk_interface_(disk_interface),
529  scan_(state, build_log, deps_log, disk_interface) {
530  status_ = new BuildStatus(config);
531 }
532 
534  Cleanup();
535 }
536 
538  if (command_runner_.get()) {
539  vector<Edge*> active_edges = command_runner_->GetActiveEdges();
540  command_runner_->Abort();
541 
542  for (vector<Edge*>::iterator i = active_edges.begin();
543  i != active_edges.end(); ++i) {
544  string depfile = (*i)->GetUnescapedDepfile();
545  for (vector<Node*>::iterator ni = (*i)->outputs_.begin();
546  ni != (*i)->outputs_.end(); ++ni) {
547  // Only delete this output if it was actually modified. This is
548  // important for things like the generator where we don't want to
549  // delete the manifest file if we can avoid it. But if the rule
550  // uses a depfile, always delete. (Consider the case where we
551  // need to rebuild an output because of a modified header file
552  // mentioned in a depfile, and the command touches its depfile
553  // but is interrupted before it touches its output file.)
554  if (!depfile.empty() ||
555  (*ni)->mtime() != disk_interface_->Stat((*ni)->path())) {
556  disk_interface_->RemoveFile((*ni)->path());
557  }
558  }
559  if (!depfile.empty())
560  disk_interface_->RemoveFile(depfile);
561  }
562  }
563 }
564 
565 Node* Builder::AddTarget(const string& name, string* err) {
566  Node* node = state_->LookupNode(name);
567  if (!node) {
568  *err = "unknown target: '" + name + "'";
569  return NULL;
570  }
571  if (!AddTarget(node, err))
572  return NULL;
573  return node;
574 }
575 
576 bool Builder::AddTarget(Node* node, string* err) {
578  if (Edge* in_edge = node->in_edge()) {
579  if (!scan_.RecomputeDirty(in_edge, err))
580  return false;
581  if (in_edge->outputs_ready())
582  return true; // Nothing to do.
583  }
584 
585  if (!plan_.AddTarget(node, err))
586  return false;
587 
588  return true;
589 }
590 
592  return !plan_.more_to_do();
593 }
594 
595 bool Builder::Build(string* err) {
596  assert(!AlreadyUpToDate());
597 
599  int pending_commands = 0;
600  int failures_allowed = config_.failures_allowed;
601 
602  // Set up the command runner if we haven't done so already.
603  if (!command_runner_.get()) {
604  if (config_.dry_run)
605  command_runner_.reset(new DryRunCommandRunner);
606  else
608  }
609 
610  // This main loop runs the entire build process.
611  // It is structured like this:
612  // First, we attempt to start as many commands as allowed by the
613  // command runner.
614  // Second, we attempt to wait for / reap the next finished command.
615  while (plan_.more_to_do()) {
616  // See if we can start any more commands.
617  if (failures_allowed && command_runner_->CanRunMore()) {
618  if (Edge* edge = plan_.FindWork()) {
619  if (!StartEdge(edge, err)) {
620  Cleanup();
622  return false;
623  }
624 
625  if (edge->is_phony()) {
626  plan_.EdgeFinished(edge);
627  } else {
628  ++pending_commands;
629  }
630 
631  // We made some progress; go back to the main loop.
632  continue;
633  }
634  }
635 
636  // See if we can reap any finished commands.
637  if (pending_commands) {
638  CommandRunner::Result result;
639  if (!command_runner_->WaitForCommand(&result) ||
640  result.status == ExitInterrupted) {
641  Cleanup();
643  *err = "interrupted by user";
644  return false;
645  }
646 
647  --pending_commands;
648  if (!FinishCommand(&result, err)) {
649  Cleanup();
651  return false;
652  }
653 
654  if (!result.success()) {
655  if (failures_allowed)
656  failures_allowed--;
657  }
658 
659  // We made some progress; start the main loop over.
660  continue;
661  }
662 
663  // If we get here, we cannot make any more progress.
665  if (failures_allowed == 0) {
666  if (config_.failures_allowed > 1)
667  *err = "subcommands failed";
668  else
669  *err = "subcommand failed";
670  } else if (failures_allowed < config_.failures_allowed)
671  *err = "cannot make progress due to previous errors";
672  else
673  *err = "stuck [this is a bug]";
674 
675  return false;
676  }
677 
679  return true;
680 }
681 
682 bool Builder::StartEdge(Edge* edge, string* err) {
683  METRIC_RECORD("StartEdge");
684  if (edge->is_phony())
685  return true;
686 
687  status_->BuildEdgeStarted(edge);
688 
689  // Create directories necessary for outputs.
690  // XXX: this will block; do we care?
691  for (vector<Node*>::iterator i = edge->outputs_.begin();
692  i != edge->outputs_.end(); ++i) {
693  if (!disk_interface_->MakeDirs((*i)->path()))
694  return false;
695  }
696 
697  // Create response file, if needed
698  // XXX: this may also block; do we care?
699  string rspfile = edge->GetUnescapedRspfile();
700  if (!rspfile.empty()) {
701  string content = edge->GetBinding("rspfile_content");
702  if (!disk_interface_->WriteFile(rspfile, content))
703  return false;
704  }
705 
706  // start command computing and run it
707  if (!command_runner_->StartCommand(edge)) {
708  err->assign("command '" + edge->EvaluateCommand() + "' failed.");
709  return false;
710  }
711 
712  return true;
713 }
714 
715 bool Builder::FinishCommand(CommandRunner::Result* result, string* err) {
716  METRIC_RECORD("FinishCommand");
717 
718  Edge* edge = result->edge;
719 
720  // First try to extract dependencies from the result, if any.
721  // This must happen first as it filters the command output (we want
722  // to filter /showIncludes output, even on compile failure) and
723  // extraction itself can fail, which makes the command fail from a
724  // build perspective.
725  vector<Node*> deps_nodes;
726  string deps_type = edge->GetBinding("deps");
727  const string deps_prefix = edge->GetBinding("msvc_deps_prefix");
728  if (!deps_type.empty()) {
729  string extract_err;
730  if (!ExtractDeps(result, deps_type, deps_prefix, &deps_nodes,
731  &extract_err) &&
732  result->success()) {
733  if (!result->output.empty())
734  result->output.append("\n");
735  result->output.append(extract_err);
736  result->status = ExitFailure;
737  }
738  }
739 
740  int start_time, end_time;
741  status_->BuildEdgeFinished(edge, result->success(), result->output,
742  &start_time, &end_time);
743 
744  // The rest of this function only applies to successful commands.
745  if (!result->success())
746  return true;
747 
748  // Restat the edge outputs, if necessary.
749  TimeStamp restat_mtime = 0;
750  if (edge->GetBindingBool("restat") && !config_.dry_run) {
751  bool node_cleaned = false;
752 
753  for (vector<Node*>::iterator i = edge->outputs_.begin();
754  i != edge->outputs_.end(); ++i) {
755  TimeStamp new_mtime = disk_interface_->Stat((*i)->path());
756  if ((*i)->mtime() == new_mtime) {
757  // The rule command did not change the output. Propagate the clean
758  // state through the build graph.
759  // Note that this also applies to nonexistent outputs (mtime == 0).
760  plan_.CleanNode(&scan_, *i);
761  node_cleaned = true;
762  }
763  }
764 
765  if (node_cleaned) {
766  // If any output was cleaned, find the most recent mtime of any
767  // (existing) non-order-only input or the depfile.
768  for (vector<Node*>::iterator i = edge->inputs_.begin();
769  i != edge->inputs_.end() - edge->order_only_deps_; ++i) {
770  TimeStamp input_mtime = disk_interface_->Stat((*i)->path());
771  if (input_mtime > restat_mtime)
772  restat_mtime = input_mtime;
773  }
774 
775  string depfile = edge->GetUnescapedDepfile();
776  if (restat_mtime != 0 && deps_type.empty() && !depfile.empty()) {
777  TimeStamp depfile_mtime = disk_interface_->Stat(depfile);
778  if (depfile_mtime > restat_mtime)
779  restat_mtime = depfile_mtime;
780  }
781 
782  // The total number of edges in the plan may have changed as a result
783  // of a restat.
785  }
786  }
787 
788  plan_.EdgeFinished(edge);
789 
790  // Delete any left over response file.
791  string rspfile = edge->GetUnescapedRspfile();
792  if (!rspfile.empty() && !g_keep_rsp)
793  disk_interface_->RemoveFile(rspfile);
794 
795  if (scan_.build_log()) {
796  if (!scan_.build_log()->RecordCommand(edge, start_time, end_time,
797  restat_mtime)) {
798  *err = string("Error writing to build log: ") + strerror(errno);
799  return false;
800  }
801  }
802 
803  if (!deps_type.empty() && !config_.dry_run) {
804  assert(edge->outputs_.size() == 1 && "should have been rejected by parser");
805  Node* out = edge->outputs_[0];
806  TimeStamp deps_mtime = disk_interface_->Stat(out->path());
807  if (!scan_.deps_log()->RecordDeps(out, deps_mtime, deps_nodes)) {
808  *err = string("Error writing to deps log: ") + strerror(errno);
809  return false;
810  }
811  }
812  return true;
813 }
814 
816  const string& deps_type,
817  const string& deps_prefix,
818  vector<Node*>* deps_nodes,
819  string* err) {
820 #ifdef _WIN32
821  if (deps_type == "msvc") {
822  CLParser parser;
823  result->output = parser.Parse(result->output, deps_prefix);
824  for (set<string>::iterator i = parser.includes_.begin();
825  i != parser.includes_.end(); ++i) {
826  deps_nodes->push_back(state_->GetNode(*i));
827  }
828  } else
829 #endif
830  if (deps_type == "gcc") {
831  string depfile = result->edge->GetUnescapedDepfile();
832  if (depfile.empty()) {
833  *err = string("edge with deps=gcc but no depfile makes no sense");
834  return false;
835  }
836 
837  string content = disk_interface_->ReadFile(depfile, err);
838  if (!err->empty())
839  return false;
840  if (content.empty())
841  return true;
842 
843  DepfileParser deps;
844  if (!deps.Parse(&content, err))
845  return false;
846 
847  // XXX check depfile matches expected output.
848  deps_nodes->reserve(deps.ins_.size());
849  for (vector<StringPiece>::iterator i = deps.ins_.begin();
850  i != deps.ins_.end(); ++i) {
851  if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err))
852  return false;
853  deps_nodes->push_back(state_->GetNode(*i));
854  }
855 
856  if (disk_interface_->RemoveFile(depfile) < 0) {
857  *err = string("deleting depfile: ") + strerror(errno) + string("\n");
858  return false;
859  }
860  } else {
861  Fatal("unknown deps type '%s'", deps_type.c_str());
862  }
863 
864  return true;
865 }
SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
Definition: subprocess.h:75
bool is_phony() const
Definition: graph.cc:323
virtual string ReadFile(const string &path, string *err)=0
Read a file to a string. Fill in |err| on error.
CommandRunner is an interface that wraps running the build subcommands.
Definition: build.h:103
Verbosity verbosity
Definition: build.h:133
SubprocessSet subprocs_
Definition: build.cc:474
map< Subprocess *, Edge * > subproc_to_edge_
Definition: build.cc:475
int order_only_deps_
Definition: graph.h:182
void BuildEdgeFinished(Edge *edge, bool success, const string &output, int *start_time, int *end_time)
Definition: build.cc:105
BuildStatus(const BuildConfig &config)
Definition: build.cc:74
TimeStamp mtime() const
Definition: graph.h:74
virtual ~RealCommandRunner()
Definition: build.cc:466
double Elapsed() const
Definition: build.h:240
RateInfo overall_rate_
Definition: build.h:279
Subprocess * NextFinished()
double max_load_average
The maximum load average we must not exceed.
Definition: build.h:139
bool more_to_do() const
Returns true if there's more work to be done.
Definition: build.h:54
Parser for the dependency information emitted by gcc's -M flags.
SlidingRateInfo current_rate_
Definition: build.h:280
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)
Definition: state.cc:114
Plan()
Definition: build.cc:261
void UpdateRate(int edges)
Definition: build.h:243
bool RecomputeDirty(Edge *edge, string *err)
Examine inputs, outputs, and command lines to judge whether an edge needs to be re-run, and update outputs_ready_ and each outputs' |dirty_| state accordingly.
Definition: graph.cc:60
set< Edge * > ready_
Definition: build.h:91
bool AddSubTarget(Node *node, vector< Node * > *stack, string *err)
Definition: build.cc:268
The result of waiting for a command.
Definition: build.h:109
string GetUnescapedRspfile()
Like GetBinding("rspfile"), but without shell escaping.
Definition: graph.cc:297
void set_dirty(bool dirty)
Definition: graph.h:77
bool AddTarget(Node *node, string *err)
Add a target to our plan (including all its dependencies).
Definition: build.cc:263
bool MakeDirs(const string &path)
Create all the parent directories for path; like mkdir -p basename path.
Information about a node in the dependency graph: the file, whether it's dirty, mtime, etc.
Definition: graph.h:35
bool success() const
Definition: build.h:114
Edge * FindWork()
Definition: build.cc:339
virtual bool StartCommand(Edge *edge)
Definition: build.cc:496
void ResumeDelayedJobs(Edge *edge)
Allows jobs blocking on |edge| to potentially resume.
Definition: build.cc:365
void ScheduleWork(Edge *edge)
Submits a ready edge as a candidate for execution.
Definition: build.cc:348
bool Parse(string *content, string *err)
Parse an input file.
bool ShouldDelayEdge() const
true if the Pool might delay this edge
Definition: state.h:49
bool StatIfNecessary(DiskInterface *disk_interface)
Return true if we needed to stat.
Definition: graph.h:47
State * state_
Definition: build.h:176
Interface for accessing the disk.
bool RecomputeOutputsDirty(Edge *edge, Node *most_recent_input)
Recompute whether any output of the edge is dirty.
Definition: graph.cc:133
const BuildConfig & config_
Definition: build.h:177
Edge * in_edge() const
Definition: graph.h:80
bool is_smart_terminal() const
Definition: line_printer.h:27
int64_t GetTimeMillis()
Get the current time as relative to some epoch.
Definition: metrics.cc:124
int finished_edges_
Definition: build.h:218
bool GetBindingBool(const string &key)
Definition: graph.cc:288
void PrintOnNewLine(const string &to_print)
Prints a string on a new line, not overprinting previous output.
const BuildConfig & config_
Definition: build.h:213
int TimeStamp
Definition: timestamp.h:22
void CleanNode(DependencyScan *scan, Node *node)
Clean the given node during the build.
Definition: build.cc:409
bool outputs_ready() const
Definition: graph.h:171
bool ExtractDeps(CommandRunner::Result *result, const string &deps_type, const string &deps_prefix, vector< Node * > *deps_nodes, string *err)
Definition: build.cc:815
Pool * pool() const
Definition: graph.h:169
An edge in the dependency graph; links between Nodes using Rules.
Definition: graph.h:137
void UpdateRate(int update_hint)
Definition: build.h:259
Store a log of every command ran for every build.
Definition: build_log.h:42
int started_edges_
Definition: build.h:218
virtual bool WaitForCommand(Result *result)
Wait for a command to complete, or return false if interrupted.
Definition: build.cc:506
string EvaluateCommand(bool incl_rsp_file=false)
Expand all variables in a command and return it as a string.
Definition: graph.cc:273
bool AlreadyUpToDate() const
Returns true if the build targets are already up to date.
Definition: build.cc:591
vector< Subprocess * > running_
Definition: subprocess.h:84
const BuildConfig & config_
Definition: build.cc:473
void BuildEdgeStarted(Edge *edge)
Definition: build.cc:94
DiskInterface * disk_interface_
Definition: build.h:187
bool CanonicalizePath(string *path, string *err)
Canonicalize a path like "foo/../bar.h" into just "bar.h".
Definition: util.cc:88
ExitStatus Finish()
Returns ExitSuccess on successful process exit, ExitInterrupted if the process was interrupted...
int command_edge_count() const
Number of edges with commands to run.
Definition: build.h:67
void EdgeFinished(Edge *edge)
Mark an edge as done building.
Definition: build.cc:370
virtual bool WriteFile(const string &path, const string &contents)=0
Create a file, with the specified name and contents Returns true on success, false on failure...
vector< Node * > inputs_
Definition: graph.h:162
As build commands run they can output extra dependency information (e.g.
Definition: deps_log.h:66
signed long long int64_t
A 64-bit integer type.
Definition: win32port.h:21
const string & GetOutput() const
double GetLoadAverage()
Definition: util.cc:424
bool outputs_ready_
Definition: graph.h:165
int parallelism
Definition: build.h:135
int failures_allowed
Definition: build.h:136
Builder(State *state, const BuildConfig &config, BuildLog *build_log, DepsLog *deps_log, DiskInterface *disk_interface)
Definition: build.cc:525
Subprocess * Add(const string &command, bool use_console=false)
BuildLog * build_log() const
Definition: graph.h:255
Subprocess wraps a single async subprocess.
Definition: subprocess.h:35
~Builder()
Definition: build.cc:533
map< Edge *, bool > want_
Keep track of which edges we want to build in this plan.
Definition: build.h:89
bool dirty() const
Definition: graph.h:76
bool FinishCommand(CommandRunner::Result *result, string *err)
Update status ninja logs following a command termination.
Definition: build.cc:715
virtual vector< Edge * > GetActiveEdges()
Definition: build.cc:478
int64_t start_time_millis_
Time the build started.
Definition: build.h:216
virtual void Abort()
Definition: build.cc:486
bool use_console() const
Definition: graph.cc:327
int total_edges_
Definition: build.h:218
int wanted_edges_
Total remaining number of wanted edges.
Definition: build.h:97
void set_smart_terminal(bool smart)
Definition: line_printer.h:28
ExitStatus status
Definition: build.h:112
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:537
vector< StringPiece > ins_
A pool for delayed edges.
Definition: state.h:39
void SetConsoleLocked(bool locked)
Lock or unlock the console.
#define METRIC_RECORD(name)
The primary interface to metrics.
Definition: metrics.h:85
auto_ptr< CommandRunner > command_runner_
Definition: build.h:179
const string & path() const
Definition: graph.h:73
void RetrieveReadyEdges(set< Edge * > *ready_queue)
Pool will add zero or more edges to the ready_queue.
Definition: state.cc:41
void PlanHasTotalEdges(int total)
Definition: build.cc:90
void NodeFinished(Node *node)
Definition: build.cc:388
bool CheckDependencyCycle(Node *node, vector< Node * > *stack, string *err)
Definition: build.cc:319
string StripAnsiEscapeCodes(const string &in)
Removes all Ansi escape codes (http://www.termsys.demon.co.uk/vtansi.htm).
Definition: util.cc:384
void Fatal(const char *msg,...)
Log a fatal message and exit.
Definition: util.cc:52
Tracks the status of a build: completion fraction, printing updates.
Definition: build.h:196
const char * progress_status_format_
The custom progress status format to use.
Definition: build.h:228
Plan plan_
Definition: build.h:178
string GetBinding(const string &key)
Returns the shell-escaped value of |key|.
Definition: graph.cc:283
Visual Studio's cl.exe requires some massaging to work with Ninja; for example, it emits include info...
Definition: msvc_helper.h:26
DependencyScan manages the process of scanning the files in a graph and updating the dirty/outputs_re...
Definition: graph.h:238
void PrintStatus(Edge *edge)
Definition: build.cc:241
set< string > includes_
Definition: msvc_helper.h:47
string Parse(const string &output, const string &deps_prefix)
Parse the full output of cl, returning the output (if any) that should printed.
void BuildFinished()
Definition: build.cc:153
bool RecordCommand(Edge *edge, int start_time, int end_time, TimeStamp restat_mtime=0)
Definition: build_log.cc:140
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
virtual int RemoveFile(const string &path)=0
Remove the file named path.
virtual bool CanRunMore()
Definition: build.cc:490
Options (e.g. verbosity, parallelism) passed to a build.
Definition: build.h:124
Global state (file status, loaded rules) for a single run.
Definition: state.h:83
bool g_keep_rsp
Definition: debug_flags.cc:17
bool StartEdge(Edge *edge, string *err)
Definition: build.cc:682
bool AllInputsReady() const
Return true if all inputs' in-edges are ready.
Definition: graph.cc:207
void Dump()
Dumps the current state of the plan.
Definition: build.cc:454
void Print(string to_print, LineType type)
Overprints the current line.
Definition: line_printer.cc:45
bool RecordDeps(Node *node, TimeStamp mtime, const vector< Node * > &nodes)
Definition: deps_log.cc:80
string GetUnescapedDepfile()
Like GetBinding("depfile"), but without shell escaping.
Definition: graph.cc:292
RunningEdgeMap running_edges_
Definition: build.h:222
virtual TimeStamp Stat(const string &path) const =0
stat() a file, returning the mtime, or 0 if missing and -1 on other errors.
bool Build(string *err)
Run the build.
Definition: build.cc:595
BuildStatus * status_
Definition: build.h:180
string FormatProgressStatus(const char *progress_status_format) const
Format the progress status string by replacing the placeholders.
Definition: build.cc:158
LinePrinter printer_
Prints progress output.
Definition: build.h:225
Node * AddTarget(const string &name, string *err)
Definition: build.cc:565
bool dry_run
Definition: build.h:134
DependencyScan scan_
Definition: build.h:188
const vector< Edge * > & out_edges() const
Definition: graph.h:86
int command_edges_
Total number of edges that have commands (not phony).
Definition: build.h:94
void snprinfRate(double rate, char(&buf)[S], const char *format) const
Definition: build.h:231
DepsLog * deps_log() const
Definition: graph.h:262
Node * LookupNode(StringPiece path) const
Definition: state.cc:123
RealCommandRunner(const BuildConfig &config)
Definition: build.cc:465
vector< Node * > outputs_
Definition: graph.h:163