1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- 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 malloc/free checker, which checks for potential memory
11 // leaks, double free, and use-after-free problems.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ClangSACheckers.h"
16 #include "InterCheckerAPI.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include <climits>
34
35 using namespace clang;
36 using namespace ento;
37
38 namespace {
39
40 // Used to check correspondence between allocators and deallocators.
41 enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
45 AF_CXXNewArray,
46 AF_IfNameIndex,
47 AF_Alloca
48 };
49
50 class RefState {
51 enum Kind { // Reference to allocated memory.
52 Allocated,
53 // Reference to zero-allocated memory.
54 AllocatedOfSizeZero,
55 // Reference to released/freed memory.
56 Released,
57 // The responsibility for freeing resources has transferred from
58 // this reference. A relinquished symbol should not be freed.
59 Relinquished,
60 // We are no longer guaranteed to have observed all manipulations
61 // of this pointer/memory. For example, it could have been
62 // passed as a parameter to an opaque function.
63 Escaped
64 };
65
66 const Stmt *S;
67 unsigned K : 3; // Kind enum, but stored as a bitfield.
68 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
69 // family.
70
RefState(Kind k,const Stmt * s,unsigned family)71 RefState(Kind k, const Stmt *s, unsigned family)
72 : S(s), K(k), Family(family) {
73 assert(family != AF_None);
74 }
75 public:
isAllocated() const76 bool isAllocated() const { return K == Allocated; }
isAllocatedOfSizeZero() const77 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
isReleased() const78 bool isReleased() const { return K == Released; }
isRelinquished() const79 bool isRelinquished() const { return K == Relinquished; }
isEscaped() const80 bool isEscaped() const { return K == Escaped; }
getAllocationFamily() const81 AllocationFamily getAllocationFamily() const {
82 return (AllocationFamily)Family;
83 }
getStmt() const84 const Stmt *getStmt() const { return S; }
85
operator ==(const RefState & X) const86 bool operator==(const RefState &X) const {
87 return K == X.K && S == X.S && Family == X.Family;
88 }
89
getAllocated(unsigned family,const Stmt * s)90 static RefState getAllocated(unsigned family, const Stmt *s) {
91 return RefState(Allocated, s, family);
92 }
getAllocatedOfSizeZero(const RefState * RS)93 static RefState getAllocatedOfSizeZero(const RefState *RS) {
94 return RefState(AllocatedOfSizeZero, RS->getStmt(),
95 RS->getAllocationFamily());
96 }
getReleased(unsigned family,const Stmt * s)97 static RefState getReleased(unsigned family, const Stmt *s) {
98 return RefState(Released, s, family);
99 }
getRelinquished(unsigned family,const Stmt * s)100 static RefState getRelinquished(unsigned family, const Stmt *s) {
101 return RefState(Relinquished, s, family);
102 }
getEscaped(const RefState * RS)103 static RefState getEscaped(const RefState *RS) {
104 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
105 }
106
Profile(llvm::FoldingSetNodeID & ID) const107 void Profile(llvm::FoldingSetNodeID &ID) const {
108 ID.AddInteger(K);
109 ID.AddPointer(S);
110 ID.AddInteger(Family);
111 }
112
dump(raw_ostream & OS) const113 void dump(raw_ostream &OS) const {
114 switch (static_cast<Kind>(K)) {
115 #define CASE(ID) case ID: OS << #ID; break;
116 CASE(Allocated)
117 CASE(AllocatedOfSizeZero)
118 CASE(Released)
119 CASE(Relinquished)
120 CASE(Escaped)
121 }
122 }
123
dump() const124 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
125 };
126
127 enum ReallocPairKind {
128 RPToBeFreedAfterFailure,
129 // The symbol has been freed when reallocation failed.
130 RPIsFreeOnFailure,
131 // The symbol does not need to be freed after reallocation fails.
132 RPDoNotTrackAfterFailure
133 };
134
135 /// \class ReallocPair
136 /// \brief Stores information about the symbol being reallocated by a call to
137 /// 'realloc' to allow modeling failed reallocation later in the path.
138 struct ReallocPair {
139 // \brief The symbol which realloc reallocated.
140 SymbolRef ReallocatedSym;
141 ReallocPairKind Kind;
142
ReallocPair__anone8977cbd0111::ReallocPair143 ReallocPair(SymbolRef S, ReallocPairKind K) :
144 ReallocatedSym(S), Kind(K) {}
Profile__anone8977cbd0111::ReallocPair145 void Profile(llvm::FoldingSetNodeID &ID) const {
146 ID.AddInteger(Kind);
147 ID.AddPointer(ReallocatedSym);
148 }
operator ==__anone8977cbd0111::ReallocPair149 bool operator==(const ReallocPair &X) const {
150 return ReallocatedSym == X.ReallocatedSym &&
151 Kind == X.Kind;
152 }
153 };
154
155 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
156
157 class MallocChecker : public Checker<check::DeadSymbols,
158 check::PointerEscape,
159 check::ConstPointerEscape,
160 check::PreStmt<ReturnStmt>,
161 check::PreCall,
162 check::PostStmt<CallExpr>,
163 check::PostStmt<CXXNewExpr>,
164 check::PreStmt<CXXDeleteExpr>,
165 check::PostStmt<BlockExpr>,
166 check::PostObjCMessage,
167 check::Location,
168 eval::Assume>
169 {
170 public:
MallocChecker()171 MallocChecker()
172 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
173 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
174 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
175 II_kmalloc(nullptr), II_if_nameindex(nullptr),
176 II_if_freenameindex(nullptr) {}
177
178 /// In pessimistic mode, the checker assumes that it does not know which
179 /// functions might free the memory.
180 enum CheckKind {
181 CK_MallocChecker,
182 CK_NewDeleteChecker,
183 CK_NewDeleteLeaksChecker,
184 CK_MismatchedDeallocatorChecker,
185 CK_NumCheckKinds
186 };
187
188 enum class MemoryOperationKind {
189 MOK_Allocate,
190 MOK_Free,
191 MOK_Any
192 };
193
194 DefaultBool IsOptimistic;
195
196 DefaultBool ChecksEnabled[CK_NumCheckKinds];
197 CheckName CheckNames[CK_NumCheckKinds];
198
199 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
200 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
201 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
202 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
203 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
204 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
205 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
206 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
207 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
208 bool Assumption) const;
209 void checkLocation(SVal l, bool isLoad, const Stmt *S,
210 CheckerContext &C) const;
211
212 ProgramStateRef checkPointerEscape(ProgramStateRef State,
213 const InvalidatedSymbols &Escaped,
214 const CallEvent *Call,
215 PointerEscapeKind Kind) const;
216 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
220
221 void printState(raw_ostream &Out, ProgramStateRef State,
222 const char *NL, const char *Sep) const override;
223
224 private:
225 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
226 mutable std::unique_ptr<BugType> BT_DoubleDelete;
227 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
228 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
229 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
230 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
231 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
232 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
234 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
235 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
236 *II_strdup, *II_kmalloc, *II_if_nameindex,
237 *II_if_freenameindex;
238 mutable Optional<uint64_t> KernelZeroFlagVal;
239
240 void initIdentifierInfo(ASTContext &C) const;
241
242 /// \brief Determine family of a deallocation expression.
243 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
244
245 /// \brief Print names of allocators and deallocators.
246 ///
247 /// \returns true on success.
248 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
249 const Expr *E) const;
250
251 /// \brief Print expected name of an allocator based on the deallocator's
252 /// family derived from the DeallocExpr.
253 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
254 const Expr *DeallocExpr) const;
255 /// \brief Print expected name of a deallocator based on the allocator's
256 /// family.
257 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
258
259 ///@{
260 /// Check if this is one of the functions which can allocate/reallocate memory
261 /// pointed to by one of its arguments.
262 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
263 bool isCMemFunction(const FunctionDecl *FD,
264 ASTContext &C,
265 AllocationFamily Family,
266 MemoryOperationKind MemKind) const;
267 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
268 ///@}
269
270 /// \brief Perform a zero-allocation check.
271 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
272 const unsigned AllocationSizeArg,
273 ProgramStateRef State) const;
274
275 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
276 const CallExpr *CE,
277 const OwnershipAttr* Att,
278 ProgramStateRef State) const;
279 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
280 const Expr *SizeEx, SVal Init,
281 ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
283 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
284 SVal SizeEx, SVal Init,
285 ProgramStateRef State,
286 AllocationFamily Family = AF_Malloc);
287
288 // Check if this malloc() for special flags. At present that means M_ZERO or
289 // __GFP_ZERO (in which case, treat it like calloc).
290 llvm::Optional<ProgramStateRef>
291 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
292 const ProgramStateRef &State) const;
293
294 /// Update the RefState to reflect the new memory allocation.
295 static ProgramStateRef
296 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
297 AllocationFamily Family = AF_Malloc);
298
299 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
300 const OwnershipAttr* Att,
301 ProgramStateRef State) const;
302 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
303 ProgramStateRef state, unsigned Num,
304 bool Hold,
305 bool &ReleasedAllocated,
306 bool ReturnsNullOnFailure = false) const;
307 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
308 const Expr *ParentExpr,
309 ProgramStateRef State,
310 bool Hold,
311 bool &ReleasedAllocated,
312 bool ReturnsNullOnFailure = false) const;
313
314 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
315 bool FreesMemOnFailure,
316 ProgramStateRef State) const;
317 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
318 ProgramStateRef State);
319
320 ///\brief Check if the memory associated with this symbol was released.
321 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
322
323 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
324
325 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
326 const Stmt *S) const;
327
328 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
329
330 /// Check if the function is known free memory, or if it is
331 /// "interesting" and should be modeled explicitly.
332 ///
333 /// \param [out] EscapingSymbol A function might not free memory in general,
334 /// but could be known to free a particular symbol. In this case, false is
335 /// returned and the single escaping symbol is returned through the out
336 /// parameter.
337 ///
338 /// We assume that pointers do not escape through calls to system functions
339 /// not handled by this checker.
340 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
341 ProgramStateRef State,
342 SymbolRef &EscapingSymbol) const;
343
344 // Implementation of the checkPointerEscape callabcks.
345 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
346 const InvalidatedSymbols &Escaped,
347 const CallEvent *Call,
348 PointerEscapeKind Kind,
349 bool(*CheckRefState)(const RefState*)) const;
350
351 ///@{
352 /// Tells if a given family/call/symbol is tracked by the current checker.
353 /// Sets CheckKind to the kind of the checker responsible for this
354 /// family/call/symbol.
355 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
356 bool IsALeakCheck = false) const;
357 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
358 const Stmt *AllocDeallocStmt,
359 bool IsALeakCheck = false) const;
360 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
361 bool IsALeakCheck = false) const;
362 ///@}
363 static bool SummarizeValue(raw_ostream &os, SVal V);
364 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
365 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
366 const Expr *DeallocExpr) const;
367 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
368 SourceRange Range) const;
369 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
370 const Expr *DeallocExpr, const RefState *RS,
371 SymbolRef Sym, bool OwnershipTransferred) const;
372 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
373 const Expr *DeallocExpr,
374 const Expr *AllocExpr = nullptr) const;
375 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
376 SymbolRef Sym) const;
377 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
378 SymbolRef Sym, SymbolRef PrevSym) const;
379
380 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
381
382 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
383 SymbolRef Sym) const;
384
385 /// Find the location of the allocation for Sym on the path leading to the
386 /// exploded node N.
387 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
388 CheckerContext &C) const;
389
390 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
391
392 /// The bug visitor which allows us to print extra diagnostics along the
393 /// BugReport path. For example, showing the allocation site of the leaked
394 /// region.
395 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
396 protected:
397 enum NotificationMode {
398 Normal,
399 ReallocationFailed
400 };
401
402 // The allocated region symbol tracked by the main analysis.
403 SymbolRef Sym;
404
405 // The mode we are in, i.e. what kind of diagnostics will be emitted.
406 NotificationMode Mode;
407
408 // A symbol from when the primary region should have been reallocated.
409 SymbolRef FailedReallocSymbol;
410
411 bool IsLeak;
412
413 public:
MallocBugVisitor(SymbolRef S,bool isLeak=false)414 MallocBugVisitor(SymbolRef S, bool isLeak = false)
415 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
416
~MallocBugVisitor()417 ~MallocBugVisitor() override {}
418
Profile(llvm::FoldingSetNodeID & ID) const419 void Profile(llvm::FoldingSetNodeID &ID) const override {
420 static int X = 0;
421 ID.AddPointer(&X);
422 ID.AddPointer(Sym);
423 }
424
isAllocated(const RefState * S,const RefState * SPrev,const Stmt * Stmt)425 inline bool isAllocated(const RefState *S, const RefState *SPrev,
426 const Stmt *Stmt) {
427 // Did not track -> allocated. Other state (released) -> allocated.
428 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
429 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
430 (!SPrev || !(SPrev->isAllocated() ||
431 SPrev->isAllocatedOfSizeZero())));
432 }
433
isReleased(const RefState * S,const RefState * SPrev,const Stmt * Stmt)434 inline bool isReleased(const RefState *S, const RefState *SPrev,
435 const Stmt *Stmt) {
436 // Did not track -> released. Other state (allocated) -> released.
437 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
438 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
439 }
440
isRelinquished(const RefState * S,const RefState * SPrev,const Stmt * Stmt)441 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
442 const Stmt *Stmt) {
443 // Did not track -> relinquished. Other state (allocated) -> relinquished.
444 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
445 isa<ObjCPropertyRefExpr>(Stmt)) &&
446 (S && S->isRelinquished()) &&
447 (!SPrev || !SPrev->isRelinquished()));
448 }
449
isReallocFailedCheck(const RefState * S,const RefState * SPrev,const Stmt * Stmt)450 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
451 const Stmt *Stmt) {
452 // If the expression is not a call, and the state change is
453 // released -> allocated, it must be the realloc return value
454 // check. If we have to handle more cases here, it might be cleaner just
455 // to track this extra bit in the state itself.
456 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
457 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
458 (SPrev && !(SPrev->isAllocated() ||
459 SPrev->isAllocatedOfSizeZero())));
460 }
461
462 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
463 const ExplodedNode *PrevN,
464 BugReporterContext &BRC,
465 BugReport &BR) override;
466
467 std::unique_ptr<PathDiagnosticPiece>
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndPathNode,BugReport & BR)468 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
469 BugReport &BR) override {
470 if (!IsLeak)
471 return nullptr;
472
473 PathDiagnosticLocation L =
474 PathDiagnosticLocation::createEndOfPath(EndPathNode,
475 BRC.getSourceManager());
476 // Do not add the statement itself as a range in case of leak.
477 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
478 false);
479 }
480
481 private:
482 class StackHintGeneratorForReallocationFailed
483 : public StackHintGeneratorForSymbol {
484 public:
StackHintGeneratorForReallocationFailed(SymbolRef S,StringRef M)485 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
486 : StackHintGeneratorForSymbol(S, M) {}
487
getMessageForArg(const Expr * ArgE,unsigned ArgIndex)488 std::string getMessageForArg(const Expr *ArgE,
489 unsigned ArgIndex) override {
490 // Printed parameters start at 1, not 0.
491 ++ArgIndex;
492
493 SmallString<200> buf;
494 llvm::raw_svector_ostream os(buf);
495
496 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
497 << " parameter failed";
498
499 return os.str();
500 }
501
getMessageForReturn(const CallExpr * CallExpr)502 std::string getMessageForReturn(const CallExpr *CallExpr) override {
503 return "Reallocation of returned value failed";
504 }
505 };
506 };
507 };
508 } // end anonymous namespace
509
510 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
511 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
512
513 // A map from the freed symbol to the symbol representing the return value of
514 // the free function.
515 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
516
517 namespace {
518 class StopTrackingCallback : public SymbolVisitor {
519 ProgramStateRef state;
520 public:
StopTrackingCallback(ProgramStateRef st)521 StopTrackingCallback(ProgramStateRef st) : state(st) {}
getState() const522 ProgramStateRef getState() const { return state; }
523
VisitSymbol(SymbolRef sym)524 bool VisitSymbol(SymbolRef sym) override {
525 state = state->remove<RegionState>(sym);
526 return true;
527 }
528 };
529 } // end anonymous namespace
530
initIdentifierInfo(ASTContext & Ctx) const531 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
532 if (II_malloc)
533 return;
534 II_alloca = &Ctx.Idents.get("alloca");
535 II_malloc = &Ctx.Idents.get("malloc");
536 II_free = &Ctx.Idents.get("free");
537 II_realloc = &Ctx.Idents.get("realloc");
538 II_reallocf = &Ctx.Idents.get("reallocf");
539 II_calloc = &Ctx.Idents.get("calloc");
540 II_valloc = &Ctx.Idents.get("valloc");
541 II_strdup = &Ctx.Idents.get("strdup");
542 II_strndup = &Ctx.Idents.get("strndup");
543 II_kmalloc = &Ctx.Idents.get("kmalloc");
544 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
545 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
546 }
547
isMemFunction(const FunctionDecl * FD,ASTContext & C) const548 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
549 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
550 return true;
551
552 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
553 return true;
554
555 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
556 return true;
557
558 if (isStandardNewDelete(FD, C))
559 return true;
560
561 return false;
562 }
563
isCMemFunction(const FunctionDecl * FD,ASTContext & C,AllocationFamily Family,MemoryOperationKind MemKind) const564 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
565 ASTContext &C,
566 AllocationFamily Family,
567 MemoryOperationKind MemKind) const {
568 if (!FD)
569 return false;
570
571 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
572 MemKind == MemoryOperationKind::MOK_Free);
573 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
574 MemKind == MemoryOperationKind::MOK_Allocate);
575
576 if (FD->getKind() == Decl::Function) {
577 const IdentifierInfo *FunI = FD->getIdentifier();
578 initIdentifierInfo(C);
579
580 if (Family == AF_Malloc && CheckFree) {
581 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
582 return true;
583 }
584
585 if (Family == AF_Malloc && CheckAlloc) {
586 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
587 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
588 FunI == II_strndup || FunI == II_kmalloc)
589 return true;
590 }
591
592 if (Family == AF_IfNameIndex && CheckFree) {
593 if (FunI == II_if_freenameindex)
594 return true;
595 }
596
597 if (Family == AF_IfNameIndex && CheckAlloc) {
598 if (FunI == II_if_nameindex)
599 return true;
600 }
601
602 if (Family == AF_Alloca && CheckAlloc) {
603 if (FunI == II_alloca)
604 return true;
605 }
606 }
607
608 if (Family != AF_Malloc)
609 return false;
610
611 if (IsOptimistic && FD->hasAttrs()) {
612 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
613 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
614 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
615 if (CheckFree)
616 return true;
617 } else if (OwnKind == OwnershipAttr::Returns) {
618 if (CheckAlloc)
619 return true;
620 }
621 }
622 }
623
624 return false;
625 }
626
627 // Tells if the callee is one of the following:
628 // 1) A global non-placement new/delete operator function.
629 // 2) A global placement operator function with the single placement argument
630 // of type std::nothrow_t.
isStandardNewDelete(const FunctionDecl * FD,ASTContext & C) const631 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
632 ASTContext &C) const {
633 if (!FD)
634 return false;
635
636 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
637 if (Kind != OO_New && Kind != OO_Array_New &&
638 Kind != OO_Delete && Kind != OO_Array_Delete)
639 return false;
640
641 // Skip all operator new/delete methods.
642 if (isa<CXXMethodDecl>(FD))
643 return false;
644
645 // Return true if tested operator is a standard placement nothrow operator.
646 if (FD->getNumParams() == 2) {
647 QualType T = FD->getParamDecl(1)->getType();
648 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
649 return II->getName().equals("nothrow_t");
650 }
651
652 // Skip placement operators.
653 if (FD->getNumParams() != 1 || FD->isVariadic())
654 return false;
655
656 // One of the standard new/new[]/delete/delete[] non-placement operators.
657 return true;
658 }
659
performKernelMalloc(const CallExpr * CE,CheckerContext & C,const ProgramStateRef & State) const660 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
661 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
662 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
663 //
664 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
665 //
666 // One of the possible flags is M_ZERO, which means 'give me back an
667 // allocation which is already zeroed', like calloc.
668
669 // 2-argument kmalloc(), as used in the Linux kernel:
670 //
671 // void *kmalloc(size_t size, gfp_t flags);
672 //
673 // Has the similar flag value __GFP_ZERO.
674
675 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
676 // code could be shared.
677
678 ASTContext &Ctx = C.getASTContext();
679 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
680
681 if (!KernelZeroFlagVal.hasValue()) {
682 if (OS == llvm::Triple::FreeBSD)
683 KernelZeroFlagVal = 0x0100;
684 else if (OS == llvm::Triple::NetBSD)
685 KernelZeroFlagVal = 0x0002;
686 else if (OS == llvm::Triple::OpenBSD)
687 KernelZeroFlagVal = 0x0008;
688 else if (OS == llvm::Triple::Linux)
689 // __GFP_ZERO
690 KernelZeroFlagVal = 0x8000;
691 else
692 // FIXME: We need a more general way of getting the M_ZERO value.
693 // See also: O_CREAT in UnixAPIChecker.cpp.
694
695 // Fall back to normal malloc behavior on platforms where we don't
696 // know M_ZERO.
697 return None;
698 }
699
700 // We treat the last argument as the flags argument, and callers fall-back to
701 // normal malloc on a None return. This works for the FreeBSD kernel malloc
702 // as well as Linux kmalloc.
703 if (CE->getNumArgs() < 2)
704 return None;
705
706 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
707 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
708 if (!V.getAs<NonLoc>()) {
709 // The case where 'V' can be a location can only be due to a bad header,
710 // so in this case bail out.
711 return None;
712 }
713
714 NonLoc Flags = V.castAs<NonLoc>();
715 NonLoc ZeroFlag = C.getSValBuilder()
716 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
717 .castAs<NonLoc>();
718 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
719 Flags, ZeroFlag,
720 FlagsEx->getType());
721 if (MaskedFlagsUC.isUnknownOrUndef())
722 return None;
723 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
724
725 // Check if maskedFlags is non-zero.
726 ProgramStateRef TrueState, FalseState;
727 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
728
729 // If M_ZERO is set, treat this like calloc (initialized).
730 if (TrueState && !FalseState) {
731 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
732 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
733 }
734
735 return None;
736 }
737
checkPostStmt(const CallExpr * CE,CheckerContext & C) const738 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
739 if (C.wasInlined)
740 return;
741
742 const FunctionDecl *FD = C.getCalleeDecl(CE);
743 if (!FD)
744 return;
745
746 ProgramStateRef State = C.getState();
747 bool ReleasedAllocatedMemory = false;
748
749 if (FD->getKind() == Decl::Function) {
750 initIdentifierInfo(C.getASTContext());
751 IdentifierInfo *FunI = FD->getIdentifier();
752
753 if (FunI == II_malloc) {
754 if (CE->getNumArgs() < 1)
755 return;
756 if (CE->getNumArgs() < 3) {
757 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
758 if (CE->getNumArgs() == 1)
759 State = ProcessZeroAllocation(C, CE, 0, State);
760 } else if (CE->getNumArgs() == 3) {
761 llvm::Optional<ProgramStateRef> MaybeState =
762 performKernelMalloc(CE, C, State);
763 if (MaybeState.hasValue())
764 State = MaybeState.getValue();
765 else
766 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
767 }
768 } else if (FunI == II_kmalloc) {
769 llvm::Optional<ProgramStateRef> MaybeState =
770 performKernelMalloc(CE, C, State);
771 if (MaybeState.hasValue())
772 State = MaybeState.getValue();
773 else
774 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
775 } else if (FunI == II_valloc) {
776 if (CE->getNumArgs() < 1)
777 return;
778 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
779 State = ProcessZeroAllocation(C, CE, 0, State);
780 } else if (FunI == II_realloc) {
781 State = ReallocMem(C, CE, false, State);
782 State = ProcessZeroAllocation(C, CE, 1, State);
783 } else if (FunI == II_reallocf) {
784 State = ReallocMem(C, CE, true, State);
785 State = ProcessZeroAllocation(C, CE, 1, State);
786 } else if (FunI == II_calloc) {
787 State = CallocMem(C, CE, State);
788 State = ProcessZeroAllocation(C, CE, 0, State);
789 State = ProcessZeroAllocation(C, CE, 1, State);
790 } else if (FunI == II_free) {
791 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
792 } else if (FunI == II_strdup) {
793 State = MallocUpdateRefState(C, CE, State);
794 } else if (FunI == II_strndup) {
795 State = MallocUpdateRefState(C, CE, State);
796 } else if (FunI == II_alloca) {
797 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
798 AF_Alloca);
799 State = ProcessZeroAllocation(C, CE, 0, State);
800 } else if (isStandardNewDelete(FD, C.getASTContext())) {
801 // Process direct calls to operator new/new[]/delete/delete[] functions
802 // as distinct from new/new[]/delete/delete[] expressions that are
803 // processed by the checkPostStmt callbacks for CXXNewExpr and
804 // CXXDeleteExpr.
805 OverloadedOperatorKind K = FD->getOverloadedOperator();
806 if (K == OO_New) {
807 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
808 AF_CXXNew);
809 State = ProcessZeroAllocation(C, CE, 0, State);
810 }
811 else if (K == OO_Array_New) {
812 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
813 AF_CXXNewArray);
814 State = ProcessZeroAllocation(C, CE, 0, State);
815 }
816 else if (K == OO_Delete || K == OO_Array_Delete)
817 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
818 else
819 llvm_unreachable("not a new/delete operator");
820 } else if (FunI == II_if_nameindex) {
821 // Should we model this differently? We can allocate a fixed number of
822 // elements with zeros in the last one.
823 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
824 AF_IfNameIndex);
825 } else if (FunI == II_if_freenameindex) {
826 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
827 }
828 }
829
830 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
831 // Check all the attributes, if there are any.
832 // There can be multiple of these attributes.
833 if (FD->hasAttrs())
834 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
835 switch (I->getOwnKind()) {
836 case OwnershipAttr::Returns:
837 State = MallocMemReturnsAttr(C, CE, I, State);
838 break;
839 case OwnershipAttr::Takes:
840 case OwnershipAttr::Holds:
841 State = FreeMemAttr(C, CE, I, State);
842 break;
843 }
844 }
845 }
846 C.addTransition(State);
847 }
848
849 // Performs a 0-sized allocations check.
ProcessZeroAllocation(CheckerContext & C,const Expr * E,const unsigned AllocationSizeArg,ProgramStateRef State) const850 ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
851 const Expr *E,
852 const unsigned AllocationSizeArg,
853 ProgramStateRef State) const {
854 if (!State)
855 return nullptr;
856
857 const Expr *Arg = nullptr;
858
859 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
860 Arg = CE->getArg(AllocationSizeArg);
861 }
862 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
863 if (NE->isArray())
864 Arg = NE->getArraySize();
865 else
866 return State;
867 }
868 else
869 llvm_unreachable("not a CallExpr or CXXNewExpr");
870
871 assert(Arg);
872
873 Optional<DefinedSVal> DefArgVal =
874 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
875
876 if (!DefArgVal)
877 return State;
878
879 // Check if the allocation size is 0.
880 ProgramStateRef TrueState, FalseState;
881 SValBuilder &SvalBuilder = C.getSValBuilder();
882 DefinedSVal Zero =
883 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
884
885 std::tie(TrueState, FalseState) =
886 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
887
888 if (TrueState && !FalseState) {
889 SVal retVal = State->getSVal(E, C.getLocationContext());
890 SymbolRef Sym = retVal.getAsLocSymbol();
891 if (!Sym)
892 return State;
893
894 const RefState *RS = State->get<RegionState>(Sym);
895 if (!RS)
896 return State; // TODO: change to assert(RS); after realloc() will
897 // guarantee have a RegionState attached.
898
899 if (!RS->isAllocated())
900 return State;
901
902 return TrueState->set<RegionState>(Sym,
903 RefState::getAllocatedOfSizeZero(RS));
904 }
905
906 // Assume the value is non-zero going forward.
907 assert(FalseState);
908 return FalseState;
909 }
910
getDeepPointeeType(QualType T)911 static QualType getDeepPointeeType(QualType T) {
912 QualType Result = T, PointeeType = T->getPointeeType();
913 while (!PointeeType.isNull()) {
914 Result = PointeeType;
915 PointeeType = PointeeType->getPointeeType();
916 }
917 return Result;
918 }
919
treatUnusedNewEscaped(const CXXNewExpr * NE)920 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
921
922 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
923 if (!ConstructE)
924 return false;
925
926 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
927 return false;
928
929 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
930
931 // Iterate over the constructor parameters.
932 for (const auto *CtorParam : CtorD->params()) {
933
934 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
935 if (CtorParamPointeeT.isNull())
936 continue;
937
938 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
939
940 if (CtorParamPointeeT->getAsCXXRecordDecl())
941 return true;
942 }
943
944 return false;
945 }
946
checkPostStmt(const CXXNewExpr * NE,CheckerContext & C) const947 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
948 CheckerContext &C) const {
949
950 if (NE->getNumPlacementArgs())
951 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
952 E = NE->placement_arg_end(); I != E; ++I)
953 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
954 checkUseAfterFree(Sym, C, *I);
955
956 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
957 return;
958
959 ParentMap &PM = C.getLocationContext()->getParentMap();
960 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
961 return;
962
963 ProgramStateRef State = C.getState();
964 // The return value from operator new is bound to a specified initialization
965 // value (if any) and we don't want to loose this value. So we call
966 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
967 // existing binding.
968 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
969 : AF_CXXNew);
970 State = ProcessZeroAllocation(C, NE, 0, State);
971 C.addTransition(State);
972 }
973
checkPreStmt(const CXXDeleteExpr * DE,CheckerContext & C) const974 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
975 CheckerContext &C) const {
976
977 if (!ChecksEnabled[CK_NewDeleteChecker])
978 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
979 checkUseAfterFree(Sym, C, DE->getArgument());
980
981 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
982 return;
983
984 ProgramStateRef State = C.getState();
985 bool ReleasedAllocated;
986 State = FreeMemAux(C, DE->getArgument(), DE, State,
987 /*Hold*/false, ReleasedAllocated);
988
989 C.addTransition(State);
990 }
991
isKnownDeallocObjCMethodName(const ObjCMethodCall & Call)992 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
993 // If the first selector piece is one of the names below, assume that the
994 // object takes ownership of the memory, promising to eventually deallocate it
995 // with free().
996 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
997 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
998 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
999 if (FirstSlot == "dataWithBytesNoCopy" ||
1000 FirstSlot == "initWithBytesNoCopy" ||
1001 FirstSlot == "initWithCharactersNoCopy")
1002 return true;
1003
1004 return false;
1005 }
1006
getFreeWhenDoneArg(const ObjCMethodCall & Call)1007 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1008 Selector S = Call.getSelector();
1009
1010 // FIXME: We should not rely on fully-constrained symbols being folded.
1011 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1012 if (S.getNameForSlot(i).equals("freeWhenDone"))
1013 return !Call.getArgSVal(i).isZeroConstant();
1014
1015 return None;
1016 }
1017
checkPostObjCMessage(const ObjCMethodCall & Call,CheckerContext & C) const1018 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1019 CheckerContext &C) const {
1020 if (C.wasInlined)
1021 return;
1022
1023 if (!isKnownDeallocObjCMethodName(Call))
1024 return;
1025
1026 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1027 if (!*FreeWhenDone)
1028 return;
1029
1030 bool ReleasedAllocatedMemory;
1031 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1032 Call.getOriginExpr(), C.getState(),
1033 /*Hold=*/true, ReleasedAllocatedMemory,
1034 /*RetNullOnFailure=*/true);
1035
1036 C.addTransition(State);
1037 }
1038
1039 ProgramStateRef
MallocMemReturnsAttr(CheckerContext & C,const CallExpr * CE,const OwnershipAttr * Att,ProgramStateRef State) const1040 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1041 const OwnershipAttr *Att,
1042 ProgramStateRef State) const {
1043 if (!State)
1044 return nullptr;
1045
1046 if (Att->getModule() != II_malloc)
1047 return nullptr;
1048
1049 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1050 if (I != E) {
1051 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1052 }
1053 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1054 }
1055
MallocMemAux(CheckerContext & C,const CallExpr * CE,const Expr * SizeEx,SVal Init,ProgramStateRef State,AllocationFamily Family)1056 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1057 const CallExpr *CE,
1058 const Expr *SizeEx, SVal Init,
1059 ProgramStateRef State,
1060 AllocationFamily Family) {
1061 if (!State)
1062 return nullptr;
1063
1064 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1065 Init, State, Family);
1066 }
1067
MallocMemAux(CheckerContext & C,const CallExpr * CE,SVal Size,SVal Init,ProgramStateRef State,AllocationFamily Family)1068 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1069 const CallExpr *CE,
1070 SVal Size, SVal Init,
1071 ProgramStateRef State,
1072 AllocationFamily Family) {
1073 if (!State)
1074 return nullptr;
1075
1076 // We expect the malloc functions to return a pointer.
1077 if (!Loc::isLocType(CE->getType()))
1078 return nullptr;
1079
1080 // Bind the return value to the symbolic value from the heap region.
1081 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1082 // side effects other than what we model here.
1083 unsigned Count = C.blockCount();
1084 SValBuilder &svalBuilder = C.getSValBuilder();
1085 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1086 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1087 .castAs<DefinedSVal>();
1088 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1089
1090 // Fill the region with the initialization value.
1091 State = State->bindDefault(RetVal, Init);
1092
1093 // Set the region's extent equal to the Size parameter.
1094 const SymbolicRegion *R =
1095 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1096 if (!R)
1097 return nullptr;
1098 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1099 Size.getAs<DefinedOrUnknownSVal>()) {
1100 SValBuilder &svalBuilder = C.getSValBuilder();
1101 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1102 DefinedOrUnknownSVal extentMatchesSize =
1103 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1104
1105 State = State->assume(extentMatchesSize, true);
1106 assert(State);
1107 }
1108
1109 return MallocUpdateRefState(C, CE, State, Family);
1110 }
1111
MallocUpdateRefState(CheckerContext & C,const Expr * E,ProgramStateRef State,AllocationFamily Family)1112 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1113 const Expr *E,
1114 ProgramStateRef State,
1115 AllocationFamily Family) {
1116 if (!State)
1117 return nullptr;
1118
1119 // Get the return value.
1120 SVal retVal = State->getSVal(E, C.getLocationContext());
1121
1122 // We expect the malloc functions to return a pointer.
1123 if (!retVal.getAs<Loc>())
1124 return nullptr;
1125
1126 SymbolRef Sym = retVal.getAsLocSymbol();
1127 assert(Sym);
1128
1129 // Set the symbol's state to Allocated.
1130 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1131 }
1132
FreeMemAttr(CheckerContext & C,const CallExpr * CE,const OwnershipAttr * Att,ProgramStateRef State) const1133 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1134 const CallExpr *CE,
1135 const OwnershipAttr *Att,
1136 ProgramStateRef State) const {
1137 if (!State)
1138 return nullptr;
1139
1140 if (Att->getModule() != II_malloc)
1141 return nullptr;
1142
1143 bool ReleasedAllocated = false;
1144
1145 for (const auto &Arg : Att->args()) {
1146 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1147 Att->getOwnKind() == OwnershipAttr::Holds,
1148 ReleasedAllocated);
1149 if (StateI)
1150 State = StateI;
1151 }
1152 return State;
1153 }
1154
FreeMemAux(CheckerContext & C,const CallExpr * CE,ProgramStateRef State,unsigned Num,bool Hold,bool & ReleasedAllocated,bool ReturnsNullOnFailure) const1155 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1156 const CallExpr *CE,
1157 ProgramStateRef State,
1158 unsigned Num,
1159 bool Hold,
1160 bool &ReleasedAllocated,
1161 bool ReturnsNullOnFailure) const {
1162 if (!State)
1163 return nullptr;
1164
1165 if (CE->getNumArgs() < (Num + 1))
1166 return nullptr;
1167
1168 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1169 ReleasedAllocated, ReturnsNullOnFailure);
1170 }
1171
1172 /// Checks if the previous call to free on the given symbol failed - if free
1173 /// failed, returns true. Also, returns the corresponding return value symbol.
didPreviousFreeFail(ProgramStateRef State,SymbolRef Sym,SymbolRef & RetStatusSymbol)1174 static bool didPreviousFreeFail(ProgramStateRef State,
1175 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1176 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1177 if (Ret) {
1178 assert(*Ret && "We should not store the null return symbol");
1179 ConstraintManager &CMgr = State->getConstraintManager();
1180 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1181 RetStatusSymbol = *Ret;
1182 return FreeFailed.isConstrainedTrue();
1183 }
1184 return false;
1185 }
1186
getAllocationFamily(CheckerContext & C,const Stmt * S) const1187 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1188 const Stmt *S) const {
1189 if (!S)
1190 return AF_None;
1191
1192 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1193 const FunctionDecl *FD = C.getCalleeDecl(CE);
1194
1195 if (!FD)
1196 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1197
1198 ASTContext &Ctx = C.getASTContext();
1199
1200 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1201 return AF_Malloc;
1202
1203 if (isStandardNewDelete(FD, Ctx)) {
1204 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1205 if (Kind == OO_New || Kind == OO_Delete)
1206 return AF_CXXNew;
1207 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1208 return AF_CXXNewArray;
1209 }
1210
1211 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1212 return AF_IfNameIndex;
1213
1214 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1215 return AF_Alloca;
1216
1217 return AF_None;
1218 }
1219
1220 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1221 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1222
1223 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1224 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1225
1226 if (isa<ObjCMessageExpr>(S))
1227 return AF_Malloc;
1228
1229 return AF_None;
1230 }
1231
printAllocDeallocName(raw_ostream & os,CheckerContext & C,const Expr * E) const1232 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1233 const Expr *E) const {
1234 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1235 // FIXME: This doesn't handle indirect calls.
1236 const FunctionDecl *FD = CE->getDirectCallee();
1237 if (!FD)
1238 return false;
1239
1240 os << *FD;
1241 if (!FD->isOverloadedOperator())
1242 os << "()";
1243 return true;
1244 }
1245
1246 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1247 if (Msg->isInstanceMessage())
1248 os << "-";
1249 else
1250 os << "+";
1251 Msg->getSelector().print(os);
1252 return true;
1253 }
1254
1255 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1256 os << "'"
1257 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1258 << "'";
1259 return true;
1260 }
1261
1262 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1263 os << "'"
1264 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1265 << "'";
1266 return true;
1267 }
1268
1269 return false;
1270 }
1271
printExpectedAllocName(raw_ostream & os,CheckerContext & C,const Expr * E) const1272 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1273 const Expr *E) const {
1274 AllocationFamily Family = getAllocationFamily(C, E);
1275
1276 switch(Family) {
1277 case AF_Malloc: os << "malloc()"; return;
1278 case AF_CXXNew: os << "'new'"; return;
1279 case AF_CXXNewArray: os << "'new[]'"; return;
1280 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1281 case AF_Alloca:
1282 case AF_None: llvm_unreachable("not a deallocation expression");
1283 }
1284 }
1285
printExpectedDeallocName(raw_ostream & os,AllocationFamily Family) const1286 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1287 AllocationFamily Family) const {
1288 switch(Family) {
1289 case AF_Malloc: os << "free()"; return;
1290 case AF_CXXNew: os << "'delete'"; return;
1291 case AF_CXXNewArray: os << "'delete[]'"; return;
1292 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1293 case AF_Alloca:
1294 case AF_None: llvm_unreachable("suspicious argument");
1295 }
1296 }
1297
FreeMemAux(CheckerContext & C,const Expr * ArgExpr,const Expr * ParentExpr,ProgramStateRef State,bool Hold,bool & ReleasedAllocated,bool ReturnsNullOnFailure) const1298 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1299 const Expr *ArgExpr,
1300 const Expr *ParentExpr,
1301 ProgramStateRef State,
1302 bool Hold,
1303 bool &ReleasedAllocated,
1304 bool ReturnsNullOnFailure) const {
1305
1306 if (!State)
1307 return nullptr;
1308
1309 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1310 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1311 return nullptr;
1312 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1313
1314 // Check for null dereferences.
1315 if (!location.getAs<Loc>())
1316 return nullptr;
1317
1318 // The explicit NULL case, no operation is performed.
1319 ProgramStateRef notNullState, nullState;
1320 std::tie(notNullState, nullState) = State->assume(location);
1321 if (nullState && !notNullState)
1322 return nullptr;
1323
1324 // Unknown values could easily be okay
1325 // Undefined values are handled elsewhere
1326 if (ArgVal.isUnknownOrUndef())
1327 return nullptr;
1328
1329 const MemRegion *R = ArgVal.getAsRegion();
1330
1331 // Nonlocs can't be freed, of course.
1332 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1333 if (!R) {
1334 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1335 return nullptr;
1336 }
1337
1338 R = R->StripCasts();
1339
1340 // Blocks might show up as heap data, but should not be free()d
1341 if (isa<BlockDataRegion>(R)) {
1342 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1343 return nullptr;
1344 }
1345
1346 const MemSpaceRegion *MS = R->getMemorySpace();
1347
1348 // Parameters, locals, statics, globals, and memory returned by
1349 // __builtin_alloca() shouldn't be freed.
1350 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1351 // FIXME: at the time this code was written, malloc() regions were
1352 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1353 // This means that there isn't actually anything from HeapSpaceRegion
1354 // that should be freed, even though we allow it here.
1355 // Of course, free() can work on memory allocated outside the current
1356 // function, so UnknownSpaceRegion is always a possibility.
1357 // False negatives are better than false positives.
1358
1359 if (isa<AllocaRegion>(R))
1360 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1361 else
1362 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1363
1364 return nullptr;
1365 }
1366
1367 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1368 // Various cases could lead to non-symbol values here.
1369 // For now, ignore them.
1370 if (!SrBase)
1371 return nullptr;
1372
1373 SymbolRef SymBase = SrBase->getSymbol();
1374 const RefState *RsBase = State->get<RegionState>(SymBase);
1375 SymbolRef PreviousRetStatusSymbol = nullptr;
1376
1377 if (RsBase) {
1378
1379 // Memory returned by alloca() shouldn't be freed.
1380 if (RsBase->getAllocationFamily() == AF_Alloca) {
1381 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1382 return nullptr;
1383 }
1384
1385 // Check for double free first.
1386 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1387 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1388 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1389 SymBase, PreviousRetStatusSymbol);
1390 return nullptr;
1391
1392 // If the pointer is allocated or escaped, but we are now trying to free it,
1393 // check that the call to free is proper.
1394 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1395 RsBase->isEscaped()) {
1396
1397 // Check if an expected deallocation function matches the real one.
1398 bool DeallocMatchesAlloc =
1399 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1400 if (!DeallocMatchesAlloc) {
1401 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1402 ParentExpr, RsBase, SymBase, Hold);
1403 return nullptr;
1404 }
1405
1406 // Check if the memory location being freed is the actual location
1407 // allocated, or an offset.
1408 RegionOffset Offset = R->getAsOffset();
1409 if (Offset.isValid() &&
1410 !Offset.hasSymbolicOffset() &&
1411 Offset.getOffset() != 0) {
1412 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1413 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1414 AllocExpr);
1415 return nullptr;
1416 }
1417 }
1418 }
1419
1420 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1421 RsBase->isAllocatedOfSizeZero());
1422
1423 // Clean out the info on previous call to free return info.
1424 State = State->remove<FreeReturnValue>(SymBase);
1425
1426 // Keep track of the return value. If it is NULL, we will know that free
1427 // failed.
1428 if (ReturnsNullOnFailure) {
1429 SVal RetVal = C.getSVal(ParentExpr);
1430 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1431 if (RetStatusSymbol) {
1432 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1433 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1434 }
1435 }
1436
1437 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1438 : getAllocationFamily(C, ParentExpr);
1439 // Normal free.
1440 if (Hold)
1441 return State->set<RegionState>(SymBase,
1442 RefState::getRelinquished(Family,
1443 ParentExpr));
1444
1445 return State->set<RegionState>(SymBase,
1446 RefState::getReleased(Family, ParentExpr));
1447 }
1448
1449 Optional<MallocChecker::CheckKind>
getCheckIfTracked(AllocationFamily Family,bool IsALeakCheck) const1450 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1451 bool IsALeakCheck) const {
1452 switch (Family) {
1453 case AF_Malloc:
1454 case AF_Alloca:
1455 case AF_IfNameIndex: {
1456 if (ChecksEnabled[CK_MallocChecker])
1457 return CK_MallocChecker;
1458
1459 return Optional<MallocChecker::CheckKind>();
1460 }
1461 case AF_CXXNew:
1462 case AF_CXXNewArray: {
1463 if (IsALeakCheck) {
1464 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1465 return CK_NewDeleteLeaksChecker;
1466 }
1467 else {
1468 if (ChecksEnabled[CK_NewDeleteChecker])
1469 return CK_NewDeleteChecker;
1470 }
1471 return Optional<MallocChecker::CheckKind>();
1472 }
1473 case AF_None: {
1474 llvm_unreachable("no family");
1475 }
1476 }
1477 llvm_unreachable("unhandled family");
1478 }
1479
1480 Optional<MallocChecker::CheckKind>
getCheckIfTracked(CheckerContext & C,const Stmt * AllocDeallocStmt,bool IsALeakCheck) const1481 MallocChecker::getCheckIfTracked(CheckerContext &C,
1482 const Stmt *AllocDeallocStmt,
1483 bool IsALeakCheck) const {
1484 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1485 IsALeakCheck);
1486 }
1487
1488 Optional<MallocChecker::CheckKind>
getCheckIfTracked(CheckerContext & C,SymbolRef Sym,bool IsALeakCheck) const1489 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1490 bool IsALeakCheck) const {
1491 const RefState *RS = C.getState()->get<RegionState>(Sym);
1492 assert(RS);
1493 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1494 }
1495
SummarizeValue(raw_ostream & os,SVal V)1496 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1497 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1498 os << "an integer (" << IntVal->getValue() << ")";
1499 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1500 os << "a constant address (" << ConstAddr->getValue() << ")";
1501 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1502 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1503 else
1504 return false;
1505
1506 return true;
1507 }
1508
SummarizeRegion(raw_ostream & os,const MemRegion * MR)1509 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1510 const MemRegion *MR) {
1511 switch (MR->getKind()) {
1512 case MemRegion::FunctionTextRegionKind: {
1513 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
1514 if (FD)
1515 os << "the address of the function '" << *FD << '\'';
1516 else
1517 os << "the address of a function";
1518 return true;
1519 }
1520 case MemRegion::BlockTextRegionKind:
1521 os << "block text";
1522 return true;
1523 case MemRegion::BlockDataRegionKind:
1524 // FIXME: where the block came from?
1525 os << "a block";
1526 return true;
1527 default: {
1528 const MemSpaceRegion *MS = MR->getMemorySpace();
1529
1530 if (isa<StackLocalsSpaceRegion>(MS)) {
1531 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1532 const VarDecl *VD;
1533 if (VR)
1534 VD = VR->getDecl();
1535 else
1536 VD = nullptr;
1537
1538 if (VD)
1539 os << "the address of the local variable '" << VD->getName() << "'";
1540 else
1541 os << "the address of a local stack variable";
1542 return true;
1543 }
1544
1545 if (isa<StackArgumentsSpaceRegion>(MS)) {
1546 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1547 const VarDecl *VD;
1548 if (VR)
1549 VD = VR->getDecl();
1550 else
1551 VD = nullptr;
1552
1553 if (VD)
1554 os << "the address of the parameter '" << VD->getName() << "'";
1555 else
1556 os << "the address of a parameter";
1557 return true;
1558 }
1559
1560 if (isa<GlobalsSpaceRegion>(MS)) {
1561 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1562 const VarDecl *VD;
1563 if (VR)
1564 VD = VR->getDecl();
1565 else
1566 VD = nullptr;
1567
1568 if (VD) {
1569 if (VD->isStaticLocal())
1570 os << "the address of the static variable '" << VD->getName() << "'";
1571 else
1572 os << "the address of the global variable '" << VD->getName() << "'";
1573 } else
1574 os << "the address of a global variable";
1575 return true;
1576 }
1577
1578 return false;
1579 }
1580 }
1581 }
1582
ReportBadFree(CheckerContext & C,SVal ArgVal,SourceRange Range,const Expr * DeallocExpr) const1583 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1584 SourceRange Range,
1585 const Expr *DeallocExpr) const {
1586
1587 if (!ChecksEnabled[CK_MallocChecker] &&
1588 !ChecksEnabled[CK_NewDeleteChecker])
1589 return;
1590
1591 Optional<MallocChecker::CheckKind> CheckKind =
1592 getCheckIfTracked(C, DeallocExpr);
1593 if (!CheckKind.hasValue())
1594 return;
1595
1596 if (ExplodedNode *N = C.generateSink()) {
1597 if (!BT_BadFree[*CheckKind])
1598 BT_BadFree[*CheckKind].reset(
1599 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1600
1601 SmallString<100> buf;
1602 llvm::raw_svector_ostream os(buf);
1603
1604 const MemRegion *MR = ArgVal.getAsRegion();
1605 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1606 MR = ER->getSuperRegion();
1607
1608 os << "Argument to ";
1609 if (!printAllocDeallocName(os, C, DeallocExpr))
1610 os << "deallocator";
1611
1612 os << " is ";
1613 bool Summarized = MR ? SummarizeRegion(os, MR)
1614 : SummarizeValue(os, ArgVal);
1615 if (Summarized)
1616 os << ", which is not memory allocated by ";
1617 else
1618 os << "not memory allocated by ";
1619
1620 printExpectedAllocName(os, C, DeallocExpr);
1621
1622 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
1623 R->markInteresting(MR);
1624 R->addRange(Range);
1625 C.emitReport(R);
1626 }
1627 }
1628
ReportFreeAlloca(CheckerContext & C,SVal ArgVal,SourceRange Range) const1629 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1630 SourceRange Range) const {
1631
1632 Optional<MallocChecker::CheckKind> CheckKind;
1633
1634 if (ChecksEnabled[CK_MallocChecker])
1635 CheckKind = CK_MallocChecker;
1636 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1637 CheckKind = CK_MismatchedDeallocatorChecker;
1638 else
1639 return;
1640
1641 if (ExplodedNode *N = C.generateSink()) {
1642 if (!BT_FreeAlloca[*CheckKind])
1643 BT_FreeAlloca[*CheckKind].reset(
1644 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1645
1646 BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind],
1647 "Memory allocated by alloca() should not be deallocated", N);
1648 R->markInteresting(ArgVal.getAsRegion());
1649 R->addRange(Range);
1650 C.emitReport(R);
1651 }
1652 }
1653
ReportMismatchedDealloc(CheckerContext & C,SourceRange Range,const Expr * DeallocExpr,const RefState * RS,SymbolRef Sym,bool OwnershipTransferred) const1654 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1655 SourceRange Range,
1656 const Expr *DeallocExpr,
1657 const RefState *RS,
1658 SymbolRef Sym,
1659 bool OwnershipTransferred) const {
1660
1661 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1662 return;
1663
1664 if (ExplodedNode *N = C.generateSink()) {
1665 if (!BT_MismatchedDealloc)
1666 BT_MismatchedDealloc.reset(
1667 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1668 "Bad deallocator", "Memory Error"));
1669
1670 SmallString<100> buf;
1671 llvm::raw_svector_ostream os(buf);
1672
1673 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1674 SmallString<20> AllocBuf;
1675 llvm::raw_svector_ostream AllocOs(AllocBuf);
1676 SmallString<20> DeallocBuf;
1677 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1678
1679 if (OwnershipTransferred) {
1680 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1681 os << DeallocOs.str() << " cannot";
1682 else
1683 os << "Cannot";
1684
1685 os << " take ownership of memory";
1686
1687 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1688 os << " allocated by " << AllocOs.str();
1689 } else {
1690 os << "Memory";
1691 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1692 os << " allocated by " << AllocOs.str();
1693
1694 os << " should be deallocated by ";
1695 printExpectedDeallocName(os, RS->getAllocationFamily());
1696
1697 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1698 os << ", not " << DeallocOs.str();
1699 }
1700
1701 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
1702 R->markInteresting(Sym);
1703 R->addRange(Range);
1704 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1705 C.emitReport(R);
1706 }
1707 }
1708
ReportOffsetFree(CheckerContext & C,SVal ArgVal,SourceRange Range,const Expr * DeallocExpr,const Expr * AllocExpr) const1709 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1710 SourceRange Range, const Expr *DeallocExpr,
1711 const Expr *AllocExpr) const {
1712
1713
1714 if (!ChecksEnabled[CK_MallocChecker] &&
1715 !ChecksEnabled[CK_NewDeleteChecker])
1716 return;
1717
1718 Optional<MallocChecker::CheckKind> CheckKind =
1719 getCheckIfTracked(C, AllocExpr);
1720 if (!CheckKind.hasValue())
1721 return;
1722
1723 ExplodedNode *N = C.generateSink();
1724 if (!N)
1725 return;
1726
1727 if (!BT_OffsetFree[*CheckKind])
1728 BT_OffsetFree[*CheckKind].reset(
1729 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1730
1731 SmallString<100> buf;
1732 llvm::raw_svector_ostream os(buf);
1733 SmallString<20> AllocNameBuf;
1734 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1735
1736 const MemRegion *MR = ArgVal.getAsRegion();
1737 assert(MR && "Only MemRegion based symbols can have offset free errors");
1738
1739 RegionOffset Offset = MR->getAsOffset();
1740 assert((Offset.isValid() &&
1741 !Offset.hasSymbolicOffset() &&
1742 Offset.getOffset() != 0) &&
1743 "Only symbols with a valid offset can have offset free errors");
1744
1745 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1746
1747 os << "Argument to ";
1748 if (!printAllocDeallocName(os, C, DeallocExpr))
1749 os << "deallocator";
1750 os << " is offset by "
1751 << offsetBytes
1752 << " "
1753 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1754 << " from the start of ";
1755 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1756 os << "memory allocated by " << AllocNameOs.str();
1757 else
1758 os << "allocated memory";
1759
1760 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
1761 R->markInteresting(MR->getBaseRegion());
1762 R->addRange(Range);
1763 C.emitReport(R);
1764 }
1765
ReportUseAfterFree(CheckerContext & C,SourceRange Range,SymbolRef Sym) const1766 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1767 SymbolRef Sym) const {
1768
1769 if (!ChecksEnabled[CK_MallocChecker] &&
1770 !ChecksEnabled[CK_NewDeleteChecker])
1771 return;
1772
1773 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1774 if (!CheckKind.hasValue())
1775 return;
1776
1777 if (ExplodedNode *N = C.generateSink()) {
1778 if (!BT_UseFree[*CheckKind])
1779 BT_UseFree[*CheckKind].reset(new BugType(
1780 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1781
1782 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
1783 "Use of memory after it is freed", N);
1784
1785 R->markInteresting(Sym);
1786 R->addRange(Range);
1787 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1788 C.emitReport(R);
1789 }
1790 }
1791
ReportDoubleFree(CheckerContext & C,SourceRange Range,bool Released,SymbolRef Sym,SymbolRef PrevSym) const1792 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1793 bool Released, SymbolRef Sym,
1794 SymbolRef PrevSym) const {
1795
1796 if (!ChecksEnabled[CK_MallocChecker] &&
1797 !ChecksEnabled[CK_NewDeleteChecker])
1798 return;
1799
1800 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1801 if (!CheckKind.hasValue())
1802 return;
1803
1804 if (ExplodedNode *N = C.generateSink()) {
1805 if (!BT_DoubleFree[*CheckKind])
1806 BT_DoubleFree[*CheckKind].reset(
1807 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1808
1809 BugReport *R =
1810 new BugReport(*BT_DoubleFree[*CheckKind],
1811 (Released ? "Attempt to free released memory"
1812 : "Attempt to free non-owned memory"),
1813 N);
1814 R->addRange(Range);
1815 R->markInteresting(Sym);
1816 if (PrevSym)
1817 R->markInteresting(PrevSym);
1818 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1819 C.emitReport(R);
1820 }
1821 }
1822
ReportDoubleDelete(CheckerContext & C,SymbolRef Sym) const1823 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1824
1825 if (!ChecksEnabled[CK_NewDeleteChecker])
1826 return;
1827
1828 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1829 if (!CheckKind.hasValue())
1830 return;
1831
1832 if (ExplodedNode *N = C.generateSink()) {
1833 if (!BT_DoubleDelete)
1834 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1835 "Double delete", "Memory Error"));
1836
1837 BugReport *R = new BugReport(*BT_DoubleDelete,
1838 "Attempt to delete released memory", N);
1839
1840 R->markInteresting(Sym);
1841 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1842 C.emitReport(R);
1843 }
1844 }
1845
ReportUseZeroAllocated(CheckerContext & C,SourceRange Range,SymbolRef Sym) const1846 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1847 SourceRange Range,
1848 SymbolRef Sym) const {
1849
1850 if (!ChecksEnabled[CK_MallocChecker] &&
1851 !ChecksEnabled[CK_NewDeleteChecker])
1852 return;
1853
1854 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1855
1856 if (!CheckKind.hasValue())
1857 return;
1858
1859 if (ExplodedNode *N = C.generateSink()) {
1860 if (!BT_UseZerroAllocated[*CheckKind])
1861 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1862 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1863
1864 BugReport *R = new BugReport(*BT_UseZerroAllocated[*CheckKind],
1865 "Use of zero-allocated memory", N);
1866
1867 R->addRange(Range);
1868 if (Sym) {
1869 R->markInteresting(Sym);
1870 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1871 }
1872 C.emitReport(R);
1873 }
1874 }
1875
ReallocMem(CheckerContext & C,const CallExpr * CE,bool FreesOnFail,ProgramStateRef State) const1876 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1877 const CallExpr *CE,
1878 bool FreesOnFail,
1879 ProgramStateRef State) const {
1880 if (!State)
1881 return nullptr;
1882
1883 if (CE->getNumArgs() < 2)
1884 return nullptr;
1885
1886 const Expr *arg0Expr = CE->getArg(0);
1887 const LocationContext *LCtx = C.getLocationContext();
1888 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
1889 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1890 return nullptr;
1891 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1892
1893 SValBuilder &svalBuilder = C.getSValBuilder();
1894
1895 DefinedOrUnknownSVal PtrEQ =
1896 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
1897
1898 // Get the size argument. If there is no size arg then give up.
1899 const Expr *Arg1 = CE->getArg(1);
1900 if (!Arg1)
1901 return nullptr;
1902
1903 // Get the value of the size argument.
1904 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
1905 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
1906 return nullptr;
1907 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
1908
1909 // Compare the size argument to 0.
1910 DefinedOrUnknownSVal SizeZero =
1911 svalBuilder.evalEQ(State, Arg1Val,
1912 svalBuilder.makeIntValWithPtrWidth(0, false));
1913
1914 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1915 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
1916 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1917 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
1918 // We only assume exceptional states if they are definitely true; if the
1919 // state is under-constrained, assume regular realloc behavior.
1920 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1921 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1922
1923 // If the ptr is NULL and the size is not 0, the call is equivalent to
1924 // malloc(size).
1925 if ( PrtIsNull && !SizeIsZero) {
1926 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
1927 UndefinedVal(), StatePtrIsNull);
1928 return stateMalloc;
1929 }
1930
1931 if (PrtIsNull && SizeIsZero)
1932 return nullptr;
1933
1934 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
1935 assert(!PrtIsNull);
1936 SymbolRef FromPtr = arg0Val.getAsSymbol();
1937 SVal RetVal = State->getSVal(CE, LCtx);
1938 SymbolRef ToPtr = RetVal.getAsSymbol();
1939 if (!FromPtr || !ToPtr)
1940 return nullptr;
1941
1942 bool ReleasedAllocated = false;
1943
1944 // If the size is 0, free the memory.
1945 if (SizeIsZero)
1946 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1947 false, ReleasedAllocated)){
1948 // The semantics of the return value are:
1949 // If size was equal to 0, either NULL or a pointer suitable to be passed
1950 // to free() is returned. We just free the input pointer and do not add
1951 // any constrains on the output pointer.
1952 return stateFree;
1953 }
1954
1955 // Default behavior.
1956 if (ProgramStateRef stateFree =
1957 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
1958
1959 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1960 UnknownVal(), stateFree);
1961 if (!stateRealloc)
1962 return nullptr;
1963
1964 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1965 if (FreesOnFail)
1966 Kind = RPIsFreeOnFailure;
1967 else if (!ReleasedAllocated)
1968 Kind = RPDoNotTrackAfterFailure;
1969
1970 // Record the info about the reallocated symbol so that we could properly
1971 // process failed reallocation.
1972 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
1973 ReallocPair(FromPtr, Kind));
1974 // The reallocated symbol should stay alive for as long as the new symbol.
1975 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
1976 return stateRealloc;
1977 }
1978 return nullptr;
1979 }
1980
CallocMem(CheckerContext & C,const CallExpr * CE,ProgramStateRef State)1981 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1982 ProgramStateRef State) {
1983 if (!State)
1984 return nullptr;
1985
1986 if (CE->getNumArgs() < 2)
1987 return nullptr;
1988
1989 SValBuilder &svalBuilder = C.getSValBuilder();
1990 const LocationContext *LCtx = C.getLocationContext();
1991 SVal count = State->getSVal(CE->getArg(0), LCtx);
1992 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1993 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
1994 svalBuilder.getContext().getSizeType());
1995 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1996
1997 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
1998 }
1999
2000 LeakInfo
getAllocationSite(const ExplodedNode * N,SymbolRef Sym,CheckerContext & C) const2001 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2002 CheckerContext &C) const {
2003 const LocationContext *LeakContext = N->getLocationContext();
2004 // Walk the ExplodedGraph backwards and find the first node that referred to
2005 // the tracked symbol.
2006 const ExplodedNode *AllocNode = N;
2007 const MemRegion *ReferenceRegion = nullptr;
2008
2009 while (N) {
2010 ProgramStateRef State = N->getState();
2011 if (!State->get<RegionState>(Sym))
2012 break;
2013
2014 // Find the most recent expression bound to the symbol in the current
2015 // context.
2016 if (!ReferenceRegion) {
2017 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2018 SVal Val = State->getSVal(MR);
2019 if (Val.getAsLocSymbol() == Sym) {
2020 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2021 // Do not show local variables belonging to a function other than
2022 // where the error is reported.
2023 if (!VR ||
2024 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2025 ReferenceRegion = MR;
2026 }
2027 }
2028 }
2029
2030 // Allocation node, is the last node in the current or parent context in
2031 // which the symbol was tracked.
2032 const LocationContext *NContext = N->getLocationContext();
2033 if (NContext == LeakContext ||
2034 NContext->isParentOf(LeakContext))
2035 AllocNode = N;
2036 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2037 }
2038
2039 return LeakInfo(AllocNode, ReferenceRegion);
2040 }
2041
reportLeak(SymbolRef Sym,ExplodedNode * N,CheckerContext & C) const2042 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2043 CheckerContext &C) const {
2044
2045 if (!ChecksEnabled[CK_MallocChecker] &&
2046 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2047 return;
2048
2049 const RefState *RS = C.getState()->get<RegionState>(Sym);
2050 assert(RS && "cannot leak an untracked symbol");
2051 AllocationFamily Family = RS->getAllocationFamily();
2052
2053 if (Family == AF_Alloca)
2054 return;
2055
2056 Optional<MallocChecker::CheckKind>
2057 CheckKind = getCheckIfTracked(Family, true);
2058
2059 if (!CheckKind.hasValue())
2060 return;
2061
2062 assert(N);
2063 if (!BT_Leak[*CheckKind]) {
2064 BT_Leak[*CheckKind].reset(
2065 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
2066 // Leaks should not be reported if they are post-dominated by a sink:
2067 // (1) Sinks are higher importance bugs.
2068 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2069 // with __noreturn functions such as assert() or exit(). We choose not
2070 // to report leaks on such paths.
2071 BT_Leak[*CheckKind]->setSuppressOnSink(true);
2072 }
2073
2074 // Most bug reports are cached at the location where they occurred.
2075 // With leaks, we want to unique them by the location where they were
2076 // allocated, and only report a single path.
2077 PathDiagnosticLocation LocUsedForUniqueing;
2078 const ExplodedNode *AllocNode = nullptr;
2079 const MemRegion *Region = nullptr;
2080 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2081
2082 ProgramPoint P = AllocNode->getLocation();
2083 const Stmt *AllocationStmt = nullptr;
2084 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
2085 AllocationStmt = Exit->getCalleeContext()->getCallSite();
2086 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
2087 AllocationStmt = SP->getStmt();
2088 if (AllocationStmt)
2089 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2090 C.getSourceManager(),
2091 AllocNode->getLocationContext());
2092
2093 SmallString<200> buf;
2094 llvm::raw_svector_ostream os(buf);
2095 if (Region && Region->canPrintPretty()) {
2096 os << "Potential leak of memory pointed to by ";
2097 Region->printPretty(os);
2098 } else {
2099 os << "Potential memory leak";
2100 }
2101
2102 BugReport *R =
2103 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2104 AllocNode->getLocationContext()->getDecl());
2105 R->markInteresting(Sym);
2106 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2107 C.emitReport(R);
2108 }
2109
checkDeadSymbols(SymbolReaper & SymReaper,CheckerContext & C) const2110 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2111 CheckerContext &C) const
2112 {
2113 if (!SymReaper.hasDeadSymbols())
2114 return;
2115
2116 ProgramStateRef state = C.getState();
2117 RegionStateTy RS = state->get<RegionState>();
2118 RegionStateTy::Factory &F = state->get_context<RegionState>();
2119
2120 SmallVector<SymbolRef, 2> Errors;
2121 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2122 if (SymReaper.isDead(I->first)) {
2123 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2124 Errors.push_back(I->first);
2125 // Remove the dead symbol from the map.
2126 RS = F.remove(RS, I->first);
2127
2128 }
2129 }
2130
2131 // Cleanup the Realloc Pairs Map.
2132 ReallocPairsTy RP = state->get<ReallocPairs>();
2133 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2134 if (SymReaper.isDead(I->first) ||
2135 SymReaper.isDead(I->second.ReallocatedSym)) {
2136 state = state->remove<ReallocPairs>(I->first);
2137 }
2138 }
2139
2140 // Cleanup the FreeReturnValue Map.
2141 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2142 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2143 if (SymReaper.isDead(I->first) ||
2144 SymReaper.isDead(I->second)) {
2145 state = state->remove<FreeReturnValue>(I->first);
2146 }
2147 }
2148
2149 // Generate leak node.
2150 ExplodedNode *N = C.getPredecessor();
2151 if (!Errors.empty()) {
2152 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2153 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
2154 for (SmallVectorImpl<SymbolRef>::iterator
2155 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2156 reportLeak(*I, N, C);
2157 }
2158 }
2159
2160 C.addTransition(state->set<RegionState>(RS), N);
2161 }
2162
checkPreCall(const CallEvent & Call,CheckerContext & C) const2163 void MallocChecker::checkPreCall(const CallEvent &Call,
2164 CheckerContext &C) const {
2165
2166 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2167 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2168 if (!Sym || checkDoubleDelete(Sym, C))
2169 return;
2170 }
2171
2172 // We will check for double free in the post visit.
2173 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2174 const FunctionDecl *FD = FC->getDecl();
2175 if (!FD)
2176 return;
2177
2178 ASTContext &Ctx = C.getASTContext();
2179 if (ChecksEnabled[CK_MallocChecker] &&
2180 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2181 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2182 MemoryOperationKind::MOK_Free)))
2183 return;
2184
2185 if (ChecksEnabled[CK_NewDeleteChecker] &&
2186 isStandardNewDelete(FD, Ctx))
2187 return;
2188 }
2189
2190 // Check if the callee of a method is deleted.
2191 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2192 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2193 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2194 return;
2195 }
2196
2197 // Check arguments for being used after free.
2198 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2199 SVal ArgSVal = Call.getArgSVal(I);
2200 if (ArgSVal.getAs<Loc>()) {
2201 SymbolRef Sym = ArgSVal.getAsSymbol();
2202 if (!Sym)
2203 continue;
2204 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2205 return;
2206 }
2207 }
2208 }
2209
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const2210 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2211 const Expr *E = S->getRetValue();
2212 if (!E)
2213 return;
2214
2215 // Check if we are returning a symbol.
2216 ProgramStateRef State = C.getState();
2217 SVal RetVal = State->getSVal(E, C.getLocationContext());
2218 SymbolRef Sym = RetVal.getAsSymbol();
2219 if (!Sym)
2220 // If we are returning a field of the allocated struct or an array element,
2221 // the callee could still free the memory.
2222 // TODO: This logic should be a part of generic symbol escape callback.
2223 if (const MemRegion *MR = RetVal.getAsRegion())
2224 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2225 if (const SymbolicRegion *BMR =
2226 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2227 Sym = BMR->getSymbol();
2228
2229 // Check if we are returning freed memory.
2230 if (Sym)
2231 checkUseAfterFree(Sym, C, E);
2232 }
2233
2234 // TODO: Blocks should be either inlined or should call invalidate regions
2235 // upon invocation. After that's in place, special casing here will not be
2236 // needed.
checkPostStmt(const BlockExpr * BE,CheckerContext & C) const2237 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2238 CheckerContext &C) const {
2239
2240 // Scan the BlockDecRefExprs for any object the retain count checker
2241 // may be tracking.
2242 if (!BE->getBlockDecl()->hasCaptures())
2243 return;
2244
2245 ProgramStateRef state = C.getState();
2246 const BlockDataRegion *R =
2247 cast<BlockDataRegion>(state->getSVal(BE,
2248 C.getLocationContext()).getAsRegion());
2249
2250 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2251 E = R->referenced_vars_end();
2252
2253 if (I == E)
2254 return;
2255
2256 SmallVector<const MemRegion*, 10> Regions;
2257 const LocationContext *LC = C.getLocationContext();
2258 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2259
2260 for ( ; I != E; ++I) {
2261 const VarRegion *VR = I.getCapturedRegion();
2262 if (VR->getSuperRegion() == R) {
2263 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2264 }
2265 Regions.push_back(VR);
2266 }
2267
2268 state =
2269 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2270 Regions.data() + Regions.size()).getState();
2271 C.addTransition(state);
2272 }
2273
isReleased(SymbolRef Sym,CheckerContext & C) const2274 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2275 assert(Sym);
2276 const RefState *RS = C.getState()->get<RegionState>(Sym);
2277 return (RS && RS->isReleased());
2278 }
2279
checkUseAfterFree(SymbolRef Sym,CheckerContext & C,const Stmt * S) const2280 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2281 const Stmt *S) const {
2282
2283 if (isReleased(Sym, C)) {
2284 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2285 return true;
2286 }
2287
2288 return false;
2289 }
2290
checkUseZeroAllocated(SymbolRef Sym,CheckerContext & C,const Stmt * S) const2291 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2292 const Stmt *S) const {
2293 assert(Sym);
2294 const RefState *RS = C.getState()->get<RegionState>(Sym);
2295
2296 if (RS && RS->isAllocatedOfSizeZero())
2297 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2298 }
2299
checkDoubleDelete(SymbolRef Sym,CheckerContext & C) const2300 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2301
2302 if (isReleased(Sym, C)) {
2303 ReportDoubleDelete(C, Sym);
2304 return true;
2305 }
2306 return false;
2307 }
2308
2309 // Check if the location is a freed symbolic region.
checkLocation(SVal l,bool isLoad,const Stmt * S,CheckerContext & C) const2310 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2311 CheckerContext &C) const {
2312 SymbolRef Sym = l.getLocSymbolInBase();
2313 if (Sym) {
2314 checkUseAfterFree(Sym, C, S);
2315 checkUseZeroAllocated(Sym, C, S);
2316 }
2317 }
2318
2319 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2320 // it - assuming that allocation failed on this path.
evalAssume(ProgramStateRef state,SVal Cond,bool Assumption) const2321 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2322 SVal Cond,
2323 bool Assumption) const {
2324 RegionStateTy RS = state->get<RegionState>();
2325 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2326 // If the symbol is assumed to be NULL, remove it from consideration.
2327 ConstraintManager &CMgr = state->getConstraintManager();
2328 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2329 if (AllocFailed.isConstrainedTrue())
2330 state = state->remove<RegionState>(I.getKey());
2331 }
2332
2333 // Realloc returns 0 when reallocation fails, which means that we should
2334 // restore the state of the pointer being reallocated.
2335 ReallocPairsTy RP = state->get<ReallocPairs>();
2336 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2337 // If the symbol is assumed to be NULL, remove it from consideration.
2338 ConstraintManager &CMgr = state->getConstraintManager();
2339 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2340 if (!AllocFailed.isConstrainedTrue())
2341 continue;
2342
2343 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2344 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2345 if (RS->isReleased()) {
2346 if (I.getData().Kind == RPToBeFreedAfterFailure)
2347 state = state->set<RegionState>(ReallocSym,
2348 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2349 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2350 state = state->remove<RegionState>(ReallocSym);
2351 else
2352 assert(I.getData().Kind == RPIsFreeOnFailure);
2353 }
2354 }
2355 state = state->remove<ReallocPairs>(I.getKey());
2356 }
2357
2358 return state;
2359 }
2360
mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent * Call,ProgramStateRef State,SymbolRef & EscapingSymbol) const2361 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2362 const CallEvent *Call,
2363 ProgramStateRef State,
2364 SymbolRef &EscapingSymbol) const {
2365 assert(Call);
2366 EscapingSymbol = nullptr;
2367
2368 // For now, assume that any C++ or block call can free memory.
2369 // TODO: If we want to be more optimistic here, we'll need to make sure that
2370 // regions escape to C++ containers. They seem to do that even now, but for
2371 // mysterious reasons.
2372 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2373 return true;
2374
2375 // Check Objective-C messages by selector name.
2376 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2377 // If it's not a framework call, or if it takes a callback, assume it
2378 // can free memory.
2379 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
2380 return true;
2381
2382 // If it's a method we know about, handle it explicitly post-call.
2383 // This should happen before the "freeWhenDone" check below.
2384 if (isKnownDeallocObjCMethodName(*Msg))
2385 return false;
2386
2387 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2388 // about, we can't be sure that the object will use free() to deallocate the
2389 // memory, so we can't model it explicitly. The best we can do is use it to
2390 // decide whether the pointer escapes.
2391 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2392 return *FreeWhenDone;
2393
2394 // If the first selector piece ends with "NoCopy", and there is no
2395 // "freeWhenDone" parameter set to zero, we know ownership is being
2396 // transferred. Again, though, we can't be sure that the object will use
2397 // free() to deallocate the memory, so we can't model it explicitly.
2398 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2399 if (FirstSlot.endswith("NoCopy"))
2400 return true;
2401
2402 // If the first selector starts with addPointer, insertPointer,
2403 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2404 // This is similar to C++ containers (vector); we still might want to check
2405 // that the pointers get freed by following the container itself.
2406 if (FirstSlot.startswith("addPointer") ||
2407 FirstSlot.startswith("insertPointer") ||
2408 FirstSlot.startswith("replacePointer") ||
2409 FirstSlot.equals("valueWithPointer")) {
2410 return true;
2411 }
2412
2413 // We should escape receiver on call to 'init'. This is especially relevant
2414 // to the receiver, as the corresponding symbol is usually not referenced
2415 // after the call.
2416 if (Msg->getMethodFamily() == OMF_init) {
2417 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2418 return true;
2419 }
2420
2421 // Otherwise, assume that the method does not free memory.
2422 // Most framework methods do not free memory.
2423 return false;
2424 }
2425
2426 // At this point the only thing left to handle is straight function calls.
2427 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2428 if (!FD)
2429 return true;
2430
2431 ASTContext &ASTC = State->getStateManager().getContext();
2432
2433 // If it's one of the allocation functions we can reason about, we model
2434 // its behavior explicitly.
2435 if (isMemFunction(FD, ASTC))
2436 return false;
2437
2438 // If it's not a system call, assume it frees memory.
2439 if (!Call->isInSystemHeader())
2440 return true;
2441
2442 // White list the system functions whose arguments escape.
2443 const IdentifierInfo *II = FD->getIdentifier();
2444 if (!II)
2445 return true;
2446 StringRef FName = II->getName();
2447
2448 // White list the 'XXXNoCopy' CoreFoundation functions.
2449 // We specifically check these before
2450 if (FName.endswith("NoCopy")) {
2451 // Look for the deallocator argument. We know that the memory ownership
2452 // is not transferred only if the deallocator argument is
2453 // 'kCFAllocatorNull'.
2454 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2455 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2456 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2457 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2458 if (DeallocatorName == "kCFAllocatorNull")
2459 return false;
2460 }
2461 }
2462 return true;
2463 }
2464
2465 // Associating streams with malloced buffers. The pointer can escape if
2466 // 'closefn' is specified (and if that function does free memory),
2467 // but it will not if closefn is not specified.
2468 // Currently, we do not inspect the 'closefn' function (PR12101).
2469 if (FName == "funopen")
2470 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2471 return false;
2472
2473 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2474 // these leaks might be intentional when setting the buffer for stdio.
2475 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2476 if (FName == "setbuf" || FName =="setbuffer" ||
2477 FName == "setlinebuf" || FName == "setvbuf") {
2478 if (Call->getNumArgs() >= 1) {
2479 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2480 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2481 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2482 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2483 return true;
2484 }
2485 }
2486
2487 // A bunch of other functions which either take ownership of a pointer or
2488 // wrap the result up in a struct or object, meaning it can be freed later.
2489 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2490 // but the Malloc checker cannot differentiate between them. The right way
2491 // of doing this would be to implement a pointer escapes callback.
2492 if (FName == "CGBitmapContextCreate" ||
2493 FName == "CGBitmapContextCreateWithData" ||
2494 FName == "CVPixelBufferCreateWithBytes" ||
2495 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2496 FName == "OSAtomicEnqueue") {
2497 return true;
2498 }
2499
2500 // Handle cases where we know a buffer's /address/ can escape.
2501 // Note that the above checks handle some special cases where we know that
2502 // even though the address escapes, it's still our responsibility to free the
2503 // buffer.
2504 if (Call->argumentsMayEscape())
2505 return true;
2506
2507 // Otherwise, assume that the function does not free memory.
2508 // Most system calls do not free the memory.
2509 return false;
2510 }
2511
retTrue(const RefState * RS)2512 static bool retTrue(const RefState *RS) {
2513 return true;
2514 }
2515
checkIfNewOrNewArrayFamily(const RefState * RS)2516 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2517 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2518 RS->getAllocationFamily() == AF_CXXNew);
2519 }
2520
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const2521 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2522 const InvalidatedSymbols &Escaped,
2523 const CallEvent *Call,
2524 PointerEscapeKind Kind) const {
2525 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2526 }
2527
checkConstPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const2528 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2529 const InvalidatedSymbols &Escaped,
2530 const CallEvent *Call,
2531 PointerEscapeKind Kind) const {
2532 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2533 &checkIfNewOrNewArrayFamily);
2534 }
2535
checkPointerEscapeAux(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind,bool (* CheckRefState)(const RefState *)) const2536 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2537 const InvalidatedSymbols &Escaped,
2538 const CallEvent *Call,
2539 PointerEscapeKind Kind,
2540 bool(*CheckRefState)(const RefState*)) const {
2541 // If we know that the call does not free memory, or we want to process the
2542 // call later, keep tracking the top level arguments.
2543 SymbolRef EscapingSymbol = nullptr;
2544 if (Kind == PSK_DirectEscapeOnCall &&
2545 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2546 EscapingSymbol) &&
2547 !EscapingSymbol) {
2548 return State;
2549 }
2550
2551 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2552 E = Escaped.end();
2553 I != E; ++I) {
2554 SymbolRef sym = *I;
2555
2556 if (EscapingSymbol && EscapingSymbol != sym)
2557 continue;
2558
2559 if (const RefState *RS = State->get<RegionState>(sym)) {
2560 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2561 CheckRefState(RS)) {
2562 State = State->remove<RegionState>(sym);
2563 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2564 }
2565 }
2566 }
2567 return State;
2568 }
2569
findFailedReallocSymbol(ProgramStateRef currState,ProgramStateRef prevState)2570 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2571 ProgramStateRef prevState) {
2572 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2573 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2574
2575 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2576 I != E; ++I) {
2577 SymbolRef sym = I.getKey();
2578 if (!currMap.lookup(sym))
2579 return sym;
2580 }
2581
2582 return nullptr;
2583 }
2584
2585 PathDiagnosticPiece *
VisitNode(const ExplodedNode * N,const ExplodedNode * PrevN,BugReporterContext & BRC,BugReport & BR)2586 MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2587 const ExplodedNode *PrevN,
2588 BugReporterContext &BRC,
2589 BugReport &BR) {
2590 ProgramStateRef state = N->getState();
2591 ProgramStateRef statePrev = PrevN->getState();
2592
2593 const RefState *RS = state->get<RegionState>(Sym);
2594 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2595 if (!RS)
2596 return nullptr;
2597
2598 const Stmt *S = nullptr;
2599 const char *Msg = nullptr;
2600 StackHintGeneratorForSymbol *StackHint = nullptr;
2601
2602 // Retrieve the associated statement.
2603 ProgramPoint ProgLoc = N->getLocation();
2604 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
2605 S = SP->getStmt();
2606 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
2607 S = Exit->getCalleeContext()->getCallSite();
2608 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
2609 // If an assumption was made on a branch, it should be caught
2610 // here by looking at the state transition.
2611 S = Edge->getSrc()->getTerminator();
2612 }
2613
2614 if (!S)
2615 return nullptr;
2616
2617 // FIXME: We will eventually need to handle non-statement-based events
2618 // (__attribute__((cleanup))).
2619
2620 // Find out if this is an interesting point and what is the kind.
2621 if (Mode == Normal) {
2622 if (isAllocated(RS, RSPrev, S)) {
2623 Msg = "Memory is allocated";
2624 StackHint = new StackHintGeneratorForSymbol(Sym,
2625 "Returned allocated memory");
2626 } else if (isReleased(RS, RSPrev, S)) {
2627 Msg = "Memory is released";
2628 StackHint = new StackHintGeneratorForSymbol(Sym,
2629 "Returning; memory was released");
2630 } else if (isRelinquished(RS, RSPrev, S)) {
2631 Msg = "Memory ownership is transferred";
2632 StackHint = new StackHintGeneratorForSymbol(Sym, "");
2633 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2634 Mode = ReallocationFailed;
2635 Msg = "Reallocation failed";
2636 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2637 "Reallocation failed");
2638
2639 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2640 // Is it possible to fail two reallocs WITHOUT testing in between?
2641 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2642 "We only support one failed realloc at a time.");
2643 BR.markInteresting(sym);
2644 FailedReallocSymbol = sym;
2645 }
2646 }
2647
2648 // We are in a special mode if a reallocation failed later in the path.
2649 } else if (Mode == ReallocationFailed) {
2650 assert(FailedReallocSymbol && "No symbol to look for.");
2651
2652 // Is this is the first appearance of the reallocated symbol?
2653 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2654 // We're at the reallocation point.
2655 Msg = "Attempt to reallocate memory";
2656 StackHint = new StackHintGeneratorForSymbol(Sym,
2657 "Returned reallocated memory");
2658 FailedReallocSymbol = nullptr;
2659 Mode = Normal;
2660 }
2661 }
2662
2663 if (!Msg)
2664 return nullptr;
2665 assert(StackHint);
2666
2667 // Generate the extra diagnostic.
2668 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2669 N->getLocationContext());
2670 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
2671 }
2672
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const2673 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2674 const char *NL, const char *Sep) const {
2675
2676 RegionStateTy RS = State->get<RegionState>();
2677
2678 if (!RS.isEmpty()) {
2679 Out << Sep << "MallocChecker :" << NL;
2680 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2681 const RefState *RefS = State->get<RegionState>(I.getKey());
2682 AllocationFamily Family = RefS->getAllocationFamily();
2683 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2684 if (!CheckKind.hasValue())
2685 CheckKind = getCheckIfTracked(Family, true);
2686
2687 I.getKey()->dumpToStream(Out);
2688 Out << " : ";
2689 I.getData().dump(Out);
2690 if (CheckKind.hasValue())
2691 Out << " (" << CheckNames[*CheckKind].getName() << ")";
2692 Out << NL;
2693 }
2694 }
2695 }
2696
registerNewDeleteLeaksChecker(CheckerManager & mgr)2697 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2698 registerCStringCheckerBasic(mgr);
2699 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2700 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2701 "Optimistic", false, checker);
2702 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2703 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2704 mgr.getCurrentCheckName();
2705 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2706 // checker.
2707 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2708 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2709 }
2710
2711 #define REGISTER_CHECKER(name) \
2712 void ento::register##name(CheckerManager &mgr) { \
2713 registerCStringCheckerBasic(mgr); \
2714 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2715 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2716 "Optimistic", false, checker); \
2717 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2718 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2719 }
2720
2721 REGISTER_CHECKER(MallocChecker)
2722 REGISTER_CHECKER(NewDeleteChecker)
2723 REGISTER_CHECKER(MismatchedDeallocatorChecker)
2724