ROSE  0.9.10.91
BinaryDataFlow.h
1 #ifndef ROSE_BinaryAnalysis_DataFlow_H
2 #define ROSE_BinaryAnalysis_DataFlow_H
3 
4 #include "DataFlowSemantics2.h"
5 #include "Diagnostics.h"
6 #include "SymbolicSemantics2.h"
7 
8 #include <boost/foreach.hpp>
9 #include <boost/lexical_cast.hpp>
10 #include <list>
11 #include <Sawyer/GraphTraversal.h>
12 #include <Sawyer/DistinctList.h>
13 #include <sstream>
14 #include <string>
15 #include <vector>
16 
17 namespace Rose {
18 namespace BinaryAnalysis {
19 
67 class DataFlow {
68 public:
75 
82 
84  typedef std::list<Variable> VariableList;
85 
92 
93 public:
95  class Exception: public std::runtime_error {
96  public:
97  explicit Exception(const std::string &s): std::runtime_error(s) {}
98  };
99 
101  class NotConverging: public Exception {
102  public:
103  explicit NotConverging(const std::string &s): Exception(s) {}
104  };
105 
106 private:
107  InstructionSemantics2::BaseSemantics::RiscOperatorsPtr userOps_; // operators (and state) provided by the user
108  InstructionSemantics2::DataFlowSemantics::RiscOperatorsPtr dfOps_; // data-flow operators (which point to user ops)
109  InstructionSemantics2::BaseSemantics::DispatcherPtr dispatcher_; // copy of user's dispatcher but with DataFlowSemantics
110  static Sawyer::Message::Facility mlog; // diagnostics for data-flow
112 
113 public:
120  init(userDispatcher);
121  }
122 
126  static void initDiagnostics();
127 
128 public:
137  Graph buildGraph(const std::vector<SgAsmInstruction*>&);
146  public:
147  typedef std::vector<SgAsmInstruction*> Instructions;
148  Instructions operator()(SgAsmInstruction *insn) { return Instructions(1, insn); }
149  Instructions operator()(SgAsmBlock *blk);
150  };
151 
152 public:
164  template<class CFG, class VertexUnpacker>
165  VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex, VertexUnpacker vertexUnpacker) {
166  using namespace Diagnostics;
167  ASSERT_this();
168  ASSERT_require(startVertex < cfg.nVertices());
169  Stream mesg(mlog[WHERE] <<"buildGraphPerVertex startVertex=" <<startVertex);
170 
171  VertexFlowGraphs result;
172  result.insert(startVertex, buildGraph(vertexUnpacker(cfg.findVertex(startVertex)->value())));
173  std::vector<InstructionSemantics2::BaseSemantics::StatePtr> postState(cfg.nVertices()); // user-defined states
174  postState[startVertex] = userOps_->currentState();
175 
177  for (Traversal t(cfg, cfg.findVertex(startVertex)); t; ++t) {
178  typename CFG::ConstVertexIterator source = t->source();
179  typename CFG::ConstVertexIterator target = t->target();
180  InstructionSemantics2::BaseSemantics::StatePtr state = postState[target->id()];
181  if (state==NULL) {
182  ASSERT_not_null(postState[source->id()]);
183  state = postState[target->id()] = postState[source->id()]->clone();
184  userOps_->currentState(state);
185  std::vector<SgAsmInstruction*> insns = vertexUnpacker(target->value());
186  result.insert(target->id(), buildGraph(insns));
187  }
188  }
189 
190  mesg <<"; processed " <<StringUtility::plural(result.size(), "vertices", "vertex") <<"\n";
191  return result;
192  }
193 
194  template<class CFG>
195  VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex) {
196  return buildGraphPerVertex(cfg, startVertex, DefaultVertexUnpacker());
197  }
204  VariableList getUniqueVariables(const VertexFlowGraphs&);
205 
211  public:
213  explicit SemanticsMerge(const InstructionSemantics2::BaseSemantics::DispatcherPtr &cpu): ops_(cpu->get_operators()) {}
214 
215  bool operator()(InstructionSemantics2::BaseSemantics::StatePtr &dst /*in,out*/,
217  struct PreserveCurrentState {
220  PreserveCurrentState(const InstructionSemantics2::BaseSemantics::RiscOperatorsPtr &ops)
221  : ops(ops), state(ops->currentState()) {}
222  ~PreserveCurrentState() { ops->currentState(state); }
223  } t(ops_);
224 
225  if (!dst) {
226  dst = src->clone();
227  return true;
228  } else {
229  ops_->currentState(src);
230  return dst->merge(src, ops_.get());
231  }
232  }
233  };
234 
239  template<class CFG, class State>
241  public:
242  bool operator()(const CFG&, const typename CFG::Edge&, const State&) {
243  return true;
244  }
245  };
246 
300  template<class CFG, class State, class TransferFunction, class MergeFunction,
301  class PathFeasibility = PathAlwaysFeasible<CFG, State> >
302  class Engine {
303  public:
304  typedef std::vector<State> VertexStates;
306  private:
307  const CFG &cfg_;
308  TransferFunction &xfer_;
309  MergeFunction merge_;
310  VertexStates incomingState_; // incoming data-flow state per CFG vertex ID
311  VertexStates outgoingState_; // outgoing data-flow state per CFG vertex ID
313  WorkList workList_; // CFG vertex IDs to be visited, last in first out w/out duplicates
314  size_t maxIterations_; // max number of iterations to allow
315  size_t nIterations_; // number of iterations since last reset
316  PathFeasibility isFeasible_; // predicate to test path feasibility
317 
318  public:
324  Engine(const CFG &cfg, TransferFunction &xfer, MergeFunction merge = MergeFunction(),
325  PathFeasibility isFeasible = PathFeasibility())
326  : cfg_(cfg), xfer_(xfer), merge_(merge), maxIterations_(-1), nIterations_(0), isFeasible_(isFeasible) {}
327 
332  const CFG &cfg() const {
333  return cfg_;
334  }
335 
337  void reset(State initialState = State()) {
338  ASSERT_this();
339  incomingState_.clear();
340  incomingState_.resize(cfg_.nVertices(), initialState);
341  outgoingState_.clear();
342  outgoingState_.resize(cfg_.nVertices(), initialState);
343  workList_.clear();
344  nIterations_ = 0;
345  }
346 
353  size_t maxIterations() const { return maxIterations_; }
354  void maxIterations(size_t n) { maxIterations_ = n; }
360  size_t nIterations() const { return nIterations_; }
361 
367  using namespace Diagnostics;
368  if (!workList_.isEmpty()) {
369  if (++nIterations_ > maxIterations_) {
370  throw NotConverging("data-flow max iterations reached"
371  " (max=" + StringUtility::numberToString(maxIterations_) + ")");
372  }
373  size_t cfgVertexId = workList_.popFront();
374  if (mlog[DEBUG]) {
375  mlog[DEBUG] <<"runOneIteration: vertex #" <<cfgVertexId <<"\n";
376  mlog[DEBUG] <<" remaining worklist is {";
377  BOOST_FOREACH (size_t id, workList_.items())
378  mlog[DEBUG] <<" " <<id;
379  mlog[DEBUG] <<" }\n";
380  }
381 
382  ASSERT_require2(cfgVertexId < cfg_.nVertices(),
383  "vertex " + boost::lexical_cast<std::string>(cfgVertexId) + " must be valid within CFG");
384  typename CFG::ConstVertexIterator vertex = cfg_.findVertex(cfgVertexId);
385  State state = incomingState_[cfgVertexId];
386  if (mlog[DEBUG]) {
387  mlog[DEBUG] <<" incoming state for vertex #" <<cfgVertexId <<":\n"
388  <<StringUtility::prefixLines(xfer_.printState(state), " ") <<"\n";
389  }
390 
391  state = outgoingState_[cfgVertexId] = xfer_(cfg_, cfgVertexId, state);
392  if (mlog[DEBUG]) {
393  mlog[DEBUG] <<" outgoing state for vertex #" <<cfgVertexId <<":\n"
394  <<StringUtility::prefixLines(xfer_.printState(state), " ") <<"\n";
395  }
396 
397  // Outgoing state must be merged into the incoming states for the CFG successors. Any such incoming state that
398  // is modified as a result will have its CFG vertex added to the work list.
399  SAWYER_MESG(mlog[DEBUG]) <<" forwarding vertex #" <<cfgVertexId <<" output state to "
400  <<StringUtility::plural(vertex->nOutEdges(), "vertices", "vertex") <<"\n";
401  BOOST_FOREACH (const typename CFG::Edge &edge, vertex->outEdges()) {
402  size_t nextVertexId = edge.target()->id();
403  if (!isFeasible_(cfg_, edge, state)) {
404  SAWYER_MESG(mlog[DEBUG]) <<" path to vertex #" <<nextVertexId <<" is not feasible, thus skipped\n";
405  } else if (merge_(incomingState_[nextVertexId], state)) {
406  if (mlog[DEBUG]) {
407  mlog[DEBUG] <<" merged with vertex #" <<nextVertexId <<" (which changed as a result)\n";
408  mlog[DEBUG] <<" merge state is: "
409  <<StringUtility::prefixLines(xfer_.printState(incomingState_[nextVertexId]),
410  " ", false) <<"\n";
411  }
412  workList_.pushBack(nextVertexId);
413  } else {
414  SAWYER_MESG(mlog[DEBUG]) <<" merged with vertex #" <<nextVertexId <<" (no change)\n";
415  }
416  }
417  }
418  return !workList_.isEmpty();
419  }
420 
422  void insertStartingVertex(size_t startVertexId, const State &initialState) {
423  incomingState_[startVertexId] = initialState;
424  workList_.pushBack(startVertexId);
425  }
426 
433  while (runOneIteration()) /*void*/;
434  }
435 
439  void runToFixedPoint(size_t startVertexId, const State &initialState) {
440  reset();
441  insertStartingVertex(startVertexId, initialState);
442  while (runOneIteration()) /*void*/;
443  }
444 
449  State getInitialState(size_t cfgVertexId) const {
450  return incomingState_[cfgVertexId];
451  }
452 
454  void setInitialState(size_t cfgVertexId, State state) {
455  incomingState_[cfgVertexId] = state;
456  }
457 
462  State getFinalState(size_t cfgVertexId) const {
463  return outgoingState_[cfgVertexId];
464  }
465 
470  const VertexStates& getInitialStates() const {
471  return incomingState_;
472  }
473 
478  const VertexStates& getFinalStates() const {
479  return outgoingState_;
480  }
481  };
482 };
483 
484 } // namespace
485 } // namespace
486 
487 #endif
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.
Basic merge operation for instruction semantics.
Base class for machine instructions.
Collection of streams.
Definition: Message.h:1579
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< class State > StatePtr
Shared-ownership pointer to a semantic state.
const VertexStates & getInitialStates() const
All incoming states.
boost::shared_ptr< class Dispatcher > DispatcherPtr
Shared-ownership pointer to a semantics instruction dispatcher.
VertexFlowGraphs buildGraphPerVertex(const CFG &cfg, size_t startVertex)
Compute data-flow per CFG vertex.
boost::shared_ptr< class RiscOperators > RiscOperatorsPtr
Shared-ownership pointer to a RISC operators object.
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:532
Functor to return instructions for a cfg vertex.
std::string plural(T n, const std::string &plural_word, const std::string &singular_word="")
Helpful way to print singular or plural words.
void maxIterations(size_t n)
Max number of iterations to allow.
void insertStartingVertex(size_t startVertexId, const State &initialState)
Add a starting vertex.
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:324
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.