blob: 503c03b51985200c76d1453dd061dc61f488bd5b [file] [log] [blame]
Reka Kovacs88ad7042018-07-20 15:14:49 +00001//=== InnerPointerChecker.cpp -------------------------------------*- C++ -*--//
Reka Kovacs18775fc2018-06-09 13:03:49 +00002//
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//
Reka Kovacse453e602018-07-07 19:27:18 +000010// This file defines a check that marks a raw pointer to a C++ container's
11// inner buffer released when the object is destroyed. This information can
12// be used by MallocChecker to detect use-after-free problems.
Reka Kovacs18775fc2018-06-09 13:03:49 +000013//
14//===----------------------------------------------------------------------===//
15
Reka Kovacse453e602018-07-07 19:27:18 +000016#include "AllocationState.h"
Reka Kovacs18775fc2018-06-09 13:03:49 +000017#include "ClangSACheckers.h"
Reka Kovacsd9f66ba2018-08-06 22:03:42 +000018#include "InterCheckerAPI.h"
Reka Kovacs18775fc2018-06-09 13:03:49 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
21#include "clang/StaticAnalyzer/Core/Checker.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Reka Kovacs18775fc2018-06-09 13:03:49 +000024
25using namespace clang;
26using namespace ento;
27
Reka Kovacs5f70d9b2018-07-11 19:08:02 +000028// Associate container objects with a set of raw pointer symbols.
Simon Pilgrim8d5f1012018-09-26 09:12:55 +000029REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(PtrSet, SymbolRef)
Reka Kovacs5f70d9b2018-07-11 19:08:02 +000030REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, PtrSet)
31
Reka Kovacse453e602018-07-07 19:27:18 +000032
Reka Kovacs18775fc2018-06-09 13:03:49 +000033namespace {
34
Reka Kovacs88ad7042018-07-20 15:14:49 +000035class InnerPointerChecker
Reka Kovacse453e602018-07-07 19:27:18 +000036 : public Checker<check::DeadSymbols, check::PostCall> {
Reka Kovacsc18ecc82018-07-19 15:10:06 +000037
38 CallDescription AppendFn, AssignFn, ClearFn, CStrFn, DataFn, EraseFn,
39 InsertFn, PopBackFn, PushBackFn, ReplaceFn, ReserveFn, ResizeFn,
40 ShrinkToFitFn, SwapFn;
Reka Kovacs18775fc2018-06-09 13:03:49 +000041
42public:
Reka Kovacs88ad7042018-07-20 15:14:49 +000043 class InnerPointerBRVisitor : public BugReporterVisitor {
Reka Kovacse453e602018-07-07 19:27:18 +000044 SymbolRef PtrToBuf;
45
46 public:
Reka Kovacs88ad7042018-07-20 15:14:49 +000047 InnerPointerBRVisitor(SymbolRef Sym) : PtrToBuf(Sym) {}
Reka Kovacse453e602018-07-07 19:27:18 +000048
49 static void *getTag() {
50 static int Tag = 0;
51 return &Tag;
52 }
53
54 void Profile(llvm::FoldingSetNodeID &ID) const override {
55 ID.AddPointer(getTag());
56 }
57
58 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
59 const ExplodedNode *PrevN,
60 BugReporterContext &BRC,
61 BugReport &BR) override;
62
63 // FIXME: Scan the map once in the visitor's constructor and do a direct
64 // lookup by region.
65 bool isSymbolTracked(ProgramStateRef State, SymbolRef Sym) {
66 RawPtrMapTy Map = State->get<RawPtrMap>();
67 for (const auto Entry : Map) {
Reka Kovacs5f70d9b2018-07-11 19:08:02 +000068 if (Entry.second.contains(Sym))
Reka Kovacse453e602018-07-07 19:27:18 +000069 return true;
70 }
71 return false;
72 }
73 };
74
Reka Kovacs88ad7042018-07-20 15:14:49 +000075 InnerPointerChecker()
Henry Wong2ca72e02018-08-22 13:30:46 +000076 : AppendFn({"std", "basic_string", "append"}),
77 AssignFn({"std", "basic_string", "assign"}),
78 ClearFn({"std", "basic_string", "clear"}),
79 CStrFn({"std", "basic_string", "c_str"}),
80 DataFn({"std", "basic_string", "data"}),
81 EraseFn({"std", "basic_string", "erase"}),
82 InsertFn({"std", "basic_string", "insert"}),
83 PopBackFn({"std", "basic_string", "pop_back"}),
84 PushBackFn({"std", "basic_string", "push_back"}),
85 ReplaceFn({"std", "basic_string", "replace"}),
86 ReserveFn({"std", "basic_string", "reserve"}),
87 ResizeFn({"std", "basic_string", "resize"}),
88 ShrinkToFitFn({"std", "basic_string", "shrink_to_fit"}),
89 SwapFn({"std", "basic_string", "swap"}) {}
Reka Kovacs18775fc2018-06-09 13:03:49 +000090
Reka Kovacsc74cfc42018-07-30 15:43:45 +000091 /// Check whether the called member function potentially invalidates
92 /// pointers referring to the container object's inner buffer.
93 bool isInvalidatingMemberFunction(const CallEvent &Call) const;
94
95 /// Mark pointer symbols associated with the given memory region released
96 /// in the program state.
97 void markPtrSymbolsReleased(const CallEvent &Call, ProgramStateRef State,
98 const MemRegion *ObjRegion,
99 CheckerContext &C) const;
100
101 /// Standard library functions that take a non-const `basic_string` argument by
102 /// reference may invalidate its inner pointers. Check for these cases and
103 /// mark the pointers released.
104 void checkFunctionArguments(const CallEvent &Call, ProgramStateRef State,
105 CheckerContext &C) const;
106
107 /// Record the connection between raw pointers referring to a container
108 /// object's inner buffer and the object's memory region in the program state.
109 /// Mark potentially invalidated pointers released.
Reka Kovacs18775fc2018-06-09 13:03:49 +0000110 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000111
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000112 /// Clean up the program state map.
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000113 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Reka Kovacs18775fc2018-06-09 13:03:49 +0000114};
115
116} // end anonymous namespace
117
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000118bool InnerPointerChecker::isInvalidatingMemberFunction(
119 const CallEvent &Call) const {
Reka Kovacsc18ecc82018-07-19 15:10:06 +0000120 if (const auto *MemOpCall = dyn_cast<CXXMemberOperatorCall>(&Call)) {
121 OverloadedOperatorKind Opc = MemOpCall->getOriginExpr()->getOperator();
122 if (Opc == OO_Equal || Opc == OO_PlusEqual)
123 return true;
124 return false;
125 }
126 return (isa<CXXDestructorCall>(Call) || Call.isCalled(AppendFn) ||
127 Call.isCalled(AssignFn) || Call.isCalled(ClearFn) ||
128 Call.isCalled(EraseFn) || Call.isCalled(InsertFn) ||
129 Call.isCalled(PopBackFn) || Call.isCalled(PushBackFn) ||
130 Call.isCalled(ReplaceFn) || Call.isCalled(ReserveFn) ||
131 Call.isCalled(ResizeFn) || Call.isCalled(ShrinkToFitFn) ||
132 Call.isCalled(SwapFn));
133}
134
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000135void InnerPointerChecker::markPtrSymbolsReleased(const CallEvent &Call,
136 ProgramStateRef State,
137 const MemRegion *MR,
138 CheckerContext &C) const {
139 if (const PtrSet *PS = State->get<RawPtrMap>(MR)) {
140 const Expr *Origin = Call.getOriginExpr();
141 for (const auto Symbol : *PS) {
142 // NOTE: `Origin` may be null, and will be stored so in the symbol's
143 // `RefState` in MallocChecker's `RegionState` program state map.
144 State = allocation_state::markReleased(State, Symbol, Origin);
145 }
146 State = State->remove<RawPtrMap>(MR);
147 C.addTransition(State);
148 return;
149 }
150}
151
152void InnerPointerChecker::checkFunctionArguments(const CallEvent &Call,
153 ProgramStateRef State,
154 CheckerContext &C) const {
155 if (const auto *FC = dyn_cast<AnyFunctionCall>(&Call)) {
156 const FunctionDecl *FD = FC->getDecl();
157 if (!FD || !FD->isInStdNamespace())
158 return;
159
160 for (unsigned I = 0, E = FD->getNumParams(); I != E; ++I) {
161 QualType ParamTy = FD->getParamDecl(I)->getType();
162 if (!ParamTy->isReferenceType() ||
163 ParamTy->getPointeeType().isConstQualified())
164 continue;
165
166 // In case of member operator calls, `this` is counted as an
167 // argument but not as a parameter.
168 bool isaMemberOpCall = isa<CXXMemberOperatorCall>(FC);
169 unsigned ArgI = isaMemberOpCall ? I+1 : I;
170
171 SVal Arg = FC->getArgSVal(ArgI);
172 const auto *ArgRegion =
173 dyn_cast_or_null<TypedValueRegion>(Arg.getAsRegion());
174 if (!ArgRegion)
175 continue;
176
177 markPtrSymbolsReleased(Call, State, ArgRegion, C);
178 }
179 }
180}
181
182// [string.require]
183//
184// "References, pointers, and iterators referring to the elements of a
185// basic_string sequence may be invalidated by the following uses of that
186// basic_string object:
187//
188// -- As an argument to any standard library function taking a reference
189// to non-const basic_string as an argument. For example, as an argument to
190// non-member functions swap(), operator>>(), and getline(), or as an argument
191// to basic_string::swap().
192//
193// -- Calling non-const member functions, except operator[], at, front, back,
194// begin, rbegin, end, and rend."
195
Reka Kovacs88ad7042018-07-20 15:14:49 +0000196void InnerPointerChecker::checkPostCall(const CallEvent &Call,
197 CheckerContext &C) const {
Reka Kovacs18775fc2018-06-09 13:03:49 +0000198 ProgramStateRef State = C.getState();
199
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000200 if (const auto *ICall = dyn_cast<CXXInstanceCall>(&Call)) {
Artem Dergachev73b38662018-08-30 18:45:05 +0000201 // TODO: Do we need these to be typed?
Henry Wong2ca72e02018-08-22 13:30:46 +0000202 const auto *ObjRegion = dyn_cast_or_null<TypedValueRegion>(
203 ICall->getCXXThisVal().getAsRegion());
Artem Dergachev73b38662018-08-30 18:45:05 +0000204 if (!ObjRegion)
205 return;
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000206
Henry Wong2ca72e02018-08-22 13:30:46 +0000207 if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) {
208 SVal RawPtr = Call.getReturnValue();
209 if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) {
210 // Start tracking this raw pointer by adding it to the set of symbols
211 // associated with this container object in the program state map.
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000212
Henry Wong2ca72e02018-08-22 13:30:46 +0000213 PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>();
214 const PtrSet *SetPtr = State->get<RawPtrMap>(ObjRegion);
215 PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet();
216 assert(C.wasInlined || !Set.contains(Sym));
217 Set = F.add(Set, Sym);
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000218
Henry Wong2ca72e02018-08-22 13:30:46 +0000219 State = State->set<RawPtrMap>(ObjRegion, Set);
220 C.addTransition(State);
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000221 }
Henry Wong2ca72e02018-08-22 13:30:46 +0000222 return;
223 }
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000224
Henry Wong2ca72e02018-08-22 13:30:46 +0000225 // Check [string.require] / second point.
226 if (isInvalidatingMemberFunction(Call)) {
227 markPtrSymbolsReleased(Call, State, ObjRegion, C);
228 return;
Reka Kovacs18775fc2018-06-09 13:03:49 +0000229 }
Reka Kovacs18775fc2018-06-09 13:03:49 +0000230 }
231
Reka Kovacsc74cfc42018-07-30 15:43:45 +0000232 // Check [string.require] / first point.
233 checkFunctionArguments(Call, State, C);
Reka Kovacs18775fc2018-06-09 13:03:49 +0000234}
235
Reka Kovacs88ad7042018-07-20 15:14:49 +0000236void InnerPointerChecker::checkDeadSymbols(SymbolReaper &SymReaper,
237 CheckerContext &C) const {
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000238 ProgramStateRef State = C.getState();
Reka Kovacs5f70d9b2018-07-11 19:08:02 +0000239 PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>();
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000240 RawPtrMapTy RPM = State->get<RawPtrMap>();
241 for (const auto Entry : RPM) {
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000242 if (!SymReaper.isLiveRegion(Entry.first)) {
Reka Kovacs5f70d9b2018-07-11 19:08:02 +0000243 // Due to incomplete destructor support, some dead regions might
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000244 // remain in the program state map. Clean them up.
245 State = State->remove<RawPtrMap>(Entry.first);
246 }
Reka Kovacs5f70d9b2018-07-11 19:08:02 +0000247 if (const PtrSet *OldSet = State->get<RawPtrMap>(Entry.first)) {
248 PtrSet CleanedUpSet = *OldSet;
249 for (const auto Symbol : Entry.second) {
250 if (!SymReaper.isLive(Symbol))
251 CleanedUpSet = F.remove(CleanedUpSet, Symbol);
252 }
253 State = CleanedUpSet.isEmpty()
Reka Kovacsc18ecc82018-07-19 15:10:06 +0000254 ? State->remove<RawPtrMap>(Entry.first)
255 : State->set<RawPtrMap>(Entry.first, CleanedUpSet);
Reka Kovacs5f70d9b2018-07-11 19:08:02 +0000256 }
Reka Kovacs7ff6a8a2018-06-09 21:08:27 +0000257 }
258 C.addTransition(State);
259}
260
Reka Kovacsbb2749a2018-08-10 23:56:57 +0000261namespace clang {
262namespace ento {
263namespace allocation_state {
264
265std::unique_ptr<BugReporterVisitor> getInnerPointerBRVisitor(SymbolRef Sym) {
266 return llvm::make_unique<InnerPointerChecker::InnerPointerBRVisitor>(Sym);
267}
268
269const MemRegion *getContainerObjRegion(ProgramStateRef State, SymbolRef Sym) {
270 RawPtrMapTy Map = State->get<RawPtrMap>();
271 for (const auto Entry : Map) {
272 if (Entry.second.contains(Sym)) {
273 return Entry.first;
274 }
275 }
276 return nullptr;
277}
278
279} // end namespace allocation_state
280} // end namespace ento
281} // end namespace clang
282
Reka Kovacse453e602018-07-07 19:27:18 +0000283std::shared_ptr<PathDiagnosticPiece>
Reka Kovacs88ad7042018-07-20 15:14:49 +0000284InnerPointerChecker::InnerPointerBRVisitor::VisitNode(const ExplodedNode *N,
285 const ExplodedNode *PrevN,
286 BugReporterContext &BRC,
287 BugReport &BR) {
Reka Kovacse453e602018-07-07 19:27:18 +0000288 if (!isSymbolTracked(N->getState(), PtrToBuf) ||
289 isSymbolTracked(PrevN->getState(), PtrToBuf))
290 return nullptr;
291
292 const Stmt *S = PathDiagnosticLocation::getStmt(N);
293 if (!S)
294 return nullptr;
295
Reka Kovacsbb2749a2018-08-10 23:56:57 +0000296 const MemRegion *ObjRegion =
297 allocation_state::getContainerObjRegion(N->getState(), PtrToBuf);
298 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
299 QualType ObjTy = TypedRegion->getValueType();
300
Reka Kovacse453e602018-07-07 19:27:18 +0000301 SmallString<256> Buf;
302 llvm::raw_svector_ostream OS(Buf);
Reka Kovacsbb2749a2018-08-10 23:56:57 +0000303 OS << "Pointer to inner buffer of '" << ObjTy.getAsString()
304 << "' obtained here";
Reka Kovacse453e602018-07-07 19:27:18 +0000305 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
306 N->getLocationContext());
307 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true,
308 nullptr);
309}
310
Reka Kovacs88ad7042018-07-20 15:14:49 +0000311void ento::registerInnerPointerChecker(CheckerManager &Mgr) {
Reka Kovacsd9f66ba2018-08-06 22:03:42 +0000312 registerInnerPointerCheckerAux(Mgr);
Reka Kovacs88ad7042018-07-20 15:14:49 +0000313 Mgr.registerChecker<InnerPointerChecker>();
Reka Kovacs18775fc2018-06-09 13:03:49 +0000314}