Skip to content

Commit 4dbaf18

Browse files
committed
[-Wunsafe-buffer-usage] Add fixits for array to pointer assignment (llvm#81343)
Introducing CArrayToPtrAssignment gadget and implementing fixits for some cases of array being assigned to pointer. Key observations: - const size array can be assigned to std::span and bounds are propagated - const size array can't be on LHS of assignment This means array to pointer assignment has no strategy implications. Fixits are implemented for cases where one of the variables in the assignment is safe. For assignment of a safe array to unsafe pointer we know that the RHS will never be transformed since it's safe and can immediately emit the optimal fixit. Similarly for assignment of unsafe array to safe pointer. (Obviously this is not and can't be future-proof in regards to what variables we consider unsafe and that is fine.) Fixits for assignment from unsafe array to unsafe pointer (from Array to Span strategy) are not implemented in this patch as that needs to be properly designed first - we might possibly implement optimal fixits for partially transformed cases, put both variables in a single fixit group or do something else. (cherry picked from commit 6fce42f)
1 parent 1591857 commit 4dbaf18

File tree

4 files changed

+161
-15
lines changed

4 files changed

+161
-15
lines changed

clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ FIXABLE_GADGET(UPCAddressofArraySubscript) // '&DRE[any]' in an Unspecified Poin
4545
FIXABLE_GADGET(UPCStandalonePointer)
4646
FIXABLE_GADGET(UPCPreIncrement) // '++Ptr' in an Unspecified Pointer Context
4747
FIXABLE_GADGET(UUCAddAssign) // 'Ptr += n' in an Unspecified Untyped Context
48-
FIXABLE_GADGET(PointerAssignment)
48+
FIXABLE_GADGET(PtrToPtrAssignment)
49+
FIXABLE_GADGET(CArrayToPtrAssignment)
4950
FIXABLE_GADGET(PointerInit)
5051

5152
#undef FIXABLE_GADGET

clang/lib/Analysis/UnsafeBufferUsage.cpp

Lines changed: 113 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
10+
#include "clang/AST/ASTContext.h"
1011
#include "clang/AST/Decl.h"
1112
#include "clang/AST/Expr.h"
1213
#include "clang/AST/RecursiveASTVisitor.h"
14+
#include "clang/AST/Stmt.h"
1315
#include "clang/AST/StmtVisitor.h"
1416
#include "clang/ASTMatchers/ASTMatchFinder.h"
17+
#include "clang/ASTMatchers/ASTMatchers.h"
1518
#include "clang/Basic/CharInfo.h"
1619
#include "clang/Basic/SourceLocation.h"
1720
#include "clang/Lex/Lexer.h"
@@ -760,21 +763,22 @@ class PointerInitGadget : public FixableGadget {
760763
/// \code
761764
/// p = q;
762765
/// \endcode
763-
class PointerAssignmentGadget : public FixableGadget {
766+
/// where both `p` and `q` are pointers.
767+
class PtrToPtrAssignmentGadget : public FixableGadget {
764768
private:
765769
static constexpr const char *const PointerAssignLHSTag = "ptrLHS";
766770
static constexpr const char *const PointerAssignRHSTag = "ptrRHS";
767771
const DeclRefExpr *PtrLHS; // the LHS pointer expression in `PA`
768772
const DeclRefExpr *PtrRHS; // the RHS pointer expression in `PA`
769773

770774
public:
771-
PointerAssignmentGadget(const MatchFinder::MatchResult &Result)
772-
: FixableGadget(Kind::PointerAssignment),
775+
PtrToPtrAssignmentGadget(const MatchFinder::MatchResult &Result)
776+
: FixableGadget(Kind::PtrToPtrAssignment),
773777
PtrLHS(Result.Nodes.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
774778
PtrRHS(Result.Nodes.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
775779

776780
static bool classof(const Gadget *G) {
777-
return G->getKind() == Kind::PointerAssignment;
781+
return G->getKind() == Kind::PtrToPtrAssignment;
778782
}
779783

780784
static Matcher matcher() {
@@ -809,6 +813,60 @@ class PointerAssignmentGadget : public FixableGadget {
809813
}
810814
};
811815

816+
/// An assignment expression of the form:
817+
/// \code
818+
/// ptr = array;
819+
/// \endcode
820+
/// where `p` is a pointer and `array` is a constant size array.
821+
class CArrayToPtrAssignmentGadget : public FixableGadget {
822+
private:
823+
static constexpr const char *const PointerAssignLHSTag = "ptrLHS";
824+
static constexpr const char *const PointerAssignRHSTag = "ptrRHS";
825+
const DeclRefExpr *PtrLHS; // the LHS pointer expression in `PA`
826+
const DeclRefExpr *PtrRHS; // the RHS pointer expression in `PA`
827+
828+
public:
829+
CArrayToPtrAssignmentGadget(const MatchFinder::MatchResult &Result)
830+
: FixableGadget(Kind::CArrayToPtrAssignment),
831+
PtrLHS(Result.Nodes.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
832+
PtrRHS(Result.Nodes.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
833+
834+
static bool classof(const Gadget *G) {
835+
return G->getKind() == Kind::CArrayToPtrAssignment;
836+
}
837+
838+
static Matcher matcher() {
839+
auto PtrAssignExpr = binaryOperator(
840+
allOf(hasOperatorName("="),
841+
hasRHS(ignoringParenImpCasts(
842+
declRefExpr(hasType(hasCanonicalType(constantArrayType())),
843+
toSupportedVariable())
844+
.bind(PointerAssignRHSTag))),
845+
hasLHS(declRefExpr(hasPointerType(), toSupportedVariable())
846+
.bind(PointerAssignLHSTag))));
847+
848+
return stmt(isInUnspecifiedUntypedContext(PtrAssignExpr));
849+
}
850+
851+
virtual std::optional<FixItList>
852+
getFixits(const FixitStrategy &S) const override;
853+
854+
virtual const Stmt *getBaseStmt() const override {
855+
// FIXME: This should be the binary operator, assuming that this method
856+
// makes sense at all on a FixableGadget.
857+
return PtrLHS;
858+
}
859+
860+
virtual DeclUseList getClaimedVarUseSites() const override {
861+
return DeclUseList{PtrLHS, PtrRHS};
862+
}
863+
864+
virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
865+
getStrategyImplications() const override {
866+
return {};
867+
}
868+
};
869+
812870
/// A call of a function or method that performs unchecked buffer operations
813871
/// over one of its pointer parameters.
814872
class UnsafeBufferUsageAttrGadget : public WarningGadget {
@@ -1428,7 +1486,7 @@ bool clang::internal::anyConflict(const SmallVectorImpl<FixItHint> &FixIts,
14281486
}
14291487

14301488
std::optional<FixItList>
1431-
PointerAssignmentGadget::getFixits(const FixitStrategy &S) const {
1489+
PtrToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
14321490
const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
14331491
const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
14341492
switch (S.lookup(LeftVD)) {
@@ -1447,6 +1505,42 @@ PointerAssignmentGadget::getFixits(const FixitStrategy &S) const {
14471505
return std::nullopt;
14481506
}
14491507

1508+
/// \returns fixit that adds .data() call after \DRE.
1509+
static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
1510+
const DeclRefExpr *DRE);
1511+
1512+
std::optional<FixItList>
1513+
CArrayToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
1514+
const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
1515+
const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
1516+
// TLDR: Implementing fixits for non-Wontfix strategy on both LHS and RHS is
1517+
// non-trivial.
1518+
//
1519+
// CArrayToPtrAssignmentGadget doesn't have strategy implications because
1520+
// constant size array propagates its bounds. Because of that LHS and RHS are
1521+
// addressed by two different fixits.
1522+
//
1523+
// At the same time FixitStrategy S doesn't reflect what group a fixit belongs
1524+
// to and can't be generally relied on in multi-variable Fixables!
1525+
//
1526+
// E. g. If an instance of this gadget is fixing variable on LHS then the
1527+
// variable on RHS is fixed by a different fixit and its strategy for LHS
1528+
// fixit is as if Wontfix.
1529+
//
1530+
// The only exception is Wontfix strategy for a given variable as that is
1531+
// valid for any fixit produced for the given input source code.
1532+
if (S.lookup(LeftVD) == FixitStrategy::Kind::Span) {
1533+
if (S.lookup(RightVD) == FixitStrategy::Kind::Wontfix) {
1534+
return FixItList{};
1535+
}
1536+
} else if (S.lookup(LeftVD) == FixitStrategy::Kind::Wontfix) {
1537+
if (S.lookup(RightVD) == FixitStrategy::Kind::Array) {
1538+
return createDataFixit(RightVD->getASTContext(), PtrRHS);
1539+
}
1540+
}
1541+
return std::nullopt;
1542+
}
1543+
14501544
std::optional<FixItList>
14511545
PointerInitGadget::getFixits(const FixitStrategy &S) const {
14521546
const auto *LeftVD = PtrInitLHS;
@@ -1864,6 +1958,19 @@ PointerDereferenceGadget::getFixits(const FixitStrategy &S) const {
18641958
return std::nullopt;
18651959
}
18661960

1961+
static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
1962+
const DeclRefExpr *DRE) {
1963+
const SourceManager &SM = Ctx.getSourceManager();
1964+
// Inserts the .data() after the DRE
1965+
std::optional<SourceLocation> EndOfOperand =
1966+
getPastLoc(DRE, SM, Ctx.getLangOpts());
1967+
1968+
if (EndOfOperand)
1969+
return FixItList{{FixItHint::CreateInsertion(*EndOfOperand, ".data()")}};
1970+
1971+
return std::nullopt;
1972+
}
1973+
18671974
// Generates fix-its replacing an expression of the form UPC(DRE) with
18681975
// `DRE.data()`
18691976
std::optional<FixItList>
@@ -1872,14 +1979,7 @@ UPCStandalonePointerGadget::getFixits(const FixitStrategy &S) const {
18721979
switch (S.lookup(VD)) {
18731980
case FixitStrategy::Kind::Array:
18741981
case FixitStrategy::Kind::Span: {
1875-
ASTContext &Ctx = VD->getASTContext();
1876-
SourceManager &SM = Ctx.getSourceManager();
1877-
// Inserts the .data() after the DRE
1878-
std::optional<SourceLocation> EndOfOperand =
1879-
getPastLoc(Node, SM, Ctx.getLangOpts());
1880-
1881-
if (EndOfOperand)
1882-
return FixItList{{FixItHint::CreateInsertion(*EndOfOperand, ".data()")}};
1982+
return createDataFixit(VD->getASTContext(), Node);
18831983
// FIXME: Points inside a macro expansion.
18841984
break;
18851985
}

clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ void unclaimed_use() {
5353
void implied_unclaimed_var(int *b) { // expected-warning{{'b' is an unsafe pointer used for buffer access}}
5454
int *a = new int[3]; // expected-warning{{'a' is an unsafe pointer used for buffer access}}
5555
a[4] = 7; // expected-note{{used in buffer access here}}
56-
a = b; // debug-note{{safe buffers debug: gadget 'PointerAssignment' refused to produce a fix}}
56+
a = b; // debug-note{{safe buffers debug: gadget 'PtrToPtrAssignment' refused to produce a fix}}
5757
b++; // expected-note{{used in pointer arithmetic here}} \
5858
// debug-note{{safe buffers debug: failed to produce fixit for 'b' : has an unclaimed use}}
5959
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage \
2+
// RUN: -fsafe-buffer-usage-suggestions \
3+
// RUN: -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
4+
5+
void safe_array_assigned_to_safe_ptr(unsigned idx) {
6+
int buffer[10];
7+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
8+
int* ptr;
9+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
10+
ptr = buffer;
11+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
12+
}
13+
14+
void safe_array_assigned_to_unsafe_ptr(unsigned idx) {
15+
int buffer[10];
16+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
17+
int* ptr;
18+
// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span<int> ptr"
19+
ptr = buffer;
20+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
21+
ptr[idx] = 0;
22+
}
23+
24+
void unsafe_array_assigned_to_safe_ptr(unsigned idx) {
25+
int buffer[10];
26+
// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:17}:"std::array<int, 10> buffer"
27+
int* ptr;
28+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
29+
ptr = buffer;
30+
// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:15}:".data()"
31+
buffer[idx] = 0;
32+
}
33+
34+
// FIXME: Implement fixit/s for this case.
35+
// See comment in CArrayToPtrAssignmentGadget::getFixits to learn why this hasn't been implemented.
36+
void unsafe_array_assigned_to_unsafe_ptr(unsigned idx) {
37+
int buffer[10];
38+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}
39+
int* ptr;
40+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}
41+
ptr = buffer;
42+
// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}
43+
buffer[idx] = 0;
44+
ptr[idx] = 0;
45+
}

0 commit comments

Comments
 (0)