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  size_t subproc_number =
492  subprocs_.running_.size() + subprocs_.finished_.size();
493  return (int)subproc_number < config_.parallelism
494  && ((subprocs_.running_.empty() || config_.max_load_average <= 0.0f)
496 }
497 
499  string command = edge->EvaluateCommand();
500  Subprocess* subproc = subprocs_.Add(command, edge->use_console());
501  if (!subproc)
502  return false;
503  subproc_to_edge_.insert(make_pair(subproc, edge));
504 
505  return true;
506 }
507 
509  Subprocess* subproc;
510  while ((subproc = subprocs_.NextFinished()) == NULL) {
511  bool interrupted = subprocs_.DoWork();
512  if (interrupted)
513  return false;
514  }
515 
516  result->status = subproc->Finish();
517  result->output = subproc->GetOutput();
518 
519  map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);
520  result->edge = i->second;
521  subproc_to_edge_.erase(i);
522 
523  delete subproc;
524  return true;
525 }
526 
527 Builder::Builder(State* state, const BuildConfig& config,
528  BuildLog* build_log, DepsLog* deps_log,
529  DiskInterface* disk_interface)
530  : state_(state), config_(config), disk_interface_(disk_interface),
531  scan_(state, build_log, deps_log, disk_interface) {
532  status_ = new BuildStatus(config);
533 }
534 
536  Cleanup();
537 }
538 
540  if (command_runner_.get()) {
541  vector<Edge*> active_edges = command_runner_->GetActiveEdges();
542  command_runner_->Abort();
543 
544  for (vector<Edge*>::iterator i = active_edges.begin();
545  i != active_edges.end(); ++i) {
546  string depfile = (*i)->GetUnescapedDepfile();
547  for (vector<Node*>::iterator ni = (*i)->outputs_.begin();
548  ni != (*i)->outputs_.end(); ++ni) {
549  // Only delete this output if it was actually modified. This is
550  // important for things like the generator where we don't want to
551  // delete the manifest file if we can avoid it. But if the rule
552  // uses a depfile, always delete. (Consider the case where we
553  // need to rebuild an output because of a modified header file
554  // mentioned in a depfile, and the command touches its depfile
555  // but is interrupted before it touches its output file.)
556  if (!depfile.empty() ||
557  (*ni)->mtime() != disk_interface_->Stat((*ni)->path())) {
558  disk_interface_->RemoveFile((*ni)->path());
559  }
560  }
561  if (!depfile.empty())
562  disk_interface_->RemoveFile(depfile);
563  }
564  }
565 }
566 
567 Node* Builder::AddTarget(const string& name, string* err) {
568  Node* node = state_->LookupNode(name);
569  if (!node) {
570  *err = "unknown target: '" + name + "'";
571  return NULL;
572  }
573  if (!AddTarget(node, err))
574  return NULL;
575  return node;
576 }
577 
578 bool Builder::AddTarget(Node* node, string* err) {
580  if (Edge* in_edge = node->in_edge()) {
581  if (!scan_.RecomputeDirty(in_edge, err))
582  return false;
583  if (in_edge->outputs_ready())
584  return true; // Nothing to do.
585  }
586 
587  if (!plan_.AddTarget(node, err))
588  return false;
589 
590  return true;
591 }
592 
594  return !plan_.more_to_do();
595 }
596 
597 bool Builder::Build(string* err) {
598  assert(!AlreadyUpToDate());
599 
601  int pending_commands = 0;
602  int failures_allowed = config_.failures_allowed;
603 
604  // Set up the command runner if we haven't done so already.
605  if (!command_runner_.get()) {
606  if (config_.dry_run)
607  command_runner_.reset(new DryRunCommandRunner);
608  else
610  }
611 
612  // This main loop runs the entire build process.
613  // It is structured like this:
614  // First, we attempt to start as many commands as allowed by the
615  // command runner.
616  // Second, we attempt to wait for / reap the next finished command.
617  while (plan_.more_to_do()) {
618  // See if we can start any more commands.
619  if (failures_allowed && command_runner_->CanRunMore()) {
620  if (Edge* edge = plan_.FindWork()) {
621  if (!StartEdge(edge, err)) {
622  Cleanup();
624  return false;
625  }
626 
627  if (edge->is_phony()) {
628  plan_.EdgeFinished(edge);
629  } else {
630  ++pending_commands;
631  }
632 
633  // We made some progress; go back to the main loop.
634  continue;
635  }
636  }
637 
638  // See if we can reap any finished commands.
639  if (pending_commands) {
640  CommandRunner::Result result;
641  if (!command_runner_->WaitForCommand(&result) ||
642  result.status == ExitInterrupted) {
643  Cleanup();
645  *err = "interrupted by user";
646  return false;
647  }
648 
649  --pending_commands;
650  if (!FinishCommand(&result, err)) {
651  Cleanup();
653  return false;
654  }
655 
656  if (!result.success()) {
657  if (failures_allowed)
658  failures_allowed--;
659  }
660 
661  // We made some progress; start the main loop over.
662  continue;
663  }
664 
665  // If we get here, we cannot make any more progress.
667  if (failures_allowed == 0) {
668  if (config_.failures_allowed > 1)
669  *err = "subcommands failed";
670  else
671  *err = "subcommand failed";
672  } else if (failures_allowed < config_.failures_allowed)
673  *err = "cannot make progress due to previous errors";
674  else
675  *err = "stuck [this is a bug]";
676 
677  return false;
678  }
679 
681  return true;
682 }
683 
684 bool Builder::StartEdge(Edge* edge, string* err) {
685  METRIC_RECORD("StartEdge");
686  if (edge->is_phony())
687  return true;
688 
689  status_->BuildEdgeStarted(edge);
690 
691  // Create directories necessary for outputs.
692  // XXX: this will block; do we care?
693  for (vector<Node*>::iterator i = edge->outputs_.begin();
694  i != edge->outputs_.end(); ++i) {
695  if (!disk_interface_->MakeDirs((*i)->path()))
696  return false;
697  }
698 
699  // Create response file, if needed
700  // XXX: this may also block; do we care?
701  string rspfile = edge->GetUnescapedRspfile();
702  if (!rspfile.empty()) {
703  string content = edge->GetBinding("rspfile_content");
704  if (!disk_interface_->WriteFile(rspfile, content))
705  return false;
706  }
707 
708  // start command computing and run it
709  if (!command_runner_->StartCommand(edge)) {
710  err->assign("command '" + edge->EvaluateCommand() + "' failed.");
711  return false;
712  }
713 
714  return true;
715 }
716 
717 bool Builder::FinishCommand(CommandRunner::Result* result, string* err) {
718  METRIC_RECORD("FinishCommand");
719 
720  Edge* edge = result->edge;
721 
722  // First try to extract dependencies from the result, if any.
723  // This must happen first as it filters the command output (we want
724  // to filter /showIncludes output, even on compile failure) and
725  // extraction itself can fail, which makes the command fail from a
726  // build perspective.
727  vector<Node*> deps_nodes;
728  string deps_type = edge->GetBinding("deps");
729  const string deps_prefix = edge->GetBinding("msvc_deps_prefix");
730  if (!deps_type.empty()) {
731  string extract_err;
732  if (!ExtractDeps(result, deps_type, deps_prefix, &deps_nodes,
733  &extract_err) &&
734  result->success()) {
735  if (!result->output.empty())
736  result->output.append("\n");
737  result->output.append(extract_err);
738  result->status = ExitFailure;
739  }
740  }
741 
742  int start_time, end_time;
743  status_->BuildEdgeFinished(edge, result->success(), result->output,
744  &start_time, &end_time);
745 
746  // The rest of this function only applies to successful commands.
747  if (!result->success())
748  return true;
749 
750  // Restat the edge outputs, if necessary.
751  TimeStamp restat_mtime = 0;
752  if (edge->GetBindingBool("restat") && !config_.dry_run) {
753  bool node_cleaned = false;
754 
755  for (vector<Node*>::iterator i = edge->outputs_.begin();
756  i != edge->outputs_.end(); ++i) {
757  TimeStamp new_mtime = disk_interface_->Stat((*i)->path());
758  if ((*i)->mtime() == new_mtime) {
759  // The rule command did not change the output. Propagate the clean
760  // state through the build graph.
761  // Note that this also applies to nonexistent outputs (mtime == 0).
762  plan_.CleanNode(&scan_, *i);
763  node_cleaned = true;
764  }
765  }
766 
767  if (node_cleaned) {
768  // If any output was cleaned, find the most recent mtime of any
769  // (existing) non-order-only input or the depfile.
770  for (vector<Node*>::iterator i = edge->inputs_.begin();
771  i != edge->inputs_.end() - edge->order_only_deps_; ++i) {
772  TimeStamp input_mtime = disk_interface_->Stat((*i)->path());
773  if (input_mtime > restat_mtime)
774  restat_mtime = input_mtime;
775  }
776 
777  string depfile = edge->GetUnescapedDepfile();
778  if (restat_mtime != 0 && deps_type.empty() && !depfile.empty()) {
779  TimeStamp depfile_mtime = disk_interface_->Stat(depfile);
780  if (depfile_mtime > restat_mtime)
781  restat_mtime = depfile_mtime;
782  }
783 
784  // The total number of edges in the plan may have changed as a result
785  // of a restat.
787  }
788  }
789 
790  plan_.EdgeFinished(edge);
791 
792  // Delete any left over response file.
793  string rspfile = edge->GetUnescapedRspfile();
794  if (!rspfile.empty() && !g_keep_rsp)
795  disk_interface_->RemoveFile(rspfile);
796 
797  if (scan_.build_log()) {
798  if (!scan_.build_log()->RecordCommand(edge, start_time, end_time,
799  restat_mtime)) {
800  *err = string("Error writing to build log: ") + strerror(errno);
801  return false;
802  }
803  }
804 
805  if (!deps_type.empty() && !config_.dry_run) {
806  assert(edge->outputs_.size() == 1 && "should have been rejected by parser");
807  Node* out = edge->outputs_[0];
808  TimeStamp deps_mtime = disk_interface_->Stat(out->path());
809  if (!scan_.deps_log()->RecordDeps(out, deps_mtime, deps_nodes)) {
810  *err = string("Error writing to deps log: ") + strerror(errno);
811  return false;
812  }
813  }
814  return true;
815 }
816 
818  const string& deps_type,
819  const string& deps_prefix,
820  vector<Node*>* deps_nodes,
821  string* err) {
822 #ifdef _WIN32
823  if (deps_type == "msvc") {
824  CLParser parser;
825  result->output = parser.Parse(result->output, deps_prefix);
826  for (set<string>::iterator i = parser.includes_.begin();
827  i != parser.includes_.end(); ++i) {
828  // ~0 is assuming that with MSVC-parsed headers, it's ok to always make
829  // all backslashes (as some of the slashes will certainly be backslashes
830  // anyway). This could be fixed if necessary with some additional
831  // complexity in IncludesNormalize::Relativize.
832  deps_nodes->push_back(state_->GetNode(*i, ~0u));
833  }
834  } else
835 #endif
836  if (deps_type == "gcc") {
837  string depfile = result->edge->GetUnescapedDepfile();
838  if (depfile.empty()) {
839  *err = string("edge with deps=gcc but no depfile makes no sense");
840  return false;
841  }
842 
843  string content = disk_interface_->ReadFile(depfile, err);
844  if (!err->empty())
845  return false;
846  if (content.empty())
847  return true;
848 
849  DepfileParser deps;
850  if (!deps.Parse(&content, err))
851  return false;
852 
853  // XXX check depfile matches expected output.
854  deps_nodes->reserve(deps.ins_.size());
855  for (vector<StringPiece>::iterator i = deps.ins_.begin();
856  i != deps.ins_.end(); ++i) {
857  unsigned int slash_bits;
858  if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits,
859  err))
860  return false;
861  deps_nodes->push_back(state_->GetNode(*i, slash_bits));
862  }
863 
864  if (disk_interface_->RemoveFile(depfile) < 0) {
865  *err = string("deleting depfile: ") + strerror(errno) + string("\n");
866  return false;
867  }
868  } else {
869  Fatal("unknown deps type '%s'", deps_type.c_str());
870  }
871 
872  return true;
873 }
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:191
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:78
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
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:81
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:498
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:48
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:84
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.
bool CanonicalizePath(string *path, unsigned int *slash_bits, string *err)
Canonicalize a path like "foo/../bar.h" into just "bar.h".
Definition: util.cc:88
const BuildConfig & config_
Definition: build.h:213
int TimeStamp
Definition: timestamp.h:22
Node * GetNode(StringPiece path, unsigned int slash_bits)
Definition: state.cc:114
void CleanNode(DependencyScan *scan, Node *node)
Clean the given node during the build.
Definition: build.cc:409
bool outputs_ready() const
Definition: graph.h:180
bool ExtractDeps(CommandRunner::Result *result, const string &deps_type, const string &deps_prefix, vector< Node * > *deps_nodes, string *err)
Definition: build.cc:817
Pool * pool() const
Definition: graph.h:178
An edge in the dependency graph; links between Nodes using Rules.
Definition: graph.h:146
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:508
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:593
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
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:171
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:574
bool outputs_ready_
Definition: graph.h:174
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:527
Subprocess * Add(const string &command, bool use_console=false)
BuildLog * build_log() const
Definition: graph.h:264
Subprocess wraps a single async subprocess.
Definition: subprocess.h:35
~Builder()
Definition: build.cc:535
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:80
bool FinishCommand(CommandRunner::Result *result, string *err)
Update status ninja logs following a command termination.
Definition: build.cc:717
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:539
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:74
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:474
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:247
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
queue< Subprocess * > finished_
Definition: subprocess.h:85
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:684
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:46
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:597
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:567
bool dry_run
Definition: build.h:134
DependencyScan scan_
Definition: build.h:188
const vector< Edge * > & out_edges() const
Definition: graph.h:90
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:271
Node * LookupNode(StringPiece path) const
Definition: state.cc:123
RealCommandRunner(const BuildConfig &config)
Definition: build.cc:465
vector< Node * > outputs_
Definition: graph.h:172