[clang] [clang][-Wunsafe-buffer-usage] Introduce `[[clang::unsafe_buffer_usage_in_data_call]]` attribute (PR #240558)
Yu Hao via cfe-commits
cfe-commits at lists.llvm.org
Tue Nov 10 12:48:58 PST 2026
https://github.com/yuhaouy updated https://github.com/llvm/llvm-project/pull/240558
>From 10cedeaeca45042d10680311cf8f8d10285f74be Mon Sep 17 00:00:00 2001
From: Yu Hao <yuhaoyu at google.com>
Date: Fri, 23 Oct 2026 01:31:07 +0000
Subject: [PATCH 1/4] move data call's cast check to DataInvocationGadget
---
clang/lib/Analysis/UnsafeBufferUsage.cpp | 51 +++++++++++++++++-------
clang/lib/Sema/AnalysisBasedWarnings.cpp | 25 ------------
2 files changed, 36 insertions(+), 40 deletions(-)
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 09f610358ca65e..ac551cca376c72 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2404,21 +2404,16 @@ class DataInvocationGadget : public WarningGadget {
auto *CE = dyn_cast<ExplicitCastExpr>(S);
if (!CE)
return false;
- for (auto *Child : CE->children()) {
- if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Child);
- MCE && isDataFunction(MCE)) {
- Result.addNode(OpTag, DynTypedNode::create(*CE));
- return true;
- }
- if (auto *Paren = dyn_cast<ParenExpr>(Child)) {
- if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Paren->getSubExpr());
- MCE && isDataFunction(MCE)) {
- Result.addNode(OpTag, DynTypedNode::create(*CE));
- return true;
- }
- }
- }
- return false;
+ const Expr *Operand = CE->getSubExpr();
+ if (auto *Paren = dyn_cast<ParenExpr>(Operand))
+ Operand = Paren->getSubExpr();
+ auto *MCE = dyn_cast<CXXMemberCallExpr>(Operand);
+ if (!MCE || !isDataFunction(MCE))
+ return false;
+ if (!isUnsafeCast(CE, Ctx))
+ return false;
+ Result.addNode(OpTag, DynTypedNode::create(*CE));
+ return true;
}
void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
@@ -2446,6 +2441,32 @@ class DataInvocationGadget : public WarningGadget {
return false;
}
+ // Returns true if `CE` casts the pointer returned by `data()` to a pointer to
+ // a larger type, or if the size of either pointee type cannot be determined.
+ static bool isUnsafeCast(const ExplicitCastExpr *CE, const ASTContext &Ctx) {
+ QualType DestType = CE->getType();
+ if (!isa<PointerType>(DestType))
+ return false;
+ QualType DestPointeeType = DestType->getPointeeType();
+
+ // If destination type is incomplete or dependent, it is unsafe to cast
+ // to anyway, no need to check its type:
+ if (DestPointeeType->isIncompleteType() ||
+ DestPointeeType->isDependentType())
+ return true;
+
+ QualType SrcType = CE->getSubExpr()->getType();
+ if (!SrcType->isPointerType())
+ return false;
+ QualType SrcPointeeType = SrcType->getPointeeType();
+
+ // Check if source type is incomplete or dependent as well:
+ if (SrcPointeeType->isIncompleteType() || SrcPointeeType->isDependentType())
+ return true;
+
+ return Ctx.getTypeSize(SrcPointeeType) < Ctx.getTypeSize(DestPointeeType);
+ }
+
SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
};
diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index 21af6ed5527ffc..b1a4ed90c95166 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2528,31 +2528,6 @@ class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
D = ME->getMemberDecl();
MsgParam = 5;
} else if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Operation)) {
- QualType destType = ECE->getType();
-
- if (!isa<PointerType>(destType))
- return;
- destType = destType.getTypePtr()->getPointeeType();
-
- // If destination type is incomplete or dependent, it is unsafe to cast
- // to anyway, no need to check its type:
- if (!destType->isIncompleteType() && !destType->isDependentType()) {
- const uint64_t dSize = Ctx.getTypeSize(destType);
- QualType srcType = ECE->getSubExpr()->getType();
-
- assert(srcType->isPointerType());
-
- QualType srcPointeeType = srcType.getTypePtr()->getPointeeType();
-
- // Check if source type is incomplete or dependent as well:
- if (!srcPointeeType->isIncompleteType() &&
- !srcPointeeType->isDependentType()) {
- const uint64_t sSize = Ctx.getTypeSize(srcPointeeType);
-
- if (sSize >= dSize)
- return;
- }
- }
if (const auto *CE = dyn_cast<CXXMemberCallExpr>(
ECE->getSubExpr()->IgnoreParens())) {
D = CE->getMethodDecl();
>From 2f118645353408fb231954f42a5c25693f2cd8ef Mon Sep 17 00:00:00 2001
From: Yu Hao <yuhaoyu at google.com>
Date: Tue, 10 Nov 2026 20:37:29 +0000
Subject: [PATCH 2/4] rename isUnsafeCast to isUnsafePointerCast
---
clang/lib/Analysis/UnsafeBufferUsage.cpp | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 95bcc9ab43bfd7..1eb20c7d88f687 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2411,7 +2411,7 @@ class DataInvocationGadget : public WarningGadget {
auto *MCE = dyn_cast<CXXMemberCallExpr>(Operand);
if (!MCE || !isDataFunction(MCE))
return false;
- if (!isUnsafeCast(CE, Ctx))
+ if (!isUnsafePointerCast(CE, Ctx))
return false;
Result.addNode(OpTag, DynTypedNode::create(*CE));
return true;
@@ -2444,7 +2444,8 @@ class DataInvocationGadget : public WarningGadget {
// Returns true if `CE` casts the pointer returned by `data()` to a pointer to
// a larger type, or if the size of either pointee type cannot be determined.
- static bool isUnsafeCast(const ExplicitCastExpr *CE, const ASTContext &Ctx) {
+ static bool isUnsafePointerCast(const ExplicitCastExpr *CE,
+ const ASTContext &Ctx) {
QualType DestType = CE->getType();
if (!isa<PointerType>(DestType))
return false;
>From f7d52b35d9e08ffa846565af5bd46feda576d4f3 Mon Sep 17 00:00:00 2001
From: Yu Hao <yuhaoyu at google.com>
Date: Mon, 9 Nov 2026 19:23:05 +0000
Subject: [PATCH 3/4] Add sub-flag -Wunsafe-buffer-usage-in-data-call for
unsafe invocation of data warnings
---
clang/docs/ReleaseNotes.md | 5 ++++
.../Analysis/Analyses/UnsafeBufferUsage.h | 10 +++++++
.../Analyses/UnsafeBufferUsageGadgets.def | 2 +-
clang/include/clang/Basic/DiagnosticGroups.td | 3 +-
.../clang/Basic/DiagnosticSemaKinds.td | 5 +++-
clang/lib/Analysis/UnsafeBufferUsage.cpp | 17 ++++++++++-
clang/lib/Sema/AnalysisBasedWarnings.cpp | 28 ++++++++++++-------
...e-buffer-usage-warning-data-invocation.cpp | 27 ++++++++++++++++--
8 files changed, 81 insertions(+), 16 deletions(-)
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 88546d7c95d5dd..0b3ed305df1e9d 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -808,6 +808,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
`-Wno-unsafe-buffer-usage-in-libc-call-string-examination` silences `strlen`
while `memcpy` is still diagnosed. (#GH127849)
+- Added `-Wunsafe-buffer-usage-in-data-call` as a diagnostic group under
+ `-Wunsafe-buffer-usage` to control warnings on unsafe casts of pointers
+ returned by container `data()` calls, which were previously diagnosed directly
+ under `-Wunsafe-buffer-usage`.
+
- Fixed the `no-` prefix being dropped when diagnosing an unknown
`-Wno-error=` or `-Wno-fatal-errors=` warning option. Clang now preserves
the no- prefix in the diagnostic and spelling suggestion.
diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
index f9fb731e489ed4..4775bc3b34bad7 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
@@ -167,6 +167,11 @@ class UnsafeBufferUsageHandler {
bool IsRelatedToDecl,
ASTContext &Ctx) = 0;
+ /// Invoked when an unsafe cast of a pointer returned by a container's data()
+ /// method is found.
+ virtual void handleUnsafeDataCall(const ExplicitCastExpr *Cast,
+ ASTContext &Ctx) = 0;
+
#ifndef NDEBUG
public:
bool areDebugNotesRequested() {
@@ -210,6 +215,11 @@ class UnsafeBufferUsageHandler {
virtual bool
ignoreUnsafeBufferInStaticSizedArray(const SourceLocation &Loc) const = 0;
+ /// \return true iff unsafe casts on container data() calls should NOT be
+ /// reported at `Loc`; false otherwise.
+ virtual bool
+ ignoreUnsafeBufferInDataCall(const SourceLocation &Loc) const = 0;
+
virtual std::string
getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc,
StringRef WSSuffix = "") const = 0;
diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
index 7e4d5772ee8685..692718a8285e00 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
@@ -36,7 +36,7 @@ WARNING_GADGET(Decrement)
WARNING_OPTIONAL_GADGET(PointerArithmetic)
WARNING_GADGET(UnsafeBufferUsageAttr)
WARNING_GADGET(UnsafeBufferUsageCtorAttr)
-WARNING_GADGET(DataInvocation)
+WARNING_OPTIONAL_GADGET(DataInvocation)
WARNING_GADGET(UniquePtrArrayAccess)
WARNING_OPTIONAL_GADGET(ArraySubscript)
WARNING_OPTIONAL_GADGET(UnsafeLibcFunctionCall)
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index eb5a1280bf41ef..2c875e4eb5ce3b 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -2038,7 +2038,8 @@ def UnsafeBufferUsageInStaticSizedArray : DiagGroup<"unsafe-buffer-usage-in-stat
def UnsafeBufferUsageInFormatAttrCall : DiagGroup<"unsafe-buffer-usage-in-format-attr-call">;
def UnsafeBufferUsageInStringView : DiagGroup<"unsafe-buffer-usage-in-string-view">;
def UnsafeBufferUsageMainArgv : DiagGroup<"unsafe-buffer-usage-main-argv">;
-def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", [UnsafeBufferUsageInContainer, UnsafeBufferUsageInLibcCall, UnsafeBufferUsageInUniquePtrArrayAccess, UnsafeBufferUsageInStaticSizedArray, UnsafeBufferUsageInFormatAttrCall, UnsafeBufferUsageInStringView, UnsafeBufferUsageMainArgv]>;
+def UnsafeBufferUsageInDataCall : DiagGroup<"unsafe-buffer-usage-in-data-call">;
+def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", [UnsafeBufferUsageInContainer, UnsafeBufferUsageInLibcCall, UnsafeBufferUsageInUniquePtrArrayAccess, UnsafeBufferUsageInStaticSizedArray, UnsafeBufferUsageInFormatAttrCall, UnsafeBufferUsageInStringView, UnsafeBufferUsageMainArgv, UnsafeBufferUsageInDataCall]>;
// Warnings and notes InstallAPI verification.
def InstallAPIViolation : DiagGroup<"installapi-violation">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3e56980e22902b..2df0237a28399f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -14087,7 +14087,7 @@ defvar UnsafeBufferVariableMsg =
defvar UnsafeBufferOperationMsg =
"%select{unsafe pointer operation|unsafe pointer arithmetic|"
"unsafe buffer access|function introduces unsafe buffer manipulation|"
- "unsafe invocation of %1|field %1 prone to unsafe buffer manipulation}0";
+ "field %1 prone to unsafe buffer manipulation}0";
defvar UnsafeBufferLibcCallMsg = "function %0 is unsafe";
def warn_unsafe_buffer_variable : Warning<UnsafeBufferVariableMsg>,
InGroup<UnsafeBufferUsage>, DefaultIgnore;
@@ -14144,6 +14144,9 @@ def warn_unsafe_buffer_usage_unique_ptr_array_access : Warning<"direct access us
InGroup<UnsafeBufferUsageInUniquePtrArrayAccess>, DefaultIgnore;
def warn_unsafe_buffer_usage_in_static_sized_array : Warning<"direct access on T[N] is unsafe due to the lack of bounds checking">,
InGroup<UnsafeBufferUsageInStaticSizedArray>, DefaultIgnore;
+def warn_unsafe_buffer_usage_in_data_call : Warning<
+ "unsafe invocation of %0">,
+ InGroup<UnsafeBufferUsageInDataCall>, DefaultIgnore;
#ifndef NDEBUG
// Not a user-facing diagnostic. Useful for debugging false negatives in
// -fsafe-buffer-usage-suggestions (i.e. lack of -Wunsafe-buffer-usage fixits).
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 1eb20c7d88f687..5f7e946d26b24e 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -293,6 +293,12 @@ ignoreUnsafeBufferInContainer(const Stmt &Node,
return Handler->ignoreUnsafeBufferInContainer(Node.getBeginLoc());
}
+static bool
+ignoreUnsafeBufferInDataCall(const Stmt &Node,
+ const UnsafeBufferUsageHandler *Handler) {
+ return Handler->ignoreUnsafeBufferInDataCall(Node.getBeginLoc());
+}
+
static bool ignoreUnsafeLibcCall(const ASTContext &Ctx, const Stmt &Node,
const UnsafeBufferUsageHandler *Handler) {
if (Ctx.getLangOpts().CPlusPlus)
@@ -2401,10 +2407,13 @@ class DataInvocationGadget : public WarningGadget {
}
static bool matches(const Stmt *S, const ASTContext &Ctx,
+ const UnsafeBufferUsageHandler *Handler,
MatchResult &Result) {
auto *CE = dyn_cast<ExplicitCastExpr>(S);
if (!CE)
return false;
+ if (ignoreUnsafeBufferInDataCall(*S, Handler))
+ return false;
const Expr *Operand = CE->getSubExpr();
if (auto *Paren = dyn_cast<ParenExpr>(Operand))
Operand = Paren->getSubExpr();
@@ -2420,7 +2429,7 @@ class DataInvocationGadget : public WarningGadget {
void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
bool IsRelatedToDecl,
ASTContext &Ctx) const override {
- Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
+ Handler.handleUnsafeDataCall(Op, Ctx);
}
SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
@@ -5047,6 +5056,8 @@ bool clang::matchUnsafePointers(const DynTypedNode &N, ASTContext &Ctx,
void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
bool IsRelatedToDecl,
ASTContext &Ctx) override {}
+ void handleUnsafeDataCall(const ExplicitCastExpr *Cast,
+ ASTContext &Ctx) override {}
bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
return false;
}
@@ -5064,6 +5075,10 @@ bool clang::matchUnsafePointers(const DynTypedNode &N, ASTContext &Ctx,
const SourceLocation &Loc) const override {
return false;
}
+ bool
+ ignoreUnsafeBufferInDataCall(const SourceLocation &Loc) const override {
+ return false;
+ }
std::string getUnsafeBufferUsageAttributeTextAt(
SourceLocation, StringRef WSSuffix = "") const override {
return "";
diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index 638323e9c15052..6b353169244658 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2570,16 +2570,6 @@ class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
assert(!IsRelatedToDecl && "Not implemented yet!");
auto *ME = cast<MemberExpr>(Operation);
D = ME->getMemberDecl();
- MsgParam = 5;
- } else if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Operation)) {
- if (const auto *CE = dyn_cast<CXXMemberCallExpr>(
- ECE->getSubExpr()->IgnoreParens())) {
- D = CE->getMethodDecl();
- }
-
- if (!D)
- return;
-
MsgParam = 4;
}
Loc = Operation->getBeginLoc();
@@ -2749,6 +2739,19 @@ class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
<< Node.getSourceRange();
}
+ void handleUnsafeDataCall(const ExplicitCastExpr *Cast,
+ ASTContext &Ctx) override {
+ const auto *CE =
+ dyn_cast<CXXMemberCallExpr>(Cast->getSubExpr()->IgnoreParens());
+ if (!CE)
+ return;
+ const CXXMethodDecl *D = CE->getMethodDecl();
+ if (!D)
+ return;
+ S.Diag(Cast->getBeginLoc(), diag::warn_unsafe_buffer_usage_in_data_call)
+ << D << Cast->getSourceRange();
+ }
+
bool isSafeBufferOptOut(const SourceLocation &Loc) const override {
return S.PP.isSafeBufferOptOut(S.getSourceManager(), Loc);
}
@@ -2774,6 +2777,10 @@ class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
diag::warn_unsafe_buffer_usage_in_static_sized_array, Loc);
}
+ bool ignoreUnsafeBufferInDataCall(const SourceLocation &Loc) const override {
+ return S.Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_data_call, Loc);
+ }
+
// Returns the text representation of clang::unsafe_buffer_usage attribute.
// `WSSuffix` holds customized "white-space"s, e.g., newline or whilespace
// characters.
@@ -3084,6 +3091,7 @@ static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
return !Diags.isIgnored(diag::warn_unsafe_buffer_operation, Loc) ||
!Diags.isIgnored(diag::warn_unsafe_buffer_variable, Loc) ||
!Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_container, Loc) ||
+ !Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_data_call, Loc) ||
(S.getLangOpts().CPlusPlus &&
(llvm::any_of(
UnsafeLibcCallDiagIDs,
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
index 107611d461d9da..65a6e56c7dd1b6 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++20 -Wno-all -Wunsafe-buffer-usage -Wno-unsafe-buffer-usage-in-container\
+// RUN: %clang_cc1 -std=c++20 -Wno-all -Wunsafe-buffer-usage-in-data-call \
// RUN: -fsafe-buffer-usage-suggestions \
// RUN: -fblocks -include %s -verify %s
@@ -6,6 +6,7 @@
// RUN: %clang_cc1 -std=c++11 -fblocks -include %s %s 2>&1 | FileCheck --allow-empty %s
// RUN: %clang_cc1 -std=c++20 -fblocks -include %s %s 2>&1 | FileCheck --allow-empty %s
// CHECK-NOT: [-Wunsafe-buffer-usage]
+// CHECK-NOT: [-Wunsafe-buffer-usage-in-data-call]
#ifndef INCLUDED
#define INCLUDED
@@ -39,7 +40,7 @@ namespace std{
public:
constexpr span<T> subspan(size_t offset, size_t count) const {
- return span<T> (elements+offset, count); // expected-warning{{unsafe pointer arithmetic}}
+ return span<T> (elements+offset, count);
}
constexpr T* data() const noexcept {
@@ -218,4 +219,26 @@ void test_complete_type(std::span<long> S) {
union CompleteUnion {};
}
+namespace test_flag {
+int *get_ptr();
+void f(std::span<int> span_ptr) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // turns off every unsafe-buffer warning
+ A *a1 = (A *)span_ptr.data(); // no-warning
+ get_ptr()[5]; // no-warning
+#pragma clang diagnostic pop
+
+#pragma clang diagnostic push
+#pragma clang diagnostic warning "-Wunsafe-buffer-usage"
+ // Parent flag enables `-Wunsafe-buffer-usage-in-data-call`:
+ A *a2 = (A *)span_ptr.data(); // expected-warning{{unsafe invocation of 'data'}}
+
+#pragma clang diagnostic ignored "-Wunsafe-buffer-usage-in-data-call"
+ // Turn on all unsafe-buffer warnings except `-Wunsafe-buffer-usage-in-data-call`:
+ A *a3 = (A *)span_ptr.data(); // no-warning
+ get_ptr()[5]; // expected-warning{{unsafe buffer access}}
+#pragma clang diagnostic pop
+}
+} // namespace test_flag
+
#endif
>From 02e606bd05feb76daf847298d465ec41d6f13229 Mon Sep 17 00:00:00 2001
From: Yu Hao <yuhaoyu at google.com>
Date: Mon, 9 Nov 2026 19:33:33 +0000
Subject: [PATCH 4/4] Add [[clang::unsafe_buffer_usage_in_data_call]] attribute
---
clang/docs/ReleaseNotes.md | 10 +++++
clang/include/clang/Basic/Attr.td | 3 +-
clang/include/clang/Basic/AttrDocs.td | 29 +++++++++++++++
clang/lib/Analysis/UnsafeBufferUsage.cpp | 11 ++++--
clang/lib/Sema/SemaDeclAttr.cpp | 10 ++++-
.../test/SemaCXX/attr-unsafe-buffer-usage.cpp | 11 ++++++
...fe-buffer-usage-in-data-call-annotated.cpp | 37 +++++++++++++++++++
7 files changed, 104 insertions(+), 7 deletions(-)
create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-in-data-call-annotated.cpp
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 0b3ed305df1e9d..6daf7c116183fd 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -449,6 +449,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
and view constructors and factory functions to opt in to
`-Wunsafe-buffer-usage-in-container` diagnostics.
+- Added `[[clang::unsafe_buffer_usage_in_data_call]]` (and equivalent spelling
+ `[[clang::unsafe_buffer_usage("data")]]`) to allow custom container and view
+ data accessor methods to opt in to `-Wunsafe-buffer-usage-in-data-call`
+ diagnostics.
+
- The thread safety attribute `lock_returned` (`RETURN_CAPABILITY`) can now be
applied to function pointers, like the other thread safety function
attributes:
@@ -813,6 +818,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
returned by container `data()` calls, which were previously diagnosed directly
under `-Wunsafe-buffer-usage`.
+- `-Wunsafe-buffer-usage-in-data-call` now warns on unsafe casts of pointers
+ returned by methods annotated with
+ `[[clang::unsafe_buffer_usage_in_data_call]]` or
+ `[[clang::unsafe_buffer_usage("data")]]`.
+
- Fixed the `no-` prefix being dropped when diagnosing an unknown
`-Wno-error=` or `-Wno-fatal-errors=` warning option. Clang now preserves
the no- prefix in the diagnostic and spelling suggestion.
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 24fd853a2384af..a2bfd7e0e13128 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -5107,7 +5107,8 @@ def ReleaseHandle : InheritableParamAttr {
def UnsafeBufferUsage : InheritableAttr {
let Spellings = [Clang<"unsafe_buffer_usage">,
- Clang<"unsafe_buffer_usage_in_container">];
+ Clang<"unsafe_buffer_usage_in_container">,
+ Clang<"unsafe_buffer_usage_in_data_call">];
let Args = [StringArgument<"Category", 1>];
let Subjects = SubjectList<[Function, Field]>;
let Documentation = [UnsafeBufferUsageDocs];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 2300c8456ef164..95d8bce5387035 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8471,6 +8471,35 @@ alternatives, though the attribute can be used even when the fix can't be automa
}
```
+- Attribute attached to container data accessor methods: The spellings
+ `[[clang::unsafe_buffer_usage_in_data_call]]` and
+ `[[clang::unsafe_buffer_usage("data")]]` are equivalent and can be placed on
+ methods of container or view types that return a pointer to the underlying
+ buffer (such as `data()` on custom span types) to opt them in to
+ `-Wunsafe-buffer-usage-in-data-call`.
+
+ Unlike the general `[[clang::unsafe_buffer_usage]]` attribute, which warns on
+ every call, this form only warns when the returned pointer is explicitly cast
+ to a pointer to a larger, incomplete, or dependent type, matching the built-in
+ check for `std::span::data`:
+
+ ```c++
+ template <typename T>
+ class CustomSpan {
+ public:
+ [[clang::unsafe_buffer_usage_in_data_call]]
+ constexpr T *data() const noexcept;
+ };
+
+ struct Large { int a, b; };
+
+ void example(CustomSpan<int> s) {
+ int *p = s.data(); // no warning
+ char *bytes = (char *)s.data(); // no warning: cast to smaller type
+ Large *l = (Large *)s.data(); // warning: unsafe invocation of 'data'
+ }
+ ```
+
}];
}
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 5f7e946d26b24e..fdcda3b34fdccd 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2389,7 +2389,9 @@ class UnsafeBufferUsageCtorAttrGadget : public WarningGadget {
SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
};
-// Warning gadget for unsafe invocation of span::data method.
+// Warning gadget for unsafe invocation of container or view data() methods
+// (including methods annotated with [[clang::unsafe_buffer_usage_in_data_call]]
+// or [[clang::unsafe_buffer_usage("data")]]).
// Triggers when the pointer returned by the invocation is immediately
// cast to a larger type.
@@ -2414,9 +2416,7 @@ class DataInvocationGadget : public WarningGadget {
return false;
if (ignoreUnsafeBufferInDataCall(*S, Handler))
return false;
- const Expr *Operand = CE->getSubExpr();
- if (auto *Paren = dyn_cast<ParenExpr>(Operand))
- Operand = Paren->getSubExpr();
+ const Expr *Operand = CE->getSubExpr()->IgnoreParens();
auto *MCE = dyn_cast<CXXMemberCallExpr>(Operand);
if (!MCE || !isDataFunction(MCE))
return false;
@@ -2443,6 +2443,9 @@ class DataInvocationGadget : public WarningGadget {
if (!callee || !isa<CXXMethodDecl>(callee))
return false;
auto *method = cast<CXXMethodDecl>(callee);
+ if (const auto *Attr = method->getAttr<UnsafeBufferUsageAttr>();
+ Attr && Attr->getCategory() == "data")
+ return true;
if (method->getNameAsString() == "data" &&
method->getParent()->isInStdNamespace() &&
llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index e57f1de9c11007..5a8be9d47fcb43 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -7268,15 +7268,21 @@ static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
StringRef Category;
- if (AL.getAttrName()->getName() == "unsafe_buffer_usage_in_container") {
+ StringRef AttrName = AL.getAttrName()->getName();
+ normalizeName(AttrName);
+ if (AttrName == "unsafe_buffer_usage_in_container") {
if (!AL.checkExactlyNumArgs(S, 0))
return;
Category = "container";
+ } else if (AttrName == "unsafe_buffer_usage_in_data_call") {
+ if (!AL.checkExactlyNumArgs(S, 0))
+ return;
+ Category = "data";
} else if (AL.getNumArgs() != 0) {
SourceLocation Loc;
if (!S.checkStringLiteralArgumentAttr(AL, 0, Category, &Loc))
return;
- if (Category != "container") {
+ if (Category != "container" && Category != "data") {
S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << Category;
return;
}
diff --git a/clang/test/SemaCXX/attr-unsafe-buffer-usage.cpp b/clang/test/SemaCXX/attr-unsafe-buffer-usage.cpp
index cab67784d90756..e08956c5999e38 100644
--- a/clang/test/SemaCXX/attr-unsafe-buffer-usage.cpp
+++ b/clang/test/SemaCXX/attr-unsafe-buffer-usage.cpp
@@ -4,3 +4,14 @@
[[clang::unsafe_buffer_usage]]
void f(int *buf, int size);
void g(int *buffer [[clang::unsafe_buffer_usage("buffer")]], int size); // expected-warning {{'clang::unsafe_buffer_usage' attribute only applies to functions}}
+
+struct DataHolder {
+ [[clang::unsafe_buffer_usage_in_data_call]]
+ int *data();
+ [[clang::unsafe_buffer_usage("data")]]
+ int *data_str();
+ [[clang::unsafe_buffer_usage_in_data_call("data")]] // expected-error {{'clang::unsafe_buffer_usage_in_data_call' attribute takes no arguments}}
+ int *data_err();
+ [[clang::unsafe_buffer_usage("invalid")]] // expected-warning {{'clang::unsafe_buffer_usage' attribute argument not supported: invalid}}
+ int *invalid_category();
+};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-data-call-annotated.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-data-call-annotated.cpp
new file mode 100644
index 00000000000000..5caf0b01922540
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-data-call-annotated.cpp
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -std=c++20 -Wno-all -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions -verify %s
+
+template <typename T>
+class CustomSpan {
+ T *ptr_;
+
+public:
+ [[clang::unsafe_buffer_usage_in_data_call]]
+ constexpr T *data() const noexcept { return ptr_; }
+
+ [[clang::unsafe_buffer_usage("data")]]
+ constexpr const T *raw_bytes() const noexcept { return ptr_; }
+
+ __attribute__((__unsafe_buffer_usage_in_data_call__))
+ constexpr T *gnu_data() const noexcept { return ptr_; }
+
+ constexpr T *unannotated_data() const noexcept { return ptr_; }
+};
+
+struct Large {
+ int a, b, c;
+};
+
+void test_annotated_methods(CustomSpan<int> s, CustomSpan<int> *sp) {
+ // Unsafe casts on [[clang::unsafe_buffer_usage_in_data_call]]:
+ Large *l1 = (Large *)s.data(); // expected-warning{{unsafe invocation of 'data'}}
+ l1 = (Large *)sp->data(); // expected-warning{{unsafe invocation of 'data'}}
+
+ // Unsafe casts on [[clang::unsafe_buffer_usage("data")]]:
+ const Large *l2 = (const Large *)s.raw_bytes(); // expected-warning{{unsafe invocation of 'raw_bytes'}}
+
+ // Unsafe casts on GNU spelling with double underscores:
+ Large *l3 = (Large *)s.gnu_data(); // expected-warning{{unsafe invocation of 'gnu_data'}}
+
+ // Unannotated methods do not warn:
+ Large *l4 = (Large *)s.unannotated_data(); // no-warning
+}
More information about the cfe-commits
mailing list