1 //===- UnsafeBufferUsage.h - Replace pointers with modern C++ ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines an analysis that aids replacing buffer accesses through 10 // raw pointers with safer C++ abstractions such as containers and views/spans. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H 15 #define LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H 16 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/Stmt.h" 19 20 namespace clang { 21 22 using DefMapTy = llvm::DenseMap<const VarDecl *, std::vector<const VarDecl *>>; 23 24 /// The interface that lets the caller handle unsafe buffer usage analysis 25 /// results by overriding this class's handle... methods. 26 class UnsafeBufferUsageHandler { 27 public: 28 UnsafeBufferUsageHandler() = default; 29 virtual ~UnsafeBufferUsageHandler() = default; 30 31 /// This analyses produces large fixits that are organized into lists 32 /// of primitive fixits (individual insertions/removals/replacements). 33 using FixItList = llvm::SmallVectorImpl<FixItHint>; 34 35 /// Invoked when an unsafe operation over raw pointers is found. 36 virtual void handleUnsafeOperation(const Stmt *Operation, 37 bool IsRelatedToDecl) = 0; 38 39 /// Invoked when a fix is suggested against a variable. This function groups 40 /// all variables that must be fixed together (i.e their types must be changed to the 41 /// same target type to prevent type mismatches) into a single fixit. 42 virtual void handleUnsafeVariableGroup(const VarDecl *Variable, 43 const DefMapTy &VarGrpMap, 44 FixItList &&Fixes) = 0; 45 46 /// Returns a reference to the `Preprocessor`: 47 virtual bool isSafeBufferOptOut(const SourceLocation &Loc) const = 0; 48 49 virtual std::string 50 getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc, 51 StringRef WSSuffix = "") const = 0; 52 }; 53 54 // This function invokes the analysis and allows the caller to react to it 55 // through the handler class. 56 void checkUnsafeBufferUsage(const Decl *D, UnsafeBufferUsageHandler &Handler, 57 bool EmitSuggestions); 58 59 namespace internal { 60 // Tests if any two `FixItHint`s in `FixIts` conflict. Two `FixItHint`s 61 // conflict if they have overlapping source ranges. 62 bool anyConflict(const llvm::SmallVectorImpl<FixItHint> &FixIts, 63 const SourceManager &SM); 64 } // namespace internal 65 } // end namespace clang 66 67 #endif /* LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H */ 68