Static Value-Flow Analysis
Loading...
Searching...
No Matches
SparseObjGraph.cpp
Go to the documentation of this file.
1//===- SparseObjGraph.cpp - Static packed Obj routes -----------------------===//
2
4
6#include "Graphs/SVFG.h"
8
9#include <deque>
10
11using namespace SVF;
12
13namespace
14{
15std::string baseName(const PAG& pag, NodeID base)
16{
17 const SVFVar* var = const_cast<PAG&>(pag).getGNode(base);
18 std::string name = var ? var->getName() : "";
19 return name.empty() ? "o" + std::to_string(base) : name;
20}
21
22std::string labelText(const PAG& pag, const NodeBS& bases)
23{
24 std::string out;
25 for (NodeID base : bases)
26 out += (out.empty() ? "" : ",") + baseName(pag, base);
27 return out;
28}
29} // namespace
30
31std::string SparseObjEdge::toString() const
32{
33 std::ostringstream out;
34 out << "edge " << getSrcID() << " -> " << getDstID() << " bases {";
35 bool first = true;
36 for (NodeID base : *bases)
37 {
38 out << (first ? "" : ",") << base;
39 first = false;
40 }
41 out << "}";
42 return out.str();
43}
44
45std::string SparseObjNode::toString() const
46{
47 std::ostringstream out;
48 out << "node " << getId() << " ICFG " << location->getId();
49 if (branch)
50 out << " branch " << branch->getSrcNode()->getId()
51 << " -> " << branch->getDstNode()->getId()
52 << " label " << branch->getSuccessorCondValue();
53 return out.str();
54}
55
57 PointerAnalysis& pta, const PAG& ir)
58 : icfg(graph), pag(ir)
59{
60 // Step 1: collect, for each base Obj, the ICFG locations of its events.
62 for (auto it = svfg.begin(); it != svfg.end(); ++it)
63 {
64 const VFGNode* vfg = it->second;
65 const ICFGNode* location = vfg->getICFGNode();
66 // Only in-function SVFG nodes participate here; global entry routes
67 // are connected below.
68 if (location && location->getFun())
69 {
70 // An indirect call edge identifies the packed Obj passed to the
71 // callee: C: f(&x) -> P: callee entry. Register both C and P as
72 // events for x so intra-function routing stops and resumes there;
73 // the interprocedural C -> P route is added here.
74 for (const VFGEdge* edge : vfg->getInEdges())
75 {
76 if (const auto* call = SVFUtil::dyn_cast<CallIndSVFGEdge>(edge))
77 {
78 const ICFGNode* caller = call->getSrcNode()->getICFGNode();
79 if (caller)
80 {
81 for (NodeID obj : call->getPointsTo())
82 {
83 if (!pag.isNullOrBlkObj(obj))
84 {
85 const NodeID base = pag.getBaseObject(obj)->getId();
86 eventsByBase[base].insert(caller);
87 eventsByBase[base].insert(location);
88 addRoute(base, caller, location, nullptr);
89 }
90 }
91 }
92 }
93 }
94
95 // MRSVFGNode already supplies points-to objects. Group each by
96 // base without modifying the SVFG or strong/weak update rules.
97 const ValVar* pointer = nullptr;
98 if (const auto* memory = SVFUtil::dyn_cast<MRSVFGNode>(vfg))
99 {
100 for (NodeID obj : memory->getPointsTo())
101 if (!pag.isNullOrBlkObj(obj))
102 eventsByBase[pag.getBaseObject(obj)->getId()].insert(location);
103 }
104 else if (const auto* store = SVFUtil::dyn_cast<StoreVFGNode>(vfg))
105 pointer = store->getLHSVar();
106 else if (const auto* load = SVFUtil::dyn_cast<LoadVFGNode>(vfg))
107 pointer = load->getRHSVar();
108
109 // Resolve ordinary load/store targets with points-to analysis.
110 // If p points to a[1], record a's base so a[0] and a[1] travel
111 // through this location as one packed Obj.
112 if (pointer)
113 {
114 for (NodeID obj : pta.getPts(pointer->getId()))
115 if (!pag.isNullOrBlkObj(obj))
116 eventsByBase[pag.getBaseObject(obj)->getId()].insert(location);
117 }
118 }
119 }
120
121 // Step 2: connect callee Obj outputs to the caller return location.
122 // For C: f(&x); R: return from the call, a RetIndSVFGEdge for x gives
123 // callee-output -> R, where AE can read the computed Obj value.
124 for (auto it = icfg.begin(); it != icfg.end(); ++it)
125 {
126 if (const auto* ret = SVFUtil::dyn_cast<RetICFGNode>(it->second))
127 {
128 for (const VFGNode* target : ret->getVFGNodes())
129 {
130 for (const VFGEdge* edge : target->getInEdges())
131 {
132 if (const auto* output = SVFUtil::dyn_cast<RetIndSVFGEdge>(edge))
133 {
134 const ICFGNode* source = output->getSrcNode()->getICFGNode();
135 if (source)
136 {
137 for (NodeID obj : output->getPointsTo())
138 {
139 if (!pag.isNullOrBlkObj(obj))
140 {
141 const NodeID base = pag.getBaseObject(obj)->getId();
142 returnedGroups[ret].set(base);
143 if (source->getFun())
144 returnedGroupsByCallee[ret][source->getFun()].set(base);
145 eventsByBase[base].insert(ret);
146 if (source->getFun())
147 eventsByBase[base].insert(source);
148 addRoute(base, source, ret, nullptr);
149 }
150 }
151 }
152 }
153 }
154 }
155 }
156 }
157
158 // Index events by location and by function: a base is routed inside a
159 // function only if it has an event there (as in the per-base walk, whose
160 // sources are the base's events and the entries of their functions).
163 Set<NodeID> globalBases;
164 for (const auto& [base, events] : eventsByBase)
165 {
166 if (pag.getBaseObject(base)->isGlobalObj())
167 globalBases.insert(base);
168 for (const ICFGNode* event : events)
169 {
170 eventsAt[event].set(base);
171 funBases[event->getFun()].set(base);
172 }
173 }
174
175 // Connect global objects from global initialization to function entries.
176 if (!globalBases.empty())
177 {
178 NodeBS globals;
179 for (NodeID base : globalBases)
180 globals.set(base);
181 const ICFGNode* global = icfg.getGlobalICFGNode();
182 for (const ICFGEdge* edge : global->getOutEdges())
183 {
184 const ICFGNode* entry = edge->getDstNode();
185 if (!SVFUtil::isa<FunEntryICFGNode>(entry))
186 continue;
187 const auto bases = funBases.find(entry->getFun());
188 if (bases == funBases.end())
189 continue;
190 NodeBS label = globals & bases->second;
191 if (!label.empty())
192 addRoute(label, global, entry, nullptr);
193 }
194 }
195
196 // Step 3: connect consecutive Obj events in ICFG order, one walk per
197 // function carrying base sets.
198 for (const auto& [fun, bases] : funBases)
199 connectFunction(fun, bases, eventsAt);
200
201 finalize();
202}
203
205
206bool SparseObjGraph::isBranch(const ICFGNode* node) const
207{
208 // Only conditional intra-function ICFG edges count as branches.
209 for (const ICFGEdge* out : node->getOutEdges())
210 {
211 const auto* intra = SVFUtil::dyn_cast<IntraCFGEdge>(out);
212 if (intra && intra->getCondition())
213 return true;
214 }
215 return false;
216}
217
219{
220 return isBranch(node) || SVFUtil::isa<CallICFGNode>(node) ||
222}
223
224void SparseObjGraph::addRoute(NodeID base, const ICFGNode* source,
225 const ICFGNode* target,
226 const IntraCFGEdge* branch)
227{
228 NodeBS bases;
229 bases.set(base);
230 addRoute(bases, source, target, branch);
231}
232
233void SparseObjGraph::addRoute(const NodeBS& bases, const ICFGNode* source,
234 const ICFGNode* target,
235 const IntraCFGEdge* branch)
236{
237 // B: if (z > 0) { use(x); use(z); }. For base z the route is
238 // B -> (B, true edge) -> Uz; AE refines B's state on the true edge
239 // once and then reads every base labeled on (B, true edge) -> Uz.
240 const NodeKey from{source, nullptr};
241 const NodeKey to{target, nullptr};
242 if (branch)
243 {
244 const NodeKey via{source, branch};
245 routeLabels[ {from, via}] |= bases;
246 routeLabels[ {via, to}] |= bases;
247 }
248 else
249 routeLabels[ {from, to}] |= bases;
250}
251
253 const FunObjVar* fun, const NodeBS& funBases,
254 const Map<const ICFGNode*, NodeBS>& eventsAt)
255{
256 // A source starts a route segment for some bases: their events, the
257 // function entry, and the control boundaries they reach. Each source
258 // processes only newly added bases; per base this is exactly the per-base
259 // walk, since a base's walk does not depend on other bases.
260 doneSources.clear();
261 pendingSources.clear();
262 sourceWorklist.clear();
263
264 addSource(icfg.getFunEntryICFGNode(fun), funBases);
265 for (const auto& event : eventsAt)
266 if (event.first->getFun() == fun)
267 addSource(event.first, event.second);
268
269 while (!sourceWorklist.empty())
270 {
271 const ICFGNode* source = sourceWorklist.front();
272 sourceWorklist.pop_front();
273 NodeBS fresh = std::move(pendingSources[source]);
274 pendingSources.erase(source);
276 if (fresh.empty())
277 continue;
278 doneSources[source] |= fresh;
279
280 if (const CallICFGNode* call = SVFUtil::dyn_cast<CallICFGNode>(source))
281 {
282 connectCallBypass(call, fresh);
283 continue;
284 }
285 for (const ICFGEdge* out : source->getOutEdges())
286 {
288 if (!intra)
289 continue;
290 const IntraCFGEdge* branch = intra->getCondition() ? intra : nullptr;
291 connectSegment(fun, source, intra->getDstNode(), branch, fresh,
292 eventsAt);
293 }
294 }
295}
296
297void SparseObjGraph::addSource(const ICFGNode* node, const NodeBS& bases)
298{
299 NodeBS fresh = bases;
300 const auto done = doneSources.find(node);
301 if (done != doneSources.end())
302 fresh.intersectWithComplement(done->second);
303 if (fresh.empty())
304 return;
305 NodeBS& waiting = pendingSources[node];
306 if (waiting.empty())
307 sourceWorklist.push_back(node);
308 waiting |= fresh;
309}
310
312 const NodeBS& bases)
313{
314 // C may call f_write(&x) or f_noop(&x). If a callee has no return edge
315 // for x, retain C -> R so that candidate carries the pre-call value; a
316 // candidate with a return edge uses callee-output -> R.
317 const RetICFGNode* ret = call->getRetICFGNode();
318 NodeBS returned;
319 const auto all = returnedGroups.find(ret);
320 if (all != returnedGroups.end())
321 returned = all->second;
322 const auto byCallee = returnedGroupsByCallee.find(ret);
323 for (const ICFGEdge* out : call->getOutEdges())
324 {
326 continue;
327 const NodeBS* calleeBases = nullptr;
328 if (byCallee != returnedGroupsByCallee.end())
329 {
330 const auto callee = byCallee->second.find(out->getDstNode()->getFun());
331 if (callee != byCallee->second.end())
332 calleeBases = &callee->second;
333 }
334 if (calleeBases)
335 returned &= *calleeBases;
336 else
337 returned.clear();
338 }
339
340 NodeBS bypass = bases;
341 bypass.intersectWithComplement(returned);
342 if (bypass.empty())
343 return;
344 // The return site is a control boundary: every bypassing base stops
345 // there and starts its next segment.
346 addRoute(bypass, call, ret, nullptr);
347 addSource(ret, bypass);
348}
349
351 const FunObjVar* fun, const ICFGNode* source, const ICFGNode* start,
352 const IntraCFGEdge* branch, const NodeBS& bases,
353 const Map<const ICFGNode*, NodeBS>& eventsAt)
354{
355 // Cross ordinary ICFG nodes between events, carrying the set of bases
356 // still travelling. A base stops at its next event; every base stops at
357 // a branch, call, or return.
359 std::deque<std::pair<const ICFGNode*, NodeBS>> walk;
360 walk.emplace_back(start, bases);
361 while (!walk.empty())
362 {
363 const ICFGNode* current = walk.front().first;
364 NodeBS travelling = std::move(walk.front().second);
365 walk.pop_front();
366 if (!current || current->getFun() != fun)
367 continue;
368 NodeBS& seen = arrived[current];
369 travelling.intersectWithComplement(seen);
370 if (travelling.empty())
371 continue;
372 seen |= travelling;
373
374 if (isControlBoundary(current))
375 {
376 addRoute(travelling, source, current, branch);
377 addSource(current, travelling);
378 continue;
379 }
380 NodeBS stop = travelling & getEvents(eventsAt, current);
381 if (!stop.empty())
382 {
383 addRoute(stop, source, current, branch);
384 travelling.intersectWithComplement(stop);
385 }
386 if (travelling.empty())
387 continue;
388 for (const ICFGEdge* next : current->getOutEdges())
390 walk.emplace_back(intra->getDstNode(), travelling);
391 }
392}
393
395 const Map<const ICFGNode*, NodeBS>& eventsAt, const ICFGNode* node)
396{
397 static const NodeBS empty;
398 const auto it = eventsAt.find(node);
399 return it == eventsAt.end() ? empty : it->second;
400}
401
403 const ICFGNode* location, const IntraCFGEdge* branch)
404{
405 Node*& node = nodes[ {location, branch}];
406 if (!node)
407 {
408 node = new Node(getTotalNodeNum(), location, branch);
409 addGNode(node->getId(), node);
410 }
411 return node;
412}
413
415{
416 u64_t hash = 1469598103934665603ULL;
417 for (NodeID base : bases)
418 hash = (hash ^ base) * 1099511628211ULL;
419 auto& bucket = labels[hash];
420 for (const auto& label : bucket)
421 if (*label == bases)
422 return label.get();
423 bucket.push_back(std::make_unique<NodeBS>(bases));
424 return bucket.back().get();
425}
426
428{
429 for (const auto& [key, bases] : routeLabels)
430 {
431 Node* source = getOrCreateNode(key.first.first, key.first.second);
432 Node* target = getOrCreateNode(key.second.first, key.second.second);
433 Edge* edge = new Edge(source, target, intern(bases));
434 const bool addedOut = source->addOutgoingEdge(edge);
435 const bool addedIn = target->addIncomingEdge(edge);
436 assert(addedOut && addedIn);
437 (void)addedOut;
438 (void)addedIn;
439 incEdgeNum();
440 if (!target->branch)
441 inputs[target->location].push_back(edge);
442 }
443 routeLabels.clear();
444}
445
446const std::vector<const SparseObjGraph::Edge*>&
448{
449 static const std::vector<const Edge*> empty;
450 const auto it = inputs.find(node);
451 return it == inputs.end() ? empty : it->second;
452}
453
454std::string SparseObjGraph::toString() const
455{
456 std::ostringstream out;
457 for (const auto& entry : *this)
458 out << entry.second->toString() << '\n';
459 for (const auto& entry : *this)
460 for (const Edge* edge : entry.second->getOutEdges())
461 out << edge->toString() << '\n';
462 return out.str();
463}
464
465namespace SVF
466{
467
468template<>
470{
471 DOTGraphTraits(bool simple = false) : DefaultDOTGraphTraits(simple) {}
472
473 static std::string getGraphName(SparseObjGraph*)
474 {
475 return "Sparse object routes";
476 }
477
478 static std::string getNodeLabel(SparseObjNode* node, SparseObjGraph*)
479 {
480 std::ostringstream out;
481 const ICFGNode* loc = node->location;
482 if (node->branch)
483 {
484 out << "branch ICFG" << loc->getId() << " -> ICFG"
485 << node->branch->getDstNode()->getId() << " ["
486 << (node->branch->getSuccessorCondValue() ? "true" : "false") << "]";
487 return out.str();
488 }
489 out << "ICFG" << loc->getId();
490 if (loc->getFun())
491 out << " @" << loc->getFun()->getName();
492 if (SVFUtil::isa<FunEntryICFGNode>(loc)) out << " (entry)";
493 else if (SVFUtil::isa<FunExitICFGNode>(loc)) out << " (exit)";
494 else if (SVFUtil::isa<CallICFGNode>(loc)) out << " (call)";
495 else if (SVFUtil::isa<RetICFGNode>(loc)) out << " (ret)";
496 else if (SVFUtil::isa<GlobalICFGNode>(loc)) out << " (global)";
497 std::string kinds;
498 for (const SVFStmt* stmt : loc->getSVFStmts())
499 {
500 const char* k = SVFUtil::isa<StoreStmt>(stmt) ? "store"
501 : SVFUtil::isa<LoadStmt>(stmt) ? "load"
502 : SVFUtil::isa<BranchStmt>(stmt) ? "branch" : nullptr;
503 if (k && kinds.find(k) == std::string::npos)
504 kinds += std::string(kinds.empty() ? "" : "+") + k;
505 }
506 std::string line;
507 {
508 const std::string src = loc->getSourceLoc();
509 const size_t ln = src.find("\"ln\": ");
510 if (ln != std::string::npos)
511 line = src.substr(ln + 6, src.find_first_of(",}", ln + 6) - ln - 6);
512 }
513 if (!line.empty() && line != "0")
514 out << " line " << line;
515 if (!kinds.empty())
516 out << "\n" << kinds;
517 return out.str();
518 }
519
521 {
522 return node->branch ? "shape=diamond,style=filled,fillcolor=\"#ffedd5\""
523 : "shape=box,style=filled,fillcolor=\"#dbeafe\"";
524 }
525
526 template <class EdgeIter>
527 static std::string getEdgeAttributes(SparseObjNode* node, EdgeIter it,
528 SparseObjGraph* graph)
529 {
530 const SparseObjEdge* edge = *(it.getCurrent());
531 std::string label = labelText(graph->getPAG(), edge->getBases());
532 std::string attr = "label=\"{" + label + "}\"";
533 const SparseObjNode* target = edge->getDstNode();
534 if (node->location->getFun() != target->location->getFun())
535 attr += ",color=blue,style=dashed,fontcolor=blue";
536 else if (node->branch || target->branch)
537 attr += ",color=\"#c2410c\",fontcolor=\"#c2410c\"";
538 return attr;
539 }
540};
541
542} // namespace SVF
543
544void SparseObjGraph::dump(const std::string& file)
545{
547}
item next
Definition cJSON.cpp:2224
const char *const name
Definition cJSON.h:264
bool isGlobalObj() const
const RetICFGNode * getRetICFGNode() const
Return callsite.
Definition ICFGNode.h:440
NodeType * getDstNode() const
iterator begin()
Iterators.
const GEdgeSetTy & getOutEdges() const
bool addIncomingEdge(EdgeType *inEdge)
Add incoming and outgoing edges.
bool addOutgoingEdge(EdgeType *outEdge)
static void WriteGraphToFile(SVF::OutStream &O, const std::string &GraphName, const GraphType &GT, bool simple=false)
virtual const FunObjVar * getFun() const
Return the function of this ICFGNode.
Definition ICFGNode.h:75
const SVFStmtList & getSVFStmts() const
Definition ICFGNode.h:116
s64_t getSuccessorCondValue() const
Definition ICFGEdge.h:144
const SVFVar * getCondition() const
Definition ICFGEdge.h:139
Definition PAG.h:46
const BaseObjVar * getBaseObject(NodeID id) const
Definition PAG.h:499
NodeID getId() const
Get ID.
Definition SVFValue.h:158
virtual const std::string getSourceLoc() const
Definition SVFValue.h:194
virtual const std::string & getName() const
Definition SVFValue.h:184
void set(unsigned Idx)
bool intersectWithComplement(const SparseBitVector &RHS)
const NodeBS & getBases() const
Base Obj IDs routed over this edge; each base carries all its fields.
std::string toString() const
const NodeBS * bases
const std::vector< const Edge * > & getInputs(const ICFGNode *node) const
Return incoming edges at this ICFG location for client-side value flow.
void addSource(const ICFGNode *node, const NodeBS &bases)
bool isBranch(const ICFGNode *node) const
Map< const ICFGNode *, std::vector< const Edge * > > inputs
static const NodeBS & getEvents(const Map< const ICFGNode *, NodeBS > &eventsAt, const ICFGNode *node)
const PAG & getPAG() const
Map< NodeKey, Node * > nodes
std::pair< const ICFGNode *, const IntraCFGEdge * > NodeKey
Map< u64_t, std::vector< std::unique_ptr< NodeBS > > > labels
Interned labels, bucketed by hash.
SparseObjGraph(const SVFG &svfg, ICFG &icfg, PointerAnalysis &pta, const PAG &pag)
Construction uses static graphs and points-to results, not AE state.
void connectCallBypass(const CallICFGNode *call, const NodeBS &bases)
Route the bases that no callee returns from the call to its return site.
Map< const ICFGNode *, NodeBS > returnedGroups
Map< const ICFGNode *, Map< const FunObjVar *, NodeBS > > returnedGroupsByCallee
bool isControlBoundary(const ICFGNode *node) const
std::map< EdgeKey, NodeBS > routeLabels
Map< const ICFGNode *, NodeBS > doneSources
Worklist of connectFunction for the function being connected.
Node * getOrCreateNode(const ICFGNode *location, const IntraCFGEdge *branch)
void connectFunction(const FunObjVar *fun, const NodeBS &funBases, const Map< const ICFGNode *, NodeBS > &eventsAt)
Walk one function once, carrying base sets instead of one base.
void connectSegment(const FunObjVar *fun, const ICFGNode *source, const ICFGNode *start, const IntraCFGEdge *branch, const NodeBS &bases, const Map< const ICFGNode *, NodeBS > &eventsAt)
~SparseObjGraph() override
std::deque< const ICFGNode * > sourceWorklist
std::string toString() const
Describe the static nodes and edges as text, without AE values.
const NodeBS * intern(const NodeBS &bases)
Map< const ICFGNode *, NodeBS > pendingSources
void dump(const std::string &file)
Write a DOT graph to <file>.dot through GraphPrinter.
void addRoute(const NodeBS &bases, const ICFGNode *source, const ICFGNode *target, const IntraCFGEdge *branch)
const IntraCFGEdge * branch
const ICFGNode * location
std::string toString() const
LLVM_NODISCARD bool isa(const Y &Val)
Definition Casting.h:241
std::ostream & outs()
Overwrite llvm::outs().
Definition SVFUtil.h:58
LLVM_NODISCARD std::enable_if_t<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition Casting.h:405
for isBitcode
Definition BasicTypes.h:70
unsigned long long u64_t
Definition GeneralType.h:69
u32_t NodeID
Definition GeneralType.h:76
std::unordered_set< Key, Hash, KeyEqual, Allocator > Set
Definition GeneralType.h:51
std::unordered_map< Key, Value, Hash, KeyEqual, Allocator > Map
Definition GeneralType.h:56
SparseBitVector NodeBS
Definition GeneralType.h:82
static std::string getEdgeAttributes(SparseObjNode *node, EdgeIter it, SparseObjGraph *graph)
static std::string getGraphName(SparseObjGraph *)
static std::string getNodeLabel(SparseObjNode *node, SparseObjGraph *)
static std::string getNodeAttributes(SparseObjNode *node, SparseObjGraph *)
DefaultDOTGraphTraits(bool simple=false)