374 Commits

Author SHA1 Message Date
jkorous-apple
644ac2a018
[-Wunsafe-buffer-usage] Introduce std::array fixits (#80084)
Array subscript on a const size array is not bounds-checked. The idiomatic
replacement is std::array which is bounds-safe in hardened mode of libc++.

This commit extends the fixit-producing machine to consider std::array as a
transformation target type and teaches it to handle the array subscript on const
size arrays with a trivial (empty) fixit.
2024-02-12 15:52:20 -08:00
Ziqing Luo
9816863dd4
[-Wunsafe-buffer-usage] Add a new warning for uses of std::span two-parameter constructors (#77148)
Constructing `std::span` objects with the two parameter constructors
could introduce mismatched bounds information, which defeats the
purpose of using `std::span`.  Therefore, we warn every use of such
constructors.

rdar://115817781
2024-01-26 15:43:46 -08:00
Kazu Hirata
73ff017c9b [Sema] Fix a warning
This patch fixes:

  clang/lib/Sema/AnalysisBasedWarnings.cpp:2269:21: error: unused
  variable 'subExpr' [-Werror,-Wunused-variable]
2024-01-22 11:17:21 -08:00
Malavika Samak
414df7051a
[-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (#78815)
The patch fixes the crash introduced by the DataInvocation warning
gadget designed to warn against unsafe invocations of span::data method.

It also now considers the invocation of span::data method inside
parenthesis.

Radar: 121223051

---------

Co-authored-by: MalavikaSamak <malavika2@apple.com>
2024-01-22 10:46:59 -08:00
Malavika Samak
7122f55c63
[-Wunsafe-buffer-usage] Warning for unsafe invocation of span::data (#75650)
…-Wunsafe-buffer-usage,

there maybe accidental re-introduction of new OutOfBound accesses into
the code bases. One such case is invoking span::data() method on a span
variable to retrieve a pointer, which is then cast to a larger type and
dereferenced. Such dereferences can introduce OutOfBound accesses.

To address this, a new WarningGadget is being introduced to warn against
such invocations.

---------

Co-authored-by: MalavikaSamak <malavika2@apple.com>
2024-01-02 15:41:00 -08:00
Clement Courbet
39427b1098
Reapply "[clang analysis][thread-safety] Handle return-by-reference..… (#68572)
…… (#68394)"

The new warnings are now under a separate flag
`-Wthread-safety-reference-return`, which is on by default under
`-Wthread-safety-reference`.

- People can opt out via `-Wthread-safety-reference
-Wnothread-safety-reference-return`.
This reverts commit 859f2d032386632562521a99db20923217d98988.
2023-10-19 08:34:59 +02:00
Caroline Tice
859f2d0323 Revert "Reapply "[clang analysis][thread-safety] Handle return-by-reference..… (#68394)"
This reverts commit cd184c866e0aad1f957910b8c7a94f98a2b21ceb.
2023-10-06 22:23:02 -07:00
Clement Courbet
cd184c866e
Reapply "[clang analysis][thread-safety] Handle return-by-reference..… (#68394)
…. (#67776)"

Now that `scudo` issues have been fixed (#68273).

This reverts commit 462bdd5bf0861a27f451f7917802a954e2046bc7.
2023-10-06 10:50:08 +02:00
Clement Courbet
00f2d9b0eb
Revert "[clang analysis][thread-safety] Handle return-by-reference...… (#67795)
… (#67776)"

This detects issues in `scudo`. Reverting until these are fixed.

```
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd.h:74:12: error: returning variable 'QuarantineCache' by reference requires holding mutex 'Mutex' exclusively [-Werror,-Wthread-safety-reference]
   74 |     return QuarantineCache;
      |            ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/combined.h:248:28: note: in instantiation of member function 'scudo::TSD<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::getQuarantineCache' requested here
  248 |     Quarantine.drain(&TSD->getQuarantineCache(),
      |                            ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd.h:57:15: note: in instantiation of member function 'scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>::commitBack' requested here
   57 |     Instance->commitBack(this);
      |               ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd_exclusive.h:172:27: note: in instantiation of member function 'scudo::TSD<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::commitBack' requested here
  172 |   TSDRegistryT::ThreadTSD.commitBack(Instance);
      |                           ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd_exclusive.h:33:46: note: in instantiation of function template specialization 'scudo::teardownThread<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>' requested here
   33 |     CHECK_EQ(pthread_key_create(&PThreadKey, teardownThread<Allocator>), 0);
      |                                              ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd_exclusive.h:42:5: note: in instantiation of member function 'scudo::TSDRegistryExT<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::init' requested here
   42 |     init(Instance); // Sets Initialized.
      |     ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd_exclusive.h:130:5: note: in instantiation of member function 'scudo::TSDRegistryExT<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::initOnceMaybe' requested here
  130 |     initOnceMaybe(Instance);
      |     ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/tsd_exclusive.h:74:5: note: in instantiation of member function 'scudo::TSDRegistryExT<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::initThread' requested here
   74 |     initThread(Instance, MinimalInit);
      |     ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/combined.h:221:17: note: in instantiation of member function 'scudo::TSDRegistryExT<scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>>::initThreadMaybe' requested here
  221 |     TSDRegistry.initThreadMaybe(this, MinimalInit);
      |                 ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/combined.h:790:5: note: in instantiation of member function 'scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>::initThreadMaybe' requested here
  790 |     initThreadMaybe();
      |     ^
/b/sanitizer-x86_64-linux-autoconf/build/llvm-project/compiler-rt/lib/scudo/standalone/wrappers_c.inc:36:25: note: in instantiation of member function 'scudo::Allocator<scudo::DefaultConfig, &malloc_postinit>::canReturnNull' requested here
   36 |     if (SCUDO_ALLOCATOR.canReturnNull()) {
```

This reverts commit 6dd96d6e80e9b3679a6161c590c60e0e99549b89.
2023-09-29 14:13:53 +02:00
Clement Courbet
6dd96d6e80
[clang analysis][thread-safety] Handle return-by-reference... (#67776)
...of guarded variables, when the function is not marked as requiring
locks:

```
class Return {
  Mutex mu;
  Foo foo GUARDED_BY(mu);

  Foo &returns_ref_locked() {
    MutexLock lock(&mu);
    return foo;  // BAD
  }

  Foo &returns_ref_locks_required() SHARED_LOCKS_REQUIRED(mu) {
    return foo;  // OK
  }
};
```

Review on Phabricator: https://reviews.llvm.org/D153131
2023-09-29 13:11:04 +02:00
Ziqing Luo
33f6161d9e [-Wunsafe-buffer-usage] Group parameter fix-its
For a function `F` whose parameters need to be fixed, we group fix-its
of F's parameters together so that either all of the parameters get
fixed or none of them gets fixed.

Reviewed by: NoQ (Artem Dergachev), t-rasmud (Rashmi Mudduluru), jkorous (Jan Korous)

Differential revision: https://reviews.llvm.org/D153059
2023-09-21 12:45:30 -07:00
ziqingluo-90
472a510bbc Re-land "[-Wunsafe-buffer-usage][NFC] Slightly refactor and optimize the code"
This reverts commit ac9a76d7487b9af1ace626eb90064194cb12c53d.

Previously an abstract class has no pure virtual function.  It causes build error on some bots.
2023-08-18 13:22:01 -07:00
Ziqing Luo
ac9a76d748 Revert "[-Wunsafe-buffer-usage][NFC] Slightly refactor and optimize the code"
This reverts commit 843784764ab58e35f8aa2da97f07dc5e810f4bcb.
There is a build failure caused by this commit.
2023-08-17 16:42:30 -07:00
Ziqing Luo
843784764a [-Wunsafe-buffer-usage][NFC] Slightly refactor and optimize the code
Slightly refactor and optimize the code in preparation for
implementing grouping parameters for a single fix-it.

Reviewed by: NoQ (Artem Dergachev), t-rasmud (Rashmi Mudduluru)

Differential revision: https://reviews.llvm.org/D156474
2023-08-17 16:24:47 -07:00
Takuya Shimizu
b3469ce6f8 [clang][Analysis] Handle && and || against variable and its negation as tautology
This patch introduces a new warning flag -Wtautological-negation-compare grouped in -Wtautological-compare that warns on the use of && or || operators against a variable and its negation.
e.g. x || !x and !x && x
This also makes the -Winfinite-recursion diagnose more cases.

Fixes https://github.com/llvm/llvm-project/issues/56035

Differential Revision: https://reviews.llvm.org/D152093
2023-08-17 17:55:48 +09:00
Aaron Ballman
0ce056a814 [C23] Rename C2x -> C23; NFC
This does the rename for most internal uses of C2x, but does not rename
or reword diagnostics (those will be done in a follow-up).

I also updated standards references and citations to the final wording
in the standard.
2023-08-11 07:43:43 -04:00
Rashmi Mudduluru
a6ae740e74 [-Wunsafe-buffer-usage] Add a facility for debugging low fixit coverage
Differential Revision: https://reviews.llvm.org/D154880
2023-07-26 17:07:36 -07:00
ziqingluo-90
a07a6f6c74 Re-land "5b012bf5ab5fcb840fe7f6c8664b8981ce6f24f3"
Removed dependency on `clangSema` from UnsafeBufferAnalysis.
2023-07-15 16:11:37 -07:00
NAKAMURA Takumi
c915908f6d Revert D150338, "[-Wunsafe-buffer-usage] Improving insertion of the [[clang::unsafe_buffer_usage]] attribute"
clangAnalysis should not depend on clangSema.

This reverts commit 5b012bf5ab5fcb840fe7f6c8664b8981ce6f24f3.
2023-07-15 13:55:11 +09:00
ziqingluo-90
5b012bf5ab [-Wunsafe-buffer-usage] Improving insertion of the [[clang::unsafe_buffer_usage]] attribute
For a fix-it that inserts the `[[clang::unsafe_buffer_usage]]`
attribute, it will lookup existing macros defined for the attribute
and use the (last defined such) macro directly. Fix-its will use raw
`[[clang::unsafe_buffer_usage]]` if no such macro is defined.

The implementation mimics how a similar machine for the
`[[fallthrough]]` attribute was implemented.

Reviewed by: NoQ (Artem Dergachev)

Differential revision: https://reviews.llvm.org/D150338
2023-07-14 14:47:07 -07:00
Nikolas Klauser
f6d557ee34 [clang][NFC] Remove trailing whitespaces and enforce it in lib, include and docs
A lot of editors remove trailing whitespaces. This patch removes any trailing whitespaces and makes sure that no new ones are added.

Reviewed By: erichkeane, paulkirth, #libc, philnik

Spies: wangpc, aheejin, MaskRay, pcwang-thead, cfe-commits, libcxx-commits, dschuff, nemanjai, arichardson, kbarton, asb, rbar, johnrusso, simoncook, sabuasal, niosHD, jrtc27, zzheng, edward-jones, rogfer01, MartinMosbeck, brucehoult, the_o, PkmX, jocewei, Jim, s.egerton, sameer.abuasal, apazos, luismarques, martong, frasercrmck, steakhal, luke

Differential Revision: https://reviews.llvm.org/D151963
2023-06-26 09:34:36 -07:00
Rashmi Mudduluru
171dfc5462 [-Wunsafe-buffer-usage] Group variables associated by pointer assignments
Differential Revision: https://reviews.llvm.org/D145739
2023-05-25 11:31:27 -07:00
Douglas Yung
2e6325c71f Revert "[-Wunsafe-buffer-usage] Group variables associated by pointer assignments"
This reverts commit ee6b08e99375fc48d1e5848704a66c2e8e57eb3b.

One of the added tests warn-unsafe-buffer-usage-multi-decl-warnings.cpp does
not seem to be deterministic, and seems to be especially problematic on Windows.

Failures of this one test on llvm-clang-x86_64-sie-win:
- https://lab.llvm.org/buildbot/#/builders/216/builds/21758
- https://lab.llvm.org/buildbot/#/builders/216/builds/21761
- https://lab.llvm.org/buildbot/#/builders/216/builds/21762
- https://lab.llvm.org/buildbot/#/builders/216/builds/21765
- https://lab.llvm.org/buildbot/#/builders/216/builds/21770
- https://lab.llvm.org/buildbot/#/builders/216/builds/21771
- https://lab.llvm.org/buildbot/#/builders/216/builds/21773
- https://lab.llvm.org/buildbot/#/builders/216/builds/21776
- https://lab.llvm.org/buildbot/#/builders/216/builds/21777
- https://lab.llvm.org/buildbot/#/builders/216/builds/21778
- https://lab.llvm.org/buildbot/#/builders/216/builds/21779

Other random bot failures:
- https://lab.llvm.org/buildbot/#/builders/65/builds/9821
- https://lab.llvm.org/buildbot/#/builders/65/builds/9822
- https://lab.llvm.org/buildbot/#/builders/65/builds/9824
- https://lab.llvm.org/buildbot/#/builders/119/builds/13440
- https://lab.llvm.org/buildbot/#/builders/119/builds/13442
- https://lab.llvm.org/buildbot/#/builders/119/builds/13444
- https://lab.llvm.org/buildbot/#/builders/119/builds/13445
- https://lab.llvm.org/buildbot/#/builders/60/builds/12156
- https://lab.llvm.org/buildbot/#/builders/60/builds/12157
- https://lab.llvm.org/buildbot/#/builders/60/builds/12160
2023-05-25 02:10:32 -07:00
Rashmi Mudduluru
ee6b08e993 [-Wunsafe-buffer-usage] Group variables associated by pointer assignments
Differential Revision: https://reviews.llvm.org/D145739
2023-05-24 16:20:55 -07:00
Artem Dergachev
b7bdf1996f [-Wunsafe-buffer-usage] Hide fixits/suggestions behind an extra flag.
This patch implements a new clang driver flag -fsafe-buffer-usage-suggestions
which allows turning the smart suggestion machine on and off (defaults to off).
This is valuable for stability reasons, as the machine is being rapidly improved\
and we don't want accidental breakages to ruin the build for innocent users.
It is also arguably useful in general because it enables separation of concerns
between project contributors: some users will actively update the code to
conform to the programming model, while others simply want to make sure that
they aren't regressing it. Finally, there could be other valid reasons to
opt out of suggestions entirely on some codebases (while continuing to enforce
-Wunsafe-buffer-usage warnings), such as lack of access to hardened libc++
(or even to the C++ standard library in general) on the target platform.

When the flag is disabled, the unsafe buffer usage analysis is reduced to
an extremely minimal mode of operation that contains virtually no smarts:
not only it doesn't offer automatic fixits, but also textual suggestions
such as "change the type of this variable to std::span to preserve bounds
information" are not displayed, and in fact the machine doesn't even try
to blame specific variables in the first place, it simply warns on
the operations and leaves everything else to the user. So this flag turns off
a lot more of our complex machinery than what we already turn off in presence
of say -fno-diagnostic-fixit-info.

The flag is discoverable: when it's off, the warnings are accompanied by a note:
telling the user that there's a flag they can use.

Differential Revision: https://reviews.llvm.org/D146669
2023-05-18 17:20:27 -07:00
ziqingluo-90
86c7e33b3f Re-land "[-Wunsafe-buffer-usage] Remove an unnecessary const-qualifier"
Re-land 7a0900fd3e2d34bc1d513a97cf8fbdc1754252d7, which includes too
much clang-format changes.  This re-land gets rid of the format changes.
2023-05-15 12:10:13 -07:00
ziqingluo-90
f39fd750ab Revert "[-Wunsafe-buffer-usage] Remove an unnecessary const-qualifier"
This reverts commit 7a0900fd3e2d34bc1d513a97cf8fbdc1754252d7.

The commit includes too much clang-format changes.
2023-05-15 11:47:00 -07:00
ziqingluo-90
7a0900fd3e [-Wunsafe-buffer-usage] Remove an unnecessary const-qualifier
A follow-up change for 6d861d498de1320d22771c329ec69f9419ef06b7:
remove an unnecessary const-qualifier so that the code doesn't have to
remove the qualifier explicitly using `std::remove_const_t`, which
triggers a warning at some bots (e.g.,
https://lab.llvm.org/buildbot/#/builders/247/builds/4442).
2023-05-12 14:46:56 -07:00
ziqingluo-90
6d861d498d [-Wunsafe-buffer-usage] Move the whole analysis to the end of a translation unit
The unsafe-buffer analysis requires a complete view of the translation
unit (TU) to be conservative. So the analysis is moved to the end of a
TU.

A summary of changes made: add a new `IssueWarnings` function in
`AnalysisBasedWarnings.cpp` for TU-based analyses. So far
[-Wunsafe-buffer-usage] is the only analysis using it but there could
be more.  `Sema` will call the new `IssueWarnings` function at the end
of parsing a TU.

Reviewed by: NoQ (Artem Dergachev)

Differential revision: https://reviews.llvm.org/D146342
2023-05-12 11:50:51 -07:00
Takuya Shimizu
de401ac2a4 [clang][Sema] Avoid duplicate diagnostics for unreachable fallthrough attribute
This patch checks whether -Wunreachable-code-fallthrough is enabled
when clang encounters unreachable fallthrough attributes and, if so,
suppresses code will never be executed warning to avoid duplicate
warnings.

Fixes https://github.com/llvm/llvm-project/issues/60416
Differential Revision: https://reviews.llvm.org/D145842
2023-03-14 08:43:35 -04:00
Deniz Evrenci
f332498f98 [Clang] Do not emit exception diagnostics from coroutines and coroutine lambdas
All exceptions thrown in coroutine bodies are caught and
unhandled_exception member of the coroutine promise type is called.
In accordance with the existing rules of diagnostics related to
exceptions thrown in functions marked noexcept, even if the promise
type's constructor, get_return_object, or unhandled_exception
throws, diagnostics should not be emitted.

Fixes #48797.

Differential Revision: https://reviews.llvm.org/D144352
2023-02-28 11:41:07 +01:00
Ziqing Luo
f78c343466 [-Wunsafe-buffer-usage] Create Fix-Its only if they are emitted
`-Wunsafe-buffer-usage` diagnostics shall not emit fix-its if fix-its
are globally disabled.

Commit on behalf of jkorous (Jan Korous)

Reviewed by: NoQ (Artem Dergachev)

Differential revision: https://reviews.llvm.org/D143697
2023-02-23 14:47:43 -08:00
Jan Korous
8b6ae9bd74 [-Wunsafe-buffer-usage] Emit Fix-Its only for C++20 and later standards
The transformation strategy we are bringing up heavily relies on std::span which was introduced as part of C++20.

Differential Revision: https://reviews.llvm.org/D143455
2023-02-09 17:28:27 -08:00
Ziqing Luo
829bcb06ec [-Wunsafe-buffer-usage] Add unsafe buffer checking opt-out pragmas
Add a pair of clang pragmas:
- `#pragma clang unsafe_buffer_usage begin` and
- `#pragma clang unsafe_buffer_usage end`,
which specify the start and end of an (unsafe buffer checking) opt-out
region, respectively.

Behaviors of opt-out regions conform to the following rules:

- No nested nor overlapped opt-out regions are allowed. One cannot
  start an opt-out region with `... unsafe_buffer_usage begin` but never
  close it with `... unsafe_buffer_usage end`. Mis-use of the pragmas
  will be warned.
- Warnings raised from unsafe buffer operations inside such an opt-out
  region will always be suppressed. This behavior CANNOT be changed by
  `clang diagnostic` pragmas or command-line flags.
- Warnings raised from unsafe operations outside of such opt-out
  regions may be reported on declarations inside opt-out
  regions. These warnings are NOT suppressed.
- An un-suppressed unsafe operation warning may be attached with
  notes. These notes are NOT suppressed as well regardless of whether
  they are in opt-out regions.

The implementation maintains a separate sequence of location pairs
representing opt-out regions in `Preprocessor`.  The `UnsafeBufferUsage`
analyzer reads the region sequence to check if an unsafe operation is
in an opt-out region. If it is, discard the warning raised from the
operation immediately.

This is a re-land after I reverting it at 9aa00c8a306561c4e3ddb09058e66bae322a0769.
The compilation error should be resolved.

Reviewed by: NoQ

Differential revision: https://reviews.llvm.org/D140179
2023-02-08 14:12:03 -08:00
Ziqing Luo
9aa00c8a30 Revert "[-Wunsafe-buffer-usage] Add unsafe buffer checking opt-out pragmas"
This reverts commit aef05b5dc5c566bcaa15b66c989ccb8d2841ac71.
It causes a buildbot failure: https://lab.llvm.org/buildbot/#/builders/216/builds/16879/steps/6/logs/stdio
2023-02-07 17:06:20 -08:00
Ziqing Luo
aef05b5dc5 [-Wunsafe-buffer-usage] Add unsafe buffer checking opt-out pragmas
Add a pair of clang pragmas:
- `#pragma clang unsafe_buffer_usage begin` and
- `#pragma clang unsafe_buffer_usage end`,
which specify the start and end of an (unsafe buffer checking) opt-out
region, respectively.

Behaviors of opt-out regions conform to the following rules:

- No nested nor overlapped opt-out regions are allowed. One cannot
  start an opt-out region with `... unsafe_buffer_usage begin` but never
  close it with `... unsafe_buffer_usage end`. Mis-use of the pragmas
  will be warned.
- Warnings raised from unsafe buffer operations inside such an opt-out
  region will always be suppressed. This behavior CANNOT be changed by
  `clang diagnostic` pragmas or command-line flags.
- Warnings raised from unsafe operations outside of such opt-out
  regions may be reported on declarations inside opt-out
  regions. These warnings are NOT suppressed.
- An un-suppressed unsafe operation warning may be attached with
  notes. These notes are NOT suppressed as well regardless of whether
  they are in opt-out regions.

The implementation maintains a separate sequence of location pairs
representing opt-out regions in `Preprocessor`.  The `UnsafeBufferUsage`
analyzer reads the region sequence to check if an unsafe operation is
in an opt-out region. If it is, discard the warning raised from the
operation immediately.

Reviewed by: NoQ

Differential revision: https://reviews.llvm.org/D140179
2023-02-07 16:54:39 -08:00
Ziqing Luo
bdf4f2bea5 [-Wunsafe-buffer-usage] Generate fix-it for local variable declarations
Use clang fix-its to transform declarations of local variables, which
are used for buffer access , to be of std::span type.

We placed a few limitations to keep the solution simple:
- it only transforms local variable declarations (no parameter declaration);
- it only considers single level pointers, i.e., pointers of type T * regardless of whether T is again a pointer;
- it only transforms to std::span types (no std::array, or std::span::iterator, or ...);
    - it can only transform a VarDecl that belongs to a DeclStmt whose has a single child.

One of the purposes of keeping this patch simple enough is to first
evaluate if fix-it is an appropriate approach to do the
transformation.

This commit was reverted by 622be09c815266632e204eaf1c7a35f050220459
for a compilation warning and now it is fixed.

Reviewed by: NoQ, jkorous

Differential revision: https://reviews.llvm.org/D139737
2023-02-07 15:40:19 -08:00
Ziqing Luo
622be09c81 Revert "[-Wunsafe-buffer-usage] Generate fix-it for local variable declarations"
This reverts commit a29e67614c3b7018287e5f68c57bba7618aa880e.
2023-02-07 14:47:43 -08:00
Ziqing Luo
a29e67614c [-Wunsafe-buffer-usage] Generate fix-it for local variable declarations
Use clang fix-its to transform declarations of local variables, which are used for buffer access , to be of std::span type.

We placed a few limitations to keep the solution simple:
- it only transforms local variable declarations (no parameter declaration);
- it only considers single level pointers, i.e., pointers of type T * regardless of whether T is again a pointer;
- it only transforms to std::span types (no std::array, or std::span::iterator, or ...);
- it can only transform a VarDecl that belongs to a DeclStmt whose has a single child.

One of the purposes of keeping this patch simple enough is to first
evaluate if fix-it is an appropriate approach to do the
transformation.

Reviewed by: NoQ, jkorous

Differential revision: https://reviews.llvm.org/D139737
2023-02-07 13:17:44 -08:00
Mariya Podchishchaeva
8681797e59 [NFC][clang] Fix static analyzer concern about uninitialized variable
Reviewed By: xazax.hun

Differential Revision: https://reviews.llvm.org/D143411
2023-02-07 04:40:44 -05:00
Mikael Holmen
0e2400ae02 [clang] Fix warning about unused variable [NFC]
gcc warned about
 ../../clang/lib/Sema/AnalysisBasedWarnings.cpp:2187:23: warning: unused variable 'FC' [-Wunused-variable]
  2187 |       if (const auto *FC = dyn_cast<CallExpr>(Operation)) {
       |                       ^~
2023-02-02 08:02:11 +01:00
Rashmi Mudduluru
acc3cc69e4 [-Wunsafe-buffer-usage] Introduce the unsafe_buffer_usage attribute
Differential Revision: https://reviews.llvm.org/D138940
2023-01-31 11:43:34 -08:00
Jan Korous
237ca436ad [-Wunsafe-buffer-usage] Group diagnostics by variable
Differential Revision: https://reviews.llvm.org/D141356
2023-01-18 15:00:22 -08:00
Jan Korous
39a63fc7fe [-Wunsafe-buffer-usage] Use relevant source locations for warnings
This way we highlight a particular unsafe subexpression by providing more accurate
source location than begin of an entire statement.

Differential Revision: https://reviews.llvm.org/D141340
2023-01-18 14:18:54 -08:00
Kazu Hirata
6ad0788c33 [clang] Use std::optional instead of llvm::Optional (NFC)
This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to remove #include "llvm/ADT/Optional.h".

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14 12:31:01 -08:00
Kazu Hirata
a1580d7b59 [clang] Add #include <optional> (NFC)
This patch adds #include <optional> to those files containing
llvm::Optional<...> or Optional<...>.

I'll post a separate patch to actually replace llvm::Optional with
std::optional.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14 11:07:21 -08:00
Benjamin Kramer
b6942a2880 [NFC] Hide implementation details in anonymous namespaces 2023-01-08 17:37:02 +01:00
Artem Dergachev
8086323a91 [-Wunsafe-buffer-usage] NFC: Implement fix-strategies and variable-use-claiming.
This patch adds more abstractions that we'll need later for emitting
-Wunsafe-buffer-usage fixits. It doesn't emit any actual fixits,
so no change is observed behavior, but it introduces a way to emit fixits,
and existing tests now verify that the compiler still emits no fixits,
despite knowing how to do so.

The purpose of our code transformation analysis is to fix variable types
in the code from raw pointer types to C++ standard collection/view types.

The analysis has to decide on its own which specific type is
the most appropriate for every variable. This patch introduces
the Strategy class that maps variables to their most appropriate types.

In D137348 we've introduced the Gadget abstraction, which describes
a rigid AST pattern that the analysis "fully understands" and may need
to fix. Which specific fix is actually necessary for a given Gadget,
and whether it's necessary at all, and whether it's possible in the first place,
depends on the Strategy. So, this patch adds a virtual method which every
gadget can implement in order to teach the analysis how to fix that gadget:

  Gadget->getFixits(Strategy)

However, even if the analysis knows how to fix every Gadget, doesn't
necessarily mean it can fix the variable. Some uses of the variable may have
never been covered by Gadgets, which corresponds to the situation that
the analysis doesn't fully understand how the variable is used. This patch
introduces a Tracker class that tracks all variable uses (i.e. DeclRefExprs)
in the function. Additionally, each Gadget now provides a new virtual method

  Gadget->getClaimedVarUseSites()

that the Tracker can call to see which DeclRefExprs are "claimed" by the Gadget.
In order to fix the variable with a certain Strategy, the Tracker needs to
confirm that there are no unclaimed uses, and every Gadget has to provide
a fix for that Strategy.

This "conservative" behavior guarantees that fixes emitted by our analysis
are correct by construction. We can now be sure that the analysis won't
attempt to emit a fix if it doesn't understand the code. Later, as we implement
more getFixits() methods in individual Gadget classes, we'll start
progressively emitting more and more fixits.

Differential Revision: https://reviews.llvm.org/D138253
2022-12-16 18:48:29 -08:00
Artem Dergachev
3b7af2796b Revert "Revert "[-Wunsafe-buffer-usage] Initial commit - Transition away from raw buffers.""
This reverts commit bc0617795f8bdcd5deab3e48b120107cc2833cdc.

Be more careful with #includes to avoid linker errors on some buildbots.
2022-12-08 16:57:59 -08:00
Artem Dergachev
bc0617795f Revert "[-Wunsafe-buffer-usage] Initial commit - Transition away from raw buffers."
This reverts commit 200007ec85f81122fd260a4e68308e54607ca37a.
2022-12-05 15:38:52 -08:00