28#include "llvm/ADT/STLExtras.h"
40class UninitializedObjectChecker
41 :
public Checker<check::EndFunction, check::DeadSymbols> {
42 const BugType BT_uninitField{
this,
"Uninitialized fields"};
46 UninitObjCheckerOptions Opts;
48 void checkEndFunction(
const ReturnStmt *RS, CheckerContext &
C)
const;
49 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &
C)
const;
54class RegularField final :
public FieldNode {
56 RegularField(
const FieldRegion *FR) : FieldNode(FR) {}
58 void printNoteMsg(llvm::raw_ostream &Out)
const override {
59 Out <<
"uninitialized field ";
62 void printPrefix(llvm::raw_ostream &Out)
const override {}
64 void printNode(llvm::raw_ostream &Out)
const override {
68 void printSeparator(llvm::raw_ostream &Out)
const override {
Out <<
'.'; }
76 const QualType BaseClassT;
79 BaseClass(
const QualType &
T) : FieldNode(
nullptr), BaseClassT(
T) {
84 void printNoteMsg(llvm::raw_ostream &Out)
const override {
85 llvm_unreachable(
"This node can never be the final node in the "
89 void printPrefix(llvm::raw_ostream &Out)
const override {}
91 void printNode(llvm::raw_ostream &Out)
const override {
92 Out << BaseClassT->getAsCXXRecordDecl()->getName() <<
"::";
95 void printSeparator(llvm::raw_ostream &Out)
const override {}
97 bool isBase()
const override {
return true; }
134void UninitializedObjectChecker::checkEndFunction(
137 const auto *CtorDecl =
138 dyn_cast_or_null<CXXConstructorDecl>(Context.getStackFrame()->getDecl());
142 if (!CtorDecl->isUserProvided())
145 if (CtorDecl->getParent()->isUnion())
156 FindUninitializedFields F(Context.getState(), R, Opts);
158 std::pair<ProgramStateRef, const UninitFieldMap &> UninitInfo =
164 if (UninitFields.empty()) {
165 Context.addTransition(UpdatedState);
171 ExplodedNode *Node = Context.generateNonFatalErrorNode(UpdatedState);
175 PathDiagnosticLocation LocUsedForUniqueing;
176 const Expr *CallSite = Context.getStackFrame()->getCallSite();
184 for (
const auto &Pair : UninitFields) {
186 auto Report = std::make_unique<PathSensitiveBugReport>(
187 BT_uninitField, Pair.second, Node, LocUsedForUniqueing,
189 Context.emitReport(std::move(
Report));
194 SmallString<100> WarningBuf;
195 llvm::raw_svector_ostream WarningOS(WarningBuf);
196 WarningOS << UninitFields.size() <<
" uninitialized field"
197 << (UninitFields.size() == 1 ?
"" :
"s")
198 <<
" at the end of the constructor call";
200 auto Report = std::make_unique<PathSensitiveBugReport>(
201 BT_uninitField, WarningOS.str(), Node, LocUsedForUniqueing,
204 using NoteTy = std::pair<PathDiagnosticLocation, StringRef>;
205 SmallVector<NoteTy> Notes;
207 for (
const auto &[FieldRegion, NoteMsg] : UninitFields) {
209 Notes.emplace_back(FieldLoc, NoteMsg);
213 llvm::sort(Notes, [](
const NoteTy &LHS,
const NoteTy &RHS) {
214 FullSourceLoc L = LHS.first.asLocation();
215 FullSourceLoc
R = RHS.first.asLocation();
222 return LHS.second < RHS.second;
225 for (
const auto &[Loc, NoteMsg] : Notes)
226 Report->addNote(NoteMsg, Loc);
228 Context.emitReport(std::move(
Report));
231void UninitializedObjectChecker::checkDeadSymbols(SymbolReaper &SR,
232 CheckerContext &
C)
const {
234 for (
const MemRegion *R : State->get<AnalyzedRegions>()) {
236 State = State->remove<AnalyzedRegions>(
R);
247 : State(State), ObjectR(R), Opts(Opts) {
254 UninitFields.clear();
257bool FindUninitializedFields::addFieldToUninits(
FieldChainInfo Chain,
262 "One must also pass the pointee region as a parameter for "
263 "dereferenceable fields!");
265 if (State->getStateManager().getContext().getSourceManager().isInSystemHeader(
272 if (State->contains<AnalyzedRegions>(FR))
276 if (State->contains<AnalyzedRegions>(PointeeR)) {
279 State = State->add<AnalyzedRegions>(PointeeR);
282 State = State->add<AnalyzedRegions>(FR);
284 UninitFieldMap::mapped_type NoteMsgBuf;
285 llvm::raw_svector_ostream
OS(NoteMsgBuf);
288 return UninitFields.insert({FR, std::move(NoteMsgBuf)}).second;
293 assert(
R->getValueType()->isRecordType() &&
294 !
R->getValueType()->isUnionType() &&
295 "This method only checks non-union record objects!");
297 const RecordDecl *RD =
R->getValueType()->getAsRecordDecl()->getDefinition();
300 IsAnyFieldInitialized =
true;
304 if (!Opts.IgnoredRecordsWithFieldPattern.empty() &&
306 IsAnyFieldInitialized =
true;
310 bool ContainsUninitField =
false;
313 for (
const FieldDecl *I : RD->
fields()) {
314 if (I->isUnnamedBitField()) {
317 const auto FieldVal =
318 State->getLValue(I, loc::MemRegionVal(R)).castAs<loc::MemRegionVal>();
319 const auto *FR = FieldVal.getRegionAs<FieldRegion>();
320 QualType
T = I->getType();
329 if (isNonUnionUninit(FR, LocalChain.
add(RegularField(FR))))
330 ContainsUninitField =
true;
335 if (isUnionUninit(FR)) {
336 if (addFieldToUninits(LocalChain.
add(RegularField(FR))))
337 ContainsUninitField =
true;
339 IsAnyFieldInitialized =
true;
344 IsAnyFieldInitialized =
true;
348 SVal
V = State->getSVal(FieldVal);
351 if (isDereferencableUninit(FR, LocalChain))
352 ContainsUninitField =
true;
357 if (isPrimitiveUninit(
V)) {
358 if (addFieldToUninits(LocalChain.
add(RegularField(FR))))
359 ContainsUninitField =
true;
364 llvm_unreachable(
"All cases are handled!");
369 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
371 return ContainsUninitField;
373 for (
const CXXBaseSpecifier &BaseSpec : CXXRD->bases()) {
374 const auto *BaseRegion = State->getLValue(BaseSpec, R)
375 .castAs<loc::MemRegionVal>()
376 .getRegionAs<TypedValueRegion>();
381 if (isNonUnionUninit(BaseRegion, LocalChain.
replaceHead(
382 BaseClass(BaseSpec.getType()))))
383 ContainsUninitField =
true;
385 if (isNonUnionUninit(BaseRegion,
386 LocalChain.
add(BaseClass(BaseSpec.getType()))))
387 ContainsUninitField =
true;
391 return ContainsUninitField;
395 assert(
R->getValueType()->isUnionType() &&
396 "This method only checks union objects!");
401bool FindUninitializedFields::isPrimitiveUninit(
SVal V) {
405 IsAnyFieldInitialized =
true;
415 if (Node.isSameRegion(FR))
425static void printTail(llvm::raw_ostream &Out,
451 Node.printPrefix(Out);
466 L.getHead().printNode(Out);
467 L.getHead().printSeparator(Out);
478 Context.getSValBuilder().getCXXThis(CtorDecl, Context.getStackFrame());
479 SVal ObjectV = Context.getState()->getSVal(ThisLoc);
492 return TVR->getValueType()->getAsCXXRecordDecl() ? TVR :
nullptr;
499 auto &MemMgr = Context.getState()->getStateManager().getRegionManager();
500 auto &SVB = Context.getSValBuilder();
502 const auto *ElemR = MemMgr.getElementRegion(
503 ThisPointeeTy, SVB.makeZeroArrayIndex(), SR, Context.getASTContext());
518 Context.getStackFrame()->parents(), [&](
const StackFrame &SF) {
519 const auto *OtherCtor = dyn_cast<CXXConstructorDecl>(SF.getDecl());
523 const SubRegion *OtherRegion =
524 getConstructedSubRegion(OtherCtor, Context);
525 return OtherRegion && CurrRegion->isSubRegionOf(OtherRegion);
530 llvm::Regex R(Pattern);
533 if (R.match(FD->getType().getAsString()))
535 if (R.match(FD->getName()))
557 const auto *Parent = dyn_cast<CXXRecordDecl>(FD->
getParent());
562 Parent = Parent->getDefinition();
563 assert(Parent &&
"The record's definition must be avaible if an uninitialized"
564 " field of it was found!");
566 ASTContext &AC = State->getStateManager().getContext();
571 hasAnyName(
"exit",
"panic",
"error",
"Assert",
"assert",
"ziperr",
572 "assfail",
"db_error",
"__assert",
"__assert2",
"_wassert",
573 "__assert_rtn",
"__assert_fail",
"dtrace_assfail",
574 "yy_fatal_error",
"_XCAssertionFailureHandler",
575 "_DTAssertionFailureHandler",
"_TSAssertionFailureHandler"))));
590 if (Accesses.empty())
592 const auto *FirstAccess = Accesses[0].getNodeAs<
MemberExpr>(
"access");
598 const auto *FirstGuard = Guards[0].getNodeAs<
Stmt>(
"guard");
601 if (FirstAccess->getBeginLoc() < FirstGuard->getBeginLoc())
612 const auto *CXXParent = dyn_cast<CXXRecordDecl>(Field->getParent());
614 if (CXXParent && CXXParent->isLambda()) {
615 assert(CXXParent->captures_begin());
616 auto It = CXXParent->captures_begin() + Field->getFieldIndex();
618 if (It->capturesVariable())
619 return llvm::Twine(
"/*captured variable*/" +
620 It->getCapturedVar()->getName())
623 if (It->capturesThis())
624 return "/*'this' capture*/";
626 llvm_unreachable(
"No other capture type is expected!");
629 return std::string(Field->getName());
632void ento::registerUninitializedObjectChecker(
CheckerManager &Mgr) {
638 ChOpts.
IsPedantic = AnOpts.getCheckerBooleanOption(Chk,
"Pedantic");
640 Chk,
"NotesAsWarnings");
642 Chk,
"CheckPointeeInitialization");
644 std::string(AnOpts.getCheckerStringOption(Chk,
"IgnoreRecordsWithField"));
646 AnOpts.getCheckerBooleanOption(Chk,
"IgnoreGuardedFields");
648 std::string ErrorMsg;
651 "a valid regex, building failed with error message "
652 "\"" + ErrorMsg +
"\"");
655bool ento::shouldRegisterUninitializedObjectChecker(
const CheckerManager &mgr) {
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
static Error printNode(StringRef Id, const MatchFinder::MatchResult &Match, std::string *Result)
static const Stmt * getMethodBody(const CXXMethodDecl *M)
static const TypedValueRegion * getConstructedRegion(const CXXConstructorDecl *CtorDecl, CheckerContext &Context)
Returns the region that was constructed by CtorDecl, or nullptr if that isn't possible.
static bool hasUnguardedAccess(const FieldDecl *FD, ProgramStateRef State)
Checks syntactically whether it is possible to access FD from the record that contains it without a p...
static bool willObjectBeAnalyzedLater(const CXXConstructorDecl *Ctor, CheckerContext &Context)
Checks whether the object constructed by Ctor will be analyzed later (e.g.
static const SubRegion * getConstructedSubRegion(const CXXConstructorDecl *CtorDecl, CheckerContext &Context)
static bool shouldIgnoreRecord(const RecordDecl *RD, StringRef Pattern)
Checks whether RD contains a field with a name or type name that matches Pattern.
static void printTail(llvm::raw_ostream &Out, const FieldChainInfo::FieldChain L)
Prints every element except the last to Out.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
Stores options for the analyzer from the command line.
Represents a C++ constructor within a class.
Represents a static or instance method of a struct/union/class.
QualType getThisType() const
Return the type of the this pointer.
SourceLocation getLocation() const
AccessSpecifier getAccess() const
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
bool isBeforeInTranslationUnitThan(SourceLocation Loc) const
Determines the order of 2 source locations in the translation unit.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
A (possibly-)qualified type.
Represents a struct/union/class.
field_range fields() const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
It represents a stack frame of the call stack.
const Decl * getDecl() const
Stmt - This represents one statement.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isStructureOrClassType() const
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
Simple checker classes that implement one frontend (i.e.
const StackFrame * getStackFrame() const
Represents a field chain.
bool contains(const FieldRegion *FR) const
llvm::ImmutableList< const FieldNode & > FieldChain
const FieldNode & getHead() const
const FieldRegion * getUninitRegion() const
FieldChainInfo replaceHead(const FieldNodeT &FN)
Constructs a new FieldChainInfo object with FN as the new head of the list.
FieldChainInfo add(const FieldNodeT &FN)
Constructs a new FieldChainInfo object with FN appended.
void printNoteMsg(llvm::raw_ostream &Out) const
A lightweight polymorphic wrapper around FieldRegion *.
virtual bool isBase() const
virtual void printNoteMsg(llvm::raw_ostream &Out) const =0
If this is the last element of the fieldchain, this method will print the note message associated wit...
virtual void printNode(llvm::raw_ostream &Out) const =0
Print the node. Should contain the name of the field stored in FR.
LLVM_ATTRIBUTE_RETURNS_NONNULL const FieldDecl * getDecl() const override
FindUninitializedFields(ProgramStateRef State, const TypedValueRegion *const R, const UninitObjCheckerOptions &Opts)
Constructs the FindUninitializedField object, searches for and stores uninitialized fields in R.
bool isAnyFieldInitialized()
Returns whether the analyzed region contains at least one initialized field.
MemRegion - The root abstract class for all memory regions.
const RegionTy * getAs() const
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
const MemRegion * getAsRegion() const
SubRegion - A region that subsets another larger region.
bool isLiveRegion(const MemRegion *region)
TypedValueRegion - An abstract class representing regions having a typed value.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicFunction< internal::Matcher< NamedDecl >, StringRef, internal::hasAnyNameFunc > hasAnyName
Matches NamedDecl nodes that have any of the specified names.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, SwitchStmt > switchStmt
Matches switch statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, MemberExpr > memberExpr
Matches member expressions.
internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher< Decl > > hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, ConditionalOperator > conditionalOperator
Matches conditional operator expressions.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
const internal::VariadicDynCastAllOfMatcher< Stmt, IfStmt > ifStmt
Matches if statements.
std::string getVariableName(const FieldDecl *Field)
Returns with Field's name.
std::map< const FieldRegion *, llvm::SmallString< 50 > > UninitFieldMap
bool isPrimitiveType(const QualType &T)
Returns true if T is a primitive type.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool isDereferencableType(const QualType &T)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
const FunctionProtoType * T
bool ShouldConvertNotesToWarnings
std::string IgnoredRecordsWithFieldPattern
bool CheckPointeeInitialization