aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Sema/AnalysisBasedWarnings.cpp
AgeCommit message (Collapse)AuthorFilesLines
10 hoursReapply "[LifetimeSafety] Reorganize code into modular components (#162474)"Utkarsh Saxena1-1/+1
This reverts commit 24a5d8a9cae9b766351d2f500a190471aa23cb13. Add link libs to the new clang library
37 hoursRevert "[LifetimeSafety] Reorganize code into modular components (#162474)"Shilei Tian1-1/+1
This reverts commit 2eb8c47b88e83cf310b86480b5b8d0f45a1f91af since it completely breaks dylib build.
41 hours[LifetimeSafety] Reorganize code into modular components (#162474)Utkarsh Saxena1-1/+1
Restructure the C++ Lifetime Safety Analysis into modular components with clear separation of concerns. This PR reorganizes the C++ Lifetime Safety Analysis code by: 1. Breaking up the monolithic `LifetimeSafety.cpp` (1500+ lines) into multiple smaller, focused files 2. Creating a dedicated `LifetimeSafety` directory with a clean component structure 3. Introducing header files for each component with proper documentation 4. Moving existing code into the appropriate component files: - `Checker.h/cpp`: Core lifetime checking logic - `Dataflow.h`: Generic dataflow analysis framework - `Facts.h`: Lifetime-relevant events and fact management - `FactsGenerator.h/cpp`: AST traversal for fact generation - `LiveOrigins.h/cpp`: Backward dataflow analysis for origin liveness - `LoanPropagation.h/cpp`: Forward dataflow analysis for loan tracking - `Loans.h`: Loan and access path definitions - `Origins.h`: Origin management - `Reporter.h`: Interface for reporting lifetime violations - `Utils.h`: Common utilities for the analysis The code functionality remains the same, but is now better organized with clearer interfaces between components.
3 days[-Wunsafe-buffer-usage] Add unique_ptr <T[]> accesses (#156773)shreya-jain1-0/+11
Add operator[] accesses of `unique_ptr<T[]>` to `-Wunsafe-buffer-usage` as a subcategory under `-Wunsafe-buffer-usage-unique-ptr-array-access`. Also discussed in https://github.com/issues/assigned?issue=llvm%7Cllvm-project%7C73452
13 days[clang][NFC] Remove const_casts from diagnostic emissions (#161211)Timm Baeder1-4/+3
This is apparently not necessary anymore. Not sure when exactly it changed though.
2025-09-03[LifetimeSafety] Fix duplicate loan generation for ImplicitCastExpr (#153661)Utkarsh Saxena1-4/+4
This PR fixes a bug in the lifetime safety analysis where `ImplicitCastExpr` nodes were causing duplicate loan generation. The changes: 1. Remove the recursive `Visit(ICE->getSubExpr())` call in `VisitImplicitCastExpr` to prevent duplicate processing of the same expression 2. Ensure the CFG build options are properly configured for lifetime safety analysis by moving the flag check earlier 3. Enhance the unit test infrastructure to properly handle multiple loans per variable 4. Add a test case that verifies implicit casts to const don't create duplicate loans 5. Add a test case for ternary operators with a FIXME note about origin propagation These changes prevent the analysis from generating duplicate loans when expressions are wrapped in implicit casts, which improves the accuracy of the lifetime safety analysis.
2025-08-27[clang] NFC: reintroduce clang/include/clang/AST/Type.h (#155050)Matheus Izvekov1-1/+1
This reintroduces `Type.h`, having earlier been renamed to `TypeBase.h`, as a redirection to `TypeBase.h`, and redirects most users to include the former instead. This is a preparatory patch for being able to provide inline definitions for `Type` methods which would otherwise cause a circular dependency with `Decl{,CXX}.h`. Doing these operations into their own NFC patch helps the git rename detection logic work, preserving the history. This patch makes clang just a little slower to build (~0.17%), just because it makes more code indirectly include `DeclCXX.h`.
2025-08-27[clang] NFC: rename clang/include/clang/AST/Type.h to TypeBase.h (#155049)Matheus Izvekov1-1/+1
This is a preparatory patch, to be able to provide inline definitions for `Type` functions which depend on `Decl{,CXX}.h`. As the latter also depends on `Type.h`, this would not be possible without some reorganizing. Splitting this rename into its own patch allows git to track this as a rename, and preserve all git history, and not force any code reformatting. A later NFC patch will reintroduce `Type.h` as redirection to `TypeBase.h`, rewriting most places back to directly including `Type.h` instead of `TypeBase.h`, leaving only a handful of places where this is necessary. Then yet a later patch will exploit this by making more stuff inline.
2025-08-18[LifetimeSafety] Implement a basic use-after-free diagnostic (#149731)Utkarsh Saxena1-2/+29
Implement use-after-free detection in the lifetime safety analysis with two warning levels. - Added a `LifetimeSafetyReporter` interface for reporting lifetime safety issues - Created two warning levels: - Definite errors (reported with `-Wexperimental-lifetime-safety-permissive`) - Potential errors (reported with `-Wexperimental-lifetime-safety-strict`) - Implemented a `LifetimeChecker` class that analyzes loan propagation and expired loans to detect use-after-free issues. - Added tracking of use sites through a new `UseFact` class. - Enhanced the `ExpireFact` to track the expressions where objects are destroyed. - Added test cases for both definite and potential use-after-free scenarios. The implementation now tracks pointer uses and can determine when a pointer is dereferenced after its loan has been expired, with appropriate diagnostics. The two warning levels provide flexibility - definite errors for high-confidence issues and potential errors for cases that depend on control flow.
2025-08-09[clang] Improve nested name specifier AST representation (#147835)Matheus Izvekov1-7/+4
This is a major change on how we represent nested name qualifications in the AST. * The nested name specifier itself and how it's stored is changed. The prefixes for types are handled within the type hierarchy, which makes canonicalization for them super cheap, no memory allocation required. Also translating a type into nested name specifier form becomes a no-op. An identifier is stored as a DependentNameType. The nested name specifier gains a lightweight handle class, to be used instead of passing around pointers, which is similar to what is implemented for TemplateName. There is still one free bit available, and this handle can be used within a PointerUnion and PointerIntPair, which should keep bit-packing aficionados happy. * The ElaboratedType node is removed, all type nodes in which it could previously apply to can now store the elaborated keyword and name qualifier, tail allocating when present. * TagTypes can now point to the exact declaration found when producing these, as opposed to the previous situation of there only existing one TagType per entity. This increases the amount of type sugar retained, and can have several applications, for example in tracking module ownership, and other tools which care about source file origins, such as IWYU. These TagTypes are lazily allocated, in order to limit the increase in AST size. This patch offers a great performance benefit. It greatly improves compilation time for [stdexec](https://github.com/NVIDIA/stdexec). For one datapoint, for `test_on2.cpp` in that project, which is the slowest compiling test, this patch improves `-c` compilation time by about 7.2%, with the `-fsyntax-only` improvement being at ~12%. This has great results on compile-time-tracker as well: ![image](https://github.com/user-attachments/assets/700dce98-2cab-4aa8-97d1-b038c0bee831) This patch also further enables other optimziations in the future, and will reduce the performance impact of template specialization resugaring when that lands. It has some other miscelaneous drive-by fixes. About the review: Yes the patch is huge, sorry about that. Part of the reason is that I started by the nested name specifier part, before the ElaboratedType part, but that had a huge performance downside, as ElaboratedType is a big performance hog. I didn't have the steam to go back and change the patch after the fact. There is also a lot of internal API changes, and it made sense to remove ElaboratedType in one go, versus removing it from one type at a time, as that would present much more churn to the users. Also, the nested name specifier having a different API avoids missing changes related to how prefixes work now, which could make existing code compile but not work. How to review: The important changes are all in `clang/include/clang/AST` and `clang/lib/AST`, with also important changes in `clang/lib/Sema/TreeTransform.h`. The rest and bulk of the changes are mostly consequences of the changes in API. PS: TagType::getDecl is renamed to `getOriginalDecl` in this patch, just for easier to rebasing. I plan to rename it back after this lands. Fixes #136624 Fixes https://github.com/llvm/llvm-project/issues/43179 Fixes https://github.com/llvm/llvm-project/issues/68670 Fixes https://github.com/llvm/llvm-project/issues/92757
2025-08-03[Sema] Use llvm::iterator_range::empty (NFC) (#151852)Kazu Hirata1-1/+1
2025-07-30[Analysis] Prevent revisiting block when searching for noreturn vars (#150582)Serge Pavlov1-0/+4
When searching for noreturn variable initializations, do not visit CFG blocks that are already visited, it prevents hanging the analysis. It must fix https://github.com/llvm/llvm-project/issues/150336.
2025-07-22[LifetimeSafety] Add language option for experimental lifetime safety (#149592)Utkarsh Saxena1-2/+1
Add a language option flag for experimental lifetime safety analysis in C++. This change provides a language option to control the experimental lifetime safety analysis feature, making it more explicit and easier to enable/disable. Previously, the feature was controlled indirectly through a diagnostic warning flag, which we do not want to accidentally enable with `-Weverything` (atm)! ### Changes: - Added a new language option `EnableLifetimeSafety` in `LangOptions.def` for experimental lifetime safety analysis in C++ - Added corresponding driver options `-fexperimental-lifetime-safety` and `-fno-experimental-lifetime-safety` in `Options.td` - Modified `AnalysisBasedWarnings.cpp` to use the new language option flag instead of checking if a specific diagnostic is ignored - Updated a test case to use the new flag instead of relying on the warning flag alone
2025-07-22Reapply "[LifetimeSafety] Revamp test suite using unittests (#149158)"Utkarsh Saxena1-2/+2
This reverts commit 54b50681ca0fd1c0c6ddb059c88981a45e2f1b19.
2025-07-22Revert "[LifetimeSafety] Revamp test suite using unittests (#149158)"Utkarsh Saxena1-2/+2
This reverts commit 688ea048affe8e79221ea1a8c376bcf20ef8f3bb.
2025-07-22[LifetimeSafety] Revamp test suite using unittests (#149158)Utkarsh Saxena1-2/+2
Refactor the Lifetime Safety Analysis infrastructure to support unit testing. - Created a public API class `LifetimeSafetyAnalysis` that encapsulates the analysis functionality - Added support for test points via a special `TestPointFact` that can be used to mark specific program points - Added unit tests that verify loan propagation in various code patterns
2025-07-17[Sema] Use llvm::all_of (NFC) (#149256)Kazu Hirata1-2/+1
We can pass a range to llvm::all_of.
2025-07-16Thread Safety Analysis: Fix pointer handling of variables with deprecated ↵Marco Elver1-5/+20
attributes (#148974) de10e44b6fe7 ("Thread Safety Analysis: Support warning on passing/returning pointers to guarded variables") added checks for passing pointer to guarded variables. While new features do not necessarily need to support the deprecated attributes (`guarded_var`, and `pt_guarded_var`), we need to ensure that such features do not cause the compiler to crash. As such, code such as this: struct { int v __attribute__((guarded_var)); } p; int *g() { return &p.v; // handleNoMutexHeld() with POK_ReturnPointer } Would crash in debug builds with the assertion in handleNoMutexHeld() triggering. The assertion is meant to capture the fact that this helper should only be used for warnings on variables (which the deprecated attributes only applied to). To fix, the function handleNoMutexHeld() should handle all POK cases that apply to variables explicitly, and produce a best-effort warning. We refrain from introducing new warnings to avoid unnecessary code bloat for deprecated features. Fixes: https://github.com/llvm/llvm-project/issues/140330
2025-07-15[Analysis] Avoid some warnings about exit from noreturn function (#144408)Serge Pavlov1-0/+150
Compiler sometimes issues warnings on exit from 'noreturn' functions, in the code like: [[noreturn]] extern void nonreturnable(); void (*func_ptr)(); [[noreturn]] void foo() { func_ptr = nonreturnable; (*func_ptr)(); } where exit cannot take place because the function pointer is actually a pointer to noreturn function. This change introduces small data analysis that can remove some of the warnings in the cases when compiler can prove that the set of reaching definitions consists of noreturn functions only.
2025-07-14[clang] Add -Wuninitialized-const-pointer (#148337)Igor Kudrin1-4/+16
This option is similar to -Wuninitialized-const-reference, but diagnoses the passing of an uninitialized value via a const pointer, like in the following code: ``` void foo(const int *); void test() { int v; foo(&v); } ``` This is an extract from #147221 as suggested in [this comment](https://github.com/llvm/llvm-project/pull/147221#discussion_r2190998730).
2025-07-14[clang] Fix suppressing diagnostics for uninitialized variables (#148336)Igor Kudrin1-40/+48
When one kind of diagnostics is disabled, this should not preclude other diagnostics from displaying, even if they have lower priority. For example, this should print a warning about passing an uninitialized variable as a const reference: ``` > cat test.cpp void foo(const int &); int f(bool a) { int v; if (a) { foo(v); v = 5; } return v; } > clang test.cpp -fsyntax-only -Wuninitialized -Wno-sometimes-uninitialized ```
2025-07-10[clang] Combine ConstRefUse with other warnings for uninitialized values ↵Igor Kudrin1-41/+13
(#147898) This helps to avoid duplicating warnings in cases like: ``` > cat test.cpp void bar(int); void foo(const int &); void test(bool a) { int v = v; if (a) bar(v); else foo(v); } > clang++.exe test.cpp -fsyntax-only -Wuninitialized test.cpp:4:11: warning: variable 'v' is uninitialized when used within its own initialization [-Wuninitialized] 4 | int v = v; | ~ ^ test.cpp:4:11: warning: variable 'v' is uninitialized when used within its own initialization [-Wuninitialized] 4 | int v = v; | ~ ^ 2 warnings generated. ```
2025-07-10[LifetimeSafety] Introduce intra-procedural analysis in Clang (#142313)Utkarsh Saxena1-0/+10
This patch introduces the initial implementation of the intra-procedural, flow-sensitive lifetime analysis for Clang, as proposed in the recent RFC: https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291 The primary goal of this initial submission is to establish the core dataflow framework and gather feedback on the overall design, fact representation, and testing strategy. The focus is on the dataflow mechanism itself rather than exhaustively covering all C++ AST edge cases, which will be addressed in subsequent patches. #### Key Components * **Conceptual Model:** Introduces the fundamental concepts of `Loan`, `Origin`, and `Path` to model memory borrows and the lifetime of pointers. * **Fact Generation:** A frontend pass traverses the Clang CFG to generate a representation of lifetime-relevant events, such as pointer assignments, taking an address, and variables going out of scope. * **Testing:** `llvm-lit` tests validate the analysis by checking the generated facts. ### Next Steps *(Not covered in this PR but planned for subsequent patches)* The following functionality is planned for the upcoming patches to build upon this foundation and make the analysis usable in practice: * **Dataflow Lattice:** A dataflow lattice used to map each pointer's symbolic `Origin` to the set of `Loans` it may contain at any given program point. * **Fixed-Point Analysis:** A worklist-based, flow-sensitive analysis that propagates the lattice state across the CFG to a fixed point. * **Placeholder Loans:** Introduce placeholder loans to represent the lifetimes of function parameters, forming the basis for analysis involving function calls. * **Annotation and Opaque Call Handling:** Use placeholder loans to correctly model **function calls**, both by respecting `[[clang::lifetimebound]]` annotations and by conservatively handling opaque/un-annotated functions. * **Error Reporting:** Implement the final analysis phase that consumes the dataflow results to generate user-facing diagnostics. This will likely require liveness analysis to identify live origins holding expired loans. * **Strict vs. Permissive Modes:** Add the logic to support both high-confidence (permissive) and more comprehensive (strict) warning levels. * **Expanded C++ Coverage:** Broaden support for common patterns, including the lifetimes of temporary objects and pointers within aggregate types (structs/containers). * Performance benchmarking * Capping number of iterations or number of times a CFGBlock is processed. --------- Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-06-27[Sema] Fix a warningKazu Hirata1-1/+1
This patch fixes: clang/lib/Sema/AnalysisBasedWarnings.cpp:686:23: error: variable 'FD' set but not used [-Werror,-Wunused-but-set-variable]
2025-06-27[clang] Suppress noreturn warning if last statement in a function is a throw ↵Samarth Narang1-1/+23
(#145166) Fixes https://github.com/llvm/llvm-project/issues/144952
2025-05-26Thread Safety Analysis: Support reentrant capabilities (#137133)Marco Elver1-3/+5
Introduce the `reentrant_capability` attribute, which may be specified alongside the `capability(..)` attribute to denote that the defined capability type is reentrant. Marking a capability as reentrant means that acquiring the same capability multiple times is safe, and does not produce warnings on attempted re-acquisition. The most significant changes required are plumbing to propagate if the attribute is present to a CapabilityExpr, and introducing ReentrancyDepth to the LockableFactEntry class.
2025-05-10[Clang] Improve `-Wtautological-overlap-compare` diagnostics flag (#133653)Yutong Zhu1-2/+3
This PR attempts to improve the diagnostics flag `-Wtautological-overlap-compare` (#13473). I have added code to warn about float-point literals and character literals. I have also changed the warning message for the non-overlapping case to provide a more correct hint to the user. Fixes #13473.
2025-04-23Remove spurious semicolon; NFCAaron Ballman1-1/+1
2025-04-23Control analysis-based diagnostics with #pragma (#136323)Aaron Ballman1-12/+31
Previously, analysis-based diagnostics (like -Wconsumed) had to be enabled at file scope in order to be run at the end of each function body. This meant that they did not respect #pragma clang diagnostic enabling or disabling the diagnostic. Now, these pragmas can control the diagnostic emission. Fixes #42199
2025-04-19[clang] Use llvm::SmallVector::pop_back_val (NFC) (#136451)Kazu Hirata1-2/+1
2025-04-15[Fix] Speedup -Wunsafe-buffer-usage when using clang modules. (#127161)Matt1-3/+15
Each piece of code should have analysis run on it precisely once. However, if you build a module, and then build another module depending on it, the header file of the module you depend on will have `-Wunsafe-buffer-usage` run on it twice. This normally isn't a huge issue, but in the case of using the standard library as a module, simply adding the line `#include <cstddef>` increases compile times by 900ms (from 100ms to 1 second) on my machine. I believe this is because the standard library has massive modules, of which only a small part is used (the AST is ~700k lines), and because if what I've been told is correct, the AST is lazily generated, and `-Wunsafe-buffer-usage` forces it to be evaluated every time. See https://issues.chromium.org/issues/351909443 for details and benchmarks.
2025-04-08[Clang] add ext warning for missing return in 'main' for C89 mode (#134617)Oleksandr T.1-11/+16
Fixes #21650 --- Clang currently inserts an implicit `return 0;` in `main()` when compiling in `C89` mode, even though the `C89` standard doesn't require this behavior. This patch changes that behavior by emitting a warning instead of silently inserting the implicit return under `-pedantic`.
2025-02-26Thread Safety Analysis: Support warning on passing/returning pointers to ↵Marco Elver1-0/+24
guarded variables Introduce `-Wthread-safety-pointer` to warn when passing or returning pointers to guarded variables or guarded data. This is is analogous to `-Wthread-safety-reference`, which performs similar checks for C++ references. Adding checks for pointer passing is required to avoid false negatives in large C codebases, where data structures are typically implemented through helpers that take pointers to instances of a data structure. The feature is planned to be enabled by default under `-Wthread-safety` in the next release cycle. This gives time for early adopters to address new findings. Pull Request: https://github.com/llvm/llvm-project/pull/127396
2025-02-25[Wunsafe-buffer-usage] Turn off unsafe-buffer warning for methods annotated ↵Malavika Samak1-0/+3
with clang::unsafe_buffer_usage attribute (#125671) Unsafe operation in methods that are already annotated with clang::unsafe_buffer_usage attribute, should not trigger a warning. This is because, the developer has already identified the method as unsafe and warning at every unsafe operation is redundant. rdar://138644831 --------- Co-authored-by: MalavikaSamak <malavika2@apple.com>
2025-02-19[Clang] [Sema] Combine fallout warnings to just one warning (#127546)foxtran1-95/+49
This merges several falloff and noreturn-related warnings and removes unused diagnostic arguments. Changes: - `warn_maybe_falloff_nonvoid_function` and `warn_falloff_nonvoid_function`, `warn_maybe_falloff_nonvoid_coroutine` and `warn_falloff_nonvoid_coroutine`, `warn_maybe_falloff_nonvoid_lambda` and `warn_falloff_nonvoid_lambda` were combined into `warn_falloff_nonvoid`, - `err_maybe_falloff_nonvoid_block` and `err_falloff_nonvoid_block` were combined into `err_falloff_nonvoid` - `err_noreturn_block_has_return_expr` and `err_noreturn_lambda_has_return_expr` were merged into `err_noreturn_has_return_expr` with the same semantics as `warn_falloff_nonvoid` or `err_falloff_nonvoid`. - Removed some diagnostic args that weren’t being used by the diagnostics.
2025-02-18[Clang] Warn about `[[noreturn]]` on coroutines (#127623)nerix1-3/+5
Declaring a coroutine `[[noreturn]]` doesn't make sense, because it will always return its handle. Clang previously crashed when trying to warn about this (diagnostic ID was 0). Fixes #127327.
2024-12-20Thread Safety Analysis: Support passing scoped locks between functions with ↵Malek Ben Slimane1-0/+40
appropriate annotations (#110523) This is helpful when multiple functions operate on the same capabilities, but we still want to use scoped lockable types for readability and exception safety. - Introduce support for thread safety annotations on function parameters marked with the 'scoped_lockable' attribute. - Add semantic checks for annotated function parameters, ensuring correct usage. - Enhance the analysis to recognize and handle parameters annotated for thread safety, extending the scope of analysis to track these across function boundries. - Verify that the underlying mutexes of function arguments match the expectations set by the annotations. Limitation: This does not work when the attribute arguments are class members, because attributes on function parameters are parsed differently from attributes on functions.
2024-11-21[Clang] Prevent null dereferences (#115502)smanna121-1/+1
This commit addresses several Static Analyzer issues related to potential null dereference by replacing dyn_cast<> with cast<> and getAs<> with castAs<> in various parts of the codes. The cast function asserts that the cast is valid, ensuring that the pointer is not null and preventing null dereference errors. The changes are made in the following files: CGBuiltin.cpp: Ensure vector types have exactly 3 elements. CGExpr.cpp: Ensure member declarations are field declarations. AnalysisBasedWarnings.cpp: Ensure operations are member expressions. SemaExprMember.cpp: Ensure base types are extended vector types. These changes ensure that the types are correctly cast and prevent potential null dereference issues, improving the robustness and safety of the code.
2024-11-18[-Wunsafe-buffer-usage] Fix bug in unsafe casts to incomplete types (#116433)Ziqing Luo1-7/+16
Fixed the crash coming from attempting to get size of incomplete types. Casting `span.data()` to a pointer-to-incomplete-type should be immediately considered unsafe. Solving issue #116286. Co-authored-by: Ziqing Luo <ziqing_luo@apple.com>
2024-11-16[Sema] Remove unused includes (NFC) (#116461)Kazu Hirata1-3/+0
Identified with misc-include-cleaner.
2024-11-15[Clang] [NFC] Refactor AST visitors in Sema and the static analyser to use ↵Sirraide1-88/+83
DynamicRecursiveASTVisitor (#115144) This pr refactors all recursive AST visitors in `Sema`, `Analyze`, and `StaticAnalysis` to inherit from DRAV instead. This is over half of the visitors that inherit from RAV directly. See also #115132, #110040, #93462 LLVM Compile-Time Tracker link for this branch: https://llvm-compile-time-tracker.com/compare.php?from=5adb5c05a2e9f31385fbba8b0436cbc07d91a44d&to=b58e589a86c06ba28d4d90613864d10be29aa5ba&stat=instructions%3Au
2024-10-17[-Wunsafe-buffer-usage] Emit a warning if pointer returned by vector::data ↵Malavika Samak1-0/+9
and array::data is cast to larger type (#111910) Emit a warning when the raw pointer retrieved from std::vector and std::array instances are cast to a larger type. Such a cast followed by a field dereference to the resulting pointer could cause an OOB access. This is similar to the existing span::data warning. (rdar://136704278) Co-authored-by: MalavikaSamak <malavika2@apple.com>
2024-09-22[-Wunsafe-buffer-usage] Fix a bug and suppress libc warnings for C files ↵Ziqing Luo1-1/+2
(#109496) - Fix a bug in UnsafeBufferUsage.cpp related to casting to PointerType - Suppress -Wunsafe-buffer-usage-in-libc-call for C files (rdar://117182250)
2024-09-05Re-land "[-Wunsafe-buffer-usage] Warning Libc functions (#101583)"ziqingluo-901-1/+22
Revert commit 23457964392d00fc872fa6021763859024fb38da, and re-land with a new flag "-Wunsafe-buffer-usage-in-libc-call" for the new warning. (rdar://117182250)
2024-09-04Revert "[-Wunsafe-buffer-usage] Warning Libc functions (#101583)"ziqingluo-901-14/+0
This reverts commit 0fffdeb5f46078ddcc61e112cd38856b1165f050. Will re-land this commit soon with a way to opt-out
2024-09-04[-Wunsafe-buffer-usage] Warning Libc functions (#101583)Ziqing Luo1-0/+14
[-Wunsafe-buffer-usage] Add warn on unsafe calls to libc functions Warning about calls to libc functions involving buffer access. Warned functions are hardcoded by names. (rdar://117182250)
2024-08-14[attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage ↵Malavika Samak1-1/+13
attribute to struct fields (#101585) Extend the unsafe_buffer_usage attribute, so they can also be added to struct fields. This will cause the compiler to warn about the unsafe field at their access sites. Co-authored-by: MalavikaSamak <malavika2@apple.com>
2024-06-11[clang] Replace X && isa<Y>(X) with isa_and_nonnull<Y>(X). NFC (#94987)Pavel Samolysov1-4/+4
This addresses a clang-tidy suggestion.
2024-05-16Respect the [[clang::unsafe_buffer_usage]] attribute for constructors (#91777)Dana Jansens1-4/+21
The -Wunsafe-buffer-usage warning should fire on any call to a function annotated with [[clang::unsafe_buffer_usage]], however it omitted calls to constructors, since the expression is a CXXConstructExpr which does not subclass CallExpr. Thus the matcher on callExpr() does not find these expressions. Add a new WarningGadget that matches cxxConstructExpr that are calling a CXXConstructDecl annotated by [[clang::unsafe_buffer_usage]] and fires the warning. The new UnsafeBufferUsageCtorAttrGadget gadget explicitly avoids matching against the std::span(ptr, size) constructor because that is handled by SpanTwoParamConstructorGadget and we never want two gadgets to match the same thing (and this is guarded by asserts). The gadgets themselves do not report the warnings, instead each gadget's Stmt is passed to the UnsafeBufferUsageHandler (implemented by UnsafeBufferUsageReporter). The Reporter is previously hardcoded that a CXXConstructExpr statement must be a match for std::span(ptr, size), but that is no longer the case. We want the Reporter to generate different warnings (in the -Wunsafe-buffer-usage-in-container subgroup) for the span contructor. And we will want it to report more warnings for other std-container-specific gadgets in the future. To handle this we allow the gadget to control if the warning is general (it calls handleUnsafeBufferUsage()) or is a std-container-specific warning (it calls handleUnsafeOperationInContainer()). Then the WarningGadget grows a virtual method to dispatch to the appropriate path in the UnsafeBufferUsageHandler. By doing so, we no longer need getBaseStmt in the Gadget interface. The only use of it for FixableGadgets was to get the SourceLocation, so we make an explicit virtual method for that on Gadget. Then the handleUnsafeOperation() dispatcher can be a virtual method that is only in WarningGadget. The SpanTwoParamConstructorGadget gadget dispatches to handleUnsafeOperationInContainer() while the other WarningGadgets all dispatch to the original handleUnsafeBufferUsage(). Tests are added for annotated constructors, conversion operattors, call operators, fold expressions, and regular methods. Issue #80482
2024-03-06[clang][NFC] Trim license header comments to 81 characters (#82919)Balazs Benics1-1/+1
clang-format would format these headers poorly by splitting it into multiple lines.