Skip to content

Commit be5bec2

Browse files
authored
Merge pull request #155 from CoreTrace/152-size-minus-k-cannot-wrap
fix(size-minus-k): report s - k only when the subtraction can wrap
2 parents a505fd8 + a9e61de commit be5bec2

12 files changed

Lines changed: 302 additions & 89 deletions

‎include/analysis/ParameterDebugBinding.hpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
namespace llvm
88
{
9+
class AllocaInst;
910
class Argument;
1011
class DILocalVariable;
1112
class DIType;
@@ -34,6 +35,10 @@ namespace ctrace::stack::analysis
3435
std::uint8_t paddingTail[5] = {};
3536
};
3637

38+
/// The source variable, parameter or local, that a debug declaration places in @p slot, or
39+
/// nullptr when no declaration names it.
40+
const llvm::DILocalVariable* declaredVariable(const llvm::AllocaInst& slot);
41+
3742
/// The parameter declared on the slot that -O0 code spills @p Arg to, or nullptr.
3843
///
3944
/// Clang stores each argument into an alloca that carries the parameter's declaration.

‎include/analysis/SizeMinusKWrites.hpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ namespace ctrace::stack::analysis
2424
std::string sinkName; // call name or "store"
2525
int64_t k = 1;
2626
const llvm::Instruction* inst = nullptr;
27-
std::uint64_t ptrNonNull : 1 = false;
28-
std::uint64_t sizeAboveK : 1 = false;
2927
std::uint64_t hasPointerDest : 1 = true;
30-
std::uint64_t reservedFlags : 61 = 0;
28+
/// `size - k` may fall below the minimum of a signed type, not below 0.
29+
std::uint64_t wrapsSigned : 1 = false;
30+
std::uint64_t reservedFlags : 62 = 0;
3131
};
3232

3333
std::vector<SizeMinusKWriteIssue> analyzeSizeMinusKWrites(

‎include/analysis/smt/SmtEncoding.hpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,13 @@ namespace ctrace::stack::analysis::smt
6060
const llvm::Value& lhs, std::int64_t rhsConstant,
6161
bool greaterThan, const QueryPoint& point = {});
6262

63+
/// @brief Whether @p lhs can be below @p bound at @p point, compared as unsigned when
64+
/// @p isUnsigned and as signed otherwise.
65+
ConstraintIR
66+
encodeBelowConstantFeasibility(const std::map<const llvm::Value*, IntRange>& ranges,
67+
const llvm::Value& lhs, std::int64_t bound, bool isUnsigned,
68+
const QueryPoint& point = {});
69+
6370
/// @brief The query of @p point without any violation: the rule's ranges, the assumptions
6471
/// before @p point and its reachability condition. Satisfiable when @p point can run.
6572
ConstraintIR encodeReachability(const std::map<const llvm::Value*, IntRange>& ranges,

‎src/analysis/ParameterDebugBinding.cpp‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,22 @@
1515

1616
namespace ctrace::stack::analysis
1717
{
18+
const llvm::DILocalVariable* declaredVariable(const llvm::AllocaInst& slot)
19+
{
20+
auto* declared = const_cast<llvm::AllocaInst*>(&slot);
21+
for (llvm::DbgVariableRecord* dvr : llvm::findDVRDeclares(declared))
22+
{
23+
if (dvr && dvr->getVariable())
24+
return dvr->getVariable();
25+
}
26+
for (llvm::DbgDeclareInst* ddi : llvm::findDbgDeclares(declared))
27+
{
28+
if (ddi && ddi->getVariable())
29+
return ddi->getVariable();
30+
}
31+
return nullptr;
32+
}
33+
1834
const llvm::DILocalVariable* spilledParameter(const llvm::Argument& Arg)
1935
{
2036
for (const llvm::User* user : Arg.users())

‎src/analysis/SizeMinusKWrites.cpp‎

Lines changed: 112 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,27 @@
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

Comments
 (0)