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);
79 recordType(hasDeclaration(cxxRecordDecl(hasName(
"::std::bad_alloc"))));
81 recordType(hasDeclaration(cxxRecordDecl(hasName(
"::std::exception"))));
82 auto BadAllocReferenceType = referenceType(pointee(BadAllocType));
83 auto ExceptionReferenceType = referenceType(pointee(ExceptionType));
85 auto CatchBadAllocType =
86 qualType(hasCanonicalType(anyOf(BadAllocType, BadAllocReferenceType,
87 ExceptionType, ExceptionReferenceType)));
88 auto BadAllocCatchingTryBlock = cxxTryStmt(hasHandlerFor(CatchBadAllocType));
90 auto NewExprMayThrow = cxxNewExpr(mayThrow());
91 auto HasNewExpr1 = expr(anyOf(NewExprMayThrow.bind(
"new1"),
92 hasDescendant(NewExprMayThrow.bind(
"new1"))));
93 auto HasNewExpr2 = expr(anyOf(NewExprMayThrow.bind(
"new2"),
94 hasDescendant(NewExprMayThrow.bind(
"new2"))));
98 hasAnyArgument(expr(HasNewExpr1).bind(
"arg1")),
100 expr(HasNewExpr2, unless(equalsBoundNode(
"arg1"))).bind(
"arg2")),
101 hasAncestor(BadAllocCatchingTryBlock)),
105 hasAnyArgument(expr(HasNewExpr1).bind(
"arg1")),
107 expr(HasNewExpr2, unless(equalsBoundNode(
"arg1"))).bind(
"arg2")),
108 unless(isListInitialization()),
109 hasAncestor(BadAllocCatchingTryBlock)),
111 Finder->addMatcher(binaryOperator(hasLHS(HasNewExpr1), hasRHS(HasNewExpr2),
112 unless(hasAnyOperatorName(
"&&",
"||",
",")),
113 hasAncestor(BadAllocCatchingTryBlock)),
116 cxxNewExpr(mayThrow(),
117 hasDescendant(NewExprMayThrow.bind(
"new2_in_new1")),
118 hasAncestor(BadAllocCatchingTryBlock))
124 const MatchFinder::MatchResult &Result) {
125 const auto *NewExpr1 = Result.Nodes.getNodeAs<CXXNewExpr>(
"new1");
126 const auto *NewExpr2 = Result.Nodes.getNodeAs<CXXNewExpr>(
"new2");
127 const auto *NewExpr2InNewExpr1 =
128 Result.Nodes.getNodeAs<CXXNewExpr>(
"new2_in_new1");
130 NewExpr2 = NewExpr2InNewExpr1;
131 assert(NewExpr1 && NewExpr2 &&
"Bound nodes not found.");
143 if (getLangOpts().CPlusPlus17 && NewExpr2InNewExpr1)
144 diag(NewExpr1->getBeginLoc(),
145 "memory allocation may leak if an other allocation is sequenced after "
146 "it and throws an exception")
147 << NewExpr1->getSourceRange() << NewExpr2->getSourceRange();
149 diag(NewExpr1->getBeginLoc(),
150 "memory allocation may leak if an other allocation is sequenced after "
151 "it and throws an exception; order of these allocations is undefined")
152 << NewExpr1->getSourceRange() << NewExpr2->getSourceRange();