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

Handles external API calls and manages abstract states. More...

#include <AbsExtAPI.h>

Public Types

enum  ExtAPIType {
  UNCLASSIFIED , MEMCPY , MEMSET , STRCPY ,
  STRCAT
}
 Enumeration of external API types. More...

Public Member Functions

void initExtFunMap ()
 Initializes the external function map.
std::string strRead (const ValVar *rhs, const ICFGNode *node)
 Reads a string from the abstract state.
void handleExtAPI (const CallICFGNode *call)
 Handles an external API call.
u32_t getElementSize (const ValVar *var)
 Get the byte size of each element for a pointer/array variable.
u32_t getStringElementSize (const ValVar *var, const ICFGNode *node)
 Scalar integer width of the pointed-to base object; zero if unknown.
IntervalValue getStringLastByte (const CallICFGNode *call, const IntervalValue &length)
 Last byte offset written for length elements plus the terminator.
IntervalValue getStrncatLength (const CallICFGNode *call)
 Elements strncat appends: min(n, strlen(src)).
void handleStringCopy (const CallICFGNode *call, const IntervalValue &length, const IntervalValue &start)
 Write length source elements and a NUL into dst at element start.
IntervalValue getStrlen (const ValVar *strValue, const ICFGNode *node)
 String length in elements, excluding NUL; an unproved end is unbounded.
void handleStrcpy (const CallICFGNode *call)
void handleStrcat (const CallICFGNode *call)
void handleStrncat (const CallICFGNode *call)
void handleMemcpy (const ValVar *dst, const ValVar *src, const IntervalValue &len, u32_t start_idx, const ICFGNode *node)
 Core memcpy: copy len bytes from src to dst starting at dst[start_idx].
void handleMemset (const ValVar *dst, const IntervalValue &elem, const IntervalValue &len, const ICFGNode *node)
IntervalValue getRangeLimitFromType (const SVFType *type)
 Gets the range limit from a type.
AbstractState & getAbsState (const ICFGNode *node)
 Retrieves the abstract state from the trace for a given ICFG node.
void collectCheckPoint ()
void checkPointAllSet ()

Static Public Member Functions

static bool isValidLength (const IntervalValue &len)
 Check if an interval length is usable (not bottom, not unbounded).
static u32_t getBoundedMinimumByteCount (const IntervalValue &len)
 Return the lower bound of len, capped by the field limit.

Public Attributes

Set< const CallICFGNode * > checkpoints

Protected Attributes

AbstractInterpretation * ae
 Owning AbstractInterpretation; provides state access.
PAG * pag
 Pointer to the SVF intermediate representation.
ICFG * icfg
 Pointer to the interprocedural control flow graph.
Map< std::string, std::function< void(const CallICFGNode *)> > func_map
 Map of function names to handlers.

Private Member Functions

 AbsExtAPI (AbstractInterpretation *ae)
 Constructor for AbsExtAPI.

Friends

class AbstractInterpretation

Detailed Description

Handles external API calls and manages abstract states.

Definition at line 48 of file AbsExtAPI.h.

Member Enumeration Documentation

◆ ExtAPIType

Enumeration of external API types.

Enumerator
UNCLASSIFIED 
MEMCPY 
MEMSET 
STRCPY 
STRCAT 

Definition at line 55 of file AbsExtAPI.h.

Constructor & Destructor Documentation

◆ AbsExtAPI()

AbsExtAPI::AbsExtAPI ( AbstractInterpretation * ae)
private

Constructor for AbsExtAPI.

Parameters
aeReference to the AbstractInterpretation instance.

Definition at line 35 of file AbsExtAPI.cpp.

35 : ae(ae)
36{
37 pag = PAG::getPAG();
38 icfg = pag->getICFG();
40}
AbstractInterpretation * ae
Owning AbstractInterpretation; provides state access.
Definition AbsExtAPI.h:142
PAG * pag
Pointer to the SVF intermediate representation.
Definition AbsExtAPI.h:143
void initExtFunMap()
Initializes the external function map.
Definition AbsExtAPI.cpp:42
ICFG * icfg
Pointer to the interprocedural control flow graph.
Definition AbsExtAPI.h:144
static PAG * getPAG(bool buildFromFile=false)
Singleton design here to make sure we only have one instance during any analysis.
Definition PAG.h:121

Member Function Documentation

◆ checkPointAllSet()

void AbsExtAPI::checkPointAllSet ( )

Definition at line 293 of file AbsExtAPI.cpp.

294{
295 if (!checkpoints.empty())
296 {
297 SVFUtil::errs() << SVFUtil::errMsg("At least one svf_assert has not been checked!!") << "\n";
298 for (const CallICFGNode* call: checkpoints)
299 SVFUtil::errs() << call->toString() + "\n";
300 assert(false);
301 }
302}
Set< const CallICFGNode * > checkpoints
Definition AbsExtAPI.h:139
std::string errMsg(const std::string &msg)
Print error message by converting a string into red string output.
Definition SVFUtil.cpp:98
std::ostream & errs()
Overwrite llvm::errs().
Definition SVFUtil.h:64

◆ collectCheckPoint()

void AbsExtAPI::collectCheckPoint ( )

Definition at line 253 of file AbsExtAPI.cpp.

254{
255 // traverse every ICFGNode
256 Set<std::string> ae_checkpoint_names = {"svf_assert"};
257 Set<std::string> buf_checkpoint_names = {"UNSAFE_BUFACCESS", "SAFE_BUFACCESS"};
258 Set<std::string> nullptr_checkpoint_names = {"UNSAFE_LOAD", "SAFE_LOAD"};
259
260 for (auto it = pag->getICFG()->begin(); it != pag->getICFG()->end(); ++it)
261 {
262 const ICFGNode* node = it->second;
263 if (const CallICFGNode *call = SVFUtil::dyn_cast<CallICFGNode>(node))
264 {
265 if (const FunObjVar *fun = call->getCalledFunction())
266 {
267 if (ae_checkpoint_names.find(fun->getName()) !=
268 ae_checkpoint_names.end())
269 {
270 checkpoints.insert(call);
271 }
273 {
274 if (buf_checkpoint_names.find(fun->getName()) !=
275 buf_checkpoint_names.end())
276 {
277 checkpoints.insert(call);
278 }
279 }
281 {
282 if (nullptr_checkpoint_names.find(fun->getName()) !=
283 nullptr_checkpoint_names.end())
284 {
285 checkpoints.insert(call);
286 }
287 }
288 }
289 }
290 }
291}
static const Option< bool > NullDerefCheck
nullptr dereference checker, Default: false
Definition Options.h:250
static const Option< bool > BufferOverflowCheck
buffer overflow checker, Default: false
Definition Options.h:248
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
std::unordered_set< Key, Hash, KeyEqual, Allocator > Set
Definition GeneralType.h:51

◆ getAbsState()

AbstractState & AbsExtAPI::getAbsState ( const ICFGNode * node)

Retrieves the abstract state from the trace for a given ICFG node.

Parameters
nodePointer to the ICFG node.
Returns
Reference to the abstract state.
Exceptions
Assertionif no trace exists for the node.

Definition at line 248 of file AbsExtAPI.cpp.

249{
250 return ae->getAbsState(node);
251}

◆ getBoundedMinimumByteCount()

u32_t AbsExtAPI::getBoundedMinimumByteCount ( const IntervalValue & len)
static

Return the lower bound of len, capped by the field limit.

Definition at line 424 of file AbsExtAPI.cpp.

425{
426 u32_t byteCount = 0;
427 if (isValidLength(len) && len.lb().getIntNumeral() > 0)
428 {
429 byteCount = std::min(Options::MaxFieldLimit(),
430 (u32_t)len.lb().getIntNumeral());
431 }
432 return byteCount;
433}
static bool isValidLength(const IntervalValue &len)
Check if an interval length is usable (not bottom, not unbounded).
s64_t getIntNumeral() const
const BoundedInt & lb() const
Return the lower bound.
static const Option< u32_t > MaxFieldLimit
Maximum number of field derivations for an object.
Definition Options.h:34
unsigned u32_t
Definition GeneralType.h:67

◆ getElementSize()

u32_t AbsExtAPI::getElementSize ( const ValVar * var)

Get the byte size of each element for a pointer/array variable.

Get the byte size of each element for a pointer/array variable. Shared by handleMemcpy, handleMemset, and getStrlen to avoid duplication.

Definition at line 403 of file AbsExtAPI.cpp.

404{
405 if (var->getType()->isArrayTy())
406 {
408 ->getTypeOfElement()->getByteSize();
409 }
410 if (var->getType()->isPointerTy())
411 return 1;
412 assert(false && "unsupported type for element size");
413 return 1;
414}
bool isArrayTy() const
Definition SVFType.h:297
bool isPointerTy() const
Definition SVFType.h:292
virtual const SVFType * getType() const
Definition SVFValue.h:169

◆ getRangeLimitFromType()

IntervalValue AbsExtAPI::getRangeLimitFromType ( const SVFType * type)

Gets the range limit from a type.

Parameters
typePointer to the SVF type.
Returns
The interval value representing the range limit.

This function, getRangeLimitFromType, calculates the lower and upper bounds of a numeric range for a given SVFType. It is used to determine the possible value range of integer types. If the type is an SVFIntegerType, it calculates the bounds based on the size and signedness of the type. The calculated bounds are returned as an IntervalValue representing the lower (lb) and upper (ub) limits of the range.

Parameters
typeThe SVFType for which to calculate the value range.
Returns
An IntervalValue representing the lower and upper bounds of the range.

Definition at line 720 of file AbsExtAPI.cpp.

721{
722 if (const SVFIntegerType* intType = SVFUtil::dyn_cast<SVFIntegerType>(type))
723 {
724 u32_t bits = type->getByteSize() * 8;
725 s64_t ub = 0;
726 s64_t lb = 0;
727 if (bits >= 32)
728 {
729 if (intType->isSigned())
730 {
731 ub = static_cast<s64_t>(std::numeric_limits<s32_t>::max());
732 lb = static_cast<s64_t>(std::numeric_limits<s32_t>::min());
733 }
734 else
735 {
736 ub = static_cast<s64_t>(std::numeric_limits<u32_t>::max());
737 lb = static_cast<s64_t>(std::numeric_limits<u32_t>::min());
738 }
739 }
740 else if (bits == 16)
741 {
742 if (intType->isSigned())
743 {
744 ub = static_cast<s64_t>(std::numeric_limits<s16_t>::max());
745 lb = static_cast<s64_t>(std::numeric_limits<s16_t>::min());
746 }
747 else
748 {
749 ub = static_cast<s64_t>(std::numeric_limits<u16_t>::max());
750 lb = static_cast<s64_t>(std::numeric_limits<u16_t>::min());
751 }
752 }
753 else if (bits == 8)
754 {
755 if (intType->isSigned())
756 {
757 ub = static_cast<s64_t>(std::numeric_limits<int8_t>::max());
758 lb = static_cast<s64_t>(std::numeric_limits<int8_t>::min());
759 }
760 else
761 {
762 ub = static_cast<s64_t>(std::numeric_limits<uint8_t>::max());
763 lb = static_cast<s64_t>(std::numeric_limits<uint8_t>::min());
764 }
765 }
766 return IntervalValue(lb, ub);
767 }
769 {
770 // handle other type like float double, set s32_t as the range
771 s64_t ub = static_cast<s64_t>(std::numeric_limits<s32_t>::max());
772 s64_t lb = static_cast<s64_t>(std::numeric_limits<s32_t>::min());
773 return IntervalValue(lb, ub);
774 }
775 else
776 {
777 return IntervalValue::top();
778 // other types, return top interval
779 }
780}
newitem type
Definition cJSON.cpp:2739
static IntervalValue top()
Create the IntervalValue [-inf, +inf].
LLVM_NODISCARD bool isa(const Y &Val)
Definition Casting.h:241
signed long long s64_t
Definition GeneralType.h:70

◆ getStringElementSize()

u32_t AbsExtAPI::getStringElementSize ( const ValVar * var,
const ICFGNode * node )

Scalar integer width of the pointed-to base object; zero if unknown.

Definition at line 435 of file AbsExtAPI.cpp.

436{
437 u32_t width = 0;
438 const AbstractValue& pointer = ae->getAbsValue(var, node);
439 if (!pointer.isAddr() || pointer.getAddrs().empty())
440 return 0;
441 for (auto addr : pointer.getAddrs())
442 {
443 const NodeID obj = getAbsState(node).getIDFromAddr(addr);
444 if (pag->isNullOrBlkObj(obj))
445 return 0;
446 const SVFType* type = pag->getBaseObject(obj)->getType();
447 while (const auto* array = SVFUtil::dyn_cast<SVFArrayType>(type))
448 type = array->getTypeOfElement();
449 if (!SVFUtil::isa<SVFIntegerType>(type) || !type->getByteSize() ||
450 (width && width != type->getByteSize()))
451 return 0;
452 width = type->getByteSize();
453 }
454 return width;
455}
AbstractState & getAbsState(const ICFGNode *node)
Retrieves the abstract state from the trace for a given ICFG node.
u32_t getIDFromAddr(u32_t addr) const
Return the internal index if addr is an address otherwise return the value of idx.
AddressValue & getAddrs()
bool isAddr() const
bool empty() const
u32_t NodeID
Definition GeneralType.h:76

◆ getStringLastByte()

IntervalValue AbsExtAPI::getStringLastByte ( const CallICFGNode * call,
const IntervalValue & length )

Last byte offset written for length elements plus the terminator.

Definition at line 457 of file AbsExtAPI.cpp.

459{
460 IntervalValue width(1);
461 if (call->getCalledFunction()->getName().find("wcs") != std::string::npos)
462 {
463 const u32_t dst = getStringElementSize(call->getArgument(0), call);
464 const u32_t src = getStringElementSize(call->getArgument(1), call);
465 // Byte storage alone does not establish the wide character width.
466 width = (dst > 1 || src > 1) && (dst <= 1 || src <= 1 || dst == src)
467 ? IntervalValue(dst > 1 ? dst : src)
468 : IntervalValue(1, IntervalValue::plus_infinity());
469 }
470 return (length + IntervalValue(1)) * width - IntervalValue(1);
471}
char const int length
Definition cJSON.h:163
u32_t getStringElementSize(const ValVar *var, const ICFGNode *node)
Scalar integer width of the pointed-to base object; zero if unknown.
const ValVar * getArgument(u32_t ArgNo) const
Parameter operations.
Definition ICFGNode.h:483
const FunObjVar * getCalledFunction() const
Definition ICFGNode.h:501
virtual const std::string & getName() const
Definition SVFValue.h:184

◆ getStrlen()

IntervalValue AbsExtAPI::getStrlen ( const ValVar * strValue,
const ICFGNode * node )

String length in elements, excluding NUL; an unproved end is unbounded.

String length in elements, read from the abstract state only. Lower bound: leading elements whose abstract value excludes 0; it stops at the first element that may be 0 (unknown, uninitialized, pointer, or a range containing 0), so uncertainty only weakens it. Upper bound: an element that is exactly 0; without one the length is unbounded above. The scan budget is not a termination guarantee.

Definition at line 479 of file AbsExtAPI.cpp.

480{
481 AbstractState& as = getAbsState(node);
482 const IntervalValue unknown(0, IntervalValue::plus_infinity());
483 IntervalValue result = IntervalValue::bottom();
484 const AbstractValue& ptrVal = ae->getAbsValue(strValue, node);
485 if (const auto* call = SVFUtil::dyn_cast<CallICFGNode>(node))
486 if (call->getCalledFunction() &&
487 call->getCalledFunction()->getName().find("wcs") == std::string::npos &&
488 getStringElementSize(strValue, node) != 1)
489 return unknown;
490 if (!ptrVal.isAddr() || ptrVal.getAddrs().empty())
491 return unknown;
492 for (const auto& addr : ptrVal.getAddrs())
493 {
494 const NodeID objId = as.getIDFromAddr(addr);
495 if (pag->isNullOrBlkObj(objId))
496 {
497 result.join_with(unknown);
498 continue;
499 }
500 const BaseObjVar* base = pag->getBaseObject(objId);
501 const auto* gep = SVFUtil::dyn_cast<GepObjVar>(pag->getSVFVar(objId));
502 const APOffset start = gep ? gep->getConstantFieldIdx() : 0;
503 u32_t lower = 0;
504 bool nonzeroPrefix = true;
505 IntervalValue length = unknown;
507 {
508 if (start < 0 || start + index >= base->getNumOfElements() ||
509 start + index >= base->getMaxFieldOffsetLimit() ||
510 start + index >= Options::MaxFieldLimit())
511 break;
512 const NodeID field = pag->getGepObjVar(objId, index);
513 const AbstractValue& cell = as.load(AbstractState::getVirtualMemAddress(field));
514 if (cell.isInterval() && !cell.isAddr() && cell.getInterval().is_zero())
515 {
516 length = IntervalValue(lower, index);
517 break;
518 }
519 if (!cell.isInterval() || cell.isAddr() || cell.getInterval().isBottom() ||
520 cell.getInterval().contains(0))
521 nonzeroPrefix = false;
522 if (nonzeroPrefix)
523 ++lower;
524 length = IntervalValue(lower, IntervalValue::plus_infinity());
525 }
526 result.join_with(length);
527 }
528 return result;
529}
int index
Definition cJSON.h:170
virtual AbstractValue & load(u32_t addr)
static u32_t getVirtualMemAddress(u32_t idx)
The physical address starts with 0x7f...... + idx.
bool isInterval() const
IntervalValue & getInterval()
u32_t getNumOfElements() const
Get the number of elements of this object.
u32_t getMaxFieldOffsetLimit() const
Get max field offset limit.
void join_with(const IntervalValue &other)
Current IntervalValue joins with another IntervalValue.
bool isBottom() const
bool is_zero() const
Return true if the IntervalValue is [0, 0].
static IntervalValue bottom()
Create the bottom IntervalValue [+inf, -inf].
static BoundedInt plus_infinity()
Get plus infinity +inf.
bool contains(int n) const
Return true if the IntervalValue contains n.
s64_t APOffset
Definition GeneralType.h:80

◆ getStrncatLength()

IntervalValue AbsExtAPI::getStrncatLength ( const CallICFGNode * call)

Elements strncat appends: min(n, strlen(src)).

Definition at line 565 of file AbsExtAPI.cpp.

566{
567 const IntervalValue n = ae->getAbsValue(call->getArgument(2), call).getInterval();
568 if (n.isBottom() || n.lb().leq(-1))
569 return IntervalValue(0, IntervalValue::plus_infinity());
570 const IntervalValue source = getStrlen(call->getArgument(1), call);
571 return IntervalValue(min(n.lb(), source.lb()), min(n.ub(), source.ub()));
572}
cJSON * n
Definition cJSON.cpp:2558
IntervalValue getStrlen(const ValVar *strValue, const ICFGNode *node)
String length in elements, excluding NUL; an unproved end is unbounded.
const BoundedInt & ub() const
Return the upper bound.

◆ handleExtAPI()

void AbsExtAPI::handleExtAPI ( const CallICFGNode * call)

Handles an external API call.

Parameters
callPointer to the call ICFG node.

Definition at line 332 of file AbsExtAPI.cpp.

333{
334 const FunObjVar *fun = call->getCalledFunction();
335 assert(fun && "FunObjVar* is nullptr");
336 ExtAPIType extType = UNCLASSIFIED;
337 // get type of mem api
338 for (const std::string &annotation: ExtAPI::getExtAPI()->getExtFuncAnnotations(fun))
339 {
340 if (annotation.find("MEMCPY") != std::string::npos)
341 extType = MEMCPY;
342 if (annotation.find("MEMSET") != std::string::npos)
343 extType = MEMSET;
344 if (annotation.find("STRCPY") != std::string::npos)
345 extType = STRCPY;
346 if (annotation.find("STRCAT") != std::string::npos)
347 extType = STRCAT;
348 }
349 if (extType == UNCLASSIFIED)
350 {
351 if (func_map.find(fun->getName()) != func_map.end())
352 {
353 func_map[fun->getName()](call);
354 }
355 else
356 {
357 const SVFVar* ret = call->getRetICFGNode()->getActualRet();
358 if (ret && !ret->getType()->isPointerTy())
359 {
360 ae->updateAbsValue(ret, IntervalValue(), call);
361 }
362 }
363 }
364 // 1. memcpy functions like memcpy_chk, strncpy, annotate("MEMCPY"), annotate("BUF_CHECK:Arg0, Arg2"), annotate("BUF_CHECK:Arg1, Arg2")
365 else if (extType == MEMCPY)
366 {
367 IntervalValue len = ae->getAbsValue(call->getArgument(2), call).getInterval();
368 handleMemcpy(call->getArgument(0), call->getArgument(1), len, 0, call);
369 }
370 else if (extType == MEMSET)
371 {
372 IntervalValue len = ae->getAbsValue(call->getArgument(2), call).getInterval();
373 IntervalValue elem = ae->getAbsValue(call->getArgument(1), call).getInterval();
374 handleMemset(call->getArgument(0), elem, len, call);
375 }
376 else if (extType == STRCPY)
377 {
378 handleStrcpy(call);
379 }
380 else if (extType == STRCAT)
381 {
382 // Both strcat and strncat are annotated as STRCAT.
383 // Distinguish by name: strncat/wcsncat contain "ncat".
384 const std::string& name = fun->getName();
385 if (name.find("ncat") != std::string::npos)
386 handleStrncat(call);
387 else
388 handleStrcat(call);
389 }
390 else
391 {
392
393 }
394 return;
395}
const char *const name
Definition cJSON.h:264
void handleMemcpy(const ValVar *dst, const ValVar *src, const IntervalValue &len, u32_t start_idx, const ICFGNode *node)
Core memcpy: copy len bytes from src to dst starting at dst[start_idx].
void handleStrncat(const CallICFGNode *call)
void handleMemset(const ValVar *dst, const IntervalValue &elem, const IntervalValue &len, const ICFGNode *node)
ExtAPIType
Enumeration of external API types.
Definition AbsExtAPI.h:55
void handleStrcat(const CallICFGNode *call)
void handleStrcpy(const CallICFGNode *call)
Map< std::string, std::function< void(const CallICFGNode *)> > func_map
Map of function names to handlers.
Definition AbsExtAPI.h:145
const RetICFGNode * getRetICFGNode() const
Return callsite.
Definition ICFGNode.h:440
static ExtAPI * getExtAPI()
Definition ExtAPI.cpp:43
const SVFVar * getActualRet() const
Return actual return parameter.
Definition ICFGNode.h:625

◆ handleMemcpy()

void AbsExtAPI::handleMemcpy ( const ValVar * dst,
const ValVar * src,
const IntervalValue & len,
u32_t start_idx,
const ICFGNode * node )

Core memcpy: copy len bytes from src to dst starting at dst[start_idx].

Definition at line 632 of file AbsExtAPI.cpp.

635{
636 AbstractState& as = getAbsState(node);
637
638 u32_t elemSize = getElementSize(dst);
640 u32_t range_val = size / elemSize;
641
642 for (u32_t index = 0; index < range_val; index++)
643 {
644 AbstractValue expr_src =
645 ae->getGepObjAddrs(node, src, IntervalValue(index));
646 AbstractValue expr_dst =
647 ae->getGepObjAddrs(node, dst, IntervalValue(index + start_idx));
648 for (const auto &dstAddr: expr_dst.getAddrs())
649 {
650 for (const auto &srcAddr: expr_src.getAddrs())
651 {
652 u32_t objId = as.getIDFromAddr(srcAddr);
653 if (as.inAddrToValTable(objId) || as.inAddrToAddrsTable(objId))
654 {
655 as.store(dstAddr, as.load(srcAddr));
656 }
657 }
658 }
659 }
660}
u32_t getElementSize(const ValVar *var)
Get the byte size of each element for a pointer/array variable.
static u32_t getBoundedMinimumByteCount(const IntervalValue &len)
Return the lower bound of len, capped by the field limit.
void store(u32_t addr, const AbstractValue &val)
virtual bool inAddrToValTable(u32_t id) const
whether the memory address stores abstract value
bool inAddrToAddrsTable(u32_t id) const
whether the memory address stores memory addresses

◆ handleMemset()

void AbsExtAPI::handleMemset ( const ValVar * dst,
const IntervalValue & elem,
const IntervalValue & len,
const ICFGNode * node )

Core memset: fill dst with elem for len bytes. Note: elemSize here uses the pointee type's full size (not array element size) to match how LLVM memset/wmemset intrinsics measure len. For a pointer to wchar_t[100], elemSize = sizeof(wchar_t[100]), so range_val reflects the number of top-level GEP fields, not individual array elements.

Definition at line 667 of file AbsExtAPI.cpp.

669{
670 AbstractState& as = getAbsState(node);
671
672 u32_t elemSize = 1;
673 if (dst->getType()->isArrayTy())
674 {
676 ->getTypeOfElement()->getByteSize();
677 }
678 else if (dst->getType()->isPointerTy())
679 {
680 elemSize = 1;
681 }
682 else
683 {
684 assert(false && "unsupported type for element size");
685 }
687 u32_t range_val = size / elemSize;
688
689 for (u32_t index = 0; index < range_val; index++)
690 {
691 AbstractValue lhs_gep = ae->getGepObjAddrs(node, dst, IntervalValue(index));
692 for (const auto &addr: lhs_gep.getAddrs())
693 {
694 u32_t objId = as.getIDFromAddr(addr);
695 if (as.inAddrToValTable(objId))
696 {
697 AbstractValue tmp = as.load(addr);
698 tmp.join_with(elem);
699 as.store(addr, tmp);
700 }
701 else
702 {
703 as.store(addr, elem);
704 }
705 }
706 }
707}
void join_with(const AbstractValue &other)

◆ handleStrcat()

void AbsExtAPI::handleStrcat ( const CallICFGNode * call)

strcat(dst, src): append all of src after the end of dst. Covers: strcat, __strcat_chk, wcscat, __wcscat_chk

Definition at line 546 of file AbsExtAPI.cpp.

547{
548 const ValVar* dst = call->getArgument(0);
549 const ValVar* src = call->getArgument(1);
550 IntervalValue dstLen = getStrlen(dst, call);
551 IntervalValue srcLen = getStrlen(src, call);
552 handleStringCopy(call, srcLen, dstLen);
553}
void handleStringCopy(const CallICFGNode *call, const IntervalValue &length, const IntervalValue &start)
Write length source elements and a NUL into dst at element start.

◆ handleStrcpy()

void AbsExtAPI::handleStrcpy ( const CallICFGNode * call)

strcpy(dst, src): copy all of src (including '\0') into dst. Covers: strcpy, __strcpy_chk, stpcpy, wcscpy, __wcscpy_chk

Definition at line 537 of file AbsExtAPI.cpp.

538{
539 const ValVar* src = call->getArgument(1);
540 IntervalValue srcLen = getStrlen(src, call);
541 handleStringCopy(call, srcLen, IntervalValue(0));
542}

◆ handleStringCopy()

void AbsExtAPI::handleStringCopy ( const CallICFGNode * call,
const IntervalValue & length,
const IntervalValue & start )

Write length source elements and a NUL into dst at element start.

Definition at line 574 of file AbsExtAPI.cpp.

576{
577 const ValVar* dst = call->getArgument(0);
578 const ValVar* src = call->getArgument(1);
579 AbstractState& as = getAbsState(call);
580 const bool precise = length.is_numeral() && start.is_numeral();
581 const bool weak = ae->getAbsValue(dst, call).getAddrs().size() != 1;
583 {
584 AbstractValue value(IntervalValue::top());
585 u32_t destination = index;
586 if (precise)
587 {
588 if (index > length.getIntNumeral() ||
590 break;
591 destination += start.getIntNumeral();
592 if (index == length.getIntNumeral())
593 value = IntervalValue(0);
594 else
595 {
596 value = AbstractValue();
597 for (auto addr : ae->getGepObjAddrs(call, src, IntervalValue(index)))
598 value.join_with(as.load(addr));
599 if (!value.isInterval() || value.isAddr())
600 value = IntervalValue::top();
601 }
602 }
603 // Uncertain positions/lengths cannot justify a copy at the lower bound.
604 else if (index < start.lb().getIntNumeral())
605 continue;
606 for (auto target : ae->getAbsValue(dst, call).getAddrs())
607 {
608 const NodeID obj = as.getIDFromAddr(target);
609 if (pag->isNullOrBlkObj(obj))
610 continue;
611 const BaseObjVar* base = pag->getBaseObject(obj);
612 const auto* gep = SVFUtil::dyn_cast<GepObjVar>(pag->getSVFVar(obj));
613 const APOffset offset = (gep ? gep->getConstantFieldIdx() : 0) + destination;
614 // Do not wrap an out-of-object write back onto the prefix.
617 continue;
618 const auto addr = AbstractState::getVirtualMemAddress(pag->getGepObjVar(obj, destination));
619 AbstractValue stored = value;
620 if (weak)
621 {
622 const AbstractValue& old = as.load(addr);
623 stored.join_with(old.isInterval() || old.isAddr()
624 ? old : AbstractValue(IntervalValue::top()));
625 }
626 as.store(addr, stored);
627 }
628 }
629}
buffer offset
Definition cJSON.cpp:1113
s64_t getIntNumeral() const
bool is_numeral() const
Return true if the IntervalValue is a number [num, num].

◆ handleStrncat()

void AbsExtAPI::handleStrncat ( const CallICFGNode * call)

strncat(dst, src, n): append at most n elements after the end of dst. Covers: strncat, __strncat_chk, wcsncat, __wcsncat_chk

Definition at line 557 of file AbsExtAPI.cpp.

558{
559 const ValVar* dst = call->getArgument(0);
560 IntervalValue n = getStrncatLength(call);
561 IntervalValue dstLen = getStrlen(dst, call);
562 handleStringCopy(call, n, dstLen);
563}
IntervalValue getStrncatLength(const CallICFGNode *call)
Elements strncat appends: min(n, strlen(src)).

◆ initExtFunMap()

void AbsExtAPI::initExtFunMap ( )

Initializes the external function map.

Definition at line 42 of file AbsExtAPI.cpp.

43{
44#define SSE_FUNC_PROCESS(LLVM_NAME ,FUNC_NAME) \
45 auto sse_##FUNC_NAME = [this](const CallICFGNode *callNode) { \
46 /* run real ext function */ \
47 assert(callNode->arg_size() >= 1 && "external function expects one argument"); \
48 const SVFVar* argVar = callNode->getArgument(0); \
49 const AbstractValue& argVal = ae->getAbsValue(argVar, callNode); \
50 IntervalValue result = IntervalValue::top(); \
51 if (argVal.isInterval() && argVal.getInterval().is_numeral()) { \
52 u32_t rhs = argVal.getInterval().lb().getIntNumeral(); \
53 result = IntervalValue(FUNC_NAME(rhs)); \
54 } \
55 const SVFVar* retVar = callNode->getRetICFGNode()->getActualRet(); \
56 ae->updateAbsValue(retVar, result, callNode); \
57 }; \
58 func_map[#FUNC_NAME] = sse_##FUNC_NAME;
59
71 SSE_FUNC_PROCESS(llvm.sin.f64, sin);
72 SSE_FUNC_PROCESS(llvm.cos.f64, cos);
73 SSE_FUNC_PROCESS(llvm.tan.f64, tan);
74 SSE_FUNC_PROCESS(llvm.log.f64, log);
75 SSE_FUNC_PROCESS(sinh, sinh);
76 SSE_FUNC_PROCESS(cosh, cosh);
77 SSE_FUNC_PROCESS(tanh, tanh);
78
79 auto sse_svf_assert = [this](const CallICFGNode* callNode)
80 {
81 checkpoints.erase(callNode);
82 const AbstractValue& arg0Val = ae->getAbsValue(callNode->getArgument(0), callNode);
83 if (arg0Val.getInterval().equals(IntervalValue(1, 1)))
84 {
85 SVFUtil::errs() << SVFUtil::sucMsg("The assertion is successfully verified!!\n");
86 }
87 else
88 {
89 SVFUtil::errs() << SVFUtil::errMsg("Assertion failure, this svf_assert cannot be verified!!\n") << callNode->toString() << "\n";
90 assert(false);
91 }
92 return;
93 };
94 func_map["svf_assert"] = sse_svf_assert;
95
96 auto svf_assert_eq = [this](const CallICFGNode* callNode)
97 {
98 const AbstractValue& arg0Val = ae->getAbsValue(callNode->getArgument(0), callNode);
99 const AbstractValue& arg1Val = ae->getAbsValue(callNode->getArgument(1), callNode);
100 if (arg0Val.getInterval().equals(arg1Val.getInterval()))
101 {
102 SVFUtil::errs() << SVFUtil::sucMsg("The assertion is successfully verified!!\n");
103 }
104 else
105 {
106 SVFUtil::errs() <<"svf_assert_eq Fail. " << callNode->toString() << "\n";
107 assert(false);
108 }
109 return;
110 };
111 func_map["svf_assert_eq"] = svf_assert_eq;
112
113 auto svf_print = [&](const CallICFGNode* callNode)
114 {
115 assert(callNode->arg_size() >= 2 && "svf_print expects two arguments");
116 std::string text = strRead(callNode->getArgument(1), callNode);
117 IntervalValue itv = ae->getAbsValue(callNode->getArgument(0), callNode).getInterval();
118 std::cout << "Text: " << text <<", Value: " << callNode->getArgument(0)->toString()
119 << ", PrintVal: " << itv.toString() << ", Loc:" << callNode->getSourceLoc() << std::endl;
120 return;
121 };
122 func_map["svf_print"] = svf_print;
123
124 auto svf_set_value = [&](const CallICFGNode* callNode)
125 {
126 assert(callNode->arg_size() >= 3 && "set_value expects three arguments");
127 AbstractState&as = getAbsState(callNode);
128 const AbstractValue& lbVal = ae->getAbsValue(callNode->getArgument(1), callNode);
129 const AbstractValue& ubVal = ae->getAbsValue(callNode->getArgument(2), callNode);
130 assert(lbVal.getInterval().is_numeral() && ubVal.getInterval().is_numeral());
131 AbstractValue num;
132 num.getInterval().set_to_top();
133 num.getInterval().meet_with(IntervalValue(lbVal.getInterval().lb(), ubVal.getInterval().ub()));
134 ae->updateAbsValue(callNode->getArgument(0), num, callNode);
135 const ICFGNode* node = SVFUtil::cast<ValVar>(callNode->getArgument(0))->getICFGNode();
136 for (const SVFStmt* stmt: node->getSVFStmts())
137 {
138 if (SVFUtil::isa<LoadStmt>(stmt))
139 {
140 const LoadStmt* load = SVFUtil::cast<LoadStmt>(stmt);
141 const AbstractValue& ptrVal = ae->getAbsValue(load->getRHSVar(), callNode);
142 for (auto addr : ptrVal.getAddrs())
143 as.store(addr, num);
144 }
145 }
146 return;
147 };
148 func_map["set_value"] = svf_set_value;
149
150 auto sse_fread = [&](const CallICFGNode *callNode)
151 {
152 assert(callNode->arg_size() >= 3 && "fread expects at least three arguments");
153 IntervalValue block_count = ae->getAbsValue(callNode->getArgument(2), callNode).getInterval();
154 IntervalValue block_size = ae->getAbsValue(callNode->getArgument(1), callNode).getInterval();
155 IntervalValue block_byte = block_count * block_size;
156 (void)block_byte;
157 };
158 func_map["fread"] = sse_fread;
159
160 auto sse_sprintf = [&](const CallICFGNode *callNode)
161 {
162 // printf is difficult to predict since it has no byte size arguments
163 };
164
165 auto sse_snprintf = [&](const CallICFGNode *callNode)
166 {
167 assert(callNode->arg_size() >= 2 &&
168 "formatted-output function expects at least two arguments");
169 u32_t elemSize = 1;
170 if (callNode->arg_size() > 2 &&
171 callNode->getArgument(2)->getType()->isArrayTy())
172 {
174 callNode->getArgument(2)->getType())
175 ->getTypeOfElement()->getByteSize();
176 }
177 IntervalValue size = ae->getAbsValue(callNode->getArgument(1), callNode).getInterval()
178 * IntervalValue(elemSize) - IntervalValue(1);
179 (void)size;
180 };
181 func_map["__snprintf_chk"] = sse_snprintf;
182 func_map["__vsprintf_chk"] = sse_sprintf;
183 func_map["__sprintf_chk"] = sse_sprintf;
184 func_map["snprintf"] = sse_snprintf;
185 func_map["sprintf"] = sse_sprintf;
186 func_map["vsprintf"] = sse_sprintf;
187 func_map["vsnprintf"] = sse_snprintf;
188 func_map["__vsnprintf_chk"] = sse_snprintf;
189 func_map["swprintf"] = sse_snprintf;
190 func_map["_snwprintf"] = sse_snprintf;
191
192
193 auto sse_itoa = [&](const CallICFGNode* callNode)
194 {
195 assert(callNode->arg_size() >= 3 && "itoa expects three arguments");
196 u32_t num = (u32_t) ae->getAbsValue(callNode->getArgument(0), callNode).getInterval().getNumeral();
197 std::string snum = std::to_string(num);
198 (void)snum;
199 };
200 func_map["itoa"] = sse_itoa;
201
202
203 auto sse_strlen = [&](const CallICFGNode *callNode)
204 {
205 assert(callNode->arg_size() >= 1 && "strlen expects one argument");
206 const SVFVar* retVar = callNode->getRetICFGNode()->getActualRet();
207 ae->updateAbsValue(retVar, getStrlen(callNode->getArgument(0), callNode), callNode);
208 };
209 func_map["strlen"] = sse_strlen;
210 func_map["wcslen"] = sse_strlen;
211
212 auto sse_recv = [&](const CallICFGNode *callNode)
213 {
214 assert(callNode->arg_size() >= 4 && "recv expects four arguments");
215 IntervalValue len = ae->getAbsValue(callNode->getArgument(2), callNode).getInterval() - IntervalValue(1);
216 const SVFVar* retVar = callNode->getRetICFGNode()->getActualRet();
217 ae->updateAbsValue(retVar, len, callNode);
218 };
219 func_map["recv"] = sse_recv;
220 func_map["__recv"] = sse_recv;
221
222 auto sse_free = [&](const CallICFGNode *callNode)
223 {
224 assert(callNode->arg_size() >= 1 && "free expects one argument");
225 AbstractState& as = getAbsState(callNode);
226 const AbstractValue& ptrVal = ae->getAbsValue(callNode->getArgument(0), callNode);
227 for (auto addr: ptrVal.getAddrs())
228 {
230 as.addToFreedAddrs(addr);
231 }
232 };
233 // Add all free-related functions to func_map
234 std::vector<std::string> freeFunctions =
235 {
236 "VOS_MemFree", "cfree", "free", "free_all_mem", "freeaddrinfo",
237 "gcry_mpi_release", "gcry_sexp_release", "globfree", "nhfree",
238 "obstack_free", "safe_cfree", "safe_free", "safefree", "safexfree",
239 "sm_free", "vim_free", "xfree", "SSL_CTX_free", "SSL_free", "XFree"
240 };
241
242 for (const auto& name : freeFunctions)
243 {
244 func_map[name] = sse_free;
245 }
246};
#define SSE_FUNC_PROCESS(LLVM_NAME,FUNC_NAME)
std::string strRead(const ValVar *rhs, const ICFGNode *node)
Reads a string from the abstract state.
static bool isNullOrBlackHoleAddr(u32_t addr)
Whether addr has no concrete backing memory object.
void addToFreedAddrs(NodeID addr)
const SVFStmtList & getSVFStmts() const
Definition ICFGNode.h:116
void meet_with(const IntervalValue &other)
Return a intersected IntervalValue.
const std::string toString() const
void set_to_top()
Set current IntervalValue as top.
bool equals(const IntervalValue &other) const
Equality comparison.
const ValVar * getRHSVar() const
int iscntrl(int c)
Definition extapi.c:1026
int isdigit(int c)
Definition extapi.c:1031
int isgraph(int c)
Definition extapi.c:1036
int isspace(char c)
Definition extapi.c:1056
int isprint(int c)
Definition extapi.c:1046
int ispunct(int argument)
Definition extapi.c:1051
int isblank(int character)
Definition extapi.c:1021
int isalnum(int character)
Definition extapi.c:1011
int isupper(int c)
Definition extapi.c:1061
int isxdigit(int c)
Definition extapi.c:1066
int isalpha(int character)
Definition extapi.c:1016
std::string sucMsg(const std::string &msg)
Returns successful message by converting a string into green string output.
Definition SVFUtil.cpp:75
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

◆ isValidLength()

bool AbsExtAPI::isValidLength ( const IntervalValue & len)
static

Check if an interval length is usable (not bottom, not unbounded).

Check if an interval length is usable for memory operations. Returns false for bottom (no information) or unbounded lower bound (cannot determine a concrete start for iteration).

Definition at line 419 of file AbsExtAPI.cpp.

420{
421 return !len.isBottom() && !len.lb().is_minus_infinity();
422}
bool is_minus_infinity() const

◆ strRead()

std::string AbsExtAPI::strRead ( const ValVar * rhs,
const ICFGNode * node )

Reads a string from the abstract state.

Parameters
asReference to the abstract state.
rhsPointer to the SVF variable representing the string.
Returns
The string value.

Definition at line 304 of file AbsExtAPI.cpp.

305{
306 AbstractState& as = getAbsState(node);
307 std::string str0;
308
310 {
311 AbstractValue expr0 =
312 ae->getGepObjAddrs(node, rhs, IntervalValue(index));
313
314 AbstractValue val;
315 for (const auto &addr: expr0.getAddrs())
316 {
317 val.join_with(as.load(addr));
318 }
319 if (!val.getInterval().is_numeral())
320 {
321 break;
322 }
323 if ((char) val.getInterval().getIntNumeral() == '\0')
324 {
325 break;
326 }
327 str0.push_back((char) val.getInterval().getIntNumeral());
328 }
329 return str0;
330}

◆ AbstractInterpretation

friend class AbstractInterpretation
friend

Definition at line 61 of file AbsExtAPI.h.

Member Data Documentation

◆ ae

AbstractInterpretation* SVF::AbsExtAPI::ae
protected

Owning AbstractInterpretation; provides state access.

Definition at line 142 of file AbsExtAPI.h.

◆ checkpoints

Set<const CallICFGNode*> SVF::AbsExtAPI::checkpoints

Definition at line 139 of file AbsExtAPI.h.

◆ func_map

Map<std::string, std::function<void(const CallICFGNode*)> > SVF::AbsExtAPI::func_map
protected

Map of function names to handlers.

Definition at line 145 of file AbsExtAPI.h.

◆ icfg

ICFG* SVF::AbsExtAPI::icfg
protected

Pointer to the interprocedural control flow graph.

Definition at line 144 of file AbsExtAPI.h.

◆ pag

PAG* SVF::AbsExtAPI::pag
protected

Pointer to the SVF intermediate representation.

Definition at line 143 of file AbsExtAPI.h.


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