1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include "build_log.h"
21 #include "debug_flags.h"
22 #include "depfile_parser.h"
24 #include "disk_interface.h"
25 #include "manifest_parser.h"
30 bool Node::Stat(DiskInterface* disk_interface, string* err) {
31 return (mtime_ = disk_interface->Stat(path_, err)) != -1;
34 bool DependencyScan::RecomputeDirty(Node* node, string* err) {
36 return RecomputeDirty(node, &stack, err);
39 bool DependencyScan::RecomputeDirty(Node* node, vector<Node*>* stack,
41 Edge* edge = node->in_edge();
43 // If we already visited this leaf node then we are done.
44 if (node->status_known())
46 // This node has no in-edge; it is dirty if it is missing.
47 if (!node->StatIfNecessary(disk_interface_, err))
50 EXPLAIN("%s has no in-edge and is missing", node->path().c_str());
51 node->set_dirty(!node->exists());
55 // If we already finished this edge then we are done.
56 if (edge->mark_ == Edge::VisitDone)
59 // If we encountered this edge earlier in the call stack we have a cycle.
60 if (!VerifyDAG(node, stack, err))
63 // Mark the edge temporarily while in the call stack.
64 edge->mark_ = Edge::VisitInStack;
65 stack->push_back(node);
68 edge->outputs_ready_ = true;
69 edge->deps_missing_ = false;
71 // Load output mtimes so we can compare them to the most recent input below.
72 for (vector<Node*>::iterator o = edge->outputs_.begin();
73 o != edge->outputs_.end(); ++o) {
74 if (!(*o)->StatIfNecessary(disk_interface_, err))
78 if (!dep_loader_.LoadDeps(edge, err)) {
81 // Failed to load dependency info: rebuild to regenerate it.
82 // LoadDeps() did EXPLAIN() already, no need to do it here.
83 dirty = edge->deps_missing_ = true;
86 // Visit all inputs; we're dirty if any of the inputs are dirty.
87 Node* most_recent_input = NULL;
88 for (vector<Node*>::iterator i = edge->inputs_.begin();
89 i != edge->inputs_.end(); ++i) {
91 if (!RecomputeDirty(*i, stack, err))
94 // If an input is not ready, neither are our outputs.
95 if (Edge* in_edge = (*i)->in_edge()) {
96 if (!in_edge->outputs_ready_)
97 edge->outputs_ready_ = false;
100 if (!edge->is_order_only(i - edge->inputs_.begin())) {
101 // If a regular input is dirty (or missing), we're dirty.
102 // Otherwise consider mtime.
104 EXPLAIN("%s is dirty", (*i)->path().c_str());
107 if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) {
108 most_recent_input = *i;
114 // We may also be dirty due to output state: missing outputs, out of
115 // date outputs, etc. Visit all outputs and determine whether they're dirty.
117 if (!RecomputeOutputsDirty(edge, most_recent_input, &dirty, err))
120 // Finally, visit each output and update their dirty state if necessary.
121 for (vector<Node*>::iterator o = edge->outputs_.begin();
122 o != edge->outputs_.end(); ++o) {
127 // If an edge is dirty, its outputs are normally not ready. (It's
128 // possible to be clean but still not be ready in the presence of
129 // order-only inputs.)
130 // But phony edges with no inputs have nothing to do, so are always
132 if (dirty && !(edge->is_phony() && edge->inputs_.empty()))
133 edge->outputs_ready_ = false;
135 // Mark the edge as finished during this walk now that it will no longer
136 // be in the call stack.
137 edge->mark_ = Edge::VisitDone;
138 assert(stack->back() == node);
144 bool DependencyScan::VerifyDAG(Node* node, vector<Node*>* stack, string* err) {
145 Edge* edge = node->in_edge();
146 assert(edge != NULL);
148 // If we have no temporary mark on the edge then we do not yet have a cycle.
149 if (edge->mark_ != Edge::VisitInStack)
152 // We have this edge earlier in the call stack. Find it.
153 vector<Node*>::iterator start = stack->begin();
154 while (start != stack->end() && (*start)->in_edge() != edge)
156 assert(start != stack->end());
158 // Make the cycle clear by reporting its start as the node at its end
159 // instead of some other output of the starting edge. For example,
160 // running 'ninja b' on
163 // should report a -> c -> a instead of b -> c -> a.
166 // Construct the error message rejecting the cycle.
167 *err = "dependency cycle: ";
168 for (vector<Node*>::const_iterator i = start; i != stack->end(); ++i) {
169 err->append((*i)->path());
172 err->append((*start)->path());
174 if ((start + 1) == stack->end() && edge->maybe_phonycycle_diagnostic()) {
175 // The manifest parser would have filtered out the self-referencing
176 // input if it were not configured to allow the error.
177 err->append(" [-w phonycycle=err]");
183 bool DependencyScan::RecomputeOutputsDirty(Edge* edge, Node* most_recent_input,
184 bool* outputs_dirty, string* err) {
185 string command = edge->EvaluateCommand(/*incl_rsp_file=*/true);
186 for (vector<Node*>::iterator o = edge->outputs_.begin();
187 o != edge->outputs_.end(); ++o) {
188 if (RecomputeOutputDirty(edge, most_recent_input, command, *o)) {
189 *outputs_dirty = true;
196 bool DependencyScan::RecomputeOutputDirty(Edge* edge,
197 Node* most_recent_input,
198 const string& command,
200 if (edge->is_phony()) {
201 // Phony edges don't write any output. Outputs are only dirty if
202 // there are no inputs and we're missing the output.
203 if (edge->inputs_.empty() && !output->exists()) {
204 EXPLAIN("output %s of phony edge with no inputs doesn't exist",
205 output->path().c_str());
211 BuildLog::LogEntry* entry = 0;
213 // Dirty if we're missing the output.
214 if (!output->exists()) {
215 EXPLAIN("output %s doesn't exist", output->path().c_str());
219 // Dirty if the output is older than the input.
220 if (most_recent_input && output->mtime() < most_recent_input->mtime()) {
221 TimeStamp output_mtime = output->mtime();
223 // If this is a restat rule, we may have cleaned the output with a restat
224 // rule in a previous run and stored the most recent input mtime in the
225 // build log. Use that mtime instead, so that the file will only be
226 // considered dirty if an input was modified since the previous run.
227 bool used_restat = false;
228 if (edge->GetBindingBool("restat") && build_log() &&
229 (entry = build_log()->LookupByOutput(output->path()))) {
230 output_mtime = entry->mtime;
234 if (output_mtime < most_recent_input->mtime()) {
235 EXPLAIN("%soutput %s older than most recent input %s "
237 used_restat ? "restat of " : "", output->path().c_str(),
238 most_recent_input->path().c_str(),
239 output_mtime, most_recent_input->mtime());
245 bool generator = edge->GetBindingBool("generator");
246 if (entry || (entry = build_log()->LookupByOutput(output->path()))) {
248 BuildLog::LogEntry::HashCommand(command) != entry->command_hash) {
249 // May also be dirty due to the command changing since the last build.
250 // But if this is a generator rule, the command changing does not make us
252 EXPLAIN("command line changed for %s", output->path().c_str());
255 if (most_recent_input && entry->mtime < most_recent_input->mtime()) {
256 // May also be dirty due to the mtime in the log being older than the
257 // mtime of the most recent input. This can occur even when the mtime
258 // on disk is newer if a previous run wrote to the output file but
259 // exited with an error or was interrupted.
260 EXPLAIN("recorded mtime of %s older than most recent input %s (%d vs %d)",
261 output->path().c_str(), most_recent_input->path().c_str(),
262 entry->mtime, most_recent_input->mtime());
266 if (!entry && !generator) {
267 EXPLAIN("command line not found in log for %s", output->path().c_str());
275 bool Edge::AllInputsReady() const {
276 for (vector<Node*>::const_iterator i = inputs_.begin();
277 i != inputs_.end(); ++i) {
278 if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready())
284 /// An Env for an Edge, providing $in and $out.
285 struct EdgeEnv : public Env {
286 enum EscapeKind { kShellEscape, kDoNotEscape };
288 EdgeEnv(Edge* edge, EscapeKind escape)
289 : edge_(edge), escape_in_out_(escape), recursive_(false) {}
290 virtual string LookupVariable(const string& var);
292 /// Given a span of Nodes, construct a list of paths suitable for a command
294 string MakePathList(vector<Node*>::iterator begin,
295 vector<Node*>::iterator end,
299 vector<string> lookups_;
301 EscapeKind escape_in_out_;
305 string EdgeEnv::LookupVariable(const string& var) {
306 if (var == "in" || var == "in_newline") {
307 int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ -
308 edge_->order_only_deps_;
309 return MakePathList(edge_->inputs_.begin(),
310 edge_->inputs_.begin() + explicit_deps_count,
311 var == "in" ? ' ' : '\n');
312 } else if (var == "out") {
313 int explicit_outs_count = edge_->outputs_.size() - edge_->implicit_outs_;
314 return MakePathList(edge_->outputs_.begin(),
315 edge_->outputs_.begin() + explicit_outs_count,
320 vector<string>::const_iterator it;
321 if ((it = find(lookups_.begin(), lookups_.end(), var)) != lookups_.end()) {
323 for (; it != lookups_.end(); ++it)
324 cycle.append(*it + " -> ");
326 Fatal(("cycle in rule variables: " + cycle).c_str());
330 // See notes on BindingEnv::LookupWithFallback.
331 const EvalString* eval = edge_->rule_->GetBinding(var);
332 if (recursive_ && eval)
333 lookups_.push_back(var);
335 // In practice, variables defined on rules never use another rule variable.
336 // For performance, only start checking for cycles after the first lookup.
338 return edge_->env_->LookupWithFallback(var, eval, this);
341 string EdgeEnv::MakePathList(vector<Node*>::iterator begin,
342 vector<Node*>::iterator end,
345 for (vector<Node*>::iterator i = begin; i != end; ++i) {
347 result.push_back(sep);
348 const string& path = (*i)->PathDecanonicalized();
349 if (escape_in_out_ == kShellEscape) {
351 GetWin32EscapedString(path, &result);
353 GetShellEscapedString(path, &result);
362 string Edge::EvaluateCommand(bool incl_rsp_file) {
363 string command = GetBinding("command");
365 string rspfile_content = GetBinding("rspfile_content");
366 if (!rspfile_content.empty())
367 command += ";rspfile=" + rspfile_content;
372 string Edge::GetBinding(const string& key) {
373 EdgeEnv env(this, EdgeEnv::kShellEscape);
374 return env.LookupVariable(key);
377 bool Edge::GetBindingBool(const string& key) {
378 return !GetBinding(key).empty();
381 string Edge::GetUnescapedDepfile() {
382 EdgeEnv env(this, EdgeEnv::kDoNotEscape);
383 return env.LookupVariable("depfile");
386 string Edge::GetUnescapedRspfile() {
387 EdgeEnv env(this, EdgeEnv::kDoNotEscape);
388 return env.LookupVariable("rspfile");
391 void Edge::Dump(const char* prefix) const {
392 printf("%s[ ", prefix);
393 for (vector<Node*>::const_iterator i = inputs_.begin();
394 i != inputs_.end() && *i != NULL; ++i) {
395 printf("%s ", (*i)->path().c_str());
397 printf("--%s-> ", rule_->name().c_str());
398 for (vector<Node*>::const_iterator i = outputs_.begin();
399 i != outputs_.end() && *i != NULL; ++i) {
400 printf("%s ", (*i)->path().c_str());
403 if (!pool_->name().empty()) {
404 printf("(in pool '%s')", pool_->name().c_str());
407 printf("(null pool?)");
409 printf("] 0x%p\n", this);
412 bool Edge::is_phony() const {
413 return rule_ == &State::kPhonyRule;
416 bool Edge::use_console() const {
417 return pool() == &State::kConsolePool;
420 bool Edge::maybe_phonycycle_diagnostic() const {
421 // CMake 2.8.12.x and 3.0.x produced self-referencing phony rules
422 // of the form "build a: phony ... a ...". Restrict our
423 // "phonycycle" diagnostic option to the form it used.
424 return is_phony() && outputs_.size() == 1 && implicit_outs_ == 0 &&
429 string Node::PathDecanonicalized(const string& path, uint64_t slash_bits) {
430 string result = path;
433 for (char* c = &result[0]; (c = strchr(c, '/')) != NULL;) {
434 if (slash_bits & mask)
443 void Node::Dump(const char* prefix) const {
444 printf("%s <%s 0x%p> mtime: %d%s, (:%s), ",
445 prefix, path().c_str(), this,
446 mtime(), mtime() ? "" : " (:missing)",
447 dirty() ? " dirty" : " clean");
449 in_edge()->Dump("in-edge: ");
451 printf("no in-edge\n");
453 printf(" out edges:\n");
454 for (vector<Edge*>::const_iterator e = out_edges().begin();
455 e != out_edges().end() && *e != NULL; ++e) {
460 bool ImplicitDepLoader::LoadDeps(Edge* edge, string* err) {
461 string deps_type = edge->GetBinding("deps");
462 if (!deps_type.empty())
463 return LoadDepsFromLog(edge, err);
465 string depfile = edge->GetUnescapedDepfile();
466 if (!depfile.empty())
467 return LoadDepFile(edge, depfile, err);
473 bool ImplicitDepLoader::LoadDepFile(Edge* edge, const string& path,
475 METRIC_RECORD("depfile load");
476 // Read depfile content. Treat a missing depfile as empty.
478 switch (disk_interface_->ReadFile(path, &content, err)) {
479 case DiskInterface::Okay:
481 case DiskInterface::NotFound:
484 case DiskInterface::OtherError:
485 *err = "loading '" + path + "': " + *err;
488 // On a missing depfile: return false and empty *err.
489 if (content.empty()) {
490 EXPLAIN("depfile '%s' is missing", path.c_str());
494 DepfileParser depfile;
496 if (!depfile.Parse(&content, &depfile_err)) {
497 *err = path + ": " + depfile_err;
502 if (!CanonicalizePath(const_cast<char*>(depfile.out_.str_),
503 &depfile.out_.len_, &unused, err)) {
504 *err = path + ": " + *err;
508 // Check that this depfile matches the edge's output, if not return false to
509 // mark the edge as dirty.
510 Node* first_output = edge->outputs_[0];
511 StringPiece opath = StringPiece(first_output->path());
512 if (opath != depfile.out_) {
513 EXPLAIN("expected depfile '%s' to mention '%s', got '%s'", path.c_str(),
514 first_output->path().c_str(), depfile.out_.AsString().c_str());
518 // Preallocate space in edge->inputs_ to be filled in below.
519 vector<Node*>::iterator implicit_dep =
520 PreallocateSpace(edge, depfile.ins_.size());
522 // Add all its in-edges.
523 for (vector<StringPiece>::iterator i = depfile.ins_.begin();
524 i != depfile.ins_.end(); ++i, ++implicit_dep) {
526 if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits,
530 Node* node = state_->GetNode(*i, slash_bits);
531 *implicit_dep = node;
532 node->AddOutEdge(edge);
533 CreatePhonyInEdge(node);
539 bool ImplicitDepLoader::LoadDepsFromLog(Edge* edge, string* err) {
540 // NOTE: deps are only supported for single-target edges.
541 Node* output = edge->outputs_[0];
542 DepsLog::Deps* deps = deps_log_->GetDeps(output);
544 EXPLAIN("deps for '%s' are missing", output->path().c_str());
548 // Deps are invalid if the output is newer than the deps.
549 if (output->mtime() > deps->mtime) {
550 EXPLAIN("stored deps info out of date for '%s' (%d vs %d)",
551 output->path().c_str(), deps->mtime, output->mtime());
555 vector<Node*>::iterator implicit_dep =
556 PreallocateSpace(edge, deps->node_count);
557 for (int i = 0; i < deps->node_count; ++i, ++implicit_dep) {
558 Node* node = deps->nodes[i];
559 *implicit_dep = node;
560 node->AddOutEdge(edge);
561 CreatePhonyInEdge(node);
566 vector<Node*>::iterator ImplicitDepLoader::PreallocateSpace(Edge* edge,
568 edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_,
570 edge->implicit_deps_ += count;
571 return edge->inputs_.end() - edge->order_only_deps_ - count;
574 void ImplicitDepLoader::CreatePhonyInEdge(Node* node) {
578 Edge* phony_edge = state_->AddEdge(&State::kPhonyRule);
579 node->set_in_edge(phony_edge);
580 phony_edge->outputs_.push_back(node);
582 // RecomputeDirty might not be called for phony_edge if a previous call
583 // to RecomputeDirty had caused the file to be stat'ed. Because previous
584 // invocations of RecomputeDirty would have seen this node without an
585 // input edge (and therefore ready), we have to set outputs_ready_ to true
586 // to avoid a potential stuck build. If we do call RecomputeDirty for
587 // this node, it will simply set outputs_ready_ to the correct value.
588 phony_edge->outputs_ready_ = true;