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 METRIC_RECORD("node stat");
32 return (mtime_ = disk_interface->Stat(path_, err)) != -1;
35 bool DependencyScan::RecomputeDirty(Edge* edge, string* err) {
37 edge->outputs_ready_ = true;
38 edge->deps_missing_ = false;
40 // RecomputeDirty() recursively walks the graph following the input nodes
41 // of |edge| and the in_edges of these nodes. It uses the stat state of each
42 // node to mark nodes as visited and doesn't traverse across nodes that have
43 // been visited already. To make sure that every edge is visited only once
44 // (important because an edge's deps are loaded every time it's visited), mark
45 // all outputs of |edge| visited as a first step. This ensures that edges
46 // with multiple inputs and outputs are visited only once, even in cyclic
48 for (vector<Node*>::iterator o = edge->outputs_.begin();
49 o != edge->outputs_.end(); ++o) {
50 if (!(*o)->StatIfNecessary(disk_interface_, err))
54 if (!dep_loader_.LoadDeps(edge, err)) {
57 // Failed to load dependency info: rebuild to regenerate it.
58 // LoadDeps() did EXPLAIN() already, no need to do it here.
59 dirty = edge->deps_missing_ = true;
62 // Visit all inputs; we're dirty if any of the inputs are dirty.
63 Node* most_recent_input = NULL;
64 for (vector<Node*>::iterator i = edge->inputs_.begin();
65 i != edge->inputs_.end(); ++i) {
66 if (!(*i)->status_known()) {
67 if (!(*i)->StatIfNecessary(disk_interface_, err))
69 if (Edge* in_edge = (*i)->in_edge()) {
70 if (!RecomputeDirty(in_edge, err))
73 // This input has no in-edge; it is dirty if it is missing.
75 EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str());
76 (*i)->set_dirty(!(*i)->exists());
80 // If an input is not ready, neither are our outputs.
81 if (Edge* in_edge = (*i)->in_edge()) {
82 if (!in_edge->outputs_ready_)
83 edge->outputs_ready_ = false;
86 if (!edge->is_order_only(i - edge->inputs_.begin())) {
87 // If a regular input is dirty (or missing), we're dirty.
88 // Otherwise consider mtime.
90 EXPLAIN("%s is dirty", (*i)->path().c_str());
93 if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) {
94 most_recent_input = *i;
100 // We may also be dirty due to output state: missing outputs, out of
101 // date outputs, etc. Visit all outputs and determine whether they're dirty.
103 if (!RecomputeOutputsDirty(edge, most_recent_input, &dirty, err))
106 // Finally, visit each output and update their dirty state if necessary.
107 for (vector<Node*>::iterator o = edge->outputs_.begin();
108 o != edge->outputs_.end(); ++o) {
113 // If an edge is dirty, its outputs are normally not ready. (It's
114 // possible to be clean but still not be ready in the presence of
115 // order-only inputs.)
116 // But phony edges with no inputs have nothing to do, so are always
118 if (dirty && !(edge->is_phony() && edge->inputs_.empty()))
119 edge->outputs_ready_ = false;
124 bool DependencyScan::RecomputeOutputsDirty(Edge* edge, Node* most_recent_input,
125 bool* outputs_dirty, string* err) {
126 string command = edge->EvaluateCommand(/*incl_rsp_file=*/true);
127 for (vector<Node*>::iterator o = edge->outputs_.begin();
128 o != edge->outputs_.end(); ++o) {
129 if (!(*o)->StatIfNecessary(disk_interface_, err))
131 if (RecomputeOutputDirty(edge, most_recent_input, command, *o)) {
132 *outputs_dirty = true;
139 bool DependencyScan::RecomputeOutputDirty(Edge* edge,
140 Node* most_recent_input,
141 const string& command,
143 if (edge->is_phony()) {
144 // Phony edges don't write any output. Outputs are only dirty if
145 // there are no inputs and we're missing the output.
146 if (edge->inputs_.empty() && !output->exists()) {
147 EXPLAIN("output %s of phony edge with no inputs doesn't exist",
148 output->path().c_str());
154 BuildLog::LogEntry* entry = 0;
156 // Dirty if we're missing the output.
157 if (!output->exists()) {
158 EXPLAIN("output %s doesn't exist", output->path().c_str());
162 // Dirty if the output is older than the input.
163 if (most_recent_input && output->mtime() < most_recent_input->mtime()) {
164 TimeStamp output_mtime = output->mtime();
166 // If this is a restat rule, we may have cleaned the output with a restat
167 // rule in a previous run and stored the most recent input mtime in the
168 // build log. Use that mtime instead, so that the file will only be
169 // considered dirty if an input was modified since the previous run.
170 bool used_restat = false;
171 if (edge->GetBindingBool("restat") && build_log() &&
172 (entry = build_log()->LookupByOutput(output->path()))) {
173 output_mtime = entry->restat_mtime;
177 if (output_mtime < most_recent_input->mtime()) {
178 EXPLAIN("%soutput %s older than most recent input %s "
180 used_restat ? "restat of " : "", output->path().c_str(),
181 most_recent_input->path().c_str(),
182 output_mtime, most_recent_input->mtime());
187 // May also be dirty due to the command changing since the last build.
188 // But if this is a generator rule, the command changing does not make us
190 if (!edge->GetBindingBool("generator") && build_log()) {
191 if (entry || (entry = build_log()->LookupByOutput(output->path()))) {
192 if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) {
193 EXPLAIN("command line changed for %s", output->path().c_str());
198 EXPLAIN("command line not found in log for %s", output->path().c_str());
206 bool Edge::AllInputsReady() const {
207 for (vector<Node*>::const_iterator i = inputs_.begin();
208 i != inputs_.end(); ++i) {
209 if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready())
215 /// An Env for an Edge, providing $in and $out.
216 struct EdgeEnv : public Env {
217 enum EscapeKind { kShellEscape, kDoNotEscape };
219 EdgeEnv(Edge* edge, EscapeKind escape)
220 : edge_(edge), escape_in_out_(escape), recursive_(false) {}
221 virtual string LookupVariable(const string& var);
223 /// Given a span of Nodes, construct a list of paths suitable for a command
225 string MakePathList(vector<Node*>::iterator begin,
226 vector<Node*>::iterator end,
230 vector<string> lookups_;
232 EscapeKind escape_in_out_;
236 string EdgeEnv::LookupVariable(const string& var) {
237 if (var == "in" || var == "in_newline") {
238 int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ -
239 edge_->order_only_deps_;
240 return MakePathList(edge_->inputs_.begin(),
241 edge_->inputs_.begin() + explicit_deps_count,
242 var == "in" ? ' ' : '\n');
243 } else if (var == "out") {
244 int explicit_outs_count = edge_->outputs_.size() - edge_->implicit_outs_;
245 return MakePathList(edge_->outputs_.begin(),
246 edge_->outputs_.begin() + explicit_outs_count,
251 vector<string>::const_iterator it;
252 if ((it = find(lookups_.begin(), lookups_.end(), var)) != lookups_.end()) {
254 for (; it != lookups_.end(); ++it)
255 cycle.append(*it + " -> ");
257 Fatal(("cycle in rule variables: " + cycle).c_str());
261 // See notes on BindingEnv::LookupWithFallback.
262 const EvalString* eval = edge_->rule_->GetBinding(var);
263 if (recursive_ && eval)
264 lookups_.push_back(var);
266 // In practice, variables defined on rules never use another rule variable.
267 // For performance, only start checking for cycles after the first lookup.
269 return edge_->env_->LookupWithFallback(var, eval, this);
272 string EdgeEnv::MakePathList(vector<Node*>::iterator begin,
273 vector<Node*>::iterator end,
276 for (vector<Node*>::iterator i = begin; i != end; ++i) {
278 result.push_back(sep);
279 const string& path = (*i)->PathDecanonicalized();
280 if (escape_in_out_ == kShellEscape) {
282 GetWin32EscapedString(path, &result);
284 GetShellEscapedString(path, &result);
293 string Edge::EvaluateCommand(bool incl_rsp_file) {
294 string command = GetBinding("command");
296 string rspfile_content = GetBinding("rspfile_content");
297 if (!rspfile_content.empty())
298 command += ";rspfile=" + rspfile_content;
303 string Edge::GetBinding(const string& key) {
304 EdgeEnv env(this, EdgeEnv::kShellEscape);
305 return env.LookupVariable(key);
308 bool Edge::GetBindingBool(const string& key) {
309 return !GetBinding(key).empty();
312 string Edge::GetUnescapedDepfile() {
313 EdgeEnv env(this, EdgeEnv::kDoNotEscape);
314 return env.LookupVariable("depfile");
317 string Edge::GetUnescapedRspfile() {
318 EdgeEnv env(this, EdgeEnv::kDoNotEscape);
319 return env.LookupVariable("rspfile");
322 void Edge::Dump(const char* prefix) const {
323 printf("%s[ ", prefix);
324 for (vector<Node*>::const_iterator i = inputs_.begin();
325 i != inputs_.end() && *i != NULL; ++i) {
326 printf("%s ", (*i)->path().c_str());
328 printf("--%s-> ", rule_->name().c_str());
329 for (vector<Node*>::const_iterator i = outputs_.begin();
330 i != outputs_.end() && *i != NULL; ++i) {
331 printf("%s ", (*i)->path().c_str());
334 if (!pool_->name().empty()) {
335 printf("(in pool '%s')", pool_->name().c_str());
338 printf("(null pool?)");
340 printf("] 0x%p\n", this);
343 bool Edge::is_phony() const {
344 return rule_ == &State::kPhonyRule;
347 bool Edge::use_console() const {
348 return pool() == &State::kConsolePool;
352 string Node::PathDecanonicalized(const string& path, unsigned int slash_bits) {
353 string result = path;
355 unsigned int mask = 1;
356 for (char* c = &result[0]; (c = strchr(c, '/')) != NULL;) {
357 if (slash_bits & mask)
366 void Node::Dump(const char* prefix) const {
367 printf("%s <%s 0x%p> mtime: %d%s, (:%s), ",
368 prefix, path().c_str(), this,
369 mtime(), mtime() ? "" : " (:missing)",
370 dirty() ? " dirty" : " clean");
372 in_edge()->Dump("in-edge: ");
374 printf("no in-edge\n");
376 printf(" out edges:\n");
377 for (vector<Edge*>::const_iterator e = out_edges().begin();
378 e != out_edges().end() && *e != NULL; ++e) {
383 bool ImplicitDepLoader::LoadDeps(Edge* edge, string* err) {
384 string deps_type = edge->GetBinding("deps");
385 if (!deps_type.empty())
386 return LoadDepsFromLog(edge, err);
388 string depfile = edge->GetUnescapedDepfile();
389 if (!depfile.empty())
390 return LoadDepFile(edge, depfile, err);
396 bool ImplicitDepLoader::LoadDepFile(Edge* edge, const string& path,
398 METRIC_RECORD("depfile load");
399 // Read depfile content. Treat a missing depfile as empty.
401 switch (disk_interface_->ReadFile(path, &content, err)) {
402 case DiskInterface::Okay:
404 case DiskInterface::NotFound:
407 case DiskInterface::OtherError:
408 *err = "loading '" + path + "': " + *err;
411 // On a missing depfile: return false and empty *err.
412 if (content.empty()) {
413 EXPLAIN("depfile '%s' is missing", path.c_str());
417 DepfileParser depfile;
419 if (!depfile.Parse(&content, &depfile_err)) {
420 *err = path + ": " + depfile_err;
425 if (!CanonicalizePath(const_cast<char*>(depfile.out_.str_),
426 &depfile.out_.len_, &unused, err))
429 // Check that this depfile matches the edge's output, if not return false to
430 // mark the edge as dirty.
431 Node* first_output = edge->outputs_[0];
432 StringPiece opath = StringPiece(first_output->path());
433 if (opath != depfile.out_) {
434 EXPLAIN("expected depfile '%s' to mention '%s', got '%s'", path.c_str(),
435 first_output->path().c_str(), depfile.out_.AsString().c_str());
439 // Preallocate space in edge->inputs_ to be filled in below.
440 vector<Node*>::iterator implicit_dep =
441 PreallocateSpace(edge, depfile.ins_.size());
443 // Add all its in-edges.
444 for (vector<StringPiece>::iterator i = depfile.ins_.begin();
445 i != depfile.ins_.end(); ++i, ++implicit_dep) {
446 unsigned int slash_bits;
447 if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits,
451 Node* node = state_->GetNode(*i, slash_bits);
452 *implicit_dep = node;
453 node->AddOutEdge(edge);
454 CreatePhonyInEdge(node);
460 bool ImplicitDepLoader::LoadDepsFromLog(Edge* edge, string* err) {
461 // NOTE: deps are only supported for single-target edges.
462 Node* output = edge->outputs_[0];
463 DepsLog::Deps* deps = deps_log_->GetDeps(output);
465 EXPLAIN("deps for '%s' are missing", output->path().c_str());
469 // Deps are invalid if the output is newer than the deps.
470 if (output->mtime() > deps->mtime) {
471 EXPLAIN("stored deps info out of date for '%s' (%d vs %d)",
472 output->path().c_str(), deps->mtime, output->mtime());
476 vector<Node*>::iterator implicit_dep =
477 PreallocateSpace(edge, deps->node_count);
478 for (int i = 0; i < deps->node_count; ++i, ++implicit_dep) {
479 Node* node = deps->nodes[i];
480 *implicit_dep = node;
481 node->AddOutEdge(edge);
482 CreatePhonyInEdge(node);
487 vector<Node*>::iterator ImplicitDepLoader::PreallocateSpace(Edge* edge,
489 edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_,
491 edge->implicit_deps_ += count;
492 return edge->inputs_.end() - edge->order_only_deps_ - count;
495 void ImplicitDepLoader::CreatePhonyInEdge(Node* node) {
499 Edge* phony_edge = state_->AddEdge(&State::kPhonyRule);
500 node->set_in_edge(phony_edge);
501 phony_edge->outputs_.push_back(node);
503 // RecomputeDirty might not be called for phony_edge if a previous call
504 // to RecomputeDirty had caused the file to be stat'ed. Because previous
505 // invocations of RecomputeDirty would have seen this node without an
506 // input edge (and therefore ready), we have to set outputs_ready_ to true
507 // to avoid a potential stuck build. If we do call RecomputeDirty for
508 // this node, it will simply set outputs_ready_ to the correct value.
509 phony_edge->outputs_ready_ = true;