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