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 AEException &e, const ICFGNode *node)
 Adds a bug to the reporter based on an exception.
void addBugToReporter (const AEException &e, const ICFGNode *node, const BufferOverflowInfo &info)
 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 138 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 151 of file AEDetector.h.

152 {
155 }
@ 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 AEException & e,
const ICFGNode * node )
inline

Adds a bug to the reporter based on an exception.

Parameters
eThe exception that was thrown.
nodePointer to the ICFG node where the bug was detected.

Definition at line 248 of file AEDetector.h.

249 {
251 }
void addBugToReporter(const AEException &e, const ICFGNode *node)
Adds a bug to the reporter based on an exception.
Definition AEDetector.h:248

◆ addBugToReporter() [2/2]

void SVF::BufOverflowDetector::addBugToReporter ( const AEException & e,
const ICFGNode * node,
const BufferOverflowInfo & info )
inline

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

Definition at line 254 of file AEDetector.h.

256 {
257
258 GenericBug::EventStack eventStack;
259 SVFBugEvent sourceInstEvent(SVFBugEvent::EventType::SourceInst, node);
260 eventStack.push_back(sourceInstEvent); // Add the source instruction event to the event stack
261
262 if (eventStack.empty())
263 {
264 return; // If the event stack is empty, return early
265 }
266
267 std::string loc = eventStack.back().getEventLoc(); // Get the location of the last event in the stack
268
269 // Check if the bug at this location has already been reported
270 if (bugLoc.find(loc) != bugLoc.end())
271 {
272 return; // If the bug location is already reported, return early
273 }
274 else
275 {
276 bugLoc.insert(loc); // Otherwise, mark this location as reported
277 }
278
279 // Add the bug to the recorder with details from the event stack
280 recoder.addAbsExecBug(GenericBug::FULLBUFOVERFLOW, eventStack,
281 info.bufferSize.lb(), info.bufferSize.ub(),
282 info.accessOffset.lb(), info.accessOffset.ub());
283 nodeToBugInfo[node] = e.what(); // Record the exception information for the node
284 }
SVFBugReport recoder
Recorder for abstract execution bugs.
Definition AEDetector.h:344
Set< std::string > bugLoc
Set of locations where bugs have been reported.
Definition AEDetector.h:343
Map< const ICFGNode *, std::string > nodeToBugInfo
Maps ICFG nodes to bug information.
Definition AEDetector.h:345
std::vector< SVFBugEvent > EventStack

◆ 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 203 of file AEDetector.h.

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

◆ 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 494 of file AEDetector.cpp.

496{
497 if (info) *info = {};
498 SVFIR* svfir = PAG::getPAG();
500
501 AbstractValue ptrVal = ae.getAbsValue(value, node);
502 if (!ptrVal.isAddr())
503 {
504 ptrVal = AddressValue(BlackHoleObjAddr);
505 ae.updateAbsValue(value, ptrVal, node);
506 }
507
508 const AddressValue& addresses = ptrVal.getAddrs();
509 if (std::any_of(addresses.begin(), addresses.end(), [&](u32_t addr)
510{
511 return svfir->isNullOrBlkObj(ae.getAbsState(node).getIDFromAddr(addr));
512 }))
513 return false;
514
515 for (const auto& addr : addresses)
516 {
517 NodeID objId = ae.getAbsState(node).getIDFromAddr(addr);
518 u32_t size = 0;
519 u32_t lower = 0;
520 // if the object is a constant size object, get the size directly
521 if (svfir->getBaseObject(objId)->isConstantByteSize())
522 {
523 size = svfir->getBaseObject(objId)->getByteSizeOfObj();
524 lower = size;
525 }
526 else
527 {
528 // if the object is not a constant size object, get the size from the addrStmt
529 const ICFGNode* addrNode = svfir->getBaseObject(objId)->getICFGNode();
530 if (!addrNode)
531 return false;
532 for (const SVFStmt* stmt2 : addrNode->getSVFStmts())
533 {
534 if (const AddrStmt* addrStmt = SVFUtil::dyn_cast<AddrStmt>(stmt2))
535 {
536 const auto bounds = ae.getAllocaInstByteSize(addrStmt);
537 size = bounds.upperBound;
538 lower = bounds.lowerBound;
539 }
540 }
541 }
542
543 IntervalValue offset(0);
544 // if the object is a GepObjVar, get the offset from the base object
545 if (SVFUtil::isa<GepObjVar>(svfir->getSVFVar(objId)))
546 {
548 }
549 else if (SVFUtil::isa<BaseObjVar>(svfir->getSVFVar(objId)))
550 {
551 // if the object is a BaseObjVar, get the offset directly
552 offset = len;
553 }
554
555 // if the offset is greater than the size, return false
556 if (offset.ub().getIntNumeral() >= size)
557 {
558 if (info) *info = {IntervalValue(lower, size), offset};
559 return false;
560 }
561 }
562 return true;
563}
#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:223
const SVFStmtList & getSVFStmts() const
Definition ICFGNode.h:116
const BaseObjVar * getBaseObject(NodeID id) const
Definition SVFIR.h:499
const SVFVar * getSVFVar(NodeID id) const
ObjVar/GepObjVar/BaseObjVar.
Definition SVFIR.h:136
static SVFIR * getPAG(bool buildFromFile=false)
Singleton design here to make sure we only have one instance during any analysis.
Definition SVFIR.h:121
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 167 of file AEDetector.h.

168 {
169 return detector->getKind() == AEDetector::BUF_OVERFLOW;
170 }

◆ 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 SVFIR* svfir = 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 (svfir->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 (svfir->getBaseObject(objId)->isConstantByteSize())
80 {
81 size = svfir->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 = svfir->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 AEException bug(stmt->toString());
109 addBugToReporter(bug, stmt->getICFGNode(),
110 {IntervalValue(lower, size), accessOffset});
111 }
112 }
113 // Some target has no known allocation size, so report one
114 // alarm with an unbounded size and the GEP's own byte offset.
115 if (hasUnknownSizeTarget)
116 addBugToReporter(AEException(stmt->toString()), node,
117 {
118 IntervalValue(0, IntervalValue::plus_infinity()),
119 ae.getGepByteOffset(gep)
120 });
121 }
122 }
123 }
124 else
125 {
126 // Handle call nodes by checking for external API calls
127 const CallICFGNode* callNode = SVFUtil::cast<CallICFGNode>(node);
128 if (SVFUtil::isExtCall(callNode->getCalledFunction()))
129 {
130 detectExtAPI(callNode);
131 }
132 }
133}
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
static bool isNullOrBlkObj(NodeID id)
Check a decoded NodeID, not an AE virtual memory address.
Definition IRGraph.h:169
const BoundedInt & ub() const
Return the upper bound.
bool isExtCall(const FunObjVar *fun)
Definition SVFUtil.cpp:526

◆ 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 239 of file AEDetector.cpp.

240{
241 assert(call->getCalledFunction() && "FunObjVar* is nullptr");
243
245
246 // Determine the type of external memory API
247 for (const std::string &annotation : ExtAPI::getExtAPI()->getExtFuncAnnotations(call->getCalledFunction()))
248 {
249 if (annotation.find("MEMCPY") != std::string::npos)
250 extType = AbsExtAPI::MEMCPY;
251 if (annotation.find("MEMSET") != std::string::npos)
252 extType = AbsExtAPI::MEMSET;
253 if (annotation.find("STRCPY") != std::string::npos)
254 extType = AbsExtAPI::STRCPY;
255 if (annotation.find("STRCAT") != std::string::npos)
256 extType = AbsExtAPI::STRCAT;
257 }
258
259 // Apply buffer overflow checks based on the determined API type
261 if (extType == AbsExtAPI::MEMCPY)
262 {
263 if (extAPIBufOverflowCheckRules.count(call->getCalledFunction()->getName()) == 0)
264 {
265 SVFUtil::errs() << "Warning: " << call->getCalledFunction()->getName() << " is not in the rules, please implement it\n";
266 return;
267 }
268 std::vector<std::pair<u32_t, u32_t>> args =
270 for (auto arg : args)
271 {
272 IntervalValue offset = ae.getAbsValue(call->getArgument(arg.second), call).getInterval() - IntervalValue(1);
273 const ValVar* argVar = call->getArgument(arg.first);
274 if (!canSafelyAccessMemory(argVar, offset, call, &info))
275 {
276 AEException bug(call->toString());
277 addBugToReporter(bug, call, info);
278 }
279 }
280 }
281 else if (extType == AbsExtAPI::MEMSET)
282 {
283 if (extAPIBufOverflowCheckRules.count(call->getCalledFunction()->getName()) == 0)
284 {
285 SVFUtil::errs() << "Warning: " << call->getCalledFunction()->getName() << " is not in the rules, please implement it\n";
286 return;
287 }
288 std::vector<std::pair<u32_t, u32_t>> args =
290 for (auto arg : args)
291 {
292 IntervalValue offset = ae.getAbsValue(call->getArgument(arg.second), call).getInterval() - IntervalValue(1);
293 const ValVar* argVar = call->getArgument(arg.first);
294 if (!canSafelyAccessMemory(argVar, offset, call, &info))
295 {
296 AEException bug(call->toString());
297 addBugToReporter(bug, call, info);
298 }
299 }
300 }
301 else if (extType == AbsExtAPI::STRCPY)
302 {
303 if (!detectStrcpy(call, info))
304 {
305 AEException bug(call->toString());
306 addBugToReporter(bug, call, info);
307 }
308 }
309 else if (extType == AbsExtAPI::STRCAT)
310 {
311 if (!detectStrcat(call, info))
312 {
313 AEException bug(call->toString());
314 addBugToReporter(bug, call, info);
315 }
316 }
317 else
318 {
319 // Handle other cases
320 }
321}
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:342
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 std::string toString() const override
Definition ICFG.cpp:129
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 459 of file AEDetector.cpp.

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

◆ 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 450 of file AEDetector.cpp.

451{
452 const ValVar* arg0Val = call->getArgument(0);
453 const ValVar* arg1Val = call->getArgument(1);
455 IntervalValue strLen = ae.getUtils()->getStrlen(arg1Val, call);
456 return canSafelyAccessMemory(arg0Val, ae.getUtils()->getStringLastByte(call, strLen), call, &info);
457}

◆ 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 333 of file AEDetector.cpp.

334{
335 SVFIR* svfir = PAG::getPAG();
337 auto obj = svfir->getSVFVar(objId);
338
340 {
341 return ae.getGepByteOffset(gep);
342 }
343 else if (SVFUtil::isa<GepObjVar>(obj))
344 {
345 return getGepObjOffsetFromBase(SVFUtil::cast<GepObjVar>(obj)) + ae.getGepByteOffset(gep);
346 }
347 else
348 {
349 assert(SVFUtil::isa<DummyObjVar>(obj) && "Unknown object type");
350 return IntervalValue::top();
351 }
352}
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 223 of file AEDetector.h.

224 {
226 return gepObjOffsetFromBase.at(obj);
227 else
228 {
229 assert(false && "GepObjVar not found in gepObjOffsetFromBase");
230 abort();
231 }
232 }
bool hasGepObjOffsetFromBase(const GepObjVar *obj) const
Checks if a GEP object has an associated offset.
Definition AEDetector.h:213

◆ 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 143 of file AEDetector.cpp.

144{
145 // get function name
146 std::string funcName = callNode->getCalledFunction()->getName();
148 if (funcName == "SAFE_BUFACCESS")
149 {
150 ae.getUtils()->checkpoints.erase(callNode);
151 if (callNode->arg_size() < 2)
152 return;
153 IntervalValue val = ae.getAbsValue(callNode->getArgument(1), callNode).getInterval();
154 if (val.isBottom())
155 {
156 val = IntervalValue(0);
157 assert(false && "SAFE_BUFACCESS size is bottom");
158 }
159 const ValVar* arg0Val = callNode->getArgument(0);
160 bool isSafe = canSafelyAccessMemory(arg0Val, val, callNode);
161 if (isSafe)
162 {
163 SVFUtil::outs() << SVFUtil::sucMsg("success: expected safe buffer access at SAFE_BUFACCESS")
164 << " — " << callNode->toString() << "\n";
165 return;
166 }
167 else
168 {
169 SVFUtil::outs() << SVFUtil::errMsg("failure: unexpected buffer overflow at SAFE_BUFACCESS")
170 << " — Position: " << callNode->getSourceLoc() << "\n";
171 assert(false);
172 }
173 }
174 else if (funcName == "UNSAFE_BUFACCESS")
175 {
176 ae.getUtils()->checkpoints.erase(callNode);
177 if (callNode->arg_size() < 2) return;
178 IntervalValue val = ae.getAbsValue(callNode->getArgument(1), callNode).getInterval();
179 if (val.isBottom())
180 {
181 assert(false && "UNSAFE_BUFACCESS size is bottom");
182 }
183 const ValVar* arg0Val = callNode->getArgument(0);
184 bool isSafe = canSafelyAccessMemory(arg0Val, val, callNode);
185 if (!isSafe)
186 {
187 SVFUtil::outs() << SVFUtil::sucMsg("success: expected buffer overflow at UNSAFE_BUFACCESS")
188 << " — " << callNode->toString() << "\n";
189 return;
190 }
191 else
192 {
193 SVFUtil::outs() << SVFUtil::errMsg("failure: buffer overflow expected at UNSAFE_BUFACCESS, but none detected")
194 << " — Position: " << callNode->getSourceLoc() << "\n";
195 assert(false);
196 }
197 }
198}
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 213 of file AEDetector.h.

214 {
215 return gepObjOffsetFromBase.find(obj) != gepObjOffsetFromBase.end();
216 }

◆ 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 206 of file AEDetector.cpp.

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

◆ reportBug()

void SVF::BufOverflowDetector::reportBug ( )
inlineoverridevirtual

Reports all detected buffer overflow bugs.

Implements SVF::AEDetector.

Definition at line 289 of file AEDetector.h.

290 {
291 if (!nodeToBugInfo.empty())
292 {
293 std::cerr << "######################Buffer Overflow (" + std::to_string(nodeToBugInfo.size())
294 + " found)######################\n";
295 std::cerr << "---------------------------------------------\n";
296 for (const auto& it : nodeToBugInfo)
297 {
298 std::cerr << it.second << "\n---------------------------------------------\n";
299 }
300 }
301 }

◆ 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 364 of file AEDetector.cpp.

365{
366 SVFIR* svfir = PAG::getPAG();
368 const AbstractState& as = ae.getAbsState(node);
369
370 for (const auto& objAddr : objAddrs)
371 {
372 NodeID objId = as.getIDFromAddr(objAddr);
373 if (svfir->isNullOrBlkObj(objId)) continue;
374 auto obj = svfir->getSVFVar(objId);
375
377 {
378 // if the object is a BaseObjVar, add the offset directly
379 // like llvm bc `arr = alloc i8 12; p = gep arr, 4`
380 // we write key value pair {gep, 4}
381 for (const auto& gepAddr : gepAddrs)
382 {
383 NodeID gepObj = as.getIDFromAddr(gepAddr);
384 if (const GepObjVar* gepObjVar = SVFUtil::dyn_cast<GepObjVar>(svfir->getSVFVar(gepObj)))
385 {
387 }
388 else if (SVFUtil::isa<BaseObjVar>(svfir->getSVFVar(gepObj)) &&
389 svfir->getBaseObject(gepObj) == svfir->getBaseObject(objId))
390 {
391 // First-field and field-insensitive GEPs retain the base Obj.
392 }
393 else
394 {
395 assert(svfir->isNullOrBlkObj(gepObj) &&
396 "GEP object is neither a GepObjVar nor an address without a backing object");
397 }
398 }
399 }
400 else if (SVFUtil::isa<GepObjVar>(obj))
401 {
402 // if the object is a GepObjVar, add the offset from the base object
403 // like llvm bc `arr = alloc i8 12; p = gep arr, 4; q = gep p, 6`
404 // we retreive {p, 4} and write {q, 4+6}
405 const GepObjVar* objVar = SVFUtil::cast<GepObjVar>(obj);
406 for (const auto& gepAddr : gepAddrs)
407 {
408 NodeID gepObj = as.getIDFromAddr(gepAddr);
409 if (const GepObjVar* gepObjVar = SVFUtil::dyn_cast<GepObjVar>(svfir->getSVFVar(gepObj)))
410 {
411 if (hasGepObjOffsetFromBase(objVar))
412 {
413 IntervalValue objOffsetFromBase =
415 if (!hasGepObjOffsetFromBase(gepObjVar))
417 gepObjVar, objOffsetFromBase + offset);
418 }
419 else
420 {
421 assert(false &&
422 "GEP RHS object has no offset from base");
423 }
424 }
425 else if (SVFUtil::isa<BaseObjVar>(svfir->getSVFVar(gepObj)) &&
426 svfir->getBaseObject(gepObj) == svfir->getBaseObject(objId))
427 {
428 // A collapsed field has no distinct GepObjVar offset to record.
429 }
430 else
431 {
432 assert(svfir->isNullOrBlkObj(gepObj) &&
433 "GEP object is neither a GepObjVar nor an address without a backing object");
434 }
435 }
436 }
437 }
438}
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:203

◆ AbstractInterpretation

friend class AbstractInterpretation
friend

Definition at line 140 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 343 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 342 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 341 of file AEDetector.h.

◆ nodeToBugInfo

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

Maps ICFG nodes to bug information.

Definition at line 345 of file AEDetector.h.

◆ recoder

SVFBugReport SVF::BufOverflowDetector::recoder
private

Recorder for abstract execution bugs.

Definition at line 344 of file AEDetector.h.


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