https://github.com/yuhaouy updated https://github.com/llvm/llvm-project/pull/240558
>From 8a550c0d5d72c3f9accdb95e43374bf869e4819f Mon Sep 17 00:00:00 2001 From: Yu Hao <[email protected]> Date: Wed, 18 Nov 2026 01:04:07 +0000 Subject: [PATCH 1/2] Add sub-flag -Wunsafe-buffer-usage-in-data-call to control 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 0601ffcec82fdb..553f05e9e2e688 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -854,6 +854,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 4d50ecb82747e9..b9b2e9d1e2851b 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -2039,7 +2039,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 dff45a081f2e8c..c6140c7c5ec35e 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -14112,7 +14112,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; @@ -14169,6 +14169,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 151167aa461d5e..856004e7767968 100644 --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -2580,16 +2580,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(); @@ -2759,6 +2749,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); } @@ -2784,6 +2787,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. @@ -3094,6 +3101,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 a2eb13c418c66e688761af569d399fa258979934 Mon Sep 17 00:00:00 2001 From: Yu Hao <[email protected]> Date: Mon, 9 Nov 2026 19:33:33 +0000 Subject: [PATCH 2/2] 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 553f05e9e2e688..fd65a1957643fe 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -489,6 +489,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: @@ -859,6 +864,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 b9896de61df54e..ca7dfd6432c399 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 9828968c9d0f41..930c6cea80be42 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -8487,6 +8487,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 0392c5067a1184..1f68ea0da0ac15 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 +} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
