24 E = E->IgnoreParenCasts();
26 ParentMapContext &PMap = C.getParentMapContext();
27 DynTypedNodeList
P = PMap.getParents(*E);
30 const Expr *ParentE =
nullptr;
31 while ((ParentE =
P[0].get<Expr>()) && ParentE->IgnoreParenCasts() == E) {
32 P = PMap.getParents(
P[0]);
37 if (
const auto *ParentVarD =
P[0].get<VarDecl>())
38 return ParentVarD->getInit()->IgnoreParenCasts() == E;
43 if (
const auto *BinOp = dyn_cast<BinaryOperator>(ParentE))
44 return BinOp->getOpcode() == BO_Assign &&
45 BinOp->getRHS()->IgnoreParenCasts() == E;
47 return isa<CallExpr, CXXConstructExpr>(ParentE);
80 recordType(hasDeclaration(cxxRecordDecl(hasName(
"::std::bad_alloc"))));
82 recordType(hasDeclaration(cxxRecordDecl(hasName(
"::std::exception"))));
83 auto BadAllocReferenceType = referenceType(pointee(BadAllocType));
84 auto ExceptionReferenceType = referenceType(pointee(ExceptionType));
86 const auto CatchBadAllocType =
87 qualType(hasCanonicalType(anyOf(BadAllocType, BadAllocReferenceType,
88 ExceptionType, ExceptionReferenceType)));
89 const auto BadAllocCatchingTryBlock =
90 cxxTryStmt(hasHandlerFor(CatchBadAllocType));
92 const auto NewExprMayThrow = cxxNewExpr(mayThrow());
93 const auto HasNewExpr1 =
94 expr(anyOf(NewExprMayThrow.bind(
"new1"),
95 hasDescendant(NewExprMayThrow.bind(
"new1"))));
96 const auto HasNewExpr2 =
97 expr(anyOf(NewExprMayThrow.bind(
"new2"),
98 hasDescendant(NewExprMayThrow.bind(
"new2"))));
102 hasAnyArgument(expr(HasNewExpr1).bind(
"arg1")),
104 expr(HasNewExpr2, unless(equalsBoundNode(
"arg1"))).bind(
"arg2")),
105 hasAncestor(BadAllocCatchingTryBlock)),
109 hasAnyArgument(expr(HasNewExpr1).bind(
"arg1")),
111 expr(HasNewExpr2, unless(equalsBoundNode(
"arg1"))).bind(
"arg2")),
112 unless(isListInitialization()),
113 hasAncestor(BadAllocCatchingTryBlock)),
115 Finder->addMatcher(binaryOperator(hasLHS(HasNewExpr1), hasRHS(HasNewExpr2),
116 unless(hasAnyOperatorName(
"&&",
"||",
",")),
117 hasAncestor(BadAllocCatchingTryBlock)),
120 cxxNewExpr(mayThrow(),
121 hasDescendant(NewExprMayThrow.bind(
"new2_in_new1")),
122 hasAncestor(BadAllocCatchingTryBlock))
128 const MatchFinder::MatchResult &Result) {
129 const auto *NewExpr1 = Result.Nodes.getNodeAs<CXXNewExpr>(
"new1");
130 const auto *NewExpr2 = Result.Nodes.getNodeAs<CXXNewExpr>(
"new2");
131 const auto *NewExpr2InNewExpr1 =
132 Result.Nodes.getNodeAs<CXXNewExpr>(
"new2_in_new1");
134 NewExpr2 = NewExpr2InNewExpr1;
135 assert(NewExpr1 && NewExpr2 &&
"Bound nodes not found.");
147 if (getLangOpts().CPlusPlus17 && NewExpr2InNewExpr1)
148 diag(NewExpr1->getBeginLoc(),
149 "memory allocation may leak if an other allocation is sequenced after "
150 "it and throws an exception")
151 << NewExpr1->getSourceRange() << NewExpr2->getSourceRange();
153 diag(NewExpr1->getBeginLoc(),
154 "memory allocation may leak if an other allocation is sequenced after "
155 "it and throws an exception; order of these allocations is undefined")
156 << NewExpr1->getSourceRange() << NewExpr2->getSourceRange();