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 <stdint.h>
20#include <stdio.h>
21#include <stdlib.h>
22
23#include <functional>
24#include <unordered_set>
25
26#if defined(__SVR4) && defined(__sun)
27#include <sys/termios.h>
28#endif
29
30#include "build_log.h"
31#include "clparser.h"
32#include "debug_flags.h"
33#include "depfile_parser.h"
34#include "deps_log.h"
35#include "disk_interface.h"
36#include "exit_status.h"
37#include "explanations.h"
38#include "graph.h"
39#include "jobserver.h"
40#include "metrics.h"
41#include "state.h"
42#include "status.h"
43#include "util.h"
44
45using namespace std;
46
47namespace {
48
49/// A CommandRunner that doesn't actually run the commands.
50struct DryRunCommandRunner : public CommandRunner {
51 // Overridden from CommandRunner:
52 size_t CanRunMore() const override;
53 bool StartCommand(Edge* edge) override;
54 bool WaitForCommand(Result* result) override;
55
56 private:
57 queue<Edge*> finished_;
58};
59
60size_t DryRunCommandRunner::CanRunMore() const {
61 return SIZE_MAX;
62}
63
64bool DryRunCommandRunner::StartCommand(Edge* edge) {
65 finished_.push(edge);
66 return true;
67}
68
69bool DryRunCommandRunner::WaitForCommand(Result* result) {
70 if (finished_.empty())
71 return false;
72
73 result->status = ExitSuccess;
74 result->edge = finished_.front();
75 finished_.pop();
76 return true;
77}
78
79} // namespace
80
82 : builder_(builder)
84 , wanted_edges_(0)
85{}
86
89 wanted_edges_ = 0;
90 ready_.clear();
91 want_.clear();
92}
93
94bool Plan::AddTarget(const Node* target, string* err) {
95 targets_.push_back(target);
96 return AddSubTarget(target, NULL, err, NULL);
97}
98
99bool Plan::AddSubTarget(const Node* node, const Node* dependent, string* err,
100 set<Edge*>* dyndep_walk) {
101 Edge* edge = node->in_edge();
102 if (!edge) {
103 // Leaf node, this can be either a regular input from the manifest
104 // (e.g. a source file), or an implicit input from a depfile or dyndep
105 // file. In the first case, a dirty flag means the file is missing,
106 // and the build should stop. In the second, do not do anything here
107 // since there is no producing edge to add to the plan.
108 if (node->dirty() && !node->generated_by_dep_loader()) {
109 string referenced;
110 if (dependent)
111 referenced = ", needed by '" + dependent->path() + "',";
112 *err = "'" + node->path() + "'" + referenced +
113 " missing and no known rule to make it";
114 }
115 return false;
116 }
117
118 if (edge->outputs_ready())
119 return false; // Don't need to do anything.
120
121 // If an entry in want_ does not already exist for edge, create an entry which
122 // maps to kWantNothing, indicating that we do not want to build this entry itself.
123 pair<map<Edge*, Want>::iterator, bool> want_ins =
124 want_.insert(make_pair(edge, kWantNothing));
125 Want& want = want_ins.first->second;
126
127 if (dyndep_walk && want == kWantToFinish)
128 return false; // Don't need to do anything with already-scheduled edge.
129
130 // If we do need to build edge and we haven't already marked it as wanted,
131 // mark it now.
132 if (node->dirty() && want == kWantNothing) {
133 want = kWantToStart;
134 EdgeWanted(edge);
135 }
136
137 if (dyndep_walk)
138 dyndep_walk->insert(edge);
139
140 if (!want_ins.second)
141 return true; // We've already processed the inputs.
142
143 for (vector<Node*>::iterator i = edge->inputs_.begin();
144 i != edge->inputs_.end(); ++i) {
145 if (!AddSubTarget(*i, node, err, dyndep_walk) && !err->empty())
146 return false;
147 }
148
149 return true;
150}
151
152void Plan::EdgeWanted(const Edge* edge) {
154 if (!edge->is_phony()) {
156 if (builder_)
157 builder_->status_->EdgeAddedToPlan(edge);
158 }
159}
160
162 if (ready_.empty())
163 return NULL;
164
165 Edge* work = ready_.top();
166
167 // If jobserver mode is enabled, try to acquire a token first,
168 // and return null in case of failure.
169 if (builder_ && builder_->jobserver_.get()) {
170 work->job_slot_ = builder_->jobserver_->TryAcquire();
171 if (!work->job_slot_.IsValid())
172 return nullptr;
173 }
174
175 ready_.pop();
176 return work;
177}
178
179void Plan::ScheduleWork(map<Edge*, Want>::iterator want_e) {
180 if (want_e->second == kWantToFinish) {
181 // This edge has already been scheduled. We can get here again if an edge
182 // and one of its dependencies share an order-only input, or if a node
183 // duplicates an out edge (see https://github.com/ninja-build/ninja/pull/519).
184 // Avoid scheduling the work again.
185 return;
186 }
187 assert(want_e->second == kWantToStart);
188 want_e->second = kWantToFinish;
189
190 Edge* edge = want_e->first;
191 Pool* pool = edge->pool();
192 if (pool->ShouldDelayEdge()) {
193 pool->DelayEdge(edge);
195 } else {
196 pool->EdgeScheduled(*edge);
197 ready_.push(edge);
198 }
199}
200
201bool Plan::EdgeFinished(Edge* edge, EdgeResult result, string* err) {
202 map<Edge*, Want>::iterator e = want_.find(edge);
203 assert(e != want_.end());
204 bool directly_wanted = e->second != kWantNothing;
205
206 // See if this job frees up any delayed jobs.
207 if (directly_wanted)
208 edge->pool()->EdgeFinished(*edge);
209 edge->pool()->RetrieveReadyEdges(&ready_);
210
211 // Release job slot if needed.
212 if (builder_ && builder_->jobserver_.get())
213 builder_->jobserver_->Release(std::move(edge->job_slot_));
214
215 // The rest of this function only applies to successful commands.
216 if (result != kEdgeSucceeded)
217 return true;
218
219 if (directly_wanted)
221 want_.erase(e);
222 edge->outputs_ready_ = true;
223
224 // Check off any nodes we were waiting for with this edge.
225 for (vector<Node*>::iterator o = edge->outputs_.begin();
226 o != edge->outputs_.end(); ++o) {
227 if (!NodeFinished(*o, err))
228 return false;
229 }
230 return true;
231}
232
233bool Plan::NodeFinished(Node* node, string* err) {
234 // If this node provides dyndep info, load it now.
235 if (node->dyndep_pending()) {
236 assert(builder_ && "dyndep requires Plan to have a Builder");
237 // Load the now-clean dyndep file. This will also update the
238 // build plan and schedule any new work that is ready.
239 return builder_->LoadDyndeps(node, err);
240 }
241
242 // See if we we want any edges from this node.
243 for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
244 oe != node->out_edges().end(); ++oe) {
245 map<Edge*, Want>::iterator want_e = want_.find(*oe);
246 if (want_e == want_.end())
247 continue;
248
249 // See if the edge is now ready.
250 if (!EdgeMaybeReady(want_e, err))
251 return false;
252 }
253 return true;
254}
255
256bool Plan::EdgeMaybeReady(map<Edge*, Want>::iterator want_e, string* err) {
257 Edge* edge = want_e->first;
258 if (edge->AllInputsReady()) {
259 if (want_e->second != kWantNothing) {
260 ScheduleWork(want_e);
261 } else {
262 // We do not need to build this edge, but we might need to build one of
263 // its dependents.
264 if (!EdgeFinished(edge, kEdgeSucceeded, err))
265 return false;
266 }
267 }
268 return true;
269}
270
271bool Plan::CleanNode(DependencyScan* scan, Node* node, string* err) {
272 node->set_dirty(false);
273
274 for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
275 oe != node->out_edges().end(); ++oe) {
276 // Don't process edges that we don't actually want.
277 map<Edge*, Want>::iterator want_e = want_.find(*oe);
278 if (want_e == want_.end() || want_e->second == kWantNothing)
279 continue;
280
281 // Don't attempt to clean an edge if it failed to load deps.
282 if ((*oe)->deps_missing_)
283 continue;
284
285 // If all non-order-only inputs for this edge are now clean,
286 // we might have changed the dirty state of the outputs.
287 vector<Node*>::iterator
288 begin = (*oe)->inputs_.begin(),
289 end = (*oe)->inputs_.end() - (*oe)->order_only_deps_;
290#if __cplusplus < 201703L
291#define MEM_FN mem_fun
292#else
293#define MEM_FN mem_fn // mem_fun was removed in C++17.
294#endif
295 if (find_if(begin, end, MEM_FN(&Node::dirty)) == end) {
296 // Recompute most_recent_input.
297 Node* most_recent_input = NULL;
298 for (vector<Node*>::iterator i = begin; i != end; ++i) {
299 if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime())
300 most_recent_input = *i;
301 }
302
303 // Now, this edge is dirty if any of the outputs are dirty.
304 // If the edge isn't dirty, clean the outputs and mark the edge as not
305 // wanted.
306 bool outputs_dirty = false;
307 if (!scan->RecomputeOutputsDirty(*oe, most_recent_input,
308 &outputs_dirty, err)) {
309 return false;
310 }
311 if (!outputs_dirty) {
312 for (vector<Node*>::iterator o = (*oe)->outputs_.begin();
313 o != (*oe)->outputs_.end(); ++o) {
314 if (!CleanNode(scan, *o, err))
315 return false;
316 }
317
318 want_e->second = kWantNothing;
320 if (!(*oe)->is_phony()) {
322 if (builder_)
323 builder_->status_->EdgeRemovedFromPlan(*oe);
324 }
325 }
326 }
327 }
328 return true;
329}
330
332 const DyndepFile& ddf, string* err) {
333 // Recompute the dirty state of all our direct and indirect dependents now
334 // that our dyndep information has been loaded.
335 if (!RefreshDyndepDependents(scan, node, err))
336 return false;
337
338 // We loaded dyndep information for those out_edges of the dyndep node that
339 // specify the node in a dyndep binding, but they may not be in the plan.
340 // Starting with those already in the plan, walk newly-reachable portion
341 // of the graph through the dyndep-discovered dependencies.
342
343 // Find edges in the the build plan for which we have new dyndep info.
344 std::vector<DyndepFile::const_iterator> dyndep_roots;
345 for (DyndepFile::const_iterator oe = ddf.begin(); oe != ddf.end(); ++oe) {
346 Edge* edge = oe->first;
347
348 // If the edge outputs are ready we do not need to consider it here.
349 if (edge->outputs_ready())
350 continue;
351
352 map<Edge*, Want>::iterator want_e = want_.find(edge);
353
354 // If the edge has not been encountered before then nothing already in the
355 // plan depends on it so we do not need to consider the edge yet either.
356 if (want_e == want_.end())
357 continue;
358
359 // This edge is already in the plan so queue it for the walk.
360 dyndep_roots.push_back(oe);
361 }
362
363 // Walk dyndep-discovered portion of the graph to add it to the build plan.
364 std::set<Edge*> dyndep_walk;
365 for (std::vector<DyndepFile::const_iterator>::iterator
366 oei = dyndep_roots.begin(); oei != dyndep_roots.end(); ++oei) {
367 DyndepFile::const_iterator oe = *oei;
368 for (vector<Node*>::const_iterator i = oe->second.implicit_inputs_.begin();
369 i != oe->second.implicit_inputs_.end(); ++i) {
370 if (!AddSubTarget(*i, oe->first->outputs_[0], err, &dyndep_walk) &&
371 !err->empty())
372 return false;
373 }
374 }
375
376 // Add out edges from this node that are in the plan (just as
377 // Plan::NodeFinished would have without taking the dyndep code path).
378 for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
379 oe != node->out_edges().end(); ++oe) {
380 map<Edge*, Want>::iterator want_e = want_.find(*oe);
381 if (want_e == want_.end())
382 continue;
383 dyndep_walk.insert(want_e->first);
384 }
385
386 // See if any encountered edges are now ready.
387 for (set<Edge*>::iterator wi = dyndep_walk.begin();
388 wi != dyndep_walk.end(); ++wi) {
389 map<Edge*, Want>::iterator want_e = want_.find(*wi);
390 if (want_e == want_.end())
391 continue;
392 if (!EdgeMaybeReady(want_e, err))
393 return false;
394 }
395
396 return true;
397}
398
400 string* err) {
401 // Collect the transitive closure of dependents and mark their edges
402 // as not yet visited by RecomputeDirty.
403 set<Node*> dependents;
404 UnmarkDependents(node, &dependents);
405
406 // Update the dirty state of all dependents and check if their edges
407 // have become wanted.
408 for (set<Node*>::iterator i = dependents.begin();
409 i != dependents.end(); ++i) {
410 Node* n = *i;
411
412 // Check if this dependent node is now dirty. Also checks for new cycles.
413 std::vector<Node*> validation_nodes;
414 if (!scan->RecomputeDirty(n, &validation_nodes, err))
415 return false;
416
417 // Add any validation nodes found during RecomputeDirty as new top level
418 // targets.
419 for (std::vector<Node*>::iterator v = validation_nodes.begin();
420 v != validation_nodes.end(); ++v) {
421 if (Edge* in_edge = (*v)->in_edge()) {
422 if (!in_edge->outputs_ready() &&
423 !AddTarget(*v, err)) {
424 return false;
425 }
426 }
427 }
428 if (!n->dirty())
429 continue;
430
431 // This edge was encountered before. However, we may not have wanted to
432 // build it if the outputs were not known to be dirty. With dyndep
433 // information an output is now known to be dirty, so we want the edge.
434 Edge* edge = n->in_edge();
435 assert(edge && !edge->outputs_ready());
436 map<Edge*, Want>::iterator want_e = want_.find(edge);
437 assert(want_e != want_.end());
438 if (want_e->second == kWantNothing) {
439 want_e->second = kWantToStart;
440 EdgeWanted(edge);
441 }
442 }
443 return true;
444}
445
446void Plan::UnmarkDependents(const Node* node, set<Node*>* dependents) {
447 for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
448 oe != node->out_edges().end(); ++oe) {
449 Edge* edge = *oe;
450
451 map<Edge*, Want>::iterator want_e = want_.find(edge);
452 if (want_e == want_.end())
453 continue;
454
455 if (edge->mark_ != Edge::VisitNone) {
456 edge->mark_ = Edge::VisitNone;
457 for (vector<Node*>::iterator o = edge->outputs_.begin();
458 o != edge->outputs_.end(); ++o) {
459 if (dependents->insert(*o).second)
460 UnmarkDependents(*o, dependents);
461 }
462 }
463 }
464}
465
466namespace {
467
468// Heuristic for edge priority weighting.
469// Phony edges are free (0 cost), all other edges are weighted equally.
470int64_t EdgeWeightHeuristic(Edge *edge) {
471 return edge->is_phony() ? 0 : 1;
472}
473
474} // namespace
475
477 METRIC_RECORD("ComputeCriticalPath");
478
479 // Convenience class to perform a topological sort of all edges
480 // reachable from a set of unique targets. Usage is:
481 //
482 // 1) Create instance.
483 //
484 // 2) Call VisitTarget() as many times as necessary.
485 // Note that duplicate targets are properly ignored.
486 //
487 // 3) Call result() to get a sorted list of edges,
488 // where each edge appears _after_ its parents,
489 // i.e. the edges producing its inputs, in the list.
490 //
491 struct TopoSort {
492 void VisitTarget(const Node* target) {
493 Edge* producer = target->in_edge();
494 if (producer)
495 Visit(producer);
496 }
497
498 const std::vector<Edge*>& result() const { return sorted_edges_; }
499
500 private:
501 // Implementation note:
502 //
503 // This is the regular depth-first-search algorithm described
504 // at https://en.wikipedia.org/wiki/Topological_sorting, except
505 // that:
506 //
507 // - Edges are appended to the end of the list, for performance
508 // reasons. Hence the order used in result().
509 //
510 // - Since the graph cannot have any cycles, temporary marks
511 // are not necessary, and a simple set is used to record
512 // which edges have already been visited.
513 //
514 void Visit(Edge* edge) {
515 auto insertion = visited_set_.emplace(edge);
516 if (!insertion.second)
517 return;
518
519 for (const Node* input : edge->inputs_) {
520 Edge* producer = input->in_edge();
521 if (producer)
522 Visit(producer);
523 }
524 sorted_edges_.push_back(edge);
525 }
526
527 std::unordered_set<Edge*> visited_set_;
528 std::vector<Edge*> sorted_edges_;
529 };
530
531 TopoSort topo_sort;
532 for (const Node* target : targets_) {
533 topo_sort.VisitTarget(target);
534 }
535
536 const auto& sorted_edges = topo_sort.result();
537
538 // First, reset all weights to 1.
539 for (Edge* edge : sorted_edges)
540 edge->set_critical_path_weight(EdgeWeightHeuristic(edge));
541
542 // Second propagate / increment weights from
543 // children to parents. Scan the list
544 // in reverse order to do so.
545 for (auto reverse_it = sorted_edges.rbegin();
546 reverse_it != sorted_edges.rend(); ++reverse_it) {
547 Edge* edge = *reverse_it;
548 int64_t edge_weight = edge->critical_path_weight();
549
550 for (const Node* input : edge->inputs_) {
551 Edge* producer = input->in_edge();
552 if (!producer)
553 continue;
554
555 int64_t producer_weight = producer->critical_path_weight();
556 int64_t candidate_weight = edge_weight + EdgeWeightHeuristic(producer);
557 if (candidate_weight > producer_weight)
558 producer->set_critical_path_weight(candidate_weight);
559 }
560 }
561}
562
564 // Add ready edges to queue.
565 assert(ready_.empty());
566 std::set<Pool*> pools;
567
568 for (std::map<Edge*, Plan::Want>::iterator it = want_.begin(),
569 end = want_.end(); it != end; ++it) {
570 Edge* edge = it->first;
571 Plan::Want want = it->second;
572 if (want == kWantToStart && edge->AllInputsReady()) {
573 Pool* pool = edge->pool();
574 if (pool->ShouldDelayEdge()) {
575 pool->DelayEdge(edge);
576 pools.insert(pool);
577 } else {
578 ScheduleWork(it);
579 }
580 }
581 }
582
583 // Call RetrieveReadyEdges only once at the end so higher priority
584 // edges are retrieved first, not the ones that happen to be first
585 // in the want_ map.
586 for (std::set<Pool*>::iterator it=pools.begin(),
587 end = pools.end(); it != end; ++it) {
588 (*it)->RetrieveReadyEdges(&ready_);
589 }
590}
591
596
597void Plan::Dump() const {
598 printf("pending: %d\n", (int)want_.size());
599 for (map<Edge*, Want>::const_iterator e = want_.begin(); e != want_.end(); ++e) {
600 if (e->second != kWantNothing)
601 printf("want ");
602 e->first->Dump();
603 }
604 printf("ready: %d\n", (int)ready_.size());
605}
606
607Builder::Builder(State* state, const BuildConfig& config, BuildLog* build_log,
608 DepsLog* deps_log, DiskInterface* disk_interface,
609 Status* status, int64_t start_time_millis)
610 : state_(state), config_(config), plan_(this), status_(status),
611 start_time_millis_(start_time_millis), disk_interface_(disk_interface),
612 explanations_(g_explaining ? new Explanations() : nullptr),
613 scan_(state, build_log, deps_log, disk_interface,
614 &config_.depfile_parser_options, explanations_.get()) {
615 lock_file_path_ = ".ninja_lock";
616 string build_dir = state_->bindings_.LookupVariable("builddir");
617 if (!build_dir.empty())
618 lock_file_path_ = build_dir + "/" + lock_file_path_;
619 status_->SetExplanations(explanations_.get());
620}
621
623 Cleanup();
624 status_->SetExplanations(nullptr);
625}
626
628 if (command_runner_.get()) {
629 vector<Edge*> active_edges = command_runner_->GetActiveEdges();
630 command_runner_->Abort();
631
632 for (vector<Edge*>::iterator e = active_edges.begin();
633 e != active_edges.end(); ++e) {
634 string depfile = (*e)->GetUnescapedDepfile();
635 for (vector<Node*>::iterator o = (*e)->outputs_.begin();
636 o != (*e)->outputs_.end(); ++o) {
637 // Only delete this output if it was actually modified. This is
638 // important for things like the generator where we don't want to
639 // delete the manifest file if we can avoid it. But if the rule
640 // uses a depfile, always delete. (Consider the case where we
641 // need to rebuild an output because of a modified header file
642 // mentioned in a depfile, and the command touches its depfile
643 // but is interrupted before it touches its output file.)
644 string err;
645 TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), &err);
646 if (new_mtime == -1) // Log and ignore Stat() errors.
647 status_->Error("%s", err.c_str());
648 if (!depfile.empty() || (*o)->mtime() != new_mtime)
649 disk_interface_->RemoveFile((*o)->path());
650 }
651 if (!depfile.empty())
652 disk_interface_->RemoveFile(depfile);
653 }
654 }
655
656 string err;
657 if (disk_interface_->Stat(lock_file_path_, &err) > 0)
658 disk_interface_->RemoveFile(lock_file_path_);
659}
660
661Node* Builder::AddTarget(const string& name, string* err) {
662 Node* node = state_->LookupNode(name);
663 if (!node) {
664 *err = "unknown target: '" + name + "'";
665 return NULL;
666 }
667 if (!AddTarget(node, err))
668 return NULL;
669 return node;
670}
671
672bool Builder::AddTarget(Node* target, string* err) {
673 std::vector<Node*> validation_nodes;
674 if (!scan_.RecomputeDirty(target, &validation_nodes, err))
675 return false;
676
677 Edge* in_edge = target->in_edge();
678 if (!in_edge || !in_edge->outputs_ready()) {
679 if (!plan_.AddTarget(target, err)) {
680 return false;
681 }
682 }
683
684 // Also add any validation nodes found during RecomputeDirty as top level
685 // targets.
686 for (std::vector<Node*>::iterator n = validation_nodes.begin();
687 n != validation_nodes.end(); ++n) {
688 if (Edge* validation_in_edge = (*n)->in_edge()) {
689 if (!validation_in_edge->outputs_ready() &&
690 !plan_.AddTarget(*n, err)) {
691 return false;
692 }
693 }
694 }
695
696 return true;
697}
698
700 return !plan_.more_to_do();
701}
702
704 assert(!AlreadyUpToDate());
705 plan_.PrepareQueue();
706
707 int pending_commands = 0;
708 int failures_allowed = config_.failures_allowed;
709
710 // Set up the command runner if we haven't done so already.
711 if (!command_runner_.get()) {
712 if (config_.dry_run)
713 command_runner_.reset(new DryRunCommandRunner);
714 else
716 ;
717 }
718
719 // We are about to start the build process.
720 status_->BuildStarted();
721
722 // This main loop runs the entire build process.
723 // It is structured like this:
724 // First, we attempt to start as many commands as allowed by the
725 // command runner.
726 // Second, we attempt to wait for / reap the next finished command.
727 while (plan_.more_to_do()) {
728 // See if we can start any more commands.
729 if (failures_allowed) {
730 size_t capacity = command_runner_->CanRunMore();
731 while (capacity > 0) {
732 Edge* edge = plan_.FindWork();
733 if (!edge)
734 break;
735
736 if (edge->GetBindingBool("generator")) {
737 scan_.build_log()->Close();
738 }
739
740 if (!StartEdge(edge, err)) {
741 Cleanup();
742 status_->BuildFinished();
743 return ExitFailure;
744 }
745
746 if (edge->is_phony()) {
747 if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
748 Cleanup();
749 status_->BuildFinished();
750 return ExitFailure;
751 }
752 } else {
753 ++pending_commands;
754
755 --capacity;
756
757 // Re-evaluate capacity.
758 size_t current_capacity = command_runner_->CanRunMore();
759 if (current_capacity < capacity)
760 capacity = current_capacity;
761 }
762 }
763
764 // We are finished with all work items and have no pending
765 // commands. Therefore, break out of the main loop.
766 if (pending_commands == 0 && !plan_.more_to_do()) break;
767 }
768
769 // See if we can reap any finished commands.
770 if (pending_commands) {
772 if (!command_runner_->WaitForCommand(&result) ||
773 result.status == ExitInterrupted) {
774 Cleanup();
775 status_->BuildFinished();
776 *err = "interrupted by user";
777 return result.status;
778 }
779
780 --pending_commands;
781 bool command_finished = FinishCommand(&result, err);
782 SetFailureCode(result.status);
783 if (!command_finished) {
784 Cleanup();
785 status_->BuildFinished();
786 if (result.success()) {
787 // If the command pretend succeeded, the status wasn't set to a proper exit code,
788 // so we set it to ExitFailure.
789 result.status = ExitFailure;
790 SetFailureCode(result.status);
791 }
792 return result.status;
793 }
794
795 if (!result.success()) {
796 if (failures_allowed)
797 failures_allowed--;
798 }
799
800 // We made some progress; start the main loop over.
801 continue;
802 }
803
804 // If we get here, we cannot make any more progress.
805 status_->BuildFinished();
806 if (failures_allowed == 0) {
807 if (config_.failures_allowed > 1)
808 *err = "subcommands failed";
809 else
810 *err = "subcommand failed";
811 } else if (failures_allowed < config_.failures_allowed)
812 *err = "cannot make progress due to previous errors";
813 else
814 *err = "stuck [this is a bug]";
815
816 return GetExitCode();
817 }
818
819 status_->BuildFinished();
820 return ExitSuccess;
821}
822
823bool Builder::StartEdge(Edge* edge, string* err) {
824 METRIC_RECORD("StartEdge");
825 if (edge->is_phony())
826 return true;
827
828 int64_t start_time_millis = GetTimeMillis() - start_time_millis_;
829 running_edges_.insert(make_pair(edge, start_time_millis));
830
831 status_->BuildEdgeStarted(edge, start_time_millis);
832
833 TimeStamp build_start = config_.dry_run ? 0 : -1;
834
835 // Create directories necessary for outputs and remember the current
836 // filesystem mtime to record later
837 // XXX: this will block; do we care?
838 for (vector<Node*>::iterator o = edge->outputs_.begin();
839 o != edge->outputs_.end(); ++o) {
840 if (!disk_interface_->MakeDirs((*o)->path()))
841 return false;
842 if (build_start == -1) {
843 disk_interface_->WriteFile(lock_file_path_, "", false);
844 build_start = disk_interface_->Stat(lock_file_path_, err);
845 if (build_start == -1)
846 build_start = 0;
847 }
848 }
849
850 edge->command_start_time_ = build_start;
851
852 // Create depfile directory if needed.
853 // XXX: this may also block; do we care?
854 std::string depfile = edge->GetUnescapedDepfile();
855 if (!depfile.empty() && !disk_interface_->MakeDirs(depfile))
856 return false;
857
858 // Create response file, if needed
859 // XXX: this may also block; do we care?
860 string rspfile = edge->GetUnescapedRspfile();
861 if (!rspfile.empty()) {
862 string content = edge->GetBinding("rspfile_content");
863 if (!disk_interface_->WriteFile(rspfile, content, true))
864 return false;
865 }
866
867 // start command computing and run it
868 if (!command_runner_->StartCommand(edge)) {
869 err->assign("command '" + edge->EvaluateCommand() + "' failed.");
870 return false;
871 }
872
873 return true;
874}
875
877 METRIC_RECORD("FinishCommand");
878
879 Edge* edge = result->edge;
880
881 // First try to extract dependencies from the result, if any.
882 // This must happen first as it filters the command output (we want
883 // to filter /showIncludes output, even on compile failure) and
884 // extraction itself can fail, which makes the command fail from a
885 // build perspective.
886 vector<Node*> deps_nodes;
887 string deps_type = edge->GetBinding("deps");
888 const string deps_prefix = edge->GetBinding("msvc_deps_prefix");
889 if (!deps_type.empty()) {
890 string extract_err;
891 if (!ExtractDeps(result, deps_type, deps_prefix, &deps_nodes,
892 &extract_err) &&
893 result->success()) {
894 if (!result->output.empty())
895 result->output.append("\n");
896 result->output.append(extract_err);
897 result->status = ExitFailure;
898 }
899 }
900
901 int64_t start_time_millis, end_time_millis;
902 RunningEdgeMap::iterator it = running_edges_.find(edge);
903 start_time_millis = it->second;
904 end_time_millis = GetTimeMillis() - start_time_millis_;
905 running_edges_.erase(it);
906
907 status_->BuildEdgeFinished(edge, start_time_millis, end_time_millis,
908 result->status, result->output);
909
910 // The rest of this function only applies to successful commands.
911 if (!result->success()) {
912 return plan_.EdgeFinished(edge, Plan::kEdgeFailed, err);
913 }
914
915 // Restat the edge outputs
916 TimeStamp record_mtime = 0;
917 if (!config_.dry_run) {
918 const bool restat = edge->GetBindingBool("restat");
919 const bool generator = edge->GetBindingBool("generator");
920 bool node_cleaned = false;
921 record_mtime = edge->command_start_time_;
922
923 // restat and generator rules must restat the outputs after the build
924 // has finished. if record_mtime == 0, then there was an error while
925 // attempting to touch/stat the temp file when the edge started and
926 // we should fall back to recording the outputs' current mtime in the
927 // log.
928 if (record_mtime == 0 || restat || generator) {
929 for (vector<Node*>::iterator o = edge->outputs_.begin();
930 o != edge->outputs_.end(); ++o) {
931 TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), err);
932 if (new_mtime == -1)
933 return false;
934 if (new_mtime > record_mtime)
935 record_mtime = new_mtime;
936 if ((*o)->mtime() == new_mtime && restat) {
937 // The rule command did not change the output. Propagate the clean
938 // state through the build graph.
939 // Note that this also applies to nonexistent outputs (mtime == 0).
940 if (!plan_.CleanNode(&scan_, *o, err))
941 return false;
942 node_cleaned = true;
943 }
944 }
945 }
946 if (node_cleaned) {
947 record_mtime = edge->command_start_time_;
948 }
949 }
950
951 if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err))
952 return false;
953
954 // Delete any left over response file.
955 string rspfile = edge->GetUnescapedRspfile();
956 if (!rspfile.empty() && !g_keep_rsp)
957 disk_interface_->RemoveFile(rspfile);
958
959 if (scan_.build_log()) {
960 if (!scan_.build_log()->RecordCommand(
961 edge, static_cast<int>(start_time_millis),
962 static_cast<int>(end_time_millis), record_mtime)) {
963 *err = string("Error writing to build log: ") + strerror(errno);
964 return false;
965 }
966 }
967
968 if (!deps_type.empty() && !config_.dry_run) {
969 assert(!edge->outputs_.empty() && "should have been rejected by parser");
970 for (std::vector<Node*>::const_iterator o = edge->outputs_.begin();
971 o != edge->outputs_.end(); ++o) {
972 TimeStamp deps_mtime = disk_interface_->Stat((*o)->path(), err);
973 if (deps_mtime == -1)
974 return false;
975 if (!scan_.deps_log()->RecordDeps(*o, deps_mtime, deps_nodes)) {
976 *err = std::string("Error writing to deps log: ") + strerror(errno);
977 return false;
978 }
979 }
980 }
981 return true;
982}
983
985 const string& deps_type,
986 const string& deps_prefix,
987 vector<Node*>* deps_nodes,
988 string* err) {
989 if (deps_type == "msvc") {
990 CLParser parser;
991 string output;
992 if (!parser.Parse(result->output, deps_prefix, &output, err))
993 return false;
994 result->output = output;
995 for (set<string>::iterator i = parser.includes_.begin();
996 i != parser.includes_.end(); ++i) {
997 // ~0 is assuming that with MSVC-parsed headers, it's ok to always make
998 // all backslashes (as some of the slashes will certainly be backslashes
999 // anyway). This could be fixed if necessary with some additional
1000 // complexity in IncludesNormalize::Relativize.
1001 deps_nodes->push_back(state_->GetNode(*i, ~0u));
1002 }
1003 } else if (deps_type == "gcc") {
1004 string depfile = result->edge->GetUnescapedDepfile();
1005 if (depfile.empty()) {
1006 *err = string("edge with deps=gcc but no depfile makes no sense");
1007 return false;
1008 }
1009
1010 // Read depfile content. Treat a missing depfile as empty.
1011 string content;
1012 switch (disk_interface_->ReadFile(depfile, &content, err)) {
1014 break;
1016 err->clear();
1017 break;
1019 return false;
1020 }
1021 if (content.empty())
1022 return true;
1023
1024 DepfileParser deps(config_.depfile_parser_options);
1025 if (!deps.Parse(&content, err))
1026 return false;
1027
1028 // XXX check depfile matches expected output.
1029 deps_nodes->reserve(deps.ins_.size());
1030 for (vector<StringPiece>::iterator i = deps.ins_.begin();
1031 i != deps.ins_.end(); ++i) {
1032 uint64_t slash_bits;
1033 CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits);
1034 deps_nodes->push_back(state_->GetNode(*i, slash_bits));
1035 }
1036
1037 if (!g_keep_depfile) {
1038 if (disk_interface_->RemoveFile(depfile) < 0) {
1039 *err = string("deleting depfile: ") + strerror(errno) + string("\n");
1040 return false;
1041 }
1042 }
1043 } else {
1044 Fatal("unknown deps type '%s'", deps_type.c_str());
1045 }
1046
1047 return true;
1048}
1049
1050bool Builder::LoadDyndeps(Node* node, string* err) {
1051 // Load the dyndep information provided by this node.
1052 DyndepFile ddf;
1053 if (!scan_.LoadDyndeps(node, &ddf, err))
1054 return false;
1055
1056 // Update the build plan to account for dyndep modifications to the graph.
1057 if (!plan_.DyndepsLoaded(&scan_, node, ddf, err))
1058 return false;
1059
1060 return true;
1061}
1062
1064 // ExitSuccess should not overwrite any error
1065 if (code != ExitSuccess) {
1066 exit_code_ = code;
1067 }
1068}
#define MEM_FN
bool g_keep_depfile
bool g_keep_rsp
bool g_explaining
ExitStatus
Definition exit_status.h:27
@ ExitInterrupted
Definition exit_status.h:30
@ ExitFailure
Definition exit_status.h:29
@ ExitSuccess
Definition exit_status.h:28
int64_t GetTimeMillis()
Get the current time as relative to some epoch.
Definition metrics.cc:111
#define METRIC_RECORD(name)
The primary interface to metrics.
Definition metrics.h:83
Definition hash_map.h:26
Options (e.g. verbosity, parallelism) passed to a build.
Definition build.h:176
Store a log of every command ran for every build.
Definition build_log.h:45
Builder wraps the build process: starting commands, updating status.
Definition build.h:197
std::unique_ptr< Jobserver::Client > jobserver_
Definition build.h:241
std::string lock_file_path_
Definition build.h:261
State * state_
Definition build.h:238
Plan plan_
Definition build.h:240
void SetFailureCode(ExitStatus code)
Definition build.cc:1063
Builder(State *state, const BuildConfig &config, BuildLog *build_log, DepsLog *deps_log, DiskInterface *disk_interface, Status *status, int64_t start_time_millis)
Definition build.cc:607
Status * status_
Definition build.h:243
void Cleanup()
Clean up after interrupted commands by deleting output files.
Definition build.cc:627
Node * AddTarget(const std::string &name, std::string *err)
int64_t start_time_millis_
Time the build started.
Definition build.h:259
bool ExtractDeps(CommandRunner::Result *result, const std::string &deps_type, const std::string &deps_prefix, std::vector< Node * > *deps_nodes, std::string *err)
Definition build.cc:984
bool FinishCommand(CommandRunner::Result *result, std::string *err)
Update status ninja logs following a command termination.
Definition build.cc:876
ExitStatus GetExitCode() const
Returns ExitStatus or the exit code of the last failed job (doesn't need to be an enum value of ExitS...
Definition build.h:247
~Builder()
Definition build.cc:622
RunningEdgeMap running_edges_
Definition build.h:256
const BuildConfig & config_
Definition build.h:239
DiskInterface * disk_interface_
Definition build.h:262
bool AlreadyUpToDate() const
Returns true if the build targets are already up to date.
Definition build.cc:699
ExitStatus Build(std::string *err)
Run the build.
Definition build.cc:703
bool StartEdge(Edge *edge, std::string *err)
Definition build.cc:823
std::unique_ptr< CommandRunner > command_runner_
Definition build.h:242
ExitStatus exit_code_
Keep the global exit code for the build.
Definition build.h:270
std::unique_ptr< Explanations > explanations_
Definition build.h:265
DependencyScan scan_
Definition build.h:267
bool LoadDyndeps(Node *node, std::string *err)
Load the dyndep information provided by the given node.
Definition build.cc:1050
Visual Studio's cl.exe requires some massaging to work with Ninja; for example, it emits include info...
Definition clparser.h:25
std::set< std::string > includes_
Definition clparser.h:48
bool Parse(const std::string &output, const std::string &deps_prefix, std::string *filtered_output, std::string *err)
Parse the full output of cl, filling filtered_output with the text that should be printed (if any).
Definition clparser.cc:80
The result of waiting for a command.
Definition build.h:156
ExitStatus status
Definition build.h:159
bool success() const
Definition build.h:161
std::string output
Definition build.h:160
CommandRunner is an interface that wraps running the build subcommands.
Definition build.h:150
static CommandRunner * factory(const BuildConfig &config, Jobserver::Client *jobserver)
Creates the RealCommandRunner.
DependencyScan manages the process of scanning the files in a graph and updating the dirty/outputs_re...
Definition graph.h:332
bool RecomputeOutputsDirty(Edge *edge, Node *most_recent_input, bool *dirty, std::string *err)
Recompute whether any output of the edge is dirty, if so sets |*dirty|.
Definition graph.cc:265
bool RecomputeDirty(Node *node, std::vector< Node * > *validation_nodes, std::string *err)
Update the |dirty_| state of the given nodes by transitively inspecting their input edges.
Definition graph.cc:49
Parser for the dependency information emitted by gcc's -M flags.
bool Parse(std::string *content, std::string *err)
Parse an input file.
std::vector< StringPiece > ins_
As build commands run they can output extra dependency information (e.g.
Definition deps_log.h:68
Interface for accessing the disk.
Store data loaded from one dyndep file.
Definition dyndep.h:42
An edge in the dependency graph; links between Nodes using Rules.
Definition graph.h:175
std::string GetBinding(const std::string &key) const
Returns the shell-escaped value of |key|.
Definition graph.cc:511
int64_t critical_path_weight() const
Definition graph.h:209
std::vector< Node * > outputs_
Definition graph.h:217
Jobserver::Slot job_slot_
A Jobserver slot instance. Invalid by default.
Definition graph.h:268
VisitMark mark_
Definition graph.h:221
bool outputs_ready() const
Definition graph.h:233
void set_critical_path_weight(int64_t critical_path_weight)
Definition graph.h:210
@ VisitNone
Definition graph.h:177
Pool * pool() const
Definition graph.h:231
bool is_phony() const
Definition graph.cc:563
bool GetBindingBool(const std::string &key) const
Definition graph.cc:516
TimeStamp command_start_time_
Definition graph.h:228
std::string EvaluateCommand(bool incl_rsp_file=false) const
Expand all variables in a command and return it as a string.
Definition graph.cc:501
std::vector< Node * > inputs_
Definition graph.h:216
std::string GetUnescapedRspfile() const
Like GetBinding("rspfile"), but without shell escaping.
Definition graph.cc:530
std::string GetUnescapedDepfile() const
Like GetBinding("depfile"), but without shell escaping.
Definition graph.cc:520
bool AllInputsReady() const
Return true if all inputs' in-edges are ready.
Definition graph.cc:381
bool outputs_ready_
Definition graph.h:224
A class used to record a list of explanation strings associated with a given 'item' pointer.
bool IsValid() const
Return true if this instance is valid, i.e.
Definition jobserver.h:76
Information about a node in the dependency graph: the file, whether it's dirty, mtime,...
Definition graph.h:42
void set_dirty(bool dirty)
Definition graph.h:94
const std::string & path() const
Definition graph.h:82
Edge * in_edge() const
Definition graph.h:100
bool generated_by_dep_loader() const
Indicates whether this node was generated from a depfile or dyndep file, instead of being a regular i...
Definition graph.h:105
bool dirty() const
Definition graph.h:93
bool dyndep_pending() const
Definition graph.h:97
TimeStamp mtime() const
Definition graph.h:91
const std::vector< Edge * > & out_edges() const
Definition graph.h:114
bool AddSubTarget(const Node *node, const Node *dependent, std::string *err, std::set< Edge * > *dyndep_walk)
Definition build.cc:99
int command_edges_
Total number of edges that have commands (not phony).
Definition build.h:139
void Reset()
Reset state. Clears want and ready sets.
Definition build.cc:87
bool EdgeMaybeReady(std::map< Edge *, Want >::iterator want_e, std::string *err)
Definition build.cc:256
bool DyndepsLoaded(DependencyScan *scan, const Node *node, const DyndepFile &ddf, std::string *err)
Update the build plan to account for modifications made to the graph by information loaded from a dyn...
Definition build.cc:331
void ScheduleInitialEdges()
Definition build.cc:563
bool AddTarget(const Node *target, std::string *err)
Add a target to our plan (including all its dependencies).
Definition build.cc:94
int wanted_edges_
Total remaining number of wanted edges.
Definition build.h:142
void Dump() const
Dumps the current state of the plan.
Definition build.cc:597
Builder * builder_
Definition build.h:134
bool RefreshDyndepDependents(DependencyScan *scan, const Node *node, std::string *err)
Definition build.cc:399
void PrepareQueue()
Definition build.cc:592
Want
Enumerate possible steps we want for an edge.
Definition build.h:90
@ kWantNothing
We do not want to build the edge, but we might want to build one of its dependents.
Definition build.h:93
@ kWantToFinish
We want to build the edge, have scheduled it, and are waiting for it to complete.
Definition build.h:98
@ kWantToStart
We want to build the edge, but have not yet scheduled it.
Definition build.h:95
void ScheduleWork(std::map< Edge *, Want >::iterator want_e)
Submits a ready edge as a candidate for execution.
Definition build.cc:179
std::map< Edge *, Want > want_
Keep track of which edges we want to build in this plan.
Definition build.h:130
EdgePriorityQueue ready_
Definition build.h:132
void ComputeCriticalPath()
Definition build.cc:476
void EdgeWanted(const Edge *edge)
Definition build.cc:152
std::vector< const Node * > targets_
user provided targets in build order, earlier one have higher priority
Definition build.h:136
void UnmarkDependents(const Node *node, std::set< Node * > *dependents)
Definition build.cc:446
bool EdgeFinished(Edge *edge, EdgeResult result, std::string *err)
Mark an edge as done building (whether it succeeded or failed).
Definition build.cc:201
EdgeResult
Definition build.h:59
@ kEdgeSucceeded
Definition build.h:61
@ kEdgeFailed
Definition build.h:60
Edge * FindWork()
Definition build.cc:161
Plan(Builder *builder=NULL)
Definition build.cc:81
bool CleanNode(DependencyScan *scan, Node *node, std::string *err)
Clean the given node during the build.
Definition build.cc:271
bool NodeFinished(Node *node, std::string *err)
Update plan with knowledge that the given node is up to date.
Definition build.cc:233
A pool for delayed edges.
Definition state.h:40
bool ShouldDelayEdge() const
true if the Pool might delay this edge
Definition state.h:51
void DelayEdge(Edge *edge)
adds the given edge to this Pool to be delayed.
Definition state.cc:36
void RetrieveReadyEdges(EdgePriorityQueue *ready_queue)
Pool will add zero or more edges to the ready_queue.
Definition state.cc:41
void EdgeScheduled(const Edge &edge)
informs this Pool that the given edge is committed to be run.
Definition state.cc:26
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
Global state (file status) for a single run.
Definition state.h:95
Node * LookupNode(StringPiece path) const
Definition state.cc:104
Abstract interface to object that tracks the status of a build: completion fraction,...
Definition status.h:27
int64_t TimeStamp
Definition timestamp.h:31
void CanonicalizePath(string *path, uint64_t *slash_bits)
Definition util.cc:124
void Fatal(const char *msg,...)
Log a fatal message and exit.
Definition util.cc:67
unsigned long long uint64_t
Definition win32port.h:29
signed long long int64_t
A 64-bit integer type.
Definition win32port.h:28