Skip to content

Commit f74f568

Browse files
authored
[clang][analyzer] PointerSubChecker should not warn on pointers converted to numerical type (#111846)
Pointer values casted to integer (non-pointer) type should be able to be subtracted as usual.
1 parent 73ad416 commit f74f568

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
6161
if (LR->getSymbolicBase() || RR->getSymbolicBase())
6262
return;
6363

64+
if (!B->getLHS()->getType()->isPointerType() ||
65+
!B->getRHS()->getType()->isPointerType())
66+
return;
67+
6468
const auto *ElemLR = dyn_cast<ElementRegion>(LR);
6569
const auto *ElemRR = dyn_cast<ElementRegion>(RR);
6670

clang/test/Analysis/pointer-sub.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// RUN: %clang_analyze_cc1 -analyzer-checker=security.PointerSub -analyzer-output=text-minimal -verify %s
22

3+
typedef int * Ptr;
4+
35
void f1(void) {
46
int x, y, z[10];
57
int d = &y - &x; // expected-warning{{Subtraction of two pointers that do not point into the same array is undefined behavior}}
@@ -10,6 +12,12 @@ void f1(void) {
1012
d = &x - (&x + 1); // no-warning
1113
d = (&x + 0) - &x; // no-warning
1214
d = (z + 10) - z; // no-warning
15+
d = (long long)&y - (long long)&x; // no-warning
16+
long long l = 1;
17+
d = l - (long long)&y; // no-warning
18+
Ptr p1 = &x;
19+
Ptr p2 = &y;
20+
d = p1 - p2; // expected-warning{{Subtraction of two pointers that do not point into the same array is undefined behavior}}
1321
}
1422

1523
void f2(void) {
@@ -28,6 +36,10 @@ void f2(void) {
2836

2937
d = (int *)((char *)(&a[4]) + sizeof(int)) - &a[4]; // no-warning (pointers into the same array data)
3038
d = (int *)((char *)(&a[4]) + 1) - &a[4]; // expected-warning{{Subtraction of two pointers that}}
39+
40+
long long a1 = (long long)&a[1];
41+
long long b1 = (long long)&b[1];
42+
d = a1 - b1;
3143
}
3244

3345
void f3(void) {

0 commit comments

Comments
 (0)