Skip to content

Commit fe39a15

Browse files
shreya-jaingithub-actions[bot]
authored andcommitted
Automerge: [-Wunsafe-buffer-usage] Add unique_ptr <T[]> accesses (#156773)
Add operator[] accesses of `unique_ptr<T[]>` to `-Wunsafe-buffer-usage` as a subcategory under `-Wunsafe-buffer-usage-unique-ptr-array-access`. Also discussed in https://github.com/issues/assigned?issue=llvm%7Cllvm-project%7C73452
2 parents e88cf57 + 9aa94f6 commit fe39a15

File tree

7 files changed

+163
-3
lines changed

7 files changed

+163
-3
lines changed

clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H
1515
#define LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H
1616

17+
#include "clang/AST/ASTTypeTraits.h"
1718
#include "clang/AST/Decl.h"
1819
#include "clang/AST/Expr.h"
1920
#include "clang/AST/Stmt.h"
@@ -139,6 +140,12 @@ class UnsafeBufferUsageHandler {
139140
FixItList &&Fixes, const Decl *D,
140141
const FixitStrategy &VarTargetTypes) = 0;
141142

143+
// Invoked when an array subscript operator[] is used on a
144+
// std::unique_ptr<T[]>.
145+
virtual void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
146+
bool IsRelatedToDecl,
147+
ASTContext &Ctx) = 0;
148+
142149
#ifndef NDEBUG
143150
public:
144151
bool areDebugNotesRequested() {

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ WARNING_GADGET(PointerArithmetic)
3838
WARNING_GADGET(UnsafeBufferUsageAttr)
3939
WARNING_GADGET(UnsafeBufferUsageCtorAttr)
4040
WARNING_GADGET(DataInvocation)
41+
WARNING_GADGET(UniquePtrArrayAccess)
4142
WARNING_OPTIONAL_GADGET(UnsafeLibcFunctionCall)
4243
WARNING_OPTIONAL_GADGET(SpanTwoParamConstructor) // Uses of `std::span(arg0, arg1)`
4344
FIXABLE_GADGET(ULCArraySubscript) // `DRE[any]` in an Unspecified Lvalue Context

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1750,7 +1750,8 @@ def ReadOnlyPlacementChecks : DiagGroup<"read-only-types">;
17501750
// Warnings and fixes to support the "safe buffers" programming model.
17511751
def UnsafeBufferUsageInContainer : DiagGroup<"unsafe-buffer-usage-in-container">;
17521752
def UnsafeBufferUsageInLibcCall : DiagGroup<"unsafe-buffer-usage-in-libc-call">;
1753-
def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", [UnsafeBufferUsageInContainer, UnsafeBufferUsageInLibcCall]>;
1753+
def UnsafeBufferUsageInUniquePtrArrayAccess : DiagGroup<"unsafe-buffer-usage-in-unique-ptr-array-access">;
1754+
def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", [UnsafeBufferUsageInContainer, UnsafeBufferUsageInLibcCall, UnsafeBufferUsageInUniquePtrArrayAccess]>;
17541755

17551756
// Warnings and notes InstallAPI verification.
17561757
def InstallAPIViolation : DiagGroup<"installapi-violation">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13295,6 +13295,8 @@ def note_safe_buffer_usage_suggestions_disabled : Note<
1329513295
def warn_unsafe_buffer_usage_in_container : Warning<
1329613296
"the two-parameter std::span construction is unsafe as it can introduce mismatch between buffer size and the bound information">,
1329713297
InGroup<UnsafeBufferUsageInContainer>, DefaultIgnore;
13298+
def warn_unsafe_buffer_usage_unique_ptr_array_access : Warning<"direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking">,
13299+
InGroup<UnsafeBufferUsageInUniquePtrArrayAccess>, DefaultIgnore;
1329813300
#ifndef NDEBUG
1329913301
// Not a user-facing diagnostic. Useful for debugging false negatives in
1330013302
// -fsafe-buffer-usage-suggestions (i.e. lack of -Wunsafe-buffer-usage fixits).

clang/lib/Analysis/UnsafeBufferUsage.cpp

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include "clang/AST/Attr.h"
1414
#include "clang/AST/Decl.h"
1515
#include "clang/AST/DeclCXX.h"
16+
#include "clang/AST/DeclTemplate.h"
1617
#include "clang/AST/DynamicRecursiveASTVisitor.h"
1718
#include "clang/AST/Expr.h"
1819
#include "clang/AST/FormatString.h"
@@ -1318,6 +1319,97 @@ static bool isSupportedVariable(const DeclRefExpr &Node) {
13181319
return D != nullptr && isa<VarDecl>(D);
13191320
}
13201321

1322+
// Returns true for RecordDecl of type std::unique_ptr<T[]>
1323+
static bool isUniquePtrArray(const CXXRecordDecl *RecordDecl) {
1324+
if (!RecordDecl || !RecordDecl->isInStdNamespace() ||
1325+
RecordDecl->getNameAsString() != "unique_ptr")
1326+
return false;
1327+
1328+
const ClassTemplateSpecializationDecl *class_template_specialization_decl =
1329+
dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl);
1330+
if (!class_template_specialization_decl)
1331+
return false;
1332+
1333+
const TemplateArgumentList &template_args =
1334+
class_template_specialization_decl->getTemplateArgs();
1335+
if (template_args.size() == 0)
1336+
return false;
1337+
1338+
const TemplateArgument &first_arg = template_args[0];
1339+
if (first_arg.getKind() != TemplateArgument::Type)
1340+
return false;
1341+
1342+
QualType referred_type = first_arg.getAsType();
1343+
return referred_type->isArrayType();
1344+
}
1345+
1346+
class UniquePtrArrayAccessGadget : public WarningGadget {
1347+
private:
1348+
static constexpr const char *const AccessorTag = "unique_ptr_array_access";
1349+
const CXXOperatorCallExpr *AccessorExpr;
1350+
1351+
public:
1352+
UniquePtrArrayAccessGadget(const MatchResult &Result)
1353+
: WarningGadget(Kind::UniquePtrArrayAccess),
1354+
AccessorExpr(Result.getNodeAs<CXXOperatorCallExpr>(AccessorTag)) {
1355+
assert(AccessorExpr &&
1356+
"UniquePtrArrayAccessGadget requires a matched CXXOperatorCallExpr");
1357+
}
1358+
1359+
static bool classof(const Gadget *G) {
1360+
return G->getKind() == Kind::UniquePtrArrayAccess;
1361+
}
1362+
1363+
static bool matches(const Stmt *S, const ASTContext &Ctx,
1364+
MatchResult &Result) {
1365+
1366+
const CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(S);
1367+
if (!OpCall || OpCall->getOperator() != OO_Subscript)
1368+
return false;
1369+
1370+
const Expr *Callee = OpCall->getCallee()->IgnoreParenImpCasts();
1371+
if (!Callee)
1372+
return false;
1373+
1374+
const CXXMethodDecl *Method =
1375+
dyn_cast_or_null<CXXMethodDecl>(OpCall->getDirectCallee());
1376+
if (!Method)
1377+
return false;
1378+
1379+
if (Method->getOverloadedOperator() != OO_Subscript)
1380+
return false;
1381+
1382+
const CXXRecordDecl *RecordDecl = Method->getParent();
1383+
if (!isUniquePtrArray(RecordDecl))
1384+
return false;
1385+
1386+
const Expr *IndexExpr = OpCall->getArg(1);
1387+
clang::Expr::EvalResult Eval;
1388+
1389+
// Allow [0]
1390+
if (IndexExpr->EvaluateAsInt(Eval, Ctx) && Eval.Val.getInt().isZero())
1391+
return false;
1392+
1393+
Result.addNode(AccessorTag, DynTypedNode::create(*OpCall));
1394+
return true;
1395+
}
1396+
void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1397+
bool IsRelatedToDecl,
1398+
ASTContext &Ctx) const override {
1399+
Handler.handleUnsafeUniquePtrArrayAccess(
1400+
DynTypedNode::create(*AccessorExpr), IsRelatedToDecl, Ctx);
1401+
}
1402+
1403+
SourceLocation getSourceLoc() const override {
1404+
if (AccessorExpr)
1405+
return AccessorExpr->getOperatorLoc();
1406+
return SourceLocation();
1407+
}
1408+
1409+
DeclUseList getClaimedVarUseSites() const override { return {}; }
1410+
SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
1411+
};
1412+
13211413
using FixableGadgetList = std::vector<std::unique_ptr<FixableGadget>>;
13221414
using WarningGadgetList = std::vector<std::unique_ptr<WarningGadget>>;
13231415

@@ -2632,10 +2724,13 @@ std::set<const Expr *> clang::findUnsafePointers(const FunctionDecl *FD) {
26322724
const VariableGroupsManager &, FixItList &&,
26332725
const Decl *,
26342726
const FixitStrategy &) override {}
2635-
bool isSafeBufferOptOut(const SourceLocation &) const override {
2727+
void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
2728+
bool IsRelatedToDecl,
2729+
ASTContext &Ctx) override {}
2730+
bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
26362731
return false;
26372732
}
2638-
bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
2733+
bool isSafeBufferOptOut(const SourceLocation &) const override {
26392734
return false;
26402735
}
26412736
bool ignoreUnsafeBufferInLibcCall(const SourceLocation &) const override {

clang/lib/Sema/AnalysisBasedWarnings.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2605,6 +2605,17 @@ class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
26052605
#endif
26062606
}
26072607

2608+
void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
2609+
bool IsRelatedToDecl,
2610+
ASTContext &Ctx) override {
2611+
SourceLocation Loc;
2612+
std::string Message;
2613+
2614+
Loc = Node.get<Stmt>()->getBeginLoc();
2615+
S.Diag(Loc, diag::warn_unsafe_buffer_usage_unique_ptr_array_access)
2616+
<< Node.getSourceRange();
2617+
}
2618+
26082619
bool isSafeBufferOptOut(const SourceLocation &Loc) const override {
26092620
return S.PP.isSafeBufferOptOut(S.getSourceManager(), Loc);
26102621
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions -std=c++20 -verify=expected %s
2+
3+
namespace std {
4+
inline namespace __1 {
5+
template <class T> class unique_ptr {
6+
public:
7+
T &operator[](long long i) const;
8+
};
9+
} // namespace __1
10+
} // namespace std
11+
12+
int get_index() {
13+
return 4;
14+
}
15+
16+
void basic_unique_ptr() {
17+
std::unique_ptr<int[]> p1;
18+
int i = 2;
19+
const int j = 3;
20+
int k = 0;
21+
22+
p1[0]; // This is allowed
23+
24+
p1[k]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
25+
26+
p1[1]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
27+
28+
p1[1L]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
29+
30+
p1[1LL]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
31+
32+
p1[3 * 5]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
33+
34+
p1[i]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
35+
36+
p1[j]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
37+
38+
p1[i + 5]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
39+
40+
p1[get_index()]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
41+
42+
}
43+

0 commit comments

Comments
 (0)