https://github.com/yuhaouy updated https://github.com/llvm/llvm-project/pull/240553
>From 10cedeaeca45042d10680311cf8f8d10285f74be Mon Sep 17 00:00:00 2001 From: Yu Hao <[email protected]> Date: Fri, 23 Oct 2026 01:31:07 +0000 Subject: [PATCH 1/3] 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 <[email protected]> Date: Tue, 10 Nov 2026 20:37:29 +0000 Subject: [PATCH 2/3] 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 <[email protected]> Date: Mon, 9 Nov 2026 19:23:05 +0000 Subject: [PATCH 3/3] 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 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
