ROSE  0.10.5.0
BinaryDataFlow.h
1 #ifndef ROSE_BinaryAnalysis_DataFlow_H
2 #define ROSE_BinaryAnalysis_DataFlow_H
3 
4 #include <rosePublicConfig.h>
5 #ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT
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->get_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&) {
247  return true;
248  }
249  };
250 
304  template<class CFG, class State, class TransferFunction, class MergeFunction,
305  class PathFeasibility = PathAlwaysFeasible<CFG, State> >
306  class Engine {
307  public:
308  typedef std::vector<State> VertexStates;
310  private:
311  const CFG &cfg_;
312  TransferFunction &xfer_;
313  MergeFunction merge_;
314  VertexStates incomingState_; // incoming data-flow state per CFG vertex ID
315  VertexStates outgoingState_; // outgoing data-flow state per CFG vertex ID
317  WorkList workList_; // CFG vertex IDs to be visited, last in first out w/out duplicates
318  size_t maxIterations_; // max number of iterations to allow
319  size_t nIterations_; // number of iterations since last reset
320  PathFeasibility isFeasible_; // predicate to test path feasibility
321 
322  public:
328  Engine(const CFG &cfg, TransferFunction &xfer, MergeFunction merge = MergeFunction(),
329  PathFeasibility isFeasible = PathFeasibility())
330  : cfg_(cfg), xfer_(xfer), merge_(merge), maxIterations_(-1), nIterations_(0), isFeasible_(isFeasible) {}
331 
336  const CFG &cfg() const {
337  return cfg_;
338  }
339 
341  void reset(State initialState = State()) {
342  ASSERT_this();
343  incomingState_.clear();
344  incomingState_.resize(cfg_.nVertices(), initialState);
345  outgoingState_.clear();
346  outgoingState_.resize(cfg_.nVertices(), initialState);
347  workList_.clear();
348  nIterations_ = 0;
349  }
350 
357  size_t maxIterations() const { return maxIterations_; }
358  void maxIterations(size_t n) { maxIterations_ = n; }
364  size_t nIterations() const { return nIterations_; }
365 
371  using namespace Diagnostics;
372  if (!workList_.isEmpty()) {
373  if (++nIterations_ > maxIterations_) {
374  throw NotConverging("data-flow max iterations reached"
375  " (max=" + StringUtility::numberToString(maxIterations_) + ")");
376  }
377  size_t cfgVertexId = workList_.popFront();
378  if (mlog[DEBUG]) {
379  mlog[DEBUG] <<"runOneIteration: vertex #" <<cfgVertexId <<"\n";
380  mlog[DEBUG] <<" remaining worklist is {";
381  BOOST_FOREACH (size_t id, workList_.items())
382  mlog[DEBUG] <<" " <<id;
383  mlog[DEBUG] <<" }\n";
384  }
385 
386  ASSERT_require2(cfgVertexId < cfg_.nVertices(),
387  "vertex " + boost::lexical_cast<std::string>(cfgVertexId) + " must be valid within CFG");
388  typename CFG::ConstVertexIterator vertex = cfg_.findVertex(cfgVertexId);
389  State state = incomingState_[cfgVertexId];
390  if (mlog[DEBUG]) {
391  mlog[DEBUG] <<" incoming state for vertex #" <<cfgVertexId <<":\n"
392  <<StringUtility::prefixLines(xfer_.printState(state), " ") <<"\n";
393  }
394 
395  state = outgoingState_[cfgVertexId] = xfer_(cfg_, cfgVertexId, state);
396  if (mlog[DEBUG]) {
397  mlog[DEBUG] <<" outgoing state for vertex #" <<cfgVertexId <<":\n"
398  <<StringUtility::prefixLines(xfer_.printState(state), " ") <<"\n";
399  }
400 
401  // Outgoing state must be merged into the incoming states for the CFG successors. Any such incoming state that
402  // is modified as a result will have its CFG vertex added to the work list.
403  SAWYER_MESG(mlog[DEBUG]) <<" forwarding vertex #" <<cfgVertexId <<" output state to "
404  <<StringUtility::plural(vertex->nOutEdges(), "vertices", "vertex") <<"\n";
405  BOOST_FOREACH (const typename CFG::Edge &edge, vertex->outEdges()) {
406  size_t nextVertexId = edge.target()->id();
407  if (!isFeasible_(cfg_, edge, state)) {
408  SAWYER_MESG(mlog[DEBUG]) <<" path to vertex #" <<nextVertexId <<" is not feasible, thus skipped\n";
409  } else if (merge_(incomingState_[nextVertexId], state)) {
410  if (mlog[DEBUG]) {
411  mlog[DEBUG] <<" merged with vertex #" <<nextVertexId <<" (which changed as a result)\n";
412  mlog[DEBUG] <<" merge state is: "
413  <<StringUtility::prefixLines(xfer_.printState(incomingState_[nextVertexId]),
414  " ", false) <<"\n";
415  }
416  workList_.pushBack(nextVertexId);
417  } else {
418  SAWYER_MESG(mlog[DEBUG]) <<" merged with vertex #" <<nextVertexId <<" (no change)\n";
419  }
420  }
421  }
422  return !workList_.isEmpty();
423  }
424 
426  void insertStartingVertex(size_t startVertexId, const State &initialState) {
427  incomingState_[startVertexId] = initialState;
428  workList_.pushBack(startVertexId);
429  }
430 
437  while (runOneIteration()) /*void*/;
438  }
439 
443  void runToFixedPoint(size_t startVertexId, const State &initialState) {
444  reset();
445  insertStartingVertex(startVertexId, initialState);
446  while (runOneIteration()) /*void*/;
447  }
448 
453  State getInitialState(size_t cfgVertexId) const {
454  return incomingState_[cfgVertexId];
455  }
456 
458  void setInitialState(size_t cfgVertexId, State state) {
459  incomingState_[cfgVertexId] = state;
460  }
461 
466  State getFinalState(size_t cfgVertexId) const {
467  return outgoingState_[cfgVertexId];
468  }
469 
474  const VertexStates& getInitialStates() const {
475  return incomingState_;
476  }
477 
482  const VertexStates& getFinalStates() const {
483  return outgoingState_;
484  }
485  };
486 };
487 
488 } // namespace
489 } // namespace
490 
491 #endif
492 #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:1600
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.