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 const Expr *Operand = CE->getSubExpr();
2409 if (auto *Paren = dyn_cast<ParenExpr>(Operand))
2410 Operand = Paren->getSubExpr();
2411 auto *MCE = dyn_cast<CXXMemberCallExpr>(Operand);
2412 if (!MCE || !isDataFunction(MCE))
2413 return false;
2414 if (!isUnsafePointerCast(CE, Ctx))
2415 return false;
2416 Result.addNode(OpTag, DynTypedNode::create(*CE));
2417 return true;
2418 }
2419
2420 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2421 bool IsRelatedToDecl,
2422 ASTContext &Ctx) const override {
2423 Handler.handleUnsafeOperation(Op, IsRelatedToDecl, Ctx);
2424 }
2425 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2426
2427 DeclUseList getClaimedVarUseSites() const override { return {}; }
2428
2429private:
2430 static bool isDataFunction(const CXXMemberCallExpr *call) {
2431 if (!call)
2432 return false;
2433 auto *callee = call->getDirectCallee();
2434 if (!callee || !isa<CXXMethodDecl>(callee))
2435 return false;
2436 auto *method = cast<CXXMethodDecl>(callee);
2437 if (method->getNameAsString() == "data" &&
2438 method->getParent()->isInStdNamespace() &&
2439 llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
2440 method->getParent()->getName()))
2441 return true;
2442 return false;
2443 }
2444
2445 // Returns true if `CE` casts the pointer returned by `data()` to a pointer to
2446 // a larger type, or if the size of either pointee type cannot be determined.
2447 static bool isUnsafePointerCast(const ExplicitCastExpr *CE,
2448 const ASTContext &Ctx) {
2449 QualType DestType = CE->getType();
2450 if (!isa<PointerType>(DestType))
2451 return false;
2452 QualType DestPointeeType = DestType->getPointeeType();
2453
2454 // If destination type is incomplete or dependent, it is unsafe to cast
2455 // to anyway, no need to check its type:
2456 if (DestPointeeType->isIncompleteType() ||
2457 DestPointeeType->isDependentType())
2458 return true;
2459
2460 QualType SrcType = CE->getSubExpr()->getType();
2461 if (!SrcType->isPointerType())
2462 return false;
2463 QualType SrcPointeeType = SrcType->getPointeeType();
2464
2465 // Check if source type is incomplete or dependent as well:
2466 if (SrcPointeeType->isIncompleteType() || SrcPointeeType->isDependentType())
2467 return true;
2468
2469 return Ctx.getTypeSize(SrcPointeeType) < Ctx.getTypeSize(DestPointeeType);
2470 }
2471
2472 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2473};
2474
2475class UnsafeLibcFunctionCallGadget : public WarningGadget {
2476 const CallExpr *const Call;
2477 const Expr *UnsafeArg = nullptr;
2478 constexpr static const char *const Tag = "UnsafeLibcFunctionCall";
2479 // Extra tags for additional information:
2480 constexpr static const char *const UnsafeSprintfTag =
2481 "UnsafeLibcFunctionCall_sprintf";
2482 constexpr static const char *const UnsafeSizedByTag =
2483 "UnsafeLibcFunctionCall_sized_by";
2484 constexpr static const char *const UnsafeStringTag =
2485 "UnsafeLibcFunctionCall_string";
2486 constexpr static const char *const UnsafeVaListTag =
2487 "UnsafeLibcFunctionCall_va_list";
2488
2489public:
2490 enum UnsafeKind {
2491 OTHERS = 0, // no specific information, the callee function is unsafe
2492 SPRINTF = 1, // never call `-sprintf`s, call `-snprintf`s instead.
2493 SIZED_BY =
2494 2, // the first two arguments of `snprintf` function have
2495 // "__sized_by" relation but they do not conform to safe patterns
2496 STRING = 3, // an argument is a pointer-to-char-as-string but does not
2497 // guarantee null-termination
2498 VA_LIST = 4, // one of the `-printf`s function that take va_list, which is
2499 // considered unsafe as it is not compile-time check
2500 FORMAT_ATTR = 8, // flag: the callee has the format attribute
2501 } WarnedFunKind = OTHERS;
2502 UnsafeLibcFunctionFamily Family = UnsafeLibcFunctionFamily::Other;
2503
2504 UnsafeLibcFunctionCallGadget(const MatchResult &Result)
2505 : WarningGadget(Kind::UnsafeLibcFunctionCall),
2506 Call(Result.getNodeAs<CallExpr>(Tag)) {
2507 if (Result.getNodeAs<Decl>(UnsafeSprintfTag))
2508 WarnedFunKind = SPRINTF;
2509 else if (auto *E = Result.getNodeAs<Expr>(UnsafeStringTag)) {
2510 WarnedFunKind = STRING;
2511 UnsafeArg = E;
2512 } else if (Result.getNodeAs<CallExpr>(UnsafeSizedByTag)) {
2513 WarnedFunKind = SIZED_BY;
2514 UnsafeArg = Call->getArg(0);
2515 } else if (Result.getNodeAs<Decl>(UnsafeVaListTag))
2516 WarnedFunKind = VA_LIST;
2517 // Only the predefined-name and memset matches leave `WarnedFunKind` at
2518 // `OTHERS`. The printf matches always set a kind.
2519 Family = WarnedFunKind != OTHERS
2520 ? UnsafeLibcFunctionFamily::Printf
2522 *Call->getDirectCallee());
2523 }
2524
2525 static bool matches(const Stmt *S, ASTContext &Ctx,
2526 const UnsafeBufferUsageHandler *Handler,
2528 const auto *CE = dyn_cast<CallExpr>(S);
2529 if (!CE)
2530 return false;
2531 const auto *FD = CE->getDirectCallee();
2532 if (!FD)
2533 return false;
2535 return false;
2536 // The check looks up every libc-call warning, so it runs after the cheaper
2537 // scope test.
2538 if (ignoreUnsafeLibcCall(Ctx, *S, Handler))
2539 return false;
2540 // If the call has a sole null-terminated argument, e.g., strlen,
2541 // printf, atoi, we consider it safe:
2542 if (CE->getNumArgs() == 1 && isNullTermPointer(CE->getArg(0), Ctx))
2543 return false;
2544
2545 const bool isSingleStringLiteralArg =
2546 CE->getNumArgs() == 1 &&
2548 if (!isSingleStringLiteralArg) {
2549 // (unless the call has a sole string literal argument):
2551 Result.addNode(Tag, DynTypedNode::create(*CE));
2552 return true;
2553 }
2554 if (libc_func_matchers::isUnsafeMemset(*CE, Ctx)) {
2555 Result.addNode(Tag, DynTypedNode::create(*CE));
2556 return true;
2557 }
2559 Result.addNode(Tag, DynTypedNode::create(*CE));
2560 Result.addNode(UnsafeVaListTag, DynTypedNode::create(*FD));
2561 return true;
2562 }
2564 Result.addNode(Tag, DynTypedNode::create(*CE));
2565 Result.addNode(UnsafeSprintfTag, DynTypedNode::create(*FD));
2566 return true;
2567 }
2568 }
2571 Result.addNode(Tag, DynTypedNode::create(*CE));
2572 Result.addNode(UnsafeSizedByTag, DynTypedNode::create(*CE));
2573 return true;
2574 }
2576 UnsafeStringTag)) {
2577 Result.addNode(Tag, DynTypedNode::create(*CE));
2578 return true;
2579 }
2580 }
2581 return false;
2582 }
2583
2584 const Stmt *getBaseStmt() const { return Call; }
2585
2586 SourceLocation getSourceLoc() const override { return Call->getBeginLoc(); }
2587
2588 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2589 bool IsRelatedToDecl,
2590 ASTContext &Ctx) const override {
2591 Handler.handleUnsafeLibcCall(Call, WarnedFunKind, Family, Ctx, UnsafeArg);
2592 }
2593
2594 DeclUseList getClaimedVarUseSites() const override { return {}; }
2595
2596 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2597};
2598
2599class UnsafeFormatAttributedFunctionCallGadget : public WarningGadget {
2600 const CallExpr *const Call;
2601 const Expr *UnsafeArg = nullptr;
2602 constexpr static const char *const Tag = "UnsafeFormatAttributedFunctionCall";
2603 constexpr static const char *const UnsafeStringTag =
2604 "UnsafeFormatAttributedFunctionCall_string";
2605
2606public:
2607 UnsafeFormatAttributedFunctionCallGadget(const MatchResult &Result)
2608 : WarningGadget(Kind::UnsafeLibcFunctionCall),
2609 Call(Result.getNodeAs<CallExpr>(Tag)),
2610 UnsafeArg(Result.getNodeAs<Expr>(UnsafeStringTag)) {}
2611
2612 static bool matches(const Stmt *S, ASTContext &Ctx,
2613 const UnsafeBufferUsageHandler *Handler,
2615 auto *CE = dyn_cast<CallExpr>(S);
2616 if (!CE || !CE->getDirectCallee())
2617 return false;
2618 const FunctionDecl *FD = CE->getDirectCallee();
2619 if (!FD)
2620 return false;
2621 if (ignoreUnsafeFormatAttrCall(Ctx, *S, Handler))
2622 return false;
2623
2624 const FormatAttr *Attr = nullptr;
2625 bool IsPrintf = false;
2626 bool AnyAttr = llvm::any_of(
2627 FD->specific_attrs<FormatAttr>(),
2628 [&Attr, &IsPrintf](const FormatAttr *FA) -> bool {
2629 if (const auto *II = FA->getType()) {
2630 if (II->getName() == "printf" || II->getName() == "scanf") {
2631 Attr = FA;
2632 IsPrintf = II->getName() == "printf";
2633 return true;
2634 }
2635 }
2636 return false;
2637 });
2638 const Expr *UnsafeArg;
2639
2640 if (!AnyAttr)
2641 return false;
2642 // Calls to libc functions belong to -Wunsafe-buffer-usage-in-libc-call.
2643 if (ignoreUnsafeLibcCall(Ctx, *S, Handler) &&
2645 return false;
2646
2647 // FormatAttribute indexes are 1-based:
2648 unsigned FmtIdx = Attr->getFormatIdx() - 1;
2649 std::optional<unsigned> FmtArgIdx = Attr->getFirstArg() - 1;
2650
2651 if (isa<CXXMemberCallExpr>(CE)) {
2652 // For CXX member calls, attribute parameters are specified as if there is
2653 // an implicit "this". The implicit "this" is invisible through CallExpr
2654 // `CE`. (What makes it even less ergonomic is that the
2655 // implicit "this" is visible through CallExpr `CE` for CXX operator
2656 // calls!)
2657 --FmtIdx;
2658 --*FmtArgIdx;
2659 } else if (CE->getStmtClass() != Stmt::CallExprClass &&
2661 return false; // Ignore unsupported CallExpr subclasses
2662 if (*FmtArgIdx >= CE->getNumArgs())
2663 // Format arguments are allowed to be absent when variadic parameter is
2664 // used. So we need to check if those arguments exist. Moreover, when
2665 // variadic parameter is NOT used, `Attr->getFirstArg()` could be an
2666 // out-of-bound value. E.g.,
2667 // clang does not complain about `__attribute__((__format__(__printf__, 2,
2668 // 99))) void f(int, char *);`.
2669 FmtArgIdx = std::nullopt;
2670
2671 if (AnyAttr && !IsPrintf && FmtArgIdx) {
2672 // For scanf-like functions, any format argument is considered unsafe:
2673 Result.addNode(Tag, DynTypedNode::create(*CE));
2674 return true;
2675 }
2676 // For printf-like functions:
2678 Ctx, CE, UnsafeArg, FmtIdx, FmtArgIdx)) {
2679 Result.addNode(Tag, DynTypedNode::create(*CE));
2680 Result.addNode(UnsafeStringTag, DynTypedNode::create(*UnsafeArg));
2681 return true;
2682 }
2683 return false;
2684 }
2685
2686 const Stmt *getBaseStmt() const { return Call; }
2687
2688 SourceLocation getSourceLoc() const override { return Call->getBeginLoc(); }
2689
2690 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2691 bool IsRelatedToDecl,
2692 ASTContext &Ctx) const override {
2693 if (UnsafeArg)
2694 Handler.handleUnsafeLibcCall(
2695 Call,
2696 UnsafeLibcFunctionCallGadget::UnsafeKind::STRING |
2697 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2698 UnsafeLibcFunctionFamily::Other, Ctx, UnsafeArg);
2699 else
2700 Handler.handleUnsafeLibcCall(
2701 Call,
2702 UnsafeLibcFunctionCallGadget::UnsafeKind::OTHERS |
2703 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2705 }
2706
2707 DeclUseList getClaimedVarUseSites() const override { return {}; }
2708
2709 SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
2710};
2711
2712// Represents expressions of the form `DRE[*]` in the Unspecified Lvalue
2713// Context (see `findStmtsInUnspecifiedLvalueContext`).
2714// Note here `[]` is the built-in subscript operator.
2715class ULCArraySubscriptGadget : public FixableGadget {
2716private:
2717 static constexpr const char *const ULCArraySubscriptTag =
2718 "ArraySubscriptUnderULC";
2719 const ArraySubscriptExpr *Node;
2720
2721public:
2722 ULCArraySubscriptGadget(const MatchResult &Result)
2723 : FixableGadget(Kind::ULCArraySubscript),
2724 Node(Result.getNodeAs<ArraySubscriptExpr>(ULCArraySubscriptTag)) {
2725 assert(Node != nullptr && "Expecting a non-null matching result");
2726 }
2727
2728 static bool classof(const Gadget *G) {
2729 return G->getKind() == Kind::ULCArraySubscript;
2730 }
2731
2732 static bool matches(const Stmt *S,
2733 llvm::SmallVectorImpl<MatchResult> &Results) {
2734 size_t SizeBefore = Results.size();
2735 findStmtsInUnspecifiedLvalueContext(S, [&Results](const Expr *E) {
2736 const auto *ASE = dyn_cast<ArraySubscriptExpr>(E);
2737 if (!ASE)
2738 return;
2739 const auto *DRE =
2740 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts());
2741 if (!DRE || !(hasPointerType(*DRE) || hasArrayType(*DRE)) ||
2742 !isSupportedVariable(*DRE))
2743 return;
2744 MatchResult R;
2745 R.addNode(ULCArraySubscriptTag, DynTypedNode::create(*ASE));
2746 Results.emplace_back(std::move(R));
2747 });
2748 return SizeBefore != Results.size();
2749 }
2750
2751 virtual std::optional<FixItList>
2752 getFixits(const FixitStrategy &S) const override;
2753 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2754
2755 virtual DeclUseList getClaimedVarUseSites() const override {
2756 if (const auto *DRE =
2757 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts())) {
2758 return {DRE};
2759 }
2760 return {};
2761 }
2762};
2763
2764// Fixable gadget to handle stand alone pointers of the form `UPC(DRE)` in the
2765// unspecified pointer context (findStmtsInUnspecifiedPointerContext). The
2766// gadget emits fixit of the form `UPC(DRE.data())`.
2767class UPCStandalonePointerGadget : public FixableGadget {
2768private:
2769 static constexpr const char *const DeclRefExprTag = "StandalonePointer";
2770 const DeclRefExpr *Node;
2771
2772public:
2773 UPCStandalonePointerGadget(const MatchResult &Result)
2774 : FixableGadget(Kind::UPCStandalonePointer),
2775 Node(Result.getNodeAs<DeclRefExpr>(DeclRefExprTag)) {
2776 assert(Node != nullptr && "Expecting a non-null matching result");
2777 }
2778
2779 static bool classof(const Gadget *G) {
2780 return G->getKind() == Kind::UPCStandalonePointer;
2781 }
2782
2783 static bool matches(const Stmt *S,
2784 llvm::SmallVectorImpl<MatchResult> &Results) {
2785 size_t SizeBefore = Results.size();
2786 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
2787 auto *E = dyn_cast<Expr>(S);
2788 if (!E)
2789 return;
2790 const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
2791 if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)) ||
2792 !isSupportedVariable(*DRE))
2793 return;
2794 MatchResult R;
2795 R.addNode(DeclRefExprTag, DynTypedNode::create(*DRE));
2796 Results.emplace_back(std::move(R));
2797 });
2798 return SizeBefore != Results.size();
2799 }
2800
2801 virtual std::optional<FixItList>
2802 getFixits(const FixitStrategy &S) const override;
2803 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2804
2805 virtual DeclUseList getClaimedVarUseSites() const override { return {Node}; }
2806};
2807
2808class PointerDereferenceGadget : public FixableGadget {
2809 static constexpr const char *const BaseDeclRefExprTag = "BaseDRE";
2810 static constexpr const char *const OperatorTag = "op";
2811
2812 const DeclRefExpr *BaseDeclRefExpr = nullptr;
2813 const UnaryOperator *Op = nullptr;
2814
2815public:
2816 PointerDereferenceGadget(const MatchResult &Result)
2817 : FixableGadget(Kind::PointerDereference),
2818 BaseDeclRefExpr(Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
2819 Op(Result.getNodeAs<UnaryOperator>(OperatorTag)) {}
2820
2821 static bool classof(const Gadget *G) {
2822 return G->getKind() == Kind::PointerDereference;
2823 }
2824
2825 static bool matches(const Stmt *S,
2826 llvm::SmallVectorImpl<MatchResult> &Results) {
2827 size_t SizeBefore = Results.size();
2828 findStmtsInUnspecifiedLvalueContext(S, [&Results](const Stmt *S) {
2829 const auto *UO = dyn_cast<UnaryOperator>(S);
2830 if (!UO || UO->getOpcode() != UO_Deref)
2831 return;
2832 const Expr *CE = UO->getSubExpr();
2833 if (!CE)
2834 return;
2835 CE = CE->IgnoreParenImpCasts();
2836 const auto *DRE = dyn_cast<DeclRefExpr>(CE);
2837 if (!DRE || !isSupportedVariable(*DRE))
2838 return;
2839 MatchResult R;
2840 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
2841 R.addNode(OperatorTag, DynTypedNode::create(*UO));
2842 Results.emplace_back(std::move(R));
2843 });
2844 return SizeBefore != Results.size();
2845 }
2846
2847 DeclUseList getClaimedVarUseSites() const override {
2848 return {BaseDeclRefExpr};
2849 }
2850
2851 virtual std::optional<FixItList>
2852 getFixits(const FixitStrategy &S) const override;
2853 SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
2854};
2855
2856// Represents expressions of the form `&DRE[any]` in the Unspecified Pointer
2857// Context (see `findStmtsInUnspecifiedPointerContext`).
2858// Note here `[]` is the built-in subscript operator.
2859class UPCAddressofArraySubscriptGadget : public FixableGadget {
2860private:
2861 static constexpr const char *const UPCAddressofArraySubscriptTag =
2862 "AddressofArraySubscriptUnderUPC";
2863 const UnaryOperator *Node; // the `&DRE[any]` node
2864
2865public:
2866 UPCAddressofArraySubscriptGadget(const MatchResult &Result)
2867 : FixableGadget(Kind::ULCArraySubscript),
2868 Node(Result.getNodeAs<UnaryOperator>(UPCAddressofArraySubscriptTag)) {
2869 assert(Node != nullptr && "Expecting a non-null matching result");
2870 }
2871
2872 static bool classof(const Gadget *G) {
2873 return G->getKind() == Kind::UPCAddressofArraySubscript;
2874 }
2875
2876 static bool matches(const Stmt *S,
2877 llvm::SmallVectorImpl<MatchResult> &Results) {
2878 size_t SizeBefore = Results.size();
2879 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
2880 auto *E = dyn_cast<Expr>(S);
2881 if (!E)
2882 return;
2883 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreImpCasts());
2884 if (!UO || UO->getOpcode() != UO_AddrOf)
2885 return;
2886 const auto *ASE = dyn_cast<ArraySubscriptExpr>(UO->getSubExpr());
2887 if (!ASE)
2888 return;
2889 const auto *DRE =
2890 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts());
2891 if (!DRE || !isSupportedVariable(*DRE))
2892 return;
2893 MatchResult R;
2894 R.addNode(UPCAddressofArraySubscriptTag, DynTypedNode::create(*UO));
2895 Results.emplace_back(std::move(R));
2896 });
2897 return SizeBefore != Results.size();
2898 }
2899
2900 virtual std::optional<FixItList>
2901 getFixits(const FixitStrategy &) const override;
2902 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
2903
2904 virtual DeclUseList getClaimedVarUseSites() const override {
2905 const auto *ArraySubst = cast<ArraySubscriptExpr>(Node->getSubExpr());
2906 const auto *DRE =
2907 cast<DeclRefExpr>(ArraySubst->getBase()->IgnoreParenImpCasts());
2908 return {DRE};
2909 }
2910};
2911} // namespace
2912
2913namespace {
2914// An auxiliary tracking facility for the fixit analysis. It helps connect
2915// declarations to its uses and make sure we've covered all uses with our
2916// analysis before we try to fix the declaration.
2917class DeclUseTracker {
2918 using UseSetTy = llvm::SmallPtrSet<const DeclRefExpr *, 16>;
2919 using DefMapTy = llvm::DenseMap<const VarDecl *, const DeclStmt *>;
2920
2921 // Allocate on the heap for easier move.
2922 std::unique_ptr<UseSetTy> Uses{std::make_unique<UseSetTy>()};
2923 DefMapTy Defs{};
2924
2925public:
2926 DeclUseTracker() = default;
2927 DeclUseTracker(const DeclUseTracker &) = delete; // Let's avoid copies.
2928 DeclUseTracker &operator=(const DeclUseTracker &) = delete;
2929 DeclUseTracker(DeclUseTracker &&) = default;
2930 DeclUseTracker &operator=(DeclUseTracker &&) = default;
2931
2932 // Start tracking a freshly discovered DRE.
2933 void discoverUse(const DeclRefExpr *DRE) { Uses->insert(DRE); }
2934
2935 // Stop tracking the DRE as it's been fully figured out.
2936 void claimUse(const DeclRefExpr *DRE) {
2937 assert(Uses->count(DRE) &&
2938 "DRE not found or claimed by multiple matchers!");
2939 Uses->erase(DRE);
2940 }
2941
2942 // A variable is unclaimed if at least one use is unclaimed.
2943 bool hasUnclaimedUses(const VarDecl *VD) const {
2944 // FIXME: Can this be less linear? Maybe maintain a map from VDs to DREs?
2945 return any_of(*Uses, [VD](const DeclRefExpr *DRE) {
2946 return DRE->getDecl()->getCanonicalDecl() == VD->getCanonicalDecl();
2947 });
2948 }
2949
2950 UseSetTy getUnclaimedUses(const VarDecl *VD) const {
2951 UseSetTy ReturnSet;
2952 for (auto use : *Uses) {
2953 if (use->getDecl()->getCanonicalDecl() == VD->getCanonicalDecl()) {
2954 ReturnSet.insert(use);
2955 }
2956 }
2957 return ReturnSet;
2958 }
2959
2960 void discoverDecl(const DeclStmt *DS) {
2961 for (const Decl *D : DS->decls()) {
2962 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2963 // FIXME: Assertion temporarily disabled due to a bug in
2964 // ASTMatcher internal behavior in presence of GNU
2965 // statement-expressions. We need to properly investigate this
2966 // because it can screw up our algorithm in other ways.
2967 // assert(Defs.count(VD) == 0 && "Definition already discovered!");
2968 Defs[VD] = DS;
2969 }
2970 }
2971 }
2972
2973 const DeclStmt *lookupDecl(const VarDecl *VD) const {
2974 return Defs.lookup(VD);
2975 }
2976};
2977} // namespace
2978
2979// Representing a pointer type expression of the form `++Ptr` in an Unspecified
2980// Pointer Context (UPC):
2981class UPCPreIncrementGadget : public FixableGadget {
2982private:
2983 static constexpr const char *const UPCPreIncrementTag =
2984 "PointerPreIncrementUnderUPC";
2985 const UnaryOperator *Node; // the `++Ptr` node
2986
2987public:
2988 UPCPreIncrementGadget(const MatchResult &Result)
2989 : FixableGadget(Kind::UPCPreIncrement),
2990 Node(Result.getNodeAs<UnaryOperator>(UPCPreIncrementTag)) {
2991 assert(Node != nullptr && "Expecting a non-null matching result");
2992 }
2993
2994 static bool classof(const Gadget *G) {
2995 return G->getKind() == Kind::UPCPreIncrement;
2996 }
2997
2998 static bool matches(const Stmt *S,
3000 // Note here we match `++Ptr` for any expression `Ptr` of pointer type.
3001 // Although currently we can only provide fix-its when `Ptr` is a DRE, we
3002 // can have the matcher be general, so long as `getClaimedVarUseSites` does
3003 // things right.
3004 size_t SizeBefore = Results.size();
3005 findStmtsInUnspecifiedPointerContext(S, [&Results](const Stmt *S) {
3006 auto *E = dyn_cast<Expr>(S);
3007 if (!E)
3008 return;
3009 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreImpCasts());
3010 if (!UO || UO->getOpcode() != UO_PreInc)
3011 return;
3012 const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
3013 if (!DRE || !isSupportedVariable(*DRE))
3014 return;
3015 MatchResult R;
3016 R.addNode(UPCPreIncrementTag, DynTypedNode::create(*UO));
3017 Results.emplace_back(std::move(R));
3018 });
3019 return SizeBefore != Results.size();
3020 }
3021
3022 virtual std::optional<FixItList>
3023 getFixits(const FixitStrategy &S) const override;
3024 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
3025
3026 virtual DeclUseList getClaimedVarUseSites() const override {
3027 return {dyn_cast<DeclRefExpr>(Node->getSubExpr())};
3028 }
3029};
3030
3031// Representing a pointer type expression of the form `Ptr += n` in an
3032// Unspecified Untyped Context (UUC):
3033class UUCAddAssignGadget : public FixableGadget {
3034private:
3035 static constexpr const char *const UUCAddAssignTag =
3036 "PointerAddAssignUnderUUC";
3037 static constexpr const char *const OffsetTag = "Offset";
3038
3039 const BinaryOperator *Node; // the `Ptr += n` node
3040 const Expr *Offset = nullptr;
3041
3042public:
3043 UUCAddAssignGadget(const MatchResult &Result)
3044 : FixableGadget(Kind::UUCAddAssign),
3045 Node(Result.getNodeAs<BinaryOperator>(UUCAddAssignTag)),
3046 Offset(Result.getNodeAs<Expr>(OffsetTag)) {
3047 assert(Node != nullptr && "Expecting a non-null matching result");
3048 }
3049
3050 static bool classof(const Gadget *G) {
3051 return G->getKind() == Kind::UUCAddAssign;
3052 }
3053
3054 static bool matches(const Stmt *S,
3056 size_t SizeBefore = Results.size();
3057 findStmtsInUnspecifiedUntypedContext(S, [&Results](const Stmt *S) {
3058 const auto *E = dyn_cast<Expr>(S);
3059 if (!E)
3060 return;
3061 const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreImpCasts());
3062 if (!BO || BO->getOpcode() != BO_AddAssign)
3063 return;
3064 const auto *DRE = dyn_cast<DeclRefExpr>(BO->getLHS());
3065 if (!DRE || !hasPointerType(*DRE) || !isSupportedVariable(*DRE))
3066 return;
3067 MatchResult R;
3068 R.addNode(UUCAddAssignTag, DynTypedNode::create(*BO));
3069 R.addNode(OffsetTag, DynTypedNode::create(*BO->getRHS()));
3070 Results.emplace_back(std::move(R));
3071 });
3072 return SizeBefore != Results.size();
3073 }
3074
3075 virtual std::optional<FixItList>
3076 getFixits(const FixitStrategy &S) const override;
3077 SourceLocation getSourceLoc() const override { return Node->getBeginLoc(); }
3078
3079 virtual DeclUseList getClaimedVarUseSites() const override {
3080 return {dyn_cast<DeclRefExpr>(Node->getLHS())};
3081 }
3082};
3083
3084// Representing a fixable expression of the form `*(ptr + 123)` or `*(123 +
3085// ptr)`:
3086class DerefSimplePtrArithFixableGadget : public FixableGadget {
3087 static constexpr const char *const BaseDeclRefExprTag = "BaseDRE";
3088 static constexpr const char *const DerefOpTag = "DerefOp";
3089 static constexpr const char *const AddOpTag = "AddOp";
3090 static constexpr const char *const OffsetTag = "Offset";
3091
3092 const DeclRefExpr *BaseDeclRefExpr = nullptr;
3093 const UnaryOperator *DerefOp = nullptr;
3094 const BinaryOperator *AddOp = nullptr;
3095 const IntegerLiteral *Offset = nullptr;
3096
3097public:
3099 : FixableGadget(Kind::DerefSimplePtrArithFixable),
3100 BaseDeclRefExpr(Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
3101 DerefOp(Result.getNodeAs<UnaryOperator>(DerefOpTag)),
3102 AddOp(Result.getNodeAs<BinaryOperator>(AddOpTag)),
3103 Offset(Result.getNodeAs<IntegerLiteral>(OffsetTag)) {}
3104
3105 static bool matches(const Stmt *S,
3107 auto IsPtr = [](const Expr *E, MatchResult &R) {
3108 if (!E || !hasPointerType(*E))
3109 return false;
3110 const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreImpCasts());
3111 if (!DRE || !isSupportedVariable(*DRE))
3112 return false;
3113 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
3114 return true;
3115 };
3116 const auto IsPlusOverPtrAndInteger = [&IsPtr](const Expr *E,
3117 MatchResult &R) {
3118 const auto *BO = dyn_cast<BinaryOperator>(E);
3119 if (!BO || BO->getOpcode() != BO_Add)
3120 return false;
3121
3122 const auto *LHS = BO->getLHS();
3123 const auto *RHS = BO->getRHS();
3124 if (isa<IntegerLiteral>(RHS) && IsPtr(LHS, R)) {
3125 R.addNode(OffsetTag, DynTypedNode::create(*RHS));
3126 R.addNode(AddOpTag, DynTypedNode::create(*BO));
3127 return true;
3128 }
3129 if (isa<IntegerLiteral>(LHS) && IsPtr(RHS, R)) {
3130 R.addNode(OffsetTag, DynTypedNode::create(*LHS));
3131 R.addNode(AddOpTag, DynTypedNode::create(*BO));
3132 return true;
3133 }
3134 return false;
3135 };
3136 size_t SizeBefore = Results.size();
3137 const auto InnerMatcher = [&IsPlusOverPtrAndInteger,
3138 &Results](const Expr *E) {
3139 const auto *UO = dyn_cast<UnaryOperator>(E);
3140 if (!UO || UO->getOpcode() != UO_Deref)
3141 return;
3142
3143 const auto *Operand = UO->getSubExpr()->IgnoreParens();
3144 MatchResult R;
3145 if (IsPlusOverPtrAndInteger(Operand, R)) {
3146 R.addNode(DerefOpTag, DynTypedNode::create(*UO));
3147 Results.emplace_back(std::move(R));
3148 }
3149 };
3150 findStmtsInUnspecifiedLvalueContext(S, InnerMatcher);
3151 return SizeBefore != Results.size();
3152 }
3153
3154 virtual std::optional<FixItList>
3155 getFixits(const FixitStrategy &s) const final;
3156 SourceLocation getSourceLoc() const override {
3157 return DerefOp->getBeginLoc();
3158 }
3159
3160 virtual DeclUseList getClaimedVarUseSites() const final {
3161 return {BaseDeclRefExpr};
3162 }
3163};
3164
3165class WarningGadgetMatcher : public FastMatcher {
3166
3167public:
3168 WarningGadgetMatcher(WarningGadgetList &WarningGadgets)
3169 : WarningGadgets(WarningGadgets) {}
3170
3171 bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
3172 const UnsafeBufferUsageHandler &Handler) override {
3173 const Stmt *S = DynNode.get<Stmt>();
3174 if (!S)
3175 return false;
3176
3177 MatchResult Result;
3178#define WARNING_GADGET(name) \
3179 if (name##Gadget::matches(S, Ctx, Result) && \
3180 notInSafeBufferOptOut(*S, &Handler)) { \
3181 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3182 return true; \
3183 }
3184#define WARNING_OPTIONAL_GADGET(name) \
3185 if (name##Gadget::matches(S, Ctx, &Handler, Result) && \
3186 notInSafeBufferOptOut(*S, &Handler)) { \
3187 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3188 return true; \
3189 }
3190#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3191 return false;
3192 }
3193
3194private:
3195 WarningGadgetList &WarningGadgets;
3196};
3197
3198class FixableGadgetMatcher : public FastMatcher {
3199
3200public:
3201 FixableGadgetMatcher(FixableGadgetList &FixableGadgets,
3202 DeclUseTracker &Tracker)
3203 : FixableGadgets(FixableGadgets), Tracker(Tracker) {}
3204
3205 bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
3206 const UnsafeBufferUsageHandler &Handler) override {
3207 bool matchFound = false;
3208 const Stmt *S = DynNode.get<Stmt>();
3209 if (!S) {
3210 return matchFound;
3211 }
3212
3214#define FIXABLE_GADGET(name) \
3215 if (name##Gadget::matches(S, Results)) { \
3216 for (const auto &R : Results) { \
3217 FixableGadgets.push_back(std::make_unique<name##Gadget>(R)); \
3218 matchFound = true; \
3219 } \
3220 Results = {}; \
3221 }
3222#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3223 // In parallel, match all DeclRefExprs so that to find out
3224 // whether there are any uncovered by gadgets.
3225 if (auto *DRE = findDeclRefExpr(S); DRE) {
3226 Tracker.discoverUse(DRE);
3227 matchFound = true;
3228 }
3229 // Also match DeclStmts because we'll need them when fixing
3230 // their underlying VarDecls that otherwise don't have
3231 // any backreferences to DeclStmts.
3232 if (auto *DS = findDeclStmt(S); DS) {
3233 Tracker.discoverDecl(DS);
3234 matchFound = true;
3235 }
3236 return matchFound;
3237 }
3238
3239private:
3240 const DeclRefExpr *findDeclRefExpr(const Stmt *S) {
3241 const auto *DRE = dyn_cast<DeclRefExpr>(S);
3242 if (!DRE || (!hasPointerType(*DRE) && !hasArrayType(*DRE)))
3243 return nullptr;
3244 const Decl *D = DRE->getDecl();
3245 if (!D || (!isa<VarDecl>(D) && !isa<BindingDecl>(D)))
3246 return nullptr;
3247 return DRE;
3248 }
3249 const DeclStmt *findDeclStmt(const Stmt *S) {
3250 const auto *DS = dyn_cast<DeclStmt>(S);
3251 if (!DS)
3252 return nullptr;
3253 return DS;
3254 }
3255 FixableGadgetList &FixableGadgets;
3256 DeclUseTracker &Tracker;
3257};
3258
3259// Scan the function and return a list of gadgets found with provided kits.
3260static void findGadgets(const Stmt *S, ASTContext &Ctx,
3261 const UnsafeBufferUsageHandler &Handler,
3262 bool EmitSuggestions, FixableGadgetList &FixableGadgets,
3263 WarningGadgetList &WarningGadgets,
3264 DeclUseTracker &Tracker) {
3265 WarningGadgetMatcher WMatcher{WarningGadgets};
3266 forEachDescendantEvaluatedStmt(S, Ctx, Handler, WMatcher);
3267 if (EmitSuggestions) {
3268 FixableGadgetMatcher FMatcher{FixableGadgets, Tracker};
3269 forEachDescendantStmt(S, Ctx, Handler, FMatcher);
3270 }
3271}
3272
3273// Compares AST nodes by source locations.
3274template <typename NodeTy> struct CompareNode {
3275 bool operator()(const NodeTy *N1, const NodeTy *N2) const {
3276 return N1->getBeginLoc().getRawEncoding() <
3277 N2->getBeginLoc().getRawEncoding();
3278 }
3279};
3280
3281// Populate `Stmts` with the body/initializer Stmt of `D`, if `D` is one of the
3282// followings:
3283// VarDecl
3284// FieldDecl
3285// FunctionDecl
3286// BlockDecl
3287// ObjCMethodDecl
3289 const Decl *D) {
3290 auto AddStmt = [&Stmts](const Stmt *S) {
3291 if (S)
3292 Stmts.push_back(S);
3293 };
3294 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3295 AddStmt(FD->getBody());
3296 for (const auto *PD : FD->parameters())
3297 if (PD->hasDefaultArg() && !PD->hasUninstantiatedDefaultArg())
3298 AddStmt(PD->getDefaultArg());
3299 if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(FD))
3300 llvm::append_range(
3301 Stmts, llvm::map_range(CtorD->inits(),
3302 std::mem_fn(&CXXCtorInitializer::getInit)));
3303 } else if (isa<BlockDecl>(D) || isa<ObjCMethodDecl>(D)) {
3304 AddStmt(D->getBody());
3305 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3306 AddStmt(VD->getInit()); // FIXME: default arg for ParmVarDecl?
3307 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3308 AddStmt(FD->getInClassInitializer());
3309 }
3310}
3311
3313 std::map<const VarDecl *, std::set<const WarningGadget *>,
3314 // To keep keys sorted by their locations in the map so that the
3315 // order is deterministic:
3318 // These Gadgets are not related to pointer variables (e. g. temporaries).
3320};
3321
3322static WarningGadgetSets
3323groupWarningGadgetsByVar(const WarningGadgetList &AllUnsafeOperations) {
3324 WarningGadgetSets result;
3325 // If some gadgets cover more than one
3326 // variable, they'll appear more than once in the map.
3327 for (auto &G : AllUnsafeOperations) {
3328 DeclUseList ClaimedVarUseSites = G->getClaimedVarUseSites();
3329
3330 bool AssociatedWithVarDecl = false;
3331 for (const DeclRefExpr *DRE : ClaimedVarUseSites) {
3332 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3333 result.byVar[VD].insert(G.get());
3334 AssociatedWithVarDecl = true;
3335 }
3336 }
3337
3338 if (!AssociatedWithVarDecl) {
3339 result.noVar.push_back(G.get());
3340 continue;
3341 }
3342 }
3343 return result;
3344}
3345
3347 std::map<const VarDecl *, std::set<const FixableGadget *>,
3348 // To keep keys sorted by their locations in the map so that the
3349 // order is deterministic:
3352};
3353
3354static FixableGadgetSets
3355groupFixablesByVar(FixableGadgetList &&AllFixableOperations) {
3356 FixableGadgetSets FixablesForUnsafeVars;
3357 for (auto &F : AllFixableOperations) {
3358 DeclUseList DREs = F->getClaimedVarUseSites();
3359
3360 for (const DeclRefExpr *DRE : DREs) {
3361 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3362 FixablesForUnsafeVars.byVar[VD].insert(F.get());
3363 }
3364 }
3365 }
3366 return FixablesForUnsafeVars;
3367}
3368
3370 const SourceManager &SM) {
3371 // A simple interval overlap detection algorithm. Sorts all ranges by their
3372 // begin location then finds the first overlap in one pass.
3373 std::vector<const FixItHint *> All; // a copy of `FixIts`
3374
3375 for (const FixItHint &H : FixIts)
3376 All.push_back(&H);
3377 std::sort(All.begin(), All.end(),
3378 [&SM](const FixItHint *H1, const FixItHint *H2) {
3379 return SM.isBeforeInTranslationUnit(H1->RemoveRange.getBegin(),
3380 H2->RemoveRange.getBegin());
3381 });
3382
3383 const FixItHint *CurrHint = nullptr;
3384
3385 for (const FixItHint *Hint : All) {
3386 if (!CurrHint ||
3388 Hint->RemoveRange.getBegin())) {
3389 // Either to initialize `CurrHint` or `CurrHint` does not
3390 // overlap with `Hint`:
3391 CurrHint = Hint;
3392 } else
3393 // In case `Hint` overlaps the `CurrHint`, we found at least one
3394 // conflict:
3395 return true;
3396 }
3397 return false;
3398}
3399
3400std::optional<FixItList>
3401PtrToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
3402 const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
3403 const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
3404 switch (S.lookup(LeftVD)) {
3406 if (S.lookup(RightVD) == FixitStrategy::Kind::Span)
3407 return FixItList{};
3408 return std::nullopt;
3410 return std::nullopt;
3413 return std::nullopt;
3415 llvm_unreachable("unsupported strategies for FixableGadgets");
3416 }
3417 return std::nullopt;
3418}
3419
3420/// \returns fixit that adds .data() call after \DRE.
3421static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
3422 const DeclRefExpr *DRE);
3423
3424std::optional<FixItList>
3425CArrayToPtrAssignmentGadget::getFixits(const FixitStrategy &S) const {
3426 const auto *LeftVD = cast<VarDecl>(PtrLHS->getDecl());
3427 const auto *RightVD = cast<VarDecl>(PtrRHS->getDecl());
3428 // TLDR: Implementing fixits for non-Wontfix strategy on both LHS and RHS is
3429 // non-trivial.
3430 //
3431 // CArrayToPtrAssignmentGadget doesn't have strategy implications because
3432 // constant size array propagates its bounds. Because of that LHS and RHS are
3433 // addressed by two different fixits.
3434 //
3435 // At the same time FixitStrategy S doesn't reflect what group a fixit belongs
3436 // to and can't be generally relied on in multi-variable Fixables!
3437 //
3438 // E. g. If an instance of this gadget is fixing variable on LHS then the
3439 // variable on RHS is fixed by a different fixit and its strategy for LHS
3440 // fixit is as if Wontfix.
3441 //
3442 // The only exception is Wontfix strategy for a given variable as that is
3443 // valid for any fixit produced for the given input source code.
3444 if (S.lookup(LeftVD) == FixitStrategy::Kind::Span) {
3445 if (S.lookup(RightVD) == FixitStrategy::Kind::Wontfix) {
3446 return FixItList{};
3447 }
3448 } else if (S.lookup(LeftVD) == FixitStrategy::Kind::Wontfix) {
3449 if (S.lookup(RightVD) == FixitStrategy::Kind::Array) {
3450 return createDataFixit(RightVD->getASTContext(), PtrRHS);
3451 }
3452 }
3453 return std::nullopt;
3454}
3455
3456std::optional<FixItList>
3457PointerInitGadget::getFixits(const FixitStrategy &S) const {
3458 const auto *LeftVD = PtrInitLHS;
3459 const auto *RightVD = cast<VarDecl>(PtrInitRHS->getDecl());
3460 switch (S.lookup(LeftVD)) {
3461 case FixitStrategy::Kind::Span:
3462 if (S.lookup(RightVD) == FixitStrategy::Kind::Span)
3463 return FixItList{};
3464 return std::nullopt;
3465 case FixitStrategy::Kind::Wontfix:
3466 return std::nullopt;
3467 case FixitStrategy::Kind::Iterator:
3468 case FixitStrategy::Kind::Array:
3469 return std::nullopt;
3470 case FixitStrategy::Kind::Vector:
3471 llvm_unreachable("unsupported strategies for FixableGadgets");
3472 }
3473 return std::nullopt;
3474}
3475
3476static bool isNonNegativeIntegerExpr(const Expr *Expr, const VarDecl *VD,
3477 const ASTContext &Ctx) {
3478 if (auto ConstVal = Expr->getIntegerConstantExpr(Ctx)) {
3479 if (ConstVal->isNegative())
3480 return false;
3481 } else if (!Expr->getType()->isUnsignedIntegerType())
3482 return false;
3483 return true;
3484}
3485
3486std::optional<FixItList>
3487ULCArraySubscriptGadget::getFixits(const FixitStrategy &S) const {
3488 if (const auto *DRE =
3489 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts()))
3490 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3491 switch (S.lookup(VD)) {
3492 case FixitStrategy::Kind::Span: {
3493
3494 // If the index has a negative constant value, we give up as no valid
3495 // fix-it can be generated:
3496 const ASTContext &Ctx = // FIXME: we need ASTContext to be passed in!
3497 VD->getASTContext();
3498 if (!isNonNegativeIntegerExpr(Node->getIdx(), VD, Ctx))
3499 return std::nullopt;
3500 // no-op is a good fix-it, otherwise
3501 return FixItList{};
3502 }
3503 case FixitStrategy::Kind::Array:
3504 return FixItList{};
3505 case FixitStrategy::Kind::Wontfix:
3506 case FixitStrategy::Kind::Iterator:
3507 case FixitStrategy::Kind::Vector:
3508 llvm_unreachable("unsupported strategies for FixableGadgets");
3509 }
3510 }
3511 return std::nullopt;
3512}
3513
3514static std::optional<FixItList> // forward declaration
3515fixUPCAddressofArraySubscriptWithSpan(const UnaryOperator *Node);
3516
3517std::optional<FixItList>
3518UPCAddressofArraySubscriptGadget::getFixits(const FixitStrategy &S) const {
3519 auto DREs = getClaimedVarUseSites();
3520 const auto *VD = cast<VarDecl>(DREs.front()->getDecl());
3521
3522 switch (S.lookup(VD)) {
3523 case FixitStrategy::Kind::Span:
3525 case FixitStrategy::Kind::Wontfix:
3526 case FixitStrategy::Kind::Iterator:
3527 case FixitStrategy::Kind::Array:
3528 return std::nullopt;
3529 case FixitStrategy::Kind::Vector:
3530 llvm_unreachable("unsupported strategies for FixableGadgets");
3531 }
3532 return std::nullopt; // something went wrong, no fix-it
3533}
3534
3535// FIXME: this function should be customizable through format
3536static StringRef getEndOfLine() {
3537 static const char *const EOL = "\n";
3538 return EOL;
3539}
3540
3541// Returns the text indicating that the user needs to provide input there:
3542static std::string
3543getUserFillPlaceHolder(StringRef HintTextToUser = "placeholder") {
3544 std::string s = std::string("<# ");
3545 s += HintTextToUser;
3546 s += " #>";
3547 return s;
3548}
3549
3550// Return the source location of the last character of the AST `Node`.
3551template <typename NodeTy>
3552static std::optional<SourceLocation>
3553getEndCharLoc(const NodeTy *Node, const SourceManager &SM,
3554 const LangOptions &LangOpts) {
3555 if (unsigned TkLen =
3556 Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts)) {
3557 SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
3558
3559 if (Loc.isValid())
3560 return Loc;
3561 }
3562 return std::nullopt;
3563}
3564
3565// We cannot fix a variable declaration if it has some other specifiers than the
3566// type specifier. Because the source ranges of those specifiers could overlap
3567// with the source range that is being replaced using fix-its. Especially when
3568// we often cannot obtain accurate source ranges of cv-qualified type
3569// specifiers.
3570// FIXME: also deal with type attributes
3571static bool hasUnsupportedSpecifiers(const VarDecl *VD,
3572 const SourceManager &SM) {
3573 // AttrRangeOverlapping: true if at least one attribute of `VD` overlaps the
3574 // source range of `VD`:
3575 bool AttrRangeOverlapping = llvm::any_of(VD->attrs(), [&](Attr *At) -> bool {
3576 return !(SM.isBeforeInTranslationUnit(At->getRange().getEnd(),
3577 VD->getBeginLoc())) &&
3578 !(SM.isBeforeInTranslationUnit(VD->getEndLoc(),
3579 At->getRange().getBegin()));
3580 });
3581 return VD->isInlineSpecified() || VD->isConstexpr() ||
3583 AttrRangeOverlapping;
3584}
3585
3586// Returns the `SourceRange` of `D`. The reason why this function exists is
3587// that `D->getSourceRange()` may return a range where the end location is the
3588// starting location of the last token. The end location of the source range
3589// returned by this function is the last location of the last token.
3591 const SourceManager &SM,
3592 const LangOptions &LangOpts) {
3593 SourceLocation Begin = D->getBeginLoc();
3595 End = // `D->getEndLoc` should always return the starting location of the
3596 // last token, so we should get the end of the token
3597 Lexer::getLocForEndOfToken(D->getEndLoc(), 0, SM, LangOpts);
3598
3599 return SourceRange(Begin, End);
3600}
3601
3602// Returns the text of the name (with qualifiers) of a `FunctionDecl`.
3603static std::optional<StringRef> getFunNameText(const FunctionDecl *FD,
3604 const SourceManager &SM,
3605 const LangOptions &LangOpts) {
3606 SourceLocation BeginLoc = FD->getQualifier()
3608 : FD->getNameInfo().getBeginLoc();
3609 // Note that `FD->getNameInfo().getEndLoc()` returns the begin location of the
3610 // last token:
3612 FD->getNameInfo().getEndLoc(), 0, SM, LangOpts);
3613 SourceRange NameRange{BeginLoc, EndLoc};
3614
3615 return getRangeText(NameRange, SM, LangOpts);
3616}
3617
3618// Returns the text representing a `std::span` type where the element type is
3619// represented by `EltTyText`.
3620//
3621// Note the optional parameter `Qualifiers`: one needs to pass qualifiers
3622// explicitly if the element type needs to be qualified.
3623static std::string
3624getSpanTypeText(StringRef EltTyText,
3625 std::optional<Qualifiers> Quals = std::nullopt) {
3626 const char *const SpanOpen = "std::span<";
3627
3628 if (Quals)
3629 return SpanOpen + EltTyText.str() + ' ' + Quals->getAsString() + '>';
3630 return SpanOpen + EltTyText.str() + '>';
3631}
3632
3633std::optional<FixItList>
3635 const VarDecl *VD = dyn_cast<VarDecl>(BaseDeclRefExpr->getDecl());
3636
3637 if (VD && s.lookup(VD) == FixitStrategy::Kind::Span) {
3638 ASTContext &Ctx = VD->getASTContext();
3639 // std::span can't represent elements before its begin()
3640 if (auto ConstVal = Offset->getIntegerConstantExpr(Ctx))
3641 if (ConstVal->isNegative())
3642 return std::nullopt;
3643
3644 // note that the expr may (oddly) has multiple layers of parens
3645 // example:
3646 // *((..(pointer + 123)..))
3647 // goal:
3648 // pointer[123]
3649 // Fix-It:
3650 // remove '*('
3651 // replace ' + ' with '['
3652 // replace ')' with ']'
3653
3654 // example:
3655 // *((..(123 + pointer)..))
3656 // goal:
3657 // 123[pointer]
3658 // Fix-It:
3659 // remove '*('
3660 // replace ' + ' with '['
3661 // replace ')' with ']'
3662
3663 const Expr *LHS = AddOp->getLHS(), *RHS = AddOp->getRHS();
3664 const SourceManager &SM = Ctx.getSourceManager();
3665 const LangOptions &LangOpts = Ctx.getLangOpts();
3666 CharSourceRange StarWithTrailWhitespace =
3667 clang::CharSourceRange::getCharRange(DerefOp->getOperatorLoc(),
3668 LHS->getBeginLoc());
3669
3670 std::optional<SourceLocation> LHSLocation = getPastLoc(LHS, SM, LangOpts);
3671 if (!LHSLocation)
3672 return std::nullopt;
3673
3674 CharSourceRange PlusWithSurroundingWhitespace =
3675 clang::CharSourceRange::getCharRange(*LHSLocation, RHS->getBeginLoc());
3676
3677 std::optional<SourceLocation> AddOpLocation =
3678 getPastLoc(AddOp, SM, LangOpts);
3679 std::optional<SourceLocation> DerefOpLocation =
3680 getPastLoc(DerefOp, SM, LangOpts);
3681
3682 if (!AddOpLocation || !DerefOpLocation)
3683 return std::nullopt;
3684
3685 CharSourceRange ClosingParenWithPrecWhitespace =
3686 clang::CharSourceRange::getCharRange(*AddOpLocation, *DerefOpLocation);
3687
3688 return FixItList{
3689 {FixItHint::CreateRemoval(StarWithTrailWhitespace),
3690 FixItHint::CreateReplacement(PlusWithSurroundingWhitespace, "["),
3691 FixItHint::CreateReplacement(ClosingParenWithPrecWhitespace, "]")}};
3692 }
3693 return std::nullopt; // something wrong or unsupported, give up
3694}
3695
3696std::optional<FixItList>
3697PointerDereferenceGadget::getFixits(const FixitStrategy &S) const {
3698 const VarDecl *VD = cast<VarDecl>(BaseDeclRefExpr->getDecl());
3699 switch (S.lookup(VD)) {
3701 ASTContext &Ctx = VD->getASTContext();
3702 SourceManager &SM = Ctx.getSourceManager();
3703 // Required changes: *(ptr); => (ptr[0]); and *ptr; => ptr[0]
3704 // Deletes the *operand
3706 Op->getBeginLoc(), Op->getBeginLoc().getLocWithOffset(1));
3707 // Inserts the [0]
3708 if (auto LocPastOperand =
3709 getPastLoc(BaseDeclRefExpr, SM, Ctx.getLangOpts())) {
3710 return FixItList{{FixItHint::CreateRemoval(derefRange),
3711 FixItHint::CreateInsertion(*LocPastOperand, "[0]")}};
3712 }
3713 break;
3714 }
3715 case FixitStrategy::Kind::Iterator:
3716 case FixitStrategy::Kind::Array:
3717 return std::nullopt;
3718 case FixitStrategy::Kind::Vector:
3719 llvm_unreachable("FixitStrategy not implemented yet!");
3720 case FixitStrategy::Kind::Wontfix:
3721 llvm_unreachable("Invalid strategy!");
3722 }
3723
3724 return std::nullopt;
3725}
3726
3727static inline std::optional<FixItList> createDataFixit(const ASTContext &Ctx,
3728 const DeclRefExpr *DRE) {
3729 const SourceManager &SM = Ctx.getSourceManager();
3730 // Inserts the .data() after the DRE
3731 std::optional<SourceLocation> EndOfOperand =
3732 getPastLoc(DRE, SM, Ctx.getLangOpts());
3733
3734 if (EndOfOperand)
3735 return FixItList{{FixItHint::CreateInsertion(*EndOfOperand, ".data()")}};
3736
3737 return std::nullopt;
3738}
3739
3740// Generates fix-its replacing an expression of the form UPC(DRE) with
3741// `DRE.data()`
3742std::optional<FixItList>
3743UPCStandalonePointerGadget::getFixits(const FixitStrategy &S) const {
3744 const auto VD = cast<VarDecl>(Node->getDecl());
3745 switch (S.lookup(VD)) {
3746 case FixitStrategy::Kind::Array:
3747 case FixitStrategy::Kind::Span: {
3748 return createDataFixit(VD->getASTContext(), Node);
3749 // FIXME: Points inside a macro expansion.
3750 break;
3751 }
3752 case FixitStrategy::Kind::Wontfix:
3753 case FixitStrategy::Kind::Iterator:
3754 return std::nullopt;
3755 case FixitStrategy::Kind::Vector:
3756 llvm_unreachable("unsupported strategies for FixableGadgets");
3757 }
3758
3759 return std::nullopt;
3760}
3761
3762// Generates fix-its replacing an expression of the form `&DRE[e]` with
3763// `&DRE.data()[e]`:
3764static std::optional<FixItList>
3766 const auto *ArraySub = cast<ArraySubscriptExpr>(Node->getSubExpr());
3767 const auto *DRE = cast<DeclRefExpr>(ArraySub->getBase()->IgnoreImpCasts());
3768 // FIXME: this `getASTContext` call is costly, we should pass the
3769 // ASTContext in:
3770 const ASTContext &Ctx = DRE->getDecl()->getASTContext();
3771 const Expr *Idx = ArraySub->getIdx();
3772 const SourceManager &SM = Ctx.getSourceManager();
3773 const LangOptions &LangOpts = Ctx.getLangOpts();
3774 std::stringstream SS;
3775 bool IdxIsLitZero = false;
3776
3777 if (auto ICE = Idx->getIntegerConstantExpr(Ctx))
3778 if ((*ICE).isZero())
3779 IdxIsLitZero = true;
3780 std::optional<StringRef> DreString = getExprText(DRE, SM, LangOpts);
3781 if (!DreString)
3782 return std::nullopt;
3783
3784 if (IdxIsLitZero) {
3785 // If the index is literal zero, we produce the most concise fix-it:
3786 SS << (*DreString).str() << ".data()";
3787 } else {
3788 std::optional<StringRef> IndexString = getExprText(Idx, SM, LangOpts);
3789 if (!IndexString)
3790 return std::nullopt;
3791
3792 SS << "&" << (*DreString).str() << ".data()"
3793 << "[" << (*IndexString).str() << "]";
3794 }
3795 return FixItList{
3796 FixItHint::CreateReplacement(Node->getSourceRange(), SS.str())};
3797}
3798
3799std::optional<FixItList>
3801 DeclUseList DREs = getClaimedVarUseSites();
3802
3803 if (DREs.size() != 1)
3804 return std::nullopt; // In cases of `Ptr += n` where `Ptr` is not a DRE, we
3805 // give up
3806 if (const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3807 if (S.lookup(VD) == FixitStrategy::Kind::Span) {
3808 FixItList Fixes;
3809
3810 const Stmt *AddAssignNode = Node;
3811 StringRef varName = VD->getName();
3812 const ASTContext &Ctx = VD->getASTContext();
3813
3814 if (!isNonNegativeIntegerExpr(Offset, VD, Ctx))
3815 return std::nullopt;
3816
3817 // To transform UUC(p += n) to UUC(p = p.subspan(..)):
3818 bool NotParenExpr =
3819 (Offset->IgnoreParens()->getBeginLoc() == Offset->getBeginLoc());
3820 std::string SS = varName.str() + " = " + varName.str() + ".subspan";
3821 if (NotParenExpr)
3822 SS += "(";
3823
3824 std::optional<SourceLocation> AddAssignLocation = getEndCharLoc(
3825 AddAssignNode, Ctx.getSourceManager(), Ctx.getLangOpts());
3826 if (!AddAssignLocation)
3827 return std::nullopt;
3828
3829 Fixes.push_back(FixItHint::CreateReplacement(
3830 SourceRange(AddAssignNode->getBeginLoc(), Node->getOperatorLoc()),
3831 SS));
3832 if (NotParenExpr)
3833 Fixes.push_back(FixItHint::CreateInsertion(
3834 Offset->getEndLoc().getLocWithOffset(1), ")"));
3835 return Fixes;
3836 }
3837 }
3838 return std::nullopt; // Not in the cases that we can handle for now, give up.
3839}
3840
3841std::optional<FixItList>
3843 DeclUseList DREs = getClaimedVarUseSites();
3844
3845 if (DREs.size() != 1)
3846 return std::nullopt; // In cases of `++Ptr` where `Ptr` is not a DRE, we
3847 // give up
3848 if (const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3849 if (S.lookup(VD) == FixitStrategy::Kind::Span) {
3850 FixItList Fixes;
3851 std::stringstream SS;
3852 StringRef varName = VD->getName();
3853 const ASTContext &Ctx = VD->getASTContext();
3854
3855 // To transform UPC(++p) to UPC((p = p.subspan(1)).data()):
3856 SS << "(" << varName.data() << " = " << varName.data()
3857 << ".subspan(1)).data()";
3858 std::optional<SourceLocation> PreIncLocation =
3859 getEndCharLoc(Node, Ctx.getSourceManager(), Ctx.getLangOpts());
3860 if (!PreIncLocation)
3861 return std::nullopt;
3862
3863 Fixes.push_back(FixItHint::CreateReplacement(
3864 SourceRange(Node->getBeginLoc(), *PreIncLocation), SS.str()));
3865 return Fixes;
3866 }
3867 }
3868 return std::nullopt; // Not in the cases that we can handle for now, give up.
3869}
3870
3871// For a non-null initializer `Init` of `T *` type, this function returns
3872// `FixItHint`s producing a list initializer `{Init, S}` as a part of a fix-it
3873// to output stream.
3874// In many cases, this function cannot figure out the actual extent `S`. It
3875// then will use a place holder to replace `S` to ask users to fill `S` in. The
3876// initializer shall be used to initialize a variable of type `std::span<T>`.
3877// In some cases (e. g. constant size array) the initializer should remain
3878// unchanged and the function returns empty list. In case the function can't
3879// provide the right fixit it will return nullopt.
3880//
3881// FIXME: Support multi-level pointers
3882//
3883// Parameters:
3884// `Init` a pointer to the initializer expression
3885// `Ctx` a reference to the ASTContext
3886static std::optional<FixItList>
3888 const StringRef UserFillPlaceHolder) {
3889 const SourceManager &SM = Ctx.getSourceManager();
3890 const LangOptions &LangOpts = Ctx.getLangOpts();
3891
3892 // If `Init` has a constant value that is (or equivalent to) a
3893 // NULL pointer, we use the default constructor to initialize the span
3894 // object, i.e., a `std:span` variable declaration with no initializer.
3895 // So the fix-it is just to remove the initializer.
3896 if (Init->isNullPointerConstant(
3897 Ctx,
3898 // FIXME: Why does this function not ask for `const ASTContext
3899 // &`? It should. Maybe worth an NFC patch later.
3901 NPC_ValueDependentIsNotNull)) {
3902 std::optional<SourceLocation> InitLocation =
3903 getEndCharLoc(Init, SM, LangOpts);
3904 if (!InitLocation)
3905 return std::nullopt;
3906
3907 SourceRange SR(Init->getBeginLoc(), *InitLocation);
3908
3909 return FixItList{FixItHint::CreateRemoval(SR)};
3910 }
3911
3912 FixItList FixIts{};
3913 std::string ExtentText = UserFillPlaceHolder.data();
3914 StringRef One = "1";
3915
3916 // Insert `{` before `Init`:
3917 FixIts.push_back(FixItHint::CreateInsertion(Init->getBeginLoc(), "{"));
3918 // Try to get the data extent. Break into different cases:
3919 if (auto CxxNew = dyn_cast<CXXNewExpr>(Init->IgnoreImpCasts())) {
3920 // In cases `Init` is `new T[n]` and there is no explicit cast over
3921 // `Init`, we know that `Init` must evaluates to a pointer to `n` objects
3922 // of `T`. So the extent is `n` unless `n` has side effects. Similar but
3923 // simpler for the case where `Init` is `new T`.
3924 if (const Expr *Ext = CxxNew->getArraySize().value_or(nullptr)) {
3925 if (!Ext->HasSideEffects(Ctx)) {
3926 std::optional<StringRef> ExtentString = getExprText(Ext, SM, LangOpts);
3927 if (!ExtentString)
3928 return std::nullopt;
3929 ExtentText = *ExtentString;
3930 }
3931 } else if (!CxxNew->isArray())
3932 // Although the initializer is not allocating a buffer, the pointer
3933 // variable could still be used in buffer access operations.
3934 ExtentText = One;
3935 } else if (Ctx.getAsConstantArrayType(Init->IgnoreImpCasts()->getType())) {
3936 // std::span has a single parameter constructor for initialization with
3937 // constant size array. The size is auto-deduced as the constructor is a
3938 // function template. The correct fixit is empty - no changes should happen.
3939 return FixItList{};
3940 } else {
3941 // In cases `Init` is of the form `&Var` after stripping of implicit
3942 // casts, where `&` is the built-in operator, the extent is 1.
3943 if (auto AddrOfExpr = dyn_cast<UnaryOperator>(Init->IgnoreImpCasts()))
3944 if (AddrOfExpr->getOpcode() == UnaryOperatorKind::UO_AddrOf &&
3945 isa_and_present<DeclRefExpr>(AddrOfExpr->getSubExpr()))
3946 ExtentText = One;
3947 // TODO: we can handle more cases, e.g., `&a[0]`, `&a`, `std::addressof`,
3948 // and explicit casting, etc. etc.
3949 }
3950
3951 SmallString<32> StrBuffer{};
3952 std::optional<SourceLocation> LocPassInit = getPastLoc(Init, SM, LangOpts);
3953
3954 if (!LocPassInit)
3955 return std::nullopt;
3956
3957 StrBuffer.append(", ");
3958 StrBuffer.append(ExtentText);
3959 StrBuffer.append("}");
3960 FixIts.push_back(FixItHint::CreateInsertion(*LocPassInit, StrBuffer.str()));
3961 return FixIts;
3962}
3963
3964#ifndef NDEBUG
3965#define DEBUG_NOTE_DECL_FAIL(D, Msg) \
3966 Handler.addDebugNoteForVar((D), (D)->getBeginLoc(), \
3967 "failed to produce fixit for declaration '" + \
3968 (D)->getNameAsString() + "'" + (Msg))
3969#else
3970#define DEBUG_NOTE_DECL_FAIL(D, Msg)
3971#endif
3972
3973// For the given variable declaration with a pointer-to-T type, returns the text
3974// `std::span<T>`. If it is unable to generate the text, returns
3975// `std::nullopt`.
3976static std::optional<std::string>
3978 assert(VD->getType()->isPointerType());
3979
3980 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
3981 std::optional<std::string> PteTyText = getPointeeTypeText(
3982 VD, Ctx.getSourceManager(), Ctx.getLangOpts(), &PteTyQualifiers);
3983
3984 if (!PteTyText)
3985 return std::nullopt;
3986
3987 std::string SpanTyText = "std::span<";
3988
3989 SpanTyText.append(*PteTyText);
3990 // Append qualifiers to span element type if any:
3991 if (PteTyQualifiers) {
3992 SpanTyText.append(" ");
3993 SpanTyText.append(PteTyQualifiers->getAsString());
3994 }
3995 SpanTyText.append(">");
3996 return SpanTyText;
3997}
3998
3999// For a `VarDecl` of the form `T * var (= Init)?`, this
4000// function generates fix-its that
4001// 1) replace `T * var` with `std::span<T> var`; and
4002// 2) change `Init` accordingly to a span constructor, if it exists.
4003//
4004// FIXME: support Multi-level pointers
4005//
4006// Parameters:
4007// `D` a pointer the variable declaration node
4008// `Ctx` a reference to the ASTContext
4009// `UserFillPlaceHolder` the user-input placeholder text
4010// Returns:
4011// the non-empty fix-it list, if fix-its are successfuly generated; empty
4012// list otherwise.
4013static FixItList fixLocalVarDeclWithSpan(const VarDecl *D, ASTContext &Ctx,
4014 const StringRef UserFillPlaceHolder,
4015 UnsafeBufferUsageHandler &Handler) {
4017 return {};
4018
4019 FixItList FixIts{};
4020 std::optional<std::string> SpanTyText = createSpanTypeForVarDecl(D, Ctx);
4021
4022 if (!SpanTyText) {
4023 DEBUG_NOTE_DECL_FAIL(D, " : failed to generate 'std::span' type");
4024 return {};
4025 }
4026
4027 // Will hold the text for `std::span<T> Ident`:
4028 std::stringstream SS;
4029
4030 SS << *SpanTyText;
4031 // Fix the initializer if it exists:
4032 if (const Expr *Init = D->getInit()) {
4033 std::optional<FixItList> InitFixIts =
4034 FixVarInitializerWithSpan(Init, Ctx, UserFillPlaceHolder);
4035 if (!InitFixIts)
4036 return {};
4037 FixIts.insert(FixIts.end(), std::make_move_iterator(InitFixIts->begin()),
4038 std::make_move_iterator(InitFixIts->end()));
4039 }
4040 // For declaration of the form `T * ident = init;`, we want to replace
4041 // `T * ` with `std::span<T>`.
4042 // We ignore CV-qualifiers so for `T * const ident;` we also want to replace
4043 // just `T *` with `std::span<T>`.
4044 const SourceLocation EndLocForReplacement = D->getTypeSpecEndLoc();
4045 if (!EndLocForReplacement.isValid()) {
4046 DEBUG_NOTE_DECL_FAIL(D, " : failed to locate the end of the declaration");
4047 return {};
4048 }
4049 // The only exception is that for `T *ident` we'll add a single space between
4050 // "std::span<T>" and "ident".
4051 // FIXME: The condition is false for identifiers expended from macros.
4052 if (EndLocForReplacement.getLocWithOffset(1) == getVarDeclIdentifierLoc(D))
4053 SS << " ";
4054
4055 FixIts.push_back(FixItHint::CreateReplacement(
4056 SourceRange(D->getBeginLoc(), EndLocForReplacement), SS.str()));
4057 return FixIts;
4058}
4059
4060static bool hasConflictingOverload(const FunctionDecl *FD) {
4061 return !FD->getDeclContext()->lookup(FD->getDeclName()).isSingleResult();
4062}
4063
4064// For a `FunctionDecl`, whose `ParmVarDecl`s are being changed to have new
4065// types, this function produces fix-its to make the change self-contained. Let
4066// 'F' be the entity defined by the original `FunctionDecl` and "NewF" be the
4067// entity defined by the `FunctionDecl` after the change to the parameters.
4068// Fix-its produced by this function are
4069// 1. Add the `[[clang::unsafe_buffer_usage]]` attribute to each declaration
4070// of 'F';
4071// 2. Create a declaration of "NewF" next to each declaration of `F`;
4072// 3. Create a definition of "F" (as its original definition is now belongs
4073// to "NewF") next to its original definition. The body of the creating
4074// definition calls to "NewF".
4075//
4076// Example:
4077//
4078// void f(int *p); // original declaration
4079// void f(int *p) { // original definition
4080// p[5];
4081// }
4082//
4083// To change the parameter `p` to be of `std::span<int>` type, we
4084// also add overloads:
4085//
4086// [[clang::unsafe_buffer_usage]] void f(int *p); // original decl
4087// void f(std::span<int> p); // added overload decl
4088// void f(std::span<int> p) { // original def where param is changed
4089// p[5];
4090// }
4091// [[clang::unsafe_buffer_usage]] void f(int *p) { // added def
4092// return f(std::span(p, <# size #>));
4093// }
4094//
4095static std::optional<FixItList>
4097 const ASTContext &Ctx,
4098 UnsafeBufferUsageHandler &Handler) {
4099 // FIXME: need to make this conflict checking better:
4100 if (hasConflictingOverload(FD))
4101 return std::nullopt;
4102
4103 const SourceManager &SM = Ctx.getSourceManager();
4104 const LangOptions &LangOpts = Ctx.getLangOpts();
4105 const unsigned NumParms = FD->getNumParams();
4106 std::vector<std::string> NewTysTexts(NumParms);
4107 std::vector<bool> ParmsMask(NumParms, false);
4108 bool AtLeastOneParmToFix = false;
4109
4110 for (unsigned i = 0; i < NumParms; i++) {
4111 const ParmVarDecl *PVD = FD->getParamDecl(i);
4112
4114 continue;
4115 if (S.lookup(PVD) != FixitStrategy::Kind::Span)
4116 // Not supported, not suppose to happen:
4117 return std::nullopt;
4118
4119 std::optional<Qualifiers> PteTyQuals = std::nullopt;
4120 std::optional<std::string> PteTyText =
4121 getPointeeTypeText(PVD, SM, LangOpts, &PteTyQuals);
4122
4123 if (!PteTyText)
4124 // something wrong in obtaining the text of the pointee type, give up
4125 return std::nullopt;
4126 // FIXME: whether we should create std::span type depends on the
4127 // FixitStrategy.
4128 NewTysTexts[i] = getSpanTypeText(*PteTyText, PteTyQuals);
4129 ParmsMask[i] = true;
4130 AtLeastOneParmToFix = true;
4131 }
4132 if (!AtLeastOneParmToFix)
4133 // No need to create function overloads:
4134 return {};
4135 // FIXME Respect indentation of the original code.
4136
4137 // A lambda that creates the text representation of a function declaration
4138 // with the new type signatures:
4139 const auto NewOverloadSignatureCreator =
4140 [&SM, &LangOpts, &NewTysTexts,
4141 &ParmsMask](const FunctionDecl *FD) -> std::optional<std::string> {
4142 std::stringstream SS;
4143
4144 SS << ";";
4145 SS << getEndOfLine().str();
4146 // Append: ret-type func-name "("
4147 if (auto Prefix = getRangeText(
4148 SourceRange(FD->getBeginLoc(), (*FD->param_begin())->getBeginLoc()),
4149 SM, LangOpts))
4150 SS << Prefix->str();
4151 else
4152 return std::nullopt; // give up
4153 // Append: parameter-type-list
4154 const unsigned NumParms = FD->getNumParams();
4155
4156 for (unsigned i = 0; i < NumParms; i++) {
4157 const ParmVarDecl *Parm = FD->getParamDecl(i);
4158
4159 if (Parm->isImplicit())
4160 continue;
4161 if (ParmsMask[i]) {
4162 // This `i`-th parameter will be fixed with `NewTysTexts[i]` being its
4163 // new type:
4164 SS << NewTysTexts[i];
4165 // print parameter name if provided:
4166 if (IdentifierInfo *II = Parm->getIdentifier())
4167 SS << ' ' << II->getName().str();
4168 } else if (auto ParmTypeText =
4169 getRangeText(getSourceRangeToTokenEnd(Parm, SM, LangOpts),
4170 SM, LangOpts)) {
4171 // print the whole `Parm` without modification:
4172 SS << ParmTypeText->str();
4173 } else
4174 return std::nullopt; // something wrong, give up
4175 if (i != NumParms - 1)
4176 SS << ", ";
4177 }
4178 SS << ")";
4179 return SS.str();
4180 };
4181
4182 // A lambda that creates the text representation of a function definition with
4183 // the original signature:
4184 const auto OldOverloadDefCreator =
4185 [&Handler, &SM, &LangOpts, &NewTysTexts,
4186 &ParmsMask](const FunctionDecl *FD) -> std::optional<std::string> {
4187 std::stringstream SS;
4188
4189 SS << getEndOfLine().str();
4190 // Append: attr-name ret-type func-name "(" param-list ")" "{"
4191 if (auto FDPrefix = getRangeText(
4192 SourceRange(FD->getBeginLoc(), FD->getBody()->getBeginLoc()), SM,
4193 LangOpts))
4194 SS << Handler.getUnsafeBufferUsageAttributeTextAt(FD->getBeginLoc(), " ")
4195 << FDPrefix->str() << "{";
4196 else
4197 return std::nullopt;
4198 // Append: "return" func-name "("
4199 if (auto FunQualName = getFunNameText(FD, SM, LangOpts))
4200 SS << "return " << FunQualName->str() << "(";
4201 else
4202 return std::nullopt;
4203
4204 // Append: arg-list
4205 const unsigned NumParms = FD->getNumParams();
4206 for (unsigned i = 0; i < NumParms; i++) {
4207 const ParmVarDecl *Parm = FD->getParamDecl(i);
4208
4209 if (Parm->isImplicit())
4210 continue;
4211 // FIXME: If a parameter has no name, it is unused in the
4212 // definition. So we could just leave it as it is.
4213 if (!Parm->getIdentifier())
4214 // If a parameter of a function definition has no name:
4215 return std::nullopt;
4216 if (ParmsMask[i])
4217 // This is our spanified paramter!
4218 SS << NewTysTexts[i] << "(" << Parm->getIdentifier()->getName().str()
4219 << ", " << getUserFillPlaceHolder("size") << ")";
4220 else
4221 SS << Parm->getIdentifier()->getName().str();
4222 if (i != NumParms - 1)
4223 SS << ", ";
4224 }
4225 // finish call and the body
4226 SS << ");}" << getEndOfLine().str();
4227 // FIXME: 80-char line formatting?
4228 return SS.str();
4229 };
4230
4231 FixItList FixIts{};
4232 for (FunctionDecl *FReDecl : FD->redecls()) {
4233 std::optional<SourceLocation> Loc = getPastLoc(FReDecl, SM, LangOpts);
4234
4235 if (!Loc)
4236 return {};
4237 if (FReDecl->isThisDeclarationADefinition()) {
4238 assert(FReDecl == FD && "inconsistent function definition");
4239 // Inserts a definition with the old signature to the end of
4240 // `FReDecl`:
4241 if (auto OldOverloadDef = OldOverloadDefCreator(FReDecl))
4242 FixIts.emplace_back(FixItHint::CreateInsertion(*Loc, *OldOverloadDef));
4243 else
4244 return {}; // give up
4245 } else {
4246 // Adds the unsafe-buffer attribute (if not already there) to `FReDecl`:
4247 if (!FReDecl->hasAttr<UnsafeBufferUsageAttr>()) {
4248 FixIts.emplace_back(FixItHint::CreateInsertion(
4249 FReDecl->getBeginLoc(), Handler.getUnsafeBufferUsageAttributeTextAt(
4250 FReDecl->getBeginLoc(), " ")));
4251 }
4252 // Inserts a declaration with the new signature to the end of `FReDecl`:
4253 if (auto NewOverloadDecl = NewOverloadSignatureCreator(FReDecl))
4254 FixIts.emplace_back(FixItHint::CreateInsertion(*Loc, *NewOverloadDecl));
4255 else
4256 return {};
4257 }
4258 }
4259 return FixIts;
4260}
4261
4262// To fix a `ParmVarDecl` to be of `std::span` type.
4263static FixItList fixParamWithSpan(const ParmVarDecl *PVD, const ASTContext &Ctx,
4264 UnsafeBufferUsageHandler &Handler) {
4266 DEBUG_NOTE_DECL_FAIL(PVD, " : has unsupport specifier(s)");
4267 return {};
4268 }
4269 if (PVD->hasDefaultArg()) {
4270 // FIXME: generate fix-its for default values:
4271 DEBUG_NOTE_DECL_FAIL(PVD, " : has default arg");
4272 return {};
4273 }
4274
4275 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
4276 std::optional<std::string> PteTyText = getPointeeTypeText(
4277 PVD, Ctx.getSourceManager(), Ctx.getLangOpts(), &PteTyQualifiers);
4278
4279 if (!PteTyText) {
4280 DEBUG_NOTE_DECL_FAIL(PVD, " : invalid pointee type");
4281 return {};
4282 }
4283
4284 std::optional<StringRef> PVDNameText = PVD->getIdentifier()->getName();
4285
4286 if (!PVDNameText) {
4287 DEBUG_NOTE_DECL_FAIL(PVD, " : invalid identifier name");
4288 return {};
4289 }
4290
4291 std::stringstream SS;
4292 std::optional<std::string> SpanTyText = createSpanTypeForVarDecl(PVD, Ctx);
4293
4294 if (PteTyQualifiers)
4295 // Append qualifiers if they exist:
4296 SS << getSpanTypeText(*PteTyText, PteTyQualifiers);
4297 else
4298 SS << getSpanTypeText(*PteTyText);
4299 // Append qualifiers to the type of the parameter:
4300 if (PVD->getType().hasQualifiers())
4301 SS << ' ' << PVD->getType().getQualifiers().getAsString();
4302 // Append parameter's name:
4303 SS << ' ' << PVDNameText->str();
4304 // Add replacement fix-it:
4305 return {FixItHint::CreateReplacement(PVD->getSourceRange(), SS.str())};
4306}
4307
4308static FixItList fixVariableWithSpan(const VarDecl *VD,
4309 const DeclUseTracker &Tracker,
4310 ASTContext &Ctx,
4311 UnsafeBufferUsageHandler &Handler) {
4312 const DeclStmt *DS = Tracker.lookupDecl(VD);
4313 if (!DS) {
4315 " : variables declared this way not implemented yet");
4316 return {};
4317 }
4318 if (!DS->isSingleDecl()) {
4319 // FIXME: to support handling multiple `VarDecl`s in a single `DeclStmt`
4320 DEBUG_NOTE_DECL_FAIL(VD, " : multiple VarDecls");
4321 return {};
4322 }
4323 // Currently DS is an unused variable but we'll need it when
4324 // non-single decls are implemented, where the pointee type name
4325 // and the '*' are spread around the place.
4326 (void)DS;
4327
4328 // FIXME: handle cases where DS has multiple declarations
4329 return fixLocalVarDeclWithSpan(VD, Ctx, getUserFillPlaceHolder(), Handler);
4330}
4331
4332static FixItList fixVarDeclWithArray(const VarDecl *D, const ASTContext &Ctx,
4333 UnsafeBufferUsageHandler &Handler) {
4334 FixItList FixIts{};
4335
4336 // Note: the code below expects the declaration to not use any type sugar like
4337 // typedef.
4338 if (auto CAT = Ctx.getAsConstantArrayType(D->getType())) {
4339 const QualType &ArrayEltT = CAT->getElementType();
4340 assert(!ArrayEltT.isNull() && "Trying to fix a non-array type variable!");
4341 // FIXME: support multi-dimensional arrays
4342 if (isa<clang::ArrayType>(ArrayEltT.getCanonicalType()))
4343 return {};
4344
4346
4347 // Get the spelling of the element type as written in the source file
4348 // (including macros, etc.).
4349 auto MaybeElemTypeTxt =
4351 Ctx.getLangOpts());
4352 if (!MaybeElemTypeTxt)
4353 return {};
4354 const llvm::StringRef ElemTypeTxt = MaybeElemTypeTxt->trim();
4355
4356 // Find the '[' token.
4357 std::optional<Token> NextTok = Lexer::findNextToken(
4359 while (NextTok && !NextTok->is(tok::l_square) &&
4360 NextTok->getLocation() <= D->getSourceRange().getEnd())
4361 NextTok = Lexer::findNextToken(NextTok->getLocation(),
4362 Ctx.getSourceManager(), Ctx.getLangOpts());
4363 if (!NextTok)
4364 return {};
4365 const SourceLocation LSqBracketLoc = NextTok->getLocation();
4366
4367 // Get the spelling of the array size as written in the source file
4368 // (including macros, etc.).
4369 auto MaybeArraySizeTxt = getRangeText(
4370 {LSqBracketLoc.getLocWithOffset(1), D->getTypeSpecEndLoc()},
4371 Ctx.getSourceManager(), Ctx.getLangOpts());
4372 if (!MaybeArraySizeTxt)
4373 return {};
4374 const llvm::StringRef ArraySizeTxt = MaybeArraySizeTxt->trim();
4375 if (ArraySizeTxt.empty()) {
4376 // FIXME: Support array size getting determined from the initializer.
4377 // Examples:
4378 // int arr1[] = {0, 1, 2};
4379 // int arr2{3, 4, 5};
4380 // We might be able to preserve the non-specified size with `auto` and
4381 // `std::to_array`:
4382 // auto arr1 = std::to_array<int>({0, 1, 2});
4383 return {};
4384 }
4385
4386 std::optional<StringRef> IdentText =
4388
4389 if (!IdentText) {
4390 DEBUG_NOTE_DECL_FAIL(D, " : failed to locate the identifier");
4391 return {};
4392 }
4393
4394 SmallString<32> Replacement;
4395 llvm::raw_svector_ostream OS(Replacement);
4396 OS << "std::array<" << ElemTypeTxt << ", " << ArraySizeTxt << "> "
4397 << IdentText->str();
4398
4399 FixIts.push_back(FixItHint::CreateReplacement(
4400 SourceRange{D->getBeginLoc(), D->getTypeSpecEndLoc()}, OS.str()));
4401 }
4402
4403 return FixIts;
4404}
4405
4406static FixItList fixVariableWithArray(const VarDecl *VD,
4407 const DeclUseTracker &Tracker,
4408 const ASTContext &Ctx,
4409 UnsafeBufferUsageHandler &Handler) {
4410 const DeclStmt *DS = Tracker.lookupDecl(VD);
4411 assert(DS && "Fixing non-local variables not implemented yet!");
4412 if (!DS->isSingleDecl()) {
4413 // FIXME: to support handling multiple `VarDecl`s in a single `DeclStmt`
4414 return {};
4415 }
4416 // Currently DS is an unused variable but we'll need it when
4417 // non-single decls are implemented, where the pointee type name
4418 // and the '*' are spread around the place.
4419 (void)DS;
4420
4421 // FIXME: handle cases where DS has multiple declarations
4422 return fixVarDeclWithArray(VD, Ctx, Handler);
4423}
4424
4425// TODO: we should be consistent to use `std::nullopt` to represent no-fix due
4426// to any unexpected problem.
4427static FixItList
4429 /* The function decl under analysis */ const Decl *D,
4430 const DeclUseTracker &Tracker, ASTContext &Ctx,
4431 UnsafeBufferUsageHandler &Handler) {
4432 if (const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4433 auto *FD = dyn_cast<clang::FunctionDecl>(PVD->getDeclContext());
4434 if (!FD || FD != D) {
4435 // `FD != D` means that `PVD` belongs to a function that is not being
4436 // analyzed currently. Thus `FD` may not be complete.
4437 DEBUG_NOTE_DECL_FAIL(VD, " : function not currently analyzed");
4438 return {};
4439 }
4440
4441 // TODO If function has a try block we can't change params unless we check
4442 // also its catch block for their use.
4443 // FIXME We might support static class methods, some select methods,
4444 // operators and possibly lamdas.
4445 if (FD->isMain() || FD->isConstexpr() ||
4447 FD->isVariadic() ||
4448 // also covers call-operator of lamdas
4449 isa<CXXMethodDecl>(FD) ||
4450 // skip when the function body is a try-block
4451 isa_and_nonnull<CXXTryStmt>(FD->getBody()) ||
4452 FD->isOverloadedOperator()) {
4453 DEBUG_NOTE_DECL_FAIL(VD, " : unsupported function decl");
4454 return {}; // TODO test all these cases
4455 }
4456 }
4457
4458 switch (K) {
4460 if (VD->getType()->isPointerType()) {
4461 if (const auto *PVD = dyn_cast<ParmVarDecl>(VD))
4462 return fixParamWithSpan(PVD, Ctx, Handler);
4463
4464 if (VD->isLocalVarDecl())
4465 return fixVariableWithSpan(VD, Tracker, Ctx, Handler);
4466 }
4467 DEBUG_NOTE_DECL_FAIL(VD, " : not a pointer");
4468 return {};
4469 }
4471 if (VD->isLocalVarDecl() && Ctx.getAsConstantArrayType(VD->getType()))
4472 return fixVariableWithArray(VD, Tracker, Ctx, Handler);
4473
4474 DEBUG_NOTE_DECL_FAIL(VD, " : not a local const-size array");
4475 return {};
4476 }
4479 llvm_unreachable("FixitStrategy not implemented yet!");
4481 llvm_unreachable("Invalid strategy!");
4482 }
4483 llvm_unreachable("Unknown strategy!");
4484}
4485
4486// Returns true iff there exists a `FixItHint` 'h' in `FixIts` such that the
4487// `RemoveRange` of 'h' overlaps with a macro use.
4488static bool overlapWithMacro(const FixItList &FixIts) {
4489 // FIXME: For now we only check if the range (or the first token) is (part of)
4490 // a macro expansion. Ideally, we want to check for all tokens in the range.
4491 return llvm::any_of(FixIts, [](const FixItHint &Hint) {
4492 auto Range = Hint.RemoveRange;
4493 if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
4494 // If the range (or the first token) is (part of) a macro expansion:
4495 return true;
4496 return false;
4497 });
4498}
4499
4500// Returns true iff `VD` is a parameter of the declaration `D`:
4501static bool isParameterOf(const VarDecl *VD, const Decl *D) {
4502 return isa<ParmVarDecl>(VD) &&
4503 VD->getDeclContext() == dyn_cast<DeclContext>(D);
4504}
4505
4506// Erases variables in `FixItsForVariable`, if such a variable has an unfixable
4507// group mate. A variable `v` is unfixable iff `FixItsForVariable` does not
4508// contain `v`.
4510 std::map<const VarDecl *, FixItList> &FixItsForVariable,
4511 const VariableGroupsManager &VarGrpMgr) {
4512 // Variables will be removed from `FixItsForVariable`:
4514
4515 for (const auto &[VD, Ignore] : FixItsForVariable) {
4516 VarGrpRef Grp = VarGrpMgr.getGroupOfVar(VD);
4517 if (llvm::any_of(Grp,
4518 [&FixItsForVariable](const VarDecl *GrpMember) -> bool {
4519 return !FixItsForVariable.count(GrpMember);
4520 })) {
4521 // At least one group member cannot be fixed, so we have to erase the
4522 // whole group:
4523 for (const VarDecl *Member : Grp)
4524 ToErase.push_back(Member);
4525 }
4526 }
4527 for (auto *VarToErase : ToErase)
4528 FixItsForVariable.erase(VarToErase);
4529}
4530
4531// Returns the fix-its that create bounds-safe function overloads for the
4532// function `D`, if `D`'s parameters will be changed to safe-types through
4533// fix-its in `FixItsForVariable`.
4534//
4535// NOTE: In case `D`'s parameters will be changed but bounds-safe function
4536// overloads cannot created, the whole group that contains the parameters will
4537// be erased from `FixItsForVariable`.
4539 std::map<const VarDecl *, FixItList> &FixItsForVariable /* mutable */,
4540 const VariableGroupsManager &VarGrpMgr, const FunctionDecl *FD,
4541 const FixitStrategy &S, ASTContext &Ctx,
4542 UnsafeBufferUsageHandler &Handler) {
4543 FixItList FixItsSharedByParms{};
4544
4545 std::optional<FixItList> OverloadFixes =
4546 createOverloadsForFixedParams(S, FD, Ctx, Handler);
4547
4548 if (OverloadFixes) {
4549 FixItsSharedByParms.append(*OverloadFixes);
4550 } else {
4551 // Something wrong in generating `OverloadFixes`, need to remove the
4552 // whole group, where parameters are in, from `FixItsForVariable` (Note
4553 // that all parameters should be in the same group):
4554 for (auto *Member : VarGrpMgr.getGroupOfParms())
4555 FixItsForVariable.erase(Member);
4556 }
4557 return FixItsSharedByParms;
4558}
4559
4560// Constructs self-contained fix-its for each variable in `FixablesForAllVars`.
4561static std::map<const VarDecl *, FixItList>
4562getFixIts(FixableGadgetSets &FixablesForAllVars, const FixitStrategy &S,
4563 ASTContext &Ctx,
4564 /* The function decl under analysis */ const Decl *D,
4565 const DeclUseTracker &Tracker, UnsafeBufferUsageHandler &Handler,
4566 const VariableGroupsManager &VarGrpMgr) {
4567 // `FixItsForVariable` will map each variable to a set of fix-its directly
4568 // associated to the variable itself. Fix-its of distinct variables in
4569 // `FixItsForVariable` are disjoint.
4570 std::map<const VarDecl *, FixItList> FixItsForVariable;
4571
4572 // Populate `FixItsForVariable` with fix-its directly associated with each
4573 // variable. Fix-its directly associated to a variable 'v' are the ones
4574 // produced by the `FixableGadget`s whose claimed variable is 'v'.
4575 for (const auto &[VD, Fixables] : FixablesForAllVars.byVar) {
4576 FixItsForVariable[VD] =
4577 fixVariable(VD, S.lookup(VD), D, Tracker, Ctx, Handler);
4578 // If we fail to produce Fix-It for the declaration we have to skip the
4579 // variable entirely.
4580 if (FixItsForVariable[VD].empty()) {
4581 FixItsForVariable.erase(VD);
4582 continue;
4583 }
4584 for (const auto &F : Fixables) {
4585 std::optional<FixItList> Fixits = F->getFixits(S);
4586
4587 if (Fixits) {
4588 FixItsForVariable[VD].insert(FixItsForVariable[VD].end(),
4589 Fixits->begin(), Fixits->end());
4590 continue;
4591 }
4592#ifndef NDEBUG
4593 Handler.addDebugNoteForVar(
4594 VD, F->getSourceLoc(),
4595 ("gadget '" + F->getDebugName() + "' refused to produce a fix")
4596 .str());
4597#endif
4598 FixItsForVariable.erase(VD);
4599 break;
4600 }
4601 }
4602
4603 // `FixItsForVariable` now contains only variables that can be
4604 // fixed. A variable can be fixed if its declaration and all Fixables
4605 // associated to it can all be fixed.
4606
4607 // To further remove from `FixItsForVariable` variables whose group mates
4608 // cannot be fixed...
4609 eraseVarsForUnfixableGroupMates(FixItsForVariable, VarGrpMgr);
4610 // Now `FixItsForVariable` gets further reduced: a variable is in
4611 // `FixItsForVariable` iff it can be fixed and all its group mates can be
4612 // fixed.
4613
4614 // Fix-its of bounds-safe overloads of `D` are shared by parameters of `D`.
4615 // That is, when fixing multiple parameters in one step, these fix-its will
4616 // be applied only once (instead of being applied per parameter).
4617 FixItList FixItsSharedByParms{};
4618
4619 if (auto *FD = dyn_cast<FunctionDecl>(D))
4620 FixItsSharedByParms = createFunctionOverloadsForParms(
4621 FixItsForVariable, VarGrpMgr, FD, S, Ctx, Handler);
4622
4623 // The map that maps each variable `v` to fix-its for the whole group where
4624 // `v` is in:
4625 std::map<const VarDecl *, FixItList> FinalFixItsForVariable{
4626 FixItsForVariable};
4627
4628 for (auto &[Var, Ignore] : FixItsForVariable) {
4629 bool AnyParm = false;
4630 const auto VarGroupForVD = VarGrpMgr.getGroupOfVar(Var, &AnyParm);
4631
4632 for (const VarDecl *GrpMate : VarGroupForVD) {
4633 if (Var == GrpMate)
4634 continue;
4635 if (FixItsForVariable.count(GrpMate))
4636 FinalFixItsForVariable[Var].append(FixItsForVariable[GrpMate]);
4637 }
4638 if (AnyParm) {
4639 // This assertion should never fail. Otherwise we have a bug.
4640 assert(!FixItsSharedByParms.empty() &&
4641 "Should not try to fix a parameter that does not belong to a "
4642 "FunctionDecl");
4643 FinalFixItsForVariable[Var].append(FixItsSharedByParms);
4644 }
4645 }
4646 // Fix-its that will be applied in one step shall NOT:
4647 // 1. overlap with macros or/and templates; or
4648 // 2. conflict with each other.
4649 // Otherwise, the fix-its will be dropped.
4650 for (auto Iter = FinalFixItsForVariable.begin();
4651 Iter != FinalFixItsForVariable.end();)
4652 if (overlapWithMacro(Iter->second) ||
4653 clang::internal::anyConflict(Iter->second, Ctx.getSourceManager())) {
4654 Iter = FinalFixItsForVariable.erase(Iter);
4655 } else
4656 Iter++;
4657 return FinalFixItsForVariable;
4658}
4659
4660template <typename VarDeclIterTy>
4661static FixitStrategy
4662getNaiveStrategy(llvm::iterator_range<VarDeclIterTy> UnsafeVars) {
4663 FixitStrategy S;
4664 for (const VarDecl *VD : UnsafeVars) {
4667 else
4669 }
4670 return S;
4671}
4672
4673// Manages variable groups:
4675 const std::vector<VarGrpTy> &Groups;
4676 const std::map<const VarDecl *, unsigned> &VarGrpMap;
4677 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms;
4678
4679public:
4681 const std::vector<VarGrpTy> &Groups,
4682 const std::map<const VarDecl *, unsigned> &VarGrpMap,
4683 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms)
4684 : Groups(Groups), VarGrpMap(VarGrpMap),
4685 GrpsUnionForParms(GrpsUnionForParms) {}
4686
4687 VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm) const override {
4688 if (GrpsUnionForParms.contains(Var)) {
4689 if (HasParm)
4690 *HasParm = true;
4691 return GrpsUnionForParms.getArrayRef();
4692 }
4693 if (HasParm)
4694 *HasParm = false;
4695
4696 auto It = VarGrpMap.find(Var);
4697
4698 if (It == VarGrpMap.end())
4699 return {};
4700 return Groups[It->second];
4701 }
4702
4703 VarGrpRef getGroupOfParms() const override {
4704 return GrpsUnionForParms.getArrayRef();
4705 }
4706};
4707
4708static void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets,
4709 WarningGadgetList WarningGadgets,
4710 DeclUseTracker Tracker,
4711 UnsafeBufferUsageHandler &Handler,
4712 bool EmitSuggestions) {
4713 if (!EmitSuggestions) {
4714 // Our job is very easy without suggestions. Just warn about
4715 // every problematic operation and consider it done. No need to deal
4716 // with fixable gadgets, no need to group operations by variable.
4717 for (const auto &G : WarningGadgets) {
4718 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/false,
4719 D->getASTContext());
4720 }
4721
4722 // This return guarantees that most of the machine doesn't run when
4723 // suggestions aren't requested.
4724 assert(FixableGadgets.empty() &&
4725 "Fixable gadgets found but suggestions not requested!");
4726 return;
4727 }
4728
4729 // If no `WarningGadget`s ever matched, there is no unsafe operations in the
4730 // function under the analysis. No need to fix any Fixables.
4731 if (!WarningGadgets.empty()) {
4732 // Gadgets "claim" variables they're responsible for. Once this loop
4733 // finishes, the tracker will only track DREs that weren't claimed by any
4734 // gadgets, i.e. not understood by the analysis.
4735 for (const auto &G : FixableGadgets) {
4736 for (const auto *DRE : G->getClaimedVarUseSites()) {
4737 Tracker.claimUse(DRE);
4738 }
4739 }
4740 }
4741
4742 // If no `WarningGadget`s ever matched, there is no unsafe operations in the
4743 // function under the analysis. Thus, it early returns here as there is
4744 // nothing needs to be fixed.
4745 //
4746 // Note this claim is based on the assumption that there is no unsafe
4747 // variable whose declaration is invisible from the analyzing function.
4748 // Otherwise, we need to consider if the uses of those unsafe varuables needs
4749 // fix.
4750 // So far, we are not fixing any global variables or class members. And,
4751 // lambdas will be analyzed along with the enclosing function. So this early
4752 // return is correct for now.
4753 if (WarningGadgets.empty())
4754 return;
4755
4756 WarningGadgetSets UnsafeOps =
4757 groupWarningGadgetsByVar(std::move(WarningGadgets));
4758 FixableGadgetSets FixablesForAllVars =
4759 groupFixablesByVar(std::move(FixableGadgets));
4760
4761 std::map<const VarDecl *, FixItList> FixItsForVariableGroup;
4762
4763 // Filter out non-local vars and vars with unclaimed DeclRefExpr-s.
4764 for (auto it = FixablesForAllVars.byVar.cbegin();
4765 it != FixablesForAllVars.byVar.cend();) {
4766 // FIXME: need to deal with global variables later
4767 if ((!it->first->isLocalVarDecl() && !isa<ParmVarDecl>(it->first))) {
4768#ifndef NDEBUG
4769 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4770 ("failed to produce fixit for '" +
4771 it->first->getNameAsString() +
4772 "' : neither local nor a parameter"));
4773#endif
4774 it = FixablesForAllVars.byVar.erase(it);
4775 } else if (it->first->getType().getCanonicalType()->isReferenceType()) {
4776#ifndef NDEBUG
4777 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4778 ("failed to produce fixit for '" +
4779 it->first->getNameAsString() +
4780 "' : has a reference type"));
4781#endif
4782 it = FixablesForAllVars.byVar.erase(it);
4783 } else if (Tracker.hasUnclaimedUses(it->first)) {
4784 it = FixablesForAllVars.byVar.erase(it);
4785 } else if (it->first->isInitCapture()) {
4786#ifndef NDEBUG
4787 Handler.addDebugNoteForVar(it->first, it->first->getBeginLoc(),
4788 ("failed to produce fixit for '" +
4789 it->first->getNameAsString() +
4790 "' : init capture"));
4791#endif
4792 it = FixablesForAllVars.byVar.erase(it);
4793 } else {
4794 ++it;
4795 }
4796 }
4797
4798#ifndef NDEBUG
4799 for (const auto &it : UnsafeOps.byVar) {
4800 const VarDecl *const UnsafeVD = it.first;
4801 auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
4802 if (UnclaimedDREs.empty())
4803 continue;
4804 const auto UnfixedVDName = UnsafeVD->getNameAsString();
4805 for (const clang::DeclRefExpr *UnclaimedDRE : UnclaimedDREs) {
4806 std::string UnclaimedUseTrace =
4807 getDREAncestorString(UnclaimedDRE, D->getASTContext());
4808
4809 Handler.addDebugNoteForVar(
4810 UnsafeVD, UnclaimedDRE->getBeginLoc(),
4811 ("failed to produce fixit for '" + UnfixedVDName +
4812 "' : has an unclaimed use\nThe unclaimed DRE trace: " +
4813 UnclaimedUseTrace));
4814 }
4815 }
4816#endif
4817
4818 // Fixpoint iteration for pointer assignments
4819 using DepMapTy =
4820 llvm::DenseMap<const VarDecl *, llvm::SetVector<const VarDecl *>>;
4821 DepMapTy DependenciesMap{};
4822 DepMapTy PtrAssignmentGraph{};
4823
4824 for (const auto &it : FixablesForAllVars.byVar) {
4825 for (const FixableGadget *fixable : it.second) {
4826 std::optional<std::pair<const VarDecl *, const VarDecl *>> ImplPair =
4827 fixable->getStrategyImplications();
4828 if (ImplPair) {
4829 std::pair<const VarDecl *, const VarDecl *> Impl = std::move(*ImplPair);
4830 PtrAssignmentGraph[Impl.first].insert(Impl.second);
4831 }
4832 }
4833 }
4834
4835 /*
4836 The following code does a BFS traversal of the `PtrAssignmentGraph`
4837 considering all unsafe vars as starting nodes and constructs an undirected
4838 graph `DependenciesMap`. Constructing the `DependenciesMap` in this manner
4839 elimiates all variables that are unreachable from any unsafe var. In other
4840 words, this removes all dependencies that don't include any unsafe variable
4841 and consequently don't need any fixit generation.
4842 Note: A careful reader would observe that the code traverses
4843 `PtrAssignmentGraph` using `CurrentVar` but adds edges between `Var` and
4844 `Adj` and not between `CurrentVar` and `Adj`. Both approaches would
4845 achieve the same result but the one used here dramatically cuts the
4846 amount of hoops the second part of the algorithm needs to jump, given that
4847 a lot of these connections become "direct". The reader is advised not to
4848 imagine how the graph is transformed because of using `Var` instead of
4849 `CurrentVar`. The reader can continue reading as if `CurrentVar` was used,
4850 and think about why it's equivalent later.
4851 */
4852 std::set<const VarDecl *> VisitedVarsDirected{};
4853 for (const auto &[Var, ignore] : UnsafeOps.byVar) {
4854 if (VisitedVarsDirected.find(Var) == VisitedVarsDirected.end()) {
4855
4856 std::queue<const VarDecl *> QueueDirected{};
4857 QueueDirected.push(Var);
4858 while (!QueueDirected.empty()) {
4859 const VarDecl *CurrentVar = QueueDirected.front();
4860 QueueDirected.pop();
4861 VisitedVarsDirected.insert(CurrentVar);
4862 auto AdjacentNodes = PtrAssignmentGraph[CurrentVar];
4863 for (const VarDecl *Adj : AdjacentNodes) {
4864 if (VisitedVarsDirected.find(Adj) == VisitedVarsDirected.end()) {
4865 QueueDirected.push(Adj);
4866 }
4867 DependenciesMap[Var].insert(Adj);
4868 DependenciesMap[Adj].insert(Var);
4869 }
4870 }
4871 }
4872 }
4873
4874 // `Groups` stores the set of Connected Components in the graph.
4875 std::vector<VarGrpTy> Groups;
4876 // `VarGrpMap` maps variables that need fix to the groups (indexes) that the
4877 // variables belong to. Group indexes refer to the elements in `Groups`.
4878 // `VarGrpMap` is complete in that every variable that needs fix is in it.
4879 std::map<const VarDecl *, unsigned> VarGrpMap;
4880 // The union group over the ones in "Groups" that contain parameters of `D`:
4881 llvm::SetVector<const VarDecl *>
4882 GrpsUnionForParms; // these variables need to be fixed in one step
4883
4884 // Group Connected Components for Unsafe Vars
4885 // (Dependencies based on pointer assignments)
4886 std::set<const VarDecl *> VisitedVars{};
4887 for (const auto &[Var, ignore] : UnsafeOps.byVar) {
4888 if (VisitedVars.find(Var) == VisitedVars.end()) {
4889 VarGrpTy &VarGroup = Groups.emplace_back();
4890 std::queue<const VarDecl *> Queue{};
4891
4892 Queue.push(Var);
4893 while (!Queue.empty()) {
4894 const VarDecl *CurrentVar = Queue.front();
4895 Queue.pop();
4896 VisitedVars.insert(CurrentVar);
4897 VarGroup.push_back(CurrentVar);
4898 auto AdjacentNodes = DependenciesMap[CurrentVar];
4899 for (const VarDecl *Adj : AdjacentNodes) {
4900 if (VisitedVars.find(Adj) == VisitedVars.end()) {
4901 Queue.push(Adj);
4902 }
4903 }
4904 }
4905
4906 bool HasParm = false;
4907 unsigned GrpIdx = Groups.size() - 1;
4908
4909 for (const VarDecl *V : VarGroup) {
4910 VarGrpMap[V] = GrpIdx;
4911 if (!HasParm && isParameterOf(V, D))
4912 HasParm = true;
4913 }
4914 if (HasParm)
4915 GrpsUnionForParms.insert_range(VarGroup);
4916 }
4917 }
4918
4919 // Remove a `FixableGadget` if the associated variable is not in the graph
4920 // computed above. We do not want to generate fix-its for such variables,
4921 // since they are neither warned nor reachable from a warned one.
4922 //
4923 // Note a variable is not warned if it is not directly used in any unsafe
4924 // operation. A variable `v` is NOT reachable from an unsafe variable, if it
4925 // does not exist another variable `u` such that `u` is warned and fixing `u`
4926 // (transitively) implicates fixing `v`.
4927 //
4928 // For example,
4929 // ```
4930 // void f(int * p) {
4931 // int * a = p; *p = 0;
4932 // }
4933 // ```
4934 // `*p = 0` is a fixable gadget associated with a variable `p` that is neither
4935 // warned nor reachable from a warned one. If we add `a[5] = 0` to the end of
4936 // the function above, `p` becomes reachable from a warned variable.
4937 for (auto I = FixablesForAllVars.byVar.begin();
4938 I != FixablesForAllVars.byVar.end();) {
4939 // Note `VisitedVars` contain all the variables in the graph:
4940 if (!VisitedVars.count((*I).first)) {
4941 // no such var in graph:
4942 I = FixablesForAllVars.byVar.erase(I);
4943 } else
4944 ++I;
4945 }
4946
4947 // We assign strategies to variables that are 1) in the graph and 2) can be
4948 // fixed. Other variables have the default "Won't fix" strategy.
4949 FixitStrategy NaiveStrategy = getNaiveStrategy(llvm::make_filter_range(
4950 VisitedVars, [&FixablesForAllVars](const VarDecl *V) {
4951 // If a warned variable has no "Fixable", it is considered unfixable:
4952 return FixablesForAllVars.byVar.count(V);
4953 }));
4954 VariableGroupsManagerImpl VarGrpMgr(Groups, VarGrpMap, GrpsUnionForParms);
4955
4956 if (isa<NamedDecl>(D))
4957 // The only case where `D` is not a `NamedDecl` is when `D` is a
4958 // `BlockDecl`. Let's not fix variables in blocks for now
4959 FixItsForVariableGroup =
4960 getFixIts(FixablesForAllVars, NaiveStrategy, D->getASTContext(), D,
4961 Tracker, Handler, VarGrpMgr);
4962
4963 for (const auto &G : UnsafeOps.noVar) {
4964 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/false,
4965 D->getASTContext());
4966 }
4967
4968 for (const auto &[VD, WarningGadgets] : UnsafeOps.byVar) {
4969 auto FixItsIt = FixItsForVariableGroup.find(VD);
4970 Handler.handleUnsafeVariableGroup(VD, VarGrpMgr,
4971 FixItsIt != FixItsForVariableGroup.end()
4972 ? std::move(FixItsIt->second)
4973 : FixItList{},
4974 D, NaiveStrategy);
4975 for (const auto &G : WarningGadgets) {
4976 G->handleUnsafeOperation(Handler, /*IsRelatedToDecl=*/true,
4977 D->getASTContext());
4978 }
4979 }
4980}
4981
4983 UnsafeBufferUsageHandler &Handler,
4984 bool EmitSuggestions) {
4985#ifndef NDEBUG
4986 Handler.clearDebugNotes();
4987#endif
4988
4989 assert(D);
4990 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4991 // Consteval functions are free of UB by the spec, so we don't need to
4992 // visit them or produce diagnostics.
4993 if (FD->isConsteval())
4994 return;
4995 // We do not want to visit a Lambda expression defined inside a method
4996 // independently. Instead, it should be visited along with the outer method.
4997 // FIXME: do we want to do the same thing for `BlockDecl`s?
4998 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4999 if (MD->getParent()->isLambda() && MD->getParent()->isLocalClass())
5000 return;
5001 }
5002
5003 for (FunctionDecl *FReDecl : FD->redecls()) {
5004 if (FReDecl->isExternC()) {
5005 // Do not emit fixit suggestions for functions declared in an
5006 // extern "C" block.
5007 EmitSuggestions = false;
5008 break;
5009 }
5010 }
5011 }
5012
5014
5016
5017 assert(!Stmts.empty());
5018
5019 FixableGadgetList FixableGadgets;
5020 WarningGadgetList WarningGadgets;
5021 DeclUseTracker Tracker;
5022 for (const Stmt *S : Stmts) {
5023 findGadgets(S, D->getASTContext(), Handler, EmitSuggestions, FixableGadgets,
5024 WarningGadgets, Tracker);
5025 }
5026 applyGadgets(D, std::move(FixableGadgets), std::move(WarningGadgets),
5027 std::move(Tracker), Handler, EmitSuggestions);
5028}
5029
5031 std::set<const Expr *> &UnsafePointers) {
5032 class MockReporter : public UnsafeBufferUsageHandler {
5033 public:
5034 MockReporter() {}
5035 void handleUnsafeOperation(const Stmt *, bool, ASTContext &) override {}
5036 void handleUnsafeLibcCall(const CallExpr *, unsigned,
5038 const Expr *UnsafeArg = nullptr) override {}
5039 void handleUnsafeOperationInContainer(const Stmt *, bool,
5040 ASTContext &) override {}
5041 void handleUnsafeOperationInStringView(const Stmt *, bool,
5042 ASTContext &) override {}
5043 void handleUnsafeVariableGroup(const VarDecl *,
5044 const VariableGroupsManager &, FixItList &&,
5045 const Decl *,
5046 const FixitStrategy &) override {}
5047 void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
5048 bool IsRelatedToDecl,
5049 ASTContext &Ctx) override {}
5050 bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
5051 return false;
5052 }
5053 bool isSafeBufferOptOut(const SourceLocation &) const override {
5054 return false;
5055 }
5056 bool ignoreUnsafeBufferInLibcCall(const SourceLocation &) const override {
5057 return false;
5058 }
5059 bool
5060 ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &) const override {
5061 return false;
5062 }
5063 bool ignoreUnsafeBufferInStaticSizedArray(
5064 const SourceLocation &Loc) const override {
5065 return false;
5066 }
5067 std::string getUnsafeBufferUsageAttributeTextAt(
5068 SourceLocation, StringRef WSSuffix = "") const override {
5069 return "";
5070 }
5071 } Handler;
5072
5073 const Stmt *S = N.get<Stmt>();
5074 if (!S)
5075 return false;
5076
5077 MatchResult Result;
5078 WarningGadgetList WarningGadgets;
5079 bool Matched = false;
5080
5081 // FIXME: By design, we don't need MockReporter, and we are supposed to
5082 // only define WARNING_GADGET when we want to treat WARNING_OPTIONAL_GADGET
5083 // the same as WARNING_GADGET. The reason we have to do it this way now is
5084 // that some WARNING_OPTIONAL_GADGETs do not have the 3-argument `matches`
5085 // overload. We need to fix this problem in a separate patch.
5086
5087#define WARNING_GADGET(name) \
5088 if (name##Gadget::matches(S, Ctx, Result)) \
5089 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5090#define WARNING_OPTIONAL_GADGET(name) \
5091 if (name##Gadget::matches(S, Ctx, &Handler, Result)) \
5092 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5093#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
5094
5095 for (auto &WG : WarningGadgets)
5096 for (auto *E : WG->getUnsafePtrs()) {
5097 UnsafePointers.insert(E);
5098 Matched = true;
5099 }
5100 return Matched;
5101}
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:577
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
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
Expr * getSubExpr()
Definition Expr.h:3795
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:3285
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3836
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:4220
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:3442
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:3706
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3900
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:8667
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:8618
QualType getCanonicalType() const
Definition TypeBase.h:8630
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
std::string getAsString() const
Represents a struct/union/class.
Definition Decl.h:4508
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:8914
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
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 isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
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:8823
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)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#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.