29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/STLFunctionalExtras.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringMap.h"
35#include "llvm/ADT/StringRef.h"
52 std::string VisitBinaryOperator(
const BinaryOperator *BO) {
53 return "BinaryOperator(" + BO->
getOpcodeStr().str() +
")";
56 std::string VisitUnaryOperator(
const UnaryOperator *UO) {
60 std::string VisitImplicitCastExpr(
const ImplicitCastExpr *ICE) {
67static std::string getDREAncestorString(
const DeclRefExpr *DRE,
71 StmtDebugPrinter StmtPriner;
74 SS << StmtPriner.Visit(St);
78 if (StParents.
size() > 1)
79 return "unavailable due to multiple parents";
80 if (StParents.
empty())
99 virtual bool matches(
const DynTypedNode &DynNode, ASTContext &Ctx,
100 const UnsafeBufferUsageHandler &Handler) = 0;
101 virtual ~FastMatcher() =
default;
107 template <
typename T>
const T *getNodeAs(StringRef ID)
const {
108 auto It =
Nodes.find(ID);
109 if (It ==
Nodes.end()) {
112 return It->second.get<
T>();
115 void addNode(StringRef ID,
const DynTypedNode &Node) {
Nodes[
ID] = Node; }
118 llvm::StringMap<DynTypedNode>
Nodes;
122#define SIZED_CONTAINER_OR_VIEW_LIST \
123 "span", "array", "vector", "basic_string_view", "basic_string", \
134 bool FindAll,
bool IgnoreUnevaluatedContext,
136 : Matcher(&Matcher), FindAll(FindAll), Matches(
false),
137 IgnoreUnevaluatedContext(IgnoreUnevaluatedContext),
138 ActiveASTContext(&Context), Handler(&NewHandler) {
175 if (IgnoreUnevaluatedContext)
177 return DynamicRecursiveASTVisitor::TraverseGenericSelectionExpr(Node);
183 if (IgnoreUnevaluatedContext)
185 return DynamicRecursiveASTVisitor::TraverseUnaryExprOrTypeTraitExpr(Node);
189 bool TraverseQualifier)
override {
191 if (IgnoreUnevaluatedContext)
193 return DynamicRecursiveASTVisitor::TraverseTypeOfExprTypeLoc(
194 Node, TraverseQualifier);
198 bool TraverseQualifier)
override {
200 if (IgnoreUnevaluatedContext)
202 return DynamicRecursiveASTVisitor::TraverseDecltypeTypeLoc(
203 Node, TraverseQualifier);
208 if (IgnoreUnevaluatedContext)
210 return DynamicRecursiveASTVisitor::TraverseCXXNoexceptExpr(Node);
215 if (IgnoreUnevaluatedContext)
217 return DynamicRecursiveASTVisitor::TraverseCXXTypeidExpr(Node);
223 return DynamicRecursiveASTVisitor::TraverseCXXDefaultInitExpr(Node);
239 template <
typename T>
bool match(
const T &Node) {
249 FastMatcher *
const Matcher;
253 bool IgnoreUnevaluatedContext;
254 ASTContext *ActiveASTContext;
255 const UnsafeBufferUsageHandler *Handler;
270 FastMatcher &Matcher) {
278 FastMatcher &Matcher) {
314 const Stmt *S,
const llvm::function_ref<
void(
const Expr *)> OnResult) {
315 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(S);
316 CE && CE->getCastKind() == CastKind::CK_LValueToRValue)
317 OnResult(CE->getSubExpr());
318 if (
const auto *BO = dyn_cast<BinaryOperator>(S);
326 const Stmt *S, llvm::function_ref<
void(
const Stmt *)> InnerMatcher) {
335 if (
auto *CE = dyn_cast<CallExpr>(S)) {
336 if (
const auto *FnDecl = CE->getDirectCallee();
337 FnDecl && FnDecl->hasAttr<UnsafeBufferUsageAttr>())
346 if (
auto *CE = dyn_cast<CastExpr>(S)) {
347 if (CE->getCastKind() != CastKind::CK_PointerToIntegral &&
348 CE->getCastKind() != CastKind::CK_PointerToBoolean)
352 InnerMatcher(CE->getSubExpr());
356 if (
const auto *BO = dyn_cast<BinaryOperator>(S);
370 if (
const auto *BO = dyn_cast<BinaryOperator>(S);
376 InnerMatcher(BO->
getLHS());
377 InnerMatcher(BO->
getRHS());
395 const Stmt *S, llvm::function_ref<
void(
const Stmt *)> InnerMatcher) {
400 if (
auto *CS = dyn_cast<CompoundStmt>(S)) {
401 for (
auto *Child : CS->body())
404 if (
auto *IfS = dyn_cast<IfStmt>(S)) {
406 InnerMatcher(IfS->getThen());
408 InnerMatcher(IfS->getElse());
459 case Stmt::DeclRefExprClass:
461 case Stmt::BinaryOperatorClass: {
464 BO2->getLHS(), BO2->getOpcode(),
481 if (
const auto *UO = dyn_cast<UnaryOperator>(Ptr)) {
482 if (UO->
getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
488 if (
const auto *CE = dyn_cast<CallExpr>(Ptr)) {
493 return CE->getArg(0)->IgnoreParenImpCasts();
503 const auto *SizeOfExpr =
505 if (!SizeOfExpr || SizeOfExpr->getKind() != UETT_SizeOf)
507 if (SizeOfExpr->isArgumentType())
509 return SizeOfExpr->getArgumentExpr()->IgnoreParenImpCasts();
527 bool AllowDuckTypedContainers =
false) {
529 if (
auto *MCEPtr = dyn_cast<CXXMemberCallExpr>(Ptr->IgnoreParenImpCasts()))
531 dyn_cast<CXXMemberCallExpr>(Size->IgnoreParenImpCasts())) {
532 auto *DREOfPtr = dyn_cast<DeclRefExpr>(
533 MCEPtr->getImplicitObjectArgument()->IgnoreParenImpCasts());
534 auto *DREOfSize = dyn_cast<DeclRefExpr>(
535 MCESize->getImplicitObjectArgument()->IgnoreParenImpCasts());
537 if (!DREOfPtr || !DREOfSize)
541 if (DREOfPtr->getDecl() != DREOfSize->getDecl())
543 const auto *MDData = MCEPtr->getMethodDecl();
544 const auto *MDSize = MCESize->getMethodDecl();
545 if (!MDData || !MDSize)
547 if (MDData->getName() !=
"data")
550 bool AcceptSizeBytes = Ptr->getType()->getPointeeType()->isCharType();
552 if (!((AcceptSizeBytes && MDSize->getName() ==
"size_bytes") ||
557 MDSize->getName() ==
"size"))
560 if (AllowDuckTypedContainers)
564 if (!MCEPtr->getRecordDecl()->isInStdNamespace())
567 auto *ObjII = MCEPtr->getRecordDecl()->getIdentifier();
579 if (Size->EvaluateAsInt(ER, Ctx)) {
581 if (
auto *DRE = dyn_cast<DeclRefExpr>(Ptr->IgnoreParenImpCasts())) {
585 return llvm::APSInt::compareValues(
586 SizeInt, llvm::APSInt(CAT->getSize(),
true)) == 0;
618template <
typename CallOrConstructExpr>
622 bool AllowDuckTypedContainers =
false) {
623 assert(Node.getNumArgs() == 2 &&
624 "expecting a two-parameter container constructor or factory call");
627 auto HaveEqualConstantValues = [&Ctx](
const Expr *E0,
const Expr *E1) {
629 if (
auto E1CV = E1->getIntegerConstantExpr(Ctx)) {
630 return llvm::APSInt::compareValues(*E0CV, *E1CV) == 0;
634 auto AreSameDRE = [](
const Expr *E0,
const Expr *E1) {
635 if (
auto *DRE0 = dyn_cast<DeclRefExpr>(E0))
636 if (
auto *DRE1 = dyn_cast<DeclRefExpr>(E1)) {
637 return DRE0->getDecl() == DRE1->getDecl();
643 if (Arg1CV && Arg1CV->isZero())
649 case Stmt::CXXNewExprClass:
652 return AreSameDRE((*Size)->IgnoreImplicit(), Arg1) ||
653 HaveEqualConstantValues(*Size, Arg1);
658 return Arg1CV && Arg1CV->isOne();
666 if (
auto CCast = dyn_cast<CStyleCastExpr>(Arg0)) {
667 if (!CCast->getType()->isPointerType())
675 if (
const auto *
Call = dyn_cast<CallExpr>(CCast->getSubExpr())) {
677 if (
auto *AllocAttr = FD->getAttr<AllocSizeAttr>()) {
678 const Expr *EleSizeExpr =
679 Call->getArg(AllocAttr->getElemSizeParam().getASTIndex());
681 ParamIdx NumElemIdx = AllocAttr->getNumElemsParam();
688 if (
auto BO = dyn_cast<BinaryOperator>(Arg1))
695 auto IsMethodCallToSizedObject =
696 [AllowDuckTypedContainers](
const Stmt *Node, StringRef MethodName) {
697 if (
const auto *MC = dyn_cast<CXXMemberCallExpr>(Node)) {
698 const auto *MD = MC->getMethodDecl();
699 if (!MD || MD->getName() != MethodName)
701 if (AllowDuckTypedContainers)
703 if (
const auto *RD = MC->getRecordDecl())
704 if (
auto *II = RD->getDeclName().getAsIdentifierInfo();
705 II && RD->isInStdNamespace())
712 if (IsMethodCallToSizedObject(Arg0,
"begin") &&
713 IsMethodCallToSizedObject(Arg1,
"end"))
717 ->getImplicitObjectArgument()
718 ->IgnoreParenImpCasts(),
720 ->getImplicitObjectArgument()
721 ->IgnoreParenImpCasts());
733 if (
const auto *SL = dyn_cast<StringLiteral>(Arg0)) {
735 if (llvm::APSInt::compareValues(
736 llvm::APSInt::getUnsigned(SL->getLength()), *ArgSize) >= 0)
745 if (llvm::APSInt::compareValues(llvm::APSInt(CAT->getSize(),
true),
760 auto GetContainerObj = [](
const Expr *E) ->
const Expr * {
761 E = E->IgnoreParenImpCasts();
762 if (
const auto *MCE = dyn_cast<CXXMemberCallExpr>(E)) {
763 const auto *MD = MCE->getMethodDecl();
764 if (MD && MD->getIdentifier())
765 if (MD->getName() ==
"begin" || MD->getName() ==
"end")
766 return MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
771 const Expr *Obj0 = GetContainerObj(Arg0);
772 const Expr *Obj1 = GetContainerObj(Arg1);
775 const auto *DRE0 = dyn_cast<DeclRefExpr>(Obj0);
776 const auto *DRE1 = dyn_cast<DeclRefExpr>(Obj1);
781 if (DRE0->getDecl()->getCanonicalDecl() ==
782 DRE1->getDecl()->getCanonicalDecl())
795 const bool IgnoreStaticSizedArrays) {
804 if (
const auto *CATy =
805 dyn_cast<ConstantArrayType>(Node.
getBase()
809 limit = CATy->getLimitedSize();
810 }
else if (
const auto *SLiteral = dyn_cast<clang::StringLiteral>(
812 limit = SLiteral->getLength() + 1;
817 if (IgnoreStaticSizedArrays) {
827 llvm::APSInt ArrIdx = EVResult.
Val.
getInt();
830 if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
832 }
else if (
const auto *BE = dyn_cast<BinaryOperator>(IndexExpr)) {
835 if (BE->getOpcode() != BO_And && BE->getOpcode() != BO_Rem)
838 const Expr *LHS = BE->getLHS();
839 const Expr *RHS = BE->getRHS();
841 if (BE->getOpcode() == BO_Rem) {
848 llvm::APSInt result = EVResult.
Val.
getInt();
849 if (result.isNonNegative() && result.getLimitedValue() <= limit)
860 llvm::APSInt result = EVResult.
Val.
getInt();
861 if (result.isNonNegative() && result.getLimitedValue() < limit)
881 const Expr *
Base = Ptr->IgnoreParenImpCasts();
883 if (
const auto *CATy = dyn_cast<ConstantArrayType>(
884 Base->getType()->getUnqualifiedDesugaredType())) {
885 limit = CATy->getLimitedSize();
886 }
else if (
const auto *SLiteral = dyn_cast<clang::StringLiteral>(
Base)) {
887 limit = SLiteral->getLength() + 1;
892 llvm::APSInt OffsetVal = EVResult.
Val.
getInt();
893 if (Opcode == BO_Sub)
894 OffsetVal = -OffsetVal;
898 return OffsetVal.isNonNegative() && OffsetVal.getLimitedValue() < limit;
907 if (
const auto *CE = dyn_cast<ConditionalOperator>(E)) {
909 const auto *Cond = CE->getCond();
911 if (!Cond->isValueDependent() &&
912 Cond->EvaluateAsBooleanCondition(CondEval, Ctx))
913 return CondEval ? CE->getLHS() : CE->getRHS();
922 Ptr = Ptr->IgnoreParenImpCasts();
923 if (
const auto *DefaultArgE = dyn_cast<CXXDefaultArgExpr>(Ptr))
924 Ptr = DefaultArgE->getExpr()->IgnoreParenImpCasts();
931 if (
const auto *CondE = dyn_cast<ConditionalOperator>(Ptr)) {
940 if (
auto *MCE = dyn_cast<CXXMemberCallExpr>(Ptr)) {
950 static const llvm::StringSet<> NullTermFunctions = {
"strerror"};
951 if (
auto *CE = dyn_cast<CallExpr>(Ptr)) {
974 if (Name.ends_with(
"_s"))
975 return Name.drop_back(2 );
982 if (Name.starts_with(
"__") && Name.ends_with(
"_chk"))
984 Name.drop_front(2).drop_back(4) );
988static StringRef
matchName(StringRef FunName,
bool isBuiltin) {
990 if (isBuiltin && FunName.starts_with(
"__builtin_"))
994 FunName.drop_front(10 ));
996 if (FunName.starts_with(
"__asan_"))
1013 const Expr *&UnsafeArg,
const unsigned FmtIdx,
1014 std::optional<const unsigned> FmtArgIdx = std::nullopt,
1015 bool isKprintf =
false) {
1016 class StringFormatStringHandler
1020 const Expr *&UnsafeArg;
1036 unsigned PArgIdx = Precision.
getArgIndex() + FmtArgIdx;
1038 if (PArgIdx < Call->getNumArgs()) {
1039 const Expr *PArg =
Call->getArg(PArgIdx);
1042 if (
auto *CE = dyn_cast<CastExpr>(PArg);
1043 CE && CE->getType()->isSignedIntegerType())
1044 PArg = CE->getSubExpr();
1049 analyze_printf::OptionalAmount::HowSpecified::Constant) {
1051 llvm::APSInt PArgVal = llvm::APSInt(
1061 StringFormatStringHandler(
const CallExpr *
Call,
unsigned FmtArgIdx,
1063 :
Call(
Call), FmtArgIdx(FmtArgIdx), UnsafeArg(UnsafeArg), Ctx(Ctx),
1064 UnsafeArgSet(
false) {}
1067 const char *startSpecifier,
1068 unsigned specifierLen,
1076 if (ArgIdx >=
Call->getNumArgs())
1080 const Expr *Arg =
Call->getArg(ArgIdx);
1090 bool IsArgTypeValid =
1093 ?
ArgType->getPointeeType()->isWideCharType()
1094 :
ArgType->getPointeeType()->isCharType());
1097 Precision && IsArgTypeValid)
1101 UnsafeArg =
Call->getArg(ArgIdx);
1102 UnsafeArgSet =
true;
1106 bool isUnsafeArgSet() {
return UnsafeArgSet; }
1109 const Expr *Fmt =
Call->getArg(FmtIdx);
1110 unsigned FmtArgStartingIdx =
1111 FmtArgIdx.has_value() ?
static_cast<unsigned>(*FmtArgIdx) : FmtIdx + 1;
1114 if (SL->getCharByteWidth() == 1) {
1115 StringRef FmtStr = SL->getString();
1116 StringFormatStringHandler Handler(
Call, FmtArgStartingIdx, UnsafeArg,
1120 Handler, FmtStr.begin(), FmtStr.end(), Ctx.
getLangOpts(),
1122 Handler.isUnsafeArgSet();
1125 if (
auto FmtStr = SL->tryEvaluateString(Ctx)) {
1126 StringFormatStringHandler Handler(
Call, FmtArgStartingIdx, UnsafeArg,
1129 Handler, FmtStr->data(), FmtStr->data() + FmtStr->size(),
1131 Handler.isUnsafeArgSet();
1137 return llvm::any_of(
1138 llvm::make_range(
Call->arg_begin() + FmtIdx,
Call->arg_end()),
1139 [&UnsafeArg, &Ctx](
const Expr *Arg) ->
bool {
1140 if (Arg->getType()->isPointerType() && !isNullTermPointer(Arg, Ctx)) {
1160static std::optional<UnsafeLibcFunctionFamily>
1162 static const llvm::StringMap<UnsafeLibcFunctionFamily> PredefinedNames = [] {
1164 llvm::StringMap<F> M;
1165 auto Add = [&](F Family, std::initializer_list<StringRef> Names) {
1166 for (StringRef N : Names)
1169 Add(F::NumericConversion,
1170 {
"atof",
"atoi",
"atol",
"atoll",
"strtol",
"strtoll",
"strtoul",
1171 "strtoull",
"strtof",
"strtod",
"strtold",
"strtoimax",
"strtoumax"});
1173 Add(F::StringManipulation,
1174 {
"strcpy",
"strncpy",
"strlcpy",
"strcat",
"strncat",
"strlcat",
1175 "strxfrm",
"strdup",
"strndup"});
1176 Add(F::StringExamination,
1177 {
"strlen",
"strnlen",
"strcmp",
"strncmp",
"stricmp",
"strcasecmp",
1178 "strcoll",
"strchr",
"strrchr",
"strspn",
"strcspn",
"strpbrk",
1179 "strstr",
"strtok"});
1180 Add(F::Memory, {
"memchr",
"wmemchr",
"memcmp",
"wmemcmp",
"memcpy",
1181 "memccpy",
"mempcpy",
"wmemcpy",
"memmove",
"wmemmove",
1182 "wmemset",
"bcopy",
"bzero"});
1183 Add(F::IO, {
"fread",
"fwrite",
"fgets",
"fgetws",
"gets",
"fputs",
"fputws",
1185 Add(F::Other, {
"strerror_s",
"strerror_r",
"bsearch",
"qsort"});
1192 return std::nullopt;
1197 if (
auto It = PredefinedNames.find(Name); It != PredefinedNames.end())
1200 std::string NameWCS = Name.str();
1201 size_t WcsPos = NameWCS.find(
"wcs");
1203 while (WcsPos != std::string::npos) {
1204 NameWCS[WcsPos++] =
's';
1205 NameWCS[WcsPos++] =
't';
1206 NameWCS[WcsPos++] =
'r';
1207 WcsPos = NameWCS.find(
"wcs", WcsPos);
1209 if (
auto It = PredefinedNames.find(NameWCS); It != PredefinedNames.end())
1213 if (Name.ends_with(
"scanf"))
1215 return std::nullopt;
1236 assert(FD &&
"It should have been checked that FD is non-null.");
1243 if (Name !=
"memset")
1255 const auto *AddressOfVar = dyn_cast_if_present<DeclRefExpr>(
1260 const auto *SizeOfVar =
1265 return AddressOfVar->getDecl() != SizeOfVar->getDecl();
1279 return Name.starts_with(
"v") && Name.ends_with(
"printf");
1292 return Name ==
"sprintf" || Name ==
"swprintf";
1306 if (!Name.ends_with(
"printf"))
1309 StringRef Prefix = Name.drop_back(6);
1311 if (Prefix.ends_with(
"w"))
1312 Prefix = Prefix.drop_back(1);
1314 return Prefix.empty() || Prefix ==
"k" || Prefix ==
"f" || Prefix ==
"sn";
1322 MatchResult &Result, llvm::StringRef Tag) {
1326 assert(FD &&
"It should have been checked that FD is non-null.");
1344 const Expr *UnsafeArg;
1355 bool isKprintf =
false;
1356 const Expr *UnsafeArg;
1359 isKprintf = II->getName() ==
"kprintf";
1361 std::nullopt, isKprintf)) {
1374 const Expr *UnsafeArg;
1385 for (
const auto *Arg : Node.
arguments())
1400 assert(FD &&
"It should have been checked that FD is non-null.");
1415 !Size->getType()->isUnsignedIntegerType())
1424 const bool IsGlobalAndNotInAnyNamespace =
1461#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
1464 Gadget(Kind K) : K(K) {}
1466 Kind
getKind()
const {
return K; }
1469 StringRef getDebugName()
const {
1474#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
1476 llvm_unreachable(
"Unhandled Gadget::Kind enum");
1480 virtual bool isWarningGadget()
const = 0;
1483 virtual SourceLocation getSourceLoc()
const = 0;
1488 virtual DeclUseList getClaimedVarUseSites()
const = 0;
1490 virtual ~Gadget() =
default;
1498class WarningGadget :
public Gadget {
1500 WarningGadget(Kind K) : Gadget(K) {}
1502 static bool classof(
const Gadget *G) {
return G->isWarningGadget(); }
1503 bool isWarningGadget() const final {
return true; }
1505 virtual void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1506 bool IsRelatedToDecl,
1507 ASTContext &Ctx)
const = 0;
1509 virtual SmallVector<const Expr *, 1> getUnsafePtrs()
const = 0;
1516class FixableGadget :
public Gadget {
1518 FixableGadget(Kind K) : Gadget(K) {}
1520 static bool classof(
const Gadget *G) {
return !G->isWarningGadget(); }
1521 bool isWarningGadget() const final {
return false; }
1526 virtual std::optional<FixItList> getFixits(
const FixitStrategy &)
const {
1527 return std::nullopt;
1536 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
1537 getStrategyImplications()
const {
1538 return std::nullopt;
1542static bool isSupportedVariable(
const DeclRefExpr &Node) {
1554 dyn_cast<ClassTemplateSpecializationDecl>(
RecordDecl);
1555 if (!class_template_specialization_decl)
1560 if (template_args.
size() == 0)
1571class UniquePtrArrayAccessGadget :
public WarningGadget {
1573 static constexpr const char *
const AccessorTag =
"unique_ptr_array_access";
1574 const CXXOperatorCallExpr *AccessorExpr;
1578 : WarningGadget(
Kind::UniquePtrArrayAccess),
1579 AccessorExpr(
Result.getNodeAs<CXXOperatorCallExpr>(AccessorTag)) {
1580 assert(AccessorExpr &&
1581 "UniquePtrArrayAccessGadget requires a matched CXXOperatorCallExpr");
1584 static bool classof(
const Gadget *G) {
1585 return G->getKind() == Kind::UniquePtrArrayAccess;
1588 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
1591 const CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(S);
1592 if (!OpCall || OpCall->
getOperator() != OO_Subscript)
1599 const CXXMethodDecl *
Method =
1604 if (
Method->getOverloadedOperator() != OO_Subscript)
1608 if (!isUniquePtrArray(RecordDecl))
1611 const Expr *IndexExpr = OpCall->
getArg(1);
1612 clang::Expr::EvalResult Eval;
1618 Result.addNode(AccessorTag, DynTypedNode::create(*OpCall));
1621 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1622 bool IsRelatedToDecl,
1623 ASTContext &Ctx)
const override {
1625 DynTypedNode::create(*AccessorExpr), IsRelatedToDecl, Ctx);
1628 SourceLocation getSourceLoc()
const override {
1630 return AccessorExpr->getOperatorLoc();
1631 return SourceLocation();
1634 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
1635 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
1638using FixableGadgetList = std::vector<std::unique_ptr<FixableGadget>>;
1639using WarningGadgetList = std::vector<std::unique_ptr<WarningGadget>>;
1643class IncrementGadget :
public WarningGadget {
1644 static constexpr const char *
const OpTag =
"op";
1645 const UnaryOperator *Op;
1650 Op(
Result.getNodeAs<UnaryOperator>(OpTag)) {}
1652 static bool classof(
const Gadget *G) {
1653 return G->getKind() == Kind::Increment;
1656 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
1658 const auto *UO = dyn_cast<UnaryOperator>(S);
1663 Result.addNode(OpTag, DynTypedNode::create(*UO));
1667 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1668 bool IsRelatedToDecl,
1669 ASTContext &Ctx)
const override {
1672 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
1674 DeclUseList getClaimedVarUseSites()
const override {
1675 SmallVector<const DeclRefExpr *, 2> Uses;
1676 if (
const auto *DRE =
1677 dyn_cast<DeclRefExpr>(Op->getSubExpr()->IgnoreParenImpCasts())) {
1678 Uses.push_back(DRE);
1681 return std::move(Uses);
1684 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
1685 return {Op->getSubExpr()->IgnoreParenImpCasts()};
1691class DecrementGadget :
public WarningGadget {
1692 static constexpr const char *
const OpTag =
"op";
1693 const UnaryOperator *Op;
1698 Op(
Result.getNodeAs<UnaryOperator>(OpTag)) {}
1700 static bool classof(
const Gadget *G) {
1701 return G->getKind() == Kind::Decrement;
1704 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
1706 const auto *UO = dyn_cast<UnaryOperator>(S);
1711 Result.addNode(OpTag, DynTypedNode::create(*UO));
1715 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1716 bool IsRelatedToDecl,
1717 ASTContext &Ctx)
const override {
1720 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
1722 DeclUseList getClaimedVarUseSites()
const override {
1723 if (
const auto *DRE =
1724 dyn_cast<DeclRefExpr>(Op->getSubExpr()->IgnoreParenImpCasts())) {
1731 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
1732 return {Op->getSubExpr()->IgnoreParenImpCasts()};
1738class ArraySubscriptGadget :
public WarningGadget {
1739 static constexpr const char *
const ArraySubscrTag =
"ArraySubscript";
1740 const ArraySubscriptExpr *ASE;
1745 ASE(
Result.getNodeAs<ArraySubscriptExpr>(ArraySubscrTag)) {}
1747 static bool classof(
const Gadget *G) {
1748 return G->getKind() == Kind::ArraySubscript;
1751 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
1752 const UnsafeBufferUsageHandler *Handler,
1754 const auto *ASE = dyn_cast<ArraySubscriptExpr>(S);
1757 const auto *
const Base = ASE->getBase()->IgnoreParenImpCasts();
1760 const auto *Idx = dyn_cast<IntegerLiteral>(ASE->getIdx());
1761 bool IsSafeIndex = (Idx && Idx->getValue().isZero()) ||
1768 Result.addNode(ArraySubscrTag, DynTypedNode::create(*ASE));
1772 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1773 bool IsRelatedToDecl,
1774 ASTContext &Ctx)
const override {
1777 SourceLocation getSourceLoc()
const override {
return ASE->getBeginLoc(); }
1779 DeclUseList getClaimedVarUseSites()
const override {
1780 if (
const auto *DRE =
1781 dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreParenImpCasts())) {
1788 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
1789 return {ASE->getBase()->IgnoreParenImpCasts()};
1797class PointerArithmeticGadget :
public WarningGadget {
1798 static constexpr const char *
const PointerArithmeticTag =
"ptrAdd";
1799 static constexpr const char *
const PointerArithmeticPointerTag =
"ptrAddPtr";
1800 const BinaryOperator *PA;
1805 : WarningGadget(
Kind::PointerArithmetic),
1806 PA(
Result.getNodeAs<BinaryOperator>(PointerArithmeticTag)),
1807 Ptr(
Result.getNodeAs<Expr>(PointerArithmeticPointerTag)) {}
1809 static bool classof(
const Gadget *G) {
1810 return G->getKind() == Kind::PointerArithmetic;
1813 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
1814 const UnsafeBufferUsageHandler *Handler,
1816 const auto *BO = dyn_cast<BinaryOperator>(S);
1819 const auto *LHS = BO->
getLHS();
1820 const auto *RHS = BO->
getRHS();
1822 const Expr *Ptr =
nullptr;
1823 const Expr *OffsetExpr =
nullptr;
1829 RHS->getType()->isEnumeralType())) {
1836 (LHS->getType()->isIntegerType() || LHS->getType()->isEnumeralType())) {
1841 if (!Ptr || !OffsetExpr)
1852 Result.addNode(PointerArithmeticPointerTag, DynTypedNode::create(*Ptr));
1853 Result.addNode(PointerArithmeticTag, DynTypedNode::create(*BO));
1857 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1858 bool IsRelatedToDecl,
1859 ASTContext &Ctx)
const override {
1862 SourceLocation getSourceLoc()
const override {
return PA->getBeginLoc(); }
1864 DeclUseList getClaimedVarUseSites()
const override {
1865 if (
const auto *DRE = dyn_cast<DeclRefExpr>(Ptr->IgnoreParenImpCasts())) {
1872 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
1873 return {Ptr->IgnoreParenImpCasts()};
1880class SpanTwoParamConstructorGadget :
public WarningGadget {
1881 static constexpr const char *
const SpanTwoParamConstructorTag =
1882 "spanTwoParamConstructor";
1883 const CXXConstructExpr *Ctor;
1887 : WarningGadget(
Kind::SpanTwoParamConstructor),
1888 Ctor(
Result.getNodeAs<CXXConstructExpr>(SpanTwoParamConstructorTag)) {}
1890 static bool classof(
const Gadget *G) {
1891 return G->getKind() == Kind::SpanTwoParamConstructor;
1894 static bool matches(
const CXXConstructExpr *CE, ASTContext &Ctx,
1897 const auto *CRecordDecl = CDecl->
getParent();
1898 auto HasTwoParamSpanCtorDecl =
1900 CDecl->getDeclName().getAsString() ==
"span" && CE->
getNumArgs() == 2;
1903 Result.addNode(SpanTwoParamConstructorTag, DynTypedNode::create(*CE));
1907 static bool matches(
const Stmt *S, ASTContext &Ctx,
1908 const UnsafeBufferUsageHandler *Handler,
1910 const auto *CE = dyn_cast<CXXConstructExpr>(S);
1918 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1919 bool IsRelatedToDecl,
1920 ASTContext &Ctx)
const override {
1923 SourceLocation getSourceLoc()
const override {
return Ctor->getBeginLoc(); }
1925 DeclUseList getClaimedVarUseSites()
const override {
1928 if (
auto *DRE = dyn_cast<DeclRefExpr>(Ctor->getArg(0))) {
1935 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
1938class StringViewTwoParamConstructorGadget :
public WarningGadget {
1939 static constexpr const char *
const StringViewTwoParamConstructorTag =
1940 "stringViewTwoParamConstructor";
1941 const CXXConstructExpr *Ctor;
1945 : WarningGadget(
Kind::StringViewTwoParamConstructor),
1946 Ctor(
Result.getNodeAs<CXXConstructExpr>(
1947 StringViewTwoParamConstructorTag)) {}
1949 static bool classof(
const Gadget *G) {
1950 return G->getKind() == Kind::StringViewTwoParamConstructor;
1953 static bool matches(
const CXXConstructExpr *CE, ASTContext &Ctx,
1956 const auto *CRecordDecl = CDecl->
getParent();
1961 CDecl->getDeclName().getAsString() ==
"basic_string_view" &&
1967 Result.addNode(StringViewTwoParamConstructorTag, DynTypedNode::create(*CE));
1971 static bool matches(
const Stmt *S, ASTContext &Ctx,
1972 const UnsafeBufferUsageHandler *Handler,
1974 const auto *CE = dyn_cast<CXXConstructExpr>(S);
1982 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
1983 bool IsRelatedToDecl,
1984 ASTContext &Ctx)
const override {
1988 SourceLocation getSourceLoc()
const override {
return Ctor->getBeginLoc(); }
1990 DeclUseList getClaimedVarUseSites()
const override {
1993 if (
auto *DRE = dyn_cast<DeclRefExpr>(Ctor->getArg(0))) {
2000 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2008class UnsafeBufferUsageContainerAttrGadget :
public WarningGadget {
2009 constexpr static const char *
const OpTag =
"container_attr_expr";
2014 : WarningGadget(
Kind::UnsafeBufferUsageContainerAttr),
2015 Op(
Result.getNodeAs<Expr>(OpTag)) {}
2017 static bool classof(
const Gadget *G) {
2018 return G->getKind() == Kind::UnsafeBufferUsageContainerAttr;
2024 template <
typename CallOrConstructExpr>
2025 static bool isUnsafeContainerConstruction(
const Decl *Callee,
2026 const CallOrConstructExpr &Node,
2030 const auto *Attr =
Callee->getAttr<UnsafeBufferUsageAttr>();
2031 if (!Attr || Attr->getCategory() !=
"container")
2033 return Node.getNumArgs() == 2 &&
2038 static bool matches(
const Stmt *S, ASTContext &Ctx,
2039 const UnsafeBufferUsageHandler *Handler,
2045 if (
const auto *CE = dyn_cast<CXXConstructExpr>(S)) {
2048 if (SpanTwoParamConstructorGadget::matches(CE, Ctx, Tmp))
2051 if (!isUnsafeContainerConstruction(CE->
getConstructor(), *CE, Ctx))
2054 Result.addNode(OpTag, DynTypedNode::create(*CE));
2058 if (
const auto *
Call = dyn_cast<CallExpr>(S)) {
2059 if (!isUnsafeContainerConstruction(
Call->getDirectCallee(), *
Call, Ctx))
2062 Result.addNode(OpTag, DynTypedNode::create(*
Call));
2068 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2069 bool IsRelatedToDecl,
2070 ASTContext &Ctx)
const override {
2074 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2076 DeclUseList getClaimedVarUseSites()
const override {
2077 const Expr *Arg0 =
nullptr;
2079 if (
const auto *CE = dyn_cast<CXXConstructExpr>(Op);
2082 else if (
const auto *
Call = dyn_cast<CallExpr>(Op);
2084 Arg0 =
Call->getArg(0);
2094 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2101class PointerInitGadget :
public FixableGadget {
2103 static constexpr const char *
const PointerInitLHSTag =
"ptrInitLHS";
2104 static constexpr const char *
const PointerInitRHSTag =
"ptrInitRHS";
2105 const VarDecl *PtrInitLHS;
2106 const DeclRefExpr *PtrInitRHS;
2110 : FixableGadget(
Kind::PointerInit),
2111 PtrInitLHS(
Result.getNodeAs<VarDecl>(PointerInitLHSTag)),
2112 PtrInitRHS(
Result.getNodeAs<DeclRefExpr>(PointerInitRHSTag)) {}
2114 static bool classof(
const Gadget *G) {
2115 return G->getKind() == Kind::PointerInit;
2118 static bool matches(
const Stmt *S,
2119 llvm::SmallVectorImpl<MatchResult> &Results) {
2120 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
2129 const auto *DRE = dyn_cast<DeclRefExpr>(
Init->IgnoreImpCasts());
2130 if (!DRE || !
hasPointerType(*DRE) || !isSupportedVariable(*DRE)) {
2134 R.addNode(PointerInitLHSTag, DynTypedNode::create(*VD));
2135 R.addNode(PointerInitRHSTag, DynTypedNode::create(*DRE));
2136 Results.emplace_back(std::move(R));
2140 virtual std::optional<FixItList>
2141 getFixits(
const FixitStrategy &S)
const override;
2142 SourceLocation getSourceLoc()
const override {
2143 return PtrInitRHS->getBeginLoc();
2146 virtual DeclUseList getClaimedVarUseSites()
const override {
2147 return DeclUseList{PtrInitRHS};
2150 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2151 getStrategyImplications()
const override {
2152 return std::make_pair(PtrInitLHS,
cast<VarDecl>(PtrInitRHS->getDecl()));
2161class PtrToPtrAssignmentGadget :
public FixableGadget {
2163 static constexpr const char *
const PointerAssignLHSTag =
"ptrLHS";
2164 static constexpr const char *
const PointerAssignRHSTag =
"ptrRHS";
2165 const DeclRefExpr *PtrLHS;
2166 const DeclRefExpr *PtrRHS;
2170 : FixableGadget(
Kind::PtrToPtrAssignment),
2171 PtrLHS(
Result.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
2172 PtrRHS(
Result.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
2174 static bool classof(
const Gadget *G) {
2175 return G->getKind() == Kind::PtrToPtrAssignment;
2178 static bool matches(
const Stmt *S,
2179 llvm::SmallVectorImpl<MatchResult> &Results) {
2180 size_t SizeBefore = Results.size();
2182 const auto *BO = dyn_cast<BinaryOperator>(S);
2183 if (!BO || BO->
getOpcode() != BO_Assign)
2186 if (
const auto *RHSRef = dyn_cast<DeclRefExpr>(RHS);
2188 !isSupportedVariable(*RHSRef)) {
2191 const auto *LHS = BO->
getLHS();
2192 if (
const auto *LHSRef = dyn_cast<DeclRefExpr>(LHS);
2194 !isSupportedVariable(*LHSRef)) {
2198 R.addNode(PointerAssignLHSTag, DynTypedNode::create(*LHS));
2199 R.addNode(PointerAssignRHSTag, DynTypedNode::create(*RHS));
2200 Results.emplace_back(std::move(R));
2202 return SizeBefore != Results.size();
2205 virtual std::optional<FixItList>
2206 getFixits(
const FixitStrategy &S)
const override;
2207 SourceLocation getSourceLoc()
const override {
return PtrLHS->getBeginLoc(); }
2209 virtual DeclUseList getClaimedVarUseSites()
const override {
2210 return DeclUseList{PtrLHS, PtrRHS};
2213 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2214 getStrategyImplications()
const override {
2225class CArrayToPtrAssignmentGadget :
public FixableGadget {
2227 static constexpr const char *
const PointerAssignLHSTag =
"ptrLHS";
2228 static constexpr const char *
const PointerAssignRHSTag =
"ptrRHS";
2229 const DeclRefExpr *PtrLHS;
2230 const DeclRefExpr *PtrRHS;
2234 : FixableGadget(
Kind::CArrayToPtrAssignment),
2235 PtrLHS(
Result.getNodeAs<DeclRefExpr>(PointerAssignLHSTag)),
2236 PtrRHS(
Result.getNodeAs<DeclRefExpr>(PointerAssignRHSTag)) {}
2238 static bool classof(
const Gadget *G) {
2239 return G->getKind() == Kind::CArrayToPtrAssignment;
2242 static bool matches(
const Stmt *S,
2243 llvm::SmallVectorImpl<MatchResult> &Results) {
2244 size_t SizeBefore = Results.size();
2246 const auto *BO = dyn_cast<BinaryOperator>(S);
2247 if (!BO || BO->
getOpcode() != BO_Assign)
2250 if (
const auto *RHSRef = dyn_cast<DeclRefExpr>(RHS);
2253 !isSupportedVariable(*RHSRef)) {
2256 const auto *LHS = BO->
getLHS();
2257 if (
const auto *LHSRef = dyn_cast<DeclRefExpr>(LHS);
2259 !isSupportedVariable(*LHSRef)) {
2263 R.addNode(PointerAssignLHSTag, DynTypedNode::create(*LHS));
2264 R.addNode(PointerAssignRHSTag, DynTypedNode::create(*RHS));
2265 Results.emplace_back(std::move(R));
2267 return SizeBefore != Results.size();
2270 virtual std::optional<FixItList>
2271 getFixits(
const FixitStrategy &S)
const override;
2272 SourceLocation getSourceLoc()
const override {
return PtrLHS->getBeginLoc(); }
2274 virtual DeclUseList getClaimedVarUseSites()
const override {
2275 return DeclUseList{PtrLHS, PtrRHS};
2278 virtual std::optional<std::pair<const VarDecl *, const VarDecl *>>
2279 getStrategyImplications()
const override {
2286class UnsafeBufferUsageAttrGadget :
public WarningGadget {
2287 constexpr static const char *
const OpTag =
"attr_expr";
2292 : WarningGadget(
Kind::UnsafeBufferUsageAttr),
2293 Op(
Result.getNodeAs<Expr>(OpTag)) {}
2295 static bool classof(
const Gadget *G) {
2296 return G->getKind() == Kind::UnsafeBufferUsageAttr;
2299 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
2301 if (
auto *CE = dyn_cast<CallExpr>(S)) {
2302 if (
const auto *Callee = CE->getDirectCallee()) {
2303 if (
const auto *Attr =
Callee->getAttr<UnsafeBufferUsageAttr>()) {
2307 if (!Attr->getCategory().empty())
2309 Result.addNode(OpTag, DynTypedNode::create(*CE));
2314 if (
auto *ME = dyn_cast<MemberExpr>(S)) {
2317 if (
const auto *Attr =
2318 ME->getMemberDecl()->getAttr<UnsafeBufferUsageAttr>()) {
2319 if (!Attr->getCategory().empty())
2321 Result.addNode(OpTag, DynTypedNode::create(*ME));
2328 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2329 bool IsRelatedToDecl,
2330 ASTContext &Ctx)
const override {
2333 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2335 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2337 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2343class UnsafeBufferUsageCtorAttrGadget :
public WarningGadget {
2344 constexpr static const char *
const OpTag =
"cxx_construct_expr";
2345 const CXXConstructExpr *Op;
2349 : WarningGadget(
Kind::UnsafeBufferUsageCtorAttr),
2350 Op(
Result.getNodeAs<CXXConstructExpr>(OpTag)) {}
2352 static bool classof(
const Gadget *G) {
2353 return G->getKind() == Kind::UnsafeBufferUsageCtorAttr;
2357 const auto *CE = dyn_cast<CXXConstructExpr>(S);
2364 if (!Attr || !Attr->getCategory().empty())
2368 if (SpanTwoParamConstructorGadget::matches(CE, Ctx, Tmp))
2370 Result.addNode(OpTag, DynTypedNode::create(*CE));
2374 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2375 bool IsRelatedToDecl,
2376 ASTContext &Ctx)
const override {
2379 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2381 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2383 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2390class DataInvocationGadget :
public WarningGadget {
2391 constexpr static const char *
const OpTag =
"data_invocation_expr";
2392 const ExplicitCastExpr *Op;
2396 : WarningGadget(
Kind::DataInvocation),
2397 Op(
Result.getNodeAs<ExplicitCastExpr>(OpTag)) {}
2399 static bool classof(
const Gadget *G) {
2400 return G->getKind() == Kind::DataInvocation;
2403 static bool matches(
const Stmt *S,
const ASTContext &Ctx,
2405 auto *CE = dyn_cast<ExplicitCastExpr>(S);
2408 for (
auto *Child : CE->
children()) {
2409 if (
auto *MCE = dyn_cast<CXXMemberCallExpr>(Child);
2410 MCE && isDataFunction(MCE)) {
2411 Result.addNode(OpTag, DynTypedNode::create(*CE));
2414 if (
auto *
Paren = dyn_cast<ParenExpr>(Child)) {
2415 if (
auto *MCE = dyn_cast<CXXMemberCallExpr>(
Paren->getSubExpr());
2416 MCE && isDataFunction(MCE)) {
2417 Result.addNode(OpTag, DynTypedNode::create(*CE));
2425 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2426 bool IsRelatedToDecl,
2427 ASTContext &Ctx)
const override {
2430 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2432 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2435 static bool isDataFunction(
const CXXMemberCallExpr *call) {
2442 if (method->getNameAsString() ==
"data" &&
2443 method->getParent()->isInStdNamespace() &&
2444 llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
2445 method->getParent()->getName()))
2450 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2453class UnsafeLibcFunctionCallGadget :
public WarningGadget {
2454 const CallExpr *
const Call;
2455 const Expr *UnsafeArg =
nullptr;
2456 constexpr static const char *
const Tag =
"UnsafeLibcFunctionCall";
2458 constexpr static const char *
const UnsafeSprintfTag =
2459 "UnsafeLibcFunctionCall_sprintf";
2460 constexpr static const char *
const UnsafeSizedByTag =
2461 "UnsafeLibcFunctionCall_sized_by";
2462 constexpr static const char *
const UnsafeStringTag =
2463 "UnsafeLibcFunctionCall_string";
2464 constexpr static const char *
const UnsafeVaListTag =
2465 "UnsafeLibcFunctionCall_va_list";
2479 } WarnedFunKind = OTHERS;
2483 : WarningGadget(
Kind::UnsafeLibcFunctionCall),
2484 Call(
Result.getNodeAs<CallExpr>(Tag)) {
2485 if (
Result.getNodeAs<Decl>(UnsafeSprintfTag))
2486 WarnedFunKind = SPRINTF;
2487 else if (
auto *E =
Result.getNodeAs<Expr>(UnsafeStringTag)) {
2488 WarnedFunKind = STRING;
2490 }
else if (
Result.getNodeAs<CallExpr>(UnsafeSizedByTag)) {
2491 WarnedFunKind = SIZED_BY;
2492 UnsafeArg = Call->getArg(0);
2493 }
else if (
Result.getNodeAs<Decl>(UnsafeVaListTag))
2494 WarnedFunKind = VA_LIST;
2497 Family = WarnedFunKind != OTHERS
2498 ? UnsafeLibcFunctionFamily::Printf
2500 *Call->getDirectCallee());
2503 static bool matches(
const Stmt *S, ASTContext &Ctx,
2504 const UnsafeBufferUsageHandler *Handler,
2506 const auto *CE = dyn_cast<CallExpr>(S);
2509 const auto *FD = CE->getDirectCallee();
2523 const bool isSingleStringLiteralArg =
2526 if (!isSingleStringLiteralArg) {
2529 Result.addNode(Tag, DynTypedNode::create(*CE));
2533 Result.addNode(Tag, DynTypedNode::create(*CE));
2537 Result.addNode(Tag, DynTypedNode::create(*CE));
2538 Result.addNode(UnsafeVaListTag, DynTypedNode::create(*FD));
2542 Result.addNode(Tag, DynTypedNode::create(*CE));
2543 Result.addNode(UnsafeSprintfTag, DynTypedNode::create(*FD));
2549 Result.addNode(Tag, DynTypedNode::create(*CE));
2550 Result.addNode(UnsafeSizedByTag, DynTypedNode::create(*CE));
2555 Result.addNode(Tag, DynTypedNode::create(*CE));
2562 const Stmt *getBaseStmt()
const {
return Call; }
2564 SourceLocation getSourceLoc()
const override {
return Call->getBeginLoc(); }
2566 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2567 bool IsRelatedToDecl,
2568 ASTContext &Ctx)
const override {
2572 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2574 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2577class UnsafeFormatAttributedFunctionCallGadget :
public WarningGadget {
2578 const CallExpr *
const Call;
2579 const Expr *UnsafeArg =
nullptr;
2580 constexpr static const char *
const Tag =
"UnsafeFormatAttributedFunctionCall";
2581 constexpr static const char *
const UnsafeStringTag =
2582 "UnsafeFormatAttributedFunctionCall_string";
2586 : WarningGadget(
Kind::UnsafeLibcFunctionCall),
2587 Call(
Result.getNodeAs<CallExpr>(Tag)),
2588 UnsafeArg(
Result.getNodeAs<Expr>(UnsafeStringTag)) {}
2590 static bool matches(
const Stmt *S, ASTContext &Ctx,
2591 const UnsafeBufferUsageHandler *Handler,
2593 auto *CE = dyn_cast<CallExpr>(S);
2594 if (!CE || !CE->getDirectCallee())
2596 const FunctionDecl *FD = CE->getDirectCallee();
2602 const FormatAttr *Attr =
nullptr;
2603 bool IsPrintf =
false;
2604 bool AnyAttr = llvm::any_of(
2606 [&Attr, &IsPrintf](
const FormatAttr *FA) ->
bool {
2607 if (const auto *II = FA->getType()) {
2608 if (II->getName() ==
"printf" || II->getName() ==
"scanf") {
2610 IsPrintf = II->getName() ==
"printf";
2616 const Expr *UnsafeArg;
2626 unsigned FmtIdx = Attr->getFormatIdx() - 1;
2627 std::optional<unsigned> FmtArgIdx = Attr->getFirstArg() - 1;
2637 }
else if (CE->
getStmtClass() != Stmt::CallExprClass &&
2647 FmtArgIdx = std::nullopt;
2649 if (AnyAttr && !IsPrintf && FmtArgIdx) {
2651 Result.addNode(Tag, DynTypedNode::create(*CE));
2656 Ctx, CE, UnsafeArg, FmtIdx, FmtArgIdx)) {
2657 Result.addNode(Tag, DynTypedNode::create(*CE));
2658 Result.addNode(UnsafeStringTag, DynTypedNode::create(*UnsafeArg));
2664 const Stmt *getBaseStmt()
const {
return Call; }
2669 bool IsRelatedToDecl,
2674 UnsafeLibcFunctionCallGadget::UnsafeKind::STRING |
2675 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2680 UnsafeLibcFunctionCallGadget::UnsafeKind::OTHERS |
2681 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2685 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2693class ULCArraySubscriptGadget :
public FixableGadget {
2695 static constexpr const char *
const ULCArraySubscriptTag =
2696 "ArraySubscriptUnderULC";
2697 const ArraySubscriptExpr *Node;
2701 : FixableGadget(
Kind::ULCArraySubscript),
2702 Node(
Result.getNodeAs<ArraySubscriptExpr>(ULCArraySubscriptTag)) {
2703 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2706 static bool classof(
const Gadget *G) {
2707 return G->getKind() == Kind::ULCArraySubscript;
2710 static bool matches(
const Stmt *S,
2711 llvm::SmallVectorImpl<MatchResult> &Results) {
2712 size_t SizeBefore = Results.size();
2714 const auto *ASE = dyn_cast<ArraySubscriptExpr>(E);
2720 !isSupportedVariable(*DRE))
2723 R.addNode(ULCArraySubscriptTag, DynTypedNode::create(*ASE));
2724 Results.emplace_back(std::move(R));
2726 return SizeBefore != Results.size();
2729 virtual std::optional<FixItList>
2730 getFixits(
const FixitStrategy &S)
const override;
2731 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2733 virtual DeclUseList getClaimedVarUseSites()
const override {
2734 if (
const auto *DRE =
2735 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts())) {
2745class UPCStandalonePointerGadget :
public FixableGadget {
2747 static constexpr const char *
const DeclRefExprTag =
"StandalonePointer";
2748 const DeclRefExpr *Node;
2752 : FixableGadget(
Kind::UPCStandalonePointer),
2753 Node(
Result.getNodeAs<DeclRefExpr>(DeclRefExprTag)) {
2754 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2757 static bool classof(
const Gadget *G) {
2758 return G->getKind() == Kind::UPCStandalonePointer;
2761 static bool matches(
const Stmt *S,
2762 llvm::SmallVectorImpl<MatchResult> &Results) {
2763 size_t SizeBefore = Results.size();
2765 auto *E = dyn_cast<Expr>(S);
2770 !isSupportedVariable(*DRE))
2773 R.addNode(DeclRefExprTag, DynTypedNode::create(*DRE));
2774 Results.emplace_back(std::move(R));
2776 return SizeBefore != Results.size();
2779 virtual std::optional<FixItList>
2780 getFixits(
const FixitStrategy &S)
const override;
2781 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2783 virtual DeclUseList getClaimedVarUseSites()
const override {
return {Node}; }
2786class PointerDereferenceGadget :
public FixableGadget {
2787 static constexpr const char *
const BaseDeclRefExprTag =
"BaseDRE";
2788 static constexpr const char *
const OperatorTag =
"op";
2790 const DeclRefExpr *BaseDeclRefExpr =
nullptr;
2791 const UnaryOperator *Op =
nullptr;
2795 : FixableGadget(
Kind::PointerDereference),
2796 BaseDeclRefExpr(
Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
2797 Op(
Result.getNodeAs<UnaryOperator>(OperatorTag)) {}
2799 static bool classof(
const Gadget *G) {
2800 return G->getKind() == Kind::PointerDereference;
2803 static bool matches(
const Stmt *S,
2804 llvm::SmallVectorImpl<MatchResult> &Results) {
2805 size_t SizeBefore = Results.size();
2807 const auto *UO = dyn_cast<UnaryOperator>(S);
2814 const auto *DRE = dyn_cast<DeclRefExpr>(CE);
2815 if (!DRE || !isSupportedVariable(*DRE))
2818 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
2819 R.addNode(OperatorTag, DynTypedNode::create(*UO));
2820 Results.emplace_back(std::move(R));
2822 return SizeBefore != Results.size();
2825 DeclUseList getClaimedVarUseSites()
const override {
2826 return {BaseDeclRefExpr};
2829 virtual std::optional<FixItList>
2830 getFixits(
const FixitStrategy &S)
const override;
2831 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2837class UPCAddressofArraySubscriptGadget :
public FixableGadget {
2839 static constexpr const char *
const UPCAddressofArraySubscriptTag =
2840 "AddressofArraySubscriptUnderUPC";
2841 const UnaryOperator *Node;
2845 : FixableGadget(
Kind::ULCArraySubscript),
2846 Node(
Result.getNodeAs<UnaryOperator>(UPCAddressofArraySubscriptTag)) {
2847 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2850 static bool classof(
const Gadget *G) {
2851 return G->getKind() == Kind::UPCAddressofArraySubscript;
2854 static bool matches(
const Stmt *S,
2855 llvm::SmallVectorImpl<MatchResult> &Results) {
2856 size_t SizeBefore = Results.size();
2858 auto *E = dyn_cast<Expr>(S);
2862 if (!UO || UO->
getOpcode() != UO_AddrOf)
2864 const auto *ASE = dyn_cast<ArraySubscriptExpr>(UO->
getSubExpr());
2869 if (!DRE || !isSupportedVariable(*DRE))
2872 R.addNode(UPCAddressofArraySubscriptTag, DynTypedNode::create(*UO));
2873 Results.emplace_back(std::move(R));
2875 return SizeBefore != Results.size();
2878 virtual std::optional<FixItList>
2879 getFixits(
const FixitStrategy &)
const override;
2880 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2882 virtual DeclUseList getClaimedVarUseSites()
const override {
2895class DeclUseTracker {
2896 using UseSetTy = llvm::SmallPtrSet<const DeclRefExpr *, 16>;
2897 using DefMapTy = llvm::DenseMap<const VarDecl *, const DeclStmt *>;
2900 std::unique_ptr<UseSetTy> Uses{std::make_unique<UseSetTy>()};
2904 DeclUseTracker() =
default;
2905 DeclUseTracker(
const DeclUseTracker &) =
delete;
2906 DeclUseTracker &operator=(
const DeclUseTracker &) =
delete;
2907 DeclUseTracker(DeclUseTracker &&) =
default;
2908 DeclUseTracker &operator=(DeclUseTracker &&) =
default;
2911 void discoverUse(
const DeclRefExpr *DRE) { Uses->insert(DRE); }
2914 void claimUse(
const DeclRefExpr *DRE) {
2915 assert(Uses->count(DRE) &&
2916 "DRE not found or claimed by multiple matchers!");
2921 bool hasUnclaimedUses(
const VarDecl *VD)
const {
2923 return any_of(*Uses, [VD](
const DeclRefExpr *DRE) {
2928 UseSetTy getUnclaimedUses(
const VarDecl *VD)
const {
2930 for (
auto use : *Uses) {
2932 ReturnSet.insert(use);
2938 void discoverDecl(
const DeclStmt *DS) {
2939 for (
const Decl *D : DS->
decls()) {
2940 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
2951 const DeclStmt *lookupDecl(
const VarDecl *VD)
const {
2952 return Defs.lookup(VD);
2961 static constexpr const char *
const UPCPreIncrementTag =
2962 "PointerPreIncrementUnderUPC";
2967 : FixableGadget(Kind::UPCPreIncrement),
2969 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2973 return G->getKind() == Kind::UPCPreIncrement;
2982 size_t SizeBefore = Results.size();
2984 auto *E = dyn_cast<Expr>(S);
2988 if (!UO || UO->
getOpcode() != UO_PreInc)
2990 const auto *DRE = dyn_cast<DeclRefExpr>(UO->
getSubExpr());
2991 if (!DRE || !isSupportedVariable(*DRE))
2995 Results.emplace_back(std::move(R));
2997 return SizeBefore != Results.size();
3000 virtual std::optional<FixItList>
3005 return {dyn_cast<DeclRefExpr>(Node->getSubExpr())};
3013 static constexpr const char *
const UUCAddAssignTag =
3014 "PointerAddAssignUnderUUC";
3015 static constexpr const char *
const OffsetTag =
"Offset";
3018 const Expr *Offset =
nullptr;
3022 : FixableGadget(Kind::UUCAddAssign),
3025 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
3029 return G->getKind() == Kind::UUCAddAssign;
3034 size_t SizeBefore = Results.size();
3036 const auto *E = dyn_cast<Expr>(S);
3040 if (!BO || BO->
getOpcode() != BO_AddAssign)
3042 const auto *DRE = dyn_cast<DeclRefExpr>(BO->
getLHS());
3048 Results.emplace_back(std::move(R));
3050 return SizeBefore != Results.size();
3053 virtual std::optional<FixItList>
3058 return {dyn_cast<DeclRefExpr>(Node->getLHS())};
3065 static constexpr const char *
const BaseDeclRefExprTag =
"BaseDRE";
3066 static constexpr const char *
const DerefOpTag =
"DerefOp";
3067 static constexpr const char *
const AddOpTag =
"AddOp";
3068 static constexpr const char *
const OffsetTag =
"Offset";
3077 : FixableGadget(Kind::DerefSimplePtrArithFixable),
3085 auto IsPtr = [](
const Expr *E, MatchResult &R) {
3089 if (!DRE || !isSupportedVariable(*DRE))
3094 const auto IsPlusOverPtrAndInteger = [&IsPtr](
const Expr *E,
3096 const auto *BO = dyn_cast<BinaryOperator>(E);
3100 const auto *LHS = BO->
getLHS();
3101 const auto *RHS = BO->
getRHS();
3114 size_t SizeBefore = Results.size();
3115 const auto InnerMatcher = [&IsPlusOverPtrAndInteger,
3116 &Results](
const Expr *E) {
3117 const auto *UO = dyn_cast<UnaryOperator>(E);
3123 if (IsPlusOverPtrAndInteger(Operand, R)) {
3125 Results.emplace_back(std::move(R));
3129 return SizeBefore != Results.size();
3132 virtual std::optional<FixItList>
3135 return DerefOp->getBeginLoc();
3139 return {BaseDeclRefExpr};
3147 : WarningGadgets(WarningGadgets) {}
3156#define WARNING_GADGET(name) \
3157 if (name##Gadget::matches(S, Ctx, Result) && \
3158 notInSafeBufferOptOut(*S, &Handler)) { \
3159 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3162#define WARNING_OPTIONAL_GADGET(name) \
3163 if (name##Gadget::matches(S, Ctx, &Handler, Result) && \
3164 notInSafeBufferOptOut(*S, &Handler)) { \
3165 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3168#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3173 WarningGadgetList &WarningGadgets;
3180 DeclUseTracker &Tracker)
3181 : FixableGadgets(FixableGadgets), Tracker(Tracker) {}
3185 bool matchFound =
false;
3192#define FIXABLE_GADGET(name) \
3193 if (name##Gadget::matches(S, Results)) { \
3194 for (const auto &R : Results) { \
3195 FixableGadgets.push_back(std::make_unique<name##Gadget>(R)); \
3196 matchFound = true; \
3200#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3203 if (
auto *DRE = findDeclRefExpr(S); DRE) {
3204 Tracker.discoverUse(DRE);
3210 if (
auto *DS = findDeclStmt(S); DS) {
3211 Tracker.discoverDecl(DS);
3219 const auto *DRE = dyn_cast<DeclRefExpr>(S);
3227 const DeclStmt *findDeclStmt(
const Stmt *S) {
3228 const auto *DS = dyn_cast<DeclStmt>(S);
3233 FixableGadgetList &FixableGadgets;
3234 DeclUseTracker &Tracker;
3240 bool EmitSuggestions, FixableGadgetList &FixableGadgets,
3241 WarningGadgetList &WarningGadgets,
3242 DeclUseTracker &Tracker) {
3245 if (EmitSuggestions) {
3254 return N1->getBeginLoc().getRawEncoding() <
3255 N2->getBeginLoc().getRawEncoding();
3268 auto AddStmt = [&Stmts](
const Stmt *S) {
3272 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
3275 if (PD->hasDefaultArg() && !PD->hasUninstantiatedDefaultArg())
3276 AddStmt(PD->getDefaultArg());
3277 if (
const auto *CtorD = dyn_cast<CXXConstructorDecl>(FD))
3279 Stmts, llvm::map_range(CtorD->inits(),
3283 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
3285 }
else if (
const auto *FD = dyn_cast<FieldDecl>(D)) {
3286 AddStmt(FD->getInClassInitializer());
3291 std::map<const VarDecl *, std::set<const WarningGadget *>,
3305 for (
auto &G : AllUnsafeOperations) {
3306 DeclUseList ClaimedVarUseSites = G->getClaimedVarUseSites();
3308 bool AssociatedWithVarDecl =
false;
3309 for (
const DeclRefExpr *DRE : ClaimedVarUseSites) {
3310 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3311 result.
byVar[VD].insert(G.get());
3312 AssociatedWithVarDecl =
true;
3316 if (!AssociatedWithVarDecl) {
3317 result.
noVar.push_back(G.get());
3325 std::map<const VarDecl *, std::set<const FixableGadget *>,
3335 for (
auto &F : AllFixableOperations) {
3336 DeclUseList DREs = F->getClaimedVarUseSites();
3339 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3340 FixablesForUnsafeVars.
byVar[VD].insert(F.get());
3344 return FixablesForUnsafeVars;
3351 std::vector<const FixItHint *>
All;
3355 std::sort(
All.begin(),
All.end(),
3357 return SM.isBeforeInTranslationUnit(H1->RemoveRange.getBegin(),
3358 H2->RemoveRange.getBegin());
3366 Hint->RemoveRange.getBegin())) {
3378std::optional<FixItList>
3379PtrToPtrAssignmentGadget::getFixits(
const FixitStrategy &S)
const {
3382 switch (S.
lookup(LeftVD)) {
3386 return std::nullopt;
3388 return std::nullopt;
3391 return std::nullopt;
3393 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3395 return std::nullopt;
3399static inline std::optional<FixItList>
createDataFixit(
const ASTContext &Ctx,
3400 const DeclRefExpr *DRE);
3402std::optional<FixItList>
3403CArrayToPtrAssignmentGadget::getFixits(
const FixitStrategy &S)
const {
3422 if (S.
lookup(LeftVD) == FixitStrategy::Kind::Span) {
3423 if (S.
lookup(RightVD) == FixitStrategy::Kind::Wontfix) {
3426 }
else if (S.
lookup(LeftVD) == FixitStrategy::Kind::Wontfix) {
3427 if (S.
lookup(RightVD) == FixitStrategy::Kind::Array) {
3431 return std::nullopt;
3434std::optional<FixItList>
3435PointerInitGadget::getFixits(
const FixitStrategy &S)
const {
3436 const auto *LeftVD = PtrInitLHS;
3438 switch (S.
lookup(LeftVD)) {
3439 case FixitStrategy::Kind::Span:
3440 if (S.
lookup(RightVD) == FixitStrategy::Kind::Span)
3442 return std::nullopt;
3443 case FixitStrategy::Kind::Wontfix:
3444 return std::nullopt;
3445 case FixitStrategy::Kind::Iterator:
3446 case FixitStrategy::Kind::Array:
3447 return std::nullopt;
3448 case FixitStrategy::Kind::Vector:
3449 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3451 return std::nullopt;
3457 if (ConstVal->isNegative())
3464std::optional<FixItList>
3465ULCArraySubscriptGadget::getFixits(
const FixitStrategy &S)
const {
3466 if (
const auto *DRE =
3468 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3470 case FixitStrategy::Kind::Span: {
3474 const ASTContext &Ctx =
3477 return std::nullopt;
3481 case FixitStrategy::Kind::Array:
3483 case FixitStrategy::Kind::Wontfix:
3484 case FixitStrategy::Kind::Iterator:
3485 case FixitStrategy::Kind::Vector:
3486 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3489 return std::nullopt;
3492static std::optional<FixItList>
3495std::optional<FixItList>
3496UPCAddressofArraySubscriptGadget::getFixits(
const FixitStrategy &S)
const {
3497 auto DREs = getClaimedVarUseSites();
3501 case FixitStrategy::Kind::Span:
3503 case FixitStrategy::Kind::Wontfix:
3504 case FixitStrategy::Kind::Iterator:
3505 case FixitStrategy::Kind::Array:
3506 return std::nullopt;
3507 case FixitStrategy::Kind::Vector:
3508 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3510 return std::nullopt;
3515 static const char *
const EOL =
"\n";
3522 std::string s = std::string(
"<# ");
3523 s += HintTextToUser;
3529template <
typename NodeTy>
3530static std::optional<SourceLocation>
3533 if (
unsigned TkLen =
3540 return std::nullopt;
3553 bool AttrRangeOverlapping = llvm::any_of(VD->
attrs(), [&](
Attr *At) ->
bool {
3554 return !(SM.isBeforeInTranslationUnit(At->getRange().getEnd(),
3555 VD->getBeginLoc())) &&
3556 !(SM.isBeforeInTranslationUnit(VD->getEndLoc(),
3557 At->getRange().getBegin()));
3561 AttrRangeOverlapping;
3603 std::optional<Qualifiers> Quals = std::nullopt) {
3604 const char *
const SpanOpen =
"std::span<";
3607 return SpanOpen + EltTyText.str() +
' ' + Quals->getAsString() +
'>';
3608 return SpanOpen + EltTyText.str() +
'>';
3611std::optional<FixItList>
3613 const VarDecl *VD = dyn_cast<VarDecl>(BaseDeclRefExpr->getDecl());
3618 if (
auto ConstVal = Offset->getIntegerConstantExpr(Ctx))
3619 if (ConstVal->isNegative())
3620 return std::nullopt;
3641 const Expr *LHS = AddOp->getLHS(), *RHS = AddOp->getRHS();
3648 std::optional<SourceLocation> LHSLocation =
getPastLoc(LHS, SM, LangOpts);
3650 return std::nullopt;
3655 std::optional<SourceLocation> AddOpLocation =
3657 std::optional<SourceLocation> DerefOpLocation =
3660 if (!AddOpLocation || !DerefOpLocation)
3661 return std::nullopt;
3671 return std::nullopt;
3674std::optional<FixItList>
3675PointerDereferenceGadget::getFixits(
const FixitStrategy &S)
const {
3686 if (
auto LocPastOperand =
3693 case FixitStrategy::Kind::Iterator:
3694 case FixitStrategy::Kind::Array:
3695 return std::nullopt;
3696 case FixitStrategy::Kind::Vector:
3697 llvm_unreachable(
"FixitStrategy not implemented yet!");
3698 case FixitStrategy::Kind::Wontfix:
3699 llvm_unreachable(
"Invalid strategy!");
3702 return std::nullopt;
3709 std::optional<SourceLocation> EndOfOperand =
3715 return std::nullopt;
3720std::optional<FixItList>
3721UPCStandalonePointerGadget::getFixits(
const FixitStrategy &S)
const {
3724 case FixitStrategy::Kind::Array:
3725 case FixitStrategy::Kind::Span: {
3730 case FixitStrategy::Kind::Wontfix:
3731 case FixitStrategy::Kind::Iterator:
3732 return std::nullopt;
3733 case FixitStrategy::Kind::Vector:
3734 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3737 return std::nullopt;
3742static std::optional<FixItList>
3749 const Expr *Idx = ArraySub->getIdx();
3752 std::stringstream SS;
3753 bool IdxIsLitZero =
false;
3756 if ((*ICE).isZero())
3757 IdxIsLitZero =
true;
3758 std::optional<StringRef> DreString =
getExprText(DRE, SM, LangOpts);
3760 return std::nullopt;
3764 SS << (*DreString).str() <<
".data()";
3766 std::optional<StringRef> IndexString =
getExprText(Idx, SM, LangOpts);
3768 return std::nullopt;
3770 SS <<
"&" << (*DreString).str() <<
".data()"
3771 <<
"[" << (*IndexString).str() <<
"]";
3777std::optional<FixItList>
3781 if (DREs.size() != 1)
3782 return std::nullopt;
3784 if (
const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3788 const Stmt *AddAssignNode = Node;
3789 StringRef varName = VD->
getName();
3793 return std::nullopt;
3797 (Offset->IgnoreParens()->getBeginLoc() == Offset->getBeginLoc());
3798 std::string SS = varName.str() +
" = " + varName.str() +
".subspan";
3802 std::optional<SourceLocation> AddAssignLocation =
getEndCharLoc(
3804 if (!AddAssignLocation)
3805 return std::nullopt;
3812 Offset->getEndLoc().getLocWithOffset(1),
")"));
3816 return std::nullopt;
3819std::optional<FixItList>
3823 if (DREs.size() != 1)
3824 return std::nullopt;
3826 if (
const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3829 std::stringstream SS;
3830 StringRef varName = VD->
getName();
3834 SS <<
"(" << varName.data() <<
" = " << varName.data()
3835 <<
".subspan(1)).data()";
3836 std::optional<SourceLocation> PreIncLocation =
3838 if (!PreIncLocation)
3839 return std::nullopt;
3842 SourceRange(Node->getBeginLoc(), *PreIncLocation), SS.str()));
3846 return std::nullopt;
3864static std::optional<FixItList>
3866 const StringRef UserFillPlaceHolder) {
3874 if (
Init->isNullPointerConstant(
3879 NPC_ValueDependentIsNotNull)) {
3880 std::optional<SourceLocation> InitLocation =
3883 return std::nullopt;
3891 std::string ExtentText = UserFillPlaceHolder.data();
3892 StringRef One =
"1";
3897 if (
auto CxxNew = dyn_cast<CXXNewExpr>(
Init->IgnoreImpCasts())) {
3902 if (
const Expr *Ext = CxxNew->getArraySize().value_or(
nullptr)) {
3903 if (!Ext->HasSideEffects(Ctx)) {
3904 std::optional<StringRef> ExtentString =
getExprText(Ext, SM, LangOpts);
3906 return std::nullopt;
3907 ExtentText = *ExtentString;
3909 }
else if (!CxxNew->isArray())
3921 if (
auto AddrOfExpr = dyn_cast<UnaryOperator>(
Init->IgnoreImpCasts()))
3922 if (AddrOfExpr->getOpcode() == UnaryOperatorKind::UO_AddrOf &&
3923 isa_and_present<DeclRefExpr>(AddrOfExpr->getSubExpr()))
3930 std::optional<SourceLocation> LocPassInit =
getPastLoc(
Init, SM, LangOpts);
3933 return std::nullopt;
3935 StrBuffer.append(
", ");
3936 StrBuffer.append(ExtentText);
3937 StrBuffer.append(
"}");
3943#define DEBUG_NOTE_DECL_FAIL(D, Msg) \
3944 Handler.addDebugNoteForVar((D), (D)->getBeginLoc(), \
3945 "failed to produce fixit for declaration '" + \
3946 (D)->getNameAsString() + "'" + (Msg))
3948#define DEBUG_NOTE_DECL_FAIL(D, Msg)
3954static std::optional<std::string>
3958 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
3963 return std::nullopt;
3965 std::string SpanTyText =
"std::span<";
3967 SpanTyText.append(*PteTyText);
3969 if (PteTyQualifiers) {
3970 SpanTyText.append(
" ");
3971 SpanTyText.append(PteTyQualifiers->getAsString());
3973 SpanTyText.append(
">");
3992 const StringRef UserFillPlaceHolder,
4006 std::stringstream SS;
4011 std::optional<FixItList> InitFixIts =
4015 FixIts.insert(FixIts.end(), std::make_move_iterator(InitFixIts->begin()),
4016 std::make_move_iterator(InitFixIts->end()));
4023 if (!EndLocForReplacement.
isValid()) {
4073static std::optional<FixItList>
4079 return std::nullopt;
4084 std::vector<std::string> NewTysTexts(NumParms);
4085 std::vector<bool> ParmsMask(NumParms,
false);
4086 bool AtLeastOneParmToFix =
false;
4088 for (
unsigned i = 0; i < NumParms; i++) {
4095 return std::nullopt;
4097 std::optional<Qualifiers> PteTyQuals = std::nullopt;
4098 std::optional<std::string> PteTyText =
4103 return std::nullopt;
4107 ParmsMask[i] =
true;
4108 AtLeastOneParmToFix =
true;
4110 if (!AtLeastOneParmToFix)
4117 const auto NewOverloadSignatureCreator =
4118 [&SM, &LangOpts, &NewTysTexts,
4119 &ParmsMask](
const FunctionDecl *FD) -> std::optional<std::string> {
4120 std::stringstream SS;
4128 SS << Prefix->str();
4130 return std::nullopt;
4134 for (
unsigned i = 0; i < NumParms; i++) {
4142 SS << NewTysTexts[i];
4145 SS <<
' ' << II->getName().str();
4146 }
else if (
auto ParmTypeText =
4150 SS << ParmTypeText->str();
4152 return std::nullopt;
4153 if (i != NumParms - 1)
4162 const auto OldOverloadDefCreator =
4163 [&Handler, &SM, &LangOpts, &NewTysTexts,
4164 &ParmsMask](
const FunctionDecl *FD) -> std::optional<std::string> {
4165 std::stringstream SS;
4173 << FDPrefix->str() <<
"{";
4175 return std::nullopt;
4178 SS <<
"return " << FunQualName->str() <<
"(";
4180 return std::nullopt;
4184 for (
unsigned i = 0; i < NumParms; i++) {
4193 return std::nullopt;
4200 if (i != NumParms - 1)
4211 std::optional<SourceLocation> Loc =
getPastLoc(FReDecl, SM, LangOpts);
4215 if (FReDecl->isThisDeclarationADefinition()) {
4216 assert(FReDecl == FD &&
"inconsistent function definition");
4219 if (
auto OldOverloadDef = OldOverloadDefCreator(FReDecl))
4225 if (!FReDecl->hasAttr<UnsafeBufferUsageAttr>()) {
4228 FReDecl->getBeginLoc(),
" ")));
4231 if (
auto NewOverloadDecl = NewOverloadSignatureCreator(FReDecl))
4253 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
4269 std::stringstream SS;
4272 if (PteTyQualifiers)
4281 SS <<
' ' << PVDNameText->str();
4287 const DeclUseTracker &Tracker,
4290 const DeclStmt *DS = Tracker.lookupDecl(VD);
4293 " : variables declared this way not implemented yet");
4317 const QualType &ArrayEltT = CAT->getElementType();
4318 assert(!ArrayEltT.
isNull() &&
"Trying to fix a non-array type variable!");
4327 auto MaybeElemTypeTxt =
4330 if (!MaybeElemTypeTxt)
4332 const llvm::StringRef ElemTypeTxt = MaybeElemTypeTxt->trim();
4337 while (NextTok && !NextTok->is(tok::l_square) &&
4350 if (!MaybeArraySizeTxt)
4352 const llvm::StringRef ArraySizeTxt = MaybeArraySizeTxt->trim();
4353 if (ArraySizeTxt.empty()) {
4364 std::optional<StringRef> IdentText =
4373 llvm::raw_svector_ostream OS(Replacement);
4374 OS <<
"std::array<" << ElemTypeTxt <<
", " << ArraySizeTxt <<
"> "
4375 << IdentText->str();
4385 const DeclUseTracker &Tracker,
4388 const DeclStmt *DS = Tracker.lookupDecl(VD);
4389 assert(DS &&
"Fixing non-local variables not implemented yet!");
4408 const DeclUseTracker &Tracker,
ASTContext &Ctx,
4410 if (
const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4411 auto *FD = dyn_cast<clang::FunctionDecl>(PVD->getDeclContext());
4412 if (!FD || FD != D) {
4429 isa_and_nonnull<CXXTryStmt>(FD->
getBody()) ||
4439 if (
const auto *PVD = dyn_cast<ParmVarDecl>(VD))
4457 llvm_unreachable(
"FixitStrategy not implemented yet!");
4459 llvm_unreachable(
"Invalid strategy!");
4461 llvm_unreachable(
"Unknown strategy!");
4469 return llvm::any_of(FixIts, [](
const FixItHint &Hint) {
4471 if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
4488 std::map<const VarDecl *, FixItList> &FixItsForVariable,
4493 for (
const auto &[VD, Ignore] : FixItsForVariable) {
4495 if (llvm::any_of(Grp,
4496 [&FixItsForVariable](
const VarDecl *GrpMember) ->
bool {
4497 return !FixItsForVariable.count(GrpMember);
4502 ToErase.push_back(
Member);
4505 for (
auto *VarToErase : ToErase)
4506 FixItsForVariable.erase(VarToErase);
4517 std::map<const VarDecl *, FixItList> &FixItsForVariable ,
4521 FixItList FixItsSharedByParms{};
4523 std::optional<FixItList> OverloadFixes =
4526 if (OverloadFixes) {
4527 FixItsSharedByParms.append(*OverloadFixes);
4533 FixItsForVariable.erase(
Member);
4535 return FixItsSharedByParms;
4539static std::map<const VarDecl *, FixItList>
4548 std::map<const VarDecl *, FixItList> FixItsForVariable;
4553 for (
const auto &[VD, Fixables] : FixablesForAllVars.
byVar) {
4554 FixItsForVariable[VD] =
4558 if (FixItsForVariable[VD].empty()) {
4559 FixItsForVariable.erase(VD);
4562 for (
const auto &F : Fixables) {
4563 std::optional<FixItList> Fixits = F->getFixits(S);
4566 FixItsForVariable[VD].insert(FixItsForVariable[VD].end(),
4567 Fixits->begin(), Fixits->end());
4572 VD, F->getSourceLoc(),
4573 (
"gadget '" + F->getDebugName() +
"' refused to produce a fix")
4576 FixItsForVariable.erase(VD);
4595 FixItList FixItsSharedByParms{};
4597 if (
auto *FD = dyn_cast<FunctionDecl>(D))
4599 FixItsForVariable, VarGrpMgr, FD, S, Ctx, Handler);
4603 std::map<const VarDecl *, FixItList> FinalFixItsForVariable{
4606 for (
auto &[Var, Ignore] : FixItsForVariable) {
4607 bool AnyParm =
false;
4608 const auto VarGroupForVD = VarGrpMgr.
getGroupOfVar(Var, &AnyParm);
4610 for (
const VarDecl *GrpMate : VarGroupForVD) {
4613 if (FixItsForVariable.count(GrpMate))
4614 FinalFixItsForVariable[Var].append(FixItsForVariable[GrpMate]);
4618 assert(!FixItsSharedByParms.empty() &&
4619 "Should not try to fix a parameter that does not belong to a "
4621 FinalFixItsForVariable[Var].append(FixItsSharedByParms);
4628 for (
auto Iter = FinalFixItsForVariable.begin();
4629 Iter != FinalFixItsForVariable.end();)
4632 Iter = FinalFixItsForVariable.erase(Iter);
4635 return FinalFixItsForVariable;
4638template <
typename VarDeclIterTy>
4642 for (
const VarDecl *VD : UnsafeVars) {
4653 const std::vector<VarGrpTy> &Groups;
4654 const std::map<const VarDecl *, unsigned> &VarGrpMap;
4655 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms;
4659 const std::vector<VarGrpTy> &Groups,
4660 const std::map<const VarDecl *, unsigned> &VarGrpMap,
4661 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms)
4662 : Groups(Groups), VarGrpMap(VarGrpMap),
4663 GrpsUnionForParms(GrpsUnionForParms) {}
4666 if (GrpsUnionForParms.contains(Var)) {
4669 return GrpsUnionForParms.getArrayRef();
4674 auto It = VarGrpMap.find(Var);
4676 if (It == VarGrpMap.end())
4678 return Groups[It->second];
4682 return GrpsUnionForParms.getArrayRef();
4687 WarningGadgetList WarningGadgets,
4688 DeclUseTracker Tracker,
4690 bool EmitSuggestions) {
4691 if (!EmitSuggestions) {
4695 for (
const auto &G : WarningGadgets) {
4696 G->handleUnsafeOperation(Handler,
false,
4702 assert(FixableGadgets.empty() &&
4703 "Fixable gadgets found but suggestions not requested!");
4709 if (!WarningGadgets.empty()) {
4713 for (
const auto &G : FixableGadgets) {
4714 for (
const auto *DRE : G->getClaimedVarUseSites()) {
4715 Tracker.claimUse(DRE);
4731 if (WarningGadgets.empty())
4739 std::map<const VarDecl *, FixItList> FixItsForVariableGroup;
4742 for (
auto it = FixablesForAllVars.
byVar.cbegin();
4743 it != FixablesForAllVars.
byVar.cend();) {
4748 (
"failed to produce fixit for '" +
4749 it->first->getNameAsString() +
4750 "' : neither local nor a parameter"));
4752 it = FixablesForAllVars.
byVar.erase(it);
4753 }
else if (it->first->getType().getCanonicalType()->isReferenceType()) {
4756 (
"failed to produce fixit for '" +
4757 it->first->getNameAsString() +
4758 "' : has a reference type"));
4760 it = FixablesForAllVars.
byVar.erase(it);
4761 }
else if (Tracker.hasUnclaimedUses(it->first)) {
4762 it = FixablesForAllVars.
byVar.erase(it);
4763 }
else if (it->first->isInitCapture()) {
4766 (
"failed to produce fixit for '" +
4767 it->first->getNameAsString() +
4768 "' : init capture"));
4770 it = FixablesForAllVars.
byVar.erase(it);
4777 for (
const auto &it : UnsafeOps.
byVar) {
4778 const VarDecl *
const UnsafeVD = it.first;
4779 auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
4780 if (UnclaimedDREs.empty())
4784 std::string UnclaimedUseTrace =
4789 (
"failed to produce fixit for '" + UnfixedVDName +
4790 "' : has an unclaimed use\nThe unclaimed DRE trace: " +
4791 UnclaimedUseTrace));
4798 llvm::DenseMap<const VarDecl *, llvm::SetVector<const VarDecl *>>;
4799 DepMapTy DependenciesMap{};
4800 DepMapTy PtrAssignmentGraph{};
4802 for (
const auto &it : FixablesForAllVars.
byVar) {
4803 for (
const FixableGadget *fixable : it.second) {
4804 std::optional<std::pair<const VarDecl *, const VarDecl *>> ImplPair =
4805 fixable->getStrategyImplications();
4807 std::pair<const VarDecl *, const VarDecl *> Impl = std::move(*ImplPair);
4808 PtrAssignmentGraph[Impl.first].insert(Impl.second);
4830 std::set<const VarDecl *> VisitedVarsDirected{};
4831 for (
const auto &[Var, ignore] : UnsafeOps.
byVar) {
4832 if (VisitedVarsDirected.find(Var) == VisitedVarsDirected.end()) {
4834 std::queue<const VarDecl *> QueueDirected{};
4835 QueueDirected.push(Var);
4836 while (!QueueDirected.empty()) {
4837 const VarDecl *CurrentVar = QueueDirected.front();
4838 QueueDirected.pop();
4839 VisitedVarsDirected.insert(CurrentVar);
4840 auto AdjacentNodes = PtrAssignmentGraph[CurrentVar];
4841 for (
const VarDecl *Adj : AdjacentNodes) {
4842 if (VisitedVarsDirected.find(Adj) == VisitedVarsDirected.end()) {
4843 QueueDirected.push(Adj);
4845 DependenciesMap[Var].insert(Adj);
4846 DependenciesMap[Adj].insert(Var);
4853 std::vector<VarGrpTy> Groups;
4857 std::map<const VarDecl *, unsigned> VarGrpMap;
4859 llvm::SetVector<const VarDecl *>
4864 std::set<const VarDecl *> VisitedVars{};
4865 for (
const auto &[Var, ignore] : UnsafeOps.
byVar) {
4866 if (VisitedVars.find(Var) == VisitedVars.end()) {
4867 VarGrpTy &VarGroup = Groups.emplace_back();
4868 std::queue<const VarDecl *> Queue{};
4871 while (!Queue.empty()) {
4872 const VarDecl *CurrentVar = Queue.front();
4874 VisitedVars.insert(CurrentVar);
4875 VarGroup.push_back(CurrentVar);
4876 auto AdjacentNodes = DependenciesMap[CurrentVar];
4877 for (
const VarDecl *Adj : AdjacentNodes) {
4878 if (VisitedVars.find(Adj) == VisitedVars.end()) {
4884 bool HasParm =
false;
4885 unsigned GrpIdx = Groups.size() - 1;
4887 for (
const VarDecl *
V : VarGroup) {
4888 VarGrpMap[
V] = GrpIdx;
4893 GrpsUnionForParms.insert_range(VarGroup);
4915 for (
auto I = FixablesForAllVars.
byVar.begin();
4916 I != FixablesForAllVars.
byVar.end();) {
4918 if (!VisitedVars.count((*I).first)) {
4920 I = FixablesForAllVars.
byVar.erase(I);
4928 VisitedVars, [&FixablesForAllVars](
const VarDecl *
V) {
4930 return FixablesForAllVars.
byVar.count(
V);
4937 FixItsForVariableGroup =
4939 Tracker, Handler, VarGrpMgr);
4941 for (
const auto &G : UnsafeOps.
noVar) {
4942 G->handleUnsafeOperation(Handler,
false,
4946 for (
const auto &[VD, WarningGadgets] : UnsafeOps.
byVar) {
4947 auto FixItsIt = FixItsForVariableGroup.find(VD);
4949 FixItsIt != FixItsForVariableGroup.end()
4950 ? std::move(FixItsIt->second)
4953 for (
const auto &G : WarningGadgets) {
4954 G->handleUnsafeOperation(Handler,
true,
4962 bool EmitSuggestions) {
4968 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4976 if (
const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4977 if (MD->getParent()->isLambda() && MD->getParent()->isLocalClass())
4982 if (FReDecl->isExternC()) {
4985 EmitSuggestions =
false;
4995 assert(!Stmts.empty());
4997 FixableGadgetList FixableGadgets;
4998 WarningGadgetList WarningGadgets;
4999 DeclUseTracker Tracker;
5000 for (
const Stmt *S : Stmts) {
5002 WarningGadgets, Tracker);
5004 applyGadgets(D, std::move(FixableGadgets), std::move(WarningGadgets),
5005 std::move(Tracker), Handler, EmitSuggestions);
5009 std::set<const Expr *> &UnsafePointers) {
5013 void handleUnsafeOperation(
const Stmt *,
bool,
ASTContext &)
override {}
5014 void handleUnsafeLibcCall(
const CallExpr *,
unsigned,
5016 const Expr *UnsafeArg =
nullptr)
override {}
5017 void handleUnsafeOperationInContainer(
const Stmt *,
bool,
5019 void handleUnsafeOperationInStringView(
const Stmt *,
bool,
5021 void handleUnsafeVariableGroup(
const VarDecl *,
5025 void handleUnsafeUniquePtrArrayAccess(
const DynTypedNode &Node,
5026 bool IsRelatedToDecl,
5034 bool ignoreUnsafeBufferInLibcCall(
const SourceLocation &)
const override {
5038 ignoreUnsafeBufferInFormatAttrCall(
const SourceLocation &)
const override {
5041 bool ignoreUnsafeBufferInStaticSizedArray(
5045 std::string getUnsafeBufferUsageAttributeTextAt(
5056 WarningGadgetList WarningGadgets;
5057 bool Matched =
false;
5065#define WARNING_GADGET(name) \
5066 if (name##Gadget::matches(S, Ctx, Result)) \
5067 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5068#define WARNING_OPTIONAL_GADGET(name) \
5069 if (name##Gadget::matches(S, Ctx, &Handler, Result)) \
5070 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5071#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
5073 for (
auto &WG : WarningGadgets)
5074 for (
auto *E : WG->getUnsafePtrs()) {
5075 UnsafePointers.insert(E);
Defines the clang::ASTContext interface.
static bool ignoreUnsafeLibcCall(const ASTContext &Ctx, const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static void findStmtsInUnspecifiedLvalueContext(const Stmt *S, const llvm::function_ref< void(const Expr *)> OnResult)
static std::string getUserFillPlaceHolder(StringRef HintTextToUser="placeholder")
static FixItList fixVariableWithSpan(const VarDecl *VD, const DeclUseTracker &Tracker, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static std::optional< FixItList > fixUPCAddressofArraySubscriptWithSpan(const UnaryOperator *Node)
static bool ignoreUnsafeBufferInContainer(const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static WarningGadgetSets groupWarningGadgetsByVar(const WarningGadgetList &AllUnsafeOperations)
static bool hasArrayType(const Expr &E)
static StringRef getEndOfLine()
static bool notInSafeBufferOptOut(const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static std::optional< FixItList > FixVarInitializerWithSpan(const Expr *Init, ASTContext &Ctx, const StringRef UserFillPlaceHolder)
static std::optional< SourceLocation > getEndCharLoc(const NodeTy *Node, const SourceManager &SM, const LangOptions &LangOpts)
static FixItList fixVariableWithArray(const VarDecl *VD, const DeclUseTracker &Tracker, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static bool areEqualIntegralBinaryOperators(const BinaryOperator *E1, const Expr *E2_LHS, BinaryOperatorKind BOP, const Expr *E2_RHS, ASTContext &Ctx)
static bool hasPointerType(const Expr &E)
static std::string getSpanTypeText(StringRef EltTyText, std::optional< Qualifiers > Quals=std::nullopt)
static SourceRange getSourceRangeToTokenEnd(const Decl *D, const SourceManager &SM, const LangOptions &LangOpts)
static FixItList fixLocalVarDeclWithSpan(const VarDecl *D, ASTContext &Ctx, const StringRef UserFillPlaceHolder, UnsafeBufferUsageHandler &Handler)
static bool isSafeArraySubscript(const ArraySubscriptExpr &Node, const ASTContext &Ctx, const bool IgnoreStaticSizedArrays)
static std::optional< FixItList > createDataFixit(const ASTContext &Ctx, const DeclRefExpr *DRE)
static FixItList createFunctionOverloadsForParms(std::map< const VarDecl *, FixItList > &FixItsForVariable, const VariableGroupsManager &VarGrpMgr, const FunctionDecl *FD, const FixitStrategy &S, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static bool isNullTermPointer(const Expr *Ptr, ASTContext &Ctx)
static bool ignoreUnsafeFormatAttrCall(const ASTContext &Ctx, const Stmt &Node, const UnsafeBufferUsageHandler *Handler)
static bool isSafeStringViewTwoParamConstruct(const CXXConstructExpr &Node, ASTContext &Ctx)
static FixItList fixVarDeclWithArray(const VarDecl *D, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixItList fixVariable(const VarDecl *VD, FixitStrategy::Kind K, const Decl *D, const DeclUseTracker &Tracker, ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixItList fixParamWithSpan(const ParmVarDecl *PVD, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static FixitStrategy getNaiveStrategy(llvm::iterator_range< VarDeclIterTy > UnsafeVars)
static std::optional< std::string > createSpanTypeForVarDecl(const VarDecl *VD, const ASTContext &Ctx)
static bool hasConflictingOverload(const FunctionDecl *FD)
static bool isSafeTwoParamContainerConstruct(const CallOrConstructExpr &Node, ASTContext &Ctx, bool AllowDuckTypedContainers=false)
static void findStmtsInUnspecifiedPointerContext(const Stmt *S, llvm::function_ref< void(const Stmt *)> InnerMatcher)
static bool isNonNegativeIntegerExpr(const Expr *Expr, const VarDecl *VD, const ASTContext &Ctx)
static bool overlapWithMacro(const FixItList &FixIts)
static void forEachDescendantStmt(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, FastMatcher &Matcher)
static bool isPtrBufferSafe(const Expr *Ptr, const Expr *Size, ASTContext &Ctx, bool AllowDuckTypedContainers=false)
static bool hasUnsupportedSpecifiers(const VarDecl *VD, const SourceManager &SM)
static const Expr * tryConstantFoldConditionalExpr(const Expr *E, const ASTContext &Ctx)
#define DEBUG_NOTE_DECL_FAIL(D, Msg)
static void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets, WarningGadgetList WarningGadgets, DeclUseTracker Tracker, UnsafeBufferUsageHandler &Handler, bool EmitSuggestions)
static bool isSafePointerArithmetic(const Expr *Ptr, const Expr *OffsetExpr, BinaryOperatorKind Opcode, const ASTContext &Ctx)
static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx)
static void findGadgets(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, bool EmitSuggestions, FixableGadgetList &FixableGadgets, WarningGadgetList &WarningGadgets, DeclUseTracker &Tracker)
static const Expr * getSubExprInSizeOfExpr(const Expr &E)
static std::map< const VarDecl *, FixItList > getFixIts(FixableGadgetSets &FixablesForAllVars, const FixitStrategy &S, ASTContext &Ctx, const Decl *D, const DeclUseTracker &Tracker, UnsafeBufferUsageHandler &Handler, const VariableGroupsManager &VarGrpMgr)
static const Expr * getSubExprInAddressOfExpr(const Expr &E)
static void forEachDescendantEvaluatedStmt(const Stmt *S, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler, FastMatcher &Matcher)
static void findStmtsInUnspecifiedUntypedContext(const Stmt *S, llvm::function_ref< void(const Stmt *)> InnerMatcher)
static std::optional< FixItList > createOverloadsForFixedParams(const FixitStrategy &S, const FunctionDecl *FD, const ASTContext &Ctx, UnsafeBufferUsageHandler &Handler)
static void eraseVarsForUnfixableGroupMates(std::map< const VarDecl *, FixItList > &FixItsForVariable, const VariableGroupsManager &VarGrpMgr)
static FixableGadgetSets groupFixablesByVar(FixableGadgetList &&AllFixableOperations)
static bool isParameterOf(const VarDecl *VD, const Decl *D)
#define SIZED_CONTAINER_OR_VIEW_LIST
static void populateStmtsForFindingGadgets(SmallVector< const Stmt * > &Stmts, const Decl *D)
static std::optional< StringRef > getFunNameText(const FunctionDecl *FD, const SourceManager &SM, const LangOptions &LangOpts)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Preprocessor interface.
MatchFinder::MatchResult MatchResult
Defines the clang::SourceLocation class and associated facilities.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
virtual std::optional< FixItList > getFixits(const FixitStrategy &s) const final
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
DerefSimplePtrArithFixableGadget(const MatchResult &Result)
SourceLocation getSourceLoc() const override
virtual DeclUseList getClaimedVarUseSites() const final
FixableGadgetMatcher(FixableGadgetList &FixableGadgets, DeclUseTracker &Tracker)
bool matches(const DynTypedNode &DynNode, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler) override
Represents the length modifier in a format string in scanf/printf.
bool TraverseCXXTypeidExpr(CXXTypeidExpr *Node) override
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc Node, bool TraverseQualifier) override
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc Node, bool TraverseQualifier) override
bool TraverseGenericSelectionExpr(GenericSelectionExpr *Node) override
MatchDescendantVisitor(ASTContext &Context, FastMatcher &Matcher, bool FindAll, bool IgnoreUnevaluatedContext, const UnsafeBufferUsageHandler &NewHandler)
bool TraverseDecl(Decl *Node) override
bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node) override
bool findMatch(const DynTypedNode &DynNode)
bool TraverseCXXDefaultInitExpr(CXXDefaultInitExpr *Node) override
bool TraverseCXXNoexceptExpr(CXXNoexceptExpr *Node) override
bool TraverseStmt(Stmt *Node) override
virtual std::optional< FixItList > getFixits(const FixitStrategy &S) const override
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
SourceLocation getSourceLoc() const override
virtual DeclUseList getClaimedVarUseSites() const override
UPCPreIncrementGadget(const MatchResult &Result)
static bool classof(const Gadget *G)
static bool classof(const Gadget *G)
UUCAddAssignGadget(const MatchResult &Result)
virtual std::optional< FixItList > getFixits(const FixitStrategy &S) const override
static bool matches(const Stmt *S, llvm::SmallVectorImpl< MatchResult > &Results)
virtual DeclUseList getClaimedVarUseSites() const override
SourceLocation getSourceLoc() const override
VariableGroupsManagerImpl(const std::vector< VarGrpTy > &Groups, const std::map< const VarDecl *, unsigned > &VarGrpMap, const llvm::SetVector< const VarDecl * > &GrpsUnionForParms)
VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm) const override
Returns the set of variables (including Var) that need to be fixed together in one step.
VarGrpRef getGroupOfParms() const override
Returns the non-empty group of variables that include parameters of the analyzing function,...
bool matches(const DynTypedNode &DynNode, ASTContext &Ctx, const UnsafeBufferUsageHandler &Handler) override
WarningGadgetMatcher(WarningGadgetList &WarningGadgets)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
const ConstantArrayType * getAsConstantArrayType(QualType T) const
DynTypedNodeList getParents(const NodeT &Node)
Forwards to get node parents from the ParentMapContext.
QualType getFILEType() const
Retrieve the C FILE type.
const LangOptions & getLangOpts() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Attr - This represents one attribute.
A builtin binary operation expression such as "x + y" or "x <= y".
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Represents a call to a C++ constructor.
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Expr * getInit() const
Get the initializer.
A use of a default initializer in a constructor or in aggregate initialization.
Expr * getExpr()
Get the initialization expression that will be used.
Represents a static or instance method of a struct/union/class.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Represents a C++ struct/union/class.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
static const char * getCastKindName(CastKind CK)
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getEnd() const
bool isOne() const
Test whether the quantity equals one.
Represents a class template specialization, which refers to a class template with a given set of temp...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool isSingleResult() const
DeclContext * getParent()
getParent - Returns the containing DeclContext.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
A reference to a declared variable, function, enum, etc.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
const Decl * getSingleDecl() const
Decl - This represents one declaration (or definition), e.g.
bool isInStdNamespace() const
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
SourceLocation getTypeSpecEndLoc() const
SourceLocation getBeginLoc() const LLVM_READONLY
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
const DynTypedNode * begin() const
A dynamically typed AST node container.
const T * get() const
Retrieve the stored node as type T.
static DynTypedNode create(const T &Node)
Creates a DynTypedNode from Node.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
bool ShouldVisitTemplateInstantiations
bool ShouldVisitImplicitCode
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
NullPointerConstantValueDependence
Enumeration used to describe how isNullPointerConstant() should cope with value-dependent expressions...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Kind lookup(const VarDecl *VD) const
void set(const VarDecl *VD, Kind K)
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
ArrayRef< ParmVarDecl * > parameters() const
param_iterator param_begin()
bool isVariadic() const
Whether this function is variadic.
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
bool isGlobal() const
Determines whether this is a global function.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
DeclarationNameInfo getNameInfo() const
Represents a C11 generic selection.
Expr * getResultExpr()
Return the result expression of this controlling expression.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
bool isValid() const
Is this parameter index valid?
unsigned getASTIndex() const
Get the parameter index as it would normally be encoded at the AST level of representation: zero-orig...
Represents a parameter to a function.
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
PointerType - C99 6.7.5.1 - Pointer Declarators.
A (possibly-)qualified type.
bool hasQualifiers() const
Determine whether this type has any qualifiers.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
QualType getCanonicalType() const
bool isConstQualified() const
Determine whether this type is const-qualified.
std::string getAsString() const
Represents a struct/union/class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Stmt - This represents one statement.
StmtClass getStmtClass() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
const char * getStmtClassName() const
SourceLocation getBeginLoc() const LLVM_READONLY
Exposes information about the current target.
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Represents a template argument.
QualType getAsType() const
Retrieve the type for a type template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of the type hierarchy.
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
bool isPointerType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
bool isAnyPointerType() const
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
static bool isIncrementOp(Opcode Op)
SourceLocation getBeginLoc() const LLVM_READONLY
static bool isDecrementOp(Opcode Op)
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
The interface that lets the caller handle unsafe buffer usage analysis results by overriding this cla...
virtual void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node, bool IsRelatedToDecl, ASTContext &Ctx)=0
void addDebugNoteForVar(const VarDecl *VD, SourceLocation Loc, std::string Text)
virtual bool ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &Loc) const =0
virtual std::string getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc, StringRef WSSuffix="") const =0
virtual bool isSafeBufferOptOut(const SourceLocation &Loc) const =0
virtual bool ignoreUnsafeBufferInContainer(const SourceLocation &Loc) const =0
virtual void handleUnsafeOperation(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
Invoked when an unsafe operation over raw pointers is found.
virtual void handleUnsafeOperationInStringView(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
virtual void handleUnsafeLibcCall(const CallExpr *Call, unsigned PrintfInfo, UnsafeLibcFunctionFamily Family, ASTContext &Ctx, const Expr *UnsafeArg=nullptr)=0
Invoked when a call to an unsafe libc function is found.
virtual void handleUnsafeVariableGroup(const VarDecl *Variable, const VariableGroupsManager &VarGrpMgr, FixItList &&Fixes, const Decl *D, const FixitStrategy &VarTargetTypes)=0
Invoked when a fix is suggested against a variable.
virtual void handleUnsafeOperationInContainer(const Stmt *Operation, bool IsRelatedToDecl, ASTContext &Ctx)=0
Invoked when an unsafe operation with a std container is found.
virtual bool ignoreUnsafeBufferInStaticSizedArray(const SourceLocation &Loc) const =0
virtual bool ignoreUnsafeBufferInLibcCall(const SourceLocation &Loc) const =0
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isInlineSpecified() const
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
const Expr * getInit() const
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
VariableGroupsManager()=default
virtual VarGrpRef getGroupOfVar(const VarDecl *Var, bool *HasParm=nullptr) const =0
Returns the set of variables (including Var) that need to be fixed together in one step.
virtual VarGrpRef getGroupOfParms() const =0
Returns the non-empty group of variables that include parameters of the analyzing function,...
unsigned getArgIndex() const
bool hasDataArgument() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
const OptionalAmount & getPrecision() const
const PrintfConversionSpecifier & getConversionSpecifier() const
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
void matchEachArgumentWithParamType(const CallExpr &Node, llvm::function_ref< void(QualType, const Expr *)> OnParamAndArg)
bool anyConflict(const llvm::SmallVectorImpl< FixItHint > &FixIts, const SourceManager &SM)
bool matches(const til::SExpr *E1, const til::SExpr *E2)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
bool matchUnsafePointers(const DynTypedNode &N, ASTContext &Ctx, std::set< const Expr * > &UnsafePointers)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void checkUnsafeBufferUsage(const Decl *D, UnsafeBufferUsageHandler &Handler, bool EmitSuggestions)
SourceLocation getVarDeclIdentifierLoc(const DeclaratorDecl *VD)
static bool classof(const OMPClause *T)
std::vector< const VarDecl * > VarGrpTy
std::optional< StringRef > getExprText(const Expr *E, const SourceManager &SM, const LangOptions &LangOpts)
@ Result
The result type of a method or function.
const FunctionProtoType * T
std::optional< std::string > getPointeeTypeText(const DeclaratorDecl *VD, const SourceManager &SM, const LangOptions &LangOpts, std::optional< Qualifiers > *QualifiersToAppend)
std::optional< StringRef > getRangeText(SourceRange SR, const SourceManager &SM, const LangOptions &LangOpts)
std::optional< StringRef > getVarDeclIdentifierText(const DeclaratorDecl *VD, const SourceManager &SM, const LangOptions &LangOpts)
UnsafeLibcFunctionFamily
The family of an unsafe libc function.
std::optional< SourceLocation > getPastLoc(const NodeTy *Node, const SourceManager &SM, const LangOptions &LangOpts)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
@ Decrement
This is a postfix decrement operator, 'operator--(int)'.
@ Increment
This is a postfix increment operator, 'operator++(int)'.
U cast(CodeGen::Address addr)
ArrayRef< const VarDecl * > VarGrpRef
static StringRef matchLibcNameOrBuiltinChk(StringRef Name)
static bool hasUnsafePrintfStringArg(const CallExpr &Node, ASTContext &Ctx, MatchResult &Result, llvm::StringRef Tag)
static bool isPredefinedUnsafeLibcFunc(const FunctionDecl &Node)
static UnsafeLibcFunctionFamily getUnsafeLibcFunctionFamily(const FunctionDecl &Node)
static bool hasUnsafeSnprintfBuffer(const CallExpr &Node, ASTContext &Ctx)
static bool isUnsafeVaListPrintfFunc(const FunctionDecl &Node)
static bool isUnsafeSprintfFunc(const FunctionDecl &Node)
static bool hasUnsafeFormatOrSArg(ASTContext &Ctx, const CallExpr *Call, const Expr *&UnsafeArg, const unsigned FmtIdx, std::optional< const unsigned > FmtArgIdx=std::nullopt, bool isKprintf=false)
static std::optional< UnsafeLibcFunctionFamily > getPredefinedUnsafeLibcFuncFamily(const FunctionDecl &Node)
static StringRef matchLibcName(StringRef Name)
static bool isUnsafeMemset(const CallExpr &Node, ASTContext &Ctx)
static StringRef matchName(StringRef FunName, bool isBuiltin)
static bool isInLibcScope(const FunctionDecl &FD)
static bool isLibcFunction(const FunctionDecl &FD)
static bool isNormalPrintfFunc(const FunctionDecl &Node)
bool operator()(const NodeTy *N1, const NodeTy *N2) const
std::map< const VarDecl *, std::set< const FixableGadget * >, CompareNode< VarDecl > > byVar
std::map< const VarDecl *, std::set< const WarningGadget * >, CompareNode< VarDecl > > byVar
llvm::SmallVector< const WarningGadget *, 16 > noVar
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
const BoundNodes Nodes
Contains the nodes bound on the current match.