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 const Expr *
Operand = CE->getSubExpr();
2409 if (
auto *
Paren = dyn_cast<ParenExpr>(Operand))
2411 auto *MCE = dyn_cast<CXXMemberCallExpr>(Operand);
2412 if (!MCE || !isDataFunction(MCE))
2414 if (!isUnsafePointerCast(CE, Ctx))
2416 Result.addNode(OpTag, DynTypedNode::create(*CE));
2420 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2421 bool IsRelatedToDecl,
2422 ASTContext &Ctx)
const override {
2425 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2427 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2430 static bool isDataFunction(
const CXXMemberCallExpr *call) {
2437 if (method->getNameAsString() ==
"data" &&
2438 method->getParent()->isInStdNamespace() &&
2439 llvm::is_contained({SIZED_CONTAINER_OR_VIEW_LIST},
2440 method->getParent()->getName()))
2447 static bool isUnsafePointerCast(
const ExplicitCastExpr *CE,
2448 const ASTContext &Ctx) {
2449 QualType DestType = CE->
getType();
2472 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2475class UnsafeLibcFunctionCallGadget :
public WarningGadget {
2476 const CallExpr *
const Call;
2477 const Expr *UnsafeArg =
nullptr;
2478 constexpr static const char *
const Tag =
"UnsafeLibcFunctionCall";
2480 constexpr static const char *
const UnsafeSprintfTag =
2481 "UnsafeLibcFunctionCall_sprintf";
2482 constexpr static const char *
const UnsafeSizedByTag =
2483 "UnsafeLibcFunctionCall_sized_by";
2484 constexpr static const char *
const UnsafeStringTag =
2485 "UnsafeLibcFunctionCall_string";
2486 constexpr static const char *
const UnsafeVaListTag =
2487 "UnsafeLibcFunctionCall_va_list";
2501 } WarnedFunKind = OTHERS;
2505 : WarningGadget(
Kind::UnsafeLibcFunctionCall),
2506 Call(
Result.getNodeAs<CallExpr>(Tag)) {
2507 if (
Result.getNodeAs<Decl>(UnsafeSprintfTag))
2508 WarnedFunKind = SPRINTF;
2509 else if (
auto *E =
Result.getNodeAs<Expr>(UnsafeStringTag)) {
2510 WarnedFunKind = STRING;
2512 }
else if (
Result.getNodeAs<CallExpr>(UnsafeSizedByTag)) {
2513 WarnedFunKind = SIZED_BY;
2514 UnsafeArg = Call->getArg(0);
2515 }
else if (
Result.getNodeAs<Decl>(UnsafeVaListTag))
2516 WarnedFunKind = VA_LIST;
2519 Family = WarnedFunKind != OTHERS
2520 ? UnsafeLibcFunctionFamily::Printf
2522 *Call->getDirectCallee());
2525 static bool matches(
const Stmt *S, ASTContext &Ctx,
2526 const UnsafeBufferUsageHandler *Handler,
2528 const auto *CE = dyn_cast<CallExpr>(S);
2531 const auto *FD = CE->getDirectCallee();
2545 const bool isSingleStringLiteralArg =
2546 CE->getNumArgs() == 1 &&
2548 if (!isSingleStringLiteralArg) {
2551 Result.addNode(Tag, DynTypedNode::create(*CE));
2555 Result.addNode(Tag, DynTypedNode::create(*CE));
2559 Result.addNode(Tag, DynTypedNode::create(*CE));
2560 Result.addNode(UnsafeVaListTag, DynTypedNode::create(*FD));
2564 Result.addNode(Tag, DynTypedNode::create(*CE));
2565 Result.addNode(UnsafeSprintfTag, DynTypedNode::create(*FD));
2571 Result.addNode(Tag, DynTypedNode::create(*CE));
2572 Result.addNode(UnsafeSizedByTag, DynTypedNode::create(*CE));
2577 Result.addNode(Tag, DynTypedNode::create(*CE));
2584 const Stmt *getBaseStmt()
const {
return Call; }
2586 SourceLocation getSourceLoc()
const override {
return Call->getBeginLoc(); }
2588 void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
2589 bool IsRelatedToDecl,
2590 ASTContext &Ctx)
const override {
2594 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2596 SmallVector<const Expr *, 1> getUnsafePtrs()
const override {
return {}; }
2599class UnsafeFormatAttributedFunctionCallGadget :
public WarningGadget {
2600 const CallExpr *
const Call;
2601 const Expr *UnsafeArg =
nullptr;
2602 constexpr static const char *
const Tag =
"UnsafeFormatAttributedFunctionCall";
2603 constexpr static const char *
const UnsafeStringTag =
2604 "UnsafeFormatAttributedFunctionCall_string";
2608 : WarningGadget(
Kind::UnsafeLibcFunctionCall),
2609 Call(
Result.getNodeAs<CallExpr>(Tag)),
2610 UnsafeArg(
Result.getNodeAs<Expr>(UnsafeStringTag)) {}
2612 static bool matches(
const Stmt *S, ASTContext &Ctx,
2613 const UnsafeBufferUsageHandler *Handler,
2615 auto *CE = dyn_cast<CallExpr>(S);
2616 if (!CE || !CE->getDirectCallee())
2618 const FunctionDecl *FD = CE->getDirectCallee();
2624 const FormatAttr *Attr =
nullptr;
2625 bool IsPrintf =
false;
2626 bool AnyAttr = llvm::any_of(
2628 [&Attr, &IsPrintf](
const FormatAttr *FA) ->
bool {
2629 if (const auto *II = FA->getType()) {
2630 if (II->getName() ==
"printf" || II->getName() ==
"scanf") {
2632 IsPrintf = II->getName() ==
"printf";
2638 const Expr *UnsafeArg;
2648 unsigned FmtIdx = Attr->getFormatIdx() - 1;
2649 std::optional<unsigned> FmtArgIdx = Attr->getFirstArg() - 1;
2659 }
else if (CE->
getStmtClass() != Stmt::CallExprClass &&
2662 if (*FmtArgIdx >= CE->getNumArgs())
2669 FmtArgIdx = std::nullopt;
2671 if (AnyAttr && !IsPrintf && FmtArgIdx) {
2673 Result.addNode(Tag, DynTypedNode::create(*CE));
2678 Ctx, CE, UnsafeArg, FmtIdx, FmtArgIdx)) {
2679 Result.addNode(Tag, DynTypedNode::create(*CE));
2680 Result.addNode(UnsafeStringTag, DynTypedNode::create(*UnsafeArg));
2686 const Stmt *getBaseStmt()
const {
return Call; }
2691 bool IsRelatedToDecl,
2696 UnsafeLibcFunctionCallGadget::UnsafeKind::STRING |
2697 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2702 UnsafeLibcFunctionCallGadget::UnsafeKind::OTHERS |
2703 UnsafeLibcFunctionCallGadget::UnsafeKind::FORMAT_ATTR,
2707 DeclUseList getClaimedVarUseSites()
const override {
return {}; }
2715class ULCArraySubscriptGadget :
public FixableGadget {
2717 static constexpr const char *
const ULCArraySubscriptTag =
2718 "ArraySubscriptUnderULC";
2719 const ArraySubscriptExpr *Node;
2723 : FixableGadget(
Kind::ULCArraySubscript),
2724 Node(
Result.getNodeAs<ArraySubscriptExpr>(ULCArraySubscriptTag)) {
2725 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2728 static bool classof(
const Gadget *G) {
2729 return G->getKind() == Kind::ULCArraySubscript;
2732 static bool matches(
const Stmt *S,
2733 llvm::SmallVectorImpl<MatchResult> &Results) {
2734 size_t SizeBefore = Results.size();
2736 const auto *ASE = dyn_cast<ArraySubscriptExpr>(E);
2742 !isSupportedVariable(*DRE))
2745 R.addNode(ULCArraySubscriptTag, DynTypedNode::create(*ASE));
2746 Results.emplace_back(std::move(R));
2748 return SizeBefore != Results.size();
2751 virtual std::optional<FixItList>
2752 getFixits(
const FixitStrategy &S)
const override;
2753 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2755 virtual DeclUseList getClaimedVarUseSites()
const override {
2756 if (
const auto *DRE =
2757 dyn_cast<DeclRefExpr>(Node->getBase()->IgnoreImpCasts())) {
2767class UPCStandalonePointerGadget :
public FixableGadget {
2769 static constexpr const char *
const DeclRefExprTag =
"StandalonePointer";
2770 const DeclRefExpr *Node;
2774 : FixableGadget(
Kind::UPCStandalonePointer),
2775 Node(
Result.getNodeAs<DeclRefExpr>(DeclRefExprTag)) {
2776 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2779 static bool classof(
const Gadget *G) {
2780 return G->getKind() == Kind::UPCStandalonePointer;
2783 static bool matches(
const Stmt *S,
2784 llvm::SmallVectorImpl<MatchResult> &Results) {
2785 size_t SizeBefore = Results.size();
2787 auto *E = dyn_cast<Expr>(S);
2792 !isSupportedVariable(*DRE))
2795 R.addNode(DeclRefExprTag, DynTypedNode::create(*DRE));
2796 Results.emplace_back(std::move(R));
2798 return SizeBefore != Results.size();
2801 virtual std::optional<FixItList>
2802 getFixits(
const FixitStrategy &S)
const override;
2803 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2805 virtual DeclUseList getClaimedVarUseSites()
const override {
return {Node}; }
2808class PointerDereferenceGadget :
public FixableGadget {
2809 static constexpr const char *
const BaseDeclRefExprTag =
"BaseDRE";
2810 static constexpr const char *
const OperatorTag =
"op";
2812 const DeclRefExpr *BaseDeclRefExpr =
nullptr;
2813 const UnaryOperator *Op =
nullptr;
2817 : FixableGadget(
Kind::PointerDereference),
2818 BaseDeclRefExpr(
Result.getNodeAs<DeclRefExpr>(BaseDeclRefExprTag)),
2819 Op(
Result.getNodeAs<UnaryOperator>(OperatorTag)) {}
2821 static bool classof(
const Gadget *G) {
2822 return G->getKind() == Kind::PointerDereference;
2825 static bool matches(
const Stmt *S,
2826 llvm::SmallVectorImpl<MatchResult> &Results) {
2827 size_t SizeBefore = Results.size();
2829 const auto *UO = dyn_cast<UnaryOperator>(S);
2836 const auto *DRE = dyn_cast<DeclRefExpr>(CE);
2837 if (!DRE || !isSupportedVariable(*DRE))
2840 R.addNode(BaseDeclRefExprTag, DynTypedNode::create(*DRE));
2841 R.addNode(OperatorTag, DynTypedNode::create(*UO));
2842 Results.emplace_back(std::move(R));
2844 return SizeBefore != Results.size();
2847 DeclUseList getClaimedVarUseSites()
const override {
2848 return {BaseDeclRefExpr};
2851 virtual std::optional<FixItList>
2852 getFixits(
const FixitStrategy &S)
const override;
2853 SourceLocation getSourceLoc()
const override {
return Op->getBeginLoc(); }
2859class UPCAddressofArraySubscriptGadget :
public FixableGadget {
2861 static constexpr const char *
const UPCAddressofArraySubscriptTag =
2862 "AddressofArraySubscriptUnderUPC";
2863 const UnaryOperator *Node;
2867 : FixableGadget(
Kind::ULCArraySubscript),
2868 Node(
Result.getNodeAs<UnaryOperator>(UPCAddressofArraySubscriptTag)) {
2869 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2872 static bool classof(
const Gadget *G) {
2873 return G->getKind() == Kind::UPCAddressofArraySubscript;
2876 static bool matches(
const Stmt *S,
2877 llvm::SmallVectorImpl<MatchResult> &Results) {
2878 size_t SizeBefore = Results.size();
2880 auto *E = dyn_cast<Expr>(S);
2884 if (!UO || UO->
getOpcode() != UO_AddrOf)
2886 const auto *ASE = dyn_cast<ArraySubscriptExpr>(UO->
getSubExpr());
2891 if (!DRE || !isSupportedVariable(*DRE))
2894 R.addNode(UPCAddressofArraySubscriptTag, DynTypedNode::create(*UO));
2895 Results.emplace_back(std::move(R));
2897 return SizeBefore != Results.size();
2900 virtual std::optional<FixItList>
2901 getFixits(
const FixitStrategy &)
const override;
2902 SourceLocation getSourceLoc()
const override {
return Node->getBeginLoc(); }
2904 virtual DeclUseList getClaimedVarUseSites()
const override {
2917class DeclUseTracker {
2918 using UseSetTy = llvm::SmallPtrSet<const DeclRefExpr *, 16>;
2919 using DefMapTy = llvm::DenseMap<const VarDecl *, const DeclStmt *>;
2922 std::unique_ptr<UseSetTy> Uses{std::make_unique<UseSetTy>()};
2926 DeclUseTracker() =
default;
2927 DeclUseTracker(
const DeclUseTracker &) =
delete;
2928 DeclUseTracker &operator=(
const DeclUseTracker &) =
delete;
2929 DeclUseTracker(DeclUseTracker &&) =
default;
2930 DeclUseTracker &operator=(DeclUseTracker &&) =
default;
2933 void discoverUse(
const DeclRefExpr *DRE) { Uses->insert(DRE); }
2936 void claimUse(
const DeclRefExpr *DRE) {
2937 assert(Uses->count(DRE) &&
2938 "DRE not found or claimed by multiple matchers!");
2943 bool hasUnclaimedUses(
const VarDecl *VD)
const {
2945 return any_of(*Uses, [VD](
const DeclRefExpr *DRE) {
2950 UseSetTy getUnclaimedUses(
const VarDecl *VD)
const {
2952 for (
auto use : *Uses) {
2954 ReturnSet.insert(use);
2960 void discoverDecl(
const DeclStmt *DS) {
2961 for (
const Decl *D : DS->
decls()) {
2962 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
2973 const DeclStmt *lookupDecl(
const VarDecl *VD)
const {
2974 return Defs.lookup(VD);
2983 static constexpr const char *
const UPCPreIncrementTag =
2984 "PointerPreIncrementUnderUPC";
2989 : FixableGadget(Kind::UPCPreIncrement),
2991 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
2995 return G->getKind() == Kind::UPCPreIncrement;
3004 size_t SizeBefore = Results.size();
3006 auto *E = dyn_cast<Expr>(S);
3010 if (!UO || UO->
getOpcode() != UO_PreInc)
3012 const auto *DRE = dyn_cast<DeclRefExpr>(UO->
getSubExpr());
3013 if (!DRE || !isSupportedVariable(*DRE))
3017 Results.emplace_back(std::move(R));
3019 return SizeBefore != Results.size();
3022 virtual std::optional<FixItList>
3027 return {dyn_cast<DeclRefExpr>(Node->getSubExpr())};
3035 static constexpr const char *
const UUCAddAssignTag =
3036 "PointerAddAssignUnderUUC";
3037 static constexpr const char *
const OffsetTag =
"Offset";
3040 const Expr *Offset =
nullptr;
3044 : FixableGadget(Kind::UUCAddAssign),
3047 assert(Node !=
nullptr &&
"Expecting a non-null matching result");
3051 return G->getKind() == Kind::UUCAddAssign;
3056 size_t SizeBefore = Results.size();
3058 const auto *E = dyn_cast<Expr>(S);
3062 if (!BO || BO->
getOpcode() != BO_AddAssign)
3064 const auto *DRE = dyn_cast<DeclRefExpr>(BO->
getLHS());
3070 Results.emplace_back(std::move(R));
3072 return SizeBefore != Results.size();
3075 virtual std::optional<FixItList>
3080 return {dyn_cast<DeclRefExpr>(Node->getLHS())};
3087 static constexpr const char *
const BaseDeclRefExprTag =
"BaseDRE";
3088 static constexpr const char *
const DerefOpTag =
"DerefOp";
3089 static constexpr const char *
const AddOpTag =
"AddOp";
3090 static constexpr const char *
const OffsetTag =
"Offset";
3099 : FixableGadget(Kind::DerefSimplePtrArithFixable),
3107 auto IsPtr = [](
const Expr *E, MatchResult &R) {
3111 if (!DRE || !isSupportedVariable(*DRE))
3116 const auto IsPlusOverPtrAndInteger = [&IsPtr](
const Expr *E,
3118 const auto *BO = dyn_cast<BinaryOperator>(E);
3122 const auto *LHS = BO->
getLHS();
3123 const auto *RHS = BO->
getRHS();
3136 size_t SizeBefore = Results.size();
3137 const auto InnerMatcher = [&IsPlusOverPtrAndInteger,
3138 &Results](
const Expr *E) {
3139 const auto *UO = dyn_cast<UnaryOperator>(E);
3145 if (IsPlusOverPtrAndInteger(Operand, R)) {
3147 Results.emplace_back(std::move(R));
3151 return SizeBefore != Results.size();
3154 virtual std::optional<FixItList>
3157 return DerefOp->getBeginLoc();
3161 return {BaseDeclRefExpr};
3169 : WarningGadgets(WarningGadgets) {}
3178#define WARNING_GADGET(name) \
3179 if (name##Gadget::matches(S, Ctx, Result) && \
3180 notInSafeBufferOptOut(*S, &Handler)) { \
3181 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3184#define WARNING_OPTIONAL_GADGET(name) \
3185 if (name##Gadget::matches(S, Ctx, &Handler, Result) && \
3186 notInSafeBufferOptOut(*S, &Handler)) { \
3187 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result)); \
3190#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3195 WarningGadgetList &WarningGadgets;
3202 DeclUseTracker &Tracker)
3203 : FixableGadgets(FixableGadgets), Tracker(Tracker) {}
3207 bool matchFound =
false;
3214#define FIXABLE_GADGET(name) \
3215 if (name##Gadget::matches(S, Results)) { \
3216 for (const auto &R : Results) { \
3217 FixableGadgets.push_back(std::make_unique<name##Gadget>(R)); \
3218 matchFound = true; \
3222#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
3225 if (
auto *DRE = findDeclRefExpr(S); DRE) {
3226 Tracker.discoverUse(DRE);
3232 if (
auto *DS = findDeclStmt(S); DS) {
3233 Tracker.discoverDecl(DS);
3241 const auto *DRE = dyn_cast<DeclRefExpr>(S);
3249 const DeclStmt *findDeclStmt(
const Stmt *S) {
3250 const auto *DS = dyn_cast<DeclStmt>(S);
3255 FixableGadgetList &FixableGadgets;
3256 DeclUseTracker &Tracker;
3262 bool EmitSuggestions, FixableGadgetList &FixableGadgets,
3263 WarningGadgetList &WarningGadgets,
3264 DeclUseTracker &Tracker) {
3267 if (EmitSuggestions) {
3276 return N1->getBeginLoc().getRawEncoding() <
3277 N2->getBeginLoc().getRawEncoding();
3290 auto AddStmt = [&Stmts](
const Stmt *S) {
3294 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
3297 if (PD->hasDefaultArg() && !PD->hasUninstantiatedDefaultArg())
3298 AddStmt(PD->getDefaultArg());
3299 if (
const auto *CtorD = dyn_cast<CXXConstructorDecl>(FD))
3301 Stmts, llvm::map_range(CtorD->inits(),
3305 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
3307 }
else if (
const auto *FD = dyn_cast<FieldDecl>(D)) {
3308 AddStmt(FD->getInClassInitializer());
3313 std::map<const VarDecl *, std::set<const WarningGadget *>,
3327 for (
auto &G : AllUnsafeOperations) {
3328 DeclUseList ClaimedVarUseSites = G->getClaimedVarUseSites();
3330 bool AssociatedWithVarDecl =
false;
3331 for (
const DeclRefExpr *DRE : ClaimedVarUseSites) {
3332 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3333 result.
byVar[VD].insert(G.get());
3334 AssociatedWithVarDecl =
true;
3338 if (!AssociatedWithVarDecl) {
3339 result.
noVar.push_back(G.get());
3347 std::map<const VarDecl *, std::set<const FixableGadget *>,
3357 for (
auto &F : AllFixableOperations) {
3358 DeclUseList DREs = F->getClaimedVarUseSites();
3361 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3362 FixablesForUnsafeVars.
byVar[VD].insert(F.get());
3366 return FixablesForUnsafeVars;
3373 std::vector<const FixItHint *>
All;
3377 std::sort(
All.begin(),
All.end(),
3379 return SM.isBeforeInTranslationUnit(H1->RemoveRange.getBegin(),
3380 H2->RemoveRange.getBegin());
3388 Hint->RemoveRange.getBegin())) {
3400std::optional<FixItList>
3401PtrToPtrAssignmentGadget::getFixits(
const FixitStrategy &S)
const {
3404 switch (S.
lookup(LeftVD)) {
3408 return std::nullopt;
3410 return std::nullopt;
3413 return std::nullopt;
3415 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3417 return std::nullopt;
3421static inline std::optional<FixItList>
createDataFixit(
const ASTContext &Ctx,
3422 const DeclRefExpr *DRE);
3424std::optional<FixItList>
3425CArrayToPtrAssignmentGadget::getFixits(
const FixitStrategy &S)
const {
3444 if (S.
lookup(LeftVD) == FixitStrategy::Kind::Span) {
3445 if (S.
lookup(RightVD) == FixitStrategy::Kind::Wontfix) {
3448 }
else if (S.
lookup(LeftVD) == FixitStrategy::Kind::Wontfix) {
3449 if (S.
lookup(RightVD) == FixitStrategy::Kind::Array) {
3453 return std::nullopt;
3456std::optional<FixItList>
3457PointerInitGadget::getFixits(
const FixitStrategy &S)
const {
3458 const auto *LeftVD = PtrInitLHS;
3460 switch (S.
lookup(LeftVD)) {
3461 case FixitStrategy::Kind::Span:
3462 if (S.
lookup(RightVD) == FixitStrategy::Kind::Span)
3464 return std::nullopt;
3465 case FixitStrategy::Kind::Wontfix:
3466 return std::nullopt;
3467 case FixitStrategy::Kind::Iterator:
3468 case FixitStrategy::Kind::Array:
3469 return std::nullopt;
3470 case FixitStrategy::Kind::Vector:
3471 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3473 return std::nullopt;
3479 if (ConstVal->isNegative())
3486std::optional<FixItList>
3487ULCArraySubscriptGadget::getFixits(
const FixitStrategy &S)
const {
3488 if (
const auto *DRE =
3490 if (
const auto *VD = dyn_cast<VarDecl>(DRE->
getDecl())) {
3492 case FixitStrategy::Kind::Span: {
3496 const ASTContext &Ctx =
3499 return std::nullopt;
3503 case FixitStrategy::Kind::Array:
3505 case FixitStrategy::Kind::Wontfix:
3506 case FixitStrategy::Kind::Iterator:
3507 case FixitStrategy::Kind::Vector:
3508 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3511 return std::nullopt;
3514static std::optional<FixItList>
3517std::optional<FixItList>
3518UPCAddressofArraySubscriptGadget::getFixits(
const FixitStrategy &S)
const {
3519 auto DREs = getClaimedVarUseSites();
3523 case FixitStrategy::Kind::Span:
3525 case FixitStrategy::Kind::Wontfix:
3526 case FixitStrategy::Kind::Iterator:
3527 case FixitStrategy::Kind::Array:
3528 return std::nullopt;
3529 case FixitStrategy::Kind::Vector:
3530 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3532 return std::nullopt;
3537 static const char *
const EOL =
"\n";
3544 std::string s = std::string(
"<# ");
3545 s += HintTextToUser;
3551template <
typename NodeTy>
3552static std::optional<SourceLocation>
3555 if (
unsigned TkLen =
3562 return std::nullopt;
3575 bool AttrRangeOverlapping = llvm::any_of(VD->
attrs(), [&](
Attr *At) ->
bool {
3576 return !(SM.isBeforeInTranslationUnit(At->getRange().getEnd(),
3577 VD->getBeginLoc())) &&
3578 !(SM.isBeforeInTranslationUnit(VD->getEndLoc(),
3579 At->getRange().getBegin()));
3583 AttrRangeOverlapping;
3625 std::optional<Qualifiers> Quals = std::nullopt) {
3626 const char *
const SpanOpen =
"std::span<";
3629 return SpanOpen + EltTyText.str() +
' ' + Quals->getAsString() +
'>';
3630 return SpanOpen + EltTyText.str() +
'>';
3633std::optional<FixItList>
3635 const VarDecl *VD = dyn_cast<VarDecl>(BaseDeclRefExpr->getDecl());
3640 if (
auto ConstVal = Offset->getIntegerConstantExpr(Ctx))
3641 if (ConstVal->isNegative())
3642 return std::nullopt;
3663 const Expr *LHS = AddOp->getLHS(), *RHS = AddOp->getRHS();
3670 std::optional<SourceLocation> LHSLocation =
getPastLoc(LHS, SM, LangOpts);
3672 return std::nullopt;
3677 std::optional<SourceLocation> AddOpLocation =
3679 std::optional<SourceLocation> DerefOpLocation =
3682 if (!AddOpLocation || !DerefOpLocation)
3683 return std::nullopt;
3693 return std::nullopt;
3696std::optional<FixItList>
3697PointerDereferenceGadget::getFixits(
const FixitStrategy &S)
const {
3708 if (
auto LocPastOperand =
3715 case FixitStrategy::Kind::Iterator:
3716 case FixitStrategy::Kind::Array:
3717 return std::nullopt;
3718 case FixitStrategy::Kind::Vector:
3719 llvm_unreachable(
"FixitStrategy not implemented yet!");
3720 case FixitStrategy::Kind::Wontfix:
3721 llvm_unreachable(
"Invalid strategy!");
3724 return std::nullopt;
3731 std::optional<SourceLocation> EndOfOperand =
3737 return std::nullopt;
3742std::optional<FixItList>
3743UPCStandalonePointerGadget::getFixits(
const FixitStrategy &S)
const {
3746 case FixitStrategy::Kind::Array:
3747 case FixitStrategy::Kind::Span: {
3752 case FixitStrategy::Kind::Wontfix:
3753 case FixitStrategy::Kind::Iterator:
3754 return std::nullopt;
3755 case FixitStrategy::Kind::Vector:
3756 llvm_unreachable(
"unsupported strategies for FixableGadgets");
3759 return std::nullopt;
3764static std::optional<FixItList>
3771 const Expr *Idx = ArraySub->getIdx();
3774 std::stringstream SS;
3775 bool IdxIsLitZero =
false;
3778 if ((*ICE).isZero())
3779 IdxIsLitZero =
true;
3780 std::optional<StringRef> DreString =
getExprText(DRE, SM, LangOpts);
3782 return std::nullopt;
3786 SS << (*DreString).str() <<
".data()";
3788 std::optional<StringRef> IndexString =
getExprText(Idx, SM, LangOpts);
3790 return std::nullopt;
3792 SS <<
"&" << (*DreString).str() <<
".data()"
3793 <<
"[" << (*IndexString).str() <<
"]";
3799std::optional<FixItList>
3803 if (DREs.size() != 1)
3804 return std::nullopt;
3806 if (
const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3810 const Stmt *AddAssignNode = Node;
3811 StringRef varName = VD->
getName();
3815 return std::nullopt;
3819 (Offset->IgnoreParens()->getBeginLoc() == Offset->getBeginLoc());
3820 std::string SS = varName.str() +
" = " + varName.str() +
".subspan";
3824 std::optional<SourceLocation> AddAssignLocation =
getEndCharLoc(
3826 if (!AddAssignLocation)
3827 return std::nullopt;
3834 Offset->getEndLoc().getLocWithOffset(1),
")"));
3838 return std::nullopt;
3841std::optional<FixItList>
3845 if (DREs.size() != 1)
3846 return std::nullopt;
3848 if (
const VarDecl *VD = dyn_cast<VarDecl>(DREs.front()->getDecl())) {
3851 std::stringstream SS;
3852 StringRef varName = VD->
getName();
3856 SS <<
"(" << varName.data() <<
" = " << varName.data()
3857 <<
".subspan(1)).data()";
3858 std::optional<SourceLocation> PreIncLocation =
3860 if (!PreIncLocation)
3861 return std::nullopt;
3864 SourceRange(Node->getBeginLoc(), *PreIncLocation), SS.str()));
3868 return std::nullopt;
3886static std::optional<FixItList>
3888 const StringRef UserFillPlaceHolder) {
3896 if (
Init->isNullPointerConstant(
3901 NPC_ValueDependentIsNotNull)) {
3902 std::optional<SourceLocation> InitLocation =
3905 return std::nullopt;
3913 std::string ExtentText = UserFillPlaceHolder.data();
3914 StringRef One =
"1";
3919 if (
auto CxxNew = dyn_cast<CXXNewExpr>(
Init->IgnoreImpCasts())) {
3924 if (
const Expr *Ext = CxxNew->getArraySize().value_or(
nullptr)) {
3925 if (!Ext->HasSideEffects(Ctx)) {
3926 std::optional<StringRef> ExtentString =
getExprText(Ext, SM, LangOpts);
3928 return std::nullopt;
3929 ExtentText = *ExtentString;
3931 }
else if (!CxxNew->isArray())
3943 if (
auto AddrOfExpr = dyn_cast<UnaryOperator>(
Init->IgnoreImpCasts()))
3944 if (AddrOfExpr->getOpcode() == UnaryOperatorKind::UO_AddrOf &&
3945 isa_and_present<DeclRefExpr>(AddrOfExpr->getSubExpr()))
3952 std::optional<SourceLocation> LocPassInit =
getPastLoc(
Init, SM, LangOpts);
3955 return std::nullopt;
3957 StrBuffer.append(
", ");
3958 StrBuffer.append(ExtentText);
3959 StrBuffer.append(
"}");
3965#define DEBUG_NOTE_DECL_FAIL(D, Msg) \
3966 Handler.addDebugNoteForVar((D), (D)->getBeginLoc(), \
3967 "failed to produce fixit for declaration '" + \
3968 (D)->getNameAsString() + "'" + (Msg))
3970#define DEBUG_NOTE_DECL_FAIL(D, Msg)
3976static std::optional<std::string>
3980 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
3985 return std::nullopt;
3987 std::string SpanTyText =
"std::span<";
3989 SpanTyText.append(*PteTyText);
3991 if (PteTyQualifiers) {
3992 SpanTyText.append(
" ");
3993 SpanTyText.append(PteTyQualifiers->getAsString());
3995 SpanTyText.append(
">");
4014 const StringRef UserFillPlaceHolder,
4028 std::stringstream SS;
4033 std::optional<FixItList> InitFixIts =
4037 FixIts.insert(FixIts.end(), std::make_move_iterator(InitFixIts->begin()),
4038 std::make_move_iterator(InitFixIts->end()));
4045 if (!EndLocForReplacement.
isValid()) {
4095static std::optional<FixItList>
4101 return std::nullopt;
4106 std::vector<std::string> NewTysTexts(NumParms);
4107 std::vector<bool> ParmsMask(NumParms,
false);
4108 bool AtLeastOneParmToFix =
false;
4110 for (
unsigned i = 0; i < NumParms; i++) {
4117 return std::nullopt;
4119 std::optional<Qualifiers> PteTyQuals = std::nullopt;
4120 std::optional<std::string> PteTyText =
4125 return std::nullopt;
4129 ParmsMask[i] =
true;
4130 AtLeastOneParmToFix =
true;
4132 if (!AtLeastOneParmToFix)
4139 const auto NewOverloadSignatureCreator =
4140 [&SM, &LangOpts, &NewTysTexts,
4141 &ParmsMask](
const FunctionDecl *FD) -> std::optional<std::string> {
4142 std::stringstream SS;
4150 SS << Prefix->str();
4152 return std::nullopt;
4156 for (
unsigned i = 0; i < NumParms; i++) {
4164 SS << NewTysTexts[i];
4167 SS <<
' ' << II->getName().str();
4168 }
else if (
auto ParmTypeText =
4172 SS << ParmTypeText->str();
4174 return std::nullopt;
4175 if (i != NumParms - 1)
4184 const auto OldOverloadDefCreator =
4185 [&Handler, &SM, &LangOpts, &NewTysTexts,
4186 &ParmsMask](
const FunctionDecl *FD) -> std::optional<std::string> {
4187 std::stringstream SS;
4195 << FDPrefix->str() <<
"{";
4197 return std::nullopt;
4200 SS <<
"return " << FunQualName->str() <<
"(";
4202 return std::nullopt;
4206 for (
unsigned i = 0; i < NumParms; i++) {
4215 return std::nullopt;
4222 if (i != NumParms - 1)
4233 std::optional<SourceLocation> Loc =
getPastLoc(FReDecl, SM, LangOpts);
4237 if (FReDecl->isThisDeclarationADefinition()) {
4238 assert(FReDecl == FD &&
"inconsistent function definition");
4241 if (
auto OldOverloadDef = OldOverloadDefCreator(FReDecl))
4247 if (!FReDecl->hasAttr<UnsafeBufferUsageAttr>()) {
4250 FReDecl->getBeginLoc(),
" ")));
4253 if (
auto NewOverloadDecl = NewOverloadSignatureCreator(FReDecl))
4275 std::optional<Qualifiers> PteTyQualifiers = std::nullopt;
4291 std::stringstream SS;
4294 if (PteTyQualifiers)
4303 SS <<
' ' << PVDNameText->str();
4309 const DeclUseTracker &Tracker,
4312 const DeclStmt *DS = Tracker.lookupDecl(VD);
4315 " : variables declared this way not implemented yet");
4339 const QualType &ArrayEltT = CAT->getElementType();
4340 assert(!ArrayEltT.
isNull() &&
"Trying to fix a non-array type variable!");
4349 auto MaybeElemTypeTxt =
4352 if (!MaybeElemTypeTxt)
4354 const llvm::StringRef ElemTypeTxt = MaybeElemTypeTxt->trim();
4359 while (NextTok && !NextTok->is(tok::l_square) &&
4372 if (!MaybeArraySizeTxt)
4374 const llvm::StringRef ArraySizeTxt = MaybeArraySizeTxt->trim();
4375 if (ArraySizeTxt.empty()) {
4386 std::optional<StringRef> IdentText =
4395 llvm::raw_svector_ostream OS(Replacement);
4396 OS <<
"std::array<" << ElemTypeTxt <<
", " << ArraySizeTxt <<
"> "
4397 << IdentText->str();
4407 const DeclUseTracker &Tracker,
4410 const DeclStmt *DS = Tracker.lookupDecl(VD);
4411 assert(DS &&
"Fixing non-local variables not implemented yet!");
4430 const DeclUseTracker &Tracker,
ASTContext &Ctx,
4432 if (
const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4433 auto *FD = dyn_cast<clang::FunctionDecl>(PVD->getDeclContext());
4434 if (!FD || FD != D) {
4451 isa_and_nonnull<CXXTryStmt>(FD->
getBody()) ||
4461 if (
const auto *PVD = dyn_cast<ParmVarDecl>(VD))
4479 llvm_unreachable(
"FixitStrategy not implemented yet!");
4481 llvm_unreachable(
"Invalid strategy!");
4483 llvm_unreachable(
"Unknown strategy!");
4491 return llvm::any_of(FixIts, [](
const FixItHint &Hint) {
4493 if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
4510 std::map<const VarDecl *, FixItList> &FixItsForVariable,
4515 for (
const auto &[VD, Ignore] : FixItsForVariable) {
4517 if (llvm::any_of(Grp,
4518 [&FixItsForVariable](
const VarDecl *GrpMember) ->
bool {
4519 return !FixItsForVariable.count(GrpMember);
4524 ToErase.push_back(
Member);
4527 for (
auto *VarToErase : ToErase)
4528 FixItsForVariable.erase(VarToErase);
4539 std::map<const VarDecl *, FixItList> &FixItsForVariable ,
4543 FixItList FixItsSharedByParms{};
4545 std::optional<FixItList> OverloadFixes =
4548 if (OverloadFixes) {
4549 FixItsSharedByParms.append(*OverloadFixes);
4555 FixItsForVariable.erase(
Member);
4557 return FixItsSharedByParms;
4561static std::map<const VarDecl *, FixItList>
4570 std::map<const VarDecl *, FixItList> FixItsForVariable;
4575 for (
const auto &[VD, Fixables] : FixablesForAllVars.
byVar) {
4576 FixItsForVariable[VD] =
4580 if (FixItsForVariable[VD].empty()) {
4581 FixItsForVariable.erase(VD);
4584 for (
const auto &F : Fixables) {
4585 std::optional<FixItList> Fixits = F->getFixits(S);
4588 FixItsForVariable[VD].insert(FixItsForVariable[VD].end(),
4589 Fixits->begin(), Fixits->end());
4594 VD, F->getSourceLoc(),
4595 (
"gadget '" + F->getDebugName() +
"' refused to produce a fix")
4598 FixItsForVariable.erase(VD);
4617 FixItList FixItsSharedByParms{};
4619 if (
auto *FD = dyn_cast<FunctionDecl>(D))
4621 FixItsForVariable, VarGrpMgr, FD, S, Ctx, Handler);
4625 std::map<const VarDecl *, FixItList> FinalFixItsForVariable{
4628 for (
auto &[Var, Ignore] : FixItsForVariable) {
4629 bool AnyParm =
false;
4630 const auto VarGroupForVD = VarGrpMgr.
getGroupOfVar(Var, &AnyParm);
4632 for (
const VarDecl *GrpMate : VarGroupForVD) {
4635 if (FixItsForVariable.count(GrpMate))
4636 FinalFixItsForVariable[Var].append(FixItsForVariable[GrpMate]);
4640 assert(!FixItsSharedByParms.empty() &&
4641 "Should not try to fix a parameter that does not belong to a "
4643 FinalFixItsForVariable[Var].append(FixItsSharedByParms);
4650 for (
auto Iter = FinalFixItsForVariable.begin();
4651 Iter != FinalFixItsForVariable.end();)
4654 Iter = FinalFixItsForVariable.erase(Iter);
4657 return FinalFixItsForVariable;
4660template <
typename VarDeclIterTy>
4664 for (
const VarDecl *VD : UnsafeVars) {
4675 const std::vector<VarGrpTy> &Groups;
4676 const std::map<const VarDecl *, unsigned> &VarGrpMap;
4677 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms;
4681 const std::vector<VarGrpTy> &Groups,
4682 const std::map<const VarDecl *, unsigned> &VarGrpMap,
4683 const llvm::SetVector<const VarDecl *> &GrpsUnionForParms)
4684 : Groups(Groups), VarGrpMap(VarGrpMap),
4685 GrpsUnionForParms(GrpsUnionForParms) {}
4688 if (GrpsUnionForParms.contains(Var)) {
4691 return GrpsUnionForParms.getArrayRef();
4696 auto It = VarGrpMap.find(Var);
4698 if (It == VarGrpMap.end())
4700 return Groups[It->second];
4704 return GrpsUnionForParms.getArrayRef();
4709 WarningGadgetList WarningGadgets,
4710 DeclUseTracker Tracker,
4712 bool EmitSuggestions) {
4713 if (!EmitSuggestions) {
4717 for (
const auto &G : WarningGadgets) {
4718 G->handleUnsafeOperation(Handler,
false,
4724 assert(FixableGadgets.empty() &&
4725 "Fixable gadgets found but suggestions not requested!");
4731 if (!WarningGadgets.empty()) {
4735 for (
const auto &G : FixableGadgets) {
4736 for (
const auto *DRE : G->getClaimedVarUseSites()) {
4737 Tracker.claimUse(DRE);
4753 if (WarningGadgets.empty())
4761 std::map<const VarDecl *, FixItList> FixItsForVariableGroup;
4764 for (
auto it = FixablesForAllVars.
byVar.cbegin();
4765 it != FixablesForAllVars.
byVar.cend();) {
4770 (
"failed to produce fixit for '" +
4771 it->first->getNameAsString() +
4772 "' : neither local nor a parameter"));
4774 it = FixablesForAllVars.
byVar.erase(it);
4775 }
else if (it->first->getType().getCanonicalType()->isReferenceType()) {
4778 (
"failed to produce fixit for '" +
4779 it->first->getNameAsString() +
4780 "' : has a reference type"));
4782 it = FixablesForAllVars.
byVar.erase(it);
4783 }
else if (Tracker.hasUnclaimedUses(it->first)) {
4784 it = FixablesForAllVars.
byVar.erase(it);
4785 }
else if (it->first->isInitCapture()) {
4788 (
"failed to produce fixit for '" +
4789 it->first->getNameAsString() +
4790 "' : init capture"));
4792 it = FixablesForAllVars.
byVar.erase(it);
4799 for (
const auto &it : UnsafeOps.
byVar) {
4800 const VarDecl *
const UnsafeVD = it.first;
4801 auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
4802 if (UnclaimedDREs.empty())
4806 std::string UnclaimedUseTrace =
4811 (
"failed to produce fixit for '" + UnfixedVDName +
4812 "' : has an unclaimed use\nThe unclaimed DRE trace: " +
4813 UnclaimedUseTrace));
4820 llvm::DenseMap<const VarDecl *, llvm::SetVector<const VarDecl *>>;
4821 DepMapTy DependenciesMap{};
4822 DepMapTy PtrAssignmentGraph{};
4824 for (
const auto &it : FixablesForAllVars.
byVar) {
4825 for (
const FixableGadget *fixable : it.second) {
4826 std::optional<std::pair<const VarDecl *, const VarDecl *>> ImplPair =
4827 fixable->getStrategyImplications();
4829 std::pair<const VarDecl *, const VarDecl *> Impl = std::move(*ImplPair);
4830 PtrAssignmentGraph[Impl.first].insert(Impl.second);
4852 std::set<const VarDecl *> VisitedVarsDirected{};
4853 for (
const auto &[Var, ignore] : UnsafeOps.
byVar) {
4854 if (VisitedVarsDirected.find(Var) == VisitedVarsDirected.end()) {
4856 std::queue<const VarDecl *> QueueDirected{};
4857 QueueDirected.push(Var);
4858 while (!QueueDirected.empty()) {
4859 const VarDecl *CurrentVar = QueueDirected.front();
4860 QueueDirected.pop();
4861 VisitedVarsDirected.insert(CurrentVar);
4862 auto AdjacentNodes = PtrAssignmentGraph[CurrentVar];
4863 for (
const VarDecl *Adj : AdjacentNodes) {
4864 if (VisitedVarsDirected.find(Adj) == VisitedVarsDirected.end()) {
4865 QueueDirected.push(Adj);
4867 DependenciesMap[Var].insert(Adj);
4868 DependenciesMap[Adj].insert(Var);
4875 std::vector<VarGrpTy> Groups;
4879 std::map<const VarDecl *, unsigned> VarGrpMap;
4881 llvm::SetVector<const VarDecl *>
4886 std::set<const VarDecl *> VisitedVars{};
4887 for (
const auto &[Var, ignore] : UnsafeOps.
byVar) {
4888 if (VisitedVars.find(Var) == VisitedVars.end()) {
4889 VarGrpTy &VarGroup = Groups.emplace_back();
4890 std::queue<const VarDecl *> Queue{};
4893 while (!Queue.empty()) {
4894 const VarDecl *CurrentVar = Queue.front();
4896 VisitedVars.insert(CurrentVar);
4897 VarGroup.push_back(CurrentVar);
4898 auto AdjacentNodes = DependenciesMap[CurrentVar];
4899 for (
const VarDecl *Adj : AdjacentNodes) {
4900 if (VisitedVars.find(Adj) == VisitedVars.end()) {
4906 bool HasParm =
false;
4907 unsigned GrpIdx = Groups.size() - 1;
4909 for (
const VarDecl *
V : VarGroup) {
4910 VarGrpMap[
V] = GrpIdx;
4915 GrpsUnionForParms.insert_range(VarGroup);
4937 for (
auto I = FixablesForAllVars.
byVar.begin();
4938 I != FixablesForAllVars.
byVar.end();) {
4940 if (!VisitedVars.count((*I).first)) {
4942 I = FixablesForAllVars.
byVar.erase(I);
4950 VisitedVars, [&FixablesForAllVars](
const VarDecl *
V) {
4952 return FixablesForAllVars.
byVar.count(
V);
4959 FixItsForVariableGroup =
4961 Tracker, Handler, VarGrpMgr);
4963 for (
const auto &G : UnsafeOps.
noVar) {
4964 G->handleUnsafeOperation(Handler,
false,
4968 for (
const auto &[VD, WarningGadgets] : UnsafeOps.
byVar) {
4969 auto FixItsIt = FixItsForVariableGroup.find(VD);
4971 FixItsIt != FixItsForVariableGroup.end()
4972 ? std::move(FixItsIt->second)
4975 for (
const auto &G : WarningGadgets) {
4976 G->handleUnsafeOperation(Handler,
true,
4984 bool EmitSuggestions) {
4990 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4998 if (
const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4999 if (MD->getParent()->isLambda() && MD->getParent()->isLocalClass())
5004 if (FReDecl->isExternC()) {
5007 EmitSuggestions =
false;
5017 assert(!Stmts.empty());
5019 FixableGadgetList FixableGadgets;
5020 WarningGadgetList WarningGadgets;
5021 DeclUseTracker Tracker;
5022 for (
const Stmt *S : Stmts) {
5024 WarningGadgets, Tracker);
5026 applyGadgets(D, std::move(FixableGadgets), std::move(WarningGadgets),
5027 std::move(Tracker), Handler, EmitSuggestions);
5031 std::set<const Expr *> &UnsafePointers) {
5035 void handleUnsafeOperation(
const Stmt *,
bool,
ASTContext &)
override {}
5036 void handleUnsafeLibcCall(
const CallExpr *,
unsigned,
5038 const Expr *UnsafeArg =
nullptr)
override {}
5039 void handleUnsafeOperationInContainer(
const Stmt *,
bool,
5041 void handleUnsafeOperationInStringView(
const Stmt *,
bool,
5043 void handleUnsafeVariableGroup(
const VarDecl *,
5047 void handleUnsafeUniquePtrArrayAccess(
const DynTypedNode &Node,
5048 bool IsRelatedToDecl,
5056 bool ignoreUnsafeBufferInLibcCall(
const SourceLocation &)
const override {
5060 ignoreUnsafeBufferInFormatAttrCall(
const SourceLocation &)
const override {
5063 bool ignoreUnsafeBufferInStaticSizedArray(
5067 std::string getUnsafeBufferUsageAttributeTextAt(
5078 WarningGadgetList WarningGadgets;
5079 bool Matched =
false;
5087#define WARNING_GADGET(name) \
5088 if (name##Gadget::matches(S, Ctx, Result)) \
5089 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5090#define WARNING_OPTIONAL_GADGET(name) \
5091 if (name##Gadget::matches(S, Ctx, &Handler, Result)) \
5092 WarningGadgets.push_back(std::make_unique<name##Gadget>(Result));
5093#include "clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def"
5095 for (
auto &WG : WarningGadgets)
5096 for (
auto *E : WG->getUnsafePtrs()) {
5097 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 isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function 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)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
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.