blob: 53da456fd5375cb1a5ee96a9f7a1695e98fec71b [file] [log] [blame]
Kristof Umann30f08652018-06-18 11:50:17 +00001//===----- UninitializedObjectChecker.cpp ------------------------*- C++ -*-==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Kristof Umann30f08652018-06-18 11:50:17 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a checker that reports uninitialized fields in objects
10// created after a constructor call.
11//
Kristof Umann6cec6c42018-09-14 09:39:26 +000012// To read about command line options and how the checker works, refer to the
13// top of the file and inline comments in UninitializedObject.h.
Kristof Umann56963ae2018-08-13 18:17:05 +000014//
15// Some of the logic is implemented in UninitializedPointee.cpp, to reduce the
16// complexity of this file.
17//
Kristof Umann30f08652018-06-18 11:50:17 +000018//===----------------------------------------------------------------------===//
19
Kristof Umann76a21502018-12-15 16:23:51 +000020#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
Kristof Umanna37bba42018-08-13 18:22:22 +000021#include "UninitializedObject.h"
Kristof Umannffe93a12019-02-02 14:50:04 +000022#include "clang/ASTMatchers/ASTMatchFinder.h"
Kristof Umann30f08652018-06-18 11:50:17 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/Checker.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Kristof Umannef9af052018-08-08 13:18:53 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
Kristof Umann30f08652018-06-18 11:50:17 +000027
28using namespace clang;
29using namespace clang::ento;
Kristof Umannffe93a12019-02-02 14:50:04 +000030using namespace clang::ast_matchers;
Kristof Umann30f08652018-06-18 11:50:17 +000031
Kristof Umann4ff77692018-11-18 11:34:10 +000032/// We'll mark fields (and pointee of fields) that are confirmed to be
33/// uninitialized as already analyzed.
34REGISTER_SET_WITH_PROGRAMSTATE(AnalyzedRegions, const MemRegion *)
35
Kristof Umann30f08652018-06-18 11:50:17 +000036namespace {
37
Kristof Umann4ff77692018-11-18 11:34:10 +000038class UninitializedObjectChecker
39 : public Checker<check::EndFunction, check::DeadSymbols> {
Kristof Umann30f08652018-06-18 11:50:17 +000040 std::unique_ptr<BuiltinBug> BT_uninitField;
41
42public:
Kristof Umann6cec6c42018-09-14 09:39:26 +000043 // The fields of this struct will be initialized when registering the checker.
44 UninitObjCheckerOptions Opts;
Kristof Umann30f08652018-06-18 11:50:17 +000045
46 UninitializedObjectChecker()
47 : BT_uninitField(new BuiltinBug(this, "Uninitialized fields")) {}
Kristof Umann4ff77692018-11-18 11:34:10 +000048
Reka Kovacsed8c05c2018-07-16 20:47:45 +000049 void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
Kristof Umann4ff77692018-11-18 11:34:10 +000050 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Kristof Umann30f08652018-06-18 11:50:17 +000051};
52
Kristof Umann015b0592018-08-13 18:43:08 +000053/// A basic field type, that is not a pointer or a reference, it's dynamic and
54/// static type is the same.
Richard Smith651d6832018-08-13 22:07:11 +000055class RegularField final : public FieldNode {
Kristof Umann015b0592018-08-13 18:43:08 +000056public:
57 RegularField(const FieldRegion *FR) : FieldNode(FR) {}
58
59 virtual void printNoteMsg(llvm::raw_ostream &Out) const override {
60 Out << "uninitialized field ";
61 }
62
63 virtual void printPrefix(llvm::raw_ostream &Out) const override {}
64
Richard Smith651d6832018-08-13 22:07:11 +000065 virtual void printNode(llvm::raw_ostream &Out) const override {
Kristof Umann015b0592018-08-13 18:43:08 +000066 Out << getVariableName(getDecl());
67 }
68
69 virtual void printSeparator(llvm::raw_ostream &Out) const override {
70 Out << '.';
71 }
72};
73
Kristof Umannb59b45e2018-08-21 12:16:59 +000074/// Represents that the FieldNode that comes after this is declared in a base
Kristof Umannceb5f652018-09-14 09:07:40 +000075/// of the previous FieldNode. As such, this descendant doesn't wrap a
76/// FieldRegion, and is purely a tool to describe a relation between two other
77/// FieldRegion wrapping descendants.
Kristof Umannb59b45e2018-08-21 12:16:59 +000078class BaseClass final : public FieldNode {
79 const QualType BaseClassT;
80
81public:
82 BaseClass(const QualType &T) : FieldNode(nullptr), BaseClassT(T) {
83 assert(!T.isNull());
84 assert(T->getAsCXXRecordDecl());
85 }
86
87 virtual void printNoteMsg(llvm::raw_ostream &Out) const override {
88 llvm_unreachable("This node can never be the final node in the "
89 "fieldchain!");
90 }
91
92 virtual void printPrefix(llvm::raw_ostream &Out) const override {}
93
94 virtual void printNode(llvm::raw_ostream &Out) const override {
95 Out << BaseClassT->getAsCXXRecordDecl()->getName() << "::";
96 }
97
98 virtual void printSeparator(llvm::raw_ostream &Out) const override {}
99
Kristof Umann06209cb2018-08-21 15:09:22 +0000100 virtual bool isBase() const override { return true; }
Kristof Umannb59b45e2018-08-21 12:16:59 +0000101};
102
Kristof Umanncc852442018-07-12 13:13:46 +0000103} // end of anonymous namespace
104
Kristof Umann30f08652018-06-18 11:50:17 +0000105// Utility function declarations.
106
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000107/// Returns the region that was constructed by CtorDecl, or nullptr if that
108/// isn't possible.
109static const TypedValueRegion *
110getConstructedRegion(const CXXConstructorDecl *CtorDecl,
111 CheckerContext &Context);
Kristof Umann30f08652018-06-18 11:50:17 +0000112
Kristof Umann0735cfb2018-08-08 12:23:02 +0000113/// Checks whether the object constructed by \p Ctor will be analyzed later
114/// (e.g. if the object is a field of another object, in which case we'd check
115/// it multiple times).
116static bool willObjectBeAnalyzedLater(const CXXConstructorDecl *Ctor,
Kristof Umanna37bba42018-08-13 18:22:22 +0000117 CheckerContext &Context);
Kristof Umann30f08652018-06-18 11:50:17 +0000118
Kristof Umannd6145d92018-09-14 10:10:09 +0000119/// Checks whether RD contains a field with a name or type name that matches
120/// \p Pattern.
121static bool shouldIgnoreRecord(const RecordDecl *RD, StringRef Pattern);
122
Kristof Umannffe93a12019-02-02 14:50:04 +0000123/// Checks _syntactically_ whether it is possible to access FD from the record
124/// that contains it without a preceding assert (even if that access happens
125/// inside a method). This is mainly used for records that act like unions, like
126/// having multiple bit fields, with only a fraction being properly initialized.
127/// If these fields are properly guarded with asserts, this method returns
128/// false.
129///
130/// Since this check is done syntactically, this method could be inaccurate.
131static bool hasUnguardedAccess(const FieldDecl *FD, ProgramStateRef State);
132
Kristof Umann30f08652018-06-18 11:50:17 +0000133//===----------------------------------------------------------------------===//
134// Methods for UninitializedObjectChecker.
135//===----------------------------------------------------------------------===//
136
137void UninitializedObjectChecker::checkEndFunction(
Reka Kovacsed8c05c2018-07-16 20:47:45 +0000138 const ReturnStmt *RS, CheckerContext &Context) const {
Kristof Umann30f08652018-06-18 11:50:17 +0000139
140 const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(
141 Context.getLocationContext()->getDecl());
142 if (!CtorDecl)
143 return;
144
145 if (!CtorDecl->isUserProvided())
146 return;
147
148 if (CtorDecl->getParent()->isUnion())
149 return;
150
151 // This avoids essentially the same error being reported multiple times.
Kristof Umann0735cfb2018-08-08 12:23:02 +0000152 if (willObjectBeAnalyzedLater(CtorDecl, Context))
Kristof Umann30f08652018-06-18 11:50:17 +0000153 return;
154
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000155 const TypedValueRegion *R = getConstructedRegion(CtorDecl, Context);
156 if (!R)
Kristof Umann30f08652018-06-18 11:50:17 +0000157 return;
158
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000159 FindUninitializedFields F(Context.getState(), R, Opts);
Kristof Umann30f08652018-06-18 11:50:17 +0000160
Kristof Umann4ff77692018-11-18 11:34:10 +0000161 std::pair<ProgramStateRef, const UninitFieldMap &> UninitInfo =
162 F.getResults();
Kristof Umann30f08652018-06-18 11:50:17 +0000163
Kristof Umann4ff77692018-11-18 11:34:10 +0000164 ProgramStateRef UpdatedState = UninitInfo.first;
165 const UninitFieldMap &UninitFields = UninitInfo.second;
166
167 if (UninitFields.empty()) {
168 Context.addTransition(UpdatedState);
Kristof Umann30f08652018-06-18 11:50:17 +0000169 return;
Kristof Umann4ff77692018-11-18 11:34:10 +0000170 }
Kristof Umann30f08652018-06-18 11:50:17 +0000171
172 // There are uninitialized fields in the record.
173
Kristof Umann4ff77692018-11-18 11:34:10 +0000174 ExplodedNode *Node = Context.generateNonFatalErrorNode(UpdatedState);
Kristof Umann30f08652018-06-18 11:50:17 +0000175 if (!Node)
176 return;
177
178 PathDiagnosticLocation LocUsedForUniqueing;
179 const Stmt *CallSite = Context.getStackFrame()->getCallSite();
180 if (CallSite)
181 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
182 CallSite, Context.getSourceManager(), Node->getLocationContext());
183
Kristof Umann9bd44392018-06-29 11:25:24 +0000184 // For Plist consumers that don't support notes just yet, we'll convert notes
185 // to warnings.
Kristof Umann6cec6c42018-09-14 09:39:26 +0000186 if (Opts.ShouldConvertNotesToWarnings) {
Kristof Umann015b0592018-08-13 18:43:08 +0000187 for (const auto &Pair : UninitFields) {
Kristof Umann9bd44392018-06-29 11:25:24 +0000188
189 auto Report = llvm::make_unique<BugReport>(
Kristof Umann015b0592018-08-13 18:43:08 +0000190 *BT_uninitField, Pair.second, Node, LocUsedForUniqueing,
Kristof Umann9bd44392018-06-29 11:25:24 +0000191 Node->getLocationContext()->getDecl());
192 Context.emitReport(std::move(Report));
193 }
194 return;
195 }
196
Kristof Umann30f08652018-06-18 11:50:17 +0000197 SmallString<100> WarningBuf;
198 llvm::raw_svector_ostream WarningOS(WarningBuf);
199 WarningOS << UninitFields.size() << " uninitialized field"
200 << (UninitFields.size() == 1 ? "" : "s")
201 << " at the end of the constructor call";
202
203 auto Report = llvm::make_unique<BugReport>(
204 *BT_uninitField, WarningOS.str(), Node, LocUsedForUniqueing,
205 Node->getLocationContext()->getDecl());
206
Kristof Umann015b0592018-08-13 18:43:08 +0000207 for (const auto &Pair : UninitFields) {
208 Report->addNote(Pair.second,
209 PathDiagnosticLocation::create(Pair.first->getDecl(),
Kristof Umann30f08652018-06-18 11:50:17 +0000210 Context.getSourceManager()));
211 }
Kristof Umann30f08652018-06-18 11:50:17 +0000212 Context.emitReport(std::move(Report));
213}
214
Kristof Umann4ff77692018-11-18 11:34:10 +0000215void UninitializedObjectChecker::checkDeadSymbols(SymbolReaper &SR,
216 CheckerContext &C) const {
217 ProgramStateRef State = C.getState();
218 for (const MemRegion *R : State->get<AnalyzedRegions>()) {
219 if (!SR.isLiveRegion(R))
220 State = State->remove<AnalyzedRegions>(R);
221 }
222}
223
Kristof Umann30f08652018-06-18 11:50:17 +0000224//===----------------------------------------------------------------------===//
225// Methods for FindUninitializedFields.
226//===----------------------------------------------------------------------===//
227
228FindUninitializedFields::FindUninitializedFields(
Kristof Umann23ca9662018-08-13 18:48:34 +0000229 ProgramStateRef State, const TypedValueRegion *const R,
Kristof Umann6cec6c42018-09-14 09:39:26 +0000230 const UninitObjCheckerOptions &Opts)
231 : State(State), ObjectR(R), Opts(Opts) {
Kristof Umann30f08652018-06-18 11:50:17 +0000232
Kristof Umann015b0592018-08-13 18:43:08 +0000233 isNonUnionUninit(ObjectR, FieldChainInfo(ChainFactory));
Kristof Umann6cec6c42018-09-14 09:39:26 +0000234
235 // In non-pedantic mode, if ObjectR doesn't contain a single initialized
236 // field, we'll assume that Object was intentionally left uninitialized.
237 if (!Opts.IsPedantic && !isAnyFieldInitialized())
238 UninitFields.clear();
Kristof Umann30f08652018-06-18 11:50:17 +0000239}
240
Kristof Umann4ff77692018-11-18 11:34:10 +0000241bool FindUninitializedFields::addFieldToUninits(FieldChainInfo Chain,
242 const MemRegion *PointeeR) {
243 const FieldRegion *FR = Chain.getUninitRegion();
244
245 assert((PointeeR || !isDereferencableType(FR->getDecl()->getType())) &&
246 "One must also pass the pointee region as a parameter for "
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000247 "dereferenceable fields!");
Kristof Umann4ff77692018-11-18 11:34:10 +0000248
Kristof Umannffe93a12019-02-02 14:50:04 +0000249 if (State->getStateManager().getContext().getSourceManager().isInSystemHeader(
250 FR->getDecl()->getLocation()))
251 return false;
252
253 if (Opts.IgnoreGuardedFields && !hasUnguardedAccess(FR->getDecl(), State))
254 return false;
255
Kristof Umann4ff77692018-11-18 11:34:10 +0000256 if (State->contains<AnalyzedRegions>(FR))
257 return false;
258
259 if (PointeeR) {
260 if (State->contains<AnalyzedRegions>(PointeeR)) {
261 return false;
262 }
263 State = State->add<AnalyzedRegions>(PointeeR);
264 }
265
266 State = State->add<AnalyzedRegions>(FR);
267
Kristof Umann015b0592018-08-13 18:43:08 +0000268 UninitFieldMap::mapped_type NoteMsgBuf;
269 llvm::raw_svector_ostream OS(NoteMsgBuf);
270 Chain.printNoteMsg(OS);
Kristof Umannffe93a12019-02-02 14:50:04 +0000271
Kristof Umann4ff77692018-11-18 11:34:10 +0000272 return UninitFields.insert({FR, std::move(NoteMsgBuf)}).second;
Kristof Umann30f08652018-06-18 11:50:17 +0000273}
274
275bool FindUninitializedFields::isNonUnionUninit(const TypedValueRegion *R,
276 FieldChainInfo LocalChain) {
277 assert(R->getValueType()->isRecordType() &&
278 !R->getValueType()->isUnionType() &&
279 "This method only checks non-union record objects!");
280
Kristof Umannf0dd1012018-09-14 08:58:21 +0000281 const RecordDecl *RD = R->getValueType()->getAsRecordDecl()->getDefinition();
282
283 if (!RD) {
284 IsAnyFieldInitialized = true;
285 return true;
286 }
Kristof Umann30f08652018-06-18 11:50:17 +0000287
Kristof Umannd6145d92018-09-14 10:10:09 +0000288 if (!Opts.IgnoredRecordsWithFieldPattern.empty() &&
289 shouldIgnoreRecord(RD, Opts.IgnoredRecordsWithFieldPattern)) {
290 IsAnyFieldInitialized = true;
291 return false;
292 }
293
Kristof Umann30f08652018-06-18 11:50:17 +0000294 bool ContainsUninitField = false;
295
296 // Are all of this non-union's fields initialized?
297 for (const FieldDecl *I : RD->fields()) {
298
299 const auto FieldVal =
300 State->getLValue(I, loc::MemRegionVal(R)).castAs<loc::MemRegionVal>();
301 const auto *FR = FieldVal.getRegionAs<FieldRegion>();
302 QualType T = I->getType();
303
304 // If LocalChain already contains FR, then we encountered a cyclic
305 // reference. In this case, region FR is already under checking at an
306 // earlier node in the directed tree.
307 if (LocalChain.contains(FR))
308 return false;
309
310 if (T->isStructureOrClassType()) {
Kristof Umann015b0592018-08-13 18:43:08 +0000311 if (isNonUnionUninit(FR, LocalChain.add(RegularField(FR))))
Kristof Umann30f08652018-06-18 11:50:17 +0000312 ContainsUninitField = true;
313 continue;
314 }
315
316 if (T->isUnionType()) {
317 if (isUnionUninit(FR)) {
Kristof Umann015b0592018-08-13 18:43:08 +0000318 if (addFieldToUninits(LocalChain.add(RegularField(FR))))
Kristof Umann30f08652018-06-18 11:50:17 +0000319 ContainsUninitField = true;
320 } else
321 IsAnyFieldInitialized = true;
322 continue;
323 }
324
325 if (T->isArrayType()) {
326 IsAnyFieldInitialized = true;
327 continue;
328 }
329
Kristof Umannf0513792018-09-14 10:18:26 +0000330 SVal V = State->getSVal(FieldVal);
331
332 if (isDereferencableType(T) || V.getAs<nonloc::LocAsInteger>()) {
Kristof Umannceb5f652018-09-14 09:07:40 +0000333 if (isDereferencableUninit(FR, LocalChain))
Kristof Umann30f08652018-06-18 11:50:17 +0000334 ContainsUninitField = true;
335 continue;
336 }
337
Kristof Umann20e85ba2018-06-19 08:35:02 +0000338 if (isPrimitiveType(T)) {
Kristof Umann20e85ba2018-06-19 08:35:02 +0000339 if (isPrimitiveUninit(V)) {
Kristof Umann015b0592018-08-13 18:43:08 +0000340 if (addFieldToUninits(LocalChain.add(RegularField(FR))))
Kristof Umann20e85ba2018-06-19 08:35:02 +0000341 ContainsUninitField = true;
342 }
343 continue;
Kristof Umann30f08652018-06-18 11:50:17 +0000344 }
Kristof Umann20e85ba2018-06-19 08:35:02 +0000345
346 llvm_unreachable("All cases are handled!");
Kristof Umann30f08652018-06-18 11:50:17 +0000347 }
348
Kristof Umannceb5f652018-09-14 09:07:40 +0000349 // Checking bases. The checker will regard inherited data members as direct
350 // fields.
Kristof Umann30f08652018-06-18 11:50:17 +0000351 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
352 if (!CXXRD)
353 return ContainsUninitField;
354
355 for (const CXXBaseSpecifier &BaseSpec : CXXRD->bases()) {
356 const auto *BaseRegion = State->getLValue(BaseSpec, R)
357 .castAs<loc::MemRegionVal>()
358 .getRegionAs<TypedValueRegion>();
359
Kristof Umannb59b45e2018-08-21 12:16:59 +0000360 // If the head of the list is also a BaseClass, we'll overwrite it to avoid
361 // note messages like 'this->A::B::x'.
362 if (!LocalChain.isEmpty() && LocalChain.getHead().isBase()) {
363 if (isNonUnionUninit(BaseRegion, LocalChain.replaceHead(
364 BaseClass(BaseSpec.getType()))))
365 ContainsUninitField = true;
366 } else {
367 if (isNonUnionUninit(BaseRegion,
368 LocalChain.add(BaseClass(BaseSpec.getType()))))
369 ContainsUninitField = true;
370 }
Kristof Umann30f08652018-06-18 11:50:17 +0000371 }
372
373 return ContainsUninitField;
374}
375
376bool FindUninitializedFields::isUnionUninit(const TypedValueRegion *R) {
377 assert(R->getValueType()->isUnionType() &&
378 "This method only checks union objects!");
379 // TODO: Implement support for union fields.
380 return false;
381}
382
Kristof Umann30f08652018-06-18 11:50:17 +0000383bool FindUninitializedFields::isPrimitiveUninit(const SVal &V) {
384 if (V.isUndef())
385 return true;
386
387 IsAnyFieldInitialized = true;
388 return false;
389}
390
391//===----------------------------------------------------------------------===//
392// Methods for FieldChainInfo.
393//===----------------------------------------------------------------------===//
394
Kristof Umann015b0592018-08-13 18:43:08 +0000395bool FieldChainInfo::contains(const FieldRegion *FR) const {
396 for (const FieldNode &Node : Chain) {
397 if (Node.isSameRegion(FR))
398 return true;
399 }
400 return false;
Kristof Umann30f08652018-06-18 11:50:17 +0000401}
402
Kristof Umanna37bba42018-08-13 18:22:22 +0000403/// Prints every element except the last to `Out`. Since ImmutableLists store
404/// elements in reverse order, and have no reverse iterators, we use a
405/// recursive function to print the fieldchain correctly. The last element in
Kristof Umannceb5f652018-09-14 09:07:40 +0000406/// the chain is to be printed by `FieldChainInfo::print`.
Kristof Umanna37bba42018-08-13 18:22:22 +0000407static void printTail(llvm::raw_ostream &Out,
Kristof Umann82eeca32018-09-23 09:16:27 +0000408 const FieldChainInfo::FieldChain L);
Kristof Umanna37bba42018-08-13 18:22:22 +0000409
Kristof Umannceb5f652018-09-14 09:07:40 +0000410// FIXME: This function constructs an incorrect string in the following case:
Kristof Umann30f08652018-06-18 11:50:17 +0000411//
412// struct Base { int x; };
413// struct D1 : Base {}; struct D2 : Base {};
414//
415// struct MostDerived : D1, D2 {
416// MostDerived() {}
417// }
418//
419// A call to MostDerived::MostDerived() will cause two notes that say
420// "uninitialized field 'this->x'", but we can't refer to 'x' directly,
421// we need an explicit namespace resolution whether the uninit field was
422// 'D1::x' or 'D2::x'.
Kristof Umann015b0592018-08-13 18:43:08 +0000423void FieldChainInfo::printNoteMsg(llvm::raw_ostream &Out) const {
Kristof Umann30f08652018-06-18 11:50:17 +0000424 if (Chain.isEmpty())
425 return;
426
Kristof Umann82eeca32018-09-23 09:16:27 +0000427 const FieldNode &LastField = getHead();
Kristof Umann015b0592018-08-13 18:43:08 +0000428
429 LastField.printNoteMsg(Out);
430 Out << '\'';
431
432 for (const FieldNode &Node : Chain)
433 Node.printPrefix(Out);
434
435 Out << "this->";
Kristof Umann82eeca32018-09-23 09:16:27 +0000436 printTail(Out, Chain.getTail());
Kristof Umann015b0592018-08-13 18:43:08 +0000437 LastField.printNode(Out);
438 Out << '\'';
Kristof Umann30f08652018-06-18 11:50:17 +0000439}
440
Kristof Umanna37bba42018-08-13 18:22:22 +0000441static void printTail(llvm::raw_ostream &Out,
Kristof Umann82eeca32018-09-23 09:16:27 +0000442 const FieldChainInfo::FieldChain L) {
443 if (L.isEmpty())
Kristof Umann30f08652018-06-18 11:50:17 +0000444 return;
445
Kristof Umann82eeca32018-09-23 09:16:27 +0000446 printTail(Out, L.getTail());
Kristof Umann015b0592018-08-13 18:43:08 +0000447
Kristof Umann82eeca32018-09-23 09:16:27 +0000448 L.getHead().printNode(Out);
449 L.getHead().printSeparator(Out);
Kristof Umann30f08652018-06-18 11:50:17 +0000450}
451
452//===----------------------------------------------------------------------===//
453// Utility functions.
454//===----------------------------------------------------------------------===//
455
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000456static const TypedValueRegion *
457getConstructedRegion(const CXXConstructorDecl *CtorDecl,
458 CheckerContext &Context) {
Kristof Umann30f08652018-06-18 11:50:17 +0000459
Kristof Umannffe93a12019-02-02 14:50:04 +0000460 Loc ThisLoc =
461 Context.getSValBuilder().getCXXThis(CtorDecl, Context.getStackFrame());
Kristof Umann30f08652018-06-18 11:50:17 +0000462
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000463 SVal ObjectV = Context.getState()->getSVal(ThisLoc);
Kristof Umann30f08652018-06-18 11:50:17 +0000464
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000465 auto *R = ObjectV.getAsRegion()->getAs<TypedValueRegion>();
466 if (R && !R->getValueType()->getAsCXXRecordDecl())
467 return nullptr;
468
469 return R;
Kristof Umann30f08652018-06-18 11:50:17 +0000470}
471
Kristof Umann0735cfb2018-08-08 12:23:02 +0000472static bool willObjectBeAnalyzedLater(const CXXConstructorDecl *Ctor,
Kristof Umanna37bba42018-08-13 18:22:22 +0000473 CheckerContext &Context) {
Kristof Umann30f08652018-06-18 11:50:17 +0000474
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000475 const TypedValueRegion *CurrRegion = getConstructedRegion(Ctor, Context);
476 if (!CurrRegion)
Kristof Umann0735cfb2018-08-08 12:23:02 +0000477 return false;
478
479 const LocationContext *LC = Context.getLocationContext();
480 while ((LC = LC->getParent())) {
481
482 // If \p Ctor was called by another constructor.
483 const auto *OtherCtor = dyn_cast<CXXConstructorDecl>(LC->getDecl());
484 if (!OtherCtor)
485 continue;
486
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000487 const TypedValueRegion *OtherRegion =
488 getConstructedRegion(OtherCtor, Context);
489 if (!OtherRegion)
Kristof Umann0735cfb2018-08-08 12:23:02 +0000490 continue;
491
Kristof Umanndbabdfa2018-10-21 23:30:01 +0000492 // If the CurrRegion is a subregion of OtherRegion, it will be analyzed
493 // during the analysis of OtherRegion.
494 if (CurrRegion->isSubRegionOf(OtherRegion))
Kristof Umann30f08652018-06-18 11:50:17 +0000495 return true;
Kristof Umann30f08652018-06-18 11:50:17 +0000496 }
Kristof Umann0735cfb2018-08-08 12:23:02 +0000497
Kristof Umann30f08652018-06-18 11:50:17 +0000498 return false;
499}
500
Kristof Umannd6145d92018-09-14 10:10:09 +0000501static bool shouldIgnoreRecord(const RecordDecl *RD, StringRef Pattern) {
502 llvm::Regex R(Pattern);
503
504 for (const FieldDecl *FD : RD->fields()) {
505 if (R.match(FD->getType().getAsString()))
506 return true;
507 if (R.match(FD->getName()))
508 return true;
509 }
510
511 return false;
512}
513
Kristof Umannffe93a12019-02-02 14:50:04 +0000514static const Stmt *getMethodBody(const CXXMethodDecl *M) {
515 if (isa<CXXConstructorDecl>(M))
516 return nullptr;
517
518 if (!M->isDefined())
519 return nullptr;
520
521 return M->getDefinition()->getBody();
522}
523
524static bool hasUnguardedAccess(const FieldDecl *FD, ProgramStateRef State) {
525
526 if (FD->getAccess() == AccessSpecifier::AS_public)
527 return true;
528
529 const auto *Parent = dyn_cast<CXXRecordDecl>(FD->getParent());
530
531 if (!Parent)
532 return true;
533
534 Parent = Parent->getDefinition();
535 assert(Parent && "The record's definition must be avaible if an uninitialized"
536 " field of it was found!");
537
538 ASTContext &AC = State->getStateManager().getContext();
539
540 auto FieldAccessM = memberExpr(hasDeclaration(equalsNode(FD))).bind("access");
541
542 auto AssertLikeM = callExpr(callee(functionDecl(
543 anyOf(hasName("exit"), hasName("panic"), hasName("error"),
544 hasName("Assert"), hasName("assert"), hasName("ziperr"),
545 hasName("assfail"), hasName("db_error"), hasName("__assert"),
546 hasName("__assert2"), hasName("_wassert"), hasName("__assert_rtn"),
547 hasName("__assert_fail"), hasName("dtrace_assfail"),
548 hasName("yy_fatal_error"), hasName("_XCAssertionFailureHandler"),
549 hasName("_DTAssertionFailureHandler"),
550 hasName("_TSAssertionFailureHandler")))));
551
552 auto NoReturnFuncM = callExpr(callee(functionDecl(isNoReturn())));
553
554 auto GuardM =
555 stmt(anyOf(ifStmt(), switchStmt(), conditionalOperator(), AssertLikeM,
556 NoReturnFuncM))
557 .bind("guard");
558
559 for (const CXXMethodDecl *M : Parent->methods()) {
560 const Stmt *MethodBody = getMethodBody(M);
561 if (!MethodBody)
562 continue;
563
564 auto Accesses = match(stmt(hasDescendant(FieldAccessM)), *MethodBody, AC);
565 if (Accesses.empty())
566 continue;
567 const auto *FirstAccess = Accesses[0].getNodeAs<MemberExpr>("access");
568 assert(FirstAccess);
569
570 auto Guards = match(stmt(hasDescendant(GuardM)), *MethodBody, AC);
571 if (Guards.empty())
572 return true;
573 const auto *FirstGuard = Guards[0].getNodeAs<Stmt>("guard");
574 assert(FirstGuard);
575
576 if (FirstAccess->getBeginLoc() < FirstGuard->getBeginLoc())
577 return true;
578 }
579
580 return false;
581}
582
Kristof Umannf0dd1012018-09-14 08:58:21 +0000583std::string clang::ento::getVariableName(const FieldDecl *Field) {
Kristof Umann8c119092018-07-13 12:54:47 +0000584 // If Field is a captured lambda variable, Field->getName() will return with
585 // an empty string. We can however acquire it's name from the lambda's
586 // captures.
587 const auto *CXXParent = dyn_cast<CXXRecordDecl>(Field->getParent());
588
589 if (CXXParent && CXXParent->isLambda()) {
590 assert(CXXParent->captures_begin());
591 auto It = CXXParent->captures_begin() + Field->getFieldIndex();
Kristof Umannf0dd1012018-09-14 08:58:21 +0000592
593 if (It->capturesVariable())
594 return llvm::Twine("/*captured variable*/" +
595 It->getCapturedVar()->getName())
596 .str();
597
598 if (It->capturesThis())
599 return "/*'this' capture*/";
600
601 llvm_unreachable("No other capture type is expected!");
Kristof Umann8c119092018-07-13 12:54:47 +0000602 }
603
604 return Field->getName();
605}
606
Kristof Umann30f08652018-06-18 11:50:17 +0000607void ento::registerUninitializedObjectChecker(CheckerManager &Mgr) {
608 auto Chk = Mgr.registerChecker<UninitializedObjectChecker>();
Kristof Umannceb5f652018-09-14 09:07:40 +0000609
Kristof Umann6cec6c42018-09-14 09:39:26 +0000610 AnalyzerOptions &AnOpts = Mgr.getAnalyzerOptions();
611 UninitObjCheckerOptions &ChOpts = Chk->Opts;
612
Kristof Umannd6145d92018-09-14 10:10:09 +0000613 ChOpts.IsPedantic =
Kristof Umann088b1c92019-03-04 00:28:16 +0000614 AnOpts.getCheckerBooleanOption(Chk, "Pedantic", /*DefaultVal*/ false);
615 ChOpts.ShouldConvertNotesToWarnings = AnOpts.getCheckerBooleanOption(
616 Chk, "NotesAsWarnings", /*DefaultVal*/ false);
Kristof Umann0a1f91c2018-11-05 03:50:37 +0000617 ChOpts.CheckPointeeInitialization = AnOpts.getCheckerBooleanOption(
Kristof Umann088b1c92019-03-04 00:28:16 +0000618 Chk, "CheckPointeeInitialization", /*DefaultVal*/ false);
Kristof Umannd6145d92018-09-14 10:10:09 +0000619 ChOpts.IgnoredRecordsWithFieldPattern =
Kristof Umann088b1c92019-03-04 00:28:16 +0000620 AnOpts.getCheckerStringOption(Chk, "IgnoreRecordsWithField",
621 /*DefaultVal*/ "");
Kristof Umannffe93a12019-02-02 14:50:04 +0000622 ChOpts.IgnoreGuardedFields =
Kristof Umann088b1c92019-03-04 00:28:16 +0000623 AnOpts.getCheckerBooleanOption(Chk, "IgnoreGuardedFields",
624 /*DefaultVal*/ false);
Kristof Umann30f08652018-06-18 11:50:17 +0000625}
Kristof Umann058a7a42019-01-26 14:23:08 +0000626
627bool ento::shouldRegisterUninitializedObjectChecker(const LangOptions &LO) {
628 return true;
629}