Debian Codegraph @

clang/lib/Analysis/UnsafeBufferUsage.cpp

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