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