blob: a44ae9cd8d3497ac5a9face31f23529a5e3f37c6 [file] [log] [blame]
Kristof Umann30f08652018-06-18 11:50:17 +00001//===----- UninitializedObjectChecker.cpp ------------------------*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a checker that reports uninitialized fields in objects
11// created after a constructor call.
12//
Kristof Umann9bd44392018-06-29 11:25:24 +000013// This checker has two options:
14// - "Pedantic" (boolean). If its not set or is set to false, the checker
15// won't emit warnings for objects that don't have at least one initialized
16// field. This may be set with
17//
18// `-analyzer-config alpha.cplusplus.UninitializedObject:Pedantic=true`.
19//
20// - "NotesAsWarnings" (boolean). If set to true, the checker will emit a
21// warning for each uninitalized field, as opposed to emitting one warning
22// per constructor call, and listing the uninitialized fields that belongs
23// to it in notes. Defaults to false.
24//
25// `-analyzer-config alpha.cplusplus.UninitializedObject:NotesAsWarnings=true`.
Kristof Umann30f08652018-06-18 11:50:17 +000026//
27//===----------------------------------------------------------------------===//
28
29#include "ClangSACheckers.h"
30#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
31#include "clang/StaticAnalyzer/Core/Checker.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
33#include <algorithm>
34
35using namespace clang;
36using namespace clang::ento;
37
38namespace {
39
40class UninitializedObjectChecker : public Checker<check::EndFunction> {
41 std::unique_ptr<BuiltinBug> BT_uninitField;
42
43public:
Kristof Umann9bd44392018-06-29 11:25:24 +000044 // These fields will be initialized when registering the checker.
45 bool IsPedantic;
46 bool ShouldConvertNotesToWarnings;
Kristof Umann30f08652018-06-18 11:50:17 +000047
48 UninitializedObjectChecker()
49 : BT_uninitField(new BuiltinBug(this, "Uninitialized fields")) {}
50 void checkEndFunction(CheckerContext &C) const;
51};
52
Kristof Umann30f08652018-06-18 11:50:17 +000053/// Represents a field chain. A field chain is a vector of fields where the
54/// first element of the chain is the object under checking (not stored), and
55/// every other element is a field, and the element that precedes it is the
56/// object that contains it.
57///
58/// Note that this class is immutable, and new fields may only be added through
59/// constructor calls.
60class FieldChainInfo {
61 using FieldChain = llvm::ImmutableList<const FieldRegion *>;
62
63 FieldChain Chain;
64
65 const bool IsDereferenced = false;
66
67public:
68 FieldChainInfo() = default;
69
70 FieldChainInfo(const FieldChainInfo &Other, const bool IsDereferenced)
71 : Chain(Other.Chain), IsDereferenced(IsDereferenced) {}
72
73 FieldChainInfo(const FieldChainInfo &Other, const FieldRegion *FR,
74 const bool IsDereferenced = false);
75
76 bool contains(const FieldRegion *FR) const { return Chain.contains(FR); }
77 bool isPointer() const;
78
79 /// If this is a fieldchain whose last element is an uninitialized region of a
80 /// pointer type, `IsDereferenced` will store whether the pointer itself or
81 /// the pointee is uninitialized.
82 bool isDereferenced() const;
83 const FieldDecl *getEndOfChain() const;
84 void print(llvm::raw_ostream &Out) const;
85
86private:
87 /// Prints every element except the last to `Out`. Since ImmutableLists store
88 /// elements in reverse order, and have no reverse iterators, we use a
89 /// recursive function to print the fieldchain correctly. The last element in
90 /// the chain is to be printed by `print`.
91 static void printTail(llvm::raw_ostream &Out,
92 const llvm::ImmutableListImpl<const FieldRegion *> *L);
93 friend struct FieldChainInfoComparator;
94};
95
96struct FieldChainInfoComparator {
Steven Wub3684db2018-06-22 16:51:17 +000097 bool operator()(const FieldChainInfo &lhs, const FieldChainInfo &rhs) const {
Kristof Umann30f08652018-06-18 11:50:17 +000098 assert(!lhs.Chain.isEmpty() && !rhs.Chain.isEmpty() &&
99 "Attempted to store an empty fieldchain!");
100 return *lhs.Chain.begin() < *rhs.Chain.begin();
101 }
102};
103
104using UninitFieldSet = std::set<FieldChainInfo, FieldChainInfoComparator>;
105
106/// Searches for and stores uninitialized fields in a non-union object.
107class FindUninitializedFields {
108 ProgramStateRef State;
109 const TypedValueRegion *const ObjectR;
110
111 const bool IsPedantic;
112 bool IsAnyFieldInitialized = false;
113
114 UninitFieldSet UninitFields;
115
116public:
117 FindUninitializedFields(ProgramStateRef State,
118 const TypedValueRegion *const R, bool IsPedantic);
119 const UninitFieldSet &getUninitFields();
120
121private:
122 /// Adds a FieldChainInfo object to UninitFields. Return true if an insertion
123 /// took place.
124 bool addFieldToUninits(FieldChainInfo LocalChain);
125
126 // For the purposes of this checker, we'll regard the object under checking as
127 // a directed tree, where
128 // * the root is the object under checking
129 // * every node is an object that is
130 // - a union
131 // - a non-union record
132 // - a pointer/reference
133 // - an array
Kristof Umann7212cc02018-07-13 12:21:38 +0000134 // - of a primitive type, which we'll define later in a helper function.
Kristof Umann30f08652018-06-18 11:50:17 +0000135 // * the parent of each node is the object that contains it
Kristof Umann7212cc02018-07-13 12:21:38 +0000136 // * every leaf is an array, a primitive object, a nullptr or an undefined
137 // pointer.
Kristof Umann30f08652018-06-18 11:50:17 +0000138 //
139 // Example:
140 //
141 // struct A {
142 // struct B {
143 // int x, y = 0;
144 // };
145 // B b;
146 // int *iptr = new int;
147 // B* bptr;
148 //
149 // A() {}
150 // };
151 //
152 // The directed tree:
153 //
154 // ->x
155 // /
156 // ->b--->y
157 // /
158 // A-->iptr->(int value)
159 // \
160 // ->bptr
161 //
162 // From this we'll construct a vector of fieldchains, where each fieldchain
163 // represents an uninitialized field. An uninitialized field may be a
Kristof Umann7212cc02018-07-13 12:21:38 +0000164 // primitive object, a pointer, a pointee or a union without a single
165 // initialized field.
Kristof Umann30f08652018-06-18 11:50:17 +0000166 // In the above example, for the default constructor call we'll end up with
167 // these fieldchains:
168 //
169 // this->b.x
170 // this->iptr (pointee uninit)
171 // this->bptr (pointer uninit)
172 //
173 // We'll traverse each node of the above graph with the appropiate one of
174 // these methods:
175
176 /// This method checks a region of a union object, and returns true if no
177 /// field is initialized within the region.
178 bool isUnionUninit(const TypedValueRegion *R);
179
180 /// This method checks a region of a non-union object, and returns true if
181 /// an uninitialized field is found within the region.
182 bool isNonUnionUninit(const TypedValueRegion *R, FieldChainInfo LocalChain);
183
184 /// This method checks a region of a pointer or reference object, and returns
185 /// true if the ptr/ref object itself or any field within the pointee's region
186 /// is uninitialized.
187 bool isPointerOrReferenceUninit(const FieldRegion *FR,
188 FieldChainInfo LocalChain);
189
Kristof Umann30f08652018-06-18 11:50:17 +0000190 /// This method returns true if the value of a primitive object is
191 /// uninitialized.
192 bool isPrimitiveUninit(const SVal &V);
193
194 // Note that we don't have a method for arrays -- the elements of an array are
195 // often left uninitialized intentionally even when it is of a C++ record
196 // type, so we'll assume that an array is always initialized.
197 // TODO: Add a support for nonloc::LocAsInteger.
198};
199
Kristof Umanncc852442018-07-12 13:13:46 +0000200} // end of anonymous namespace
201
202// Static variable instantionations.
203
204static llvm::ImmutableListFactory<const FieldRegion *> Factory;
205
Kristof Umann30f08652018-06-18 11:50:17 +0000206// Utility function declarations.
207
208/// Returns the object that was constructed by CtorDecl, or None if that isn't
209/// possible.
Kristof Umanncc852442018-07-12 13:13:46 +0000210static Optional<nonloc::LazyCompoundVal>
Kristof Umann30f08652018-06-18 11:50:17 +0000211getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context);
212
213/// Checks whether the constructor under checking is called by another
214/// constructor.
Kristof Umanncc852442018-07-12 13:13:46 +0000215static bool isCalledByConstructor(const CheckerContext &Context);
Kristof Umann30f08652018-06-18 11:50:17 +0000216
217/// Returns whether FD can be (transitively) dereferenced to a void pointer type
218/// (void*, void**, ...). The type of the region behind a void pointer isn't
219/// known, and thus FD can not be analyzed.
Kristof Umanncc852442018-07-12 13:13:46 +0000220static bool isVoidPointer(const FieldDecl *FD);
Kristof Umann30f08652018-06-18 11:50:17 +0000221
Kristof Umann7212cc02018-07-13 12:21:38 +0000222/// Returns true if T is a primitive type. We defined this type so that for
223/// objects that we'd only like analyze as much as checking whether their
224/// value is undefined or not, such as ints and doubles, can be analyzed with
225/// ease. This also helps ensuring that every special field type is handled
226/// correctly.
Kristof Umanncc852442018-07-12 13:13:46 +0000227static bool isPrimitiveType(const QualType &T) {
Kristof Umann7212cc02018-07-13 12:21:38 +0000228 return T->isBuiltinType() || T->isEnumeralType() || T->isMemberPointerType();
Kristof Umann30f08652018-06-18 11:50:17 +0000229}
230
Kristof Umann9bd44392018-06-29 11:25:24 +0000231/// Constructs a note message for a given FieldChainInfo object.
Kristof Umanncc852442018-07-12 13:13:46 +0000232static void printNoteMessage(llvm::raw_ostream &Out,
233 const FieldChainInfo &Chain);
Kristof Umann30f08652018-06-18 11:50:17 +0000234
235//===----------------------------------------------------------------------===//
236// Methods for UninitializedObjectChecker.
237//===----------------------------------------------------------------------===//
238
239void UninitializedObjectChecker::checkEndFunction(
240 CheckerContext &Context) const {
241
242 const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(
243 Context.getLocationContext()->getDecl());
244 if (!CtorDecl)
245 return;
246
247 if (!CtorDecl->isUserProvided())
248 return;
249
250 if (CtorDecl->getParent()->isUnion())
251 return;
252
253 // This avoids essentially the same error being reported multiple times.
254 if (isCalledByConstructor(Context))
255 return;
256
257 Optional<nonloc::LazyCompoundVal> Object = getObjectVal(CtorDecl, Context);
258 if (!Object)
259 return;
260
261 FindUninitializedFields F(Context.getState(), Object->getRegion(),
262 IsPedantic);
263
264 const UninitFieldSet &UninitFields = F.getUninitFields();
265
266 if (UninitFields.empty())
267 return;
268
269 // There are uninitialized fields in the record.
270
271 ExplodedNode *Node = Context.generateNonFatalErrorNode(Context.getState());
272 if (!Node)
273 return;
274
275 PathDiagnosticLocation LocUsedForUniqueing;
276 const Stmt *CallSite = Context.getStackFrame()->getCallSite();
277 if (CallSite)
278 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
279 CallSite, Context.getSourceManager(), Node->getLocationContext());
280
Kristof Umann9bd44392018-06-29 11:25:24 +0000281 // For Plist consumers that don't support notes just yet, we'll convert notes
282 // to warnings.
283 if (ShouldConvertNotesToWarnings) {
284 for (const auto &Chain : UninitFields) {
285 SmallString<100> WarningBuf;
286 llvm::raw_svector_ostream WarningOS(WarningBuf);
287
288 printNoteMessage(WarningOS, Chain);
289
290 auto Report = llvm::make_unique<BugReport>(
291 *BT_uninitField, WarningOS.str(), Node, LocUsedForUniqueing,
292 Node->getLocationContext()->getDecl());
293 Context.emitReport(std::move(Report));
294 }
295 return;
296 }
297
Kristof Umann30f08652018-06-18 11:50:17 +0000298 SmallString<100> WarningBuf;
299 llvm::raw_svector_ostream WarningOS(WarningBuf);
300 WarningOS << UninitFields.size() << " uninitialized field"
301 << (UninitFields.size() == 1 ? "" : "s")
302 << " at the end of the constructor call";
303
304 auto Report = llvm::make_unique<BugReport>(
305 *BT_uninitField, WarningOS.str(), Node, LocUsedForUniqueing,
306 Node->getLocationContext()->getDecl());
307
Kristof Umann9bd44392018-06-29 11:25:24 +0000308 for (const auto &Chain : UninitFields) {
Kristof Umann30f08652018-06-18 11:50:17 +0000309 SmallString<200> NoteBuf;
310 llvm::raw_svector_ostream NoteOS(NoteBuf);
311
Kristof Umann9bd44392018-06-29 11:25:24 +0000312 printNoteMessage(NoteOS, Chain);
Kristof Umann30f08652018-06-18 11:50:17 +0000313
314 Report->addNote(NoteOS.str(),
Kristof Umann9bd44392018-06-29 11:25:24 +0000315 PathDiagnosticLocation::create(Chain.getEndOfChain(),
Kristof Umann30f08652018-06-18 11:50:17 +0000316 Context.getSourceManager()));
317 }
Kristof Umann30f08652018-06-18 11:50:17 +0000318 Context.emitReport(std::move(Report));
319}
320
321//===----------------------------------------------------------------------===//
322// Methods for FindUninitializedFields.
323//===----------------------------------------------------------------------===//
324
325FindUninitializedFields::FindUninitializedFields(
326 ProgramStateRef State, const TypedValueRegion *const R, bool IsPedantic)
327 : State(State), ObjectR(R), IsPedantic(IsPedantic) {}
328
329const UninitFieldSet &FindUninitializedFields::getUninitFields() {
330 isNonUnionUninit(ObjectR, FieldChainInfo());
331
332 if (!IsPedantic && !IsAnyFieldInitialized)
333 UninitFields.clear();
334
335 return UninitFields;
336}
337
338bool FindUninitializedFields::addFieldToUninits(FieldChainInfo Chain) {
339 if (State->getStateManager().getContext().getSourceManager().isInSystemHeader(
340 Chain.getEndOfChain()->getLocation()))
341 return false;
342
343 return UninitFields.insert(Chain).second;
344}
345
346bool FindUninitializedFields::isNonUnionUninit(const TypedValueRegion *R,
347 FieldChainInfo LocalChain) {
348 assert(R->getValueType()->isRecordType() &&
349 !R->getValueType()->isUnionType() &&
350 "This method only checks non-union record objects!");
351
352 const RecordDecl *RD =
353 R->getValueType()->getAs<RecordType>()->getDecl()->getDefinition();
354 assert(RD && "Referred record has no definition");
355
356 bool ContainsUninitField = false;
357
358 // Are all of this non-union's fields initialized?
359 for (const FieldDecl *I : RD->fields()) {
360
361 const auto FieldVal =
362 State->getLValue(I, loc::MemRegionVal(R)).castAs<loc::MemRegionVal>();
363 const auto *FR = FieldVal.getRegionAs<FieldRegion>();
364 QualType T = I->getType();
365
366 // If LocalChain already contains FR, then we encountered a cyclic
367 // reference. In this case, region FR is already under checking at an
368 // earlier node in the directed tree.
369 if (LocalChain.contains(FR))
370 return false;
371
372 if (T->isStructureOrClassType()) {
373 if (isNonUnionUninit(FR, {LocalChain, FR}))
374 ContainsUninitField = true;
375 continue;
376 }
377
378 if (T->isUnionType()) {
379 if (isUnionUninit(FR)) {
380 if (addFieldToUninits({LocalChain, FR}))
381 ContainsUninitField = true;
382 } else
383 IsAnyFieldInitialized = true;
384 continue;
385 }
386
387 if (T->isArrayType()) {
388 IsAnyFieldInitialized = true;
389 continue;
390 }
391
Kristof Umann30f08652018-06-18 11:50:17 +0000392 if (T->isPointerType() || T->isReferenceType()) {
393 if (isPointerOrReferenceUninit(FR, LocalChain))
394 ContainsUninitField = true;
395 continue;
396 }
397
Kristof Umann20e85ba2018-06-19 08:35:02 +0000398 if (isPrimitiveType(T)) {
399 SVal V = State->getSVal(FieldVal);
Kristof Umann30f08652018-06-18 11:50:17 +0000400
Kristof Umann20e85ba2018-06-19 08:35:02 +0000401 if (isPrimitiveUninit(V)) {
402 if (addFieldToUninits({LocalChain, FR}))
403 ContainsUninitField = true;
404 }
405 continue;
Kristof Umann30f08652018-06-18 11:50:17 +0000406 }
Kristof Umann20e85ba2018-06-19 08:35:02 +0000407
408 llvm_unreachable("All cases are handled!");
Kristof Umann30f08652018-06-18 11:50:17 +0000409 }
410
411 // Checking bases.
412 // FIXME: As of now, because of `isCalledByConstructor`, objects whose type
413 // is a descendant of another type will emit warnings for uninitalized
414 // inherited members.
415 // This is not the only way to analyze bases of an object -- if we didn't
416 // filter them out, and didn't analyze the bases, this checker would run for
417 // each base of the object in order of base initailization and in theory would
418 // find every uninitalized field. This approach could also make handling
419 // diamond inheritances more easily.
420 //
421 // This rule (that a descendant type's cunstructor is responsible for
422 // initializing inherited data members) is not obvious, and should it should
423 // be.
424 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
425 if (!CXXRD)
426 return ContainsUninitField;
427
428 for (const CXXBaseSpecifier &BaseSpec : CXXRD->bases()) {
429 const auto *BaseRegion = State->getLValue(BaseSpec, R)
430 .castAs<loc::MemRegionVal>()
431 .getRegionAs<TypedValueRegion>();
432
433 if (isNonUnionUninit(BaseRegion, LocalChain))
434 ContainsUninitField = true;
435 }
436
437 return ContainsUninitField;
438}
439
440bool FindUninitializedFields::isUnionUninit(const TypedValueRegion *R) {
441 assert(R->getValueType()->isUnionType() &&
442 "This method only checks union objects!");
443 // TODO: Implement support for union fields.
444 return false;
445}
446
447// Note that pointers/references don't contain fields themselves, so in this
448// function we won't add anything to LocalChain.
449bool FindUninitializedFields::isPointerOrReferenceUninit(
450 const FieldRegion *FR, FieldChainInfo LocalChain) {
451
452 assert((FR->getDecl()->getType()->isPointerType() ||
453 FR->getDecl()->getType()->isReferenceType()) &&
454 "This method only checks pointer/reference objects!");
455
456 SVal V = State->getSVal(FR);
457
458 if (V.isUnknown() || V.isZeroConstant()) {
459 IsAnyFieldInitialized = true;
460 return false;
461 }
462
463 if (V.isUndef()) {
464 return addFieldToUninits({LocalChain, FR});
465 }
466
467 const FieldDecl *FD = FR->getDecl();
468
469 // TODO: The dynamic type of a void pointer may be retrieved with
470 // `getDynamicTypeInfo`.
471 if (isVoidPointer(FD)) {
472 IsAnyFieldInitialized = true;
473 return false;
474 }
475
476 assert(V.getAs<Loc>() && "V should be Loc at this point!");
477
478 // At this point the pointer itself is initialized and points to a valid
479 // location, we'll now check the pointee.
480 SVal DerefdV = State->getSVal(V.castAs<Loc>());
481
482 // TODO: Dereferencing should be done according to the dynamic type.
483 while (Optional<Loc> L = DerefdV.getAs<Loc>()) {
484 DerefdV = State->getSVal(*L);
485 }
486
487 // If V is a pointer pointing to a record type.
488 if (Optional<nonloc::LazyCompoundVal> RecordV =
489 DerefdV.getAs<nonloc::LazyCompoundVal>()) {
490
491 const TypedValueRegion *R = RecordV->getRegion();
492
493 // We can't reason about symbolic regions, assume its initialized.
494 // Note that this also avoids a potential infinite recursion, because
495 // constructors for list-like classes are checked without being called, and
496 // the Static Analyzer will construct a symbolic region for Node *next; or
497 // similar code snippets.
498 if (R->getSymbolicBase()) {
499 IsAnyFieldInitialized = true;
500 return false;
501 }
502
503 const QualType T = R->getValueType();
504
505 if (T->isStructureOrClassType())
506 return isNonUnionUninit(R, {LocalChain, FR});
507
508 if (T->isUnionType()) {
509 if (isUnionUninit(R)) {
510 return addFieldToUninits({LocalChain, FR, /*IsDereferenced*/ true});
511 } else {
512 IsAnyFieldInitialized = true;
513 return false;
514 }
515 }
516
517 if (T->isArrayType()) {
518 IsAnyFieldInitialized = true;
519 return false;
520 }
521
522 llvm_unreachable("All cases are handled!");
523 }
524
525 // TODO: If possible, it should be asserted that the DerefdV at this point is
526 // primitive.
527
528 if (isPrimitiveUninit(DerefdV))
529 return addFieldToUninits({LocalChain, FR, /*IsDereferenced*/ true});
530
531 IsAnyFieldInitialized = true;
532 return false;
533}
534
Kristof Umann30f08652018-06-18 11:50:17 +0000535bool FindUninitializedFields::isPrimitiveUninit(const SVal &V) {
536 if (V.isUndef())
537 return true;
538
539 IsAnyFieldInitialized = true;
540 return false;
541}
542
543//===----------------------------------------------------------------------===//
544// Methods for FieldChainInfo.
545//===----------------------------------------------------------------------===//
546
547FieldChainInfo::FieldChainInfo(const FieldChainInfo &Other,
548 const FieldRegion *FR, const bool IsDereferenced)
549 : FieldChainInfo(Other, IsDereferenced) {
550 assert(!contains(FR) && "Can't add a field that is already a part of the "
551 "fieldchain! Is this a cyclic reference?");
552 Chain = Factory.add(FR, Other.Chain);
553}
554
555bool FieldChainInfo::isPointer() const {
556 assert(!Chain.isEmpty() && "Empty fieldchain!");
557 return (*Chain.begin())->getDecl()->getType()->isPointerType();
558}
559
560bool FieldChainInfo::isDereferenced() const {
561 assert(isPointer() && "Only pointers may or may not be dereferenced!");
562 return IsDereferenced;
563}
564
565const FieldDecl *FieldChainInfo::getEndOfChain() const {
566 assert(!Chain.isEmpty() && "Empty fieldchain!");
567 return (*Chain.begin())->getDecl();
568}
569
570// TODO: This function constructs an incorrect fieldchain string in the
571// following case:
572//
573// struct Base { int x; };
574// struct D1 : Base {}; struct D2 : Base {};
575//
576// struct MostDerived : D1, D2 {
577// MostDerived() {}
578// }
579//
580// A call to MostDerived::MostDerived() will cause two notes that say
581// "uninitialized field 'this->x'", but we can't refer to 'x' directly,
582// we need an explicit namespace resolution whether the uninit field was
583// 'D1::x' or 'D2::x'.
584//
585// TODO: If a field in the fieldchain is a captured lambda parameter, this
586// function constructs an empty string for it:
587//
588// template <class Callable> struct A {
589// Callable c;
590// A(const Callable &c, int) : c(c) {}
591// };
592//
593// int b; // say that this isn't zero initialized
594// auto alwaysTrue = [&b](int a) { return true; };
595//
596// A call with these parameters: A<decltype(alwaysTrue)>::A(alwaysTrue, int())
597// will emit a note with the message "uninitialized field: 'this->c.'". If
598// possible, the lambda parameter name should be retrieved or be replaced with a
599// "<lambda parameter>" or something similar.
600void FieldChainInfo::print(llvm::raw_ostream &Out) const {
601 if (Chain.isEmpty())
602 return;
603
604 const llvm::ImmutableListImpl<const FieldRegion *> *L =
605 Chain.getInternalPointer();
606 printTail(Out, L->getTail());
607 Out << L->getHead()->getDecl()->getNameAsString();
608}
609
610void FieldChainInfo::printTail(
611 llvm::raw_ostream &Out,
612 const llvm::ImmutableListImpl<const FieldRegion *> *L) {
613 if (!L)
614 return;
615
616 printTail(Out, L->getTail());
617 const FieldDecl *Field = L->getHead()->getDecl();
618 Out << Field->getNameAsString();
619 Out << (Field->getType()->isPointerType() ? "->" : ".");
620}
621
622//===----------------------------------------------------------------------===//
623// Utility functions.
624//===----------------------------------------------------------------------===//
625
Kristof Umanncc852442018-07-12 13:13:46 +0000626static bool isVoidPointer(const FieldDecl *FD) {
Kristof Umann30f08652018-06-18 11:50:17 +0000627 QualType T = FD->getType();
628
629 while (!T.isNull()) {
630 if (T->isVoidPointerType())
631 return true;
632 T = T->getPointeeType();
633 }
634 return false;
635}
636
Kristof Umanncc852442018-07-12 13:13:46 +0000637static Optional<nonloc::LazyCompoundVal>
Kristof Umann30f08652018-06-18 11:50:17 +0000638getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context) {
639
640 Loc ThisLoc = Context.getSValBuilder().getCXXThis(CtorDecl->getParent(),
641 Context.getStackFrame());
642 // Getting the value for 'this'.
643 SVal This = Context.getState()->getSVal(ThisLoc);
644
645 // Getting the value for '*this'.
646 SVal Object = Context.getState()->getSVal(This.castAs<Loc>());
647
648 return Object.getAs<nonloc::LazyCompoundVal>();
649}
650
651// TODO: We should also check that if the constructor was called by another
652// constructor, whether those two are in any relation to one another. In it's
653// current state, this introduces some false negatives.
Kristof Umanncc852442018-07-12 13:13:46 +0000654static bool isCalledByConstructor(const CheckerContext &Context) {
Kristof Umann30f08652018-06-18 11:50:17 +0000655 const LocationContext *LC = Context.getLocationContext()->getParent();
656
657 while (LC) {
658 if (isa<CXXConstructorDecl>(LC->getDecl()))
659 return true;
660
661 LC = LC->getParent();
662 }
663 return false;
664}
665
Kristof Umanncc852442018-07-12 13:13:46 +0000666static void printNoteMessage(llvm::raw_ostream &Out,
667 const FieldChainInfo &Chain) {
Kristof Umann9bd44392018-06-29 11:25:24 +0000668 if (Chain.isPointer()) {
669 if (Chain.isDereferenced())
670 Out << "uninitialized pointee 'this->";
671 else
672 Out << "uninitialized pointer 'this->";
673 } else
674 Out << "uninitialized field 'this->";
675 Chain.print(Out);
676 Out << "'";
677}
678
Kristof Umann30f08652018-06-18 11:50:17 +0000679void ento::registerUninitializedObjectChecker(CheckerManager &Mgr) {
680 auto Chk = Mgr.registerChecker<UninitializedObjectChecker>();
681 Chk->IsPedantic = Mgr.getAnalyzerOptions().getBooleanOption(
682 "Pedantic", /*DefaultVal*/ false, Chk);
Kristof Umann9bd44392018-06-29 11:25:24 +0000683 Chk->ShouldConvertNotesToWarnings = Mgr.getAnalyzerOptions().getBooleanOption(
684 "NotesAsWarnings", /*DefaultVal*/ false, Chk);
Kristof Umann30f08652018-06-18 11:50:17 +0000685}