clang 24.0.0git
UnsafeBufferUsage.cpp
Go to the documentation of this file.
1//===- UnsafeBufferUsage.cpp - Replace pointers with modern 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
10#include "clang/AST/APValue.h"
13#include "clang/AST/Attr.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
21#include "clang/AST/Stmt.h"
23#include "clang/AST/Type.h"
27#include "clang/Lex/Lexer.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/STLFunctionalExtras.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringMap.h"
35#include "llvm/ADT/StringRef.h"
36#include <cstddef>
37#include <optional>
38#include <queue>
39#include <set>
40#include <sstream>
41#include <vector>
42
43using namespace clang;
44
45#ifndef NDEBUG
46namespace {
47class StmtDebugPrinter
48 : public ConstStmtVisitor<StmtDebugPrinter, std::string> {
49public:
50 std::string VisitStmt(const Stmt *S) { return S->getStmtClassName(); }
51
52 std::string VisitBinaryOperator(const BinaryOperator *BO) {
53 return "BinaryOperator(" + BO->getOpcodeStr().str() + ")";
54 }
55
56 std::string VisitUnaryOperator(const UnaryOperator *UO) {
57 return "UnaryOperator(" + UO->getOpcodeStr(UO->getOpcode()).str() + ")";
58 }
59
60 std::string VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
61 return "ImplicitCastExpr(" + std::string(ICE->getCastKindName()) + ")";
62 }
63};
64
65// Returns a string of ancestor `Stmt`s of the given `DRE` in such a form:
66// "DRE ==> parent-of-DRE ==> grandparent-of-DRE ==> ...".
67static std::string getDREAncestorString(const DeclRefExpr *DRE,
68 ASTContext &Ctx) {
69 std::stringstream SS;
70 const Stmt *St = DRE;
71 StmtDebugPrinter StmtPriner;
72
73 do {
74 SS << StmtPriner.Visit(St);
75
76 DynTypedNodeList StParents = Ctx.getParents(*St);
77
78 if (StParents.size() > 1)
79 return "unavailable due to multiple parents";
80 if (StParents.empty())
81 break;
82 St = StParents.begin()->get<Stmt>();
83 if (St)
84 SS << " ==> ";
85 } while (St);
86 return SS.str();
87}
88
89} // namespace
90#endif /* NDEBUG */
91
92namespace {
93// Using a custom `FastMatcher` instead of ASTMatchers to achieve better
94// performance. FastMatcher uses simple function `matches` to find if a node
95// is a match, avoiding the dependency on the ASTMatchers framework which
96// provide a nice abstraction, but incur big performance costs.
97class FastMatcher {
98public:
99 virtual bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
100 const UnsafeBufferUsageHandler &Handler) = 0;
101 virtual ~FastMatcher() = default;
102};
103
104class MatchResult {
105
106public:
107 template <typename T> const T *getNodeAs(StringRef ID) const {
108 auto It = Nodes.find(ID);
109 if (It == Nodes.end()) {
110 return nullptr;
111 }
112 return It->second.get<T>();
113 }
114
115 void addNode(StringRef ID, const DynTypedNode &Node) { Nodes[ID] = Node; }
116
117private:
118 llvm::StringMap<DynTypedNode> Nodes;
119};
120} // namespace
121
122#define SIZED_CONTAINER_OR_VIEW_LIST \
123 "span", "array", "vector", "basic_string_view", "basic_string", \
124 "initializer_list",
125
126// A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
127// except for those belonging to a different callable of "n".
129public:
130 // Creates an AST visitor that matches `Matcher` on all
131 // descendants of a given node "n" except for the ones
132 // belonging to a different callable of "n".
133 MatchDescendantVisitor(ASTContext &Context, FastMatcher &Matcher,
134 bool FindAll, bool IgnoreUnevaluatedContext,
135 const UnsafeBufferUsageHandler &NewHandler)
136 : Matcher(&Matcher), FindAll(FindAll), Matches(false),
137 IgnoreUnevaluatedContext(IgnoreUnevaluatedContext),
138 ActiveASTContext(&Context), Handler(&NewHandler) {
140 ShouldVisitImplicitCode = false; // TODO: let's ignore implicit code for now
141 }
142
143 // Returns true if a match is found in a subtree of `DynNode`, which belongs
144 // to the same callable of `DynNode`.
145 bool findMatch(const DynTypedNode &DynNode) {
146 Matches = false;
147 if (const Stmt *StmtNode = DynNode.get<Stmt>()) {
148 TraverseStmt(const_cast<Stmt *>(StmtNode));
149 return Matches;
150 }
151 return false;
152 }
153
154 // The following are overriding methods from the base visitor class.
155 // They are public only to allow CRTP to work. They are *not *part
156 // of the public API of this class.
157
158 // For the matchers so far used in safe buffers, we only need to match
159 // `Stmt`s. To override more as needed.
160
161 bool TraverseDecl(Decl *Node) override {
162 if (!Node)
163 return true;
164 if (!match(*Node))
165 return false;
166 // To skip callables:
168 return true;
169 // Traverse descendants
171 }
172
174 // These are unevaluated, except the result expression.
175 if (IgnoreUnevaluatedContext)
176 return TraverseStmt(Node->getResultExpr());
177 return DynamicRecursiveASTVisitor::TraverseGenericSelectionExpr(Node);
178 }
179
180 bool
182 // Unevaluated context.
183 if (IgnoreUnevaluatedContext)
184 return true;
185 return DynamicRecursiveASTVisitor::TraverseUnaryExprOrTypeTraitExpr(Node);
186 }
187
189 bool TraverseQualifier) override {
190 // Unevaluated context.
191 if (IgnoreUnevaluatedContext)
192 return true;
193 return DynamicRecursiveASTVisitor::TraverseTypeOfExprTypeLoc(
194 Node, TraverseQualifier);
195 }
196
198 bool TraverseQualifier) override {
199 // Unevaluated context.
200 if (IgnoreUnevaluatedContext)
201 return true;
202 return DynamicRecursiveASTVisitor::TraverseDecltypeTypeLoc(
203 Node, TraverseQualifier);
204 }
205
207 // Unevaluated context.
208 if (IgnoreUnevaluatedContext)
209 return true;
210 return DynamicRecursiveASTVisitor::TraverseCXXNoexceptExpr(Node);
211 }
212
214 // Unevaluated context.
215 if (IgnoreUnevaluatedContext)
216 return true;
217 return DynamicRecursiveASTVisitor::TraverseCXXTypeidExpr(Node);
218 }
219
221 if (!TraverseStmt(Node->getExpr()))
222 return false;
223 return DynamicRecursiveASTVisitor::TraverseCXXDefaultInitExpr(Node);
224 }
225
226 bool TraverseStmt(Stmt *Node) override {
227 if (!Node)
228 return true;
229 if (!match(*Node))
230 return false;
232 }
233
234private:
235 // Sets 'Matched' to true if 'Matcher' matches 'Node'
236 //
237 // Returns 'true' if traversal should continue after this function
238 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
239 template <typename T> bool match(const T &Node) {
240 if (Matcher->matches(DynTypedNode::create(Node), *ActiveASTContext,
241 *Handler)) {
242 Matches = true;
243 if (!FindAll)
244 return false; // Abort as soon as a match is found.
245 }
246 return true;
247 }
248
249 FastMatcher *const Matcher;
250 // When true, finds all matches. When false, finds the first match and stops.
251 const bool FindAll;
252 bool Matches;
253 bool IgnoreUnevaluatedContext;
254 ASTContext *ActiveASTContext;
255 const UnsafeBufferUsageHandler *Handler;
256};
257
258// Because we're dealing with raw pointers, let's define what we mean by that.
259static bool hasPointerType(const Expr &E) {
261}
262
263static bool hasArrayType(const Expr &E) {
265}
266
267static void
269 const UnsafeBufferUsageHandler &Handler,
270 FastMatcher &Matcher) {
271 MatchDescendantVisitor Visitor(Ctx, Matcher, /*FindAll=*/true,
272 /*IgnoreUnevaluatedContext=*/true, Handler);
273 Visitor.findMatch(DynTypedNode::create(*S));
274}
275
276static void forEachDescendantStmt(const Stmt *S, ASTContext &Ctx,
277 const UnsafeBufferUsageHandler &Handler,
278 FastMatcher &Matcher) {
279 MatchDescendantVisitor Visitor(Ctx, Matcher, /*FindAll=*/true,
280 /*IgnoreUnevaluatedContext=*/false, Handler);
281 Visitor.findMatch(DynTypedNode::create(*S));
282}
283
284// Matches a `Stmt` node iff the node is in a safe-buffer opt-out region
285static bool notInSafeBufferOptOut(const Stmt &Node,
286 const UnsafeBufferUsageHandler *Handler) {
287 return !Handler->isSafeBufferOptOut(Node.getBeginLoc());
288}
289
290static bool
292 const UnsafeBufferUsageHandler *Handler) {
293 return Handler->ignoreUnsafeBufferInContainer(Node.getBeginLoc());
294}
295
296static bool ignoreUnsafeLibcCall(const ASTContext &Ctx, const Stmt &Node,
297 const UnsafeBufferUsageHandler *Handler) {
298 if (Ctx.getLangOpts().CPlusPlus)
299 return Handler->ignoreUnsafeBufferInLibcCall(Node.getBeginLoc());
300 return true; /* Only warn about libc calls for C++ */
301}
302
303static bool
305 const UnsafeBufferUsageHandler *Handler) {
306 if (Ctx.getLangOpts().CPlusPlus)
307 return Handler->ignoreUnsafeBufferInFormatAttrCall(Node.getBeginLoc());
308 return true; /* Only warn about format attribute calls for C++ */
309}
310
311// Finds any expression 'e' such that `OnResult`
312// matches 'e' and 'e' is in an Unspecified Lvalue Context.
314 const Stmt *S, const llvm::function_ref<void(const Expr *)> OnResult) {
315 if (const auto *CE = dyn_cast<ImplicitCastExpr>(S);
316 CE && CE->getCastKind() == CastKind::CK_LValueToRValue)
317 OnResult(CE->getSubExpr());
318 if (const auto *BO = dyn_cast<BinaryOperator>(S);
319 BO && BO->getOpcode() == BO_Assign)
320 OnResult(BO->getLHS());
321}
322
323// Finds any expression `e` such that `InnerMatcher` matches `e` and
324// `e` is in an Unspecified Pointer Context (UPC).
326 const Stmt *S, llvm::function_ref<void(const Stmt *)> InnerMatcher) {
327 // A UPC can be
328 // 1. an argument of a function call (except the callee has [[unsafe_...]]
329 // attribute), or
330 // 2. the operand of a pointer-to-(integer or bool) cast operation; or
331 // 3. the operand of a comparator operation; or
332 // 4. the operand of a pointer subtraction operation
333 // (i.e., computing the distance between two pointers); or ...
334
335 if (auto *CE = dyn_cast<CallExpr>(S)) {
336 if (const auto *FnDecl = CE->getDirectCallee();
337 FnDecl && FnDecl->hasAttr<UnsafeBufferUsageAttr>())
338 return;
340 *CE, [&InnerMatcher](QualType Type, const Expr *Arg) {
341 if (Type->isAnyPointerType())
342 InnerMatcher(Arg);
343 });
344 }
345
346 if (auto *CE = dyn_cast<CastExpr>(S)) {
347 if (CE->getCastKind() != CastKind::CK_PointerToIntegral &&
348 CE->getCastKind() != CastKind::CK_PointerToBoolean)
349 return;
350 if (!hasPointerType(*CE->getSubExpr()))
351 return;
352 InnerMatcher(CE->getSubExpr());
353 }
354
355 // Pointer comparison operator.
356 if (const auto *BO = dyn_cast<BinaryOperator>(S);
357 BO && (BO->getOpcode() == BO_EQ || BO->getOpcode() == BO_NE ||
358 BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE ||
359 BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE)) {
360 auto *LHS = BO->getLHS();
361 if (hasPointerType(*LHS))
362 InnerMatcher(LHS);
363
364 auto *RHS = BO->getRHS();
365 if (hasPointerType(*RHS))
366 InnerMatcher(RHS);
367 }
368
369 // Pointer subtractions.
370 if (const auto *BO = dyn_cast<BinaryOperator>(S);
371 BO && BO->getOpcode() == BO_Sub && hasPointerType(*BO->getLHS()) &&
372 hasPointerType(*BO->getRHS())) {
373 // Note that here we need both LHS and RHS to be
374 // pointer. Then the inner matcher can match any of
375 // them:
376 InnerMatcher(BO->getLHS());
377 InnerMatcher(BO->getRHS());
378 }
379 // FIXME: any more cases? (UPC excludes the RHS of an assignment. For now
380 // we don't have to check that.)
381}
382
383// Finds statements in unspecified untyped context i.e. any expression 'e' such
384// that `InnerMatcher` matches 'e' and 'e' is in an unspecified untyped context
385// (i.e the expression 'e' isn't evaluated to an RValue). For example, consider
386// the following code:
387// int *p = new int[4];
388// int *q = new int[4];
389// if ((p = q)) {}
390// p = q;
391// The expression `p = q` in the conditional of the `if` statement
392// `if ((p = q))` is evaluated as an RValue, whereas the expression `p = q;`
393// in the assignment statement is in an untyped context.
395 const Stmt *S, llvm::function_ref<void(const Stmt *)> InnerMatcher) {
396 // An unspecified context can be
397 // 1. A compound statement,
398 // 2. The body of an if statement
399 // 3. Body of a loop
400 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
401 for (auto *Child : CS->body())
402 InnerMatcher(Child);
403 }
404 if (auto *IfS = dyn_cast<IfStmt>(S)) {
405 if (IfS->getThen())
406 InnerMatcher(IfS->getThen());
407 if (IfS->getElse())
408 InnerMatcher(IfS->getElse());
409 }
410 // FIXME: Handle loop bodies.
411}
412
413// Returns true iff integer E1 is equivalent to integer E2.
414//
415// For now we only support such expressions:
416// expr := DRE | const-value | expr BO expr
417// BO := '*' | '+'
418//
419// FIXME: We can reuse the expression comparator of the interop analysis after
420// it has been upstreamed.
421static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx);
423 const Expr *E2_LHS,
425 const Expr *E2_RHS,
426 ASTContext &Ctx) {
427 if (E1->getOpcode() == BOP) {
428 switch (BOP) {
429 // Commutative operators:
430 case BO_Mul:
431 case BO_Add:
432 return (areEqualIntegers(E1->getLHS(), E2_LHS, Ctx) &&
433 areEqualIntegers(E1->getRHS(), E2_RHS, Ctx)) ||
434 (areEqualIntegers(E1->getLHS(), E2_RHS, Ctx) &&
435 areEqualIntegers(E1->getRHS(), E2_LHS, Ctx));
436 default:
437 return false;
438 }
439 }
440 return false;
441}
442
443static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx) {
444 E1 = E1->IgnoreParenImpCasts();
445 E2 = E2->IgnoreParenImpCasts();
446 if (!E1->getType()->isIntegerType() || E1->getType() != E2->getType())
447 return false;
448
449 Expr::EvalResult ER1, ER2;
450
451 // If both are constants:
452 if (E1->EvaluateAsInt(ER1, Ctx) && E2->EvaluateAsInt(ER2, Ctx))
453 return ER1.Val.getInt() == ER2.Val.getInt();
454
455 // Otherwise, they should have identical stmt kind:
456 if (E1->getStmtClass() != E2->getStmtClass())
457 return false;
458 switch (E1->getStmtClass()) {
459 case Stmt::DeclRefExprClass:
460 return cast<DeclRefExpr>(E1)->getDecl() == cast<DeclRefExpr>(E2)->getDecl();
461 case Stmt::BinaryOperatorClass: {
462 auto BO2 = cast<BinaryOperator>(E2);
464 BO2->getLHS(), BO2->getOpcode(),
465 BO2->getRHS(), Ctx);
466 }
467 default:
468 return false;
469 }
470}
471
472// Given an expression like `&X` or `std::addressof(X)`, returns the `Expr`
473// corresponding to `X` (after removing parens and implicit casts).
474// Returns null if the input expression `E` is not an address-of expression.
475static const Expr *getSubExprInAddressOfExpr(const Expr &E) {
476 if (!E.getType()->isPointerType())
477 return nullptr;
478 const Expr *Ptr = E.IgnoreParenImpCasts();
479
480 // `&X` where `X` is an `Expr`.
481 if (const auto *UO = dyn_cast<UnaryOperator>(Ptr)) {
482 if (UO->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
483 return nullptr;
484 return UO->getSubExpr()->IgnoreParenImpCasts();
485 }
486
487 // `std::addressof(X)` where `X` is an `Expr`.
488 if (const auto *CE = dyn_cast<CallExpr>(Ptr)) {
489 const FunctionDecl *FnDecl = CE->getDirectCallee();
490 if (!FnDecl || !FnDecl->isInStdNamespace() ||
491 FnDecl->getNameAsString() != "addressof" || CE->getNumArgs() != 1)
492 return nullptr;
493 return CE->getArg(0)->IgnoreParenImpCasts();
494 }
495
496 return nullptr;
497}
498
499// Given an expression like `sizeof(X)`, returns the `Expr` corresponding to `X`
500// (after removing parens and implicit casts). Returns null if the expression
501// `E` is not a `sizeof` expression or is `sizeof(T)` for a type `T`.
502static const Expr *getSubExprInSizeOfExpr(const Expr &E) {
503 const auto *SizeOfExpr =
504 dyn_cast<UnaryExprOrTypeTraitExpr>(E.IgnoreParenImpCasts());
505 if (!SizeOfExpr || SizeOfExpr->getKind() != UETT_SizeOf)
506 return nullptr;
507 if (SizeOfExpr->isArgumentType())
508 return nullptr;
509 return SizeOfExpr->getArgumentExpr()->IgnoreParenImpCasts();
510}
511
512// Providing that `Ptr` is a pointer and `Size` is an unsigned-integral
513// expression, returns true iff they follow one of the following safe
514// patterns:
515// 1. Ptr is `DRE.data()` and Size is `DRE.size()` (or `DRE.size_bytes()` for
516// char pointers), where `DRE` is a hardened container or view (or any
517// container/view object when `AllowDuckTypedContainers` is true);
518//
519// 2. Ptr is `a` and Size is `n`, where `a` is of an array-of-T with constant
520// size `n`;
521//
522// 3. Ptr is `&var` and Size is `1`; or
523// Ptr is `std::addressof(...)` and Size is `1`;
524//
525// 4. Size is `0`;
526static bool isPtrBufferSafe(const Expr *Ptr, const Expr *Size, ASTContext &Ctx,
527 bool AllowDuckTypedContainers = false) {
528 // Pattern 1:
529 if (auto *MCEPtr = dyn_cast<CXXMemberCallExpr>(Ptr->IgnoreParenImpCasts()))
530 if (auto *MCESize =
531 dyn_cast<CXXMemberCallExpr>(Size->IgnoreParenImpCasts())) {
532 auto *DREOfPtr = dyn_cast<DeclRefExpr>(
533 MCEPtr->getImplicitObjectArgument()->IgnoreParenImpCasts());
534 auto *DREOfSize = dyn_cast<DeclRefExpr>(
535 MCESize->getImplicitObjectArgument()->IgnoreParenImpCasts());
536
537 if (!DREOfPtr || !DREOfSize)
538 return false; // not in safe pattern
539 // We need to make sure 'a' is identical to 'b' for 'a.data()' and
540 // 'b.size()' otherwise we do not know they match:
541 if (DREOfPtr->getDecl() != DREOfSize->getDecl())
542 return false;
543 const auto *MDData = MCEPtr->getMethodDecl();
544 const auto *MDSize = MCESize->getMethodDecl();
545 if (!MDData || !MDSize)
546 return false;
547 if (MDData->getName() != "data")
548 return false;
549
550 bool AcceptSizeBytes = Ptr->getType()->getPointeeType()->isCharType();
551
552 if (!((AcceptSizeBytes && MDSize->getName() == "size_bytes") ||
553 // Note here the pointer must be a pointer-to-char type unless there
554 // is explicit casting. If there is explicit casting, this branch
555 // is unreachable. Thus, at this branch "size" and "size_bytes" are
556 // equivalent as the pointer is a char pointer:
557 MDSize->getName() == "size"))
558 return false;
559
560 if (AllowDuckTypedContainers)
561 return true;
562
563 // `MCEPtr->getRecordDecl()` must be non-null as `DREOfPtr` is non-null:
564 if (!MCEPtr->getRecordDecl()->isInStdNamespace())
565 return false;
566
567 auto *ObjII = MCEPtr->getRecordDecl()->getIdentifier();
568
569 if (!ObjII)
570 return false;
571
572 return llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
573 ObjII->getName());
574 }
575
577
578 // Pattern 2-4:
579 if (Size->EvaluateAsInt(ER, Ctx)) {
580 // Pattern 2:
581 if (auto *DRE = dyn_cast<DeclRefExpr>(Ptr->IgnoreParenImpCasts())) {
582 if (auto *CAT = Ctx.getAsConstantArrayType(DRE->getType())) {
583 llvm::APSInt SizeInt = ER.Val.getInt();
584
585 return llvm::APSInt::compareValues(
586 SizeInt, llvm::APSInt(CAT->getSize(), true)) == 0;
587 }
588 return false;
589 }
590
591 // Pattern 3:
592 if (ER.Val.getInt().isOne() && getSubExprInAddressOfExpr(*Ptr) != nullptr)
593 return true;
594
595 // Pattern 4:
596 if (ER.Val.getInt().isZero())
597 return true;
598 }
599
600 return false;
601}
602
603// Given the two arguments `(Arg0, Arg1)` of a container/view constructor or
604// factory function call, returns true iff the arguments match one of the
605// following safe forms:
606// 1. `(new T[n], n)`, where `n` is a literal or a DRE
607// 2. `(new T, 1)`
608// 3. `((char *)f(args), args[N] * args[M])`, where
609// `f` is a function with attribute `alloc_size(N, M)`;
610// `args` represents the list of arguments;
611// `N, M` are parameter indexes to the allocating element number and size.
612// Sometimes, there is only one parameter index representing the total
613// size.
614// 4. `(x.begin(), x.end())` where `x` is an object in the
615// SIZED_CONTAINER_OR_VIEW_LIST (or any container/view object when
616// `AllowDuckTypedContainers` is true).
617// 5. `isPtrBufferSafe` returns true for the two arguments.
618template <typename CallOrConstructExpr>
619static bool
620isSafeTwoParamContainerConstruct(const CallOrConstructExpr &Node,
621 ASTContext &Ctx,
622 bool AllowDuckTypedContainers = false) {
623 assert(Node.getNumArgs() == 2 &&
624 "expecting a two-parameter container constructor or factory call");
625 const Expr *Arg0 = Node.getArg(0)->IgnoreParenImpCasts();
626 const Expr *Arg1 = Node.getArg(1)->IgnoreParenImpCasts();
627 auto HaveEqualConstantValues = [&Ctx](const Expr *E0, const Expr *E1) {
628 if (auto E0CV = E0->getIntegerConstantExpr(Ctx))
629 if (auto E1CV = E1->getIntegerConstantExpr(Ctx)) {
630 return llvm::APSInt::compareValues(*E0CV, *E1CV) == 0;
631 }
632 return false;
633 };
634 auto AreSameDRE = [](const Expr *E0, const Expr *E1) {
635 if (auto *DRE0 = dyn_cast<DeclRefExpr>(E0))
636 if (auto *DRE1 = dyn_cast<DeclRefExpr>(E1)) {
637 return DRE0->getDecl() == DRE1->getDecl();
638 }
639 return false;
640 };
641 std::optional<llvm::APSInt> Arg1CV = Arg1->getIntegerConstantExpr(Ctx);
642
643 if (Arg1CV && Arg1CV->isZero())
644 // Check form 5:
645 return true;
646
647 // Check forms 1-2:
648 switch (Arg0->getStmtClass()) {
649 case Stmt::CXXNewExprClass:
650 if (auto Size = cast<CXXNewExpr>(Arg0)->getArraySize()) {
651 // Check form 1:
652 return AreSameDRE((*Size)->IgnoreImplicit(), Arg1) ||
653 HaveEqualConstantValues(*Size, Arg1);
654 }
655 // TODO: what's placeholder type? avoid it for now.
656 if (!cast<CXXNewExpr>(Arg0)->hasPlaceholderType()) {
657 // Check form 2:
658 return Arg1CV && Arg1CV->isOne();
659 }
660 break;
661 default:
662 break;
663 }
664
665 // Check form 3:
666 if (auto CCast = dyn_cast<CStyleCastExpr>(Arg0)) {
667 if (!CCast->getType()->isPointerType())
668 return false;
669
670 QualType PteTy = CCast->getType()->getPointeeType();
671
672 if (!(PteTy->isConstantSizeType() && Ctx.getTypeSizeInChars(PteTy).isOne()))
673 return false;
674
675 if (const auto *Call = dyn_cast<CallExpr>(CCast->getSubExpr())) {
676 if (const FunctionDecl *FD = Call->getDirectCallee())
677 if (auto *AllocAttr = FD->getAttr<AllocSizeAttr>()) {
678 const Expr *EleSizeExpr =
679 Call->getArg(AllocAttr->getElemSizeParam().getASTIndex());
680 // NumElemIdx is invalid if AllocSizeAttr has 1 argument:
681 ParamIdx NumElemIdx = AllocAttr->getNumElemsParam();
682
683 if (!NumElemIdx.isValid())
684 return areEqualIntegers(Arg1, EleSizeExpr, Ctx);
685
686 const Expr *NumElesExpr = Call->getArg(NumElemIdx.getASTIndex());
687
688 if (auto BO = dyn_cast<BinaryOperator>(Arg1))
689 return areEqualIntegralBinaryOperators(BO, NumElesExpr, BO_Mul,
690 EleSizeExpr, Ctx);
691 }
692 }
693 }
694 // Check form 4:
695 auto IsMethodCallToSizedObject =
696 [AllowDuckTypedContainers](const Stmt *Node, StringRef MethodName) {
697 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(Node)) {
698 const auto *MD = MC->getMethodDecl();
699 if (!MD || MD->getName() != MethodName)
700 return false;
701 if (AllowDuckTypedContainers)
702 return true;
703 if (const auto *RD = MC->getRecordDecl())
704 if (auto *II = RD->getDeclName().getAsIdentifierInfo();
705 II && RD->isInStdNamespace())
706 return llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
707 II->getName());
708 }
709 return false;
710 };
711
712 if (IsMethodCallToSizedObject(Arg0, "begin") &&
713 IsMethodCallToSizedObject(Arg1, "end"))
714 return AreSameDRE(
715 // We know Arg0 and Arg1 are `CXXMemberCallExpr`s:
717 ->getImplicitObjectArgument()
718 ->IgnoreParenImpCasts(),
720 ->getImplicitObjectArgument()
721 ->IgnoreParenImpCasts());
722
723 // Check 5:
724 return isPtrBufferSafe(Arg0, Arg1, Ctx, AllowDuckTypedContainers);
725}
726
728 ASTContext &Ctx) {
729 const Expr *Arg0 = Node.getArg(0)->IgnoreParenImpCasts();
730 const Expr *Arg1 = Node.getArg(1)->IgnoreParenImpCasts();
731
732 // Pattern 1: String Literals
733 if (const auto *SL = dyn_cast<StringLiteral>(Arg0)) {
734 if (auto ArgSize = Arg1->getIntegerConstantExpr(Ctx)) {
735 if (llvm::APSInt::compareValues(
736 llvm::APSInt::getUnsigned(SL->getLength()), *ArgSize) >= 0)
737 return true;
738 return false; // Explicitly unsafe if size > length
739 }
740 }
741
742 // Pattern 2: Constant Arrays
743 if (const auto *CAT = Ctx.getAsConstantArrayType(Arg0->getType())) {
744 if (auto ArgSize = Arg1->getIntegerConstantExpr(Ctx)) {
745 if (llvm::APSInt::compareValues(llvm::APSInt(CAT->getSize(), true),
746 *ArgSize) >= 0)
747 return true;
748 return false; // Explicitly unsafe if size > ArraySize
749 }
750 }
751
752 // Pattern 3: Zero length
753 if (auto Val = Arg1->getIntegerConstantExpr(Ctx)) {
754 if (Val->isZero())
755 return true;
756 }
757
758 // Pattern 4: string_view(it, it) - Only safe if it's .begin() and .end() of
759 // the SAME object
760 auto GetContainerObj = [](const Expr *E) -> const Expr * {
761 E = E->IgnoreParenImpCasts();
762 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(E)) {
763 const auto *MD = MCE->getMethodDecl();
764 if (MD && MD->getIdentifier())
765 if (MD->getName() == "begin" || MD->getName() == "end")
766 return MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
767 }
768 return nullptr;
769 };
770
771 const Expr *Obj0 = GetContainerObj(Arg0);
772 const Expr *Obj1 = GetContainerObj(Arg1);
773
774 if (Obj0 && Obj1) {
775 const auto *DRE0 = dyn_cast<DeclRefExpr>(Obj0);
776 const auto *DRE1 = dyn_cast<DeclRefExpr>(Obj1);
777
778 // If both are references to variables, they MUST point to the same
779 // declaration.
780 if (DRE0 && DRE1) {
781 if (DRE0->getDecl()->getCanonicalDecl() ==
782 DRE1->getDecl()->getCanonicalDecl())
783 return true;
784 }
785
786 // If they aren't both DeclRefExprs or don't match, we DO NOT return true.
787 // This ensures v1.begin(), v2.end() triggers a warning.
788 }
789
790 return false; // Default to unsafe
791}
792
794 const ASTContext &Ctx,
795 const bool IgnoreStaticSizedArrays) {
796 // FIXME: Proper solution:
797 // - refactor Sema::CheckArrayAccess
798 // - split safe/OOB/unknown decision logic from diagnostics emitting code
799 // - e. g. "Try harder to find a NamedDecl to point at in the note."
800 // already duplicated
801 // - call both from Sema and from here
802
803 uint64_t limit;
804 if (const auto *CATy =
805 dyn_cast<ConstantArrayType>(Node.getBase()
807 ->getType()
809 limit = CATy->getLimitedSize();
810 } else if (const auto *SLiteral = dyn_cast<clang::StringLiteral>(
811 Node.getBase()->IgnoreParenImpCasts())) {
812 limit = SLiteral->getLength() + 1;
813 } else {
814 return false;
815 }
816
817 if (IgnoreStaticSizedArrays) {
818 // If we made it here, it means a size was found for the var being accessed
819 // (either string literal or array). If it's fixed size, we can ignore it.
820 return true;
821 }
822
823 Expr::EvalResult EVResult;
824 const Expr *IndexExpr = Node.getIdx();
825 if (!IndexExpr->isValueDependent() &&
826 IndexExpr->EvaluateAsInt(EVResult, Ctx)) {
827 llvm::APSInt ArrIdx = EVResult.Val.getInt();
828 // FIXME: ArrIdx.isNegative() we could immediately emit an error as that's a
829 // bug
830 if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
831 return true;
832 } else if (const auto *BE = dyn_cast<BinaryOperator>(IndexExpr)) {
833 // For an integer expression `e` and an integer constant `n`, `e & n` and
834 // `n & e` are bounded by `n`:
835 if (BE->getOpcode() != BO_And && BE->getOpcode() != BO_Rem)
836 return false;
837
838 const Expr *LHS = BE->getLHS();
839 const Expr *RHS = BE->getRHS();
840
841 if (BE->getOpcode() == BO_Rem) {
842 // If n is a negative number, then n % const can be greater than const
843 if (!LHS->getType()->isUnsignedIntegerType()) {
844 return false;
845 }
846
847 if (!RHS->isValueDependent() && RHS->EvaluateAsInt(EVResult, Ctx)) {
848 llvm::APSInt result = EVResult.Val.getInt();
849 if (result.isNonNegative() && result.getLimitedValue() <= limit)
850 return true;
851 }
852
853 return false;
854 }
855
856 if ((!LHS->isValueDependent() &&
857 LHS->EvaluateAsInt(EVResult, Ctx)) || // case: `n & e`
858 (!RHS->isValueDependent() &&
859 RHS->EvaluateAsInt(EVResult, Ctx))) { // `e & n`
860 llvm::APSInt result = EVResult.Val.getInt();
861 if (result.isNonNegative() && result.getLimitedValue() < limit)
862 return true;
863 }
864 return false;
865 }
866 return false;
867}
868
869static bool isSafePointerArithmetic(const Expr *Ptr, const Expr *OffsetExpr,
870 BinaryOperatorKind Opcode,
871 const ASTContext &Ctx) {
872 Expr::EvalResult EVResult;
873
874 if (OffsetExpr->isValueDependent() ||
875 !OffsetExpr->EvaluateAsInt(EVResult, Ctx)) {
876 // Dynamic offsets are not safe.
877 return false;
878 }
879
880 uint64_t limit = 0;
881 const Expr *Base = Ptr->IgnoreParenImpCasts();
882
883 if (const auto *CATy = dyn_cast<ConstantArrayType>(
884 Base->getType()->getUnqualifiedDesugaredType())) {
885 limit = CATy->getLimitedSize();
886 } else if (const auto *SLiteral = dyn_cast<clang::StringLiteral>(Base)) {
887 limit = SLiteral->getLength() + 1;
888 } else {
889 return false;
890 }
891
892 llvm::APSInt OffsetVal = EVResult.Val.getInt();
893 if (Opcode == BO_Sub)
894 OffsetVal = -OffsetVal;
895
896 // If the offset is a constant, and it is within the bounds of the
897 // array, then it is safe.
898 return OffsetVal.isNonNegative() && OffsetVal.getLimitedValue() < limit;
899}
900
901// Constant fold a conditional expression 'cond ? A : B' to
902// - 'A', if 'cond' has constant true value;
903// - 'B', if 'cond' has constant false value.
905 const ASTContext &Ctx) {
906 // FIXME: more places can use this function
907 if (const auto *CE = dyn_cast<ConditionalOperator>(E)) {
908 bool CondEval;
909 const auto *Cond = CE->getCond();
910
911 if (!Cond->isValueDependent() &&
912 Cond->EvaluateAsBooleanCondition(CondEval, Ctx))
913 return CondEval ? CE->getLHS() : CE->getRHS();
914 }
915 return E;
916}
917
918// A pointer type expression is known to be null-terminated, if it has the
919// form: E.c_str(), for any expression E of `std::string` type.
920static bool isNullTermPointer(const Expr *Ptr, ASTContext &Ctx) {
921 // Strip CXXDefaultArgExpr before check:
922 Ptr = Ptr->IgnoreParenImpCasts();
923 if (const auto *DefaultArgE = dyn_cast<CXXDefaultArgExpr>(Ptr))
924 Ptr = DefaultArgE->getExpr()->IgnoreParenImpCasts();
925 // Try to perform constant fold recursively:
926 if (const auto *NewPtr = tryConstantFoldConditionalExpr(Ptr, Ctx);
927 NewPtr != Ptr)
928 return isNullTermPointer(NewPtr, Ctx);
929 // Split the analysis for conditional expressions that cannot be
930 // constant-folded:
931 if (const auto *CondE = dyn_cast<ConditionalOperator>(Ptr)) {
932 return isNullTermPointer(CondE->getLHS(), Ctx) &&
933 isNullTermPointer(CondE->getRHS(), Ctx);
934 }
935
937 return true;
938 if (isa<PredefinedExpr>(Ptr))
939 return true;
940 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Ptr)) {
941 const CXXMethodDecl *MD = MCE->getMethodDecl();
942 const CXXRecordDecl *RD = MCE->getRecordDecl()->getCanonicalDecl();
943
944 if (MD && RD && RD->isInStdNamespace() && MD->getIdentifier())
945 if (MD->getName() == "c_str" && RD->getName() == "basic_string")
946 return true;
947 }
948
949 // Functions known to return properly null terminated strings.
950 static const llvm::StringSet<> NullTermFunctions = {"strerror"};
951 if (auto *CE = dyn_cast<CallExpr>(Ptr)) {
952 const FunctionDecl *F = CE->getDirectCallee();
953 if (F && F->getIdentifier() && NullTermFunctions.contains(F->getName()))
954 return true;
955 }
956 return false;
957}
958
959// Under `libc_func_matchers`, define a set of matchers that match unsafe
960// functions in libc and unsafe calls to them.
962// A tiny parser to strip off common prefix and suffix of libc function names
963// in real code.
964//
965// Given a function name, `matchName()` returns `CoreName` according to the
966// following grammar:
967//
968// LibcName := CoreName | CoreName + "_s"
969// MatchingName := "__builtin_" + LibcName |
970// "__builtin___" + LibcName + "_chk" |
971// "__asan_" + LibcName
972//
973static StringRef matchLibcName(StringRef Name) {
974 if (Name.ends_with("_s"))
975 return Name.drop_back(2 /* truncate "_s" */);
976 return Name;
977}
978
979// Parameter `Name` is the substring after stripping off the prefix
980// "__builtin_".
981static StringRef matchLibcNameOrBuiltinChk(StringRef Name) {
982 if (Name.starts_with("__") && Name.ends_with("_chk"))
983 return matchLibcName(
984 Name.drop_front(2).drop_back(4) /* truncate "__" and "_chk" */);
985 return matchLibcName(Name);
986}
987
988static StringRef matchName(StringRef FunName, bool isBuiltin) {
989 // Try to match __builtin_:
990 if (isBuiltin && FunName.starts_with("__builtin_"))
991 // Then either it is __builtin_LibcName or __builtin___LibcName_chk or no
992 // match:
994 FunName.drop_front(10 /* truncate "__builtin_" */));
995 // Try to match __asan_:
996 if (FunName.starts_with("__asan_"))
997 return matchLibcName(FunName.drop_front(7 /* truncate of "__asan_" */));
998 return matchLibcName(FunName);
999}
1000
1001// Return true iff at least one of following cases holds:
1002// 1. Format string is a literal and there is an unsafe pointer argument
1003// corresponding to an `s` specifier;
1004// 2. Format string is not a literal and there is least an unsafe pointer
1005// argument (including the formatter argument).
1006//
1007// `UnsafeArg` is the output argument that will be set only if this function
1008// returns true.
1009//
1010// Format arguments start at `FmtIdx` + 1, if `FmtArgIdx` is insignificant.
1011static bool
1013 const Expr *&UnsafeArg, const unsigned FmtIdx,
1014 std::optional<const unsigned> FmtArgIdx = std::nullopt,
1015 bool isKprintf = false) {
1016 class StringFormatStringHandler
1018 const CallExpr *Call;
1019 unsigned FmtArgIdx;
1020 const Expr *&UnsafeArg;
1021 ASTContext &Ctx;
1022 bool UnsafeArgSet;
1023
1024 // Returns an `Expr` representing the precision if specified, null
1025 // otherwise.
1026 // The parameter `Call` is a printf call and the parameter `Precision` is
1027 // the precision of a format specifier of the `Call`.
1028 //
1029 // For example, for the `printf("%d, %.10s", 10, p)` call
1030 // `Precision` can be the precision of either "%d" or "%.10s". The former
1031 // one will have `NotSpecified` kind.
1032 const Expr *
1033 getPrecisionAsExpr(const analyze_printf::OptionalAmount &Precision,
1034 const CallExpr *Call) {
1035 if (Precision.hasDataArgument()) {
1036 unsigned PArgIdx = Precision.getArgIndex() + FmtArgIdx;
1037
1038 if (PArgIdx < Call->getNumArgs()) {
1039 const Expr *PArg = Call->getArg(PArgIdx);
1040
1041 // Strip the cast if `PArg` is a cast-to-int expression:
1042 if (auto *CE = dyn_cast<CastExpr>(PArg);
1043 CE && CE->getType()->isSignedIntegerType())
1044 PArg = CE->getSubExpr();
1045 return PArg;
1046 }
1047 }
1048 if (Precision.getHowSpecified() ==
1049 analyze_printf::OptionalAmount::HowSpecified::Constant) {
1050 auto SizeTy = Ctx.getSizeType();
1051 llvm::APSInt PArgVal = llvm::APSInt(
1052 llvm::APInt(Ctx.getTypeSize(SizeTy), Precision.getConstantAmount()),
1053 true);
1054
1055 return IntegerLiteral::Create(Ctx, PArgVal, Ctx.getSizeType(), {});
1056 }
1057 return nullptr;
1058 }
1059
1060 public:
1061 StringFormatStringHandler(const CallExpr *Call, unsigned FmtArgIdx,
1062 const Expr *&UnsafeArg, ASTContext &Ctx)
1063 : Call(Call), FmtArgIdx(FmtArgIdx), UnsafeArg(UnsafeArg), Ctx(Ctx),
1064 UnsafeArgSet(false) {}
1065
1066 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1067 const char *startSpecifier,
1068 unsigned specifierLen,
1069 const TargetInfo &Target) override {
1070 if (FS.getConversionSpecifier().getKind() !=
1072 return true; // continue parsing
1073
1074 unsigned ArgIdx = FS.getArgIndex() + FmtArgIdx;
1075
1076 if (ArgIdx >= Call->getNumArgs())
1077 // If the `ArgIdx` is invalid, give up.
1078 return true; // continue parsing
1079
1080 const Expr *Arg = Call->getArg(ArgIdx);
1081
1082 if (isNullTermPointer(Arg, Ctx))
1083 // If Arg is a null-terminated pointer, it is safe anyway.
1084 return true; // continue parsing
1085
1086 // Otherwise, check if the specifier has a precision and if the character
1087 // pointer is safely bound by the precision:
1089 QualType ArgType = Arg->getType();
1090 bool IsArgTypeValid = // Is ArgType a character pointer type?
1091 ArgType->isPointerType() &&
1093 ? ArgType->getPointeeType()->isWideCharType()
1094 : ArgType->getPointeeType()->isCharType());
1095
1096 if (auto *Precision = getPrecisionAsExpr(FS.getPrecision(), Call);
1097 Precision && IsArgTypeValid)
1098 if (isPtrBufferSafe(Arg, Precision, Ctx))
1099 return true;
1100 // Handle unsafe case:
1101 UnsafeArg = Call->getArg(ArgIdx); // output
1102 UnsafeArgSet = true;
1103 return false; // returning false stops parsing immediately
1104 }
1105
1106 bool isUnsafeArgSet() { return UnsafeArgSet; }
1107 };
1108
1109 const Expr *Fmt = Call->getArg(FmtIdx);
1110 unsigned FmtArgStartingIdx =
1111 FmtArgIdx.has_value() ? static_cast<unsigned>(*FmtArgIdx) : FmtIdx + 1;
1112
1113 if (auto *SL = dyn_cast<clang::StringLiteral>(Fmt->IgnoreParenImpCasts())) {
1114 if (SL->getCharByteWidth() == 1) {
1115 StringRef FmtStr = SL->getString();
1116 StringFormatStringHandler Handler(Call, FmtArgStartingIdx, UnsafeArg,
1117 Ctx);
1118
1120 Handler, FmtStr.begin(), FmtStr.end(), Ctx.getLangOpts(),
1121 Ctx.getTargetInfo(), isKprintf) &&
1122 Handler.isUnsafeArgSet();
1123 }
1124
1125 if (auto FmtStr = SL->tryEvaluateString(Ctx)) {
1126 StringFormatStringHandler Handler(Call, FmtArgStartingIdx, UnsafeArg,
1127 Ctx);
1129 Handler, FmtStr->data(), FmtStr->data() + FmtStr->size(),
1130 Ctx.getLangOpts(), Ctx.getTargetInfo(), isKprintf) &&
1131 Handler.isUnsafeArgSet();
1132 }
1133 }
1134 // If format is not a string literal, we cannot analyze the format string.
1135 // In this case, this call is considered unsafe if at least one argument
1136 // (including the format argument) is unsafe pointer.
1137 return llvm::any_of(
1138 llvm::make_range(Call->arg_begin() + FmtIdx, Call->arg_end()),
1139 [&UnsafeArg, &Ctx](const Expr *Arg) -> bool {
1140 if (Arg->getType()->isPointerType() && !isNullTermPointer(Arg, Ctx)) {
1141 UnsafeArg = Arg;
1142 return true;
1143 }
1144 return false;
1145 });
1146}
1147
1148// Matches a FunctionDecl node such that
1149// 1. It's name, after stripping off predefined prefix and suffix, is
1150// `CoreName`; and
1151// 2. `CoreName` or `CoreName[str/wcs]` is one of the `PredefinedNames`, which
1152// maps libc function names to their families.
1153//
1154// Note: For predefined prefix and suffix, see `matchName()`.
1155// The notation `CoreName[str/wcs]` means a new name obtained from replace
1156// string "wcs" with "str" in `CoreName`.
1157//
1158// Returns the family of the matched function, or std::nullopt if it does not
1159// match.
1160static std::optional<UnsafeLibcFunctionFamily>
1162 static const llvm::StringMap<UnsafeLibcFunctionFamily> PredefinedNames = [] {
1163 using F = UnsafeLibcFunctionFamily;
1164 llvm::StringMap<F> M;
1165 auto Add = [&](F Family, std::initializer_list<StringRef> Names) {
1166 for (StringRef N : Names)
1167 M[N] = Family;
1168 };
1169 Add(F::NumericConversion,
1170 {"atof", "atoi", "atol", "atoll", "strtol", "strtoll", "strtoul",
1171 "strtoull", "strtof", "strtod", "strtold", "strtoimax", "strtoumax"});
1172 // "strfromf", "strfromd", "strfroml", // C23?
1173 Add(F::StringManipulation,
1174 {"strcpy", "strncpy", "strlcpy", "strcat", "strncat", "strlcat",
1175 "strxfrm", "strdup", "strndup"});
1176 Add(F::StringExamination,
1177 {"strlen", "strnlen", "strcmp", "strncmp", "stricmp", "strcasecmp",
1178 "strcoll", "strchr", "strrchr", "strspn", "strcspn", "strpbrk",
1179 "strstr", "strtok"});
1180 Add(F::Memory, {"memchr", "wmemchr", "memcmp", "wmemcmp", "memcpy",
1181 "memccpy", "mempcpy", "wmemcpy", "memmove", "wmemmove",
1182 "wmemset", "bcopy", "bzero"});
1183 Add(F::IO, {"fread", "fwrite", "fgets", "fgetws", "gets", "fputs", "fputws",
1184 "puts"});
1185 Add(F::Other, {"strerror_s", "strerror_r", "bsearch", "qsort"});
1186 return M;
1187 }();
1188
1189 auto *II = Node.getIdentifier();
1190
1191 if (!II)
1192 return std::nullopt;
1193
1194 StringRef Name = matchName(II->getName(), Node.getBuiltinID());
1195
1196 // Match predefined names:
1197 if (auto It = PredefinedNames.find(Name); It != PredefinedNames.end())
1198 return It->second;
1199
1200 std::string NameWCS = Name.str();
1201 size_t WcsPos = NameWCS.find("wcs");
1202
1203 while (WcsPos != std::string::npos) {
1204 NameWCS[WcsPos++] = 's';
1205 NameWCS[WcsPos++] = 't';
1206 NameWCS[WcsPos++] = 'r';
1207 WcsPos = NameWCS.find("wcs", WcsPos);
1208 }
1209 if (auto It = PredefinedNames.find(NameWCS); It != PredefinedNames.end())
1210 return It->second;
1211 // All `scanf` functions are unsafe (including `sscanf`, `vsscanf`, etc.. They
1212 // all should end with "scanf"):
1213 if (Name.ends_with("scanf"))
1215 return std::nullopt;
1216}
1217
1219 return getPredefinedUnsafeLibcFuncFamily(Node).has_value();
1220}
1221
1222// Returns the family of a callee that isPredefinedUnsafeLibcFunc or
1223// isUnsafeMemset matched. Only memset is not in PredefinedNames.
1226 if (auto Family = getPredefinedUnsafeLibcFuncFamily(Node))
1227 return *Family;
1229}
1230
1231// Returns true if this is an unsafe call to `memset`.
1232// The only call we currently consider safe is of the form
1233// `memset(&x, 0, sizeof(x))`, with possible variations in parentheses.
1234static bool isUnsafeMemset(const CallExpr &Node, ASTContext &Ctx) {
1235 const FunctionDecl *FD = Node.getDirectCallee();
1236 assert(FD && "It should have been checked that FD is non-null.");
1237
1238 const IdentifierInfo *II = FD->getIdentifier();
1239 if (!II)
1240 return false;
1241
1242 StringRef Name = matchName(II->getName(), FD->getBuiltinID());
1243 if (Name != "memset")
1244 return false;
1245
1246 // We currently only handle the basic forms of `memset` with 3 parameters.
1247 // There is also `__builtin___memset_chk()` which takes a 4th `destlen`
1248 // parameter for bounds checking, but we don't consider its safe forms yet.
1249 // https://refspecs.linuxbase.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/libc---memset-chk-1.html
1250 if (FD->getNumParams() != 3)
1251 return true;
1252
1253 // Now we have a known version of `memset`, consider it unsafe unless it's in
1254 // the form `memset(&x, 0, sizeof(x))`.
1255 const auto *AddressOfVar = dyn_cast_if_present<DeclRefExpr>(
1257 if (!AddressOfVar)
1258 return true;
1259
1260 const auto *SizeOfVar =
1261 dyn_cast_if_present<DeclRefExpr>(getSubExprInSizeOfExpr(*Node.getArg(2)));
1262 if (!SizeOfVar)
1263 return true;
1264
1265 return AddressOfVar->getDecl() != SizeOfVar->getDecl();
1266}
1267
1268// Match a call to one of the `v*printf` functions taking `va_list`. We cannot
1269// check safety for these functions so they should be changed to their
1270// non-va_list versions.
1271static bool isUnsafeVaListPrintfFunc(const FunctionDecl &Node) {
1272 auto *II = Node.getIdentifier();
1273
1274 if (!II)
1275 return false;
1276
1277 StringRef Name = matchName(II->getName(), Node.getBuiltinID());
1278
1279 return Name.starts_with("v") && Name.ends_with("printf");
1280}
1281
1282// Matches a call to one of the `sprintf` functions as they are always unsafe
1283// and should be changed to `snprintf`.
1284static bool isUnsafeSprintfFunc(const FunctionDecl &Node) {
1285 auto *II = Node.getIdentifier();
1286
1287 if (!II)
1288 return false;
1289
1290 StringRef Name = matchName(II->getName(), Node.getBuiltinID());
1291
1292 return Name == "sprintf" || Name == "swprintf";
1293}
1294
1295// Match function declarations of `printf`, `fprintf`, `snprintf` and their wide
1296// character versions. Calls to these functions can be safe if their arguments
1297// are carefully made safe.
1298static bool isNormalPrintfFunc(const FunctionDecl &Node) {
1299 auto *II = Node.getIdentifier();
1300
1301 if (!II)
1302 return false;
1303
1304 StringRef Name = matchName(II->getName(), Node.getBuiltinID());
1305
1306 if (!Name.ends_with("printf"))
1307 return false;
1308
1309 StringRef Prefix = Name.drop_back(6);
1310
1311 if (Prefix.ends_with("w"))
1312 Prefix = Prefix.drop_back(1);
1313
1314 return Prefix.empty() || Prefix == "k" || Prefix == "f" || Prefix == "sn";
1315}
1316
1317// This matcher requires that it is known that the callee `isNormalPrintf`.
1318// Then if the format string is a string literal, this matcher matches when at
1319// least one string argument is unsafe. If the format is not a string literal,
1320// this matcher matches when at least one pointer type argument is unsafe.
1321static bool hasUnsafePrintfStringArg(const CallExpr &Node, ASTContext &Ctx,
1322 MatchResult &Result, llvm::StringRef Tag) {
1323 // Determine what printf it is by examining formal parameters:
1324 const FunctionDecl *FD = Node.getDirectCallee();
1325
1326 assert(FD && "It should have been checked that FD is non-null.");
1327
1328 unsigned NumParms = FD->getNumParams();
1329
1330 if (NumParms < 1)
1331 return false; // possibly some user-defined printf function
1332
1333 QualType FirstParmTy = FD->getParamDecl(0)->getType();
1334
1335 if (!FirstParmTy->isPointerType())
1336 return false; // possibly some user-defined printf function
1337
1338 QualType FirstPteTy = FirstParmTy->castAs<PointerType>()->getPointeeType();
1339
1340 if (!Ctx.getFILEType()
1341 .isNull() && //`FILE *` must be in the context if it is fprintf
1342 FirstPteTy.getCanonicalType() == Ctx.getFILEType().getCanonicalType()) {
1343 // It is a fprintf:
1344 const Expr *UnsafeArg;
1345
1346 if (hasUnsafeFormatOrSArg(Ctx, &Node, UnsafeArg, /* FmtIdx= */ 1)) {
1347 Result.addNode(Tag, DynTypedNode::create(*UnsafeArg));
1348 return true;
1349 }
1350 return false;
1351 }
1352
1353 if (FirstPteTy.isConstQualified()) {
1354 // If the first parameter is a `const char *`, it is a printf/kprintf:
1355 bool isKprintf = false;
1356 const Expr *UnsafeArg;
1357
1358 if (auto *II = FD->getIdentifier())
1359 isKprintf = II->getName() == "kprintf";
1360 if (hasUnsafeFormatOrSArg(Ctx, &Node, UnsafeArg, /* FmtIdx= */ 0,
1361 /* FmtArgIdx= */ std::nullopt, isKprintf)) {
1362 Result.addNode(Tag, DynTypedNode::create(*UnsafeArg));
1363 return true;
1364 }
1365 return false;
1366 }
1367
1368 if (NumParms > 2) {
1369 QualType SecondParmTy = FD->getParamDecl(1)->getType();
1370
1371 if (!FirstPteTy.isConstQualified() && SecondParmTy->isIntegerType()) {
1372 // If the first parameter type is non-const qualified `char *` and the
1373 // second is an integer, it is a snprintf:
1374 const Expr *UnsafeArg;
1375
1376 if (hasUnsafeFormatOrSArg(Ctx, &Node, UnsafeArg, /* FmtIdx= */ 2)) {
1377 Result.addNode(Tag, DynTypedNode::create(*UnsafeArg));
1378 return true;
1379 }
1380 return false;
1381 }
1382 }
1383 // We don't really recognize this "normal" printf, the only thing we
1384 // can do is to require all pointers to be null-terminated:
1385 for (const auto *Arg : Node.arguments())
1386 if (Arg->getType()->isPointerType() && !isNullTermPointer(Arg, Ctx)) {
1387 Result.addNode(Tag, DynTypedNode::create(*Arg));
1388 return true;
1389 }
1390 return false;
1391}
1392
1393// This function requires that it is known that the callee `isNormalPrintf`.
1394// It returns true iff the first two arguments of the call is a pointer
1395// `Ptr` and an unsigned integer `Size` and they are NOT safe, i.e.,
1396// `!isPtrBufferSafe(Ptr, Size)`.
1397static bool hasUnsafeSnprintfBuffer(const CallExpr &Node, ASTContext &Ctx) {
1398 const FunctionDecl *FD = Node.getDirectCallee();
1399
1400 assert(FD && "It should have been checked that FD is non-null.");
1401
1402 if (FD->getNumParams() < 3)
1403 return false; // Not an snprint
1404
1405 QualType FirstParmTy = FD->getParamDecl(0)->getType();
1406
1407 if (!FirstParmTy->isPointerType())
1408 return false; // Not an snprint
1409
1410 QualType FirstPteTy = FirstParmTy->castAs<PointerType>()->getPointeeType();
1411 const Expr *Buf = Node.getArg(0), *Size = Node.getArg(1);
1412
1413 if (FirstPteTy.isConstQualified() || !FirstPteTy->isAnyCharacterType() ||
1414 !Buf->getType()->isPointerType() ||
1415 !Size->getType()->isUnsignedIntegerType())
1416 return false; // not an snprintf call
1417
1418 return !isPtrBufferSafe(Buf, Size, Ctx);
1419}
1420
1421// A libc function must either be in the std:: namespace or a global function
1422// that is not in any namespace.
1423static bool isInLibcScope(const FunctionDecl &FD) {
1424 const bool IsGlobalAndNotInAnyNamespace =
1426
1427 return FD.isInStdNamespace() || IsGlobalAndNotInAnyNamespace;
1428}
1429
1430// Matches a function that UnsafeLibcFunctionCallGadget treats as a libc
1431// function: in the libc scope, with a libc name.
1432static bool isLibcFunction(const FunctionDecl &FD) {
1433 return isInLibcScope(FD) &&
1436}
1437} // namespace libc_func_matchers
1438
1439namespace {
1440// Because the analysis revolves around variables and their types, we'll need to
1441// track uses of variables (aka DeclRefExprs).
1442using DeclUseList = SmallVector<const DeclRefExpr *, 1>;
1443
1444// Convenience typedef.
1445using FixItList = SmallVector<FixItHint, 4>;
1446} // namespace
1447
1448namespace {
1449/// Gadget is an individual operation in the code that may be of interest to
1450/// this analysis. Each (non-abstract) subclass corresponds to a specific
1451/// rigid AST structure that constitutes an operation on a pointer-type object.
1452/// Discovery of a gadget in the code corresponds to claiming that we understand
1453/// what this part of code is doing well enough to potentially improve it.
1454/// Gadgets can be warning (immediately deserving a warning) or fixable (not
1455/// always deserving a warning per se, but requires our attention to identify
1456/// it warrants a fixit).
1457class Gadget {
1458public:
1459 enum class Kind {
1460#define GADGET(x) x,
1461#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
1462 };
1463
1464 Gadget(Kind K) : K(K) {}
1465
1466 Kind getKind() const { return K; }
1467
1468#ifndef NDEBUG
1469 StringRef getDebugName() const {
1470 switch (K) {
1471#define GADGET(x) \
1472 case Kind::x: \
1473 return #x;
1474#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
1475 }
1476 llvm_unreachable("Unhandled Gadget::Kind enum");
1477 }
1478#endif
1479
1480 virtual bool isWarningGadget() const = 0;
1481 // TODO remove this method from WarningGadget interface. It's only used for
1482 // debug prints in FixableGadget.
1483 virtual SourceLocation getSourceLoc() const = 0;
1484
1485 /// Returns the list of pointer-type variables on which this gadget performs
1486 /// its operation. Typically, there's only one variable. This isn't a list
1487 /// of all DeclRefExprs in the gadget's AST!
1488 virtual DeclUseList getClaimedVarUseSites() const = 0;
1489
1490 virtual ~Gadget() = default;
1491
1492private:
1493 Kind K;
1494};
1495
1496/// Warning gadgets correspond to unsafe code patterns that warrants
1497/// an immediate warning.
1498class WarningGadget : public Gadget {
1499public:
1500 WarningGadget(Kind K) : Gadget(K) {}
1501
1502 static bool classof(const Gadget *G) { return G->isWarningGadget(); }
1503 bool isWarningGadget() const final { return true; }
1504
1505 virtual void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1506 bool IsRelatedToDecl,
1507 ASTContext &Ctx) const = 0;
1508
1509 virtual SmallVector<const Expr *, 1> getUnsafePtrs() const = 0;
1510};
1511
1512/// Fixable gadgets correspond to code patterns that aren't always unsafe but
1513/// need to be properly recognized in order to emit fixes. For example, if a raw
1514/// pointer-type variable is replaced by a safe C++ container, every use of such
1515/// variable must be carefully considered and possibly updated.
1516class FixableGadget : public Gadget {
1517public:
1518 FixableGadget(Kind K) : Gadget(K) {}
1519
1520 static bool classof(const Gadget *G) { return !G->isWarningGadget(); }
1521 bool isWarningGadget() const final { return false; }
1522
1523 /// Returns a fixit that would fix the current gadget according to
1524 /// the current strategy. Returns std::nullopt if the fix cannot be produced;
1525 /// returns an empty list if no fixes are necessary.
1526 virtual std::optional<FixItList> getFixits(const FixitStrategy &) const {
1527 return std::nullopt;
1528 }
1529
1530 /// Returns a list of two elements where the first element is the LHS of a
1531 /// pointer assignment statement and the second element is the RHS. This
1532 /// two-element list represents the fact that the LHS buffer gets its bounds
1533 /// information from the RHS buffer. This information will be used later to
1534 /// group all those variables whose types must be modified together to prevent
1535 /// type mismatches.
1536 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
1537 getStrategyImplications() const {
1538 return std::nullopt;
1539 }
1540};
1541
1542static bool isSupportedVariable(const DeclRefExpr &Node) {
1543 const Decl *D = Node.getDecl();
1544 return D != nullptr && isa<VarDecl>(D);
1545}
1546
1547// Returns true for RecordDecl of type std::unique_ptr<T[]>
1548static bool isUniquePtrArray(const CXXRecordDecl *RecordDecl) {
1550 RecordDecl->getNameAsString() != "unique_ptr")
1551 return false;
1552
1553 const ClassTemplateSpecializationDecl *class_template_specialization_decl =
1554 dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl);
1555 if (!class_template_specialization_decl)
1556 return false;
1557
1558 const TemplateArgumentList &template_args =
1559 class_template_specialization_decl->getTemplateArgs();
1560 if (template_args.size() == 0)
1561 return false;
1562
1563 const TemplateArgument &first_arg = template_args[0];
1564 if (first_arg.getKind() != TemplateArgument::Type)
1565 return false;
1566
1567 QualType referred_type = first_arg.getAsType();
1568 return referred_type->isArrayType();
1569}
1570
1571class UniquePtrArrayAccessGadget : public WarningGadget {
1572private:
1573 static constexpr const char *const AccessorTag = "unique_ptr_array_access";
1574 const CXXOperatorCallExpr *AccessorExpr;
1575
1576public:
1577 UniquePtrArrayAccessGadget(const MatchResult &Result)
1578 : WarningGadget(Kind::UniquePtrArrayAccess),
1579 AccessorExpr(Result.getNodeAs<CXXOperatorCallExpr>(AccessorTag)) {
1580 assert(AccessorExpr &&
1581 "UniquePtrArrayAccessGadget requires a matched CXXOperatorCallExpr");
1582 }
1583
1584 static bool classof(const Gadget *G) {
1585 return G->getKind() == Kind::UniquePtrArrayAccess;
1586 }
1587
1588 static bool matches(const Stmt *S, const ASTContext &Ctx,
1590
1591 const CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(S);
1592 if (!OpCall || OpCall->getOperator() != OO_Subscript)
1593 return false;
1594
1595 const Expr *Callee = OpCall->getCallee()->IgnoreParenImpCasts();
1596 if (!Callee)
1597 return false;
1598
1599 const CXXMethodDecl *Method =
1600 dyn_cast_or_null<CXXMethodDecl>(OpCall->getDirectCallee());
1601 if (!Method)
1602 return false;
1603
1604 if (Method->getOverloadedOperator() != OO_Subscript)
1605 return false;
1606
1607 const CXXRecordDecl *RecordDecl = Method->getParent();
1608 if (!isUniquePtrArray(RecordDecl))
1609 return false;
1610
1611 const Expr *IndexExpr = OpCall->getArg(1);
1612 clang::Expr::EvalResult Eval;
1613
1614 // Allow [0]
1615 if (IndexExpr->EvaluateAsInt(Eval, Ctx) && Eval.Val.getInt().isZero())
1616 return false;
1617
1618 Result.addNode(AccessorTag, DynTypedNode::create(*OpCall));
1619 return true;
1620 }
1621 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1622 bool IsRelatedToDecl,
1623 ASTContext &Ctx) const override {
1625 DynTypedNode::create(*AccessorExpr), IsRelatedToDecl, Ctx);
1626 }
1627
1628 SourceLocation getSourceLoc() const override {
1629 if (AccessorExpr)
1630 return AccessorExpr->getOperatorLoc();
1631 return SourceLocation();
1632 }
1633
1634 DeclUseList getClaimedVarUseSites() const override { return {}; }
1635 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
1636};
1637
1638using FixableGadgetList = std::vector<std::unique_ptr<FixableGadget>>;
1639using WarningGadgetList = std::vector<std::unique_ptr<WarningGadget>>;
1640
1641/// An increment of a pointer-type value is unsafe as it may run the pointer
1642/// out of bounds.
1643class IncrementGadget : public WarningGadget {
1644 static constexpr const char *const OpTag = "op";
1645 const UnaryOperator *Op;
1646
1647public:
1648 IncrementGadget(const MatchResult &Result)
1649 : WarningGadget(Kind::Increment),
1650 Op(Result.getNodeAs<UnaryOperator>(OpTag)) {}
1651
1652 static bool classof(const Gadget *G) {
1653 return G->getKind() == Kind::Increment;
1654 }
1655
1656 static bool matches(const Stmt *S, const ASTContext &Ctx,
1658 const auto *UO = dyn_cast<UnaryOperator>(S);
1659 if (!UO || !UO->isIncrementOp())
1660 return false;
1662 return false;
1663 Result.addNode(OpTag, DynTypedNode::create(*UO));
1664 return true;
1665 }
1666
1667 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1668 bool IsRelatedToDecl,
1669 ASTContext &Ctx) const override {
1670 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
1671 }
1672 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
1673
1674 DeclUseList getClaimedVarUseSites() const override {
1675 SmallVector<const DeclRefExpr *, 2> Uses;
1676 if (const auto *DRE =
1677 dyn_cast<DeclRefExpr>(Op->getSubExpr()->IgnoreParenImpCasts())) {
1678 Uses.push_back(DRE);
1679 }
1680
1681 return std::move(Uses);
1682 }
1683
1684 SmallVector<const Expr *, 1> getUnsafePtrs() const override {
1685 return {Op->getSubExpr()->IgnoreParenImpCasts()};
1686 }
1687};
1688
1689/// A decrement of a pointer-type value is unsafe as it may run the pointer
1690/// out of bounds.
1691class DecrementGadget : public WarningGadget {
1692 static constexpr const char *const OpTag = "op";
1693 const UnaryOperator *Op;
1694
1695public:
1696 DecrementGadget(const MatchResult &Result)
1697 : WarningGadget(Kind::Decrement),
1698 Op(Result.getNodeAs<UnaryOperator>(OpTag)) {}
1699
1700 static bool classof(const Gadget *G) {
1701 return G->getKind() == Kind::Decrement;
1702 }
1703
1704 static bool matches(const Stmt *S, const ASTContext &Ctx,
1706 const auto *UO = dyn_cast<UnaryOperator>(S);
1707 if (!UO || !UO->isDecrementOp())
1708 return false;
1710 return false;
1711 Result.addNode(OpTag, DynTypedNode::create(*UO));
1712 return true;
1713 }
1714
1715 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1716 bool IsRelatedToDecl,
1717 ASTContext &Ctx) const override {
1718 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
1719 }
1720 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
1721
1722 DeclUseList getClaimedVarUseSites() const override {
1723 if (const auto *DRE =
1724 dyn_cast<DeclRefExpr>(Op->getSubExpr()->IgnoreParenImpCasts())) {
1725 return {DRE};
1726 }
1727
1728 return {};
1729 }
1730
1731 SmallVector<const Expr *, 1> getUnsafePtrs() const override {
1732 return {Op->getSubExpr()->IgnoreParenImpCasts()};
1733 }
1734};
1735
1736/// Array subscript expressions on raw pointers as if they're arrays. Unsafe as
1737/// it doesn't have any bounds checks for the array.
1738class ArraySubscriptGadget : public WarningGadget {
1739 static constexpr const char *const ArraySubscrTag = "ArraySubscript";
1740 const ArraySubscriptExpr *ASE;
1741
1742public:
1743 ArraySubscriptGadget(const MatchResult &Result)
1744 : WarningGadget(Kind::ArraySubscript),
1745 ASE(Result.getNodeAs<ArraySubscriptExpr>(ArraySubscrTag)) {}
1746
1747 static bool classof(const Gadget *G) {
1748 return G->getKind() == Kind::ArraySubscript;
1749 }
1750
1751 static bool matches(const Stmt *S, const ASTContext &Ctx,
1752 const UnsafeBufferUsageHandler *Handler,
1754 const auto *ASE = dyn_cast<ArraySubscriptExpr>(S);
1755 if (!ASE)
1756 return false;
1757 const auto *const Base = ASE->getBase()->IgnoreParenImpCasts();
1758 if (!hasPointerType(*Base) && !hasArrayType(*Base))
1759 return false;
1760 const auto *Idx = dyn_cast<IntegerLiteral>(ASE->getIdx());
1761 bool IsSafeIndex = (Idx && Idx->getValue().isZero()) ||
1762 isa<ArrayInitIndexExpr>(ASE->getIdx());
1763 if (IsSafeIndex ||
1765 *ASE, Ctx,
1767 return false;
1768 Result.addNode(ArraySubscrTag, DynTypedNode::create(*ASE));
1769 return true;
1770 }
1771
1772 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1773 bool IsRelatedToDecl,
1774 ASTContext &Ctx) const override {
1775 Handler.handleUnsafeOperation(ASE, IsRelatedToDecl, Ctx);
1776 }
1777 SourceLocation getSourceLoc() const override { return ASE->getBeginLoc(); }
1778
1779 DeclUseList getClaimedVarUseSites() const override {
1780 if (const auto *DRE =
1781 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts())) {
1782 return {DRE};
1783 }
1784
1785 return {};
1786 }
1787
1788 SmallVector<const Expr *, 1> getUnsafePtrs() const override {
1789 return {ASE->getBase()->IgnoreParenImpCasts()};
1790 }
1791};
1792
1793/// A pointer arithmetic expression of one of the forms:
1794/// \code
1795/// ptr + n | n + ptr | ptr - n | ptr += n | ptr -= n
1796/// \endcode
1797class PointerArithmeticGadget : public WarningGadget {
1798 static constexpr const char *const PointerArithmeticTag = "ptrAdd";
1799 static constexpr const char *const PointerArithmeticPointerTag = "ptrAddPtr";
1800 const BinaryOperator *PA; // pointer arithmetic expression
1801 const Expr *Ptr; // the pointer expression in `PA`
1802
1803public:
1804 PointerArithmeticGadget(const MatchResult &Result)
1805 : WarningGadget(Kind::PointerArithmetic),
1806 PA(Result.getNodeAs<BinaryOperator>(PointerArithmeticTag)),
1807 Ptr(Result.getNodeAs<Expr>(PointerArithmeticPointerTag)) {}
1808
1809 static bool classof(const Gadget *G) {
1810 return G->getKind() == Kind::PointerArithmetic;
1811 }
1812
1813 static bool matches(const Stmt *S, const ASTContext &Ctx,
1814 const UnsafeBufferUsageHandler *Handler,
1816 const auto *BO = dyn_cast<BinaryOperator>(S);
1817 if (!BO)
1818 return false;
1819 const auto *LHS = BO->getLHS();
1820 const auto *RHS = BO->getRHS();
1821
1822 const Expr *Ptr = nullptr;
1823 const Expr *OffsetExpr = nullptr;
1824
1825 // ptr at left
1826 if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub ||
1827 BO->getOpcode() == BO_AddAssign || BO->getOpcode() == BO_SubAssign) {
1828 if (hasPointerType(*LHS) && (RHS->getType()->isIntegerType() ||
1829 RHS->getType()->isEnumeralType())) {
1830 Ptr = LHS;
1831 OffsetExpr = RHS;
1832 }
1833 }
1834 // ptr at right
1835 if (BO->getOpcode() == BO_Add && hasPointerType(*RHS) &&
1836 (LHS->getType()->isIntegerType() || LHS->getType()->isEnumeralType())) {
1837 Ptr = RHS;
1838 OffsetExpr = LHS;
1839 }
1840
1841 if (!Ptr || !OffsetExpr)
1842 return false;
1843
1844 // If -Wno-unsafe-buffer-usage-in-static-sized-array is used, suppress
1845 // warnings for guaranteed safe pointer arithmetic.
1847 isSafePointerArithmetic(Ptr, OffsetExpr, BO->getOpcode(), Ctx)) {
1848 return false;
1849 }
1850
1851 // Default: warn on all pointer arithmetic
1852 Result.addNode(PointerArithmeticPointerTag, DynTypedNode::create(*Ptr));
1853 Result.addNode(PointerArithmeticTag, DynTypedNode::create(*BO));
1854 return true;
1855 }
1856
1857 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1858 bool IsRelatedToDecl,
1859 ASTContext &Ctx) const override {
1860 Handler.handleUnsafeOperation(PA, IsRelatedToDecl, Ctx);
1861 }
1862 SourceLocation getSourceLoc() const override { return PA->getBeginLoc(); }
1863
1864 DeclUseList getClaimedVarUseSites() const override {
1865 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ptr->IgnoreParenImpCasts())) {
1866 return {DRE};
1867 }
1868
1869 return {};
1870 }
1871
1872 SmallVector<const Expr *, 1> getUnsafePtrs() const override {
1873 return {Ptr->IgnoreParenImpCasts()};
1874 }
1875
1876 // FIXME: pointer adding zero should be fine
1877 // FIXME: this gadge will need a fix-it
1878};
1879
1880class SpanTwoParamConstructorGadget : public WarningGadget {
1881 static constexpr const char *const SpanTwoParamConstructorTag =
1882 "spanTwoParamConstructor";
1883 const CXXConstructExpr *Ctor; // the span constructor expression
1884
1885public:
1886 SpanTwoParamConstructorGadget(const MatchResult &Result)
1887 : WarningGadget(Kind::SpanTwoParamConstructor),
1888 Ctor(Result.getNodeAs<CXXConstructExpr>(SpanTwoParamConstructorTag)) {}
1889
1890 static bool classof(const Gadget *G) {
1891 return G->getKind() == Kind::SpanTwoParamConstructor;
1892 }
1893
1894 static bool matches(const CXXConstructExpr *CE, ASTContext &Ctx,
1896 const auto *CDecl = CE->getConstructor();
1897 const auto *CRecordDecl = CDecl->getParent();
1898 auto HasTwoParamSpanCtorDecl =
1899 CRecordDecl->isInStdNamespace() &&
1900 CDecl->getDeclName().getAsString() == "span" && CE->getNumArgs() == 2;
1901 if (!HasTwoParamSpanCtorDecl || isSafeTwoParamContainerConstruct(*CE, Ctx))
1902 return false;
1903 Result.addNode(SpanTwoParamConstructorTag, DynTypedNode::create(*CE));
1904 return true;
1905 }
1906
1907 static bool matches(const Stmt *S, ASTContext &Ctx,
1908 const UnsafeBufferUsageHandler *Handler,
1910 const auto *CE = dyn_cast<CXXConstructExpr>(S);
1911 if (!CE)
1912 return false;
1913 if (ignoreUnsafeBufferInContainer(*S, Handler))
1914 return false;
1915 return matches(CE, Ctx, Result);
1916 }
1917
1918 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1919 bool IsRelatedToDecl,
1920 ASTContext &Ctx) const override {
1921 Handler.handleUnsafeOperationInContainer(Ctor, IsRelatedToDecl, Ctx);
1922 }
1923 SourceLocation getSourceLoc() const override { return Ctor->getBeginLoc(); }
1924
1925 DeclUseList getClaimedVarUseSites() const override {
1926 // If the constructor call is of the form `std::span{var, n}`, `var` is
1927 // considered an unsafe variable.
1928 if (auto *DRE = dyn_cast<DeclRefExpr>(Ctor->getArg(0))) {
1929 if (isa<VarDecl>(DRE->getDecl()))
1930 return {DRE};
1931 }
1932 return {};
1933 }
1934
1935 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
1936};
1937
1938class StringViewTwoParamConstructorGadget : public WarningGadget {
1939 static constexpr const char *const StringViewTwoParamConstructorTag =
1940 "stringViewTwoParamConstructor";
1941 const CXXConstructExpr *Ctor; // the string_view constructor expression
1942
1943public:
1944 StringViewTwoParamConstructorGadget(const MatchResult &Result)
1945 : WarningGadget(Kind::StringViewTwoParamConstructor),
1946 Ctor(Result.getNodeAs<CXXConstructExpr>(
1947 StringViewTwoParamConstructorTag)) {}
1948
1949 static bool classof(const Gadget *G) {
1950 return G->getKind() == Kind::StringViewTwoParamConstructor;
1951 }
1952
1953 static bool matches(const CXXConstructExpr *CE, ASTContext &Ctx,
1955 const auto *CDecl = CE->getConstructor();
1956 const auto *CRecordDecl = CDecl->getParent();
1957
1958 // MATCH: std::basic_string_view
1959 bool IsStringView =
1960 CRecordDecl->isInStdNamespace() &&
1961 CDecl->getDeclName().getAsString() == "basic_string_view" &&
1962 CE->getNumArgs() == 2;
1963
1964 if (!IsStringView || isSafeStringViewTwoParamConstruct(*CE, Ctx))
1965 return false;
1966
1967 Result.addNode(StringViewTwoParamConstructorTag, DynTypedNode::create(*CE));
1968 return true;
1969 }
1970
1971 static bool matches(const Stmt *S, ASTContext &Ctx,
1972 const UnsafeBufferUsageHandler *Handler,
1974 const auto *CE = dyn_cast<CXXConstructExpr>(S);
1975 if (!CE)
1976 return false;
1977 if (ignoreUnsafeBufferInContainer(*S, Handler))
1978 return false;
1979 return matches(CE, Ctx, Result);
1980 }
1981
1982 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1983 bool IsRelatedToDecl,
1984 ASTContext &Ctx) const override {
1985 Handler.handleUnsafeOperationInStringView(Ctor, IsRelatedToDecl, Ctx);
1986 }
1987
1988 SourceLocation getSourceLoc() const override { return Ctor->getBeginLoc(); }
1989
1990 DeclUseList getClaimedVarUseSites() const override {
1991 // If the constructor call is of the form `std::string_view{var, n}`, `var`
1992 // is considered an unsafe variable.
1993 if (auto *DRE = dyn_cast<DeclRefExpr>(Ctor->getArg(0))) {
1994 if (isa<VarDecl>(DRE->getDecl()))
1995 return {DRE};
1996 }
1997 return {};
1998 }
1999
2000 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2001};
2002
2003/// A call of a constructor or factory function annotated with
2004/// `[[clang::unsafe_buffer_usage("container")]]` (or
2005/// `[[clang::unsafe_buffer_usage_in_container]]`). Evaluates whether the
2006/// arguments are safe via `isSafeTwoParamContainerConstruct` and emits a
2007/// diagnostic under `-Wunsafe-buffer-usage-in-container` when unsafe.
2008class UnsafeBufferUsageContainerAttrGadget : public WarningGadget {
2009 constexpr static const char *const OpTag = "container_attr_expr";
2010 const Expr *Op;
2011
2012public:
2013 UnsafeBufferUsageContainerAttrGadget(const MatchResult &Result)
2014 : WarningGadget(Kind::UnsafeBufferUsageContainerAttr),
2015 Op(Result.getNodeAs<Expr>(OpTag)) {}
2016
2017 static bool classof(const Gadget *G) {
2018 return G->getKind() == Kind::UnsafeBufferUsageContainerAttr;
2019 }
2020
2021 // Returns true iff `Callee` is annotated with
2022 // `[[clang::unsafe_buffer_usage("container")]]` and the arguments of `Node`
2023 // are not provably safe.
2024 template <typename CallOrConstructExpr>
2025 static bool isUnsafeContainerConstruction(const Decl *Callee,
2026 const CallOrConstructExpr &Node,
2027 ASTContext &Ctx) {
2028 if (!Callee)
2029 return false;
2030 const auto *Attr = Callee->getAttr<UnsafeBufferUsageAttr>();
2031 if (!Attr || Attr->getCategory() != "container")
2032 return false;
2033 return Node.getNumArgs() == 2 &&
2035 /*AllowDuckTypedContainers=*/true);
2036 }
2037
2038 static bool matches(const Stmt *S, ASTContext &Ctx,
2039 const UnsafeBufferUsageHandler *Handler,
2041 if (ignoreUnsafeBufferInContainer(*S, Handler))
2042 return false;
2043
2044 // S is a constructor call.
2045 if (const auto *CE = dyn_cast<CXXConstructExpr>(S)) {
2046 // std::span(ptr, size) ctor is handled by SpanTwoParamConstructorGadget.
2047 MatchResult Tmp;
2048 if (SpanTwoParamConstructorGadget::matches(CE, Ctx, Tmp))
2049 return false;
2050
2051 if (!isUnsafeContainerConstruction(CE->getConstructor(), *CE, Ctx))
2052 return false;
2053
2054 Result.addNode(OpTag, DynTypedNode::create(*CE));
2055 return true;
2056 }
2057 // S is a factory function call.
2058 if (const auto *Call = dyn_cast<CallExpr>(S)) {
2059 if (!isUnsafeContainerConstruction(Call->getDirectCallee(), *Call, Ctx))
2060 return false;
2061
2062 Result.addNode(OpTag, DynTypedNode::create(*Call));
2063 return true;
2064 }
2065 return false;
2066 }
2067
2068 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2069 bool IsRelatedToDecl,
2070 ASTContext &Ctx) const override {
2071 Handler.handleUnsafeOperationInContainer(Op, IsRelatedToDecl, Ctx);
2072 }
2073
2074 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2075
2076 DeclUseList getClaimedVarUseSites() const override {
2077 const Expr *Arg0 = nullptr;
2078
2079 if (const auto *CE = dyn_cast<CXXConstructExpr>(Op);
2080 CE && CE->getNumArgs() > 0)
2081 Arg0 = CE->getArg(0);
2082 else if (const auto *Call = dyn_cast<CallExpr>(Op);
2083 Call && Call->getNumArgs() > 0)
2084 Arg0 = Call->getArg(0);
2085
2086 if (Arg0)
2087 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg0->IgnoreParenImpCasts()))
2088 if (isa<VarDecl>(DRE->getDecl()))
2089 return {DRE};
2090
2091 return {};
2092 }
2093
2094 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2095};
2096
2097/// A pointer initialization expression of the form:
2098/// \code
2099/// int *p = q;
2100/// \endcode
2101class PointerInitGadget : public FixableGadget {
2102private:
2103 static constexpr const char *const PointerInitLHSTag = "ptrInitLHS";
2104 static constexpr const char *const PointerInitRHSTag = "ptrInitRHS";
2105 const VarDecl *PtrInitLHS; // the LHS pointer expression in `PI`
2106 const DeclRefExpr *PtrInitRHS; // the RHS pointer expression in `PI`
2107
2108public:
2109 PointerInitGadget(const MatchResult &Result)
2110 : FixableGadget(Kind::PointerInit),
2111 PtrInitLHS(Result.getNodeAs<VarDecl>(PointerInitLHSTag)),
2112 PtrInitRHS(Result.getNodeAs<DeclRefExpr>(PointerInitRHSTag)) {}
2113
2114 static bool classof(const Gadget *G) {
2115 return G->getKind() == Kind::PointerInit;
2116 }
2117
2118 static bool matches(const Stmt *S,
2119 llvm::SmallVectorImpl<MatchResult> &Results) {
2120 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
2121 if (!DS || !DS->isSingleDecl())
2122 return false;
2123 const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2124 if (!VD)
2125 return false;
2126 const Expr *Init = VD->getAnyInitializer();
2127 if (!Init)
2128 return false;
2129 const auto *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreImpCasts());
2130 if (!DRE || !hasPointerType(*DRE) || !isSupportedVariable(*DRE)) {
2131 return false;
2132 }
2133 MatchResult R;
2134 R.addNode(PointerInitLHSTag, DynTypedNode::create(*VD));
2135 R.addNode(PointerInitRHSTag, DynTypedNode::create(*DRE));
2136 Results.emplace_back(std::move(R));
2137 return true;
2138 }
2139
2140 virtual std::optional<FixItList>
2141 getFixits(const FixitStrategy &S) const override;
2142 SourceLocation getSourceLoc() const override {
2143 return PtrInitRHS->getBeginLoc();
2144 }
2145
2146 virtual DeclUseList getClaimedVarUseSites() const override {
2147 return DeclUseList{PtrInitRHS};
2148 }
2149
2150 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2151 getStrategyImplications() const override {
2152 return std::make_pair(PtrInitLHS, cast<VarDecl>(PtrInitRHS->getDecl()));
2153 }
2154};
2155
2156/// A pointer assignment expression of the form:
2157/// \code
2158/// p = q;
2159/// \endcode
2160/// where both `p` and `q` are pointers.
2161class PtrToPtrAssignmentGadget : public FixableGadget {
2162private:
2163 static constexpr const char *const PointerAssignLHSTag = "ptrLHS";
2164 static constexpr const char *const PointerAssignRHSTag = "ptrRHS";
2165 const DeclRefExpr *PtrLHS; // the LHS pointer expression in `PA`
2166 const DeclRefExpr *PtrRHS; // the RHS pointer expression in `PA`
2167
2168public:
2169 PtrToPtrAssignmentGadget(const MatchResult &Result)
2170 : FixableGadget(Kind::PtrToPtrAssignment),
2171 PtrLHS(Result.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
2172 PtrRHS(Result.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
2173
2174 static bool classof(const Gadget *G) {
2175 return G->getKind() == Kind::PtrToPtrAssignment;
2176 }
2177
2178 static bool matches(const Stmt *S,
2179 llvm::SmallVectorImpl<MatchResult> &Results) {
2180 size_t SizeBefore = Results.size();
2181 findStmtsInUnspecifiedUntypedContext(S, [&Results](const Stmt *S) {
2182 const auto *BO = dyn_cast<BinaryOperator>(S);
2183 if (!BO || BO->getOpcode() != BO_Assign)
2184 return;
2185 const auto *RHS = BO->getRHS()->IgnoreParenImpCasts();
2186 if (const auto *RHSRef = dyn_cast<DeclRefExpr>(RHS);
2187 !RHSRef || !hasPointerType(*RHSRef) ||
2188 !isSupportedVariable(*RHSRef)) {
2189 return;
2190 }
2191 const auto *LHS = BO->getLHS();
2192 if (const auto *LHSRef = dyn_cast<DeclRefExpr>(LHS);
2193 !LHSRef || !hasPointerType(*LHSRef) ||
2194 !isSupportedVariable(*LHSRef)) {
2195 return;
2196 }
2197 MatchResult R;
2198 R.addNode(PointerAssignLHSTag, DynTypedNode::create(*LHS));
2199 R.addNode(PointerAssignRHSTag, DynTypedNode::create(*RHS));
2200 Results.emplace_back(std::move(R));
2201 });
2202 return SizeBefore != Results.size();
2203 }
2204
2205 virtual std::optional<FixItList>
2206 getFixits(const FixitStrategy &S) const override;
2207 SourceLocation getSourceLoc() const override { return PtrLHS->getBeginLoc(); }
2208
2209 virtual DeclUseList getClaimedVarUseSites() const override {
2210 return DeclUseList{PtrLHS, PtrRHS};
2211 }
2212
2213 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2214 getStrategyImplications() const override {
2215 return std::make_pair(cast<VarDecl>(PtrLHS->getDecl()),
2216 cast<VarDecl>(PtrRHS->getDecl()));
2217 }
2218};
2219
2220/// An assignment expression of the form:
2221/// \code
2222/// ptr = array;
2223/// \endcode
2224/// where `p` is a pointer and `array` is a constant size array.
2225class CArrayToPtrAssignmentGadget : public FixableGadget {
2226private:
2227 static constexpr const char *const PointerAssignLHSTag = "ptrLHS";
2228 static constexpr const char *const PointerAssignRHSTag = "ptrRHS";
2229 const DeclRefExpr *PtrLHS; // the LHS pointer expression in `PA`
2230 const DeclRefExpr *PtrRHS; // the RHS pointer expression in `PA`
2231
2232public:
2233 CArrayToPtrAssignmentGadget(const MatchResult &Result)
2234 : FixableGadget(Kind::CArrayToPtrAssignment),
2235 PtrLHS(Result.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
2236 PtrRHS(Result.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
2237
2238 static bool classof(const Gadget *G) {
2239 return G->getKind() == Kind::CArrayToPtrAssignment;
2240 }
2241
2242 static bool matches(const Stmt *S,
2243 llvm::SmallVectorImpl<MatchResult> &Results) {
2244 size_t SizeBefore = Results.size();
2245 findStmtsInUnspecifiedUntypedContext(S, [&Results](const Stmt *S) {
2246 const auto *BO = dyn_cast<BinaryOperator>(S);
2247 if (!BO || BO->getOpcode() != BO_Assign)
2248 return;
2249 const auto *RHS = BO->getRHS()->IgnoreParenImpCasts();
2250 if (const auto *RHSRef = dyn_cast<DeclRefExpr>(RHS);
2251 !RHSRef ||
2252 !isa<ConstantArrayType>(RHSRef->getType().getCanonicalType()) ||
2253 !isSupportedVariable(*RHSRef)) {
2254 return;
2255 }
2256 const auto *LHS = BO->getLHS();
2257 if (const auto *LHSRef = dyn_cast<DeclRefExpr>(LHS);
2258 !LHSRef || !hasPointerType(*LHSRef) ||
2259 !isSupportedVariable(*LHSRef)) {
2260 return;
2261 }
2262 MatchResult R;
2263 R.addNode(PointerAssignLHSTag, DynTypedNode::create(*LHS));
2264 R.addNode(PointerAssignRHSTag, DynTypedNode::create(*RHS));
2265 Results.emplace_back(std::move(R));
2266 });
2267 return SizeBefore != Results.size();
2268 }
2269
2270 virtual std::optional<FixItList>
2271 getFixits(const FixitStrategy &S) const override;
2272 SourceLocation getSourceLoc() const override { return PtrLHS->getBeginLoc(); }
2273
2274 virtual DeclUseList getClaimedVarUseSites() const override {
2275 return DeclUseList{PtrLHS, PtrRHS};
2276 }
2277
2278 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2279 getStrategyImplications() const override {
2280 return {};
2281 }
2282};
2283
2284/// A call of a function or method that performs unchecked buffer operations
2285/// over one of its pointer parameters.
2286class UnsafeBufferUsageAttrGadget : public WarningGadget {
2287 constexpr static const char *const OpTag = "attr_expr";
2288 const Expr *Op;
2289
2290public:
2291 UnsafeBufferUsageAttrGadget(const MatchResult &Result)
2292 : WarningGadget(Kind::UnsafeBufferUsageAttr),
2293 Op(Result.getNodeAs<Expr>(OpTag)) {}
2294
2295 static bool classof(const Gadget *G) {
2296 return G->getKind() == Kind::UnsafeBufferUsageAttr;
2297 }
2298
2299 static bool matches(const Stmt *S, const ASTContext &Ctx,
2301 if (auto *CE = dyn_cast<CallExpr>(S)) {
2302 if (const auto *Callee = CE->getDirectCallee()) {
2303 if (const auto *Attr = Callee->getAttr<UnsafeBufferUsageAttr>()) {
2304 // Skip if this is annotated with a category (e.g.,
2305 // `[[clang::unsafe_buffer_usage("container")]]`) as that case is
2306 // handled by its category-specific gadget.
2307 if (!Attr->getCategory().empty())
2308 return false;
2309 Result.addNode(OpTag, DynTypedNode::create(*CE));
2310 return true;
2311 }
2312 }
2313 }
2314 if (auto *ME = dyn_cast<MemberExpr>(S)) {
2315 if (!isa<FieldDecl>(ME->getMemberDecl()))
2316 return false;
2317 if (const auto *Attr =
2318 ME->getMemberDecl()->getAttr<UnsafeBufferUsageAttr>()) {
2319 if (!Attr->getCategory().empty())
2320 return false;
2321 Result.addNode(OpTag, DynTypedNode::create(*ME));
2322 return true;
2323 }
2324 }
2325 return false;
2326 }
2327
2328 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2329 bool IsRelatedToDecl,
2330 ASTContext &Ctx) const override {
2331 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
2332 }
2333 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2334
2335 DeclUseList getClaimedVarUseSites() const override { return {}; }
2336
2337 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2338};
2339
2340/// A call of a constructor that performs unchecked buffer operations
2341/// over one of its pointer parameters, or constructs a class object that will
2342/// perform buffer operations that depend on the correctness of the parameters.
2343class UnsafeBufferUsageCtorAttrGadget : public WarningGadget {
2344 constexpr static const char *const OpTag = "cxx_construct_expr";
2345 const CXXConstructExpr *Op;
2346
2347public:
2348 UnsafeBufferUsageCtorAttrGadget(const MatchResult &Result)
2349 : WarningGadget(Kind::UnsafeBufferUsageCtorAttr),
2350 Op(Result.getNodeAs<CXXConstructExpr>(OpTag)) {}
2351
2352 static bool classof(const Gadget *G) {
2353 return G->getKind() == Kind::UnsafeBufferUsageCtorAttr;
2354 }
2355
2356 static bool matches(const Stmt *S, ASTContext &Ctx, MatchResult &Result) {
2357 const auto *CE = dyn_cast<CXXConstructExpr>(S);
2358 if (!CE)
2359 return false;
2360 const auto *Attr = CE->getConstructor()->getAttr<UnsafeBufferUsageAttr>();
2361 // Skip if this is annotated with a category (e.g.,
2362 // `[[clang::unsafe_buffer_usage("container")]]`) as that case is
2363 // handled by its category-specific gadget.
2364 if (!Attr || !Attr->getCategory().empty())
2365 return false;
2366 // std::span(ptr, size) ctor is handled by SpanTwoParamConstructorGadget.
2367 MatchResult Tmp;
2368 if (SpanTwoParamConstructorGadget::matches(CE, Ctx, Tmp))
2369 return false;
2370 Result.addNode(OpTag, DynTypedNode::create(*CE));
2371 return true;
2372 }
2373
2374 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2375 bool IsRelatedToDecl,
2376 ASTContext &Ctx) const override {
2377 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
2378 }
2379 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2380
2381 DeclUseList getClaimedVarUseSites() const override { return {}; }
2382
2383 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2384};
2385
2386// Warning gadget for unsafe invocation of span::data method.
2387// Triggers when the pointer returned by the invocation is immediately
2388// cast to a larger type.
2389
2390class DataInvocationGadget : public WarningGadget {
2391 constexpr static const char *const OpTag = "data_invocation_expr";
2392 const ExplicitCastExpr *Op;
2393
2394public:
2395 DataInvocationGadget(const MatchResult &Result)
2396 : WarningGadget(Kind::DataInvocation),
2397 Op(Result.getNodeAs<ExplicitCastExpr>(OpTag)) {}
2398
2399 static bool classof(const Gadget *G) {
2400 return G->getKind() == Kind::DataInvocation;
2401 }
2402
2403 static bool matches(const Stmt *S, const ASTContext &Ctx,
2405 auto *CE = dyn_cast<ExplicitCastExpr>(S);
2406 if (!CE)
2407 return false;
2408 for (auto *Child : CE->children()) {
2409 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Child);
2410 MCE && isDataFunction(MCE)) {
2411 Result.addNode(OpTag, DynTypedNode::create(*CE));
2412 return true;
2413 }
2414 if (auto *Paren = dyn_cast<ParenExpr>(Child)) {
2415 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Paren->getSubExpr());
2416 MCE && isDataFunction(MCE)) {
2417 Result.addNode(OpTag, DynTypedNode::create(*CE));
2418 return true;
2419 }
2420 }
2421 }
2422 return false;
2423 }
2424
2425 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2426 bool IsRelatedToDecl,
2427 ASTContext &Ctx) const override {
2428 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
2429 }
2430 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2431
2432 DeclUseList getClaimedVarUseSites() const override { return {}; }
2433
2434private:
2435 static bool isDataFunction(const CXXMemberCallExpr *call) {
2436 if (!call)
2437 return false;
2438 auto *callee = call->getDirectCallee();
2439 if (!callee || !isa<CXXMethodDecl>(callee))
2440 return false;
2441 auto *method = cast<CXXMethodDecl>(callee);
2442 if (method->getNameAsString() == "data" &&
2443 method->getParent()->isInStdNamespace() &&
2444 llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
2445 method->getParent()->getName()))
2446 return true;
2447 return false;
2448 }
2449
2450 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2451};
2452
2453class UnsafeLibcFunctionCallGadget : public WarningGadget {
2454 const CallExpr *const Call;
2455 const Expr *UnsafeArg = nullptr;
2456 constexpr static const char *const Tag = "UnsafeLibcFunctionCall";
2457 // Extra tags for additional information:
2458 constexpr static const char *const UnsafeSprintfTag =
2459 "UnsafeLibcFunctionCall_sprintf";
2460 constexpr static const char *const UnsafeSizedByTag =
2461 "UnsafeLibcFunctionCall_sized_by";
2462 constexpr static const char *const UnsafeStringTag =
2463 "UnsafeLibcFunctionCall_string";
2464 constexpr static const char *const UnsafeVaListTag =
2465 "UnsafeLibcFunctionCall_va_list";
2466
2467public:
2468 enum UnsafeKind {
2469 OTHERS = 0, // no specific information, the callee function is unsafe
2470 SPRINTF = 1, // never call `-sprintf`s, call `-snprintf`s instead.
2471 SIZED_BY =
2472 2, // the first two arguments of `snprintf` function have
2473 // "__sized_by" relation but they do not conform to safe patterns
2474 STRING = 3, // an argument is a pointer-to-char-as-string but does not
2475 // guarantee null-termination
2476 VA_LIST = 4, // one of the `-printf`s function that take va_list, which is
2477 // considered unsafe as it is not compile-time check
2478 FORMAT_ATTR = 8, // flag: the callee has the format attribute
2479 } WarnedFunKind = OTHERS;
2480 UnsafeLibcFunctionFamily Family = UnsafeLibcFunctionFamily::Other;
2481
2482 UnsafeLibcFunctionCallGadget(const MatchResult &Result)
2483 : WarningGadget(Kind::UnsafeLibcFunctionCall),
2484 Call(Result.getNodeAs<CallExpr>(Tag)) {
2485 if (Result.getNodeAs<Decl>(UnsafeSprintfTag))
2486 WarnedFunKind = SPRINTF;
2487 else if (auto *E = Result.getNodeAs<Expr>(UnsafeStringTag)) {
2488 WarnedFunKind = STRING;
2489 UnsafeArg = E;
2490 } else if (Result.getNodeAs<CallExpr>(UnsafeSizedByTag)) {
2491 WarnedFunKind = SIZED_BY;
2492 UnsafeArg = Call->getArg(0);
2493 } else if (Result.getNodeAs<Decl>(UnsafeVaListTag))
2494 WarnedFunKind = VA_LIST;
2495 // Only the predefined-name and memset matches leave `WarnedFunKind` at
2496 // `OTHERS`. The printf matches always set a kind.
2497 Family = WarnedFunKind != OTHERS
2498 ? UnsafeLibcFunctionFamily::Printf
2500 *Call->getDirectCallee());
2501 }
2502
2503 static bool matches(const Stmt *S, ASTContext &Ctx,
2504 const UnsafeBufferUsageHandler *Handler,
2506 const auto *CE = dyn_cast<CallExpr>(S);
2507 if (!CE)
2508 return false;
2509 const auto *FD = CE->getDirectCallee();
2510 if (!FD)
2511 return false;
2513 return false;
2514 // The check looks up every libc-call warning, so it runs after the cheaper
2515 // scope test.
2516 if (ignoreUnsafeLibcCall(Ctx, *S, Handler))
2517 return false;
2518 // If the call has a sole null-terminated argument, e.g., strlen,
2519 // printf, atoi, we consider it safe:
2520 if (CE->getNumArgs() == 1 && isNullTermPointer(CE->getArg(0), Ctx))
2521 return false;
2522
2523 const bool isSingleStringLiteralArg =
2524 CE->getNumArgs() == 1 &&
2526 if (!isSingleStringLiteralArg) {
2527 // (unless the call has a sole string literal argument):
2529 Result.addNode(Tag, DynTypedNode::create(*CE));
2530 return true;
2531 }
2532 if (libc_func_matchers::isUnsafeMemset(*CE, Ctx)) {
2533 Result.addNode(Tag, DynTypedNode::create(*CE));
2534 return true;
2535 }
2537 Result.addNode(Tag, DynTypedNode::create(*CE));
2538 Result.addNode(UnsafeVaListTag, DynTypedNode::create(*FD));
2539 return true;
2540 }
2542 Result.addNode(Tag, DynTypedNode::create(*CE));
2543 Result.addNode(UnsafeSprintfTag, DynTypedNode::create(*FD));
2544 return true;
2545 }
2546 }
2549 Result.addNode(Tag, DynTypedNode::create(*CE));
2550 Result.addNode(UnsafeSizedByTag, DynTypedNode::create(*CE));
2551 return true;
2552 }
2554 UnsafeStringTag)) {
2555 Result.addNode(Tag, DynTypedNode::create(*CE));
2556 return true;
2557 }
2558 }
2559 return false;
2560 }
2561
2562 const Stmt *getBaseStmt() const { return Call; }
2563
2564 SourceLocation getSourceLoc() const override { return Call->getBeginLoc(); }
2565
2566 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2567 bool IsRelatedToDecl,
2568 ASTContext &Ctx) const override {
2569 Handler.handleUnsafeLibcCall(Call, WarnedFunKind, Family, Ctx, UnsafeArg);
2570 }
2571
2572 DeclUseList getClaimedVarUseSites() const override { return {}; }
2573
2574 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2575};
2576
2577class UnsafeFormatAttributedFunctionCallGadget : public WarningGadget {
2578 const CallExpr *const Call;
2579 const Expr *UnsafeArg = nullptr;
2580 constexpr static const char *const Tag = "UnsafeFormatAttributedFunctionCall";
2581 constexpr static const char *const UnsafeStringTag =
2582 "UnsafeFormatAttributedFunctionCall_string";
2583
2584public:
2585 UnsafeFormatAttributedFunctionCallGadget(const MatchResult &Result)
2586 : WarningGadget(Kind::UnsafeLibcFunctionCall),
2587 Call(Result.getNodeAs<CallExpr>(Tag)),
2588 UnsafeArg(Result.getNodeAs<Expr>(UnsafeStringTag)) {}
2589
2590 static bool matches(const Stmt *S, ASTContext &Ctx,
2591 const UnsafeBufferUsageHandler *Handler,
2593 auto *CE = dyn_cast<CallExpr>(S);
2594 if (!CE || !CE->getDirectCallee())
2595 return false;
2596 const FunctionDecl *FD = CE->getDirectCallee();
2597 if (!FD)
2598 return false;
2599 if (ignoreUnsafeFormatAttrCall(Ctx, *S, Handler))
2600 return false;
2601
2602 const FormatAttr *Attr = nullptr;
2603 bool IsPrintf = false;
2604 bool AnyAttr = llvm::any_of(
2605 FD->specific_attrs<FormatAttr>(),
2606 [&Attr, &IsPrintf](const FormatAttr *FA) -> bool {
2607 if (const auto *II = FA->getType()) {
2608 if (II->getName() == "printf" || II->getName() == "scanf") {
2609 Attr = FA;
2610 IsPrintf = II->getName() == "printf";
2611 return true;
2612 }
2613 }
2614 return false;
2615 });
2616 const Expr *UnsafeArg;
2617
2618 if (!AnyAttr)
2619 return false;
2620 // Calls to libc functions belong to -Wunsafe-buffer-usage-in-libc-call.
2621 if (ignoreUnsafeLibcCall(Ctx, *S, Handler) &&
2623 return false;
2624
2625 // FormatAttribute indexes are 1-based:
2626 unsigned FmtIdx = Attr->getFormatIdx() - 1;
2627 std::optional<unsigned> FmtArgIdx = Attr->getFirstArg() - 1;
2628
2629 if (isa<CXXMemberCallExpr>(CE)) {
2630 // For CXX member calls, attribute parameters are specified as if there is
2631 // an implicit "this". The implicit "this" is invisible through CallExpr
2632 // `CE`. (What makes it even less ergonomic is that the
2633 // implicit "this" is visible through CallExpr `CE` for CXX operator
2634 // calls!)
2635 --FmtIdx;
2636 --*FmtArgIdx;
2637 } else if (CE->getStmtClass() != Stmt::CallExprClass &&
2639 return false; // Ignore unsupported CallExpr subclasses
2640 if (*FmtArgIdx >= CE->getNumArgs())
2641 // Format arguments are allowed to be absent when variadic parameter is
2642 // used. So we need to check if those arguments exist. Moreover, when
2643 // variadic parameter is NOT used, `Attr->getFirstArg()` could be an
2644 // out-of-bound value. E.g.,
2645 // clang does not complain about `__attribute__((__format__(__printf__, 2,
2646 // 99))) void f(int, char *);`.
2647 FmtArgIdx = std::nullopt;
2648
2649 if (AnyAttr && !IsPrintf && FmtArgIdx) {
2650 // For scanf-like functions, any format argument is considered unsafe:
2651 Result.addNode(Tag, DynTypedNode::create(*CE));
2652 return true;
2653 }
2654 // For printf-like functions:
2656 Ctx, CE, UnsafeArg, FmtIdx, FmtArgIdx)) {
2657 Result.addNode(Tag, DynTypedNode::create(*CE));
2658 Result.addNode(UnsafeStringTag, DynTypedNode::create(*UnsafeArg));
2659 return true;
2660 }
2661 return false;
2662 }
2663
2664 const Stmt *getBaseStmt() const { return Call; }
2665
2666 SourceLocation getSourceLoc() const override { return Call->getBeginLoc(); }
2667
2668 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2669 bool IsRelatedToDecl,
2670 ASTContext &Ctx) const override {
2671 if (UnsafeArg)
2672 Handler.handleUnsafeLibcCall(
2673 Call,
2674 UnsafeLibcFunctionCallGadget::UnsafeKind::STRING |
2675 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2676 UnsafeLibcFunctionFamily::Other, Ctx, UnsafeArg);
2677 else
2678 Handler.handleUnsafeLibcCall(
2679 Call,
2680 UnsafeLibcFunctionCallGadget::UnsafeKind::OTHERS |
2681 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2683 }
2684
2685 DeclUseList getClaimedVarUseSites() const override { return {}; }
2686
2687 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2688};
2689
2690// Represents expressions of the form `DRE[*]` in the Unspecified Lvalue
2691// Context (see `findStmtsInUnspecifiedLvalueContext`).
2692// Note here `[]` is the built-in subscript operator.
2693class ULCArraySubscriptGadget : public FixableGadget {
2694private:
2695 static constexpr const char *const ULCArraySubscriptTag =
2696 "ArraySubscriptUnderULC";
2697 const ArraySubscriptExpr *Node;
2698
2699public:
2700 ULCArraySubscriptGadget(const MatchResult &Result)
2701 : FixableGadget(Kind::ULCArraySubscript),
2702 Node(Result.getNodeAs<ArraySubscriptExpr>(ULCArraySubscriptTag)) {
2703 assert(Node != nullptr && "Expecting a non-null matching result");
2704 }
2705
2706 static bool classof(const Gadget *G) {
2707 return G->getKind() == Kind::ULCArraySubscript;
2708 }
2709
2710 static bool matches(const Stmt *S,
2711 llvm::SmallVectorImpl<MatchResult> &Results) {
2712 size_t SizeBefore = Results.size();
2713 findStmtsInUnspecifiedLvalueContext(S, [&Results](const Expr *E) {
2714 const auto *ASE = dyn_cast<ArraySubscriptExpr>(E);
2715 if (!ASE)
2716 return;
2717 const auto *DRE =
2718 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts());
2719 if (!DRE || !(hasPointerType(*DRE) || hasArrayType(*DRE)) ||
2720 !isSupportedVariable(*DRE))
2721 return;
2722 MatchResult R;
2723 R.addNode(ULCArraySubscriptTag, DynTypedNode::create(*ASE));
2724 Results.emplace_back(std::move(R));
2725 });
2726 return SizeBefore != Results.size();
2727 }
2728
2729 virtual std::optional<FixItList>
2730 getFixits(const FixitStrategy &S) const override;
2731 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2732
2733 virtual DeclUseList getClaimedVarUseSites() const override {
2734 if (const auto *DRE =
2735 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts())) {
2736 return {DRE};
2737 }
2738 return {};
2739 }
2740};
2741
2742// Fixable gadget to handle stand alone pointers of the form `UPC(DRE)` in the
2743// unspecified pointer context (findStmtsInUnspecifiedPointerContext). The
2744// gadget emits fixit of the form `UPC(DRE.data())`.
2745class UPCStandalonePointerGadget : public FixableGadget {
2746private:
2747 static constexpr const char *const DeclRefExprTag = "StandalonePointer";
2748 const DeclRefExpr *Node;
2749
2750public:
2751 UPCStandalonePointerGadget(const MatchResult &Result)
2752 : FixableGadget(Kind::UPCStandalonePointer),
2753 Node(Result.getNodeAs<DeclRefExpr>(DeclRefExprTag)) {
2754 assert(Node != nullptr && "Expecting a non-null matching result");
2755 }
2756
2757 static bool classof(const Gadget *G) {
2758 return G->getKind() == Kind::UPCStandalonePointer;
2759 }
2760
2761 static bool matches(const Stmt *S,
2762 llvm::SmallVectorImpl<MatchResult> &Results) {
2763 size_t SizeBefore = Results.size();
2764 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
2765 auto *E = dyn_cast<Expr>(S);
2766 if (!E)
2767 return;
2768 const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
2769 if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)) ||
2770 !isSupportedVariable(*DRE))
2771 return;
2772 MatchResult R;
2773 R.addNode(DeclRefExprTag, DynTypedNode::create(*DRE));
2774 Results.emplace_back(std::move(R));
2775 });
2776 return SizeBefore != Results.size();
2777 }
2778
2779 virtual std::optional<FixItList>
2780 getFixits(const FixitStrategy &S) const override;
2781 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2782
2783 virtual DeclUseList getClaimedVarUseSites() const override { return {Node}; }
2784};
2785
2786class PointerDereferenceGadget : public FixableGadget {
2787 static constexpr const char *const BaseDeclRefExprTag = "BaseDRE";
2788 static constexpr const char *const OperatorTag = "op";
2789
2790 const DeclRefExpr *BaseDeclRefExpr = nullptr;
2791 const UnaryOperator *Op = nullptr;
2792
2793public:
2794 PointerDereferenceGadget(const MatchResult &Result)
2795 : FixableGadget(Kind::PointerDereference),
2796 BaseDeclRefExpr(Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
2797 Op(Result.getNodeAs<UnaryOperator>(OperatorTag)) {}
2798
2799 static bool classof(const Gadget *G) {
2800 return G->getKind() == Kind::PointerDereference;
2801 }
2802
2803 static bool matches(const Stmt *S,
2804 llvm::SmallVectorImpl<MatchResult> &Results) {
2805 size_t SizeBefore = Results.size();
2806 findStmtsInUnspecifiedLvalueContext(S, [&Results](const Stmt *S) {
2807 const auto *UO = dyn_cast<UnaryOperator>(S);
2808 if (!UO || UO->getOpcode() != UO_Deref)
2809 return;
2810 const Expr *CE = UO->getSubExpr();
2811 if (!CE)
2812 return;
2813 CE = CE->IgnoreParenImpCasts();
2814 const auto *DRE = dyn_cast<DeclRefExpr>(CE);
2815 if (!DRE || !isSupportedVariable(*DRE))
2816 return;
2817 MatchResult R;
2818 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
2819 R.addNode(OperatorTag, DynTypedNode::create(*UO));
2820 Results.emplace_back(std::move(R));
2821 });
2822 return SizeBefore != Results.size();
2823 }
2824
2825 DeclUseList getClaimedVarUseSites() const override {
2826 return {BaseDeclRefExpr};
2827 }
2828
2829 virtual std::optional<FixItList>
2830 getFixits(const FixitStrategy &S) const override;
2831 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2832};
2833
2834// Represents expressions of the form `&DRE[any]` in the Unspecified Pointer
2835// Context (see `findStmtsInUnspecifiedPointerContext`).
2836// Note here `[]` is the built-in subscript operator.
2837class UPCAddressofArraySubscriptGadget : public FixableGadget {
2838private:
2839 static constexpr const char *const UPCAddressofArraySubscriptTag =
2840 "AddressofArraySubscriptUnderUPC";
2841 const UnaryOperator *Node; // the `&DRE[any]` node
2842
2843public:
2844 UPCAddressofArraySubscriptGadget(const MatchResult &Result)
2845 : FixableGadget(Kind::ULCArraySubscript),
2846 Node(Result.getNodeAs<UnaryOperator>(UPCAddressofArraySubscriptTag)) {
2847 assert(Node != nullptr && "Expecting a non-null matching result");
2848 }
2849
2850 static bool classof(const Gadget *G) {
2851 return G->getKind() == Kind::UPCAddressofArraySubscript;
2852 }
2853
2854 static bool matches(const Stmt *S,
2855 llvm::SmallVectorImpl<MatchResult> &Results) {
2856 size_t SizeBefore = Results.size();
2857 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
2858 auto *E = dyn_cast<Expr>(S);
2859 if (!E)
2860 return;
2861 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreImpCasts());
2862 if (!UO || UO->getOpcode() != UO_AddrOf)
2863 return;
2864 const auto *ASE = dyn_cast<ArraySubscriptExpr>(UO->getSubExpr());
2865 if (!ASE)
2866 return;
2867 const auto *DRE =
2868 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts());
2869 if (!DRE || !isSupportedVariable(*DRE))
2870 return;
2871 MatchResult R;
2872 R.addNode(UPCAddressofArraySubscriptTag, DynTypedNode::create(*UO));
2873 Results.emplace_back(std::move(R));
2874 });
2875 return SizeBefore != Results.size();
2876 }
2877
2878 virtual std::optional<FixItList>
2879 getFixits(const FixitStrategy &) const override;
2880 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2881
2882 virtual DeclUseList getClaimedVarUseSites() const override {
2883 const auto *ArraySubst = cast<ArraySubscriptExpr>(Node->getSubExpr());
2884 const auto *DRE =
2885 cast<DeclRefExpr>(ArraySubst->getBase()->IgnoreParenImpCasts());
2886 return {DRE};
2887 }
2888};
2889} // namespace
2890
2891namespace {
2892// An auxiliary tracking facility for the fixit analysis. It helps connect
2893// declarations to its uses and make sure we've covered all uses with our
2894// analysis before we try to fix the declaration.
2895class DeclUseTracker {
2896 using UseSetTy = llvm::SmallPtrSet<const DeclRefExpr *, 16>;
2897 using DefMapTy = llvm::DenseMap<const VarDecl *, const DeclStmt *>;
2898
2899 // Allocate on the heap for easier move.
2900 std::unique_ptr<UseSetTy> Uses{std::make_unique<UseSetTy>()};
2901 DefMapTy Defs{};
2902
2903public:
2904 DeclUseTracker() = default;
2905 DeclUseTracker(const DeclUseTracker &) = delete; // Let's avoid copies.
2906 DeclUseTracker &operator=(const DeclUseTracker &) = delete;
2907 DeclUseTracker(DeclUseTracker &&) = default;
2908 DeclUseTracker &operator=(DeclUseTracker &&) = default;
2909
2910 // Start tracking a freshly discovered DRE.
2911 void discoverUse(const DeclRefExpr *DRE) { Uses->insert(DRE); }
2912
2913 // Stop tracking the DRE as it's been fully figured out.
2914 void claimUse(const DeclRefExpr *DRE) {
2915 assert(Uses->count(DRE) &&
2916 "DRE not found or claimed by multiple matchers!");
2917 Uses->erase(DRE);
2918 }
2919
2920 // A variable is unclaimed if at least one use is unclaimed.
2921 bool hasUnclaimedUses(const VarDecl *VD) const {
2922 // FIXME: Can this be less linear? Maybe maintain a map from VDs to DREs?
2923 return any_of(*Uses, [VD](const DeclRefExpr *DRE) {
2924 return DRE->getDecl()->getCanonicalDecl() == VD->getCanonicalDecl();
2925 });
2926 }
2927
2928 UseSetTy getUnclaimedUses(const VarDecl *VD) const {
2929 UseSetTy ReturnSet;
2930 for (auto use : *Uses) {
2931 if (use->getDecl()->getCanonicalDecl() == VD->getCanonicalDecl()) {
2932 ReturnSet.insert(use);
2933 }
2934 }
2935 return ReturnSet;
2936 }
2937
2938 void discoverDecl(const DeclStmt *DS) {
2939 for (const Decl *D : DS->decls()) {
2940 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2941 // FIXME: Assertion temporarily disabled due to a bug in
2942 // ASTMatcher internal behavior in presence of GNU
2943 // statement-expressions. We need to properly investigate this
2944 // because it can screw up our algorithm in other ways.
2945 // assert(Defs.count(VD) == 0 && "Definition already discovered!");
2946 Defs[VD] = DS;
2947 }
2948 }
2949 }
2950
2951 const DeclStmt *lookupDecl(const VarDecl *VD) const {
2952 return Defs.lookup(VD);
2953 }
2954};
2955} // namespace
2956
2957// Representing a pointer type expression of the form `++Ptr` in an Unspecified
2958// Pointer Context (UPC):
2959class UPCPreIncrementGadget : public FixableGadget {
2960private:
2961 static constexpr const char *const UPCPreIncrementTag =
2962 "PointerPreIncrementUnderUPC";
2963 const UnaryOperator *Node; // the `++Ptr` node
2964
2965public:
2966 UPCPreIncrementGadget(const MatchResult &Result)
2967 : FixableGadget(Kind::UPCPreIncrement),
2968 Node(Result.getNodeAs<UnaryOperator>(UPCPreIncrementTag)) {
2969 assert(Node != nullptr && "Expecting a non-null matching result");
2970 }
2971
2972 static bool classof(const Gadget *G) {
2973 return G->getKind() == Kind::UPCPreIncrement;
2974 }
2975
2976 static bool matches(const Stmt *S,
2978 // Note here we match `++Ptr` for any expression `Ptr` of pointer type.
2979 // Although currently we can only provide fix-its when `Ptr` is a DRE, we
2980 // can have the matcher be general, so long as `getClaimedVarUseSites` does
2981 // things right.
2982 size_t SizeBefore = Results.size();
2983 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
2984 auto *E = dyn_cast<Expr>(S);
2985 if (!E)
2986 return;
2987 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreImpCasts());
2988 if (!UO || UO->getOpcode() != UO_PreInc)
2989 return;
2990 const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
2991 if (!DRE || !isSupportedVariable(*DRE))
2992 return;
2993 MatchResult R;
2994 R.addNode(UPCPreIncrementTag, DynTypedNode::create(*UO));
2995 Results.emplace_back(std::move(R));
2996 });
2997 return SizeBefore != Results.size();
2998 }
2999
3000 virtual std::optional<FixItList>
3001 getFixits(const FixitStrategy &S) const override;
3002 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
3003
3004 virtual DeclUseList getClaimedVarUseSites() const override {
3005 return {dyn_cast<DeclRefExpr>(Node->getSubExpr())};
3006 }
3007};
3008
3009// Representing a pointer type expression of the form `Ptr += n` in an
3010// Unspecified Untyped Context (UUC):
3011class UUCAddAssignGadget : public FixableGadget {
3012private:
3013 static constexpr const char *const UUCAddAssignTag =
3014 "PointerAddAssignUnderUUC";
3015 static constexpr const char *const OffsetTag = "Offset";
3016
3017 const BinaryOperator *Node; // the `Ptr += n` node
3018 const Expr *Offset = nullptr;
3019
3020public:
3021 UUCAddAssignGadget(const MatchResult &Result)
3022 : FixableGadget(Kind::UUCAddAssign),
3023 Node(Result.getNodeAs<BinaryOperator>(UUCAddAssignTag)),
3024 Offset(Result.getNodeAs<Expr>(OffsetTag)) {
3025 assert(Node != nullptr && "Expecting a non-null matching result");
3026 }
3027
3028 static bool classof(const Gadget *G) {
3029 return G->getKind() == Kind::UUCAddAssign;
3030 }
3031
3032 static bool matches(const Stmt *S,
3034 size_t SizeBefore = Results.size();
3035 findStmtsInUnspecifiedUntypedContext(S, [&Results](const Stmt *S) {
3036 const auto *E = dyn_cast<Expr>(S);
3037 if (!E)
3038 return;
3039 const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreImpCasts());
3040 if (!BO || BO->getOpcode() != BO_AddAssign)
3041 return;
3042 const auto *DRE = dyn_cast<DeclRefExpr>(BO->getLHS());
3043 if (!DRE || !hasPointerType(*DRE) || !isSupportedVariable(*DRE))
3044 return;
3045 MatchResult R;
3046 R.addNode(UUCAddAssignTag, DynTypedNode::create(*BO));
3047 R.addNode(OffsetTag, DynTypedNode::create(*BO->getRHS()));
3048 Results.emplace_back(std::move(R));
3049 });
3050 return SizeBefore != Results.size();
3051 }
3052
3053 virtual std::optional<FixItList>
3054 getFixits(const FixitStrategy &S) const override;
3055 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
3056
3057 virtual DeclUseList getClaimedVarUseSites() const override {
3058 return {dyn_cast<DeclRefExpr>(Node->getLHS())};
3059 }
3060};
3061
3062// Representing a fixable expression of the form `*(ptr + 123)` or `*(123 +
3063// ptr)`:
3064class DerefSimplePtrArithFixableGadget : public FixableGadget {
3065 static constexpr const char *const BaseDeclRefExprTag = "BaseDRE";
3066 static constexpr const char *const DerefOpTag = "DerefOp";
3067 static constexpr const char *const AddOpTag = "AddOp";
3068 static constexpr const char *const OffsetTag = "Offset";
3069
3070 const DeclRefExpr *BaseDeclRefExpr = nullptr;
3071 const UnaryOperator *DerefOp = nullptr;
3072 const BinaryOperator *AddOp = nullptr;
3073 const IntegerLiteral *Offset = nullptr;
3074
3075public:
3077 : FixableGadget(Kind::DerefSimplePtrArithFixable),
3078 BaseDeclRefExpr(Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
3079 DerefOp(Result.getNodeAs<UnaryOperator>(DerefOpTag)),
3080 AddOp(Result.getNodeAs<BinaryOperator>(AddOpTag)),
3081 Offset(Result.getNodeAs<IntegerLiteral>(OffsetTag)) {}
3082
3083 static bool matches(const Stmt *S,
3085 auto IsPtr = [](const Expr *E, MatchResult &R) {
3086 if (!E || !hasPointerType(*E))
3087 return false;
3088 const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreImpCasts());
3089 if (!DRE || !isSupportedVariable(*DRE))
3090 return false;
3091 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
3092 return true;
3093 };
3094 const auto IsPlusOverPtrAndInteger = [&IsPtr](const Expr *E,
3095 MatchResult &R) {
3096 const auto *BO = dyn_cast<BinaryOperator>(E);
3097 if (!BO || BO->getOpcode() != BO_Add)
3098 return false;
3099
3100 const auto *LHS = BO->getLHS();
3101 const auto *RHS = BO->getRHS();
3102 if (isa<IntegerLiteral>(RHS) && IsPtr(LHS, R)) {
3103 R.addNode(OffsetTag, DynTypedNode::create(*RHS));
3104 R.addNode(AddOpTag, DynTypedNode::create(*BO));
3105 return true;
3106 }
3107 if (isa<IntegerLiteral>(LHS) && IsPtr(RHS, R)) {
3108 R.addNode(OffsetTag, DynTypedNode::create(*LHS));
3109 R.addNode(AddOpTag, DynTypedNode::create(*BO));
3110 return true;
3111 }
3112 return false;
3113 };
3114 size_t SizeBefore = Results.size();
3115 const auto InnerMatcher = [&IsPlusOverPtrAndInteger,
3116 &Results](const Expr *E) {
3117 const auto *UO = dyn_cast<UnaryOperator>(E);
3118 if (!UO || UO->getOpcode() != UO_Deref)
3119 return;
3120
3121 const auto *Operand = UO->getSubExpr()->IgnoreParens();
3122 MatchResult R;
3123 if (IsPlusOverPtrAndInteger(Operand, R)) {
3124 R.addNode(DerefOpTag, DynTypedNode::create(*UO));
3125 Results.emplace_back(std::move(R));
3126 }
3127 };
3128 findStmtsInUnspecifiedLvalueContext(S, InnerMatcher);
3129 return SizeBefore != Results.size();
3130 }
3131
3132 virtual std::optional<FixItList>
3133 getFixits(const FixitStrategy &s) const final;
3134 SourceLocation getSourceLoc() const override {
3135 return DerefOp->getBeginLoc();
3136 }
3137
3138 virtual DeclUseList getClaimedVarUseSites() const final {
3139 return {BaseDeclRefExpr};
3140 }
3141};
3142
3143class WarningGadgetMatcher : public FastMatcher {
3144
3145public:
3146 WarningGadgetMatcher(WarningGadgetList &WarningGadgets)
3147 : WarningGadgets(WarningGadgets) {}
3148
3149 bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
3150 const UnsafeBufferUsageHandler &Handler) override {
3151 const Stmt *S = DynNode.get<Stmt>();
3152 if (!S)
3153 return false;
3154
3155 MatchResult Result;
3156#define WARNING_GADGET(name) \
3157 if (name##Gadget::matches(S, Ctx, Result) && \
3158 notInSafeBufferOptOut(*S, &Handler)) { \
3159 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3160 return true; \
3161 }
3162#define WARNING_OPTIONAL_GADGET(name) \
3163 if (name##Gadget::matches(S, Ctx, &Handler, Result) && \
3164 notInSafeBufferOptOut(*S, &Handler)) { \
3165 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3166 return true; \
3167 }
3168#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3169 return false;
3170 }
3171
3172private:
3173 WarningGadgetList &WarningGadgets;
3174};
3175
3176class FixableGadgetMatcher : public FastMatcher {
3177
3178public:
3179 FixableGadgetMatcher(FixableGadgetList &FixableGadgets,
3180 DeclUseTracker &Tracker)
3181 : FixableGadgets(FixableGadgets), Tracker(Tracker) {}
3182
3183 bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
3184 const UnsafeBufferUsageHandler &Handler) override {
3185 bool matchFound = false;
3186 const Stmt *S = DynNode.get<Stmt>();
3187 if (!S) {
3188 return matchFound;
3189 }
3190
3192#define FIXABLE_GADGET(name) \
3193 if (name##Gadget::matches(S, Results)) { \
3194 for (const auto &R : Results) { \
3195 FixableGadgets.push_back(std::make_unique<name##Gadget>(R)); \
3196 matchFound = true; \
3197 } \
3198 Results = {}; \
3199 }
3200#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3201 // In parallel, match all DeclRefExprs so that to find out
3202 // whether there are any uncovered by gadgets.
3203 if (auto *DRE = findDeclRefExpr(S); DRE) {
3204 Tracker.discoverUse(DRE);
3205 matchFound = true;
3206 }
3207 // Also match DeclStmts because we'll need them when fixing
3208 // their underlying VarDecls that otherwise don't have
3209 // any backreferences to DeclStmts.
3210 if (auto *DS = findDeclStmt(S); DS) {
3211 Tracker.discoverDecl(DS);
3212 matchFound = true;
3213 }
3214 return matchFound;
3215 }
3216
3217private:
3218 const DeclRefExpr *findDeclRefExpr(const Stmt *S) {
3219 const auto *DRE = dyn_cast<DeclRefExpr>(S);
3220 if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)))
3221 return nullptr;
3222 const Decl *D = DRE->getDecl();
3223 if (!D || (!isa<VarDecl>(D) && !isa<BindingDecl>(D)))
3224 return nullptr;
3225 return DRE;
3226 }
3227 const DeclStmt *findDeclStmt(const Stmt *S) {
3228 const auto *DS = dyn_cast<DeclStmt>(S);
3229 if (!DS)
3230 return nullptr;
3231 return DS;
3232 }
3233 FixableGadgetList &FixableGadgets;
3234 DeclUseTracker &Tracker;
3235};
3236
3237// Scan the function and return a list of gadgets found with provided kits.
3238static void findGadgets(const Stmt *S, ASTContext &Ctx,
3239 const UnsafeBufferUsageHandler &Handler,
3240 bool EmitSuggestions, FixableGadgetList &FixableGadgets,
3241 WarningGadgetList &WarningGadgets,
3242 DeclUseTracker &Tracker) {
3243 WarningGadgetMatcher WMatcher{WarningGadgets};
3244 forEachDescendantEvaluatedStmt(S, Ctx, Handler, WMatcher);
3245 if (EmitSuggestions) {
3246 FixableGadgetMatcher FMatcher{FixableGadgets, Tracker};
3247 forEachDescendantStmt(S, Ctx, Handler, FMatcher);
3248 }
3249}
3250
3251// Compares AST nodes by source locations.
3252template <typename NodeTy> struct CompareNode {
3253 bool operator()(const NodeTy *N1, const NodeTy *N2) const {
3254 return N1->getBeginLoc().getRawEncoding() <
3255 N2->getBeginLoc().getRawEncoding();
3256 }
3257};
3258
3259// Populate `Stmts` with the body/initializer Stmt of `D`, if `D` is one of the
3260// followings:
3261// VarDecl
3262// FieldDecl
3263// FunctionDecl
3264// BlockDecl
3265// ObjCMethodDecl
3267 const Decl *D) {
3268 auto AddStmt = [&Stmts](const Stmt *S) {
3269 if (S)
3270 Stmts.push_back(S);
3271 };
3272 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3273 AddStmt(FD->getBody());
3274 for (const auto *PD : FD->parameters())
3275 if (PD->hasDefaultArg() && !PD->hasUninstantiatedDefaultArg())
3276 AddStmt(PD->getDefaultArg());
3277 if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(FD))
3278 llvm::append_range(
3279 Stmts, llvm::map_range(CtorD->inits(),
3280 std::mem_fn(&CXXCtorInitializer::getInit)));
3281 } else if (isa<BlockDecl>(D) || isa<ObjCMethodDecl>(D)) {
3282 AddStmt(D->getBody());
3283 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3284 AddStmt(VD->getInit()); // FIXME: default arg for ParmVarDecl?
3285 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3286 AddStmt(FD->getInClassInitializer());
3287 }
3288}
3289
3291 std::map<const VarDecl *, std::set<const WarningGadget *>,
3292 // To keep keys sorted by their locations in the map so that the
3293 // order is deterministic:
3296 // These Gadgets are not related to pointer variables (e. g. temporaries).
3298};
3299
3300static WarningGadgetSets
3301groupWarningGadgetsByVar(const WarningGadgetList &AllUnsafeOperations) {
3302 WarningGadgetSets result;
3303 // If some gadgets cover more than one
3304 // variable, they'll appear more than once in the map.
3305 for (auto &G : AllUnsafeOperations) {
3306 DeclUseList ClaimedVarUseSites = G->getClaimedVarUseSites();
3307
3308 bool AssociatedWithVarDecl = false;
3309 for (const DeclRefExpr *DRE : ClaimedVarUseSites) {
3310 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3311 result.byVar[VD].insert(G.get());
3312 AssociatedWithVarDecl = true;
3313 }
3314 }
3315
3316 if (!AssociatedWithVarDecl) {
3317 result.noVar.push_back(G.get());
3318 continue;
3319 }
3320 }
3321 return result;
3322}
3323
3325 std::map<const VarDecl *, std::set<const FixableGadget *>,
3326 // To keep keys sorted by their locations in the map so that the
3327 // order is deterministic:
3330};
3331
3332static FixableGadgetSets
3333groupFixablesByVar(FixableGadgetList &&AllFixableOperations) {
3334 FixableGadgetSets FixablesForUnsafeVars;
3335 for (auto &F : AllFixableOperations) {
3336 DeclUseList DREs = F->getClaimedVarUseSites();
3337
3338 for (const DeclRefExpr *DRE : DREs) {
3339 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3340 FixablesForUnsafeVars.byVar[VD].insert(F.get());
3341 }
3342 }
3343 }
3344 return FixablesForUnsafeVars;
3345}
3346
3348 const SourceManager &SM) {
3349 // A simple interval overlap detection algorithm. Sorts all ranges by their
3350 // begin location then finds the first overlap in one pass.
3351 std::vector<const FixItHint *> All; // a copy of `FixIts`
3352
3353 for (const FixItHint &H : FixIts)
3354 All.push_back(&H);
3355 std::sort(All.begin(), All.end(),
3356 [&SM](const FixItHint *H1, const FixItHint *H2) {
3357 return SM.isBeforeInTranslationUnit(H1->RemoveRange.getBegin(),
3358 H2->RemoveRange.getBegin());
3359 });
3360
3361 const FixItHint *CurrHint = nullptr;
3362
3363 for (const FixItHint *Hint : All) {
3364 if (!CurrHint ||
3366 Hint->RemoveRange.getBegin())) {
3367 // Either to initialize `CurrHint` or `CurrHint` does not
3368 // overlap with `Hint`:
3369 CurrHint = Hint;
3370 } else
3371 // In case `Hint` overlaps the `CurrHint`, we found at least one
3372 // conflict:
3373 return true;
3374 }
3375 return false;
3376}
3377
3378std::optional<FixItList>
3379PtrToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
3380 const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
3381 const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
3382 switch (S.lookup(LeftVD)) {
3384 if (S.lookup(RightVD) == FixitStrategy::Kind::Span)
3385 return FixItList{};
3386 return std::nullopt;
3388 return std::nullopt;
3391 return std::nullopt;
3393 llvm_unreachable("unsupported strategies for FixableGadgets");
3394 }
3395 return std::nullopt;
3396}
3397
3398/// \returns fixit that adds .data() call after \DRE.
3399static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
3400 const DeclRefExpr *DRE);
3401
3402std::optional<FixItList>
3403CArrayToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
3404 const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
3405 const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
3406 // TLDR: Implementing fixits for non-Wontfix strategy on both LHS and RHS is
3407 // non-trivial.
3408 //
3409 // CArrayToPtrAssignmentGadget doesn't have strategy implications because
3410 // constant size array propagates its bounds. Because of that LHS and RHS are
3411 // addressed by two different fixits.
3412 //
3413 // At the same time FixitStrategy S doesn't reflect what group a fixit belongs
3414 // to and can't be generally relied on in multi-variable Fixables!
3415 //
3416 // E. g. If an instance of this gadget is fixing variable on LHS then the
3417 // variable on RHS is fixed by a different fixit and its strategy for LHS
3418 // fixit is as if Wontfix.
3419 //
3420 // The only exception is Wontfix strategy for a given variable as that is
3421 // valid for any fixit produced for the given input source code.
3422 if (S.lookup(LeftVD) == FixitStrategy::Kind::Span) {
3423 if (S.lookup(RightVD) == FixitStrategy::Kind::Wontfix) {
3424 return FixItList{};
3425 }
3426 } else if (S.lookup(LeftVD) == FixitStrategy::Kind::Wontfix) {
3427 if (S.lookup(RightVD) == FixitStrategy::Kind::Array) {
3428 return createDataFixit(RightVD->getASTContext(), PtrRHS);
3429 }
3430 }
3431 return std::nullopt;
3432}
3433
3434std::optional<FixItList>
3435PointerInitGadget::getFixits(const FixitStrategy &S) const {
3436 const auto *LeftVD = PtrInitLHS;
3437 const auto *RightVD = cast<VarDecl>(PtrInitRHS->getDecl());
3438 switch (S.lookup(LeftVD)) {
3439 case FixitStrategy::Kind::Span:
3440 if (S.lookup(RightVD) == FixitStrategy::Kind::Span)
3441 return FixItList{};
3442 return std::nullopt;
3443 case FixitStrategy::Kind::Wontfix:
3444 return std::nullopt;
3445 case FixitStrategy::Kind::Iterator:
3446 case FixitStrategy::Kind::Array:
3447 return std::nullopt;
3448 case FixitStrategy::Kind::Vector:
3449 llvm_unreachable("unsupported strategies for FixableGadgets");
3450 }
3451 return std::nullopt;
3452}
3453
3454static bool isNonNegativeIntegerExpr(const Expr *Expr, const VarDecl *VD,
3455 const ASTContext &Ctx) {
3456 if (auto ConstVal = Expr->getIntegerConstantExpr(Ctx)) {
3457 if (ConstVal->isNegative())
3458 return false;
3459 } else if (!Expr->getType()->isUnsignedIntegerType())
3460 return false;
3461 return true;
3462}
3463
3464std::optional<FixItList>
3465ULCArraySubscriptGadget::getFixits(const FixitStrategy &S) const {
3466 if (const auto *DRE =
3467 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts()))
3468 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3469 switch (S.lookup(VD)) {
3470 case FixitStrategy::Kind::Span: {
3471
3472 // If the index has a negative constant value, we give up as no valid
3473 // fix-it can be generated:
3474 const ASTContext &Ctx = // FIXME: we need ASTContext to be passed in!
3475 VD->getASTContext();
3476 if (!isNonNegativeIntegerExpr(Node->getIdx(), VD, Ctx))
3477 return std::nullopt;
3478 // no-op is a good fix-it, otherwise
3479 return FixItList{};
3480 }
3481 case FixitStrategy::Kind::Array:
3482 return FixItList{};
3483 case FixitStrategy::Kind::Wontfix:
3484 case FixitStrategy::Kind::Iterator:
3485 case FixitStrategy::Kind::Vector:
3486 llvm_unreachable("unsupported strategies for FixableGadgets");
3487 }
3488 }
3489 return std::nullopt;
3490}
3491
3492static std::optional<FixItList> // forward declaration
3493fixUPCAddressofArraySubscriptWithSpan(const UnaryOperator *Node);
3494
3495std::optional<FixItList>
3496UPCAddressofArraySubscriptGadget::getFixits(const FixitStrategy &S) const {
3497 auto DREs = getClaimedVarUseSites();
3498 const auto *VD = cast<VarDecl>(DREs.front()->getDecl());
3499
3500 switch (S.lookup(VD)) {
3501 case FixitStrategy::Kind::Span:
3503 case FixitStrategy::Kind::Wontfix:
3504 case FixitStrategy::Kind::Iterator:
3505 case FixitStrategy::Kind::Array:
3506 return std::nullopt;
3507 case FixitStrategy::Kind::Vector:
3508 llvm_unreachable("unsupported strategies for FixableGadgets");
3509 }
3510 return std::nullopt; // something went wrong, no fix-it
3511}
3512
3513// FIXME: this function should be customizable through format
3514static StringRef getEndOfLine() {
3515 static const char *const EOL = "\n";
3516 return EOL;
3517}
3518
3519// Returns the text indicating that the user needs to provide input there:
3520static std::string
3521getUserFillPlaceHolder(StringRef HintTextToUser = "placeholder") {
3522 std::string s = std::string("<# ");
3523 s += HintTextToUser;
3524 s += " #>";
3525 return s;
3526}
3527
3528// Return the source location of the last character of the AST `Node`.
3529template <typename NodeTy>
3530static std::optional<SourceLocation>
3531getEndCharLoc(const NodeTy *Node, const SourceManager &SM,
3532 const LangOptions &LangOpts) {
3533 if (unsigned TkLen =
3534 Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts)) {
3535 SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
3536
3537 if (Loc.isValid())
3538 return Loc;
3539 }
3540 return std::nullopt;
3541}
3542
3543// We cannot fix a variable declaration if it has some other specifiers than the
3544// type specifier. Because the source ranges of those specifiers could overlap
3545// with the source range that is being replaced using fix-its. Especially when
3546// we often cannot obtain accurate source ranges of cv-qualified type
3547// specifiers.
3548// FIXME: also deal with type attributes
3549static bool hasUnsupportedSpecifiers(const VarDecl *VD,
3550 const SourceManager &SM) {
3551 // AttrRangeOverlapping: true if at least one attribute of `VD` overlaps the
3552 // source range of `VD`:
3553 bool AttrRangeOverlapping = llvm::any_of(VD->attrs(), [&](Attr *At) -> bool {
3554 return !(SM.isBeforeInTranslationUnit(At->getRange().getEnd(),
3555 VD->getBeginLoc())) &&
3556 !(SM.isBeforeInTranslationUnit(VD->getEndLoc(),
3557 At->getRange().getBegin()));
3558 });
3559 return VD->isInlineSpecified() || VD->isConstexpr() ||
3561 AttrRangeOverlapping;
3562}
3563
3564// Returns the `SourceRange` of `D`. The reason why this function exists is
3565// that `D->getSourceRange()` may return a range where the end location is the
3566// starting location of the last token. The end location of the source range
3567// returned by this function is the last location of the last token.
3569 const SourceManager &SM,
3570 const LangOptions &LangOpts) {
3571 SourceLocation Begin = D->getBeginLoc();
3573 End = // `D->getEndLoc` should always return the starting location of the
3574 // last token, so we should get the end of the token
3575 Lexer::getLocForEndOfToken(D->getEndLoc(), 0, SM, LangOpts);
3576
3577 return SourceRange(Begin, End);
3578}
3579
3580// Returns the text of the name (with qualifiers) of a `FunctionDecl`.
3581static std::optional<StringRef> getFunNameText(const FunctionDecl *FD,
3582 const SourceManager &SM,
3583 const LangOptions &LangOpts) {
3584 SourceLocation BeginLoc = FD->getQualifier()
3586 : FD->getNameInfo().getBeginLoc();
3587 // Note that `FD->getNameInfo().getEndLoc()` returns the begin location of the
3588 // last token:
3590 FD->getNameInfo().getEndLoc(), 0, SM, LangOpts);
3591 SourceRange NameRange{BeginLoc, EndLoc};
3592
3593 return getRangeText(NameRange, SM, LangOpts);
3594}
3595
3596// Returns the text representing a `std::span` type where the element type is
3597// represented by `EltTyText`.
3598//
3599// Note the optional parameter `Qualifiers`: one needs to pass qualifiers
3600// explicitly if the element type needs to be qualified.
3601static std::string
3602getSpanTypeText(StringRef EltTyText,
3603 std::optional<Qualifiers> Quals = std::nullopt) {
3604 const char *const SpanOpen = "std::span<";
3605
3606 if (Quals)
3607 return SpanOpen + EltTyText.str() + ' ' + Quals->getAsString() + '>';
3608 return SpanOpen + EltTyText.str() + '>';
3609}
3610
3611std::optional<FixItList>
3613 const VarDecl *VD = dyn_cast<VarDecl>(BaseDeclRefExpr->getDecl());
3614
3615 if (VD && s.lookup(VD) == FixitStrategy::Kind::Span) {
3616 ASTContext &Ctx = VD->getASTContext();
3617 // std::span can't represent elements before its begin()
3618 if (auto ConstVal = Offset->getIntegerConstantExpr(Ctx))
3619 if (ConstVal->isNegative())
3620 return std::nullopt;
3621
3622 // note that the expr may (oddly) has multiple layers of parens
3623 // example:
3624 // *((..(pointer + 123)..))
3625 // goal:
3626 // pointer[123]
3627 // Fix-It:
3628 // remove '*('
3629 // replace ' + ' with '['
3630 // replace ')' with ']'
3631
3632 // example:
3633 // *((..(123 + pointer)..))
3634 // goal:
3635 // 123[pointer]
3636 // Fix-It:
3637 // remove '*('
3638 // replace ' + ' with '['
3639 // replace ')' with ']'
3640
3641 const Expr *LHS = AddOp->getLHS(), *RHS = AddOp->getRHS();
3642 const SourceManager &SM = Ctx.getSourceManager();
3643 const LangOptions &LangOpts = Ctx.getLangOpts();
3644 CharSourceRange StarWithTrailWhitespace =
3645 clang::CharSourceRange::getCharRange(DerefOp->getOperatorLoc(),
3646 LHS->getBeginLoc());
3647
3648 std::optional<SourceLocation> LHSLocation = getPastLoc(LHS, SM, LangOpts);
3649 if (!LHSLocation)
3650 return std::nullopt;
3651
3652 CharSourceRange PlusWithSurroundingWhitespace =
3653 clang::CharSourceRange::getCharRange(*LHSLocation, RHS->getBeginLoc());
3654
3655 std::optional<SourceLocation> AddOpLocation =
3656 getPastLoc(AddOp, SM, LangOpts);
3657 std::optional<SourceLocation> DerefOpLocation =
3658 getPastLoc(DerefOp, SM, LangOpts);
3659
3660 if (!AddOpLocation || !DerefOpLocation)
3661 return std::nullopt;
3662
3663 CharSourceRange ClosingParenWithPrecWhitespace =
3664 clang::CharSourceRange::getCharRange(*AddOpLocation, *DerefOpLocation);
3665
3666 return FixItList{
3667 {FixItHint::CreateRemoval(StarWithTrailWhitespace),
3668 FixItHint::CreateReplacement(PlusWithSurroundingWhitespace, "["),
3669 FixItHint::CreateReplacement(ClosingParenWithPrecWhitespace, "]")}};
3670 }
3671 return std::nullopt; // something wrong or unsupported, give up
3672}
3673
3674std::optional<FixItList>
3675PointerDereferenceGadget::getFixits(const FixitStrategy &S) const {
3676 const VarDecl *VD = cast<VarDecl>(BaseDeclRefExpr->getDecl());
3677 switch (S.lookup(VD)) {
3679 ASTContext &Ctx = VD->getASTContext();
3680 SourceManager &SM = Ctx.getSourceManager();
3681 // Required changes: *(ptr); => (ptr[0]); and *ptr; => ptr[0]
3682 // Deletes the *operand
3684 Op->getBeginLoc(), Op->getBeginLoc().getLocWithOffset(1));
3685 // Inserts the [0]
3686 if (auto LocPastOperand =
3687 getPastLoc(BaseDeclRefExpr, SM, Ctx.getLangOpts())) {
3688 return FixItList{{FixItHint::CreateRemoval(derefRange),
3689 FixItHint::CreateInsertion(*LocPastOperand, "[0]")}};
3690 }
3691 break;
3692 }
3693 case FixitStrategy::Kind::Iterator:
3694 case FixitStrategy::Kind::Array:
3695 return std::nullopt;
3696 case FixitStrategy::Kind::Vector:
3697 llvm_unreachable("FixitStrategy not implemented yet!");
3698 case FixitStrategy::Kind::Wontfix:
3699 llvm_unreachable("Invalid strategy!");
3700 }
3701
3702 return std::nullopt;
3703}
3704
3705static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
3706 const DeclRefExpr *DRE) {
3707 const SourceManager &SM = Ctx.getSourceManager();
3708 // Inserts the .data() after the DRE
3709 std::optional<SourceLocation> EndOfOperand =
3710 getPastLoc(DRE, SM, Ctx.getLangOpts());
3711
3712 if (EndOfOperand)
3713 return FixItList{{FixItHint::CreateInsertion(*EndOfOperand, ".data()")}};
3714
3715 return std::nullopt;
3716}
3717
3718// Generates fix-its replacing an expression of the form UPC(DRE) with
3719// `DRE.data()`
3720std::optional<FixItList>
3721UPCStandalonePointerGadget::getFixits(const FixitStrategy &S) const {
3722 const auto VD = cast<VarDecl>(Node->getDecl());
3723 switch (S.lookup(VD)) {
3724 case FixitStrategy::Kind::Array:
3725 case FixitStrategy::Kind::Span: {
3726 return createDataFixit(VD->getASTContext(), Node);
3727 // FIXME: Points inside a macro expansion.
3728 break;
3729 }
3730 case FixitStrategy::Kind::Wontfix:
3731 case FixitStrategy::Kind::Iterator:
3732 return std::nullopt;
3733 case FixitStrategy::Kind::Vector:
3734 llvm_unreachable("unsupported strategies for FixableGadgets");
3735 }
3736
3737 return std::nullopt;
3738}
3739
3740// Generates fix-its replacing an expression of the form `&DRE[e]` with
3741// `&DRE.data()[e]`:
3742static std::optional<FixItList>
3744 const auto *ArraySub = cast<ArraySubscriptExpr>(Node->getSubExpr());
3745 const auto *DRE = cast<DeclRefExpr>(ArraySub->getBase()->IgnoreImpCasts());
3746 // FIXME: this `getASTContext` call is costly, we should pass the
3747 // ASTContext in:
3748 const ASTContext &Ctx = DRE->getDecl()->getASTContext();
3749 const Expr *Idx = ArraySub->getIdx();
3750 const SourceManager &SM = Ctx.getSourceManager();
3751 const LangOptions &LangOpts = Ctx.getLangOpts();
3752 std::stringstream SS;
3753 bool IdxIsLitZero = false;
3754
3755 if (auto ICE = Idx->getIntegerConstantExpr(Ctx))
3756 if ((*ICE).isZero())
3757 IdxIsLitZero = true;
3758 std::optional<StringRef> DreString = getExprText(DRE, SM, LangOpts);
3759 if (!DreString)
3760 return std::nullopt;
3761
3762 if (IdxIsLitZero) {
3763 // If the index is literal zero, we produce the most concise fix-it:
3764 SS << (*DreString).str() << ".data()";
3765 } else {
3766 std::optional<StringRef> IndexString = getExprText(Idx, SM, LangOpts);
3767 if (!IndexString)
3768 return std::nullopt;
3769
3770 SS << "&" << (*DreString).str() << ".data()"
3771 << "[" << (*IndexString).str() << "]";
3772 }
3773 return FixItList{
3774 FixItHint::CreateReplacement(Node->getSourceRange(), SS.str())};
3775}
3776
3777std::optional<FixItList>
3779 DeclUseList DREs = getClaimedVarUseSites();
3780
3781 if (DREs.size() != 1)
3782 return std::nullopt; // In cases of `Ptr += n` where `Ptr` is not a DRE, we
3783 // give up
3784 if (const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3785 if (S.lookup(VD) == FixitStrategy::Kind::Span) {
3786 FixItList Fixes;
3787
3788 const Stmt *AddAssignNode = Node;
3789 StringRef varName = VD->getName();
3790 const ASTContext &Ctx = VD->getASTContext();
3791
3792 if (!isNonNegativeIntegerExpr(Offset, VD, Ctx))
3793 return std::nullopt;
3794
3795 // To transform UUC(p += n) to UUC(p = p.subspan(..)):
3796 bool NotParenExpr =
3797 (Offset->IgnoreParens()->getBeginLoc() == Offset->getBeginLoc());
3798 std::string SS = varName.str() + " = " + varName.str() + ".subspan";
3799 if (NotParenExpr)
3800 SS += "(";
3801
3802 std::optional<SourceLocation> AddAssignLocation = getEndCharLoc(
3803 AddAssignNode, Ctx.getSourceManager(), Ctx.getLangOpts());
3804 if (!AddAssignLocation)
3805 return std::nullopt;
3806
3807 Fixes.push_back(FixItHint::CreateReplacement(
3808 SourceRange(AddAssignNode->getBeginLoc(), Node->getOperatorLoc()),
3809 SS));
3810 if (NotParenExpr)
3811 Fixes.push_back(FixItHint::CreateInsertion(
3812 Offset->getEndLoc().getLocWithOffset(1), ")"));
3813 return Fixes;
3814 }
3815 }
3816 return std::nullopt; // Not in the cases that we can handle for now, give up.
3817}
3818
3819std::optional<FixItList>
3821 DeclUseList DREs = getClaimedVarUseSites();
3822
3823 if (DREs.size() != 1)
3824 return std::nullopt; // In cases of `++Ptr` where `Ptr` is not a DRE, we
3825 // give up
3826 if (const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3827 if (S.lookup(VD) == FixitStrategy::Kind::Span) {
3828 FixItList Fixes;
3829 std::stringstream SS;
3830 StringRef varName = VD->getName();
3831 const ASTContext &Ctx = VD->getASTContext();
3832
3833 // To transform UPC(++p) to UPC((p = p.subspan(1)).data()):
3834 SS << "(" << varName.data() << " = " << varName.data()
3835 << ".subspan(1)).data()";
3836 std::optional<SourceLocation> PreIncLocation =
3837 getEndCharLoc(Node, Ctx.getSourceManager(), Ctx.getLangOpts());
3838 if (!PreIncLocation)
3839 return std::nullopt;
3840
3841 Fixes.push_back(FixItHint::CreateReplacement(
3842 SourceRange(Node->getBeginLoc(), *PreIncLocation), SS.str()));
3843 return Fixes;
3844 }
3845 }
3846 return std::nullopt; // Not in the cases that we can handle for now, give up.
3847}
3848
3849// For a non-null initializer `Init` of `T *` type, this function returns
3850// `FixItHint`s producing a list initializer `{Init, S}` as a part of a fix-it
3851// to output stream.
3852// In many cases, this function cannot figure out the actual extent `S`. It
3853// then will use a place holder to replace `S` to ask users to fill `S` in. The
3854// initializer shall be used to initialize a variable of type `std::span<T>`.
3855// In some cases (e. g. constant size array) the initializer should remain
3856// unchanged and the function returns empty list. In case the function can't
3857// provide the right fixit it will return nullopt.
3858//
3859// FIXME: Support multi-level pointers
3860//
3861// Parameters:
3862// `Init` a pointer to the initializer expression
3863// `Ctx` a reference to the ASTContext
3864static std::optional<FixItList>
3866 const StringRef UserFillPlaceHolder) {
3867 const SourceManager &SM = Ctx.getSourceManager();
3868 const LangOptions &LangOpts = Ctx.getLangOpts();
3869
3870 // If `Init` has a constant value that is (or equivalent to) a
3871 // NULL pointer, we use the default constructor to initialize the span
3872 // object, i.e., a `std:span` variable declaration with no initializer.
3873 // So the fix-it is just to remove the initializer.
3874 if (Init->isNullPointerConstant(
3875 Ctx,
3876 // FIXME: Why does this function not ask for `const ASTContext
3877 // &`? It should. Maybe worth an NFC patch later.
3879 NPC_ValueDependentIsNotNull)) {
3880 std::optional<SourceLocation> InitLocation =
3881 getEndCharLoc(Init, SM, LangOpts);
3882 if (!InitLocation)
3883 return std::nullopt;
3884
3885 SourceRange SR(Init->getBeginLoc(), *InitLocation);
3886
3887 return FixItList{FixItHint::CreateRemoval(SR)};
3888 }
3889
3890 FixItList FixIts{};
3891 std::string ExtentText = UserFillPlaceHolder.data();
3892 StringRef One = "1";
3893
3894 // Insert `{` before `Init`:
3895 FixIts.push_back(FixItHint::CreateInsertion(Init->getBeginLoc(), "{"));
3896 // Try to get the data extent. Break into different cases:
3897 if (auto CxxNew = dyn_cast<CXXNewExpr>(Init->IgnoreImpCasts())) {
3898 // In cases `Init` is `new T[n]` and there is no explicit cast over
3899 // `Init`, we know that `Init` must evaluates to a pointer to `n` objects
3900 // of `T`. So the extent is `n` unless `n` has side effects. Similar but
3901 // simpler for the case where `Init` is `new T`.
3902 if (const Expr *Ext = CxxNew->getArraySize().value_or(nullptr)) {
3903 if (!Ext->HasSideEffects(Ctx)) {
3904 std::optional<StringRef> ExtentString = getExprText(Ext, SM, LangOpts);
3905 if (!ExtentString)
3906 return std::nullopt;
3907 ExtentText = *ExtentString;
3908 }
3909 } else if (!CxxNew->isArray())
3910 // Although the initializer is not allocating a buffer, the pointer
3911 // variable could still be used in buffer access operations.
3912 ExtentText = One;
3913 } else if (Ctx.getAsConstantArrayType(Init->IgnoreImpCasts()->getType())) {
3914 // std::span has a single parameter constructor for initialization with
3915 // constant size array. The size is auto-deduced as the constructor is a
3916 // function template. The correct fixit is empty - no changes should happen.
3917 return FixItList{};
3918 } else {
3919 // In cases `Init` is of the form `&Var` after stripping of implicit
3920 // casts, where `&` is the built-in operator, the extent is 1.
3921 if (auto AddrOfExpr = dyn_cast<UnaryOperator>(Init->IgnoreImpCasts()))
3922 if (AddrOfExpr->getOpcode() == UnaryOperatorKind::UO_AddrOf &&
3923 isa_and_present<DeclRefExpr>(AddrOfExpr->getSubExpr()))
3924 ExtentText = One;
3925 // TODO: we can handle more cases, e.g., `&a[0]`, `&a`, `std::addressof`,
3926 // and explicit casting, etc. etc.
3927 }
3928
3929 SmallString<32> StrBuffer{};
3930 std::optional<SourceLocation> LocPassInit = getPastLoc(Init, SM, LangOpts);
3931
3932 if (!LocPassInit)
3933 return std::nullopt;
3934
3935 StrBuffer.append(", ");
3936 StrBuffer.append(ExtentText);
3937 StrBuffer.append("}");
3938 FixIts.push_back(FixItHint::CreateInsertion(*LocPassInit, StrBuffer.str()));
3939 return FixIts;
3940}
3941
3942#ifndef NDEBUG
3943#define DEBUG_NOTE_DECL_FAIL(D, Msg) \
3944 Handler.addDebugNoteForVar((D), (D)->getBeginLoc(), \
3945 "failed to produce fixit for declaration '" + \
3946 (D)->getNameAsString() + "'" + (Msg))
3947#else
3948#define DEBUG_NOTE_DECL_FAIL(D, Msg)
3949#endif
3950
3951// For the given variable declaration with a pointer-to-T type, returns the text
3952// `std::span<T>`. If it is unable to generate the text, returns
3953// `std::nullopt`.
3954static std::optional<std::string>
3956 assert(VD->getType()->isPointerType());
3957
3958 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
3959 std::optional<std::string> PteTyText = getPointeeTypeText(
3960 VD, Ctx.getSourceManager(), Ctx.getLangOpts(), &PteTyQualifiers);
3961
3962 if (!PteTyText)
3963 return std::nullopt;
3964
3965 std::string SpanTyText = "std::span<";
3966
3967 SpanTyText.append(*PteTyText);
3968 // Append qualifiers to span element type if any:
3969 if (PteTyQualifiers) {
3970 SpanTyText.append(" ");
3971 SpanTyText.append(PteTyQualifiers->getAsString());
3972 }
3973 SpanTyText.append(">");
3974 return SpanTyText;
3975}
3976
3977// For a `VarDecl` of the form `T * var (= Init)?`, this
3978// function generates fix-its that
3979// 1) replace `T * var` with `std::span<T> var`; and
3980// 2) change `Init` accordingly to a span constructor, if it exists.
3981//
3982// FIXME: support Multi-level pointers
3983//
3984// Parameters:
3985// `D` a pointer the variable declaration node
3986// `Ctx` a reference to the ASTContext
3987// `UserFillPlaceHolder` the user-input placeholder text
3988// Returns:
3989// the non-empty fix-it list, if fix-its are successfuly generated; empty
3990// list otherwise.
3991static FixItList fixLocalVarDeclWithSpan(const VarDecl *D, ASTContext &Ctx,
3992 const StringRef UserFillPlaceHolder,
3993 UnsafeBufferUsageHandler &Handler) {
3995 return {};
3996
3997 FixItList FixIts{};
3998 std::optional<std::string> SpanTyText = createSpanTypeForVarDecl(D, Ctx);
3999
4000 if (!SpanTyText) {
4001 DEBUG_NOTE_DECL_FAIL(D, " : failed to generate 'std::span' type");
4002 return {};
4003 }
4004
4005 // Will hold the text for `std::span<T> Ident`:
4006 std::stringstream SS;
4007
4008 SS << *SpanTyText;
4009 // Fix the initializer if it exists:
4010 if (const Expr *Init = D->getInit()) {
4011 std::optional<FixItList> InitFixIts =
4012 FixVarInitializerWithSpan(Init, Ctx, UserFillPlaceHolder);
4013 if (!InitFixIts)
4014 return {};
4015 FixIts.insert(FixIts.end(), std::make_move_iterator(InitFixIts->begin()),
4016 std::make_move_iterator(InitFixIts->end()));
4017 }
4018 // For declaration of the form `T * ident = init;`, we want to replace
4019 // `T * ` with `std::span<T>`.
4020 // We ignore CV-qualifiers so for `T * const ident;` we also want to replace
4021 // just `T *` with `std::span<T>`.
4022 const SourceLocation EndLocForReplacement = D->getTypeSpecEndLoc();
4023 if (!EndLocForReplacement.isValid()) {
4024 DEBUG_NOTE_DECL_FAIL(D, " : failed to locate the end of the declaration");
4025 return {};
4026 }
4027 // The only exception is that for `T *ident` we'll add a single space between
4028 // "std::span<T>" and "ident".
4029 // FIXME: The condition is false for identifiers expended from macros.
4030 if (EndLocForReplacement.getLocWithOffset(1) == getVarDeclIdentifierLoc(D))
4031 SS << " ";
4032
4033 FixIts.push_back(FixItHint::CreateReplacement(
4034 SourceRange(D->getBeginLoc(), EndLocForReplacement), SS.str()));
4035 return FixIts;
4036}
4037
4038static bool hasConflictingOverload(const FunctionDecl *FD) {
4039 return !FD->getDeclContext()->lookup(FD->getDeclName()).isSingleResult();
4040}
4041
4042// For a `FunctionDecl`, whose `ParmVarDecl`s are being changed to have new
4043// types, this function produces fix-its to make the change self-contained. Let
4044// 'F' be the entity defined by the original `FunctionDecl` and "NewF" be the
4045// entity defined by the `FunctionDecl` after the change to the parameters.
4046// Fix-its produced by this function are
4047// 1. Add the `[[clang::unsafe_buffer_usage]]` attribute to each declaration
4048// of 'F';
4049// 2. Create a declaration of "NewF" next to each declaration of `F`;
4050// 3. Create a definition of "F" (as its original definition is now belongs
4051// to "NewF") next to its original definition. The body of the creating
4052// definition calls to "NewF".
4053//
4054// Example:
4055//
4056// void f(int *p); // original declaration
4057// void f(int *p) { // original definition
4058// p[5];
4059// }
4060//
4061// To change the parameter `p` to be of `std::span<int>` type, we
4062// also add overloads:
4063//
4064// [[clang::unsafe_buffer_usage]] void f(int *p); // original decl
4065// void f(std::span<int> p); // added overload decl
4066// void f(std::span<int> p) { // original def where param is changed
4067// p[5];
4068// }
4069// [[clang::unsafe_buffer_usage]] void f(int *p) { // added def
4070// return f(std::span(p, <# size #>));
4071// }
4072//
4073static std::optional<FixItList>
4075 const ASTContext &Ctx,
4076 UnsafeBufferUsageHandler &Handler) {
4077 // FIXME: need to make this conflict checking better:
4078 if (hasConflictingOverload(FD))
4079 return std::nullopt;
4080
4081 const SourceManager &SM = Ctx.getSourceManager();
4082 const LangOptions &LangOpts = Ctx.getLangOpts();
4083 const unsigned NumParms = FD->getNumParams();
4084 std::vector<std::string> NewTysTexts(NumParms);
4085 std::vector<bool> ParmsMask(NumParms, false);
4086 bool AtLeastOneParmToFix = false;
4087
4088 for (unsigned i = 0; i < NumParms; i++) {
4089 const ParmVarDecl *PVD = FD->getParamDecl(i);
4090
4092 continue;
4093 if (S.lookup(PVD) != FixitStrategy::Kind::Span)
4094 // Not supported, not suppose to happen:
4095 return std::nullopt;
4096
4097 std::optional<Qualifiers> PteTyQuals = std::nullopt;
4098 std::optional<std::string> PteTyText =
4099 getPointeeTypeText(PVD, SM, LangOpts, &PteTyQuals);
4100
4101 if (!PteTyText)
4102 // something wrong in obtaining the text of the pointee type, give up
4103 return std::nullopt;
4104 // FIXME: whether we should create std::span type depends on the
4105 // FixitStrategy.
4106 NewTysTexts[i] = getSpanTypeText(*PteTyText, PteTyQuals);
4107 ParmsMask[i] = true;
4108 AtLeastOneParmToFix = true;
4109 }
4110 if (!AtLeastOneParmToFix)
4111 // No need to create function overloads:
4112 return {};
4113 // FIXME Respect indentation of the original code.
4114
4115 // A lambda that creates the text representation of a function declaration
4116 // with the new type signatures:
4117 const auto NewOverloadSignatureCreator =
4118 [&SM, &LangOpts, &NewTysTexts,
4119 &ParmsMask](const FunctionDecl *FD) -> std::optional<std::string> {
4120 std::stringstream SS;
4121
4122 SS << ";";
4123 SS << getEndOfLine().str();
4124 // Append: ret-type func-name "("
4125 if (auto Prefix = getRangeText(
4126 SourceRange(FD->getBeginLoc(), (*FD->param_begin())->getBeginLoc()),
4127 SM, LangOpts))
4128 SS << Prefix->str();
4129 else
4130 return std::nullopt; // give up
4131 // Append: parameter-type-list
4132 const unsigned NumParms = FD->getNumParams();
4133
4134 for (unsigned i = 0; i < NumParms; i++) {
4135 const ParmVarDecl *Parm = FD->getParamDecl(i);
4136
4137 if (Parm->isImplicit())
4138 continue;
4139 if (ParmsMask[i]) {
4140 // This `i`-th parameter will be fixed with `NewTysTexts[i]` being its
4141 // new type:
4142 SS << NewTysTexts[i];
4143 // print parameter name if provided:
4144 if (IdentifierInfo *II = Parm->getIdentifier())
4145 SS << ' ' << II->getName().str();
4146 } else if (auto ParmTypeText =
4147 getRangeText(getSourceRangeToTokenEnd(Parm, SM, LangOpts),
4148 SM, LangOpts)) {
4149 // print the whole `Parm` without modification:
4150 SS << ParmTypeText->str();
4151 } else
4152 return std::nullopt; // something wrong, give up
4153 if (i != NumParms - 1)
4154 SS << ", ";
4155 }
4156 SS << ")";
4157 return SS.str();
4158 };
4159
4160 // A lambda that creates the text representation of a function definition with
4161 // the original signature:
4162 const auto OldOverloadDefCreator =
4163 [&Handler, &SM, &LangOpts, &NewTysTexts,
4164 &ParmsMask](const FunctionDecl *FD) -> std::optional<std::string> {
4165 std::stringstream SS;
4166
4167 SS << getEndOfLine().str();
4168 // Append: attr-name ret-type func-name "(" param-list ")" "{"
4169 if (auto FDPrefix = getRangeText(
4170 SourceRange(FD->getBeginLoc(), FD->getBody()->getBeginLoc()), SM,
4171 LangOpts))
4172 SS << Handler.getUnsafeBufferUsageAttributeTextAt(FD->getBeginLoc(), " ")
4173 << FDPrefix->str() << "{";
4174 else
4175 return std::nullopt;
4176 // Append: "return" func-name "("
4177 if (auto FunQualName = getFunNameText(FD, SM, LangOpts))
4178 SS << "return " << FunQualName->str() << "(";
4179 else
4180 return std::nullopt;
4181
4182 // Append: arg-list
4183 const unsigned NumParms = FD->getNumParams();
4184 for (unsigned i = 0; i < NumParms; i++) {
4185 const ParmVarDecl *Parm = FD->getParamDecl(i);
4186
4187 if (Parm->isImplicit())
4188 continue;
4189 // FIXME: If a parameter has no name, it is unused in the
4190 // definition. So we could just leave it as it is.
4191 if (!Parm->getIdentifier())
4192 // If a parameter of a function definition has no name:
4193 return std::nullopt;
4194 if (ParmsMask[i])
4195 // This is our spanified paramter!
4196 SS << NewTysTexts[i] << "(" << Parm->getIdentifier()->getName().str()
4197 << ", " << getUserFillPlaceHolder("size") << ")";
4198 else
4199 SS << Parm->getIdentifier()->getName().str();
4200 if (i != NumParms - 1)
4201 SS << ", ";
4202 }
4203 // finish call and the body
4204 SS << ");}" << getEndOfLine().str();
4205 // FIXME: 80-char line formatting?
4206 return SS.str();
4207 };
4208
4209 FixItList FixIts{};
4210 for (FunctionDecl *FReDecl : FD->redecls()) {
4211 std::optional<SourceLocation> Loc = getPastLoc(FReDecl, SM, LangOpts);
4212
4213 if (!Loc)
4214 return {};
4215 if (FReDecl->isThisDeclarationADefinition()) {
4216 assert(FReDecl == FD && "inconsistent function definition");
4217 // Inserts a definition with the old signature to the end of
4218 // `FReDecl`:
4219 if (auto OldOverloadDef = OldOverloadDefCreator(FReDecl))
4220 FixIts.emplace_back(FixItHint::CreateInsertion(*Loc, *OldOverloadDef));
4221 else
4222 return {}; // give up
4223 } else {
4224 // Adds the unsafe-buffer attribute (if not already there) to `FReDecl`:
4225 if (!FReDecl->hasAttr<UnsafeBufferUsageAttr>()) {
4226 FixIts.emplace_back(FixItHint::CreateInsertion(
4227 FReDecl->getBeginLoc(), Handler.getUnsafeBufferUsageAttributeTextAt(
4228 FReDecl->getBeginLoc(), " ")));
4229 }
4230 // Inserts a declaration with the new signature to the end of `FReDecl`:
4231 if (auto NewOverloadDecl = NewOverloadSignatureCreator(FReDecl))
4232 FixIts.emplace_back(FixItHint::CreateInsertion(*Loc, *NewOverloadDecl));
4233 else
4234 return {};
4235 }
4236 }
4237 return FixIts;
4238}
4239
4240// To fix a `ParmVarDecl` to be of `std::span` type.
4241static FixItList fixParamWithSpan(const ParmVarDecl *PVD, const ASTContext &Ctx,
4242 UnsafeBufferUsageHandler &Handler) {
4244 DEBUG_NOTE_DECL_FAIL(PVD, " : has unsupport specifier(s)");
4245 return {};
4246 }
4247 if (PVD->hasDefaultArg()) {
4248 // FIXME: generate fix-its for default values:
4249 DEBUG_NOTE_DECL_FAIL(PVD, " : has default arg");
4250 return {};
4251 }
4252
4253 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
4254 std::optional<std::string> PteTyText = getPointeeTypeText(
4255 PVD, Ctx.getSourceManager(), Ctx.getLangOpts(), &PteTyQualifiers);
4256
4257 if (!PteTyText) {
4258 DEBUG_NOTE_DECL_FAIL(PVD, " : invalid pointee type");
4259 return {};
4260 }
4261
4262 std::optional<StringRef> PVDNameText = PVD->getIdentifier()->getName();
4263
4264 if (!PVDNameText) {
4265 DEBUG_NOTE_DECL_FAIL(PVD, " : invalid identifier name");
4266 return {};
4267 }
4268
4269 std::stringstream SS;
4270 std::optional<std::string> SpanTyText = createSpanTypeForVarDecl(PVD, Ctx);
4271
4272 if (PteTyQualifiers)
4273 // Append qualifiers if they exist:
4274 SS << getSpanTypeText(*PteTyText, PteTyQualifiers);
4275 else
4276 SS << getSpanTypeText(*PteTyText);
4277 // Append qualifiers to the type of the parameter:
4278 if (PVD->getType().hasQualifiers())
4279 SS << ' ' << PVD->getType().getQualifiers().getAsString();
4280 // Append parameter's name:
4281 SS << ' ' << PVDNameText->str();
4282 // Add replacement fix-it:
4283 return {FixItHint::CreateReplacement(PVD->getSourceRange(), SS.str())};
4284}
4285
4286static FixItList fixVariableWithSpan(const VarDecl *VD,
4287 const DeclUseTracker &Tracker,
4288 ASTContext &Ctx,
4289 UnsafeBufferUsageHandler &Handler) {
4290 const DeclStmt *DS = Tracker.lookupDecl(VD);
4291 if (!DS) {
4293 " : variables declared this way not implemented yet");
4294 return {};
4295 }
4296 if (!DS->isSingleDecl()) {
4297 // FIXME: to support handling multiple `VarDecl`s in a single `DeclStmt`
4298 DEBUG_NOTE_DECL_FAIL(VD, " : multiple VarDecls");
4299 return {};
4300 }
4301 // Currently DS is an unused variable but we'll need it when
4302 // non-single decls are implemented, where the pointee type name
4303 // and the '*' are spread around the place.
4304 (void)DS;
4305
4306 // FIXME: handle cases where DS has multiple declarations
4307 return fixLocalVarDeclWithSpan(VD, Ctx, getUserFillPlaceHolder(), Handler);
4308}
4309
4310static FixItList fixVarDeclWithArray(const VarDecl *D, const ASTContext &Ctx,
4311 UnsafeBufferUsageHandler &Handler) {
4312 FixItList FixIts{};
4313
4314 // Note: the code below expects the declaration to not use any type sugar like
4315 // typedef.
4316 if (auto CAT = Ctx.getAsConstantArrayType(D->getType())) {
4317 const QualType &ArrayEltT = CAT->getElementType();
4318 assert(!ArrayEltT.isNull() && "Trying to fix a non-array type variable!");
4319 // FIXME: support multi-dimensional arrays
4320 if (isa<clang::ArrayType>(ArrayEltT.getCanonicalType()))
4321 return {};
4322
4324
4325 // Get the spelling of the element type as written in the source file
4326 // (including macros, etc.).
4327 auto MaybeElemTypeTxt =
4329 Ctx.getLangOpts());
4330 if (!MaybeElemTypeTxt)
4331 return {};
4332 const llvm::StringRef ElemTypeTxt = MaybeElemTypeTxt->trim();
4333
4334 // Find the '[' token.
4335 std::optional<Token> NextTok = Lexer::findNextToken(
4337 while (NextTok && !NextTok->is(tok::l_square) &&
4338 NextTok->getLocation() <= D->getSourceRange().getEnd())
4339 NextTok = Lexer::findNextToken(NextTok->getLocation(),
4340 Ctx.getSourceManager(), Ctx.getLangOpts());
4341 if (!NextTok)
4342 return {};
4343 const SourceLocation LSqBracketLoc = NextTok->getLocation();
4344
4345 // Get the spelling of the array size as written in the source file
4346 // (including macros, etc.).
4347 auto MaybeArraySizeTxt = getRangeText(
4348 {LSqBracketLoc.getLocWithOffset(1), D->getTypeSpecEndLoc()},
4349 Ctx.getSourceManager(), Ctx.getLangOpts());
4350 if (!MaybeArraySizeTxt)
4351 return {};
4352 const llvm::StringRef ArraySizeTxt = MaybeArraySizeTxt->trim();
4353 if (ArraySizeTxt.empty()) {
4354 // FIXME: Support array size getting determined from the initializer.
4355 // Examples:
4356 // int arr1[] = {0, 1, 2};
4357 // int arr2{3, 4, 5};
4358 // We might be able to preserve the non-specified size with `auto` and
4359 // `std::to_array`:
4360 // auto arr1 = std::to_array<int>({0, 1, 2});
4361 return {};
4362 }
4363
4364 std::optional<StringRef> IdentText =
4366
4367 if (!IdentText) {
4368 DEBUG_NOTE_DECL_FAIL(D, " : failed to locate the identifier");
4369 return {};
4370 }
4371
4372 SmallString<32> Replacement;
4373 llvm::raw_svector_ostream OS(Replacement);
4374 OS << "std::array<" << ElemTypeTxt << ", " << ArraySizeTxt << "> "
4375 << IdentText->str();
4376
4377 FixIts.push_back(FixItHint::CreateReplacement(
4378 SourceRange{D->getBeginLoc(), D->getTypeSpecEndLoc()}, OS.str()));
4379 }
4380
4381 return FixIts;
4382}
4383
4384static FixItList fixVariableWithArray(const VarDecl *VD,
4385 const DeclUseTracker &Tracker,
4386 const ASTContext &Ctx,
4387 UnsafeBufferUsageHandler &Handler) {
4388 const DeclStmt *DS = Tracker.lookupDecl(VD);
4389 assert(DS && "Fixing non-local variables not implemented yet!");
4390 if (!DS->isSingleDecl()) {
4391 // FIXME: to support handling multiple `VarDecl`s in a single `DeclStmt`
4392 return {};
4393 }
4394 // Currently DS is an unused variable but we'll need it when
4395 // non-single decls are implemented, where the pointee type name
4396 // and the '*' are spread around the place.
4397 (void)DS;
4398
4399 // FIXME: handle cases where DS has multiple declarations
4400 return fixVarDeclWithArray(VD, Ctx, Handler);
4401}
4402
4403// TODO: we should be consistent to use `std::nullopt` to represent no-fix due
4404// to any unexpected problem.
4405static FixItList
4407 /* The function decl under analysis */ const Decl *D,
4408 const DeclUseTracker &Tracker, ASTContext &Ctx,
4409 UnsafeBufferUsageHandler &Handler) {
4410 if (const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4411 auto *FD = dyn_cast<clang::FunctionDecl>(PVD->getDeclContext());
4412 if (!FD || FD != D) {
4413 // `FD != D` means that `PVD` belongs to a function that is not being
4414 // analyzed currently. Thus `FD` may not be complete.
4415 DEBUG_NOTE_DECL_FAIL(VD, " : function not currently analyzed");
4416 return {};
4417 }
4418
4419 // TODO If function has a try block we can't change params unless we check
4420 // also its catch block for their use.
4421 // FIXME We might support static class methods, some select methods,
4422 // operators and possibly lamdas.
4423 if (FD->isMain() || FD->isConstexpr() ||
4425 FD->isVariadic() ||
4426 // also covers call-operator of lamdas
4427 isa<CXXMethodDecl>(FD) ||
4428 // skip when the function body is a try-block
4429 isa_and_nonnull<CXXTryStmt>(FD->getBody()) ||
4430 FD->isOverloadedOperator()) {
4431 DEBUG_NOTE_DECL_FAIL(VD, " : unsupported function decl");
4432 return {}; // TODO test all these cases
4433 }
4434 }
4435
4436 switch (K) {
4438 if (VD->getType()->isPointerType()) {
4439 if (const auto *PVD = dyn_cast<ParmVarDecl>(VD))
4440 return fixParamWithSpan(PVD, Ctx, Handler);
4441
4442 if (VD->isLocalVarDecl())
4443 return fixVariableWithSpan(VD, Tracker, Ctx, Handler);
4444 }
4445 DEBUG_NOTE_DECL_FAIL(VD, " : not a pointer");
4446 return {};
4447 }
4449 if (VD->isLocalVarDecl() && Ctx.getAsConstantArrayType(VD->getType()))
4450 return fixVariableWithArray(VD, Tracker, Ctx, Handler);
4451
4452 DEBUG_NOTE_DECL_FAIL(VD, " : not a local const-size array");
4453 return {};
4454 }
4457 llvm_unreachable("FixitStrategy not implemented yet!");
4459 llvm_unreachable("Invalid strategy!");
4460 }
4461 llvm_unreachable("Unknown strategy!");
4462}
4463
4464// Returns true iff there exists a `FixItHint` 'h' in `FixIts` such that the
4465// `RemoveRange` of 'h' overlaps with a macro use.
4466static bool overlapWithMacro(const FixItList &FixIts) {
4467 // FIXME: For now we only check if the range (or the first token) is (part of)
4468 // a macro expansion. Ideally, we want to check for all tokens in the range.
4469 return llvm::any_of(FixIts, [](const FixItHint &Hint) {
4470 auto Range = Hint.RemoveRange;
4471 if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
4472 // If the range (or the first token) is (part of) a macro expansion:
4473 return true;
4474 return false;
4475 });
4476}
4477
4478// Returns true iff `VD` is a parameter of the declaration `D`:
4479static bool isParameterOf(const VarDecl *VD, const Decl *D) {
4480 return isa<ParmVarDecl>(VD) &&
4481 VD->getDeclContext() == dyn_cast<DeclContext>(D);
4482}
4483
4484// Erases variables in `FixItsForVariable`, if such a variable has an unfixable
4485// group mate. A variable `v` is unfixable iff `FixItsForVariable` does not
4486// contain `v`.
4488 std::map<const VarDecl *, FixItList> &FixItsForVariable,
4489 const VariableGroupsManager &VarGrpMgr) {
4490 // Variables will be removed from `FixItsForVariable`:
4492
4493 for (const auto &[VD, Ignore] : FixItsForVariable) {
4494 VarGrpRef Grp = VarGrpMgr.getGroupOfVar(VD);
4495 if (llvm::any_of(Grp,
4496 [&FixItsForVariable](const VarDecl *GrpMember) -> bool {
4497 return !FixItsForVariable.count(GrpMember);
4498 })) {
4499 // At least one group member cannot be fixed, so we have to erase the
4500 // whole group:
4501 for (const VarDecl *Member : Grp)
4502 ToErase.push_back(Member);
4503 }
4504 }
4505 for (auto *VarToErase : ToErase)
4506 FixItsForVariable.erase(VarToErase);
4507}
4508
4509// Returns the fix-its that create bounds-safe function overloads for the
4510// function `D`, if `D`'s parameters will be changed to safe-types through
4511// fix-its in `FixItsForVariable`.
4512//
4513// NOTE: In case `D`'s parameters will be changed but bounds-safe function
4514// overloads cannot created, the whole group that contains the parameters will
4515// be erased from `FixItsForVariable`.
4517 std::map<const VarDecl *, FixItList> &FixItsForVariable /* mutable */,
4518 const VariableGroupsManager &VarGrpMgr, const FunctionDecl *FD,
4519 const FixitStrategy &S, ASTContext &Ctx,
4520 UnsafeBufferUsageHandler &Handler) {
4521 FixItList FixItsSharedByParms{};
4522
4523 std::optional<FixItList> OverloadFixes =
4524 createOverloadsForFixedParams(S, FD, Ctx, Handler);
4525
4526 if (OverloadFixes) {
4527 FixItsSharedByParms.append(*OverloadFixes);
4528 } else {
4529 // Something wrong in generating `OverloadFixes`, need to remove the
4530 // whole group, where parameters are in, from `FixItsForVariable` (Note
4531 // that all parameters should be in the same group):
4532 for (auto *Member : VarGrpMgr.getGroupOfParms())
4533 FixItsForVariable.erase(Member);
4534 }
4535 return FixItsSharedByParms;
4536}
4537
4538// Constructs self-contained fix-its for each variable in `FixablesForAllVars`.
4539static std::map<const VarDecl *, FixItList>
4540getFixIts(FixableGadgetSets &FixablesForAllVars, const FixitStrategy &S,
4541 ASTContext &Ctx,
4542 /* The function decl under analysis */ const Decl *D,
4543 const DeclUseTracker &Tracker, UnsafeBufferUsageHandler &Handler,
4544 const VariableGroupsManager &VarGrpMgr) {
4545 // `FixItsForVariable` will map each variable to a set of fix-its directly
4546 // associated to the variable itself. Fix-its of distinct variables in
4547 // `FixItsForVariable` are disjoint.
4548 std::map<const VarDecl *, FixItList> FixItsForVariable;
4549
4550 // Populate `FixItsForVariable` with fix-its directly associated with each
4551 // variable. Fix-its directly associated to a variable 'v' are the ones
4552 // produced by the `FixableGadget`s whose claimed variable is 'v'.
4553 for (const auto &[VD, Fixables] : FixablesForAllVars.byVar) {
4554 FixItsForVariable[VD] =
4555 fixVariable(VD, S.lookup(VD), D, Tracker, Ctx, Handler);
4556 // If we fail to produce Fix-It for the declaration we have to skip the
4557 // variable entirely.
4558 if (FixItsForVariable[VD].empty()) {
4559 FixItsForVariable.erase(VD);
4560 continue;
4561 }
4562 for (const auto &F : Fixables) {
4563 std::optional<FixItList> Fixits = F->getFixits(S);
4564
4565 if (Fixits) {
4566 FixItsForVariable[VD].insert(FixItsForVariable[VD].end(),
4567 Fixits->begin(), Fixits->end());
4568 continue;
4569 }
4570#ifndef NDEBUG
4571 Handler.addDebugNoteForVar(
4572 VD, F->getSourceLoc(),
4573 ("gadget '" + F->getDebugName() + "' refused to produce a fix")
4574 .str());
4575#endif
4576 FixItsForVariable.erase(VD);
4577 break;
4578 }
4579 }
4580
4581 // `FixItsForVariable` now contains only variables that can be
4582 // fixed. A variable can be fixed if its declaration and all Fixables
4583 // associated to it can all be fixed.
4584
4585 // To further remove from `FixItsForVariable` variables whose group mates
4586 // cannot be fixed...
4587 eraseVarsForUnfixableGroupMates(FixItsForVariable, VarGrpMgr);
4588 // Now `FixItsForVariable` gets further reduced: a variable is in
4589 // `FixItsForVariable` iff it can be fixed and all its group mates can be
4590 // fixed.
4591
4592 // Fix-its of bounds-safe overloads of `D` are shared by parameters of `D`.
4593 // That is, when fixing multiple parameters in one step, these fix-its will
4594 // be applied only once (instead of being applied per parameter).
4595 FixItList FixItsSharedByParms{};
4596
4597 if (auto *FD = dyn_cast<FunctionDecl>(D))
4598 FixItsSharedByParms = createFunctionOverloadsForParms(
4599 FixItsForVariable, VarGrpMgr, FD, S, Ctx, Handler);
4600
4601 // The map that maps each variable `v` to fix-its for the whole group where
4602 // `v` is in:
4603 std::map<const VarDecl *, FixItList> FinalFixItsForVariable{
4604 FixItsForVariable};
4605
4606 for (auto &[Var, Ignore] : FixItsForVariable) {
4607 bool AnyParm = false;
4608 const auto VarGroupForVD = VarGrpMgr.getGroupOfVar(Var, &AnyParm);
4609
4610 for (const VarDecl *GrpMate : VarGroupForVD) {
4611 if (Var == GrpMate)
4612 continue;
4613 if (FixItsForVariable.count(GrpMate))
4614 FinalFixItsForVariable[Var].append(FixItsForVariable[GrpMate]);
4615 }
4616 if (AnyParm) {
4617 // This assertion should never fail. Otherwise we have a bug.
4618 assert(!FixItsSharedByParms.empty() &&
4619 "Should not try to fix a parameter that does not belong to a "
4620 "FunctionDecl");
4621 FinalFixItsForVariable[Var].append(FixItsSharedByParms);
4622 }
4623 }
4624 // Fix-its that will be applied in one step shall NOT:
4625 // 1. overlap with macros or/and templates; or
4626 // 2. conflict with each other.
4627 // Otherwise, the fix-its will be dropped.
4628 for (auto Iter = FinalFixItsForVariable.begin();
4629 Iter != FinalFixItsForVariable.end();)
4630 if (overlapWithMacro(Iter->second) ||
4631 clang::internal::anyConflict(Iter->second, Ctx.getSourceManager())) {
4632 Iter = FinalFixItsForVariable.erase(Iter);
4633 } else
4634 Iter++;
4635 return FinalFixItsForVariable;
4636}
4637
4638template <typename VarDeclIterTy>
4639static FixitStrategy
4640getNaiveStrategy(llvm::iterator_range<VarDeclIterTy> UnsafeVars) {
4641 FixitStrategy S;
4642 for (const VarDecl *VD : UnsafeVars) {
4645 else
4647 }
4648 return S;
4649}
4650
4651// Manages variable groups:
4653 const std::vector<VarGrpTy> &Groups;
4654 const std::map<const VarDecl *, unsigned> &VarGrpMap;
4655 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms;
4656
4657public:
4659 const std::vector<VarGrpTy> &Groups,
4660 const std::map<const VarDecl *, unsigned> &VarGrpMap,
4661 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms)
4662 : Groups(Groups), VarGrpMap(VarGrpMap),
4663 GrpsUnionForParms(GrpsUnionForParms) {}
4664
4665 VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm) const override {
4666 if (GrpsUnionForParms.contains(Var)) {
4667 if (HasParm)
4668 *HasParm = true;
4669 return GrpsUnionForParms.getArrayRef();
4670 }
4671 if (HasParm)
4672 *HasParm = false;
4673
4674 auto It = VarGrpMap.find(Var);
4675
4676 if (It == VarGrpMap.end())
4677 return {};
4678 return Groups[It->second];
4679 }
4680
4681 VarGrpRef getGroupOfParms() const override {
4682 return GrpsUnionForParms.getArrayRef();
4683 }
4684};
4685
4686static void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets,
4687 WarningGadgetList WarningGadgets,
4688 DeclUseTracker Tracker,
4689 UnsafeBufferUsageHandler &Handler,
4690 bool EmitSuggestions) {
4691 if (!EmitSuggestions) {
4692 // Our job is very easy without suggestions. Just warn about
4693 // every problematic operation and consider it done. No need to deal
4694 // with fixable gadgets, no need to group operations by variable.
4695 for (const auto &G : WarningGadgets) {
4696 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/false,
4697 D->getASTContext());
4698 }
4699
4700 // This return guarantees that most of the machine doesn't run when
4701 // suggestions aren't requested.
4702 assert(FixableGadgets.empty() &&
4703 "Fixable gadgets found but suggestions not requested!");
4704 return;
4705 }
4706
4707 // If no `WarningGadget`s ever matched, there is no unsafe operations in the
4708 // function under the analysis. No need to fix any Fixables.
4709 if (!WarningGadgets.empty()) {
4710 // Gadgets "claim" variables they're responsible for. Once this loop
4711 // finishes, the tracker will only track DREs that weren't claimed by any
4712 // gadgets, i.e. not understood by the analysis.
4713 for (const auto &G : FixableGadgets) {
4714 for (const auto *DRE : G->getClaimedVarUseSites()) {
4715 Tracker.claimUse(DRE);
4716 }
4717 }
4718 }
4719
4720 // If no `WarningGadget`s ever matched, there is no unsafe operations in the
4721 // function under the analysis. Thus, it early returns here as there is
4722 // nothing needs to be fixed.
4723 //
4724 // Note this claim is based on the assumption that there is no unsafe
4725 // variable whose declaration is invisible from the analyzing function.
4726 // Otherwise, we need to consider if the uses of those unsafe varuables needs
4727 // fix.
4728 // So far, we are not fixing any global variables or class members. And,
4729 // lambdas will be analyzed along with the enclosing function. So this early
4730 // return is correct for now.
4731 if (WarningGadgets.empty())
4732 return;
4733
4734 WarningGadgetSets UnsafeOps =
4735 groupWarningGadgetsByVar(std::move(WarningGadgets));
4736 FixableGadgetSets FixablesForAllVars =
4737 groupFixablesByVar(std::move(FixableGadgets));
4738
4739 std::map<const VarDecl *, FixItList> FixItsForVariableGroup;
4740
4741 // Filter out non-local vars and vars with unclaimed DeclRefExpr-s.
4742 for (auto it = FixablesForAllVars.byVar.cbegin();
4743 it != FixablesForAllVars.byVar.cend();) {
4744 // FIXME: need to deal with global variables later
4745 if ((!it->first->isLocalVarDecl() && !isa<ParmVarDecl>(it->first))) {
4746#ifndef NDEBUG
4747 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4748 ("failed to produce fixit for '" +
4749 it->first->getNameAsString() +
4750 "' : neither local nor a parameter"));
4751#endif
4752 it = FixablesForAllVars.byVar.erase(it);
4753 } else if (it->first->getType().getCanonicalType()->isReferenceType()) {
4754#ifndef NDEBUG
4755 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4756 ("failed to produce fixit for '" +
4757 it->first->getNameAsString() +
4758 "' : has a reference type"));
4759#endif
4760 it = FixablesForAllVars.byVar.erase(it);
4761 } else if (Tracker.hasUnclaimedUses(it->first)) {
4762 it = FixablesForAllVars.byVar.erase(it);
4763 } else if (it->first->isInitCapture()) {
4764#ifndef NDEBUG
4765 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4766 ("failed to produce fixit for '" +
4767 it->first->getNameAsString() +
4768 "' : init capture"));
4769#endif
4770 it = FixablesForAllVars.byVar.erase(it);
4771 } else {
4772 ++it;
4773 }
4774 }
4775
4776#ifndef NDEBUG
4777 for (const auto &it : UnsafeOps.byVar) {
4778 const VarDecl *const UnsafeVD = it.first;
4779 auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
4780 if (UnclaimedDREs.empty())
4781 continue;
4782 const auto UnfixedVDName = UnsafeVD->getNameAsString();
4783 for (const clang::DeclRefExpr *UnclaimedDRE : UnclaimedDREs) {
4784 std::string UnclaimedUseTrace =
4785 getDREAncestorString(UnclaimedDRE, D->getASTContext());
4786
4787 Handler.addDebugNoteForVar(
4788 UnsafeVD, UnclaimedDRE->getBeginLoc(),
4789 ("failed to produce fixit for '" + UnfixedVDName +
4790 "' : has an unclaimed use\nThe unclaimed DRE trace: " +
4791 UnclaimedUseTrace));
4792 }
4793 }
4794#endif
4795
4796 // Fixpoint iteration for pointer assignments
4797 using DepMapTy =
4798 llvm::DenseMap<const VarDecl *, llvm::SetVector<const VarDecl *>>;
4799 DepMapTy DependenciesMap{};
4800 DepMapTy PtrAssignmentGraph{};
4801
4802 for (const auto &it : FixablesForAllVars.byVar) {
4803 for (const FixableGadget *fixable : it.second) {
4804 std::optional<std::pair<const VarDecl *, const VarDecl *>> ImplPair =
4805 fixable->getStrategyImplications();
4806 if (ImplPair) {
4807 std::pair<const VarDecl *, const VarDecl *> Impl = std::move(*ImplPair);
4808 PtrAssignmentGraph[Impl.first].insert(Impl.second);
4809 }
4810 }
4811 }
4812
4813 /*
4814 The following code does a BFS traversal of the `PtrAssignmentGraph`
4815 considering all unsafe vars as starting nodes and constructs an undirected
4816 graph `DependenciesMap`. Constructing the `DependenciesMap` in this manner
4817 elimiates all variables that are unreachable from any unsafe var. In other
4818 words, this removes all dependencies that don't include any unsafe variable
4819 and consequently don't need any fixit generation.
4820 Note: A careful reader would observe that the code traverses
4821 `PtrAssignmentGraph` using `CurrentVar` but adds edges between `Var` and
4822 `Adj` and not between `CurrentVar` and `Adj`. Both approaches would
4823 achieve the same result but the one used here dramatically cuts the
4824 amount of hoops the second part of the algorithm needs to jump, given that
4825 a lot of these connections become "direct". The reader is advised not to
4826 imagine how the graph is transformed because of using `Var` instead of
4827 `CurrentVar`. The reader can continue reading as if `CurrentVar` was used,
4828 and think about why it's equivalent later.
4829 */
4830 std::set<const VarDecl *> VisitedVarsDirected{};
4831 for (const auto &[Var, ignore] : UnsafeOps.byVar) {
4832 if (VisitedVarsDirected.find(Var) == VisitedVarsDirected.end()) {
4833
4834 std::queue<const VarDecl *> QueueDirected{};
4835 QueueDirected.push(Var);
4836 while (!QueueDirected.empty()) {
4837 const VarDecl *CurrentVar = QueueDirected.front();
4838 QueueDirected.pop();
4839 VisitedVarsDirected.insert(CurrentVar);
4840 auto AdjacentNodes = PtrAssignmentGraph[CurrentVar];
4841 for (const VarDecl *Adj : AdjacentNodes) {
4842 if (VisitedVarsDirected.find(Adj) == VisitedVarsDirected.end()) {
4843 QueueDirected.push(Adj);
4844 }
4845 DependenciesMap[Var].insert(Adj);
4846 DependenciesMap[Adj].insert(Var);
4847 }
4848 }
4849 }
4850 }
4851
4852 // `Groups` stores the set of Connected Components in the graph.
4853 std::vector<VarGrpTy> Groups;
4854 // `VarGrpMap` maps variables that need fix to the groups (indexes) that the
4855 // variables belong to. Group indexes refer to the elements in `Groups`.
4856 // `VarGrpMap` is complete in that every variable that needs fix is in it.
4857 std::map<const VarDecl *, unsigned> VarGrpMap;
4858 // The union group over the ones in "Groups" that contain parameters of `D`:
4859 llvm::SetVector<const VarDecl *>
4860 GrpsUnionForParms; // these variables need to be fixed in one step
4861
4862 // Group Connected Components for Unsafe Vars
4863 // (Dependencies based on pointer assignments)
4864 std::set<const VarDecl *> VisitedVars{};
4865 for (const auto &[Var, ignore] : UnsafeOps.byVar) {
4866 if (VisitedVars.find(Var) == VisitedVars.end()) {
4867 VarGrpTy &VarGroup = Groups.emplace_back();
4868 std::queue<const VarDecl *> Queue{};
4869
4870 Queue.push(Var);
4871 while (!Queue.empty()) {
4872 const VarDecl *CurrentVar = Queue.front();
4873 Queue.pop();
4874 VisitedVars.insert(CurrentVar);
4875 VarGroup.push_back(CurrentVar);
4876 auto AdjacentNodes = DependenciesMap[CurrentVar];
4877 for (const VarDecl *Adj : AdjacentNodes) {
4878 if (VisitedVars.find(Adj) == VisitedVars.end()) {
4879 Queue.push(Adj);
4880 }
4881 }
4882 }
4883
4884 bool HasParm = false;
4885 unsigned GrpIdx = Groups.size() - 1;
4886
4887 for (const VarDecl *V : VarGroup) {
4888 VarGrpMap[V] = GrpIdx;
4889 if (!HasParm && isParameterOf(V, D))
4890 HasParm = true;
4891 }
4892 if (HasParm)
4893 GrpsUnionForParms.insert_range(VarGroup);
4894 }
4895 }
4896
4897 // Remove a `FixableGadget` if the associated variable is not in the graph
4898 // computed above. We do not want to generate fix-its for such variables,
4899 // since they are neither warned nor reachable from a warned one.
4900 //
4901 // Note a variable is not warned if it is not directly used in any unsafe
4902 // operation. A variable `v` is NOT reachable from an unsafe variable, if it
4903 // does not exist another variable `u` such that `u` is warned and fixing `u`
4904 // (transitively) implicates fixing `v`.
4905 //
4906 // For example,
4907 // ```
4908 // void f(int * p) {
4909 // int * a = p; *p = 0;
4910 // }
4911 // ```
4912 // `*p = 0` is a fixable gadget associated with a variable `p` that is neither
4913 // warned nor reachable from a warned one. If we add `a[5] = 0` to the end of
4914 // the function above, `p` becomes reachable from a warned variable.
4915 for (auto I = FixablesForAllVars.byVar.begin();
4916 I != FixablesForAllVars.byVar.end();) {
4917 // Note `VisitedVars` contain all the variables in the graph:
4918 if (!VisitedVars.count((*I).first)) {
4919 // no such var in graph:
4920 I = FixablesForAllVars.byVar.erase(I);
4921 } else
4922 ++I;
4923 }
4924
4925 // We assign strategies to variables that are 1) in the graph and 2) can be
4926 // fixed. Other variables have the default "Won't fix" strategy.
4927 FixitStrategy NaiveStrategy = getNaiveStrategy(llvm::make_filter_range(
4928 VisitedVars, [&FixablesForAllVars](const VarDecl *V) {
4929 // If a warned variable has no "Fixable", it is considered unfixable:
4930 return FixablesForAllVars.byVar.count(V);
4931 }));
4932 VariableGroupsManagerImpl VarGrpMgr(Groups, VarGrpMap, GrpsUnionForParms);
4933
4934 if (isa<NamedDecl>(D))
4935 // The only case where `D` is not a `NamedDecl` is when `D` is a
4936 // `BlockDecl`. Let's not fix variables in blocks for now
4937 FixItsForVariableGroup =
4938 getFixIts(FixablesForAllVars, NaiveStrategy, D->getASTContext(), D,
4939 Tracker, Handler, VarGrpMgr);
4940
4941 for (const auto &G : UnsafeOps.noVar) {
4942 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/false,
4943 D->getASTContext());
4944 }
4945
4946 for (const auto &[VD, WarningGadgets] : UnsafeOps.byVar) {
4947 auto FixItsIt = FixItsForVariableGroup.find(VD);
4948 Handler.handleUnsafeVariableGroup(VD, VarGrpMgr,
4949 FixItsIt != FixItsForVariableGroup.end()
4950 ? std::move(FixItsIt->second)
4951 : FixItList{},
4952 D, NaiveStrategy);
4953 for (const auto &G : WarningGadgets) {
4954 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/true,
4955 D->getASTContext());
4956 }
4957 }
4958}
4959
4961 UnsafeBufferUsageHandler &Handler,
4962 bool EmitSuggestions) {
4963#ifndef NDEBUG
4964 Handler.clearDebugNotes();
4965#endif
4966
4967 assert(D);
4968 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4969 // Consteval functions are free of UB by the spec, so we don't need to
4970 // visit them or produce diagnostics.
4971 if (FD->isConsteval())
4972 return;
4973 // We do not want to visit a Lambda expression defined inside a method
4974 // independently. Instead, it should be visited along with the outer method.
4975 // FIXME: do we want to do the same thing for `BlockDecl`s?
4976 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4977 if (MD->getParent()->isLambda() && MD->getParent()->isLocalClass())
4978 return;
4979 }
4980
4981 for (FunctionDecl *FReDecl : FD->redecls()) {
4982 if (FReDecl->isExternC()) {
4983 // Do not emit fixit suggestions for functions declared in an
4984 // extern "C" block.
4985 EmitSuggestions = false;
4986 break;
4987 }
4988 }
4989 }
4990
4992
4994
4995 assert(!Stmts.empty());
4996
4997 FixableGadgetList FixableGadgets;
4998 WarningGadgetList WarningGadgets;
4999 DeclUseTracker Tracker;
5000 for (const Stmt *S : Stmts) {
5001 findGadgets(S, D->getASTContext(), Handler, EmitSuggestions, FixableGadgets,
5002 WarningGadgets, Tracker);
5003 }
5004 applyGadgets(D, std::move(FixableGadgets), std::move(WarningGadgets),
5005 std::move(Tracker), Handler, EmitSuggestions);
5006}
5007
5009 std::set<const Expr *> &UnsafePointers) {
5010 class MockReporter : public UnsafeBufferUsageHandler {
5011 public:
5012 MockReporter() {}
5013 void handleUnsafeOperation(const Stmt *, bool, ASTContext &) override {}
5014 void handleUnsafeLibcCall(const CallExpr *, unsigned,
5016 const Expr *UnsafeArg = nullptr) override {}
5017 void handleUnsafeOperationInContainer(const Stmt *, bool,
5018 ASTContext &) override {}
5019 void handleUnsafeOperationInStringView(const Stmt *, bool,
5020 ASTContext &) override {}
5021 void handleUnsafeVariableGroup(const VarDecl *,
5022 const VariableGroupsManager &, FixItList &&,
5023 const Decl *,
5024 const FixitStrategy &) override {}
5025 void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
5026 bool IsRelatedToDecl,
5027 ASTContext &Ctx) override {}
5028 bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
5029 return false;
5030 }
5031 bool isSafeBufferOptOut(const SourceLocation &) const override {
5032 return false;
5033 }
5034 bool ignoreUnsafeBufferInLibcCall(const SourceLocation &) const override {
5035 return false;
5036 }
5037 bool
5038 ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &) const override {
5039 return false;
5040 }
5041 bool ignoreUnsafeBufferInStaticSizedArray(
5042 const SourceLocation &Loc) const override {
5043 return false;
5044 }
5045 std::string getUnsafeBufferUsageAttributeTextAt(
5046 SourceLocation, StringRef WSSuffix = "") const override {
5047 return "";
5048 }
5049 } Handler;
5050
5051 const Stmt *S = N.get<Stmt>();
5052 if (!S)
5053 return false;
5054
5055 MatchResult Result;
5056 WarningGadgetList WarningGadgets;
5057 bool Matched = false;
5058
5059 // FIXME: By design, we don't need MockReporter, and we are supposed to
5060 // only define WARNING_GADGET when we want to treat WARNING_OPTIONAL_GADGET
5061 // the same as WARNING_GADGET. The reason we have to do it this way now is
5062 // that some WARNING_OPTIONAL_GADGETs do not have the 3-argument `matches`
5063 // overload. We need to fix this problem in a separate patch.
5064
5065#define WARNING_GADGET(name) \
5066 if (name##Gadget::matches(S, Ctx, Result)) \
5067 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5068#define WARNING_OPTIONAL_GADGET(name) \
5069 if (name##Gadget::matches(S, Ctx, &Handler, Result)) \
5070 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5071#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
5072
5073 for (auto &WG : WarningGadgets)
5074 for (auto *E : WG->getUnsafePtrs()) {
5075 UnsafePointers.insert(E);
5076 Matched = true;
5077 }
5078 return Matched;
5079}
Defines the clang::ASTContext interface.
#define V(N, I)
static bool ignoreUnsafeLibcCall(const ASTContext &Ctx, const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static void findStmtsInUnspecifiedLvalueContext(const Stmt *S, const llvm::function_ref< void(const Expr *)> OnResult)
static std::string getUserFillPlaceHolder(StringRef HintTextToUser="placeholder")
static FixItList fixVariableWithSpan(const VarDecl *VD, const DeclUseTracker &Tracker, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static std::optional< FixItList > fixUPCAddressofArraySubscriptWithSpan(const UnaryOperator *Node)
static bool ignoreUnsafeBufferInContainer(const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static WarningGadgetSets groupWarningGadgetsByVar(const WarningGadgetList &AllUnsafeOperations)
static bool hasArrayType(const Expr &E)
static StringRef getEndOfLine()
static bool notInSafeBufferOptOut(const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static std::optional< FixItList > FixVarInitializerWithSpan(const Expr *Init, ASTContext &Ctx, const StringRef UserFillPlaceHolder)
static std::optional< SourceLocation > getEndCharLoc(const NodeTy *Node, const SourceManager &SM, const LangOptions &LangOpts)
static FixItList fixVariableWithArray(const VarDecl *VD, const DeclUseTracker &Tracker, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static bool areEqualIntegralBinaryOperators(const BinaryOperator *E1, const Expr *E2_LHS, BinaryOperatorKind BOP, const Expr *E2_RHS, ASTContext &Ctx)
static bool hasPointerType(const Expr &E)
static std::string getSpanTypeText(StringRef EltTyText, std::optional< Qualifiers > Quals=std::nullopt)
static SourceRange getSourceRangeToTokenEnd(const Decl *D, const SourceManager &SM, const LangOptions &LangOpts)
static FixItList fixLocalVarDeclWithSpan(const VarDecl *D, ASTContext &Ctx, const StringRef UserFillPlaceHolder, UnsafeBufferUsageHandler &Handler)
static bool isSafeArraySubscript(const ArraySubscriptExpr &Node, const ASTContext &Ctx, const bool IgnoreStaticSizedArrays)
static std::optional< FixItList > createDataFixit(const ASTContext &Ctx, const DeclRefExpr *DRE)
static FixItList createFunctionOverloadsForParms(std::map< const VarDecl *, FixItList > &FixItsForVariable, const VariableGroupsManager &VarGrpMgr, const FunctionDecl *FD, const FixitStrategy &S, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static bool isNullTermPointer(const Expr *Ptr, ASTContext &Ctx)
static bool ignoreUnsafeFormatAttrCall(const ASTContext &Ctx, const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static bool isSafeStringViewTwoParamConstruct(const CXXConstructExpr &Node, ASTContext &Ctx)
static FixItList fixVarDeclWithArray(const VarDecl *D, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixItList fixVariable(const VarDecl *VD, FixitStrategy::Kind K, const Decl *D, const DeclUseTracker &Tracker, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixItList fixParamWithSpan(const ParmVarDecl *PVD, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixitStrategy getNaiveStrategy(llvm::iterator_range< VarDeclIterTy > UnsafeVars)
static std::optional< std::string > createSpanTypeForVarDecl(const VarDecl *VD, const ASTContext &Ctx)
static bool hasConflictingOverload(const FunctionDecl *FD)
static bool isSafeTwoParamContainerConstruct(const CallOrConstructExpr &Node, ASTContext &Ctx, bool AllowDuckTypedContainers=false)
static void findStmtsInUnspecifiedPointerContext(const Stmt *S, llvm::function_ref< void(const Stmt *)> InnerMatcher)
static bool isNonNegativeIntegerExpr(const Expr *Expr, const VarDecl *VD, const ASTContext &Ctx)
static bool overlapWithMacro(const FixItList &FixIts)
static void forEachDescendantStmt(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, FastMatcher &Matcher)
static bool isPtrBufferSafe(const Expr *Ptr, const Expr *Size, ASTContext &Ctx, bool AllowDuckTypedContainers=false)
static bool hasUnsupportedSpecifiers(const VarDecl *VD, const SourceManager &SM)
static const Expr * tryConstantFoldConditionalExpr(const Expr *E, const ASTContext &Ctx)
#define DEBUG_NOTE_DECL_FAIL(D, Msg)
static void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets, WarningGadgetList WarningGadgets, DeclUseTracker Tracker, UnsafeBufferUsageHandler &Handler, bool EmitSuggestions)
static bool isSafePointerArithmetic(const Expr *Ptr, const Expr *OffsetExpr, BinaryOperatorKind Opcode, const ASTContext &Ctx)
static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx)
static void findGadgets(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, bool EmitSuggestions, FixableGadgetList &FixableGadgets, WarningGadgetList &WarningGadgets, DeclUseTracker &Tracker)
static const Expr * getSubExprInSizeOfExpr(const Expr &E)
static std::map< const VarDecl *, FixItList > getFixIts(FixableGadgetSets &FixablesForAllVars, const FixitStrategy &S, ASTContext &Ctx, const Decl *D, const DeclUseTracker &Tracker, UnsafeBufferUsageHandler &Handler, const VariableGroupsManager &VarGrpMgr)
static const Expr * getSubExprInAddressOfExpr(const Expr &E)
static void forEachDescendantEvaluatedStmt(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, FastMatcher &Matcher)
static void findStmtsInUnspecifiedUntypedContext(const Stmt *S, llvm::function_ref< void(const Stmt *)> InnerMatcher)
static std::optional< FixItList > createOverloadsForFixedParams(const FixitStrategy &S, const FunctionDecl *FD, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static void eraseVarsForUnfixableGroupMates(std::map< const VarDecl *, FixItList > &FixItsForVariable, const VariableGroupsManager &VarGrpMgr)
static FixableGadgetSets groupFixablesByVar(FixableGadgetList &&AllFixableOperations)
static bool isParameterOf(const VarDecl *VD, const Decl *D)
#define SIZED_CONTAINER_OR_VIEW_LIST
static void populateStmtsForFindingGadgets(SmallVector< const Stmt * > &Stmts, const Decl *D)
static std::optional< StringRef > getFunNameText(const FunctionDecl *FD, const SourceManager &SM, const LangOptions &LangOpts)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Preprocessor interface.
MatchFinder::MatchResult MatchResult
Defines the clang::SourceLocation class and associated facilities.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
virtual std::optional< FixItList > getFixits(const FixitStrategy &s) const final
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
DerefSimplePtrArithFixableGadget(const MatchResult &Result)
SourceLocation getSourceLoc() const override
virtual DeclUseList getClaimedVarUseSites() const final
FixableGadgetMatcher(FixableGadgetList &FixableGadgets, DeclUseTracker &Tracker)
bool matches(const DynTypedNode &DynNode, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler) override
Represents the length modifier in a format string in scanf/printf.
Kind getKind() const
bool TraverseCXXTypeidExpr(CXXTypeidExpr *Node) override
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc Node, bool TraverseQualifier) override
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc Node, bool TraverseQualifier) override
bool TraverseGenericSelectionExpr(GenericSelectionExpr *Node) override
MatchDescendantVisitor(ASTContext &Context, FastMatcher &Matcher, bool FindAll, bool IgnoreUnevaluatedContext, const UnsafeBufferUsageHandler &NewHandler)
bool TraverseDecl(Decl *Node) override
bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node) override
bool findMatch(const DynTypedNode &DynNode)
bool TraverseCXXDefaultInitExpr(CXXDefaultInitExpr *Node) override
bool TraverseCXXNoexceptExpr(CXXNoexceptExpr *Node) override
bool TraverseStmt(Stmt *Node) override
virtual std::optional< FixItList > getFixits(const FixitStrategy &S) const override
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
SourceLocation getSourceLoc() const override
virtual DeclUseList getClaimedVarUseSites() const override
UPCPreIncrementGadget(const MatchResult &Result)
static bool classof(const Gadget *G)
static bool classof(const Gadget *G)
UUCAddAssignGadget(const MatchResult &Result)
virtual std::optional< FixItList > getFixits(const FixitStrategy &S) const override
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
virtual DeclUseList getClaimedVarUseSites() const override
SourceLocation getSourceLoc() const override
VariableGroupsManagerImpl(const std::vector< VarGrpTy > &Groups, const std::map< const VarDecl *, unsigned > &VarGrpMap, const llvm::SetVector< const VarDecl * > &GrpsUnionForParms)
VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm) const override
Returns the set of variables (including Var) that need to be fixed together in one step.
VarGrpRef getGroupOfParms() const override
Returns the non-empty group of variables that include parameters of the analyzing function,...
bool matches(const DynTypedNode &DynNode, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler) override
WarningGadgetMatcher(WarningGadgetList &WarningGadgets)
APSInt & getInt()
Definition APValue.h:573
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:913
const ConstantArrayType * getAsConstantArrayType(QualType T) const
DynTypedNodeList getParents(const NodeT &Node)
Forwards to get node parents from the ParentMapContext.
QualType getFILEType() const
Retrieve the C FILE type.
const LangOptions & getLangOpts() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
Attr - This represents one attribute.
Definition Attr.h:47
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
Expr * getRHS() const
Definition Expr.h:4159
Opcode getOpcode() const
Definition Expr.h:4152
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
child_range children()
Definition ExprCXX.h:1743
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2612
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4363
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
static const char * getCastKindName(CastKind CK)
Definition Expr.cpp:1987
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getEnd() const
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
Represents a class template specialization, which refers to a class template with a given set of temp...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool isNamespace() const
Definition DeclBase.h:2221
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1655
decl_range decls()
Definition Stmt.h:1690
const Decl * getSingleDecl() const
Definition Stmt.h:1657
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1105
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
DeclContext * getDeclContext()
Definition DeclBase.h:457
attr_range attrs() const
Definition DeclBase.h:544
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
SourceLocation getTypeSpecEndLoc() const
Definition Decl.cpp:2011
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:847
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:839
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
const DynTypedNode * begin() const
A dynamically typed AST node container.
const T * get() const
Retrieve the stored node as type T.
static DynTypedNode create(const T &Node)
Creates a DynTypedNode from Node.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
NullPointerConstantValueDependence
Enumeration used to describe how isNullPointerConstant() should cope with value-dependent expressions...
Definition Expr.h:870
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
QualType getType() const
Definition Expr.h:146
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition Diagnostic.h:83
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Kind lookup(const VarDecl *VD) const
void set(const VarDecl *VD, Kind K)
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3835
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
param_iterator param_begin()
Definition Decl.h:2959
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3137
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4219
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3441
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3110
bool isConsteval() const
Definition Decl.h:2651
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3705
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3899
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2367
Represents a C11 generic selection.
Definition Expr.h:6268
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:509
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:882
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:319
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
bool isValid() const
Is this parameter index valid?
Definition Attr.h:344
unsigned getASTIndex() const
Get the parameter index as it would normally be encoded at the AST level of representation: zero-orig...
Definition Attr.h:363
Represents a parameter to a function.
Definition Decl.h:1832
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3064
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2986
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8758
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8709
QualType getCanonicalType() const
Definition TypeBase.h:8721
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8742
std::string getAsString() const
Represents a struct/union/class.
Definition Decl.h:4506
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const char * getStmtClassName() const
Definition Stmt.cpp:86
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:228
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Represents a template argument.
QualType getAsType() const
Retrieve the type for a type template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:9005
bool isPointerType() const
Definition TypeBase.h:8906
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9339
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9589
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2355
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2460
bool isAnyPointerType() const
Definition TypeBase.h:8914
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2395
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2431
static bool isDecrementOp(Opcode Op)
Definition Expr.h:2402
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1438
The interface that lets the caller handle unsafe buffer usage analysis results by overriding this cla...
virtual void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node, bool IsRelatedToDecl, ASTContext &Ctx)=0
void addDebugNoteForVar(const VarDecl *VD, SourceLocation Loc, std::string Text)
virtual bool ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &Loc) const =0
virtual std::string getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc, StringRef WSSuffix="") const =0
virtual bool isSafeBufferOptOut(const SourceLocation &Loc) const =0
virtual bool ignoreUnsafeBufferInContainer(const SourceLocation &Loc) const =0
virtual void handleUnsafeOperation(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
Invoked when an unsafe operation over raw pointers is found.
virtual void handleUnsafeOperationInStringView(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
virtual void handleUnsafeLibcCall(const CallExpr *Call, unsigned PrintfInfo, UnsafeLibcFunctionFamily Family, ASTContext &Ctx, const Expr *UnsafeArg=nullptr)=0
Invoked when a call to an unsafe libc function is found.
virtual void handleUnsafeVariableGroup(const VarDecl *Variable, const VariableGroupsManager &VarGrpMgr, FixItList &&Fixes, const Decl *D, const FixitStrategy &VarTargetTypes)=0
Invoked when a fix is suggested against a variable.
virtual void handleUnsafeOperationInContainer(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
Invoked when an unsafe operation with a std container is found.
virtual bool ignoreUnsafeBufferInStaticSizedArray(const SourceLocation &Loc) const =0
virtual bool ignoreUnsafeBufferInLibcCall(const SourceLocation &Loc) const =0
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isInlineSpecified() const
Definition Decl.h:1591
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2661
const Expr * getInit() const
Definition Decl.h:1393
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
virtual VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm=nullptr) const =0
Returns the set of variables (including Var) that need to be fixed together in one step.
virtual VarGrpRef getGroupOfParms() const =0
Returns the non-empty group of variables that include parameters of the analyzing function,...
const LengthModifier & getLengthModifier() const
const OptionalAmount & getPrecision() const
const PrintfConversionSpecifier & getConversionSpecifier() const
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
void matchEachArgumentWithParamType(const CallExpr &Node, llvm::function_ref< void(QualType, const Expr *)> OnParamAndArg)
bool anyConflict(const llvm::SmallVectorImpl< FixItHint > &FixIts, const SourceManager &SM)
bool matches(const til::SExpr *E1, const til::SExpr *E2)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool matchUnsafePointers(const DynTypedNode &N, ASTContext &Ctx, std::set< const Expr * > &UnsafePointers)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void checkUnsafeBufferUsage(const Decl *D, UnsafeBufferUsageHandler &Handler, bool EmitSuggestions)
SourceLocation getVarDeclIdentifierLoc(const DeclaratorDecl *VD)
static bool classof(const OMPClause *T)
std::vector< const VarDecl * > VarGrpTy
std::optional< StringRef > getExprText(const Expr *E, const SourceManager &SM, const LangOptions &LangOpts)
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
std::optional< std::string > getPointeeTypeText(const DeclaratorDecl *VD, const SourceManager &SM, const LangOptions &LangOpts, std::optional< Qualifiers > *QualifiersToAppend)
Definition FixitUtil.cpp:22
std::optional< StringRef > getRangeText(SourceRange SR, const SourceManager &SM, const LangOptions &LangOpts)
std::optional< StringRef > getVarDeclIdentifierText(const DeclaratorDecl *VD, const SourceManager &SM, const LangOptions &LangOpts)
UnsafeLibcFunctionFamily
The family of an unsafe libc function.
std::optional< SourceLocation > getPastLoc(const NodeTy *Node, const SourceManager &SM, const LangOptions &LangOpts)
Definition FixitUtil.h:54
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
@ Decrement
This is a postfix decrement operator, 'operator--(int)'.
Definition Decl.h:2049
@ Increment
This is a postfix increment operator, 'operator++(int)'.
Definition Decl.h:2047
U cast(CodeGen::Address addr)
Definition Address.h:327
ArrayRef< const VarDecl * > VarGrpRef
static StringRef matchLibcNameOrBuiltinChk(StringRef Name)
static bool hasUnsafePrintfStringArg(const CallExpr &Node, ASTContext &Ctx, MatchResult &Result, llvm::StringRef Tag)
static bool isPredefinedUnsafeLibcFunc(const FunctionDecl &Node)
static UnsafeLibcFunctionFamily getUnsafeLibcFunctionFamily(const FunctionDecl &Node)
static bool hasUnsafeSnprintfBuffer(const CallExpr &Node, ASTContext &Ctx)
static bool isUnsafeVaListPrintfFunc(const FunctionDecl &Node)
static bool isUnsafeSprintfFunc(const FunctionDecl &Node)
static bool hasUnsafeFormatOrSArg(ASTContext &Ctx, const CallExpr *Call, const Expr *&UnsafeArg, const unsigned FmtIdx, std::optional< const unsigned > FmtArgIdx=std::nullopt, bool isKprintf=false)
static std::optional< UnsafeLibcFunctionFamily > getPredefinedUnsafeLibcFuncFamily(const FunctionDecl &Node)
static StringRef matchLibcName(StringRef Name)
static bool isUnsafeMemset(const CallExpr &Node, ASTContext &Ctx)
static StringRef matchName(StringRef FunName, bool isBuiltin)
static bool isInLibcScope(const FunctionDecl &FD)
static bool isLibcFunction(const FunctionDecl &FD)
static bool isNormalPrintfFunc(const FunctionDecl &Node)
#define false
Definition stdbool.h:26
bool operator()(const NodeTy *N1, const NodeTy *N2) const
std::map< const VarDecl *, std::set< const FixableGadget * >, CompareNode< VarDecl > > byVar
std::map< const VarDecl *, std::set< const WarningGadget * >, CompareNode< VarDecl > > byVar
llvm::SmallVector< const WarningGadget *, 16 > noVar
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
const BoundNodes Nodes
Contains the nodes bound on the current match.