ROSE  0.11.31.0
BinaryDataFlow.h
1 #ifndef ROSE_BinaryAnalysis_DataFlow_H
2 #define ROSE_BinaryAnalysis_DataFlow_H
3 
4 #include <featureTests.h>
5 #ifdef ROSE_ENABLE_BINARY_ANALYSIS
6 
7 #include "DataFlowSemantics2.h"
8 #include "Diagnostics.h"
9 #include "RoseException.h"
10 #include "SymbolicSemantics2.h"
11 
12 #include <boost/foreach.hpp>
13 #include <boost/lexical_cast.hpp>
14 #include <list>
15 #include <Sawyer/GraphTraversal.h>
16 #include <Sawyer/DistinctList.h>
17 #include <sstream>
18 #include <string>
19 #include <vector>
20 
21 namespace Rose {
22 namespace BinaryAnalysis {
23 
71 class DataFlow {
72 public:
79 
86 
88  typedef std::list<Variable> VariableList;
89 
96 
97 public:
99  class Exception: public Rose::Exception {
100  public:
101  explicit Exception(const std::string &s): Rose::Exception(s) {}
102  };
103 
105  class NotConverging: public Exception {
106  public:
107  explicit NotConverging(const std::string &s): Exception(s) {}
108  };
109 
110 private:
111  InstructionSemantics2::BaseSemantics::RiscOperatorsPtr userOps_; // operators (and state) provided by the user
112  InstructionSemantics2::DataFlowSemantics::RiscOperatorsPtr dfOps_; // data-flow operators (which point to user ops)
113  InstructionSemantics2::BaseSemantics::DispatcherPtr dispatcher_; // copy of user's dispatcher but with DataFlowSemantics
114  static Sawyer::Message::Facility mlog; // diagnostics for data-flow
116 
117 public:
124  init(userDispatcher);
125  }
126 
130  static void initDiagnostics();
131 
132 public:
141  Graph buildGraph(const std::vector<SgAsmInstruction*>&);
150  public:
151  typedef std::vector<SgAsmInstruction*> Instructions;
152  Instructions operator()(SgAsmInstruction *insn) { return Instructions(1, insn); }
153  Instructions operator()(SgAsmBlock *blk);
154  };
155 
156 public:
168  template<class CFG, class VertexUnpacker>
169  VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex, VertexUnpacker vertexUnpacker) {
170  using namespace Diagnostics;
171  ASSERT_this();
172  ASSERT_require(startVertex < cfg.nVertices());
173  Stream mesg(mlog[WHERE] <<"buildGraphPerVertex startVertex=" <<startVertex);
174 
175  VertexFlowGraphs result;
176  result.insert(startVertex, buildGraph(vertexUnpacker(cfg.findVertex(startVertex)->value())));
177  std::vector<InstructionSemantics2::BaseSemantics::StatePtr> postState(cfg.nVertices()); // user-defined states
178  postState[startVertex] = userOps_->currentState();
179 
181  for (Traversal t(cfg, cfg.findVertex(startVertex)); t; ++t) {
182  typename CFG::ConstVertexIterator source = t->source();
183  typename CFG::ConstVertexIterator target = t->target();
184  InstructionSemantics2::BaseSemantics::StatePtr state = postState[target->id()];
185  if (state==NULL) {
186  ASSERT_not_null(postState[source->id()]);
187  state = postState[target->id()] = postState[source->id()]->clone();
188  userOps_->currentState(state);
189  std::vector<SgAsmInstruction*> insns = vertexUnpacker(target->value());
190  result.insert(target->id(), buildGraph(insns));
191  }
192  }
193 
194  mesg <<"; processed " <<StringUtility::plural(result.size(), "vertices", "vertex") <<"\n";
195  return result;
196  }
197 
198  template<class CFG>
199  VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex) {
200  return buildGraphPerVertex(cfg, startVertex, DefaultVertexUnpacker());
201  }
208  VariableList getUniqueVariables(const VertexFlowGraphs&);
209 
215  public:
217  explicit SemanticsMerge(const InstructionSemantics2::BaseSemantics::DispatcherPtr &cpu): ops_(cpu->operators()) {}
218 
219  bool operator()(InstructionSemantics2::BaseSemantics::StatePtr &dst /*in,out*/,
221  struct PreserveCurrentState {
224  PreserveCurrentState(const InstructionSemantics2::BaseSemantics::RiscOperatorsPtr &ops)
225  : ops(ops), state(ops->currentState()) {}
226  ~PreserveCurrentState() { ops->currentState(state); }
227  } t(ops_);
228 
229  if (!dst) {
230  dst = src->clone();
231  return true;
232  } else {
233  ops_->currentState(src);
234  return dst->merge(src, ops_.get());
235  }
236  }
237  };
238 
243  template<class CFG, class State>
245  public:
246  bool operator()(const CFG&, const typename CFG::Edge&, const State&, const State&) {
247  return true;
248  }
249  };
250 
308  template<class CFG, class State, class TransferFunction, class MergeFunction,
309  class PathFeasibility = PathAlwaysFeasible<CFG, State> >
310  class Engine {
311  public:
312  typedef std::vector<State> VertexStates;
314  private:
315  const CFG &cfg_;
316  TransferFunction &xfer_;
317  MergeFunction merge_;
318  VertexStates incomingState_; // incoming data-flow state per CFG vertex ID
319  VertexStates outgoingState_; // outgoing data-flow state per CFG vertex ID
321  WorkList workList_; // CFG vertex IDs to be visited, last in first out w/out duplicates
322  size_t maxIterations_; // max number of iterations to allow
323  size_t nIterations_; // number of iterations since last reset
324  PathFeasibility isFeasible_; // predicate to test path feasibility
325 
326  public:
332  Engine(const CFG &cfg, TransferFunction &xfer, MergeFunction merge = MergeFunction(),
333  PathFeasibility isFeasible = PathFeasibility())
334  : cfg_(cfg), xfer_(xfer), merge_(merge), maxIterations_(-1), nIterations_(0), isFeasible_(isFeasible) {
335  reset();
336  }
337 
342  const CFG &cfg() const {
343  return cfg_;
344  }
345 
347  void reset(State initialState = State()) {
348  ASSERT_this();
349  incomingState_.clear();
350  incomingState_.resize(cfg_.nVertices(), initialState);
351  outgoingState_.clear();
352  outgoingState_.resize(cfg_.nVertices(), initialState);
353  workList_.clear();
354  nIterations_ = 0;
355  }
356 
363  size_t maxIterations() const { return maxIterations_; }
364  void maxIterations(size_t n) { maxIterations_ = n; }
370  size_t nIterations() const { return nIterations_; }
371 
377  using namespace Diagnostics;
378  if (!workList_.isEmpty()) {
379  if (++nIterations_ > maxIterations_) {
380  throw NotConverging("data-flow max iterations reached"
381  " (max=" + StringUtility::numberToString(maxIterations_) + ")");
382  }
383  size_t cfgVertexId = workList_.popFront();
384  if (mlog[DEBUG]) {
385  mlog[DEBUG] <<"runOneIteration: vertex #" <<cfgVertexId <<"\n";
386  mlog[DEBUG] <<" remaining worklist is {";
387  BOOST_FOREACH (size_t id, workList_.items())
388  mlog[DEBUG] <<" " <<id;
389  mlog[DEBUG] <<" }\n";
390  }
391 
392  ASSERT_require2(cfgVertexId < cfg_.nVertices(),
393  "vertex " + boost::lexical_cast<std::string>(cfgVertexId) + " must be valid within CFG");
394  typename CFG::ConstVertexIterator vertex = cfg_.findVertex(cfgVertexId);
395  State state = incomingState_[cfgVertexId];
396  if (mlog[DEBUG]) {
397  mlog[DEBUG] <<" incoming state for vertex #" <<cfgVertexId <<":\n"
398  <<StringUtility::prefixLines(xfer_.toString(state), " ") <<"\n";
399  }
400 
401  state = outgoingState_[cfgVertexId] = xfer_(cfg_, cfgVertexId, state);
402  if (mlog[DEBUG]) {
403  mlog[DEBUG] <<" outgoing state for vertex #" <<cfgVertexId <<":\n"
404  <<StringUtility::prefixLines(xfer_.toString(state), " ") <<"\n";
405  }
406 
407  // Outgoing state must be merged into the incoming states for the CFG successors. Any such incoming state that
408  // is modified as a result will have its CFG vertex added to the work list.
409  SAWYER_MESG(mlog[DEBUG]) <<" forwarding vertex #" <<cfgVertexId <<" output state to "
410  <<StringUtility::plural(vertex->nOutEdges(), "vertices", "vertex") <<"\n";
411  BOOST_FOREACH (const typename CFG::Edge &edge, vertex->outEdges()) {
412  size_t nextVertexId = edge.target()->id();
413  if (!isFeasible_(cfg_, edge, state, incomingState_[nextVertexId])) {
414  SAWYER_MESG(mlog[DEBUG]) <<" path to vertex #" <<nextVertexId <<" is not feasible, thus skipped\n";
415  } else if (merge_(incomingState_[nextVertexId], state)) {
416  if (mlog[DEBUG]) {
417  mlog[DEBUG] <<" merged with vertex #" <<nextVertexId <<" (which changed as a result)\n";
418  mlog[DEBUG] <<" merge state is: "
419  <<StringUtility::prefixLines(xfer_.toString(incomingState_[nextVertexId]),
420  " ", false) <<"\n";
421  }
422  workList_.pushBack(nextVertexId);
423  } else {
424  SAWYER_MESG(mlog[DEBUG]) <<" merged with vertex #" <<nextVertexId <<" (no change)\n";
425  }
426  }
427  }
428  return !workList_.isEmpty();
429  }
430 
432  void insertStartingVertex(size_t startVertexId, const State &initialState) {
433  incomingState_[startVertexId] = initialState;
434  workList_.pushBack(startVertexId);
435  }
436 
443  while (runOneIteration()) /*void*/;
444  }
445 
449  void runToFixedPoint(size_t startVertexId, const State &initialState) {
450  reset();
451  insertStartingVertex(startVertexId, initialState);
452  while (runOneIteration()) /*void*/;
453  }
454 
459  State getInitialState(size_t cfgVertexId) const {
460  return incomingState_[cfgVertexId];
461  }
462 
464  void setInitialState(size_t cfgVertexId, State state) {
465  incomingState_[cfgVertexId] = state;
466  }
467 
472  State getFinalState(size_t cfgVertexId) const {
473  return outgoingState_[cfgVertexId];
474  }
475 
480  const VertexStates& getInitialStates() const {
481  return incomingState_;
482  }
483 
488  const VertexStates& getFinalStates() const {
489  return outgoingState_;
490  }
491  };
492 };
493 
494 } // namespace
495 } // namespace
496 
497 #endif
498 #endif
boost::shared_ptr< RiscOperators > RiscOperatorsPtr
Shared-ownership pointer to a RISC operators object.
Sawyer::Container::Map< size_t, Graph > VertexFlowGraphs
Map from CFG vertex to data-flow graph.
ROSE_UTIL_API std::string numberToString(long long)
Convert an integer to a string.
Instruction basic block.
InstructionSemantics2::DataFlowSemantics::DataFlowGraph Graph
Data-flow graph.
std::string plural(T n, const std::string &plural_phrase, const std::string &singular_phrase="")
Helpful way to print singular or plural words.
Basic merge operation for instruction semantics.
Base class for machine instructions.
Collection of streams.
Definition: Message.h:1606
boost::shared_ptr< State > StatePtr
Shared-ownership pointer to a semantic state.
AbstractLocation Variable
Variable participating in data flow.
Depth-first, forward traversal for edges.
Engine(const CFG &cfg, TransferFunction &xfer, MergeFunction merge=MergeFunction(), PathFeasibility isFeasible=PathFeasibility())
Constructor.
static void initDiagnostics()
Initialize diagnostics.
std::list< Variable > VariableList
List of variables.
DataFlow(const InstructionSemantics2::BaseSemantics::DispatcherPtr &userDispatcher)
Constructor.
Main namespace for the ROSE library.
bool isEmpty() const
Determines whether list is empty.
Definition: DistinctList.h:66
Graph buildGraph(const std::vector< SgAsmInstruction * > &)
Compute data-flow.
ROSE_UTIL_API std::string prefixLines(const std::string &lines, const std::string &prefix, bool prefixAtFront=true, bool prefixAtBack=false)
Insert a prefix string before every line.
void runToFixedPoint()
Run data-flow until it reaches a fixed point.
bool runOneIteration()
Runs one iteration.
const CFG & cfg() const
Data-flow control flow graph.
State getInitialState(size_t cfgVertexId) const
Return the incoming state for the specified CFG vertex.
VariableList getUniqueVariables(const VertexFlowGraphs &)
Get list of unique variables.
boost::shared_ptr< Dispatcher > DispatcherPtr
Shared-ownership pointer to a semantics instruction dispatcher.
const VertexStates & getInitialStates() const
All incoming states.
VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex)
Compute data-flow per CFG vertex.
Exceptions when a fixed point is not reached.
Trivial path feasibility predicate.
State getFinalState(size_t cfgVertexId) const
Return the outgoing state for the specified CFG vertex.
const Items & items() const
Return all items as a list.
Definition: DistinctList.h:181
size_t nIterations() const
Number of iterations run.
void pushBack(const Item &item)
Insert item at back of list if distinct.
Definition: DistinctList.h:133
std::vector< State > VertexStates
Data-flow states indexed by vertex ID.
Item popFront()
Return and erase item at front of list.
Definition: DistinctList.h:145
Data-flow exception base class.
void reset(State initialState=State())
Reset engine to initial state.
Various tools for data-flow analysis.
Map & insert(const Key &key, const Value &value)
Insert or update a key/value pair.
Definition: Sawyer/Map.h:594
Functor to return instructions for a cfg vertex.
void maxIterations(size_t n)
Max number of iterations to allow.
void insertStartingVertex(size_t startVertexId, const State &initialState)
Add a starting vertex.
Base class for all ROSE exceptions.
Definition: RoseException.h:9
VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex, VertexUnpacker vertexUnpacker)
Compute data-flow per CFG vertex.
void runToFixedPoint(size_t startVertexId, const State &initialState)
Add starting point and run to fixed point.
size_t size() const
Number of nodes, keys, or values in this container.
Definition: Sawyer/Map.h:386
void clear()
Clear the list.
Definition: DistinctList.h:58
size_t maxIterations() const
Max number of iterations to allow.
const VertexStates & getFinalStates() const
All outgoing states.
void setInitialState(size_t cfgVertexId, State state)
Set the initial state for the specified CFG vertex.