33
44#include " analysis/IntRanges.hpp"
55#include " analysis/FunctionFacts.hpp"
6+ #include " analysis/ParameterDebugBinding.hpp"
67#include " analysis/smt/SmtEncoding.hpp"
78#include " analysis/smt/SmtRefinement.hpp"
89
10+ #include < algorithm>
911#include < map>
1012#include < optional>
1113#include < utility>
1214
15+ #include < llvm/ADT/APInt.h>
1316#include < llvm/ADT/DenseMap.h>
1417#include < llvm/ADT/SmallPtrSet.h>
1518#include < llvm/Analysis/AssumptionCache.h>
1619#include < llvm/Analysis/LazyValueInfo.h>
1720#include < llvm/Analysis/TargetLibraryInfo.h>
21+ #include < llvm/BinaryFormat/Dwarf.h>
1822#include < llvm/Config/llvm-config.h>
1923#include < llvm/IR/Argument.h>
2024#include < llvm/IR/Constants.h>
2125#include < llvm/IR/DataLayout.h>
26+ #include < llvm/IR/DebugInfoMetadata.h>
2227#include < llvm/IR/Function.h>
2328#include < llvm/IR/InstrTypes.h>
2429#include < llvm/IR/Instruction.h>
@@ -58,6 +63,9 @@ namespace ctrace::stack::analysis
5863 int64_t k = 0 ;
5964 // / The size the subtraction really uses: @ref base with its casts.
6065 llvm::Value* operand = nullptr ;
66+ // / The signedness the program gives the result, from the cast that widens it:
67+ // / clang sign-extends a signed value and zero-extends an unsigned one.
68+ std::optional<IntReading> reading;
6169 };
6270
6371 struct SizeMinusKSink
@@ -79,18 +87,18 @@ namespace ctrace::stack::analysis
7987 {
8088 }
8189
82- SmtFeasibility
83- isSignedLessEqualFeasible (const std::map<const llvm::Value*, IntRange>& ranges,
84- const llvm::Value& lhs, std::int64_t rhsConstant,
85- const llvm::Instruction* contextInst,
86- const FunctionFacts* facts) const
90+ SmtFeasibility isBelowFeasible (const std::map<const llvm::Value*, IntRange>& ranges,
91+ const llvm::Value& lhs, std::int64_t bound,
92+ IntReading reading, const llvm::Instruction* contextInst,
93+ const FunctionFacts* facts) const
8794 {
8895 const smt::QueryPoint point = queryPoint (contextInst, facts);
8996 return evaluateQueryAt (ranges, point,
9097 [&]
9198 {
92- return smt::encodeSignedComparisonFeasibility (
93- ranges, lhs, rhsConstant, false , point);
99+ return smt::encodeBelowConstantFeasibility (
100+ ranges, lhs, bound, reading == IntReading::Unsigned,
101+ point);
94102 });
95103 }
96104 };
@@ -157,6 +165,18 @@ namespace ctrace::stack::analysis
157165 template <typename Canonicalize>
158166 static SizeMinusKMatch matchSizeMinusK (llvm::Value* v, Canonicalize canonicalize)
159167 {
168+ // The cast applied to the subtraction itself, the innermost one, says how its
169+ // result is read, as for a stack-buffer index.
170+ std::optional<IntReading> reading;
171+ while (auto * cast = llvm::dyn_cast<llvm::CastInst>(v))
172+ {
173+ reading.reset ();
174+ if (llvm::isa<llvm::SExtInst>(cast))
175+ reading = IntReading::Signed;
176+ else if (llvm::isa<llvm::ZExtInst>(cast))
177+ reading = IntReading::Unsigned;
178+ v = cast->getOperand (0 );
179+ }
160180 v = canonicalize (v);
161181 if (auto * bin = llvm::dyn_cast<llvm::BinaryOperator>(v))
162182 {
@@ -169,7 +189,7 @@ namespace ctrace::stack::analysis
169189 {
170190 int64_t k = c->getSExtValue ();
171191 if (k > 0 )
172- return {lhs, k, bin->getOperand (0 )};
192+ return {lhs, k, bin->getOperand (0 ), reading };
173193 }
174194 }
175195 if (bin->getOpcode () == llvm::Instruction::Add)
@@ -178,7 +198,7 @@ namespace ctrace::stack::analysis
178198 {
179199 int64_t k = -c->getSExtValue ();
180200 if (k > 0 )
181- return {lhs, k, bin->getOperand (0 )};
201+ return {lhs, k, bin->getOperand (0 ), reading };
182202 }
183203 }
184204 }
@@ -189,7 +209,9 @@ namespace ctrace::stack::analysis
189209 llvm::Value* lhs, llvm::Value* rhs, llvm::Instruction* at)
190210 {
191211#if LLVM_VERSION_MAJOR >= 17
192- if (llvm::Constant* c = lvi.getPredicateAt (pred, lhs, rhs, at, false ))
212+ // The block value bounds a cast by its source: a zero-extended byte is never
213+ // negative.
214+ if (llvm::Constant* c = lvi.getPredicateAt (pred, lhs, rhs, at, true ))
193215 {
194216 if (auto * ci = llvm::dyn_cast<llvm::ConstantInt>(c))
195217 return ci->isOne ();
@@ -200,34 +222,28 @@ namespace ctrace::stack::analysis
200222#endif
201223 }
202224
203- static bool isNonNullAt (llvm::Value* v, llvm::Instruction* at, llvm::LazyValueInfo& lvi)
225+ // / Whether @p size loads a variable declared with an unsigned type as wide as @p size.
226+ // / Subtracting a constant from it is then unsigned whatever the constant's type. A
227+ // / signed variable proves nothing: `n - sizeof(T)` is unsigned for a `long n`.
228+ static bool readsUnsignedVariable (const llvm::Value& size)
204229 {
205- if (!v || !v->getType ()->isPointerTy ())
206- return false ;
207- if (auto * arg = llvm::dyn_cast<llvm::Argument>(v))
230+ const auto * load = llvm::dyn_cast<llvm::LoadInst>(&size);
231+ const auto * slot = load ? llvm::dyn_cast<llvm::AllocaInst>(
232+ load->getPointerOperand ()->stripPointerCasts ())
233+ : nullptr ;
234+ const llvm::DILocalVariable* variable = slot ? declaredVariable (*slot) : nullptr ;
235+ const llvm::DIType* type = variable ? variable->getType () : nullptr ;
236+ while (const auto * derived = llvm::dyn_cast_or_null<llvm::DIDerivedType>(type))
208237 {
209- if (arg->hasNonNullAttr ())
210- return true ;
238+ const unsigned tag = derived->getTag ();
239+ if (tag != llvm::dwarf::DW_TAG_typedef && tag != llvm::dwarf::DW_TAG_const_type &&
240+ tag != llvm::dwarf::DW_TAG_volatile_type)
241+ break ;
242+ type = derived->getBaseType ();
211243 }
212- if (auto * call = llvm::dyn_cast<llvm::CallBase>(v))
213- {
214- if (call->hasRetAttr (llvm::Attribute::NonNull))
215- return true ;
216- }
217- auto * ptrTy = llvm::cast<llvm::PointerType>(v->getType ());
218- auto * nullPtr = llvm::ConstantPointerNull::get (ptrTy);
219- return predicateAt (lvi, llvm::CmpInst::ICMP_NE , v, nullPtr, at);
220- }
221-
222- static bool isGreaterThanAt (llvm::Value* v, int64_t bound, llvm::Instruction* at,
223- llvm::LazyValueInfo& lvi)
224- {
225- if (!v || !v->getType ()->isIntegerTy ())
226- return false ;
227- if (auto * c = llvm::dyn_cast<llvm::ConstantInt>(v))
228- return c->getSExtValue () > bound;
229- auto * boundConst = llvm::ConstantInt::get (v->getType (), bound, true );
230- return predicateAt (lvi, llvm::CmpInst::ICMP_SGT , v, boundConst, at);
244+ const auto * basic = llvm::dyn_cast_or_null<llvm::DIBasicType>(type);
245+ return basic && basic->getEncoding () == llvm::dwarf::DW_ATE_unsigned &&
246+ basic->getSizeInBits () == size.getType ()->getIntegerBitWidth ();
231247 }
232248
233249 static bool getKnownSinkCallInfo (llvm::CallBase* CB , const llvm::TargetLibraryInfo& TLI ,
@@ -486,31 +502,69 @@ namespace ctrace::stack::analysis
486502 return v;
487503 };
488504
489- auto emitIssue = [&](Instruction* at, Value* dest, const SizeMinusKMatch& match,
490- StringRef sinkName, bool hasPtrDest)
505+ // Whether `size >= bound` holds at @p at, read as @p reading.
506+ auto provenAtLeast = [&](const SizeMinusKMatch& match, IntReading reading,
507+ int64_t bound, Instruction* at)
491508 {
509+ Value* size = match.operand ;
510+ const bool isUnsigned = reading == IntReading::Unsigned;
511+ if (predicateAt (LVI , isUnsigned ? CmpInst::ICMP_UGE : CmpInst::ICMP_SGE , size,
512+ ConstantInt::get (size->getType (), bound, true ), at))
513+ return true ;
514+
515+ // -O0 code re-reads a variable from its slot, which carries its bounds. Take
516+ // them where the value is read: `b[--l]` stores to the slot before the write.
517+ const Value* key = size;
518+ const Instruction* readAt = at;
519+ if (auto * load = dyn_cast<LoadInst>(size))
520+ {
521+ key = load->getPointerOperand ();
522+ readAt = load;
523+ }
524+ if (const std::optional<IntRange> range = pointRanges.at (key, *readAt, reading);
525+ range && range->hasLower && range->lower >= bound)
526+ return true ;
527+
528+ // Bound the size the call really uses, casts included: a narrowing cast can
529+ // make it small however large the value before the cast. The range is known
530+ // for match.base, and the encoded casts carry it to the operand.
531+ const std::map<const llvm::Value*, IntRange> queryRanges =
532+ buildValueQueryRanges (*match.base , pointRanges.at (*at));
533+ return evaluator.isBelowFeasible (queryRanges, *size, bound, reading, at, &facts) ==
534+ SmtFeasibility::Infeasible;
535+ };
536+
537+ // Reports `size - k` when the subtraction can wrap in the signedness the program
538+ // gives it (CWE-191): below 0 when unsigned, below the type's minimum when signed.
539+ // A signed result that is only negative is exact: an index then writes before the
540+ // buffer (CWE-124), and a length becomes a huge size_t on conversion (CWE-195),
541+ // neither of which is an underflow of the subtraction.
542+ auto emitIssue = [&](Instruction* at, const SizeMinusKMatch& match, StringRef sinkName)
543+ {
544+ std::optional<IntReading> reading = match.reading ;
545+ if (!reading && readsUnsignedVariable (*match.operand ))
546+ reading = IntReading::Unsigned;
547+ // Unknown signedness asks both questions. A type wider than 64 bits takes the
548+ // 64-bit minimum: proving the size above it still rules out the wrap.
549+ const unsigned width =
550+ std::min (match.operand ->getType ()->getIntegerBitWidth (), 64u );
551+ const int64_t signedMin = APInt::getSignedMinValue (width).getSExtValue ();
552+ const bool mayWrapUnsigned =
553+ reading != IntReading::Signed &&
554+ !provenAtLeast (match, IntReading::Unsigned, match.k , at);
555+ const bool mayWrapSigned =
556+ !mayWrapUnsigned && reading != IntReading::Unsigned &&
557+ !provenAtLeast (match, IntReading::Signed, signedMin + match.k , at);
558+ if (!mayWrapUnsigned && !mayWrapSigned)
559+ return ;
560+
492561 SizeMinusKWriteIssue issue;
493562 issue.funcName = F.getName ().str ();
494563 issue.sinkName = sinkName.str ();
495- issue.hasPointerDest = hasPtrDest;
496- issue.ptrNonNull = hasPtrDest ? isNonNullAt (dest, at, LVI ) : true ;
497- const int64_t k = match.k ;
498- issue.sizeAboveK = isGreaterThanAt (match.base , k, at, LVI );
499- if (!issue.sizeAboveK && match.operand && match.operand ->getType ()->isIntegerTy ())
500- {
501- // Bound the size the call really uses, casts included: a narrowing cast can
502- // make it small however large the value before the cast. The range is known
503- // for match.base, and the encoded casts carry it to the operand.
504- const std::map<const llvm::Value*, IntRange> queryRanges =
505- buildValueQueryRanges (*match.base , pointRanges.at (*at));
506- if (evaluator.isSignedLessEqualFeasible (queryRanges, *match.operand , k, at,
507- &facts) == SmtFeasibility::Infeasible)
508- issue.sizeAboveK = true ;
509- }
510- issue.k = k;
564+ issue.k = match.k ;
511565 issue.inst = at;
512- if (! issue.ptrNonNull || !issue. sizeAboveK )
513- out.push_back (std::move (issue));
566+ issue.wrapsSigned = mayWrapSigned;
567+ out.push_back (std::move (issue));
514568 };
515569
516570 for (Instruction& I : instructions (F))
@@ -529,7 +583,7 @@ namespace ctrace::stack::analysis
529583 std::string label = canonicalizeSinkName (sinkName);
530584 if (label == " llvm.mem*" || label == " lib call" )
531585 label += " (len = size-k)" ;
532- emitIssue (&I, canonical ( CB -> getArgOperand (dstIdx)), match, label, true );
586+ emitIssue (&I, match, label);
533587 }
534588 continue ;
535589 }
@@ -549,8 +603,7 @@ namespace ctrace::stack::analysis
549603 matchSizeMinusK (CB ->getArgOperand (sink.lenIdx ), canonical);
550604 if (!match.base )
551605 continue ;
552- emitIssue (&I, canonical (CB ->getArgOperand (sink.dstIdx )), match,
553- calleeFn->getName (), true );
606+ emitIssue (&I, match, calleeFn->getName ());
554607 }
555608 }
556609 }
@@ -570,8 +623,7 @@ namespace ctrace::stack::analysis
570623 }
571624 if (!match.base )
572625 continue ;
573- emitIssue (&I, canonical (gep->getPointerOperand ()), match,
574- " store (idx = size-k)" , true );
626+ emitIssue (&I, match, " store (idx = size-k)" );
575627 }
576628 }
577629 }
0 commit comments