Static Value-Flow Analysis
Loading...
Searching...
No Matches
SVF::BufOverflowDetector Class Reference

Detector for identifying buffer overflow issues. More...

#include <AEDetector.h>

Inheritance diagram for SVF::BufOverflowDetector:
SVF::AEDetector

Classes

struct  BufferOverflowInfo

Public Member Functions

 BufOverflowDetector ()
 Constructor initializes the detector kind to BUF_OVERFLOW and sets up external API buffer overflow rules.
 ~BufOverflowDetector ()=default
 Destructor.
void updateGepObjOffsetFromBase (const ICFGNode *node, AddressValue gepAddrs, AddressValue objAddrs, IntervalValue offset)
 Updates the offset of a GEP object from its base.
void detect (const ICFGNode *) override
 Detect buffer overflow issues within a node.
void handleStubFunctions (const CallICFGNode *) override
 Handles external API calls related to buffer overflow detection.
void addToGepObjOffsetFromBase (const GepObjVar *obj, const IntervalValue &offset)
 Adds an offset to a GEP object.
bool hasGepObjOffsetFromBase (const GepObjVar *obj) const
 Checks if a GEP object has an associated offset.
IntervalValue getGepObjOffsetFromBase (const GepObjVar *obj) const
 Retrieves the offset of a GEP object from its base.
IntervalValue getAccessOffset (NodeID objId, const GepStmt *gep)
 Retrieves the access offset for a given object and GEP statement.
void addBugToReporter (const ICFGNode *node, const SVFStmt *stmt=nullptr)
 Reports a bug, generating its text only for a new location.
void addBugToReporter (const ICFGNode *node, const BufferOverflowInfo &info, const SVFStmt *stmt=nullptr)
 Report an OOB alarm with the buffer size and offset from its check.
void reportBug () override
 Reports all detected buffer overflow bugs.
void initExtAPIBufOverflowCheckRules ()
 Initializes external API buffer overflow check rules.
void detectExtAPI (const CallICFGNode *call)
 Handles external API calls related to buffer overflow detection.
bool canSafelyAccessMemory (const ValVar *value, const IntervalValue &len, const ICFGNode *node, BufferOverflowInfo *info=nullptr)
 Checks if memory can be safely accessed.
Public Member Functions inherited from SVF::AEDetector
 AEDetector ()
 Constructor initializes the detector kind to UNKNOWN.
virtual ~AEDetector ()=default
 Virtual destructor for safe polymorphic use.
DetectorKind getKind () const
 Get the kind of the detector.

Static Public Member Functions

static bool classof (const AEDetector *detector)
 Check if the detector is of the BUF_OVERFLOW kind.
Static Public Member Functions inherited from SVF::AEDetector
static bool classof (const AEDetector *detector)
 Check if the detector is of the UNKNOWN kind.

Private Member Functions

bool detectStrcat (const CallICFGNode *call, BufferOverflowInfo &info)
 Detects buffer overflow in 'strcat' function calls.
bool detectStrcpy (const CallICFGNode *call, BufferOverflowInfo &info)
 Detects buffer overflow in 'strcpy' function calls.

Private Attributes

Map< const GepObjVar *, IntervalValue > gepObjOffsetFromBase
 Maps GEP objects to their offsets from the base.
Map< std::string, std::vector< std::pair< u32_t, u32_t > > > extAPIBufOverflowCheckRules
 Rules for checking buffer overflows in external APIs.
Set< std::string > bugLoc
 Set of locations where bugs have been reported.
SVFBugReport recoder
 Recorder for abstract execution bugs.
Map< const ICFGNode *, std::string > nodeToBugInfo
 Maps ICFG nodes to bug information.

Friends

class AbstractInterpretation

Additional Inherited Members

Public Types inherited from SVF::AEDetector
enum  DetectorKind { BUF_OVERFLOW , NULL_DEREF , UNKNOWN }
 Enumerates the types of detectors available. More...
Protected Attributes inherited from SVF::AEDetector
DetectorKind kind
 The kind of the detector.

Detailed Description

Detector for identifying buffer overflow issues.

Definition at line 111 of file AEDetector.h.

Constructor & Destructor Documentation

◆ BufOverflowDetector()

SVF::BufOverflowDetector::BufOverflowDetector ( )
inline

Constructor initializes the detector kind to BUF_OVERFLOW and sets up external API buffer overflow rules.

Definition at line 124 of file AEDetector.h.

125 {
128 }
@ BUF_OVERFLOW
Detector for buffer overflow issues.
Definition AEDetector.h:51
DetectorKind kind
The kind of the detector.
Definition AEDetector.h:104
void initExtAPIBufOverflowCheckRules()
Initializes external API buffer overflow check rules.

◆ ~BufOverflowDetector()

SVF::BufOverflowDetector::~BufOverflowDetector ( )
default

Destructor.

Member Function Documentation

◆ addBugToReporter() [1/2]

void SVF::BufOverflowDetector::addBugToReporter ( const ICFGNode * node,
const BufferOverflowInfo & info,
const SVFStmt * stmt = nullptr )
inline

Report an OOB alarm with the buffer size and offset from its check.

Definition at line 227 of file AEDetector.h.

229 {
230
231 GenericBug::EventStack eventStack;
232 SVFBugEvent sourceInstEvent(SVFBugEvent::EventType::SourceInst, node);
233 eventStack.push_back(sourceInstEvent); // Add the source instruction event to the event stack
234
235 if (eventStack.empty())
236 {
237 return; // If the event stack is empty, return early
238 }
239
240 std::string loc = eventStack.back().getEventLoc(); // Get the location of the last event in the stack
241
242 // Check if the bug at this location has already been reported
243 if (bugLoc.find(loc) != bugLoc.end())
244 {
245 return; // If the bug location is already reported, return early
246 }
247 else
248 {
249 bugLoc.insert(loc); // Otherwise, mark this location as reported
250 }
251
252 // Add the bug to the recorder with details from the event stack
253 recoder.addAbsExecBug(GenericBug::FULLBUFOVERFLOW, eventStack,
254 info.bufferSize.lb(), info.bufferSize.ub(),
255 info.accessOffset.lb(), info.accessOffset.ub());
256 // Duplicate locations returned above without formatting the IR again.
257 nodeToBugInfo[node] = stmt ? stmt->toString() : node->toString();
258 }
SVFBugReport recoder
Recorder for abstract execution bugs.
Definition AEDetector.h:318
Set< std::string > bugLoc
Set of locations where bugs have been reported.
Definition AEDetector.h:317
Map< const ICFGNode *, std::string > nodeToBugInfo
Maps ICFG nodes to bug information.
Definition AEDetector.h:319
std::vector< SVFBugEvent > EventStack

◆ addBugToReporter() [2/2]

void SVF::BufOverflowDetector::addBugToReporter ( const ICFGNode * node,
const SVFStmt * stmt = nullptr )
inline

Reports a bug, generating its text only for a new location.

Parameters
nodePointer to the ICFG node where the bug was detected.
stmtOptional statement to describe; otherwise describe node.

Definition at line 221 of file AEDetector.h.

222 {
224 }
void addBugToReporter(const ICFGNode *node, const SVFStmt *stmt=nullptr)
Reports a bug, generating its text only for a new location.
Definition AEDetector.h:221

◆ addToGepObjOffsetFromBase()

void SVF::BufOverflowDetector::addToGepObjOffsetFromBase ( const GepObjVar * obj,
const IntervalValue & offset )
inline

Adds an offset to a GEP object.

Parameters
objPointer to the GEP object.
offsetThe interval value of the offset.

Definition at line 176 of file AEDetector.h.

177 {
179 }
buffer offset
Definition cJSON.cpp:1113
Map< const GepObjVar *, IntervalValue > gepObjOffsetFromBase
Maps GEP objects to their offsets from the base.
Definition AEDetector.h:315

◆ canSafelyAccessMemory()

bool BufOverflowDetector::canSafelyAccessMemory ( const ValVar * value,
const IntervalValue & len,
const ICFGNode * node,
BufferOverflowInfo * info = nullptr )

Checks if memory can be safely accessed.

Checks if a memory access is safe given a specific buffer length.

Parameters
valuePointer to the SVF var.
lenThe interval value representing the length of the memory access.
nodeThe ICFG node providing context.
Returns
True if the memory access is safe, false otherwise.

This function ensures that a given memory access, starting at a specific value, does not exceed the allocated size of the buffer.

Parameters
asReference to the abstract state.
valuePointer to the SVF var.
lenThe interval value representing the length of the memory access.
Returns
True if the memory access is safe, false otherwise.

Definition at line 483 of file AEDetector.cpp.

485{
486 if (info) *info = {};
487 PAG* pag = PAG::getPAG();
489
490 AbstractValue ptrVal = ae.getAbsValue(value, node);
491 if (!ptrVal.isAddr())
492 {
493 ptrVal = AddressValue(BlackHoleObjAddr);
494 ae.updateAbsValue(value, ptrVal, node);
495 }
496
497 const AddressValue& addresses = ptrVal.getAddrs();
498 if (std::any_of(addresses.begin(), addresses.end(), [&](u32_t addr)
499{
500 return pag->isNullOrBlkObj(ae.getAbsState(node).getIDFromAddr(addr));
501 }))
502 return false;
503
504 for (const auto& addr : addresses)
505 {
506 NodeID objId = ae.getAbsState(node).getIDFromAddr(addr);
507 u32_t size = 0;
508 u32_t lower = 0;
509 // if the object is a constant size object, get the size directly
510 if (pag->getBaseObject(objId)->isConstantByteSize())
511 {
512 size = pag->getBaseObject(objId)->getByteSizeOfObj();
513 lower = size;
514 }
515 else
516 {
517 // if the object is not a constant size object, get the size from the addrStmt
518 const ICFGNode* addrNode = pag->getBaseObject(objId)->getICFGNode();
519 if (!addrNode)
520 return false;
521 for (const SVFStmt* stmt2 : addrNode->getSVFStmts())
522 {
523 if (const AddrStmt* addrStmt = SVFUtil::dyn_cast<AddrStmt>(stmt2))
524 {
525 const auto bounds = ae.getAllocaInstByteSize(addrStmt);
526 size = bounds.upperBound;
527 lower = bounds.lowerBound;
528 }
529 }
530 }
531
532 IntervalValue offset(0);
533 // if the object is a GepObjVar, get the offset from the base object
534 if (SVFUtil::isa<GepObjVar>(pag->getSVFVar(objId)))
535 {
537 }
538 else if (SVFUtil::isa<BaseObjVar>(pag->getSVFVar(objId)))
539 {
540 // if the object is a BaseObjVar, get the offset directly
541 offset = len;
542 }
543
544 // if the offset is greater than the size, return false
545 if (offset.ub().getIntNumeral() >= size)
546 {
547 if (info) *info = {IntervalValue(lower, size), offset};
548 return false;
549 }
550 }
551 return true;
552}
#define BlackHoleObjAddr
static AbstractInterpretation & getAEInstance()
AddressValue & getAddrs()
bool isAddr() const
AddrSet::const_iterator end() const
AddrSet::const_iterator begin() const
const ICFGNode * getICFGNode() const
Get the ICFGNode related to the creation of this object.
bool isConstantByteSize() const
Check if byte size is a const value.
u32_t getByteSizeOfObj() const
Get the byte size of this object.
IntervalValue getGepObjOffsetFromBase(const GepObjVar *obj) const
Retrieves the offset of a GEP object from its base.
Definition AEDetector.h:196
const SVFStmtList & getSVFStmts() const
Definition ICFGNode.h:116
static PAG * getPAG(bool buildFromFile=false)
Singleton design here to make sure we only have one instance during any analysis.
Definition PAG.h:121
const BaseObjVar * getBaseObject(NodeID id) const
Definition PAG.h:499
const SVFVar * getSVFVar(NodeID id) const
ObjVar/GepObjVar/BaseObjVar.
Definition PAG.h:136
std::enable_if_t<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > cast(const Y &Val)
Definition Casting.h:360
LLVM_NODISCARD bool isa(const Y &Val)
Definition Casting.h:241
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
u32_t NodeID
Definition GeneralType.h:76
unsigned u32_t
Definition GeneralType.h:67

◆ classof()

bool SVF::BufOverflowDetector::classof ( const AEDetector * detector)
inlinestatic

Check if the detector is of the BUF_OVERFLOW kind.

Parameters
detectorPointer to the detector.
Returns
True if the detector is of type BUF_OVERFLOW, false otherwise.

Definition at line 140 of file AEDetector.h.

141 {
142 return detector->getKind() == AEDetector::BUF_OVERFLOW;
143 }

◆ detect()

void BufOverflowDetector::detect ( const ICFGNode * node)
overridevirtual

Detect buffer overflow issues within a node.

Detects buffer overflow issues within a given ICFG node.

Parameters
asReference to the abstract state.
nodePointer to the ICFG node.

This function handles both non-call nodes, where it analyzes GEP (GetElementPtr) instructions for potential buffer overflows, and call nodes, where it checks for external API calls that may cause overflows.

Parameters
asReference to the abstract state.
nodePointer to the ICFG node.

Implements SVF::AEDetector.

Definition at line 46 of file AEDetector.cpp.

47{
50 {
51 // Handle non-call nodes by analyzing GEP instructions
52 for (const SVFStmt* stmt : node->getSVFStmts())
53 {
54 if (const GepStmt* gep = SVFUtil::dyn_cast<GepStmt>(stmt))
55 {
56 PAG* pag = PAG::getPAG();
57
58 // Update the GEP object offset from its base
59 const AbstractValue& lhsVal = ae.getAbsValue(gep->getLHSVar(), node);
60 const AbstractValue& rhsVal = ae.getAbsValue(gep->getRHSVar(), node);
61 updateGepObjOffsetFromBase(node, lhsVal.getAddrs(), rhsVal.getAddrs(),
62 ae.getGepByteOffset(gep));
63
64 const AddressValue& objAddrs = rhsVal.getAddrs();
65 bool hasUnknownSizeTarget = false;
66 for (const auto& addr : objAddrs)
67 {
68 // Null/black-hole objects have neither an allocation size nor
69 // a defining ICFG node that can be inspected below.
70 const NodeID objId = ae.getAbsState(node).getIDFromAddr(addr);
71 if (pag->isNullOrBlkObj(objId))
72 {
73 hasUnknownSizeTarget = true;
74 continue;
75 }
76 u32_t size = 0;
77 u32_t lower = 0;
78 // like `int arr[10]` which has constant size before runtime
79 if (pag->getBaseObject(objId)->isConstantByteSize())
80 {
81 size = pag->getBaseObject(objId)->getByteSizeOfObj();
82 lower = size;
83 }
84 else
85 {
86 // like `int len = ***; int arr[len]`, whose size can only be known in runtime
87 const ICFGNode* addrNode = pag->getBaseObject(objId)->getICFGNode();
88 if (!addrNode)
89 {
90 hasUnknownSizeTarget = true;
91 continue;
92 }
93 for (const SVFStmt* stmt2 : addrNode->getSVFStmts())
94 {
95 if (const AddrStmt* addrStmt = SVFUtil::dyn_cast<AddrStmt>(stmt2))
96 {
97 const auto bounds = ae.getAllocaInstByteSize(addrStmt);
98 size = bounds.upperBound;
99 lower = bounds.lowerBound;
100 }
101 }
102 }
103
104 // Calculate access offset and check for potential overflow
105 IntervalValue accessOffset = getAccessOffset(objId, gep);
106 if (accessOffset.ub().getIntNumeral() >= size)
107 {
108 addBugToReporter(stmt->getICFGNode(),
109 {IntervalValue(lower, size), accessOffset}, stmt);
110 }
111 }
112 // Some target has no known allocation size, so report one
113 // alarm with an unbounded size and the GEP's own byte offset.
114 if (hasUnknownSizeTarget)
115 addBugToReporter(node,
116 {
117 IntervalValue(0, IntervalValue::plus_infinity()),
118 ae.getGepByteOffset(gep)
119 }, stmt);
120 }
121 }
122 }
123 else
124 {
125 // Handle call nodes by checking for external API calls
126 const CallICFGNode* callNode = SVFUtil::cast<CallICFGNode>(node);
127 if (SVFUtil::isExtCall(callNode->getCalledFunction()))
128 {
129 detectExtAPI(callNode);
130 }
131 }
132}
s64_t getIntNumeral() const
IntervalValue getAccessOffset(NodeID objId, const GepStmt *gep)
Retrieves the access offset for a given object and GEP statement.
void updateGepObjOffsetFromBase(const ICFGNode *node, AddressValue gepAddrs, AddressValue objAddrs, IntervalValue offset)
Updates the offset of a GEP object from its base.
void detectExtAPI(const CallICFGNode *call)
Handles external API calls related to buffer overflow detection.
const FunObjVar * getCalledFunction() const
Definition ICFGNode.h:501
const BoundedInt & ub() const
Return the upper bound.
static BoundedInt plus_infinity()
Get plus infinity +inf.
static bool isNullOrBlkObj(NodeID id)
Check a decoded NodeID, not an AE virtual memory address.
Definition PAGBase.h:168
bool isExtCall(const FunObjVar *fun)
Definition SVFUtil.cpp:524

◆ detectExtAPI()

void BufOverflowDetector::detectExtAPI ( const CallICFGNode * call)

Handles external API calls related to buffer overflow detection.

Parameters
asReference to the abstract state.
callPointer to the call ICFG node.

This function checks the type of external memory API (e.g., memcpy, memset, strcpy, strcat) and applies the corresponding buffer overflow checks based on predefined rules.

Parameters
callPointer to the call ICFG node.

Definition at line 238 of file AEDetector.cpp.

239{
240 assert(call->getCalledFunction() && "FunObjVar* is nullptr");
242
244
245 // Determine the type of external memory API
246 for (const std::string &annotation : ExtAPI::getExtAPI()->getExtFuncAnnotations(call->getCalledFunction()))
247 {
248 if (annotation.find("MEMCPY") != std::string::npos)
249 extType = AbsExtAPI::MEMCPY;
250 if (annotation.find("MEMSET") != std::string::npos)
251 extType = AbsExtAPI::MEMSET;
252 if (annotation.find("STRCPY") != std::string::npos)
253 extType = AbsExtAPI::STRCPY;
254 if (annotation.find("STRCAT") != std::string::npos)
255 extType = AbsExtAPI::STRCAT;
256 }
257
258 // Apply buffer overflow checks based on the determined API type
260 if (extType == AbsExtAPI::MEMCPY)
261 {
262 if (extAPIBufOverflowCheckRules.count(call->getCalledFunction()->getName()) == 0)
263 {
264 SVFUtil::errs() << "Warning: " << call->getCalledFunction()->getName() << " is not in the rules, please implement it\n";
265 return;
266 }
267 std::vector<std::pair<u32_t, u32_t>> args =
269 for (auto arg : args)
270 {
271 IntervalValue offset = ae.getAbsValue(call->getArgument(arg.second), call).getInterval() - IntervalValue(1);
272 const ValVar* argVar = call->getArgument(arg.first);
273 if (!canSafelyAccessMemory(argVar, offset, call, &info))
274 {
275 addBugToReporter(call, info);
276 }
277 }
278 }
279 else if (extType == AbsExtAPI::MEMSET)
280 {
281 if (extAPIBufOverflowCheckRules.count(call->getCalledFunction()->getName()) == 0)
282 {
283 SVFUtil::errs() << "Warning: " << call->getCalledFunction()->getName() << " is not in the rules, please implement it\n";
284 return;
285 }
286 std::vector<std::pair<u32_t, u32_t>> args =
288 for (auto arg : args)
289 {
290 IntervalValue offset = ae.getAbsValue(call->getArgument(arg.second), call).getInterval() - IntervalValue(1);
291 const ValVar* argVar = call->getArgument(arg.first);
292 if (!canSafelyAccessMemory(argVar, offset, call, &info))
293 {
294 addBugToReporter(call, info);
295 }
296 }
297 }
298 else if (extType == AbsExtAPI::STRCPY)
299 {
300 if (!detectStrcpy(call, info))
301 {
302 addBugToReporter(call, info);
303 }
304 }
305 else if (extType == AbsExtAPI::STRCAT)
306 {
307 if (!detectStrcat(call, info))
308 {
309 addBugToReporter(call, info);
310 }
311 }
312 else
313 {
314 // Handle other cases
315 }
316}
ExtAPIType
Enumeration of external API types.
Definition AbsExtAPI.h:55
bool detectStrcat(const CallICFGNode *call, BufferOverflowInfo &info)
Detects buffer overflow in 'strcat' function calls.
Map< std::string, std::vector< std::pair< u32_t, u32_t > > > extAPIBufOverflowCheckRules
Rules for checking buffer overflows in external APIs.
Definition AEDetector.h:316
bool canSafelyAccessMemory(const ValVar *value, const IntervalValue &len, const ICFGNode *node, BufferOverflowInfo *info=nullptr)
Checks if memory can be safely accessed.
bool detectStrcpy(const CallICFGNode *call, BufferOverflowInfo &info)
Detects buffer overflow in 'strcpy' function calls.
const ValVar * getArgument(u32_t ArgNo) const
Parameter operations.
Definition ICFGNode.h:483
static ExtAPI * getExtAPI()
Definition ExtAPI.cpp:43
virtual const std::string & getName() const
Definition SVFValue.h:184
std::ostream & errs()
Overwrite llvm::errs().
Definition SVFUtil.h:64

◆ detectStrcat()

bool BufOverflowDetector::detectStrcat ( const CallICFGNode * call,
BufferOverflowInfo & info )
private

Detects buffer overflow in 'strcat' function calls.

Parameters
callPointer to the call ICFG node.
Returns
True if a buffer overflow is detected, false otherwise.

Definition at line 448 of file AEDetector.cpp.

449{
451 const std::vector<std::string> strcatGroup = {"__strcat_chk", "strcat", "__wcscat_chk", "wcscat"};
452 const std::vector<std::string> strncatGroup = {"__strncat_chk", "strncat", "__wcsncat_chk", "wcsncat"};
453
454 // Detectors see the state after the call, where dst already holds the
455 // concatenation, so strlen(dst) is the index of the new terminator.
456 // If the append overflowed, no terminator is inside dst and the length
457 // stays unbounded above, which keeps the reported access sound.
458 if (std::find(strcatGroup.begin(), strcatGroup.end(), call->getCalledFunction()->getName()) != strcatGroup.end() ||
459 std::find(strncatGroup.begin(), strncatGroup.end(), call->getCalledFunction()->getName()) != strncatGroup.end())
460 {
461 const ValVar* arg0Val = call->getArgument(0);
462 IntervalValue totalLen = ae.getUtils()->getStrlen(arg0Val, call);
463 return canSafelyAccessMemory(arg0Val, ae.getUtils()->getStringLastByte(call, totalLen), call, &info);
464 }
465 else
466 {
467 assert(false && "Unknown strcat function, please add it to strcatGroup or strncatGroup");
468 abort();
469 }
470}

◆ detectStrcpy()

bool BufOverflowDetector::detectStrcpy ( const CallICFGNode * call,
BufferOverflowInfo & info )
private

Detects buffer overflow in 'strcpy' function calls.

Parameters
callPointer to the call ICFG node.
Returns
True if a buffer overflow is detected, false otherwise.

This function checks if the destination buffer can safely accommodate the source string being copied, accounting for the null terminator.

Parameters
asReference to the abstract state.
callPointer to the call ICFG node.
Returns
True if the memory access is safe, false otherwise.

Definition at line 439 of file AEDetector.cpp.

440{
441 const ValVar* arg0Val = call->getArgument(0);
442 const ValVar* arg1Val = call->getArgument(1);
444 IntervalValue strLen = ae.getUtils()->getStrlen(arg1Val, call);
445 return canSafelyAccessMemory(arg0Val, ae.getUtils()->getStringLastByte(call, strLen), call, &info);
446}

◆ getAccessOffset()

IntervalValue BufOverflowDetector::getAccessOffset ( SVF::NodeID objId,
const GepStmt * gep )

Retrieves the access offset for a given object and GEP statement.

Parameters
asReference to the abstract state.
objIdThe ID of the object.
gepPointer to the GEP statement.
Returns
The interval value of the access offset.

This function calculates the access offset for a base object or a sub-object of an aggregate object (using GEP). If the object is a dummy object, it returns a top interval value.

Parameters
objIdThe ID of the object.
gepPointer to the GEP statement.
Returns
The interval value of the access offset.

Definition at line 328 of file AEDetector.cpp.

329{
330 PAG* pag = PAG::getPAG();
332 auto obj = pag->getSVFVar(objId);
333
335 {
336 return ae.getGepByteOffset(gep);
337 }
338 else if (SVFUtil::isa<GepObjVar>(obj))
339 {
340 return getGepObjOffsetFromBase(SVFUtil::cast<GepObjVar>(obj)) + ae.getGepByteOffset(gep);
341 }
342 else
343 {
344 assert(SVFUtil::isa<DummyObjVar>(obj) && "Unknown object type");
345 return IntervalValue::top();
346 }
347}
static IntervalValue top()
Create the IntervalValue [-inf, +inf].

◆ getGepObjOffsetFromBase()

IntervalValue SVF::BufOverflowDetector::getGepObjOffsetFromBase ( const GepObjVar * obj) const
inline

Retrieves the offset of a GEP object from its base.

Parameters
objPointer to the GEP object.
Returns
The interval value of the offset.

Definition at line 196 of file AEDetector.h.

197 {
199 return gepObjOffsetFromBase.at(obj);
200 else
201 {
202 assert(false && "GepObjVar not found in gepObjOffsetFromBase");
203 abort();
204 }
205 }
bool hasGepObjOffsetFromBase(const GepObjVar *obj) const
Checks if a GEP object has an associated offset.
Definition AEDetector.h:186

◆ handleStubFunctions()

void BufOverflowDetector::handleStubFunctions ( const CallICFGNode * callNode)
overridevirtual

Handles external API calls related to buffer overflow detection.

Handles stub functions within the ICFG node.

Parameters
callPointer to the call ICFG node.

This function is a placeholder for handling stub functions within the ICFG node.

Parameters
nodePointer to the ICFG node.

Implements SVF::AEDetector.

Definition at line 142 of file AEDetector.cpp.

143{
144 // get function name
145 std::string funcName = callNode->getCalledFunction()->getName();
147 if (funcName == "SAFE_BUFACCESS")
148 {
149 ae.getUtils()->checkpoints.erase(callNode);
150 if (callNode->arg_size() < 2)
151 return;
152 IntervalValue val = ae.getAbsValue(callNode->getArgument(1), callNode).getInterval();
153 if (val.isBottom())
154 {
155 val = IntervalValue(0);
156 assert(false && "SAFE_BUFACCESS size is bottom");
157 }
158 const ValVar* arg0Val = callNode->getArgument(0);
159 bool isSafe = canSafelyAccessMemory(arg0Val, val, callNode);
160 if (isSafe)
161 {
162 SVFUtil::outs() << SVFUtil::sucMsg("success: expected safe buffer access at SAFE_BUFACCESS")
163 << " — " << callNode->toString() << "\n";
164 return;
165 }
166 else
167 {
168 SVFUtil::outs() << SVFUtil::errMsg("failure: unexpected buffer overflow at SAFE_BUFACCESS")
169 << " — Position: " << callNode->getSourceLoc() << "\n";
170 assert(false);
171 }
172 }
173 else if (funcName == "UNSAFE_BUFACCESS")
174 {
175 ae.getUtils()->checkpoints.erase(callNode);
176 if (callNode->arg_size() < 2) return;
177 IntervalValue val = ae.getAbsValue(callNode->getArgument(1), callNode).getInterval();
178 if (val.isBottom())
179 {
180 assert(false && "UNSAFE_BUFACCESS size is bottom");
181 }
182 const ValVar* arg0Val = callNode->getArgument(0);
183 bool isSafe = canSafelyAccessMemory(arg0Val, val, callNode);
184 if (!isSafe)
185 {
186 SVFUtil::outs() << SVFUtil::sucMsg("success: expected buffer overflow at UNSAFE_BUFACCESS")
187 << " — " << callNode->toString() << "\n";
188 return;
189 }
190 else
191 {
192 SVFUtil::outs() << SVFUtil::errMsg("failure: buffer overflow expected at UNSAFE_BUFACCESS, but none detected")
193 << " — Position: " << callNode->getSourceLoc() << "\n";
194 assert(false);
195 }
196 }
197}
const std::string toString() const override
Definition ICFG.cpp:129
const std::string getSourceLoc() const override
Definition ICFGNode.h:571
u32_t arg_size() const
Definition ICFGNode.h:488
bool isBottom() const
std::string sucMsg(const std::string &msg)
Returns successful message by converting a string into green string output.
Definition SVFUtil.cpp:75
std::string errMsg(const std::string &msg)
Print error message by converting a string into red string output.
Definition SVFUtil.cpp:98
std::ostream & outs()
Overwrite llvm::outs().
Definition SVFUtil.h:58

◆ hasGepObjOffsetFromBase()

bool SVF::BufOverflowDetector::hasGepObjOffsetFromBase ( const GepObjVar * obj) const
inline

Checks if a GEP object has an associated offset.

Parameters
objPointer to the GEP object.
Returns
True if the GEP object has an offset, false otherwise.

Definition at line 186 of file AEDetector.h.

187 {
188 return gepObjOffsetFromBase.find(obj) != gepObjOffsetFromBase.end();
189 }

◆ initExtAPIBufOverflowCheckRules()

void BufOverflowDetector::initExtAPIBufOverflowCheckRules ( )

Initializes external API buffer overflow check rules.

This function sets up rules for various memory-related functions like memcpy, memset, etc., defining which arguments should be checked for buffer overflows.

Definition at line 205 of file AEDetector.cpp.

206{
207 extAPIBufOverflowCheckRules["llvm_memcpy_p0i8_p0i8_i64"] = {{0, 2}, {1, 2}};
208 extAPIBufOverflowCheckRules["llvm_memcpy_p0_p0_i64"] = {{0, 2}, {1, 2}};
209 extAPIBufOverflowCheckRules["llvm_memcpy_p0i8_p0i8_i32"] = {{0, 2}, {1, 2}};
210 extAPIBufOverflowCheckRules["llvm_memcpy"] = {{0, 2}, {1, 2}};
211 extAPIBufOverflowCheckRules["llvm_memmove"] = {{0, 2}, {1, 2}};
212 extAPIBufOverflowCheckRules["llvm_memmove_p0i8_p0i8_i64"] = {{0, 2}, {1, 2}};
213 extAPIBufOverflowCheckRules["llvm_memmove_p0_p0_i64"] = {{0, 2}, {1, 2}};
214 extAPIBufOverflowCheckRules["llvm_memmove_p0i8_p0i8_i32"] = {{0, 2}, {1, 2}};
215 extAPIBufOverflowCheckRules["__memcpy_chk"] = {{0, 2}, {1, 2}};
216 extAPIBufOverflowCheckRules["memmove"] = {{0, 2}, {1, 2}};
217 extAPIBufOverflowCheckRules["bcopy"] = {{0, 2}, {1, 2}};
218 extAPIBufOverflowCheckRules["memccpy"] = {{0, 3}, {1, 3}};
219 extAPIBufOverflowCheckRules["__memmove_chk"] = {{0, 2}, {1, 2}};
220 extAPIBufOverflowCheckRules["llvm_memset"] = {{0, 2}};
221 extAPIBufOverflowCheckRules["llvm_memset_p0i8_i32"] = {{0, 2}};
222 extAPIBufOverflowCheckRules["llvm_memset_p0i8_i64"] = {{0, 2}};
223 extAPIBufOverflowCheckRules["llvm_memset_p0_i64"] = {{0, 2}};
224 extAPIBufOverflowCheckRules["__memset_chk"] = {{0, 2}};
225 extAPIBufOverflowCheckRules["wmemset"] = {{0, 2}};
226 extAPIBufOverflowCheckRules["strncpy"] = {{0, 2}, {1, 2}};
227 extAPIBufOverflowCheckRules["iconv"] = {{1, 2}, {3, 4}};
228}

◆ reportBug()

void SVF::BufOverflowDetector::reportBug ( )
inlineoverridevirtual

Reports all detected buffer overflow bugs.

Implements SVF::AEDetector.

Definition at line 263 of file AEDetector.h.

264 {
265 if (!nodeToBugInfo.empty())
266 {
267 std::cerr << "######################Buffer Overflow (" + std::to_string(nodeToBugInfo.size())
268 + " found)######################\n";
269 std::cerr << "---------------------------------------------\n";
270 for (const auto& it : nodeToBugInfo)
271 {
272 std::cerr << it.second << "\n---------------------------------------------\n";
273 }
274 }
275 }

◆ updateGepObjOffsetFromBase()

void BufOverflowDetector::updateGepObjOffsetFromBase ( const ICFGNode * node,
SVF::AddressValue gepAddrs,
SVF::AddressValue objAddrs,
SVF::IntervalValue offset )

Updates the offset of a GEP object from its base.

Parameters
asReference to the abstract state.
gepAddrsAddress value for GEP.
objAddrsAddress value for the object.
offsetThe interval value of the offset.

This function calculates and stores the offset of a GEP object from its base object using the addresses and offsets provided.

Parameters
gepAddrsThe addresses of the GEP objects.
objAddrsThe addresses of the base objects.
offsetThe interval value of the offset.

Definition at line 359 of file AEDetector.cpp.

360{
361 PAG* pag = PAG::getPAG();
363 const AbstractState& as = ae.getAbsState(node);
364
365 for (const auto& objAddr : objAddrs)
366 {
367 NodeID objId = as.getIDFromAddr(objAddr);
368 if (pag->isNullOrBlkObj(objId)) continue;
369 auto obj = pag->getSVFVar(objId);
370
372 {
373 // if the object is a BaseObjVar, add the offset directly
374 // like llvm bc `arr = alloc i8 12; p = gep arr, 4`
375 // we write key value pair {gep, 4}
376 for (const auto& gepAddr : gepAddrs)
377 {
378 NodeID gepObj = as.getIDFromAddr(gepAddr);
379 if (const GepObjVar* gepObjVar = SVFUtil::dyn_cast<GepObjVar>(pag->getSVFVar(gepObj)))
380 {
382 }
383 else if (SVFUtil::isa<BaseObjVar>(pag->getSVFVar(gepObj)) &&
384 pag->getBaseObject(gepObj) == pag->getBaseObject(objId))
385 {
386 // First-field and field-insensitive GEPs retain the base Obj.
387 }
388 // Otherwise the GEP result is null/blackhole, or (with imprecise
389 // address sets) another base object: nothing to record.
390 }
391 }
392 else if (SVFUtil::isa<GepObjVar>(obj))
393 {
394 // if the object is a GepObjVar, add the offset from the base object
395 // like llvm bc `arr = alloc i8 12; p = gep arr, 4; q = gep p, 6`
396 // we retreive {p, 4} and write {q, 4+6}
397 const GepObjVar* objVar = SVFUtil::cast<GepObjVar>(obj);
398 for (const auto& gepAddr : gepAddrs)
399 {
400 NodeID gepObj = as.getIDFromAddr(gepAddr);
401 if (const GepObjVar* gepObjVar = SVFUtil::dyn_cast<GepObjVar>(pag->getSVFVar(gepObj)))
402 {
403 if (hasGepObjOffsetFromBase(objVar))
404 {
405 IntervalValue objOffsetFromBase =
407 if (!hasGepObjOffsetFromBase(gepObjVar))
409 gepObjVar, objOffsetFromBase + offset);
410 }
411 else
412 {
413 assert(false &&
414 "GEP RHS object has no offset from base");
415 }
416 }
417 else if (SVFUtil::isa<BaseObjVar>(pag->getSVFVar(gepObj)) &&
418 pag->getBaseObject(gepObj) == pag->getBaseObject(objId))
419 {
420 // A collapsed field has no distinct GepObjVar offset to record.
421 }
422 // Otherwise the GEP result is null/blackhole, or (with imprecise
423 // address sets) another base object: nothing to record.
424 }
425 }
426 }
427}
u32_t getIDFromAddr(u32_t addr) const
Return the internal index if addr is an address otherwise return the value of idx.
void addToGepObjOffsetFromBase(const GepObjVar *obj, const IntervalValue &offset)
Adds an offset to a GEP object.
Definition AEDetector.h:176

◆ AbstractInterpretation

friend class AbstractInterpretation
friend

Definition at line 113 of file AEDetector.h.

Member Data Documentation

◆ bugLoc

Set<std::string> SVF::BufOverflowDetector::bugLoc
private

Set of locations where bugs have been reported.

Definition at line 317 of file AEDetector.h.

◆ extAPIBufOverflowCheckRules

Map<std::string, std::vector<std::pair<u32_t, u32_t> > > SVF::BufOverflowDetector::extAPIBufOverflowCheckRules
private

Rules for checking buffer overflows in external APIs.

Definition at line 316 of file AEDetector.h.

◆ gepObjOffsetFromBase

Map<const GepObjVar*, IntervalValue> SVF::BufOverflowDetector::gepObjOffsetFromBase
private

Maps GEP objects to their offsets from the base.

Definition at line 315 of file AEDetector.h.

◆ nodeToBugInfo

Map<const ICFGNode*, std::string> SVF::BufOverflowDetector::nodeToBugInfo
private

Maps ICFG nodes to bug information.

Definition at line 319 of file AEDetector.h.

◆ recoder

SVFBugReport SVF::BufOverflowDetector::recoder
private

Recorder for abstract execution bugs.

Definition at line 318 of file AEDetector.h.


The documentation for this class was generated from the following files: