• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <climits>
22 #include <stdint.h>
23 #include <functional>
24 
25 #if defined(__SVR4) && defined(__sun)
26 #include <sys/termios.h>
27 #endif
28 
29 #include "build_log.h"
30 #include "clparser.h"
31 #include "debug_flags.h"
32 #include "depfile_parser.h"
33 #include "deps_log.h"
34 #include "disk_interface.h"
35 #include "graph.h"
36 #include "metrics.h"
37 #include "state.h"
38 #include "status.h"
39 #include "subprocess.h"
40 #include "util.h"
41 
42 using namespace std;
43 
44 namespace {
45 
46 /// A CommandRunner that doesn't actually run the commands.
47 struct DryRunCommandRunner : public CommandRunner {
~DryRunCommandRunner__anone437749c0111::DryRunCommandRunner48     virtual ~DryRunCommandRunner() {}
49 
50     // Overridden from CommandRunner:
51     virtual size_t CanRunMore() const;
52     virtual bool StartCommand(Edge* edge);
53     virtual bool WaitForCommand(Result* result);
54 
55     private:
56         queue<Edge*> finished_;
57 };
58 
CanRunMore() const59 size_t DryRunCommandRunner::CanRunMore() const {
60     return SIZE_MAX;
61 }
62 
StartCommand(Edge * edge)63 bool DryRunCommandRunner::StartCommand(Edge* edge) {
64     finished_.push(edge);
65     return true;
66 }
67 
WaitForCommand(Result * result)68 bool DryRunCommandRunner::WaitForCommand(Result* result) {
69     if (finished_.empty())
70         return false;
71 
72     result->status = ExitSuccess;
73     result->edge = finished_.front();
74     finished_.pop();
75     return true;
76 }
77 
78 }  // namespace
79 
Plan(Builder * builder)80 Plan::Plan(Builder* builder)
81     : builder_(builder)
82     , command_edges_(0)
83     , wanted_edges_(0)
84 {}
85 
Reset()86 void Plan::Reset() {
87     command_edges_ = 0;
88     wanted_edges_ = 0;
89     ready_.clear();
90     want_.clear();
91 }
92 
AddTarget(const Node * target,string * err)93 bool Plan::AddTarget(const Node* target, string* err) {
94     return AddSubTarget(target, NULL, err, NULL);
95 }
96 
AddSubTarget(const Node * node,const Node * dependent,string * err,set<Edge * > * dyndep_walk)97 bool Plan::AddSubTarget(const Node* node, const Node* dependent, string* err,
98                                                 set<Edge*>* dyndep_walk) {
99     Edge* edge = node->in_edge();
100     if (!edge) {
101         // Leaf node, this can be either a regular input from the manifest
102         // (e.g. a source file), or an implicit input from a depfile or dyndep
103         // file. In the first case, a dirty flag means the file is missing,
104         // and the build should stop. In the second, do not do anything here
105         // since there is no producing edge to add to the plan.
106         if (node->dirty() && !node->generated_by_dep_loader()) {
107             string referenced;
108             if (dependent)
109                 referenced = ", needed by '" + dependent->path() + "',";
110                 *err = "'" + node->path() + "'" + referenced +
111                     " missing and no known rule to make it";
112         }
113         return false;
114     }
115 
116     if (edge->outputs_ready())
117         return false;  // Don't need to do anything.
118 
119     // If an entry in want_ does not already exist for edge, create an entry which
120     // maps to kWantNothing, indicating that we do not want to build this entry itself.
121     pair<map<Edge*, Want>::iterator, bool> want_ins =
122         want_.insert(make_pair(edge, kWantNothing));
123     Want& want = want_ins.first->second;
124 
125     if (dyndep_walk && want == kWantToFinish)
126         return false;  // Don't need to do anything with already-scheduled edge.
127 
128     // If we do need to build edge and we haven't already marked it as wanted,
129     // mark it now.
130     if (node->dirty() && want == kWantNothing) {
131         want = kWantToStart;
132         EdgeWanted(edge);
133         if (!dyndep_walk && edge->AllInputsReady())
134             ScheduleWork(want_ins.first);
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 
EdgeWanted(const Edge * edge)152 void Plan::EdgeWanted(const Edge* edge) {
153     ++wanted_edges_;
154     if (!edge->is_phony()) {
155         ++command_edges_;
156         if (builder_)
157             builder_->status_->EdgeAddedToPlan(edge);
158     }
159 }
160 
FindWork()161 Edge* Plan::FindWork() {
162     if (ready_.empty())
163         return NULL;
164 
165     EdgeSet::iterator e = ready_.begin();
166     Edge* edge = *e;
167     ready_.erase(e);
168     return edge;
169 }
170 
ScheduleWork(map<Edge *,Want>::iterator want_e)171 void Plan::ScheduleWork(map<Edge*, Want>::iterator want_e) {
172     if (want_e->second == kWantToFinish) {
173         // This edge has already been scheduled.  We can get here again if an edge
174         // and one of its dependencies share an order-only input, or if a node
175         // duplicates an out edge (see https://github.com/ninja-build/ninja/pull/519).
176         // Avoid scheduling the work again.
177         return;
178     }
179     assert(want_e->second == kWantToStart);
180     want_e->second = kWantToFinish;
181 
182     Edge* edge = want_e->first;
183     Pool* pool = edge->pool();
184     if (pool->ShouldDelayEdge()) {
185         pool->DelayEdge(edge);
186         pool->RetrieveReadyEdges(&ready_);
187     } else {
188         pool->EdgeScheduled(*edge);
189         ready_.insert(edge);
190     }
191 }
192 
EdgeFinished(Edge * edge,EdgeResult result,string * err)193 bool Plan::EdgeFinished(Edge* edge, EdgeResult result, string* err) {
194     map<Edge*, Want>::iterator e = want_.find(edge);
195     assert(e != want_.end());
196     bool directly_wanted = e->second != kWantNothing;
197 
198     // See if this job frees up any delayed jobs.
199     if (directly_wanted)
200         edge->pool()->EdgeFinished(*edge);
201     edge->pool()->RetrieveReadyEdges(&ready_);
202 
203     // The rest of this function only applies to successful commands.
204     if (result != kEdgeSucceeded)
205         return true;
206 
207     if (directly_wanted)
208         --wanted_edges_;
209     want_.erase(e);
210     edge->outputs_ready_ = true;
211 
212     // Check off any nodes we were waiting for with this edge.
213     for (vector<Node*>::iterator o = edge->outputs_.begin();
214             o != edge->outputs_.end(); ++o) {
215         if (!NodeFinished(*o, err))
216             return false;
217     }
218     return true;
219 }
220 
NodeFinished(Node * node,string * err)221 bool Plan::NodeFinished(Node* node, string* err) {
222     // If this node provides dyndep info, load it now.
223     if (node->dyndep_pending()) {
224         assert(builder_ && "dyndep requires Plan to have a Builder");
225         // Load the now-clean dyndep file.  This will also update the
226         // build plan and schedule any new work that is ready.
227         return builder_->LoadDyndeps(node, err);
228     }
229 
230     // See if we we want any edges from this node.
231     for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
232             oe != node->out_edges().end(); ++oe) {
233         map<Edge*, Want>::iterator want_e = want_.find(*oe);
234         if (want_e == want_.end())
235             continue;
236 
237         // See if the edge is now ready.
238         if (!EdgeMaybeReady(want_e, err))
239             return false;
240     }
241     return true;
242 }
243 
EdgeMaybeReady(map<Edge *,Want>::iterator want_e,string * err)244 bool Plan::EdgeMaybeReady(map<Edge*, Want>::iterator want_e, string* err) {
245     Edge* edge = want_e->first;
246     if (edge->AllInputsReady()) {
247         if (want_e->second != kWantNothing) {
248             ScheduleWork(want_e);
249         } else {
250             // We do not need to build this edge, but we might need to build one of
251             // its dependents.
252             if (!EdgeFinished(edge, kEdgeSucceeded, err))
253                 return false;
254         }
255     }
256     return true;
257 }
258 
CleanNode(DependencyScan * scan,Node * node,string * err)259 bool Plan::CleanNode(DependencyScan* scan, Node* node, string* err) {
260     node->set_dirty(false);
261 
262     for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
263             oe != node->out_edges().end(); ++oe) {
264         // Don't process edges that we don't actually want.
265         map<Edge*, Want>::iterator want_e = want_.find(*oe);
266         if (want_e == want_.end() || want_e->second == kWantNothing)
267             continue;
268 
269         // Don't attempt to clean an edge if it failed to load deps.
270         if ((*oe)->deps_missing_)
271             continue;
272 
273         // If all non-order-only inputs for this edge are now clean,
274         // we might have changed the dirty state of the outputs.
275         vector<Node*>::iterator
276             begin = (*oe)->inputs_.begin(),
277             end = (*oe)->inputs_.end() - (*oe)->order_only_deps_;
278 #if __cplusplus < 201703L
279 #define MEM_FN mem_fun
280 #else
281 #define MEM_FN mem_fn  // mem_fun was removed in C++17.
282 #endif
283         if (find_if(begin, end, MEM_FN(&Node::dirty)) == end) {
284             // Recompute most_recent_input.
285             Node* most_recent_input = NULL;
286             for (vector<Node*>::iterator i = begin; i != end; ++i) {
287                 if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime())
288                     most_recent_input = *i;
289             }
290 
291             // Now, this edge is dirty if any of the outputs are dirty.
292             // If the edge isn't dirty, clean the outputs and mark the edge as not
293             // wanted.
294             bool outputs_dirty = false;
295             if (!scan->RecomputeOutputsDirty(*oe, most_recent_input,
296                 &outputs_dirty, err)) {
297                 return false;
298             }
299             if (!outputs_dirty) {
300                 for (vector<Node*>::iterator o = (*oe)->outputs_.begin();
301                     o != (*oe)->outputs_.end(); ++o) {
302                     if (!CleanNode(scan, *o, err))
303                         return false;
304                 }
305 
306                 want_e->second = kWantNothing;
307                 --wanted_edges_;
308                 if (!(*oe)->is_phony()) {
309                     --command_edges_;
310                     if (builder_)
311                         builder_->status_->EdgeRemovedFromPlan(*oe);
312                 }
313             }
314         }
315     }
316     return true;
317 }
318 
DyndepsLoaded(DependencyScan * scan,const Node * node,const DyndepFile & ddf,string * err)319 bool Plan::DyndepsLoaded(DependencyScan* scan, const Node* node,
320                                                   const DyndepFile& ddf, string* err) {
321     // Recompute the dirty state of all our direct and indirect dependents now
322     // that our dyndep information has been loaded.
323     if (!RefreshDyndepDependents(scan, node, err))
324         return false;
325 
326     // We loaded dyndep information for those out_edges of the dyndep node that
327     // specify the node in a dyndep binding, but they may not be in the plan.
328     // Starting with those already in the plan, walk newly-reachable portion
329     // of the graph through the dyndep-discovered dependencies.
330 
331     // Find edges in the the build plan for which we have new dyndep info.
332     std::vector<DyndepFile::const_iterator> dyndep_roots;
333     for (DyndepFile::const_iterator oe = ddf.begin(); oe != ddf.end(); ++oe) {
334         Edge* edge = oe->first;
335 
336         // If the edge outputs are ready we do not need to consider it here.
337         if (edge->outputs_ready())
338             continue;
339 
340         map<Edge*, Want>::iterator want_e = want_.find(edge);
341 
342         // If the edge has not been encountered before then nothing already in the
343         // plan depends on it so we do not need to consider the edge yet either.
344         if (want_e == want_.end())
345             continue;
346 
347         // This edge is already in the plan so queue it for the walk.
348         dyndep_roots.push_back(oe);
349     }
350 
351     // Walk dyndep-discovered portion of the graph to add it to the build plan.
352     std::set<Edge*> dyndep_walk;
353     for (std::vector<DyndepFile::const_iterator>::iterator
354               oei = dyndep_roots.begin(); oei != dyndep_roots.end(); ++oei) {
355         DyndepFile::const_iterator oe = *oei;
356         for (vector<Node*>::const_iterator i = oe->second.implicit_inputs_.begin();
357                 i != oe->second.implicit_inputs_.end(); ++i) {
358             if (!AddSubTarget(*i, oe->first->outputs_[0], err, &dyndep_walk) &&
359                     !err->empty())
360                 return false;
361         }
362     }
363 
364     // Add out edges from this node that are in the plan (just as
365     // Plan::NodeFinished would have without taking the dyndep code path).
366     for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
367             oe != node->out_edges().end(); ++oe) {
368         map<Edge*, Want>::iterator want_e = want_.find(*oe);
369         if (want_e == want_.end())
370             continue;
371         dyndep_walk.insert(want_e->first);
372     }
373 
374     // See if any encountered edges are now ready.
375     for (set<Edge*>::iterator wi = dyndep_walk.begin();
376             wi != dyndep_walk.end(); ++wi) {
377         map<Edge*, Want>::iterator want_e = want_.find(*wi);
378         if (want_e == want_.end())
379             continue;
380         if (!EdgeMaybeReady(want_e, err))
381             return false;
382     }
383 
384     return true;
385 }
386 
RefreshDyndepDependents(DependencyScan * scan,const Node * node,string * err)387 bool Plan::RefreshDyndepDependents(DependencyScan* scan, const Node* node,
388                                                                       string* err) {
389     // Collect the transitive closure of dependents and mark their edges
390     // as not yet visited by RecomputeDirty.
391     set<Node*> dependents;
392     UnmarkDependents(node, &dependents);
393 
394     // Update the dirty state of all dependents and check if their edges
395     // have become wanted.
396     for (set<Node*>::iterator i = dependents.begin();
397             i != dependents.end(); ++i) {
398         Node* n = *i;
399 
400         // Check if this dependent node is now dirty.  Also checks for new cycles.
401         std::vector<Node*> validation_nodes;
402         if (!scan->RecomputeDirty(n, &validation_nodes, err))
403             return false;
404 
405         // Add any validation nodes found during RecomputeDirty as new top level
406         // targets.
407         for (std::vector<Node*>::iterator v = validation_nodes.begin();
408                 v != validation_nodes.end(); ++v) {
409             if (Edge* in_edge = (*v)->in_edge()) {
410                 if (!in_edge->outputs_ready() &&
411                         !AddTarget(*v, err)) {
412                     return false;
413                 }
414             }
415         }
416         if (!n->dirty())
417             continue;
418 
419         // This edge was encountered before.  However, we may not have wanted to
420         // build it if the outputs were not known to be dirty.  With dyndep
421         // information an output is now known to be dirty, so we want the edge.
422         Edge* edge = n->in_edge();
423         assert(edge && !edge->outputs_ready());
424         map<Edge*, Want>::iterator want_e = want_.find(edge);
425         assert(want_e != want_.end());
426         if (want_e->second == kWantNothing) {
427             want_e->second = kWantToStart;
428             EdgeWanted(edge);
429         }
430     }
431     return true;
432 }
433 
UnmarkDependents(const Node * node,set<Node * > * dependents)434 void Plan::UnmarkDependents(const Node* node, set<Node*>* dependents) {
435     for (vector<Edge*>::const_iterator oe = node->out_edges().begin();
436             oe != node->out_edges().end(); ++oe) {
437         Edge* edge = *oe;
438 
439         map<Edge*, Want>::iterator want_e = want_.find(edge);
440         if (want_e == want_.end())
441             continue;
442 
443         if (edge->mark_ != Edge::VisitNone) {
444             edge->mark_ = Edge::VisitNone;
445             for (vector<Node*>::iterator o = edge->outputs_.begin();
446                     o != edge->outputs_.end(); ++o) {
447                 if (dependents->insert(*o).second)
448                     UnmarkDependents(*o, dependents);
449             }
450         }
451     }
452 }
453 
Dump() const454 void Plan::Dump() const {
455     printf("pending: %d\n", (int)want_.size());
456     for (map<Edge*, Want>::const_iterator e = want_.begin(); e != want_.end(); ++e) {
457         if (e->second != kWantNothing)
458             printf("want ");
459         e->first->Dump();
460     }
461     printf("ready: %d\n", (int)ready_.size());
462 }
463 
464 struct RealCommandRunner : public CommandRunner {
RealCommandRunnerRealCommandRunner465     explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
~RealCommandRunnerRealCommandRunner466     virtual ~RealCommandRunner() {}
467     virtual size_t CanRunMore() const;
468     virtual bool StartCommand(Edge* edge);
469     virtual bool WaitForCommand(Result* result);
470     virtual vector<Edge*> GetActiveEdges();
471     virtual void Abort();
472 
473     const BuildConfig& config_;
474     SubprocessSet subprocs_;
475     map<const Subprocess*, Edge*> subproc_to_edge_;
476 };
477 
GetActiveEdges()478 vector<Edge*> RealCommandRunner::GetActiveEdges() {
479     vector<Edge*> edges;
480     for (map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.begin();
481             e != subproc_to_edge_.end(); ++e)
482         edges.push_back(e->second);
483     return edges;
484 }
485 
Abort()486 void RealCommandRunner::Abort() {
487     subprocs_.Clear();
488 }
489 
CanRunMore() const490 size_t RealCommandRunner::CanRunMore() const {
491     size_t subproc_number =
492         subprocs_.running_.size() + subprocs_.finished_.size();
493 
494     int64_t capacity = config_.parallelism - subproc_number;
495 
496     if (config_.max_load_average > 0.0f) {
497         int load_capacity = config_.max_load_average - GetLoadAverage();
498         if (load_capacity < capacity)
499             capacity = load_capacity;
500     }
501 
502     if (capacity < 0)
503         capacity = 0;
504 
505     if (capacity == 0 && subprocs_.running_.empty())
506         // Ensure that we make progress.
507         capacity = 1;
508 
509     return capacity;
510 }
511 
StartCommand(Edge * edge)512 bool RealCommandRunner::StartCommand(Edge* edge) {
513     string command = edge->EvaluateCommand();
514     Subprocess* subproc = subprocs_.Add(command, edge->use_console());
515     if (!subproc)
516         return false;
517     subproc_to_edge_.insert(make_pair(subproc, edge));
518 
519     return true;
520 }
521 
WaitForCommand(Result * result)522 bool RealCommandRunner::WaitForCommand(Result* result) {
523     Subprocess* subproc;
524     while ((subproc = subprocs_.NextFinished()) == NULL) {
525         bool interrupted = subprocs_.DoWork();
526         if (interrupted)
527             return false;
528     }
529 
530     result->status = subproc->Finish();
531     result->output = subproc->GetOutput();
532 
533     map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.find(subproc);
534     result->edge = e->second;
535     subproc_to_edge_.erase(e);
536 
537     delete subproc;
538     return true;
539 }
540 
Builder(State * state,const BuildConfig & config,BuildLog * build_log,DepsLog * deps_log,DiskInterface * disk_interface,Status * status,int64_t start_time_millis)541 Builder::Builder(State* state, const BuildConfig& config,
542                                   BuildLog* build_log, DepsLog* deps_log,
543                                   DiskInterface* disk_interface, Status *status,
544                                   int64_t start_time_millis)
545         : state_(state), config_(config), plan_(this), status_(status),
546             start_time_millis_(start_time_millis), disk_interface_(disk_interface),
547             scan_(state, build_log, deps_log, disk_interface,
548                 &config_.depfile_parser_options) {
549     lock_file_path_ = ".ninja_lock";
550     string build_dir = state_->bindings_.LookupVariable("builddir");
551     if (!build_dir.empty())
552         lock_file_path_ = build_dir + "/" + lock_file_path_;
553 }
554 
~Builder()555 Builder::~Builder() {
556     Cleanup();
557 }
558 
Cleanup()559 void Builder::Cleanup() {
560     if (command_runner_.get()) {
561         vector<Edge*> active_edges = command_runner_->GetActiveEdges();
562         command_runner_->Abort();
563 
564         for (vector<Edge*>::iterator e = active_edges.begin();
565                 e != active_edges.end(); ++e) {
566             string depfile = (*e)->GetUnescapedDepfile();
567             for (vector<Node*>::iterator o = (*e)->outputs_.begin();
568                     o != (*e)->outputs_.end(); ++o) {
569                 // Only delete this output if it was actually modified.  This is
570                 // important for things like the generator where we don't want to
571                 // delete the manifest file if we can avoid it.  But if the rule
572                 // uses a depfile, always delete.  (Consider the case where we
573                 // need to rebuild an output because of a modified header file
574                 // mentioned in a depfile, and the command touches its depfile
575                 // but is interrupted before it touches its output file.)
576                 string err;
577                 TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), &err);
578                 if (new_mtime == -1)  // Log and ignore Stat() errors.
579                     status_->Error("%s", err.c_str());
580                 if (!depfile.empty() || (*o)->mtime() != new_mtime)
581                     disk_interface_->RemoveFile((*o)->path());
582             }
583             if (!depfile.empty())
584                 disk_interface_->RemoveFile(depfile);
585         }
586     }
587 
588     string err;
589     if (disk_interface_->Stat(lock_file_path_, &err) > 0)
590         disk_interface_->RemoveFile(lock_file_path_);
591 }
592 
AddTarget(const string & name,string * err)593 Node* Builder::AddTarget(const string& name, string* err) {
594     Node* node = state_->LookupNode(name);
595     if (!node) {
596         *err = "unknown target: '" + name + "'";
597         return NULL;
598     }
599     if (!AddTarget(node, err))
600         return NULL;
601     return node;
602 }
603 
AddTarget(Node * target,string * err)604 bool Builder::AddTarget(Node* target, string* err) {
605     std::vector<Node*> validation_nodes;
606     if (!scan_.RecomputeDirty(target, &validation_nodes, err))
607         return false;
608 
609     Edge* in_edge = target->in_edge();
610     if (!in_edge || !in_edge->outputs_ready()) {
611         if (!plan_.AddTarget(target, err)) {
612             return false;
613         }
614     }
615 
616     // Also add any validation nodes found during RecomputeDirty as top level
617     // targets.
618     for (std::vector<Node*>::iterator n = validation_nodes.begin();
619             n != validation_nodes.end(); ++n) {
620         if (Edge* validation_in_edge = (*n)->in_edge()) {
621             if (!validation_in_edge->outputs_ready() &&
622                 !plan_.AddTarget(*n, err)) {
623                 return false;
624             }
625         }
626     }
627 
628     return true;
629 }
630 
AlreadyUpToDate() const631 bool Builder::AlreadyUpToDate() const {
632     return !plan_.more_to_do();
633 }
634 
Build(string * err)635 bool Builder::Build(string* err) {
636     assert(!AlreadyUpToDate());
637 
638     int pending_commands = 0;
639     int failures_allowed = config_.failures_allowed;
640 
641     // Set up the command runner if we haven't done so already.
642     if (!command_runner_.get()) {
643         if (config_.dry_run)
644             command_runner_.reset(new DryRunCommandRunner);
645         else
646             command_runner_.reset(new RealCommandRunner(config_));
647     }
648 
649     // We are about to start the build process.
650     status_->BuildStarted();
651 
652     // This main loop runs the entire build process.
653     // It is structured like this:
654     // First, we attempt to start as many commands as allowed by the
655     // command runner.
656     // Second, we attempt to wait for / reap the next finished command.
657     while (plan_.more_to_do()) {
658         // See if we can start any more commands.
659         if (failures_allowed) {
660             size_t capacity = command_runner_->CanRunMore();
661             while (capacity > 0) {
662                 Edge* edge = plan_.FindWork();
663                 if (!edge)
664                     break;
665 
666                 if (edge->GetBindingBool("generator")) {
667                     scan_.build_log()->Close();
668                 }
669 
670                 if (!StartEdge(edge, err)) {
671                     Cleanup();
672                     status_->BuildFinished();
673                     return false;
674                 }
675 
676                 if (edge->is_phony()) {
677                     if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
678                         Cleanup();
679                         status_->BuildFinished();
680                         return false;
681                     }
682                 } else {
683                     ++pending_commands;
684 
685                     --capacity;
686 
687                     // Re-evaluate capacity.
688                     size_t current_capacity = command_runner_->CanRunMore();
689                     if (current_capacity < capacity)
690                         capacity = current_capacity;
691                 }
692             }
693 
694             // We are finished with all work items and have no pending
695             // commands. Therefore, break out of the main loop.
696             if (pending_commands == 0 && !plan_.more_to_do()) break;
697         }
698 
699         // See if we can reap any finished commands.
700         if (pending_commands) {
701             CommandRunner::Result result;
702             if (!command_runner_->WaitForCommand(&result) ||
703                     result.status == ExitInterrupted) {
704                 Cleanup();
705                 status_->BuildFinished();
706                 *err = "interrupted by user";
707                 return false;
708             }
709 
710             --pending_commands;
711             if (!FinishCommand(&result, err)) {
712                 Cleanup();
713                 status_->BuildFinished();
714                 return false;
715             }
716 
717             if (!result.success()) {
718                 if (failures_allowed)
719                     failures_allowed--;
720             }
721 
722             // We made some progress; start the main loop over.
723             continue;
724         }
725 
726         // If we get here, we cannot make any more progress.
727         status_->BuildFinished();
728         if (failures_allowed == 0) {
729             if (config_.failures_allowed > 1)
730                 *err = "subcommands failed";
731             else
732                 *err = "subcommand failed";
733         } else if (failures_allowed < config_.failures_allowed)
734             *err = "cannot make progress due to previous errors";
735         else
736             *err = "stuck [this is a bug]";
737 
738         return false;
739     }
740 
741     status_->BuildFinished();
742     return true;
743 }
744 
Trim(std::string & s)745 static std::string &Trim(std::string &s)
746 {
747     if (s.empty()) {
748         return s;
749     }
750     s.erase(0, s.find_first_not_of(" \t\r\n"));
751     s.erase(s.find_last_not_of(" \t\r\n") + 1);
752     return s;
753 }
754 
SplitStringBySpace(std::string content)755 static std::vector<std::string> SplitStringBySpace(std::string content)
756 {
757     std::string space_delimiter = " ";
758     std::vector<std::string> words{};
759     size_t pos = 0;
760     std::string temp_content = content;
761     while ((pos = temp_content.find(space_delimiter)) != string::npos) {
762         std::string sub_str = temp_content.substr(0, pos);
763         std::string tmp = Trim(sub_str);
764         if (!tmp.empty()) {
765             words.push_back(tmp);
766         }
767         temp_content = temp_content.substr(pos + 1);
768     }
769     std::string tmp_last = Trim(temp_content);
770     if (!tmp_last.empty()) {
771         words.push_back(tmp_last);
772     }
773     return words;
774 }
775 
SplicingWholeContent(std::string content,std::string whole_content,bool is_whole_archive)776 static std::string SplicingWholeContent(std::string content, std::string whole_content, bool is_whole_archive)
777 {
778     if (whole_content.empty()) {
779         return content;
780     }
781 
782     std::string temp_content = content;
783     if (is_whole_archive) {
784         temp_content += " -Wl,--whole-archive";
785     }
786 
787     std::vector<std::string> whole_list = SplitStringBySpace(whole_content);
788     std::vector<std::string> content_list = SplitStringBySpace(temp_content);
789     for (const std::string &word : whole_list) {
790         auto it = std::find_if(content_list.begin(), content_list.end(), [&](const std::string& s) {
791             return s.find(word) != std::string::npos;
792         });
793         if (it != content_list.end()) {
794             content_list.push_back(*it);
795             content_list.erase(it);
796         }
797     }
798 
799     std::string result = "";
800     for (int i = 0; i < content_list.size(); i++) {
801         result += content_list[i];
802         if (i != content_list.size() - 1) {
803             result += " ";
804         }
805     }
806     return result;
807 }
808 
GetContent(Edge * edge)809 std::string Builder::GetContent(Edge* edge)
810 {
811     std::string content = edge->GetBinding("rspfile_content");
812     std::string toolchain_whole_status =  edge->env_->LookupVariable("toolchain_whole_status");
813 
814     if (toolchain_whole_status == "0") {
815         return SplicingWholeContent(content, edge->env_->LookupVariable("whole-archive"), true);
816     } else if (toolchain_whole_status == "1") {
817         return SplicingWholeContent(content, edge->env_->LookupVariable("no-whole-archive"), false);
818     } else {
819         return content;
820     }
821 }
822 
StartEdge(Edge * edge,string * err)823 bool 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 = -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_, "");
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 response file, if needed
853     // XXX: this may also block; do we care?
854     string rspfile = edge->GetUnescapedRspfile();
855     if (!rspfile.empty()) {
856         string content = GetContent(edge);
857         if (!disk_interface_->WriteFile(rspfile, content))
858             return false;
859     }
860 
861     // start command computing and run it
862     if (!command_runner_->StartCommand(edge)) {
863         err->assign("command '" + edge->EvaluateCommand() + "' failed.");
864         return false;
865     }
866 
867     return true;
868 }
869 
FinishCommand(CommandRunner::Result * result,string * err)870 bool Builder::FinishCommand(CommandRunner::Result* result, string* err) {
871     METRIC_RECORD("FinishCommand");
872 
873     Edge* edge = result->edge;
874 
875     // First try to extract dependencies from the result, if any.
876     // This must happen first as it filters the command output (we want
877     // to filter /showIncludes output, even on compile failure) and
878     // extraction itself can fail, which makes the command fail from a
879     // build perspective.
880     vector<Node*> deps_nodes;
881     string deps_type = edge->GetBinding("deps");
882     const string deps_prefix = edge->GetBinding("msvc_deps_prefix");
883     if (!deps_type.empty()) {
884         string extract_err;
885         if (!ExtractDeps(result, deps_type, deps_prefix, &deps_nodes,
886             &extract_err) && result->success()) {
887             if (!result->output.empty())
888                 result->output.append("\n");
889             result->output.append(extract_err);
890             result->status = ExitFailure;
891         }
892     }
893 
894     int64_t start_time_millis, end_time_millis;
895     RunningEdgeMap::iterator it = running_edges_.find(edge);
896     start_time_millis = it->second;
897     end_time_millis = GetTimeMillis() - start_time_millis_;
898     running_edges_.erase(it);
899 
900     status_->BuildEdgeFinished(edge, start_time_millis, end_time_millis,
901         result->success(), result->output);
902 
903     // The rest of this function only applies to successful commands.
904     if (!result->success()) {
905         return plan_.EdgeFinished(edge, Plan::kEdgeFailed, err);
906     }
907 
908     // Restat the edge outputs
909     TimeStamp record_mtime = 0;
910     if (!config_.dry_run) {
911         const bool restat = edge->GetBindingBool("restat");
912         const bool generator = edge->GetBindingBool("generator");
913         bool node_cleaned = false;
914         record_mtime = edge->command_start_time_;
915 
916         // restat and generator rules must restat the outputs after the build
917         // has finished. if record_mtime == 0, then there was an error while
918         // attempting to touch/stat the temp file when the edge started and
919         // we should fall back to recording the outputs' current mtime in the
920         // log.
921         if (record_mtime == 0 || restat || generator) {
922             for (vector<Node*>::iterator o = edge->outputs_.begin();
923                     o != edge->outputs_.end(); ++o) {
924                 TimeStamp new_mtime = disk_interface_->Stat((*o)->path(), err);
925                 if (new_mtime == -1)
926                     return false;
927                 if (new_mtime > record_mtime)
928                     record_mtime = new_mtime;
929                 if ((*o)->mtime() == new_mtime && restat) {
930                     // The rule command did not change the output.  Propagate the clean
931                     // state through the build graph.
932                     // Note that this also applies to nonexistent outputs (mtime == 0).
933                     if (!plan_.CleanNode(&scan_, *o, err))
934                         return false;
935                     node_cleaned = true;
936                 }
937             }
938         }
939         if (node_cleaned) {
940             record_mtime = edge->command_start_time_;
941         }
942     }
943 
944     if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err))
945         return false;
946 
947     // Delete any left over response file.
948     string rspfile = edge->GetUnescapedRspfile();
949     if (!rspfile.empty() && !g_keep_rsp)
950         disk_interface_->RemoveFile(rspfile);
951 
952     if (scan_.build_log()) {
953         if (!scan_.build_log()->RecordCommand(edge, start_time_millis,
954             end_time_millis, record_mtime)) {
955             *err = string("Error writing to build log: ") + strerror(errno);
956             return false;
957         }
958     }
959 
960     if (!deps_type.empty() && !config_.dry_run) {
961         assert(!edge->outputs_.empty() && "should have been rejected by parser");
962         for (std::vector<Node*>::const_iterator o = edge->outputs_.begin();
963                 o != edge->outputs_.end(); ++o) {
964             TimeStamp deps_mtime = disk_interface_->Stat((*o)->path(), err);
965             if (deps_mtime == -1)
966                 return false;
967             if (!scan_.deps_log()->RecordDeps(*o, deps_mtime, deps_nodes)) {
968                 *err = std::string("Error writing to deps log: ") + strerror(errno);
969                 return false;
970             }
971         }
972     }
973     return true;
974 }
975 
ExtractDeps(CommandRunner::Result * result,const string & deps_type,const string & deps_prefix,vector<Node * > * deps_nodes,string * err)976 bool Builder::ExtractDeps(CommandRunner::Result* result,
977                                                     const string& deps_type,
978                                                     const string& deps_prefix,
979                                                     vector<Node*>* deps_nodes,
980                                                     string* err) {
981     if (deps_type == "msvc") {
982         CLParser parser;
983         string output;
984         if (!parser.Parse(result->output, deps_prefix, &output, err))
985             return false;
986         result->output = output;
987         for (set<string>::iterator i = parser.includes_.begin();
988                 i != parser.includes_.end(); ++i) {
989             // ~0 is assuming that with MSVC-parsed headers, it's ok to always make
990             // all backslashes (as some of the slashes will certainly be backslashes
991             // anyway). This could be fixed if necessary with some additional
992             // complexity in IncludesNormalize::Relativize.
993             deps_nodes->push_back(state_->GetNode(*i, ~0u));
994         }
995     } else if (deps_type == "gcc") {
996         string depfile = result->edge->GetUnescapedDepfile();
997         if (depfile.empty()) {
998             *err = string("edge with deps=gcc but no depfile makes no sense");
999             return false;
1000         }
1001 
1002         // Read depfile content.  Treat a missing depfile as empty.
1003         string content;
1004         switch (disk_interface_->ReadFile(depfile, &content, err)) {
1005         case DiskInterface::Okay:
1006             break;
1007         case DiskInterface::NotFound:
1008             err->clear();
1009             break;
1010         case DiskInterface::OtherError:
1011             return false;
1012         }
1013         if (content.empty())
1014             return true;
1015 
1016         DepfileParser deps(config_.depfile_parser_options);
1017         if (!deps.Parse(&content, err))
1018             return false;
1019 
1020         // XXX check depfile matches expected output.
1021         deps_nodes->reserve(deps.ins_.size());
1022         for (vector<StringPiece>::iterator i = deps.ins_.begin();
1023                 i != deps.ins_.end(); ++i) {
1024             uint64_t slash_bits;
1025             CanonicalizePath(const_cast<char*>(i->str_), &i->len_, &slash_bits);
1026             deps_nodes->push_back(state_->GetNode(*i, slash_bits));
1027         }
1028 
1029         if (!g_keep_depfile) {
1030             if (disk_interface_->RemoveFile(depfile) < 0) {
1031                 *err = string("deleting depfile: ") + strerror(errno) + string("\n");
1032                 return false;
1033             }
1034         }
1035     } else {
1036         Fatal("unknown deps type '%s'", deps_type.c_str());
1037     }
1038 
1039     return true;
1040 }
1041 
LoadDyndeps(Node * node,string * err)1042 bool Builder::LoadDyndeps(Node* node, string* err) {
1043     status_->BuildLoadDyndeps();
1044 
1045     // Load the dyndep information provided by this node.
1046     DyndepFile ddf;
1047     if (!scan_.LoadDyndeps(node, &ddf, err))
1048         return false;
1049 
1050     // Update the build plan to account for dyndep modifications to the graph.
1051     if (!plan_.DyndepsLoaded(&scan_, node, ddf, err))
1052         return false;
1053 
1054     return true;
1055 }
1056