Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file defines malloc/free checker, which checks for potential memory
10
// leaks, double free, and use-after-free problems.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "InterCheckerAPI.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/SourceManager.h"
19
#include "clang/Basic/TargetInfo.h"
20
#include "clang/Lex/Lexer.h"
21
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22
#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
23
#include "clang/StaticAnalyzer/Core/Checker.h"
24
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
25
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
26
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
27
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
28
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
30
#include "llvm/ADT/STLExtras.h"
31
#include "llvm/ADT/SmallString.h"
32
#include "llvm/ADT/StringExtras.h"
33
#include "AllocationState.h"
34
#include <climits>
35
#include <utility>
36
37
using namespace clang;
38
using namespace ento;
39
40
namespace {
41
42
// Used to check correspondence between allocators and deallocators.
43
enum AllocationFamily {
44
  AF_None,
45
  AF_Malloc,
46
  AF_CXXNew,
47
  AF_CXXNewArray,
48
  AF_IfNameIndex,
49
  AF_Alloca,
50
  AF_InnerBuffer
51
};
52
53
class RefState {
54
  enum Kind { // Reference to allocated memory.
55
              Allocated,
56
              // Reference to zero-allocated memory.
57
              AllocatedOfSizeZero,
58
              // Reference to released/freed memory.
59
              Released,
60
              // The responsibility for freeing resources has transferred from
61
              // this reference. A relinquished symbol should not be freed.
62
              Relinquished,
63
              // We are no longer guaranteed to have observed all manipulations
64
              // of this pointer/memory. For example, it could have been
65
              // passed as a parameter to an opaque function.
66
              Escaped
67
  };
68
69
  const Stmt *S;
70
  unsigned K : 3; // Kind enum, but stored as a bitfield.
71
  unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
72
                        // family.
73
74
  RefState(Kind k, const Stmt *s, unsigned family)
75
2.63k
    : S(s), K(k), Family(family) {
76
2.63k
    assert(family != AF_None);
77
2.63k
  }
78
public:
79
28.7k
  bool isAllocated() const { return K == Allocated; }
80
5.95k
  bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
81
19.3k
  bool isReleased() const { return K == Released; }
82
1.63k
  bool isRelinquished() const { return K == Relinquished; }
83
83
  bool isEscaped() const { return K == Escaped; }
84
4.28k
  AllocationFamily getAllocationFamily() const {
85
4.28k
    return (AllocationFamily)Family;
86
4.28k
  }
87
672
  const Stmt *getStmt() const { return S; }
88
89
592
  bool operator==(const RefState &X) const {
90
592
    return K == X.K && S == X.S && Family == X.Family;
91
592
  }
92
93
1.42k
  static RefState getAllocated(unsigned family, const Stmt *s) {
94
1.42k
    return RefState(Allocated, s, family);
95
1.42k
  }
96
96
  static RefState getAllocatedOfSizeZero(const RefState *RS) {
97
96
    return RefState(AllocatedOfSizeZero, RS->getStmt(),
98
96
                    RS->getAllocationFamily());
99
96
  }
100
685
  static RefState getReleased(unsigned family, const Stmt *s) {
101
685
    return RefState(Released, s, family);
102
685
  }
103
25
  static RefState getRelinquished(unsigned family, const Stmt *s) {
104
25
    return RefState(Relinquished, s, family);
105
25
  }
106
405
  static RefState getEscaped(const RefState *RS) {
107
405
    return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
108
405
  }
109
110
3.64k
  void Profile(llvm::FoldingSetNodeID &ID) const {
111
3.64k
    ID.AddInteger(K);
112
3.64k
    ID.AddPointer(S);
113
3.64k
    ID.AddInteger(Family);
114
3.64k
  }
115
116
0
  void dump(raw_ostream &OS) const {
117
0
    switch (static_cast<Kind>(K)) {
118
0
#define CASE(ID) case ID: OS << #ID; break;
119
0
    CASE(Allocated)
120
0
    CASE(AllocatedOfSizeZero)
121
0
    CASE(Released)
122
0
    CASE(Relinquished)
123
0
    CASE(Escaped)
124
0
    }
125
0
  }
126
127
0
  LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
128
};
129
130
enum ReallocPairKind {
131
  RPToBeFreedAfterFailure,
132
  // The symbol has been freed when reallocation failed.
133
  RPIsFreeOnFailure,
134
  // The symbol does not need to be freed after reallocation fails.
135
  RPDoNotTrackAfterFailure
136
};
137
138
/// \class ReallocPair
139
/// Stores information about the symbol being reallocated by a call to
140
/// 'realloc' to allow modeling failed reallocation later in the path.
141
struct ReallocPair {
142
  // The symbol which realloc reallocated.
143
  SymbolRef ReallocatedSym;
144
  ReallocPairKind Kind;
145
146
  ReallocPair(SymbolRef S, ReallocPairKind K) :
147
54
    ReallocatedSym(S), Kind(K) {}
148
110
  void Profile(llvm::FoldingSetNodeID &ID) const {
149
110
    ID.AddInteger(Kind);
150
110
    ID.AddPointer(ReallocatedSym);
151
110
  }
152
24
  bool operator==(const ReallocPair &X) const {
153
24
    return ReallocatedSym == X.ReallocatedSym &&
154
24
           Kind == X.Kind;
155
24
  }
156
};
157
158
typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
159
160
class MallocChecker : public Checker<check::DeadSymbols,
161
                                     check::PointerEscape,
162
                                     check::ConstPointerEscape,
163
                                     check::PreStmt<ReturnStmt>,
164
                                     check::EndFunction,
165
                                     check::PreCall,
166
                                     check::PostStmt<CallExpr>,
167
                                     check::PostStmt<CXXNewExpr>,
168
                                     check::NewAllocator,
169
                                     check::PreStmt<CXXDeleteExpr>,
170
                                     check::PostStmt<BlockExpr>,
171
                                     check::PostObjCMessage,
172
                                     check::Location,
173
                                     eval::Assume>
174
{
175
public:
176
  MallocChecker()
177
      : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
178
        II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
179
        II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
180
        II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
181
        II_kfree(nullptr), II_if_nameindex(nullptr),
182
        II_if_freenameindex(nullptr), II_wcsdup(nullptr),
183
        II_win_wcsdup(nullptr), II_g_malloc(nullptr), II_g_malloc0(nullptr),
184
        II_g_realloc(nullptr), II_g_try_malloc(nullptr),
185
        II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
186
        II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
187
        II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
188
        II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
189
179
        II_g_try_realloc_n(nullptr) {}
190
191
  /// In pessimistic mode, the checker assumes that it does not know which
192
  /// functions might free the memory.
193
  enum CheckKind {
194
    CK_MallocChecker,
195
    CK_NewDeleteChecker,
196
    CK_NewDeleteLeaksChecker,
197
    CK_MismatchedDeallocatorChecker,
198
    CK_InnerPointerChecker,
199
    CK_NumCheckKinds
200
  };
201
202
  enum class MemoryOperationKind {
203
    MOK_Allocate,
204
    MOK_Free,
205
    MOK_Any
206
  };
207
208
  DefaultBool IsOptimistic;
209
210
  DefaultBool ChecksEnabled[CK_NumCheckKinds];
211
  CheckName CheckNames[CK_NumCheckKinds];
212
213
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
214
  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
215
  void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
216
  void checkNewAllocator(const CXXNewExpr *NE, SVal Target,
217
                         CheckerContext &C) const;
218
  void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
219
  void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
220
  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
221
  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
222
  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
223
  void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
224
  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
225
                            bool Assumption) const;
226
  void checkLocation(SVal l, bool isLoad, const Stmt *S,
227
                     CheckerContext &C) const;
228
229
  ProgramStateRef checkPointerEscape(ProgramStateRef State,
230
                                    const InvalidatedSymbols &Escaped,
231
                                    const CallEvent *Call,
232
                                    PointerEscapeKind Kind) const;
233
  ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
234
                                          const InvalidatedSymbols &Escaped,
235
                                          const CallEvent *Call,
236
                                          PointerEscapeKind Kind) const;
237
238
  void printState(raw_ostream &Out, ProgramStateRef State,
239
                  const char *NL, const char *Sep) const override;
240
241
private:
242
  mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
243
  mutable std::unique_ptr<BugType> BT_DoubleDelete;
244
  mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
245
  mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
246
  mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
247
  mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
248
  mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
249
  mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
250
  mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
251
  mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
252
                         *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
253
                         *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
254
                         *II_kfree, *II_if_nameindex, *II_if_freenameindex,
255
                         *II_wcsdup, *II_win_wcsdup, *II_g_malloc,
256
                         *II_g_malloc0, *II_g_realloc, *II_g_try_malloc,
257
                         *II_g_try_malloc0, *II_g_try_realloc, *II_g_free,
258
                         *II_g_memdup, *II_g_malloc_n, *II_g_malloc0_n,
259
                         *II_g_realloc_n, *II_g_try_malloc_n,
260
                         *II_g_try_malloc0_n, *II_g_try_realloc_n;
261
  mutable Optional<uint64_t> KernelZeroFlagVal;
262
263
  void initIdentifierInfo(ASTContext &C) const;
264
265
  /// Determine family of a deallocation expression.
266
  AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
267
268
  /// Print names of allocators and deallocators.
269
  ///
270
  /// \returns true on success.
271
  bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
272
                             const Expr *E) const;
273
274
  /// Print expected name of an allocator based on the deallocator's
275
  /// family derived from the DeallocExpr.
276
  void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
277
                              const Expr *DeallocExpr) const;
278
  /// Print expected name of a deallocator based on the allocator's
279
  /// family.
280
  void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
281
282
  ///@{
283
  /// Check if this is one of the functions which can allocate/reallocate memory
284
  /// pointed to by one of its arguments.
285
  bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
286
  bool isCMemFunction(const FunctionDecl *FD,
287
                      ASTContext &C,
288
                      AllocationFamily Family,
289
                      MemoryOperationKind MemKind) const;
290
  bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
291
  ///@}
292
293
  /// Process C++ operator new()'s allocation, which is the part of C++
294
  /// new-expression that goes before the constructor.
295
  void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
296
                            SVal Target) const;
297
298
  /// Perform a zero-allocation check.
299
  /// The optional \p RetVal parameter specifies the newly allocated pointer
300
  /// value; if unspecified, the value of expression \p E is used.
301
  ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
302
                                        const unsigned AllocationSizeArg,
303
                                        ProgramStateRef State,
304
                                        Optional<SVal> RetVal = None) const;
305
306
  ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
307
                                       const CallExpr *CE,
308
                                       const OwnershipAttr* Att,
309
                                       ProgramStateRef State) const;
310
  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
311
                                      const Expr *SizeEx, SVal Init,
312
                                      ProgramStateRef State,
313
                                      AllocationFamily Family = AF_Malloc);
314
  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
315
                                      SVal SizeEx, SVal Init,
316
                                      ProgramStateRef State,
317
                                      AllocationFamily Family = AF_Malloc);
318
319
  static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
320
                                       ProgramStateRef State, SVal Target);
321
322
  // Check if this malloc() for special flags. At present that means M_ZERO or
323
  // __GFP_ZERO (in which case, treat it like calloc).
324
  llvm::Optional<ProgramStateRef>
325
  performKernelMalloc(const CallExpr *CE, CheckerContext &C,
326
                      const ProgramStateRef &State) const;
327
328
  /// Update the RefState to reflect the new memory allocation.
329
  /// The optional \p RetVal parameter specifies the newly allocated pointer
330
  /// value; if unspecified, the value of expression \p E is used.
331
  static ProgramStateRef
332
  MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
333
                       AllocationFamily Family = AF_Malloc,
334
                       Optional<SVal> RetVal = None);
335
336
  ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
337
                              const OwnershipAttr* Att,
338
                              ProgramStateRef State) const;
339
  ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
340
                             ProgramStateRef state, unsigned Num,
341
                             bool Hold,
342
                             bool &ReleasedAllocated,
343
                             bool ReturnsNullOnFailure = false) const;
344
  ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
345
                             const Expr *ParentExpr,
346
                             ProgramStateRef State,
347
                             bool Hold,
348
                             bool &ReleasedAllocated,
349
                             bool ReturnsNullOnFailure = false) const;
350
351
  ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
352
                                bool FreesMemOnFailure,
353
                                ProgramStateRef State,
354
                                bool SuffixWithN = false) const;
355
  static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
356
                                   const Expr *BlockBytes);
357
  static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
358
                                   ProgramStateRef State);
359
360
  /// Check if the memory associated with this symbol was released.
361
  bool isReleased(SymbolRef Sym, CheckerContext &C) const;
362
363
  /// See if deallocation happens in a suspicious context. If so, escape the
364
  /// pointers that otherwise would have been deallocated and return true.
365
  bool suppressDeallocationsInSuspiciousContexts(const CallExpr *CE,
366
                                                 CheckerContext &C) const;
367
368
  bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
369
370
  void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
371
                             const Stmt *S) const;
372
373
  bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
374
375
  /// Check if the function is known free memory, or if it is
376
  /// "interesting" and should be modeled explicitly.
377
  ///
378
  /// \param [out] EscapingSymbol A function might not free memory in general,
379
  ///   but could be known to free a particular symbol. In this case, false is
380
  ///   returned and the single escaping symbol is returned through the out
381
  ///   parameter.
382
  ///
383
  /// We assume that pointers do not escape through calls to system functions
384
  /// not handled by this checker.
385
  bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
386
                                   ProgramStateRef State,
387
                                   SymbolRef &EscapingSymbol) const;
388
389
  // Implementation of the checkPointerEscape callbacks.
390
  ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
391
                                  const InvalidatedSymbols &Escaped,
392
                                  const CallEvent *Call,
393
                                  PointerEscapeKind Kind,
394
                                  bool(*CheckRefState)(const RefState*)) const;
395
396
  // Implementation of the checkPreStmt and checkEndFunction callbacks.
397
  void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
398
399
  ///@{
400
  /// Tells if a given family/call/symbol is tracked by the current checker.
401
  /// Sets CheckKind to the kind of the checker responsible for this
402
  /// family/call/symbol.
403
  Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
404
                                        bool IsALeakCheck = false) const;
405
  Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
406
                                        const Stmt *AllocDeallocStmt,
407
                                        bool IsALeakCheck = false) const;
408
  Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
409
                                        bool IsALeakCheck = false) const;
410
  ///@}
411
  static bool SummarizeValue(raw_ostream &os, SVal V);
412
  static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
413
  void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
414
                     const Expr *DeallocExpr) const;
415
  void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
416
                        SourceRange Range) const;
417
  void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
418
                               const Expr *DeallocExpr, const RefState *RS,
419
                               SymbolRef Sym, bool OwnershipTransferred) const;
420
  void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
421
                        const Expr *DeallocExpr,
422
                        const Expr *AllocExpr = nullptr) const;
423
  void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
424
                          SymbolRef Sym) const;
425
  void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
426
                        SymbolRef Sym, SymbolRef PrevSym) const;
427
428
  void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
429
430
  void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
431
                              SymbolRef Sym) const;
432
433
  void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
434
                                 SourceRange Range, const Expr *FreeExpr) const;
435
436
  /// Find the location of the allocation for Sym on the path leading to the
437
  /// exploded node N.
438
  LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
439
                             CheckerContext &C) const;
440
441
  void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
442
443
  /// The bug visitor which allows us to print extra diagnostics along the
444
  /// BugReport path. For example, showing the allocation site of the leaked
445
  /// region.
446
  class MallocBugVisitor final : public BugReporterVisitor {
447
  protected:
448
    enum NotificationMode {
449
      Normal,
450
      ReallocationFailed
451
    };
452
453
    // The allocated region symbol tracked by the main analysis.
454
    SymbolRef Sym;
455
456
    // The mode we are in, i.e. what kind of diagnostics will be emitted.
457
    NotificationMode Mode;
458
459
    // A symbol from when the primary region should have been reallocated.
460
    SymbolRef FailedReallocSymbol;
461
462
    // A C++ destructor stack frame in which memory was released. Used for
463
    // miscellaneous false positive suppression.
464
    const StackFrameContext *ReleaseDestructorLC;
465
466
    bool IsLeak;
467
468
  public:
469
    MallocBugVisitor(SymbolRef S, bool isLeak = false)
470
        : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
471
570
          ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
472
473
586
    static void *getTag() {
474
586
      static int Tag = 0;
475
586
      return &Tag;
476
586
    }
477
478
570
    void Profile(llvm::FoldingSetNodeID &ID) const override {
479
570
      ID.AddPointer(getTag());
480
570
      ID.AddPointer(Sym);
481
570
    }
482
483
    inline bool isAllocated(const RefState *S, const RefState *SPrev,
484
25.4k
                            const Stmt *Stmt) {
485
25.4k
      // Did not track -> allocated. Other state (released) -> allocated.
486
25.4k
      return (Stmt && 
(25.4k
isa<CallExpr>(Stmt)25.4k
||
isa<CXXNewExpr>(Stmt)22.6k
) &&
487
25.4k
              
(4.59k
S4.59k
&&
(1.95k
S->isAllocated()1.95k
||
S->isAllocatedOfSizeZero()490
)) &&
488
25.4k
              
(1.56k
!SPrev1.56k
||
!(1.12k
SPrev->isAllocated()1.12k
||
489
1.12k
                           
SPrev->isAllocatedOfSizeZero()38
)));
490
25.4k
    }
491
492
    inline bool isReleased(const RefState *S, const RefState *SPrev,
493
25.0k
                           const Stmt *Stmt) {
494
25.0k
      // Did not track -> released. Other state (allocated) -> released.
495
25.0k
      // The statement associated with the release might be missing.
496
25.0k
      bool IsReleased = (S && 
S->isReleased()13.7k
) &&
497
25.0k
                        
(2.75k
!SPrev2.75k
||
!SPrev->isReleased()2.66k
);
498
25.0k
      assert(!IsReleased ||
499
25.0k
             (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
500
25.0k
             (!Stmt && S->getAllocationFamily() == AF_InnerBuffer));
501
25.0k
      return IsReleased;
502
25.0k
    }
503
504
    inline bool isRelinquished(const RefState *S, const RefState *SPrev,
505
24.8k
                               const Stmt *Stmt) {
506
24.8k
      // Did not track -> relinquished. Other state (allocated) -> relinquished.
507
24.8k
      return (Stmt && 
(24.7k
isa<CallExpr>(Stmt)24.7k
||
isa<ObjCMessageExpr>(Stmt)22.3k
||
508
24.7k
                                              
isa<ObjCPropertyRefExpr>(Stmt)22.2k
) &&
509
24.8k
              
(2.50k
S2.50k
&&
S->isRelinquished()992
) &&
510
24.8k
              
(15
!SPrev15
||
!SPrev->isRelinquished()14
));
511
24.8k
    }
512
513
    inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
514
24.7k
                                     const Stmt *Stmt) {
515
24.7k
      // If the expression is not a call, and the state change is
516
24.7k
      // released -> allocated, it must be the realloc return value
517
24.7k
      // check. If we have to handle more cases here, it might be cleaner just
518
24.7k
      // to track this extra bit in the state itself.
519
24.7k
      return ((!Stmt || 
!isa<CallExpr>(Stmt)24.7k
) &&
520
24.7k
              
(22.3k
S22.3k
&&
(12.6k
S->isAllocated()12.6k
||
S->isAllocatedOfSizeZero()3.06k
)) &&
521
24.7k
              
(10.1k
SPrev10.1k
&&
!(10.1k
SPrev->isAllocated()10.1k
||
522
10.1k
                          
SPrev->isAllocatedOfSizeZero()602
)));
523
24.7k
    }
524
525
    std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
526
                                                   BugReporterContext &BRC,
527
                                                   BugReport &BR) override;
528
529
    std::shared_ptr<PathDiagnosticPiece>
530
    getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
531
528
               BugReport &BR) override {
532
528
      if (!IsLeak)
533
303
        return nullptr;
534
225
535
225
      PathDiagnosticLocation L =
536
225
        PathDiagnosticLocation::createEndOfPath(EndPathNode,
537
225
                                                BRC.getSourceManager());
538
225
      // Do not add the statement itself as a range in case of leak.
539
225
      return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
540
225
                                                         false);
541
225
    }
542
543
  private:
544
    class StackHintGeneratorForReallocationFailed
545
        : public StackHintGeneratorForSymbol {
546
    public:
547
      StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
548
6
        : StackHintGeneratorForSymbol(S, M) {}
549
550
      std::string getMessageForArg(const Expr *ArgE,
551
1
                                   unsigned ArgIndex) override {
552
1
        // Printed parameters start at 1, not 0.
553
1
        ++ArgIndex;
554
1
555
1
        SmallString<200> buf;
556
1
        llvm::raw_svector_ostream os(buf);
557
1
558
1
        os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
559
1
           << " parameter failed";
560
1
561
1
        return os.str();
562
1
      }
563
564
0
      std::string getMessageForReturn(const CallExpr *CallExpr) override {
565
0
        return "Reallocation of returned value failed";
566
0
      }
567
    };
568
  };
569
};
570
} // end anonymous namespace
571
572
REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
573
REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
574
REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
575
576
// A map from the freed symbol to the symbol representing the return value of
577
// the free function.
578
REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
579
580
namespace {
581
class StopTrackingCallback final : public SymbolVisitor {
582
  ProgramStateRef state;
583
public:
584
5
  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
585
5
  ProgramStateRef getState() const { return state; }
586
587
1
  bool VisitSymbol(SymbolRef sym) override {
588
1
    state = state->remove<RegionState>(sym);
589
1
    return true;
590
1
  }
591
};
592
} // end anonymous namespace
593
594
29.9k
void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
595
29.9k
  if (II_malloc)
596
29.7k
    return;
597
125
  II_alloca = &Ctx.Idents.get("alloca");
598
125
  II_malloc = &Ctx.Idents.get("malloc");
599
125
  II_free = &Ctx.Idents.get("free");
600
125
  II_realloc = &Ctx.Idents.get("realloc");
601
125
  II_reallocf = &Ctx.Idents.get("reallocf");
602
125
  II_calloc = &Ctx.Idents.get("calloc");
603
125
  II_valloc = &Ctx.Idents.get("valloc");
604
125
  II_strdup = &Ctx.Idents.get("strdup");
605
125
  II_strndup = &Ctx.Idents.get("strndup");
606
125
  II_wcsdup = &Ctx.Idents.get("wcsdup");
607
125
  II_kmalloc = &Ctx.Idents.get("kmalloc");
608
125
  II_kfree = &Ctx.Idents.get("kfree");
609
125
  II_if_nameindex = &Ctx.Idents.get("if_nameindex");
610
125
  II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
611
125
612
125
  //MSVC uses `_`-prefixed instead, so we check for them too.
613
125
  II_win_strdup = &Ctx.Idents.get("_strdup");
614
125
  II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
615
125
  II_win_alloca = &Ctx.Idents.get("_alloca");
616
125
617
125
  // Glib
618
125
  II_g_malloc = &Ctx.Idents.get("g_malloc");
619
125
  II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
620
125
  II_g_realloc = &Ctx.Idents.get("g_realloc");
621
125
  II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
622
125
  II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
623
125
  II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
624
125
  II_g_free = &Ctx.Idents.get("g_free");
625
125
  II_g_memdup = &Ctx.Idents.get("g_memdup");
626
125
  II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
627
125
  II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
628
125
  II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
629
125
  II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
630
125
  II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
631
125
  II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
632
125
}
633
634
639
bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
635
639
  if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
636
475
    return true;
637
164
638
164
  if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
639
0
    return true;
640
164
641
164
  if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
642
0
    return true;
643
164
644
164
  if (isStandardNewDelete(FD, C))
645
8
    return true;
646
156
647
156
  return false;
648
156
}
649
650
bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
651
                                   ASTContext &C,
652
                                   AllocationFamily Family,
653
20.1k
                                   MemoryOperationKind MemKind) const {
654
20.1k
  if (!FD)
655
0
    return false;
656
20.1k
657
20.1k
  bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
658
20.1k
                    
MemKind == MemoryOperationKind::MOK_Free18.6k
);
659
20.1k
  bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
660
20.1k
                     
MemKind == MemoryOperationKind::MOK_Allocate18.6k
);
661
20.1k
662
20.1k
  if (FD->getKind() == Decl::Function) {
663
18.2k
    const IdentifierInfo *FunI = FD->getIdentifier();
664
18.2k
    initIdentifierInfo(C);
665
18.2k
666
18.2k
    if (Family == AF_Malloc && 
CheckFree9.72k
) {
667
9.72k
      if (FunI == II_free || 
FunI == II_realloc8.72k
||
FunI == II_reallocf8.58k
||
668
9.72k
          
FunI == II_g_free8.57k
||
FunI == II_kfree8.48k
)
669
1.24k
        return true;
670
16.9k
    }
671
16.9k
672
16.9k
    if (Family == AF_Malloc && 
CheckAlloc8.48k
) {
673
286
      if (FunI == II_malloc || 
FunI == II_realloc270
||
FunI == II_reallocf270
||
674
286
          
FunI == II_calloc270
||
FunI == II_valloc270
||
FunI == II_strdup270
||
675
286
          
FunI == II_win_strdup246
||
FunI == II_strndup242
||
FunI == II_wcsdup241
||
676
286
          
FunI == II_win_wcsdup239
||
FunI == II_kmalloc235
||
677
286
          
FunI == II_g_malloc235
||
FunI == II_g_malloc0235
||
678
286
          
FunI == II_g_realloc235
||
FunI == II_g_try_malloc221
||
679
286
          
FunI == II_g_try_malloc0221
||
FunI == II_g_try_realloc221
||
680
286
          
FunI == II_g_memdup207
||
FunI == II_g_malloc_n207
||
681
286
          
FunI == II_g_malloc0_n207
||
FunI == II_g_realloc_n207
||
682
286
          
FunI == II_g_try_malloc_n193
||
FunI == II_g_try_malloc0_n193
||
683
286
          
FunI == II_g_try_realloc_n193
)
684
107
        return true;
685
16.8k
    }
686
16.8k
687
16.8k
    if (Family == AF_IfNameIndex && 
CheckFree8.34k
) {
688
8.34k
      if (FunI == II_if_freenameindex)
689
0
        return true;
690
16.8k
    }
691
16.8k
692
16.8k
    if (Family == AF_IfNameIndex && 
CheckAlloc8.34k
) {
693
157
      if (FunI == II_if_nameindex)
694
0
        return true;
695
16.8k
    }
696
16.8k
697
16.8k
    if (Family == AF_Alloca && 
CheckAlloc157
) {
698
157
      if (FunI == II_alloca || FunI == II_win_alloca)
699
0
        return true;
700
18.7k
    }
701
16.8k
  }
702
18.7k
703
18.7k
  if (Family != AF_Malloc)
704
9.46k
    return false;
705
9.32k
706
9.32k
  if (IsOptimistic && 
FD->hasAttrs()70
) {
707
41
    for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
708
39
      OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
709
39
      if(OwnKind == OwnershipAttr::Takes || 
OwnKind == OwnershipAttr::Holds31
) {
710
22
        if (CheckFree)
711
22
          return true;
712
17
      } else if (OwnKind == OwnershipAttr::Returns) {
713
17
        if (CheckAlloc)
714
0
          return true;
715
17
      }
716
39
    }
717
41
  }
718
9.32k
719
9.32k
  
return false9.30k
;
720
9.32k
}
721
722
// Tells if the callee is one of the builtin new/delete operators, including
723
// placement operators and other standard overloads.
724
bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
725
11.6k
                                        ASTContext &C) const {
726
11.6k
  if (!FD)
727
0
    return false;
728
11.6k
729
11.6k
  OverloadedOperatorKind Kind = FD->getOverloadedOperator();
730
11.6k
  if (Kind != OO_New && 
Kind != OO_Array_New11.1k
&&
731
11.6k
      
Kind != OO_Delete11.0k
&&
Kind != OO_Array_Delete10.6k
)
732
10.5k
    return false;
733
1.04k
734
1.04k
  // This is standard if and only if it's not defined in a user file.
735
1.04k
  SourceLocation L = FD->getLocation();
736
1.04k
  // If the header for operator delete is not included, it's still defined
737
1.04k
  // in an invalid source location. Check to make sure we don't crash.
738
1.04k
  return !L.isValid() || 
C.getSourceManager().isInSystemHeader(L)30
;
739
1.04k
}
740
741
llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
742
0
  const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
743
0
  // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
744
0
  //
745
0
  // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
746
0
  //
747
0
  // One of the possible flags is M_ZERO, which means 'give me back an
748
0
  // allocation which is already zeroed', like calloc.
749
0
750
0
  // 2-argument kmalloc(), as used in the Linux kernel:
751
0
  //
752
0
  // void *kmalloc(size_t size, gfp_t flags);
753
0
  //
754
0
  // Has the similar flag value __GFP_ZERO.
755
0
756
0
  // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
757
0
  // code could be shared.
758
0
759
0
  ASTContext &Ctx = C.getASTContext();
760
0
  llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
761
0
762
0
  if (!KernelZeroFlagVal.hasValue()) {
763
0
    if (OS == llvm::Triple::FreeBSD)
764
0
      KernelZeroFlagVal = 0x0100;
765
0
    else if (OS == llvm::Triple::NetBSD)
766
0
      KernelZeroFlagVal = 0x0002;
767
0
    else if (OS == llvm::Triple::OpenBSD)
768
0
      KernelZeroFlagVal = 0x0008;
769
0
    else if (OS == llvm::Triple::Linux)
770
0
      // __GFP_ZERO
771
0
      KernelZeroFlagVal = 0x8000;
772
0
    else
773
0
      // FIXME: We need a more general way of getting the M_ZERO value.
774
0
      // See also: O_CREAT in UnixAPIChecker.cpp.
775
0
776
0
      // Fall back to normal malloc behavior on platforms where we don't
777
0
      // know M_ZERO.
778
0
      return None;
779
0
  }
780
0
781
0
  // We treat the last argument as the flags argument, and callers fall-back to
782
0
  // normal malloc on a None return. This works for the FreeBSD kernel malloc
783
0
  // as well as Linux kmalloc.
784
0
  if (CE->getNumArgs() < 2)
785
0
    return None;
786
0
787
0
  const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
788
0
  const SVal V = C.getSVal(FlagsEx);
789
0
  if (!V.getAs<NonLoc>()) {
790
0
    // The case where 'V' can be a location can only be due to a bad header,
791
0
    // so in this case bail out.
792
0
    return None;
793
0
  }
794
0
795
0
  NonLoc Flags = V.castAs<NonLoc>();
796
0
  NonLoc ZeroFlag = C.getSValBuilder()
797
0
      .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
798
0
      .castAs<NonLoc>();
799
0
  SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
800
0
                                                      Flags, ZeroFlag,
801
0
                                                      FlagsEx->getType());
802
0
  if (MaskedFlagsUC.isUnknownOrUndef())
803
0
    return None;
804
0
  DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
805
0
806
0
  // Check if maskedFlags is non-zero.
807
0
  ProgramStateRef TrueState, FalseState;
808
0
  std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
809
0
810
0
  // If M_ZERO is set, treat this like calloc (initialized).
811
0
  if (TrueState && !FalseState) {
812
0
    SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
813
0
    return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
814
0
  }
815
0
816
0
  return None;
817
0
}
818
819
SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
820
66
                                         const Expr *BlockBytes) {
821
66
  SValBuilder &SB = C.getSValBuilder();
822
66
  SVal BlocksVal = C.getSVal(Blocks);
823
66
  SVal BlockBytesVal = C.getSVal(BlockBytes);
824
66
  ProgramStateRef State = C.getState();
825
66
  SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
826
66
                                SB.getContext().getSizeType());
827
66
  return TotalSize;
828
66
}
829
830
22.8k
void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
831
22.8k
  if (C.wasInlined)
832
10.2k
    return;
833
12.6k
834
12.6k
  const FunctionDecl *FD = C.getCalleeDecl(CE);
835
12.6k
  if (!FD)
836
8
    return;
837
12.6k
838
12.6k
  ProgramStateRef State = C.getState();
839
12.6k
  bool ReleasedAllocatedMemory = false;
840
12.6k
841
12.6k
  if (FD->getKind() == Decl::Function) {
842
11.6k
    initIdentifierInfo(C.getASTContext());
843
11.6k
    IdentifierInfo *FunI = FD->getIdentifier();
844
11.6k
845
11.6k
    if (FunI == II_malloc || 
FunI == II_g_malloc11.1k
||
FunI == II_g_try_malloc11.1k
) {
846
565
      if (CE->getNumArgs() < 1)
847
2
        return;
848
563
      if (CE->getNumArgs() < 3) {
849
563
        State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
850
563
        if (CE->getNumArgs() == 1)
851
563
          State = ProcessZeroAllocation(C, CE, 0, State);
852
563
      } else 
if (0
CE->getNumArgs() == 30
) {
853
0
        llvm::Optional<ProgramStateRef> MaybeState =
854
0
          performKernelMalloc(CE, C, State);
855
0
        if (MaybeState.hasValue())
856
0
          State = MaybeState.getValue();
857
0
        else
858
0
          State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
859
0
      }
860
11.1k
    } else if (FunI == II_kmalloc) {
861
1
      if (CE->getNumArgs() < 1)
862
1
        return;
863
0
      llvm::Optional<ProgramStateRef> MaybeState =
864
0
        performKernelMalloc(CE, C, State);
865
0
      if (MaybeState.hasValue())
866
0
        State = MaybeState.getValue();
867
0
      else
868
0
        State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
869
11.1k
    } else if (FunI == II_valloc) {
870
5
      if (CE->getNumArgs() < 1)
871
1
        return;
872
4
      State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
873
4
      State = ProcessZeroAllocation(C, CE, 0, State);
874
11.1k
    } else if (FunI == II_realloc || 
FunI == II_g_realloc11.0k
||
875
11.1k
               
FunI == II_g_try_realloc11.0k
) {
876
70
      State = ReallocMemAux(C, CE, false, State);
877
70
      State = ProcessZeroAllocation(C, CE, 1, State);
878
11.0k
    } else if (FunI == II_reallocf) {
879
4
      State = ReallocMemAux(C, CE, true, State);
880
4
      State = ProcessZeroAllocation(C, CE, 1, State);
881
11.0k
    } else if (FunI == II_calloc) {
882
25
      State = CallocMem(C, CE, State);
883
25
      State = ProcessZeroAllocation(C, CE, 0, State);
884
25
      State = ProcessZeroAllocation(C, CE, 1, State);
885
11.0k
    } else if (FunI == II_free || 
FunI == II_g_free10.6k
||
FunI == II_kfree10.5k
) {
886
421
      if (suppressDeallocationsInSuspiciousContexts(CE, C))
887
1
        return;
888
420
889
420
      State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
890
10.5k
    } else if (FunI == II_strdup || 
FunI == II_win_strdup10.5k
||
891
10.5k
               
FunI == II_wcsdup10.5k
||
FunI == II_win_wcsdup10.5k
) {
892
88
      State = MallocUpdateRefState(C, CE, State);
893
10.5k
    } else if (FunI == II_strndup) {
894
1
      State = MallocUpdateRefState(C, CE, State);
895
10.5k
    } else if (FunI == II_alloca || 
FunI == II_win_alloca10.4k
) {
896
13
      if (CE->getNumArgs() < 1)
897
1
        return;
898
12
      State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
899
12
                           AF_Alloca);
900
12
      State = ProcessZeroAllocation(C, CE, 0, State);
901
10.4k
    } else if (isStandardNewDelete(FD, C.getASTContext())) {
902
64
      // Process direct calls to operator new/new[]/delete/delete[] functions
903
64
      // as distinct from new/new[]/delete/delete[] expressions that are
904
64
      // processed by the checkPostStmt callbacks for CXXNewExpr and
905
64
      // CXXDeleteExpr.
906
64
      OverloadedOperatorKind K = FD->getOverloadedOperator();
907
64
      if (K == OO_New) {
908
35
        State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
909
35
                             AF_CXXNew);
910
35
        State = ProcessZeroAllocation(C, CE, 0, State);
911
35
      }
912
29
      else if (K == OO_Array_New) {
913
19
        State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
914
19
                             AF_CXXNewArray);
915
19
        State = ProcessZeroAllocation(C, CE, 0, State);
916
19
      }
917
10
      else if (K == OO_Delete || 
K == OO_Array_Delete2
)
918
10
        State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
919
10
      else
920
10
        
llvm_unreachable0
("not a new/delete operator");
921
10.4k
    } else if (FunI == II_if_nameindex) {
922
0
      // Should we model this differently? We can allocate a fixed number of
923
0
      // elements with zeros in the last one.
924
0
      State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
925
0
                           AF_IfNameIndex);
926
10.4k
    } else if (FunI == II_if_freenameindex) {
927
0
      State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
928
10.4k
    } else if (FunI == II_g_malloc0 || 
FunI == II_g_try_malloc010.4k
) {
929
14
      if (CE->getNumArgs() < 1)
930
0
        return;
931
14
      SValBuilder &svalBuilder = C.getSValBuilder();
932
14
      SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
933
14
      State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
934
14
      State = ProcessZeroAllocation(C, CE, 0, State);
935
10.4k
    } else if (FunI == II_g_memdup) {
936
0
      if (CE->getNumArgs() < 2)
937
0
        return;
938
0
      State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
939
0
      State = ProcessZeroAllocation(C, CE, 1, State);
940
10.4k
    } else if (FunI == II_g_malloc_n || 
FunI == II_g_try_malloc_n10.4k
||
941
10.4k
               
FunI == II_g_malloc0_n10.3k
||
FunI == II_g_try_malloc0_n10.3k
) {
942
28
      if (CE->getNumArgs() < 2)
943
0
        return;
944
28
      SVal Init = UndefinedVal();
945
28
      if (FunI == II_g_malloc0_n || 
FunI == II_g_try_malloc0_n21
) {
946
14
        SValBuilder &SB = C.getSValBuilder();
947
14
        Init = SB.makeZeroVal(SB.getContext().CharTy);
948
14
      }
949
28
      SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
950
28
      State = MallocMemAux(C, CE, TotalSize, Init, State);
951
28
      State = ProcessZeroAllocation(C, CE, 0, State);
952
28
      State = ProcessZeroAllocation(C, CE, 1, State);
953
10.3k
    } else if (FunI == II_g_realloc_n || 
FunI == II_g_try_realloc_n10.3k
) {
954
14
      if (CE->getNumArgs() < 3)
955
0
        return;
956
14
      State = ReallocMemAux(C, CE, false, State, true);
957
14
      State = ProcessZeroAllocation(C, CE, 1, State);
958
14
      State = ProcessZeroAllocation(C, CE, 2, State);
959
14
    }
960
11.6k
  }
961
12.6k
962
12.6k
  
if (12.6k
IsOptimistic12.6k
||
ChecksEnabled[CK_MismatchedDeallocatorChecker]12.5k
) {
963
351
    // Check all the attributes, if there are any.
964
351
    // There can be multiple of these attributes.
965
351
    if (FD->hasAttrs())
966
56
      for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
967
29
        switch (I->getOwnKind()) {
968
29
        case OwnershipAttr::Returns:
969
19
          State = MallocMemReturnsAttr(C, CE, I, State);
970
19
          break;
971
29
        case OwnershipAttr::Takes:
972
10
        case OwnershipAttr::Holds:
973
10
          State = FreeMemAttr(C, CE, I, State);
974
10
          break;
975
29
        }
976
29
      }
977
351
  }
978
12.6k
  C.addTransition(State);
979
12.6k
}
980
981
// Performs a 0-sized allocations check.
982
ProgramStateRef MallocChecker::ProcessZeroAllocation(
983
    CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
984
1.38k
    ProgramStateRef State, Optional<SVal> RetVal) const {
985
1.38k
  if (!State)
986
14
    return nullptr;
987
1.36k
988
1.36k
  if (!RetVal)
989
841
    RetVal = C.getSVal(E);
990
1.36k
991
1.36k
  const Expr *Arg = nullptr;
992
1.36k
993
1.36k
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
994
841
    Arg = CE->getArg(AllocationSizeArg);
995
841
  }
996
527
  else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
997
527
    if (NE->isArray())
998
82
      Arg = *NE->getArraySize();
999
445
    else
1000
445
      return State;
1001
527
  }
1002
527
  else
1003
527
    llvm_unreachable("not a CallExpr or CXXNewExpr");
1004
1.36k
1005
1.36k
  assert(Arg);
1006
923
1007
923
  Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
1008
923
1009
923
  if (!DefArgVal)
1010
0
    return State;
1011
923
1012
923
  // Check if the allocation size is 0.
1013
923
  ProgramStateRef TrueState, FalseState;
1014
923
  SValBuilder &SvalBuilder = C.getSValBuilder();
1015
923
  DefinedSVal Zero =
1016
923
      SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1017
923
1018
923
  std::tie(TrueState, FalseState) =
1019
923
      State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1020
923
1021
923
  if (TrueState && 
!FalseState143
) {
1022
115
    SymbolRef Sym = RetVal->getAsLocSymbol();
1023
115
    if (!Sym)
1024
0
      return State;
1025
115
1026
115
    const RefState *RS = State->get<RegionState>(Sym);
1027
115
    if (RS) {
1028
96
      if (RS->isAllocated())
1029
96
        return TrueState->set<RegionState>(Sym,
1030
96
                                          RefState::getAllocatedOfSizeZero(RS));
1031
0
      else
1032
0
        return State;
1033
19
    } else {
1034
19
      // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1035
19
      // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1036
19
      // tracked. Add zero-reallocated Sym to the state to catch references
1037
19
      // to zero-allocated memory.
1038
19
      return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1039
19
    }
1040
808
  }
1041
808
1042
808
  // Assume the value is non-zero going forward.
1043
808
  assert(FalseState);
1044
808
  return FalseState;
1045
808
}
1046
1047
8
static QualType getDeepPointeeType(QualType T) {
1048
8
  QualType Result = T, PointeeType = T->getPointeeType();
1049
10
  while (!PointeeType.isNull()) {
1050
2
    Result = PointeeType;
1051
2
    PointeeType = PointeeType->getPointeeType();
1052
2
  }
1053
8
  return Result;
1054
8
}
1055
1056
79
static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1057
79
1058
79
  const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1059
79
  if (!ConstructE)
1060
15
    return false;
1061
64
1062
64
  if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1063
0
    return false;
1064
64
1065
64
  const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1066
64
1067
64
  // Iterate over the constructor parameters.
1068
64
  for (const auto *CtorParam : CtorD->parameters()) {
1069
14
1070
14
    QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1071
14
    if (CtorParamPointeeT.isNull())
1072
6
      continue;
1073
8
1074
8
    CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1075
8
1076
8
    if (CtorParamPointeeT->getAsCXXRecordDecl())
1077
6
      return true;
1078
8
  }
1079
64
1080
64
  
return false58
;
1081
64
}
1082
1083
void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1084
                                         CheckerContext &C,
1085
547
                                         SVal Target) const {
1086
547
  if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1087
14
    return;
1088
533
1089
533
  ParentMap &PM = C.getLocationContext()->getParentMap();
1090
533
  if (!PM.isConsumedExpr(NE) && 
treatUnusedNewEscaped(NE)79
)
1091
6
    return;
1092
527
1093
527
  ProgramStateRef State = C.getState();
1094
527
  // The return value from operator new is bound to a specified initialization
1095
527
  // value (if any) and we don't want to loose this value. So we call
1096
527
  // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1097
527
  // existing binding.
1098
527
  State = MallocUpdateRefState(C, NE, State, NE->isArray() ? 
AF_CXXNewArray82
1099
527
                                                           : 
AF_CXXNew445
, Target);
1100
527
  State = addExtentSize(C, NE, State, Target);
1101
527
  State = ProcessZeroAllocation(C, NE, 0, State, Target);
1102
527
  C.addTransition(State);
1103
527
}
1104
1105
void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1106
627
                                  CheckerContext &C) const {
1107
627
  if (!C.getAnalysisManager().getAnalyzerOptions().MayInlineCXXAllocator)
1108
6
    processNewAllocation(NE, C, C.getSVal(NE));
1109
627
}
1110
1111
void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1112
623
                                      CheckerContext &C) const {
1113
623
  if (!C.wasInlined)
1114
541
    processNewAllocation(NE, C, Target);
1115
623
}
1116
1117
// Sets the extent value of the MemRegion allocated by
1118
// new expression NE to its size in Bytes.
1119
//
1120
ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1121
                                             const CXXNewExpr *NE,
1122
                                             ProgramStateRef State,
1123
527
                                             SVal Target) {
1124
527
  if (!State)
1125
0
    return nullptr;
1126
527
  SValBuilder &svalBuilder = C.getSValBuilder();
1127
527
  SVal ElementCount;
1128
527
  const SubRegion *Region;
1129
527
  if (NE->isArray()) {
1130
82
    const Expr *SizeExpr = *NE->getArraySize();
1131
82
    ElementCount = C.getSVal(SizeExpr);
1132
82
    // Store the extent size for the (symbolic)region
1133
82
    // containing the elements.
1134
82
    Region = Target.getAsRegion()
1135
82
                 ->getAs<SubRegion>()
1136
82
                 ->StripCasts()
1137
82
                 ->getAs<SubRegion>();
1138
445
  } else {
1139
445
    ElementCount = svalBuilder.makeIntVal(1, true);
1140
445
    Region = Target.getAsRegion()->getAs<SubRegion>();
1141
445
  }
1142
527
  assert(Region);
1143
527
1144
527
  // Set the region's extent equal to the Size in Bytes.
1145
527
  QualType ElementType = NE->getAllocatedType();
1146
527
  ASTContext &AstContext = C.getASTContext();
1147
527
  CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1148
527
1149
527
  if (ElementCount.getAs<NonLoc>()) {
1150
527
    DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1151
527
    // size in Bytes = ElementCount*TypeSize
1152
527
    SVal SizeInBytes = svalBuilder.evalBinOpNN(
1153
527
        State, BO_Mul, ElementCount.castAs<NonLoc>(),
1154
527
        svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1155
527
        svalBuilder.getArrayIndexType());
1156
527
    DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1157
527
        State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1158
527
    State = State->assume(extentMatchesSize, true);
1159
527
  }
1160
527
  return State;
1161
527
}
1162
1163
void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1164
413
                                 CheckerContext &C) const {
1165
413
1166
413
  if (!ChecksEnabled[CK_NewDeleteChecker])
1167
116
    if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1168
82
      checkUseAfterFree(Sym, C, DE->getArgument());
1169
413
1170
413
  if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1171
0
    return;
1172
413
1173
413
  ProgramStateRef State = C.getState();
1174
413
  bool ReleasedAllocated;
1175
413
  State = FreeMemAux(C, DE->getArgument(), DE, State,
1176
413
                     /*Hold*/false, ReleasedAllocated);
1177
413
1178
413
  C.addTransition(State);
1179
413
}
1180
1181
149
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1182
149
  // If the first selector piece is one of the names below, assume that the
1183
149
  // object takes ownership of the memory, promising to eventually deallocate it
1184
149
  // with free().
1185
149
  // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1186
149
  // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1187
149
  StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1188
149
  return FirstSlot == "dataWithBytesNoCopy" ||
1189
149
         
FirstSlot == "initWithBytesNoCopy"126
||
1190
149
         
FirstSlot == "initWithCharactersNoCopy"114
;
1191
149
}
1192
1193
57
static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1194
57
  Selector S = Call.getSelector();
1195
57
1196
57
  // FIXME: We should not rely on fully-constrained symbols being folded.
1197
100
  for (unsigned i = 1; i < S.getNumArgs(); 
++i43
)
1198
77
    if (S.getNameForSlot(i).equals("freeWhenDone"))
1199
34
      return !Call.getArgSVal(i).isZeroConstant();
1200
57
1201
57
  
return None23
;
1202
57
}
1203
1204
void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1205
94
                                         CheckerContext &C) const {
1206
94
  if (C.wasInlined)
1207
1
    return;
1208
93
1209
93
  if (!isKnownDeallocObjCMethodName(Call))
1210
61
    return;
1211
32
1212
32
  if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1213
30
    if (!*FreeWhenDone)
1214
4
      return;
1215
28
1216
28
  bool ReleasedAllocatedMemory;
1217
28
  ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1218
28
                                     Call.getOriginExpr(), C.getState(),
1219
28
                                     /*Hold=*/true, ReleasedAllocatedMemory,
1220
28
                                     /*ReturnsNullOnFailure=*/true);
1221
28
1222
28
  C.addTransition(State);
1223
28
}
1224
1225
ProgramStateRef
1226
MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1227
                                    const OwnershipAttr *Att,
1228
19
                                    ProgramStateRef State) const {
1229
19
  if (!State)
1230
0
    return nullptr;
1231
19
1232
19
  if (Att->getModule() != II_malloc)
1233
0
    return nullptr;
1234
19
1235
19
  OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1236
19
  if (I != E) {
1237
1
    return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1238
1
                        State);
1239
1
  }
1240
18
  return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1241
18
}
1242
1243
ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1244
                                            const CallExpr *CE,
1245
                                            const Expr *SizeEx, SVal Init,
1246
                                            ProgramStateRef State,
1247
648
                                            AllocationFamily Family) {
1248
648
  if (!State)
1249
0
    return nullptr;
1250
648
1251
648
  return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
1252
648
}
1253
1254
ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1255
                                           const CallExpr *CE,
1256
                                           SVal Size, SVal Init,
1257
                                           ProgramStateRef State,
1258
777
                                           AllocationFamily Family) {
1259
777
  if (!State)
1260
0
    return nullptr;
1261
777
1262
777
  // We expect the malloc functions to return a pointer.
1263
777
  if (!Loc::isLocType(CE->getType()))
1264
2
    return nullptr;
1265
775
1266
775
  // Bind the return value to the symbolic value from the heap region.
1267
775
  // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1268
775
  // side effects other than what we model here.
1269
775
  unsigned Count = C.blockCount();
1270
775
  SValBuilder &svalBuilder = C.getSValBuilder();
1271
775
  const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1272
775
  DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1273
775
      .castAs<DefinedSVal>();
1274
775
  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1275
775
1276
775
  // Fill the region with the initialization value.
1277
775
  State = State->bindDefaultInitial(RetVal, Init, LCtx);
1278
775
1279
775
  // Set the region's extent equal to the Size parameter.
1280
775
  const SymbolicRegion *R =
1281
775
      dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1282
775
  if (!R)
1283
0
    return nullptr;
1284
775
  if (Optional<DefinedOrUnknownSVal> DefinedSize =
1285
775
          Size.getAs<DefinedOrUnknownSVal>()) {
1286
775
    SValBuilder &svalBuilder = C.getSValBuilder();
1287
775
    DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1288
775
    DefinedOrUnknownSVal extentMatchesSize =
1289
775
        svalBuilder.evalEQ(State, Extent, *DefinedSize);
1290
775
1291
775
    State = State->assume(extentMatchesSize, true);
1292
775
    assert(State);
1293
775
  }
1294
775
1295
775
  return MallocUpdateRefState(C, CE, State, Family);
1296
775
}
1297
1298
ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1299
                                                    const Expr *E,
1300
                                                    ProgramStateRef State,
1301
                                                    AllocationFamily Family,
1302
1.39k
                                                    Optional<SVal> RetVal) {
1303
1.39k
  if (!State)
1304
0
    return nullptr;
1305
1.39k
1306
1.39k
  // Get the return value.
1307
1.39k
  if (!RetVal)
1308
864
    RetVal = C.getSVal(E);
1309
1.39k
1310
1.39k
  // We expect the malloc functions to return a pointer.
1311
1.39k
  if (!RetVal->getAs<Loc>())
1312
1
    return nullptr;
1313
1.39k
1314
1.39k
  SymbolRef Sym = RetVal->getAsLocSymbol();
1315
1.39k
  // This is a return value of a function that was not inlined, such as malloc()
1316
1.39k
  // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1317
1.39k
  assert(Sym);
1318
1.39k
1319
1.39k
  // Set the symbol's state to Allocated.
1320
1.39k
  return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1321
1.39k
}
1322
1323
ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1324
                                           const CallExpr *CE,
1325
                                           const OwnershipAttr *Att,
1326
10
                                           ProgramStateRef State) const {
1327
10
  if (!State)
1328
0
    return nullptr;
1329
10
1330
10
  if (Att->getModule() != II_malloc)
1331
0
    return nullptr;
1332
10
1333
10
  bool ReleasedAllocated = false;
1334
10
1335
11
  for (const auto &Arg : Att->args()) {
1336
11
    ProgramStateRef StateI = FreeMemAux(
1337
11
        C, CE, State, Arg.getASTIndex(),
1338
11
        Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
1339
11
    if (StateI)
1340
6
      State = StateI;
1341
11
  }
1342
10
  return State;
1343
10
}
1344
1345
ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1346
                                          const CallExpr *CE,
1347
                                          ProgramStateRef State,
1348
                                          unsigned Num,
1349
                                          bool Hold,
1350
                                          bool &ReleasedAllocated,
1351
521
                                          bool ReturnsNullOnFailure) const {
1352
521
  if (!State)
1353
0
    return nullptr;
1354
521
1355
521
  if (CE->getNumArgs() < (Num + 1))
1356
3
    return nullptr;
1357
518
1358
518
  return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1359
518
                    ReleasedAllocated, ReturnsNullOnFailure);
1360
518
}
1361
1362
/// Checks if the previous call to free on the given symbol failed - if free
1363
/// failed, returns true. Also, returns the corresponding return value symbol.
1364
static bool didPreviousFreeFail(ProgramStateRef State,
1365
75
                                SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1366
75
  const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1367
75
  if (Ret) {
1368
10
    assert(*Ret && "We should not store the null return symbol");
1369
10
    ConstraintManager &CMgr = State->getConstraintManager();
1370
10
    ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1371
10
    RetStatusSymbol = *Ret;
1372
10
    return FreeFailed.isConstrainedTrue();
1373
10
  }
1374
65
  return false;
1375
65
}
1376
1377
AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1378
902
                                                    const Stmt *S) const {
1379
902
  if (!S)
1380
0
    return AF_None;
1381
902
1382
902
  if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1383
490
    const FunctionDecl *FD = C.getCalleeDecl(CE);
1384
490
1385
490
    if (!FD)
1386
16
      FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1387
490
1388
490
    ASTContext &Ctx = C.getASTContext();
1389
490
1390
490
    if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1391
482
      return AF_Malloc;
1392
8
1393
8
    if (isStandardNewDelete(FD, Ctx)) {
1394
8
      OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1395
8
      if (Kind == OO_New || Kind == OO_Delete)
1396
6
        return AF_CXXNew;
1397
2
      else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1398
2
        return AF_CXXNewArray;
1399
0
    }
1400
0
1401
0
    if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1402
0
      return AF_IfNameIndex;
1403
0
1404
0
    if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1405
0
      return AF_Alloca;
1406
0
1407
0
    return AF_None;
1408
0
  }
1409
412
1410
412
  if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1411
9
    return NE->isArray() ? 
AF_CXXNewArray4
:
AF_CXXNew5
;
1412
403
1413
403
  if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1414
378
    return DE->isArrayForm() ? 
AF_CXXNewArray61
:
AF_CXXNew317
;
1415
25
1416
25
  if (isa<ObjCMessageExpr>(S))
1417
25
    return AF_Malloc;
1418
0
1419
0
  return AF_None;
1420
0
}
1421
1422
bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1423
186
                                          const Expr *E) const {
1424
186
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1425
95
    // FIXME: This doesn't handle indirect calls.
1426
95
    const FunctionDecl *FD = CE->getDirectCallee();
1427
95
    if (!FD)
1428
0
      return false;
1429
95
1430
95
    os << *FD;
1431
95
    if (!FD->isOverloadedOperator())
1432
81
      os << "()";
1433
95
    return true;
1434
95
  }
1435
91
1436
91
  if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1437
3
    if (Msg->isInstanceMessage())
1438
0
      os << "-";
1439
3
    else
1440
3
      os << "+";
1441
3
    Msg->getSelector().print(os);
1442
3
    return true;
1443
3
  }
1444
88
1445
88
  if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1446
28
    os << "'"
1447
28
       << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1448
28
       << "'";
1449
28
    return true;
1450
28
  }
1451
60
1452
60
  if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1453
60
    os << "'"
1454
60
       << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1455
60
       << "'";
1456
60
    return true;
1457
60
  }
1458
0
1459
0
  return false;
1460
0
}
1461
1462
void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1463
43
                                           const Expr *E) const {
1464
43
  AllocationFamily Family = getAllocationFamily(C, E);
1465
43
1466
43
  switch(Family) {
1467
43
    
case AF_Malloc: os << "malloc()"; return23
;
1468
43
    
case AF_CXXNew: os << "'new'"; return12
;
1469
43
    
case AF_CXXNewArray: os << "'new[]'"; return8
;
1470
43
    
case AF_IfNameIndex: os << "'if_nameindex()'"; return0
;
1471
43
    
case AF_InnerBuffer: os << "container-specific allocator"; return0
;
1472
43
    case AF_Alloca:
1473
0
    case AF_None: llvm_unreachable("not a deallocation expression");
1474
43
  }
1475
43
}
1476
1477
void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1478
52
                                             AllocationFamily Family) const {
1479
52
  switch(Family) {
1480
52
    
case AF_Malloc: os << "free()"; return24
;
1481
52
    
case AF_CXXNew: os << "'delete'"; return12
;
1482
52
    
case AF_CXXNewArray: os << "'delete[]'"; return16
;
1483
52
    
case AF_IfNameIndex: os << "'if_freenameindex()'"; return0
;
1484
52
    
case AF_InnerBuffer: os << "container-specific deallocator"; return0
;
1485
52
    case AF_Alloca:
1486
0
    case AF_None: llvm_unreachable("suspicious argument");
1487
52
  }
1488
52
}
1489
1490
ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1491
                                          const Expr *ArgExpr,
1492
                                          const Expr *ParentExpr,
1493
                                          ProgramStateRef State,
1494
                                          bool Hold,
1495
                                          bool &ReleasedAllocated,
1496
959
                                          bool ReturnsNullOnFailure) const {
1497
959
1498
959
  if (!State)
1499
0
    return nullptr;
1500
959
1501
959
  SVal ArgVal = C.getSVal(ArgExpr);
1502
959
  if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1503
1
    return nullptr;
1504
958
  DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1505
958
1506
958
  // Check for null dereferences.
1507
958
  if (!location.getAs<Loc>())
1508
2
    return nullptr;
1509
956
1510
956
  // The explicit NULL case, no operation is performed.
1511
956
  ProgramStateRef notNullState, nullState;
1512
956
  std::tie(notNullState, nullState) = State->assume(location);
1513
956
  if (nullState && 
!notNullState533
)
1514
29
    return nullptr;
1515
927
1516
927
  // Unknown values could easily be okay
1517
927
  // Undefined values are handled elsewhere
1518
927
  if (ArgVal.isUnknownOrUndef())
1519
0
    return nullptr;
1520
927
1521
927
  const MemRegion *R = ArgVal.getAsRegion();
1522
927
1523
927
  // Nonlocs can't be freed, of course.
1524
927
  // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1525
927
  if (!R) {
1526
4
    ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1527
4
    return nullptr;
1528
4
  }
1529
923
1530
923
  R = R->StripCasts();
1531
923
1532
923
  // Blocks might show up as heap data, but should not be free()d
1533
923
  if (isa<BlockDataRegion>(R)) {
1534
2
    ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1535
2
    return nullptr;
1536
2
  }
1537
921
1538
921
  const MemSpaceRegion *MS = R->getMemorySpace();
1539
921
1540
921
  // Parameters, locals, statics, globals, and memory returned by
1541
921
  // __builtin_alloca() shouldn't be freed.
1542
921
  if (!(isa<UnknownSpaceRegion>(MS) || 
isa<HeapSpaceRegion>(MS)729
)) {
1543
62
    // FIXME: at the time this code was written, malloc() regions were
1544
62
    // represented by conjured symbols, which are all in UnknownSpaceRegion.
1545
62
    // This means that there isn't actually anything from HeapSpaceRegion
1546
62
    // that should be freed, even though we allow it here.
1547
62
    // Of course, free() can work on memory allocated outside the current
1548
62
    // function, so UnknownSpaceRegion is always a possibility.
1549
62
    // False negatives are better than false positives.
1550
62
1551
62
    if (isa<AllocaRegion>(R))
1552
8
      ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1553
54
    else
1554
54
      ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1555
62
1556
62
    return nullptr;
1557
62
  }
1558
859
1559
859
  const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1560
859
  // Various cases could lead to non-symbol values here.
1561
859
  // For now, ignore them.
1562
859
  if (!SrBase)
1563
0
    return nullptr;
1564
859
1565
859
  SymbolRef SymBase = SrBase->getSymbol();
1566
859
  const RefState *RsBase = State->get<RegionState>(SymBase);
1567
859
  SymbolRef PreviousRetStatusSymbol = nullptr;
1568
859
1569
859
  if (RsBase) {
1570
696
1571
696
    // Memory returned by alloca() shouldn't be freed.
1572
696
    if (RsBase->getAllocationFamily() == AF_Alloca) {
1573
6
      ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1574
6
      return nullptr;
1575
6
    }
1576
690
1577
690
    // Check for double free first.
1578
690
    if ((RsBase->isReleased() || 
RsBase->isRelinquished()626
) &&
1579
690
        
!didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)75
) {
1580
69
      ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1581
69
                       SymBase, PreviousRetStatusSymbol);
1582
69
      return nullptr;
1583
69
1584
69
    // If the pointer is allocated or escaped, but we are now trying to free it,
1585
69
    // check that the call to free is proper.
1586
621
    } else if (RsBase->isAllocated() || 
RsBase->isAllocatedOfSizeZero()105
||
1587
621
               
RsBase->isEscaped()83
) {
1588
615
1589
615
      // Check if an expected deallocation function matches the real one.
1590
615
      bool DeallocMatchesAlloc =
1591
615
        RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1592
615
      if (!DeallocMatchesAlloc) {
1593
78
        ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1594
78
                                ParentExpr, RsBase, SymBase, Hold);
1595
78
        return nullptr;
1596
78
      }
1597
537
1598
537
      // Check if the memory location being freed is the actual location
1599
537
      // allocated, or an offset.
1600
537
      RegionOffset Offset = R->getAsOffset();
1601
537
      if (Offset.isValid() &&
1602
537
          !Offset.hasSymbolicOffset() &&
1603
537
          
Offset.getOffset() != 0536
) {
1604
29
        const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1605
29
        ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1606
29
                         AllocExpr);
1607
29
        return nullptr;
1608
29
      }
1609
677
    }
1610
690
  }
1611
677
1612
677
  if (SymBase->getType()->isFunctionPointerType()) {
1613
3
    ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1614
3
    return nullptr;
1615
3
  }
1616
674
1617
674
  ReleasedAllocated = (RsBase != nullptr) && 
(514
RsBase->isAllocated()514
||
1618
514
                                              
RsBase->isAllocatedOfSizeZero()67
);
1619
674
1620
674
  // Clean out the info on previous call to free return info.
1621
674
  State = State->remove<FreeReturnValue>(SymBase);
1622
674
1623
674
  // Keep track of the return value. If it is NULL, we will know that free
1624
674
  // failed.
1625
674
  if (ReturnsNullOnFailure) {
1626
21
    SVal RetVal = C.getSVal(ParentExpr);
1627
21
    SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1628
21
    if (RetStatusSymbol) {
1629
21
      C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1630
21
      State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1631
21
    }
1632
21
  }
1633
674
1634
674
  AllocationFamily Family = RsBase ? 
RsBase->getAllocationFamily()514
1635
674
                                   : 
getAllocationFamily(C, ParentExpr)160
;
1636
674
  // Normal free.
1637
674
  if (Hold)
1638
25
    return State->set<RegionState>(SymBase,
1639
25
                                   RefState::getRelinquished(Family,
1640
25
                                                             ParentExpr));
1641
649
1642
649
  return State->set<RegionState>(SymBase,
1643
649
                                 RefState::getReleased(Family, ParentExpr));
1644
649
}
1645
1646
Optional<MallocChecker::CheckKind>
1647
MallocChecker::getCheckIfTracked(AllocationFamily Family,
1648
679
                                 bool IsALeakCheck) const {
1649
679
  switch (Family) {
1650
679
  case AF_Malloc:
1651
354
  case AF_Alloca:
1652
354
  case AF_IfNameIndex: {
1653
354
    if (ChecksEnabled[CK_MallocChecker])
1654
303
      return CK_MallocChecker;
1655
51
    return None;
1656
51
  }
1657
295
  case AF_CXXNew:
1658
295
  case AF_CXXNewArray: {
1659
295
    if (IsALeakCheck) {
1660
93
      if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1661
67
        return CK_NewDeleteLeaksChecker;
1662
202
    }
1663
202
    else {
1664
202
      if (ChecksEnabled[CK_NewDeleteChecker])
1665
178
        return CK_NewDeleteChecker;
1666
50
    }
1667
50
    return None;
1668
50
  }
1669
50
  case AF_InnerBuffer: {
1670
30
    if (ChecksEnabled[CK_InnerPointerChecker])
1671
30
      return CK_InnerPointerChecker;
1672
0
    return None;
1673
0
  }
1674
0
  case AF_None: {
1675
0
    llvm_unreachable("no family");
1676
0
  }
1677
0
  }
1678
0
  llvm_unreachable("unhandled family");
1679
0
}
1680
1681
Optional<MallocChecker::CheckKind>
1682
MallocChecker::getCheckIfTracked(CheckerContext &C,
1683
                                 const Stmt *AllocDeallocStmt,
1684
84
                                 bool IsALeakCheck) const {
1685
84
  return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1686
84
                           IsALeakCheck);
1687
84
}
1688
1689
Optional<MallocChecker::CheckKind>
1690
MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1691
307
                                 bool IsALeakCheck) const {
1692
307
  if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1693
4
    return CK_MallocChecker;
1694
303
1695
303
  const RefState *RS = C.getState()->get<RegionState>(Sym);
1696
303
  assert(RS);
1697
303
  return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1698
303
}
1699
1700
4
bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1701
4
  if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1702
0
    os << "an integer (" << IntVal->getValue() << ")";
1703
4
  else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1704
2
    os << "a constant address (" << ConstAddr->getValue() << ")";
1705
2
  else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1706
2
    os << "the address of the label '" << Label->getLabel()->getName() << "'";
1707
0
  else
1708
0
    return false;
1709
4
1710
4
  return true;
1711
4
}
1712
1713
bool MallocChecker::SummarizeRegion(raw_ostream &os,
1714
39
                                    const MemRegion *MR) {
1715
39
  switch (MR->getKind()) {
1716
39
  case MemRegion::FunctionCodeRegionKind: {
1717
3
    const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1718
3
    if (FD)
1719
3
      os << "the address of the function '" << *FD << '\'';
1720
0
    else
1721
0
      os << "the address of a function";
1722
3
    return true;
1723
39
  }
1724
39
  case MemRegion::BlockCodeRegionKind:
1725
0
    os << "block text";
1726
0
    return true;
1727
39
  case MemRegion::BlockDataRegionKind:
1728
2
    // FIXME: where the block came from?
1729
2
    os << "a block";
1730
2
    return true;
1731
39
  default: {
1732
34
    const MemSpaceRegion *MS = MR->getMemorySpace();
1733
34
1734
34
    if (isa<StackLocalsSpaceRegion>(MS)) {
1735
28
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
1736
28
      const VarDecl *VD;
1737
28
      if (VR)
1738
26
        VD = VR->getDecl();
1739
2
      else
1740
2
        VD = nullptr;
1741
28
1742
28
      if (VD)
1743
26
        os << "the address of the local variable '" << VD->getName() << "'";
1744
2
      else
1745
2
        os << "the address of a local stack variable";
1746
28
      return true;
1747
28
    }
1748
6
1749
6
    if (isa<StackArgumentsSpaceRegion>(MS)) {
1750
2
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
1751
2
      const VarDecl *VD;
1752
2
      if (VR)
1753
2
        VD = VR->getDecl();
1754
0
      else
1755
0
        VD = nullptr;
1756
2
1757
2
      if (VD)
1758
2
        os << "the address of the parameter '" << VD->getName() << "'";
1759
0
      else
1760
0
        os << "the address of a parameter";
1761
2
      return true;
1762
2
    }
1763
4
1764
4
    if (isa<GlobalsSpaceRegion>(MS)) {
1765
4
      const VarRegion *VR = dyn_cast<VarRegion>(MR);
1766
4
      const VarDecl *VD;
1767
4
      if (VR)
1768
4
        VD = VR->getDecl();
1769
0
      else
1770
0
        VD = nullptr;
1771
4
1772
4
      if (VD) {
1773
4
        if (VD->isStaticLocal())
1774
2
          os << "the address of the static variable '" << VD->getName() << "'";
1775
2
        else
1776
2
          os << "the address of the global variable '" << VD->getName() << "'";
1777
4
      } else
1778
0
        os << "the address of a global variable";
1779
4
      return true;
1780
4
    }
1781
0
1782
0
    return false;
1783
0
  }
1784
39
  }
1785
39
}
1786
1787
void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1788
                                  SourceRange Range,
1789
60
                                  const Expr *DeallocExpr) const {
1790
60
1791
60
  if (!ChecksEnabled[CK_MallocChecker] &&
1792
60
      
!ChecksEnabled[CK_NewDeleteChecker]26
)
1793
4
    return;
1794
56
1795
56
  Optional<MallocChecker::CheckKind> CheckKind =
1796
56
      getCheckIfTracked(C, DeallocExpr);
1797
56
  if (!CheckKind.hasValue())
1798
13
    return;
1799
43
1800
43
  if (ExplodedNode *N = C.generateErrorNode()) {
1801
43
    if (!BT_BadFree[*CheckKind])
1802
17
      BT_BadFree[*CheckKind].reset(new BugType(
1803
17
          CheckNames[*CheckKind], "Bad free", categories::MemoryError));
1804
43
1805
43
    SmallString<100> buf;
1806
43
    llvm::raw_svector_ostream os(buf);
1807
43
1808
43
    const MemRegion *MR = ArgVal.getAsRegion();
1809
53
    while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1810
10
      MR = ER->getSuperRegion();
1811
43
1812
43
    os << "Argument to ";
1813
43
    if (!printAllocDeallocName(os, C, DeallocExpr))
1814
0
      os << "deallocator";
1815
43
1816
43
    os << " is ";
1817
43
    bool Summarized = MR ? 
SummarizeRegion(os, MR)39
1818
43
                         : 
SummarizeValue(os, ArgVal)4
;
1819
43
    if (Summarized)
1820
43
      os << ", which is not memory allocated by ";
1821
0
    else
1822
0
      os << "not memory allocated by ";
1823
43
1824
43
    printExpectedAllocName(os, C, DeallocExpr);
1825
43
1826
43
    auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1827
43
    R->markInteresting(MR);
1828
43
    R->addRange(Range);
1829
43
    C.emitReport(std::move(R));
1830
43
  }
1831
43
}
1832
1833
void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1834
14
                                     SourceRange Range) const {
1835
14
1836
14
  Optional<MallocChecker::CheckKind> CheckKind;
1837
14
1838
14
  if (ChecksEnabled[CK_MallocChecker])
1839
4
    CheckKind = CK_MallocChecker;
1840
10
  else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1841
2
    CheckKind = CK_MismatchedDeallocatorChecker;
1842
8
  else
1843
8
    return;
1844
6
1845
6
  if (ExplodedNode *N = C.generateErrorNode()) {
1846
6
    if (!BT_FreeAlloca[*CheckKind])
1847
4
      BT_FreeAlloca[*CheckKind].reset(new BugType(
1848
4
          CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
1849
6
1850
6
    auto R = llvm::make_unique<BugReport>(
1851
6
        *BT_FreeAlloca[*CheckKind],
1852
6
        "Memory allocated by alloca() should not be deallocated", N);
1853
6
    R->markInteresting(ArgVal.getAsRegion());
1854
6
    R->addRange(Range);
1855
6
    C.emitReport(std::move(R));
1856
6
  }
1857
6
}
1858
1859
void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1860
                                            SourceRange Range,
1861
                                            const Expr *DeallocExpr,
1862
                                            const RefState *RS,
1863
                                            SymbolRef Sym,
1864
78
                                            bool OwnershipTransferred) const {
1865
78
1866
78
  if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1867
24
    return;
1868
54
1869
54
  if (ExplodedNode *N = C.generateErrorNode()) {
1870
54
    if (!BT_MismatchedDealloc)
1871
10
      BT_MismatchedDealloc.reset(
1872
10
          new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1873
10
                      "Bad deallocator", categories::MemoryError));
1874
54
1875
54
    SmallString<100> buf;
1876
54
    llvm::raw_svector_ostream os(buf);
1877
54
1878
54
    const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1879
54
    SmallString<20> AllocBuf;
1880
54
    llvm::raw_svector_ostream AllocOs(AllocBuf);
1881
54
    SmallString<20> DeallocBuf;
1882
54
    llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1883
54
1884
54
    if (OwnershipTransferred) {
1885
2
      if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1886
2
        os << DeallocOs.str() << " cannot";
1887
0
      else
1888
0
        os << "Cannot";
1889
2
1890
2
      os << " take ownership of memory";
1891
2
1892
2
      if (printAllocDeallocName(AllocOs, C, AllocExpr))
1893
2
        os << " allocated by " << AllocOs.str();
1894
52
    } else {
1895
52
      os << "Memory";
1896
52
      if (printAllocDeallocName(AllocOs, C, AllocExpr))
1897
52
        os << " allocated by " << AllocOs.str();
1898
52
1899
52
      os << " should be deallocated by ";
1900
52
        printExpectedDeallocName(os, RS->getAllocationFamily());
1901
52
1902
52
      if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1903
52
        os << ", not " << DeallocOs.str();
1904
52
    }
1905
54
1906
54
    auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1907
54
    R->markInteresting(Sym);
1908
54
    R->addRange(Range);
1909
54
    R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1910
54
    C.emitReport(std::move(R));
1911
54
  }
1912
54
}
1913
1914
void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1915
                                     SourceRange Range, const Expr *DeallocExpr,
1916
29
                                     const Expr *AllocExpr) const {
1917
29
1918
29
1919
29
  if (!ChecksEnabled[CK_MallocChecker] &&
1920
29
      
!ChecksEnabled[CK_NewDeleteChecker]14
)
1921
4
    return;
1922
25
1923
25
  Optional<MallocChecker::CheckKind> CheckKind =
1924
25
      getCheckIfTracked(C, AllocExpr);
1925
25
  if (!CheckKind.hasValue())
1926
9
    return;
1927
16
1928
16
  ExplodedNode *N = C.generateErrorNode();
1929
16
  if (!N)
1930
0
    return;
1931
16
1932
16
  if (!BT_OffsetFree[*CheckKind])
1933
10
    BT_OffsetFree[*CheckKind].reset(new BugType(
1934
10
        CheckNames[*CheckKind], "Offset free", categories::MemoryError));
1935
16
1936
16
  SmallString<100> buf;
1937
16
  llvm::raw_svector_ostream os(buf);
1938
16
  SmallString<20> AllocNameBuf;
1939
16
  llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1940
16
1941
16
  const MemRegion *MR = ArgVal.getAsRegion();
1942
16
  assert(MR && "Only MemRegion based symbols can have offset free errors");
1943
16
1944
16
  RegionOffset Offset = MR->getAsOffset();
1945
16
  assert((Offset.isValid() &&
1946
16
          !Offset.hasSymbolicOffset() &&
1947
16
          Offset.getOffset() != 0) &&
1948
16
         "Only symbols with a valid offset can have offset free errors");
1949
16
1950
16
  int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1951
16
1952
16
  os << "Argument to ";
1953
16
  if (!printAllocDeallocName(os, C, DeallocExpr))
1954
0
    os << "deallocator";
1955
16
  os << " is offset by "
1956
16
     << offsetBytes
1957
16
     << " "
1958
16
     << ((abs(offsetBytes) > 1) ? 
"bytes"14
:
"byte"2
)
1959
16
     << " from the start of ";
1960
16
  if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1961
16
    os << "memory allocated by " << AllocNameOs.str();
1962
0
  else
1963
0
    os << "allocated memory";
1964
16
1965
16
  auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1966
16
  R->markInteresting(MR->getBaseRegion());
1967
16
  R->addRange(Range);
1968
16
  C.emitReport(std::move(R));
1969
16
}
1970
1971
void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1972
211
                                       SymbolRef Sym) const {
1973
211
1974
211
  if (!ChecksEnabled[CK_MallocChecker] &&
1975
211
      
!ChecksEnabled[CK_NewDeleteChecker]155
&&
1976
211
      
!ChecksEnabled[CK_InnerPointerChecker]52
)
1977
22
    return;
1978
189
1979
189
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1980
189
  if (!CheckKind.hasValue())
1981
20
    return;
1982
169
1983
169
  if (ExplodedNode *N = C.generateErrorNode()) {
1984
169
    if (!BT_UseFree[*CheckKind])
1985
39
      BT_UseFree[*CheckKind].reset(new BugType(
1986
39
          CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
1987
169
1988
169
    AllocationFamily AF =
1989
169
        C.getState()->get<RegionState>(Sym)->getAllocationFamily();
1990
169
1991
169
    auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1992
169
        AF == AF_InnerBuffer
1993
169
              ? 
"Inner pointer of container used after re/deallocation"30
1994
169
              : 
"Use of memory after it is freed"139
,
1995
169
        N);
1996
169
1997
169
    R->markInteresting(Sym);
1998
169
    R->addRange(Range);
1999
169
    R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2000
169
2001
169
    if (AF == AF_InnerBuffer)
2002
30
      R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2003
169
2004
169
    C.emitReport(std::move(R));
2005
169
  }
2006
169
}
2007
2008
void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
2009
                                     bool Released, SymbolRef Sym,
2010
69
                                     SymbolRef PrevSym) const {
2011
69
2012
69
  if (!ChecksEnabled[CK_MallocChecker] &&
2013
69
      
!ChecksEnabled[CK_NewDeleteChecker]24
)
2014
10
    return;
2015
59
2016
59
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2017
59
  if (!CheckKind.hasValue())
2018
9
    return;
2019
50
2020
50
  if (ExplodedNode *N = C.generateErrorNode()) {
2021
46
    if (!BT_DoubleFree[*CheckKind])
2022
22
      BT_DoubleFree[*CheckKind].reset(new BugType(
2023
22
          CheckNames[*CheckKind], "Double free", categories::MemoryError));
2024
46
2025
46
    auto R = llvm::make_unique<BugReport>(
2026
46
        *BT_DoubleFree[*CheckKind],
2027
46
        (Released ? 
"Attempt to free released memory"41
2028
46
                  : 
"Attempt to free non-owned memory"5
),
2029
46
        N);
2030
46
    R->addRange(Range);
2031
46
    R->markInteresting(Sym);
2032
46
    if (PrevSym)
2033
4
      R->markInteresting(PrevSym);
2034
46
    R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2035
46
    C.emitReport(std::move(R));
2036
46
  }
2037
50
}
2038
2039
16
void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2040
16
2041
16
  if (!ChecksEnabled[CK_NewDeleteChecker])
2042
0
    return;
2043
16
2044
16
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2045
16
  if (!CheckKind.hasValue())
2046
0
    return;
2047
16
2048
16
  if (ExplodedNode *N = C.generateErrorNode()) {
2049
16
    if (!BT_DoubleDelete)
2050
8
      BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2051
8
                                        "Double delete",
2052
8
                                        categories::MemoryError));
2053
16
2054
16
    auto R = llvm::make_unique<BugReport>(
2055
16
        *BT_DoubleDelete, "Attempt to delete released memory", N);
2056
16
2057
16
    R->markInteresting(Sym);
2058
16
    R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2059
16
    C.emitReport(std::move(R));
2060
16
  }
2061
16
}
2062
2063
void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2064
                                           SourceRange Range,
2065
43
                                           SymbolRef Sym) const {
2066
43
2067
43
  if (!ChecksEnabled[CK_MallocChecker] &&
2068
43
      
!ChecksEnabled[CK_NewDeleteChecker]28
)
2069
0
    return;
2070
43
2071
43
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2072
43
2073
43
  if (!CheckKind.hasValue())
2074
7
    return;
2075
36
2076
36
  if (ExplodedNode *N = C.generateErrorNode()) {
2077
36
    if (!BT_UseZerroAllocated[*CheckKind])
2078
9
      BT_UseZerroAllocated[*CheckKind].reset(
2079
9
          new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2080
9
                      categories::MemoryError));
2081
36
2082
36
    auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2083
36
                                         "Use of zero-allocated memory", N);
2084
36
2085
36
    R->addRange(Range);
2086
36
    if (Sym) {
2087
36
      R->markInteresting(Sym);
2088
36
      R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2089
36
    }
2090
36
    C.emitReport(std::move(R));
2091
36
  }
2092
36
}
2093
2094
void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2095
                                              SourceRange Range,
2096
3
                                              const Expr *FreeExpr) const {
2097
3
  if (!ChecksEnabled[CK_MallocChecker])
2098
0
    return;
2099
3
2100
3
  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2101
3
  if (!CheckKind.hasValue())
2102
0
    return;
2103
3
2104
3
  if (ExplodedNode *N = C.generateErrorNode()) {
2105
3
    if (!BT_BadFree[*CheckKind])
2106
2
      BT_BadFree[*CheckKind].reset(new BugType(
2107
2
          CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2108
3
2109
3
    SmallString<100> Buf;
2110
3
    llvm::raw_svector_ostream Os(Buf);
2111
3
2112
3
    const MemRegion *MR = ArgVal.getAsRegion();
2113
3
    while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2114
0
      MR = ER->getSuperRegion();
2115
3
2116
3
    Os << "Argument to ";
2117
3
    if (!printAllocDeallocName(Os, C, FreeExpr))
2118
0
      Os << "deallocator";
2119
3
2120
3
    Os << " is a function pointer";
2121
3
2122
3
    auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2123
3
    R->markInteresting(MR);
2124
3
    R->addRange(Range);
2125
3
    C.emitReport(std::move(R));
2126
3
  }
2127
3
}
2128
2129
ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2130
                                             const CallExpr *CE,
2131
                                             bool FreesOnFail,
2132
                                             ProgramStateRef State,
2133
88
                                             bool SuffixWithN) const {
2134
88
  if (!State)
2135
0
    return nullptr;
2136
88
2137
88
  if (SuffixWithN && 
CE->getNumArgs() < 314
)
2138
0
    return nullptr;
2139
88
  else if (CE->getNumArgs() < 2)
2140
1
    return nullptr;
2141
87
2142
87
  const Expr *arg0Expr = CE->getArg(0);
2143
87
  SVal Arg0Val = C.getSVal(arg0Expr);
2144
87
  if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2145
0
    return nullptr;
2146
87
  DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2147
87
2148
87
  SValBuilder &svalBuilder = C.getSValBuilder();
2149
87
2150
87
  DefinedOrUnknownSVal PtrEQ =
2151
87
    svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2152
87
2153
87
  // Get the size argument.
2154
87
  const Expr *Arg1 = CE->getArg(1);
2155
87
2156
87
  // Get the value of the size argument.
2157
87
  SVal TotalSize = C.getSVal(Arg1);
2158
87
  if (SuffixWithN)
2159
14
    TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2160
87
  if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2161
0
    return nullptr;
2162
87
2163
87
  // Compare the size argument to 0.
2164
87
  DefinedOrUnknownSVal SizeZero =
2165
87
    svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2166
87
                       svalBuilder.makeIntValWithPtrWidth(0, false));
2167
87
2168
87
  ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2169
87
  std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2170
87
  ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2171
87
  std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2172
87
  // We only assume exceptional states if they are definitely true; if the
2173
87
  // state is under-constrained, assume regular realloc behavior.
2174
87
  bool PrtIsNull = StatePtrIsNull && 
!StatePtrNotNull80
;
2175
87
  bool SizeIsZero = StateSizeIsZero && 
!StateSizeNotZero24
;
2176
87
2177
87
  // If the ptr is NULL and the size is not 0, the call is equivalent to
2178
87
  // malloc(size).
2179
87
  if (PrtIsNull && 
!SizeIsZero9
) {
2180
5
    ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2181
5
                                               UndefinedVal(), StatePtrIsNull);
2182
5
    return stateMalloc;
2183
5
  }
2184
82
2185
82
  if (PrtIsNull && 
SizeIsZero4
)
2186
4
    return State;
2187
78
2188
78
  // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2189
78
  assert(!PrtIsNull);
2190
78
  SymbolRef FromPtr = arg0Val.getAsSymbol();
2191
78
  SVal RetVal = C.getSVal(CE);
2192
78
  SymbolRef ToPtr = RetVal.getAsSymbol();
2193
78
  if (!FromPtr || !ToPtr)
2194
0
    return nullptr;
2195
78
2196
78
  bool ReleasedAllocated = false;
2197
78
2198
78
  // If the size is 0, free the memory.
2199
78
  if (SizeIsZero)
2200
17
    if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2201
15
                                               false, ReleasedAllocated)){
2202
15
      // The semantics of the return value are:
2203
15
      // If size was equal to 0, either NULL or a pointer suitable to be passed
2204
15
      // to free() is returned. We just free the input pointer and do not add
2205
15
      // any constrains on the output pointer.
2206
15
      return stateFree;
2207
15
    }
2208
63
2209
63
  // Default behavior.
2210
63
  if (ProgramStateRef stateFree =
2211
54
        FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2212
54
2213
54
    ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2214
54
                                                UnknownVal(), stateFree);
2215
54
    if (!stateRealloc)
2216
0
      return nullptr;
2217
54
2218
54
    ReallocPairKind Kind = RPToBeFreedAfterFailure;
2219
54
    if (FreesOnFail)
2220
3
      Kind = RPIsFreeOnFailure;
2221
51
    else if (!ReleasedAllocated)
2222
6
      Kind = RPDoNotTrackAfterFailure;
2223
54
2224
54
    // Record the info about the reallocated symbol so that we could properly
2225
54
    // process failed reallocation.
2226
54
    stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2227
54
                                                   ReallocPair(FromPtr, Kind));
2228
54
    // The reallocated symbol should stay alive for as long as the new symbol.
2229
54
    C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2230
54
    return stateRealloc;
2231
54
  }
2232
9
  return nullptr;
2233
9
}
2234
2235
ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2236
25
                                         ProgramStateRef State) {
2237
25
  if (!State)
2238
0
    return nullptr;
2239
25
2240
25
  if (CE->getNumArgs() < 2)
2241
1
    return nullptr;
2242
24
2243
24
  SValBuilder &svalBuilder = C.getSValBuilder();
2244
24
  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2245
24
  SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2246
24
2247
24
  return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2248
24
}
2249
2250
LeakInfo
2251
MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2252
249
                                 CheckerContext &C) const {
2253
249
  const LocationContext *LeakContext = N->getLocationContext();
2254
249
  // Walk the ExplodedGraph backwards and find the first node that referred to
2255
249
  // the tracked symbol.
2256
249
  const ExplodedNode *AllocNode = N;
2257
249
  const MemRegion *ReferenceRegion = nullptr;
2258
249
2259
8.11k
  while (N) {
2260
8.11k
    ProgramStateRef State = N->getState();
2261
8.11k
    if (!State->get<RegionState>(Sym))
2262
249
      break;
2263
7.86k
2264
7.86k
    // Find the most recent expression bound to the symbol in the current
2265
7.86k
    // context.
2266
7.86k
      if (!ReferenceRegion) {
2267
6.54k
        if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2268
338
          SVal Val = State->getSVal(MR);
2269
338
          if (Val.getAsLocSymbol() == Sym) {
2270
228
            const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2271
228
            // Do not show local variables belonging to a function other than
2272
228
            // where the error is reported.
2273
228
            if (!VR ||
2274
228
                (VR->getStackFrame() == LeakContext->getStackFrame()))
2275
223
              ReferenceRegion = MR;
2276
228
          }
2277
338
        }
2278
6.54k
      }
2279
7.86k
2280
7.86k
    // Allocation node, is the last node in the current or parent context in
2281
7.86k
    // which the symbol was tracked.
2282
7.86k
    const LocationContext *NContext = N->getLocationContext();
2283
7.86k
    if (NContext == LeakContext ||
2284
7.86k
        
NContext->isParentOf(LeakContext)567
)
2285
7.31k
      AllocNode = N;
2286
7.86k
    N = N->pred_empty() ? 
nullptr0
: *(N->pred_begin());
2287
7.86k
  }
2288
249
2289
249
  return LeakInfo(AllocNode, ReferenceRegion);
2290
249
}
2291
2292
void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2293
349
                               CheckerContext &C) const {
2294
349
2295
349
  if (!ChecksEnabled[CK_MallocChecker] &&
2296
349
      
!ChecksEnabled[CK_NewDeleteLeaksChecker]136
)
2297
51
    return;
2298
298
2299
298
  const RefState *RS = C.getState()->get<RegionState>(Sym);
2300
298
  assert(RS && "cannot leak an untracked symbol");
2301
298
  AllocationFamily Family = RS->getAllocationFamily();
2302
298
2303
298
  if (Family == AF_Alloca)
2304
6
    return;
2305
292
2306
292
  Optional<MallocChecker::CheckKind>
2307
292
      CheckKind = getCheckIfTracked(Family, true);
2308
292
2309
292
  if (!CheckKind.hasValue())
2310
43
    return;
2311
249
2312
249
  assert(N);
2313
249
  if (!BT_Leak[*CheckKind]) {
2314
60
    // Leaks should not be reported if they are post-dominated by a sink:
2315
60
    // (1) Sinks are higher importance bugs.
2316
60
    // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2317
60
    //     with __noreturn functions such as assert() or exit(). We choose not
2318
60
    //     to report leaks on such paths.
2319
60
    BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2320
60
                                          categories::MemoryError,
2321
60
                                          /*SuppressOnSink=*/true));
2322
60
  }
2323
249
2324
249
  // Most bug reports are cached at the location where they occurred.
2325
249
  // With leaks, we want to unique them by the location where they were
2326
249
  // allocated, and only report a single path.
2327
249
  PathDiagnosticLocation LocUsedForUniqueing;
2328
249
  const ExplodedNode *AllocNode = nullptr;
2329
249
  const MemRegion *Region = nullptr;
2330
249
  std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2331
249
2332
249
  const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2333
249
  if (AllocationStmt)
2334
249
    LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2335
249
                                              C.getSourceManager(),
2336
249
                                              AllocNode->getLocationContext());
2337
249
2338
249
  SmallString<200> buf;
2339
249
  llvm::raw_svector_ostream os(buf);
2340
249
  if (Region && 
Region->canPrintPretty()223
) {
2341
219
    os << "Potential leak of memory pointed to by ";
2342
219
    Region->printPretty(os);
2343
219
  } else {
2344
30
    os << "Potential memory leak";
2345
30
  }
2346
249
2347
249
  auto R = llvm::make_unique<BugReport>(
2348
249
      *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2349
249
      AllocNode->getLocationContext()->getDecl());
2350
249
  R->markInteresting(Sym);
2351
249
  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2352
249
  C.emitReport(std::move(R));
2353
249
}
2354
2355
void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2356
                                     CheckerContext &C) const
2357
105k
{
2358
105k
  ProgramStateRef state = C.getState();
2359
105k
  RegionStateTy OldRS = state->get<RegionState>();
2360
105k
  RegionStateTy::Factory &F = state->get_context<RegionState>();
2361
105k
2362
105k
  RegionStateTy RS = OldRS;
2363
105k
  SmallVector<SymbolRef, 2> Errors;
2364
117k
  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; 
++I11.3k
) {
2365
11.3k
    if (SymReaper.isDead(I->first)) {
2366
1.10k
      if (I->second.isAllocated() || 
I->second.isAllocatedOfSizeZero()797
)
2367
349
        Errors.push_back(I->first);
2368
1.10k
      // Remove the dead symbol from the map.
2369
1.10k
      RS = F.remove(RS, I->first);
2370
1.10k
    }
2371
11.3k
  }
2372
105k
2373
105k
  if (RS == OldRS) {
2374
104k
    // We shouldn't have touched other maps yet.
2375
104k
    assert(state->get<ReallocPairs>() ==
2376
104k
           C.getState()->get<ReallocPairs>());
2377
104k
    assert(state->get<FreeReturnValue>() ==
2378
104k
           C.getState()->get<FreeReturnValue>());
2379
104k
    return;
2380
104k
  }
2381
993
2382
993
  // Cleanup the Realloc Pairs Map.
2383
993
  ReallocPairsTy RP = state->get<ReallocPairs>();
2384
1.11k
  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; 
++I125
) {
2385
125
    if (SymReaper.isDead(I->first) ||
2386
125
        
SymReaper.isDead(I->second.ReallocatedSym)79
) {
2387
46
      state = state->remove<ReallocPairs>(I->first);
2388
46
    }
2389
125
  }
2390
993
2391
993
  // Cleanup the FreeReturnValue Map.
2392
993
  FreeReturnValueTy FR = state->get<FreeReturnValue>();
2393
1.01k
  for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; 
++I18
) {
2394
18
    if (SymReaper.isDead(I->first) ||
2395
18
        
SymReaper.isDead(I->second)0
) {
2396
18
      state = state->remove<FreeReturnValue>(I->first);
2397
18
    }
2398
18
  }
2399
993
2400
993
  // Generate leak node.
2401
993
  ExplodedNode *N = C.getPredecessor();
2402
993
  if (!Errors.empty()) {
2403
345
    static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2404
345
    N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2405
345
    if (N) {
2406
345
      for (SmallVectorImpl<SymbolRef>::iterator
2407
694
           I = Errors.begin(), E = Errors.end(); I != E; 
++I349
) {
2408
349
        reportLeak(*I, N, C);
2409
349
      }
2410
345
    }
2411
345
  }
2412
993
2413
993
  C.addTransition(state->set<RegionState>(RS), N);
2414
993
}
2415
2416
void MallocChecker::checkPreCall(const CallEvent &Call,
2417
26.7k
                                 CheckerContext &C) const {
2418
26.7k
2419
26.7k
  if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2420
807
    SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2421
807
    if (!Sym || 
checkDoubleDelete(Sym, C)76
)
2422
747
      return;
2423
25.9k
  }
2424
25.9k
2425
25.9k
  // We will check for double free in the post visit.
2426
25.9k
  if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2427
25.8k
    const FunctionDecl *FD = FC->getDecl();
2428
25.8k
    if (!FD)
2429
8
      return;
2430
25.8k
2431
25.8k
    ASTContext &Ctx = C.getASTContext();
2432
25.8k
    if (ChecksEnabled[CK_MallocChecker] &&
2433
25.8k
        
(9.55k
isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free)9.55k
||
2434
9.55k
         isCMemFunction(FD, Ctx, AF_IfNameIndex,
2435
9.13k
                        MemoryOperationKind::MOK_Free)))
2436
418
      return;
2437
25.5k
  }
2438
25.5k
2439
25.5k
  // Check if the callee of a method is deleted.
2440
25.5k
  if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2441
2.10k
    SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2442
2.10k
    if (!Sym || 
checkUseAfterFree(Sym, C, CC->getCXXThisExpr())1.01k
)
2443
1.09k
      return;
2444
24.4k
  }
2445
24.4k
2446
24.4k
  // Check arguments for being used after free.
2447
47.4k
  
for (unsigned I = 0, E = Call.getNumArgs(); 24.4k
I != E;
++I23.0k
) {
2448
23.1k
    SVal ArgSVal = Call.getArgSVal(I);
2449
23.1k
    if (ArgSVal.getAs<Loc>()) {
2450
12.8k
      SymbolRef Sym = ArgSVal.getAsSymbol();
2451
12.8k
      if (!Sym)
2452
10.0k
        continue;
2453
2.84k
      if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2454
129
        return;
2455
2.84k
    }
2456
23.1k
  }
2457
24.4k
}
2458
2459
void MallocChecker::checkPreStmt(const ReturnStmt *S,
2460
6.39k
                                 CheckerContext &C) const {
2461
6.39k
  checkEscapeOnReturn(S, C);
2462
6.39k
}
2463
2464
// In the CFG, automatic destructors come after the return statement.
2465
// This callback checks for returning memory that is freed by automatic
2466
// destructors, as those cannot be reached in checkPreStmt().
2467
void MallocChecker::checkEndFunction(const ReturnStmt *S,
2468
19.2k
                                     CheckerContext &C) const {
2469
19.2k
  checkEscapeOnReturn(S, C);
2470
19.2k
}
2471
2472
void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2473
25.6k
                                        CheckerContext &C) const {
2474
25.6k
  if (!S)
2475
12.9k
    return;
2476
12.7k
2477
12.7k
  const Expr *E = S->getRetValue();
2478
12.7k
  if (!E)
2479
211
    return;
2480
12.5k
2481
12.5k
  // Check if we are returning a symbol.
2482
12.5k
  ProgramStateRef State = C.getState();
2483
12.5k
  SVal RetVal = C.getSVal(E);
2484
12.5k
  SymbolRef Sym = RetVal.getAsSymbol();
2485
12.5k
  if (!Sym)
2486
11.6k
    // If we are returning a field of the allocated struct or an array element,
2487
11.6k
    // the callee could still free the memory.
2488
11.6k
    // TODO: This logic should be a part of generic symbol escape callback.
2489
11.6k
    if (const MemRegion *MR = RetVal.getAsRegion())
2490
374
      if (isa<FieldRegion>(MR) || 
isa<ElementRegion>(MR)190
)
2491
256
        if (const SymbolicRegion *BMR =
2492
158
              dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2493
158
          Sym = BMR->getSymbol();
2494
12.5k
2495
12.5k
  // Check if we are returning freed memory.
2496
12.5k
  if (Sym)
2497
1.06k
    checkUseAfterFree(Sym, C, E);
2498
12.5k
}
2499
2500
// TODO: Blocks should be either inlined or should call invalidate regions
2501
// upon invocation. After that's in place, special casing here will not be
2502
// needed.
2503
void MallocChecker::checkPostStmt(const BlockExpr *BE,
2504
50
                                  CheckerContext &C) const {
2505
50
2506
50
  // Scan the BlockDecRefExprs for any object the retain count checker
2507
50
  // may be tracking.
2508
50
  if (!BE->getBlockDecl()->hasCaptures())
2509
45
    return;
2510
5
2511
5
  ProgramStateRef state = C.getState();
2512
5
  const BlockDataRegion *R =
2513
5
    cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2514
5
2515
5
  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2516
5
                                            E = R->referenced_vars_end();
2517
5
2518
5
  if (I == E)
2519
0
    return;
2520
5
2521
5
  SmallVector<const MemRegion*, 10> Regions;
2522
5
  const LocationContext *LC = C.getLocationContext();
2523
5
  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2524
5
2525
10
  for ( ; I != E; 
++I5
) {
2526
5
    const VarRegion *VR = I.getCapturedRegion();
2527
5
    if (VR->getSuperRegion() == R) {
2528
1
      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2529
1
    }
2530
5
    Regions.push_back(VR);
2531
5
  }
2532
5
2533
5
  state =
2534
5
    state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2535
5
  C.addTransition(state);
2536
5
}
2537
2538
18.6k
bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2539
18.6k
  assert(Sym);
2540
18.6k
  const RefState *RS = C.getState()->get<RegionState>(Sym);
2541
18.6k
  return (RS && 
RS->isReleased()2.07k
);
2542
18.6k
}
2543
2544
bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2545
421
    const CallExpr *CE, CheckerContext &C) const {
2546
421
  if (CE->getNumArgs() == 0)
2547
3
    return false;
2548
418
2549
418
  StringRef FunctionStr = "";
2550
418
  if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2551
415
    if (const Stmt *Body = FD->getBody())
2552
415
      if (Body->getBeginLoc().isValid())
2553
415
        FunctionStr =
2554
415
            Lexer::getSourceText(CharSourceRange::getTokenRange(
2555
415
                                     {FD->getBeginLoc(), Body->getBeginLoc()}),
2556
415
                                 C.getSourceManager(), C.getLangOpts());
2557
418
2558
418
  // We do not model the Integer Set Library's retain-count based allocation.
2559
418
  if (!FunctionStr.contains("__isl_"))
2560
417
    return false;
2561
1
2562
1
  ProgramStateRef State = C.getState();
2563
1
2564
1
  for (const Expr *Arg : CE->arguments())
2565
1
    if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2566
1
      if (const RefState *RS = State->get<RegionState>(Sym))
2567
0
        State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2568
1
2569
1
  C.addTransition(State);
2570
1
  return true;
2571
1
}
2572
2573
bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2574
18.5k
                                      const Stmt *S) const {
2575
18.5k
2576
18.5k
  if (isReleased(Sym, C)) {
2577
211
    ReportUseAfterFree(C, S->getSourceRange(), Sym);
2578
211
    return true;
2579
211
  }
2580
18.3k
2581
18.3k
  return false;
2582
18.3k
}
2583
2584
void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2585
13.5k
                                          const Stmt *S) const {
2586
13.5k
  assert(Sym);
2587
13.5k
2588
13.5k
  if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2589
651
    if (RS->isAllocatedOfSizeZero())
2590
39
      ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2591
651
  }
2592
12.9k
  else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2593
4
    ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2594
4
  }
2595
13.5k
}
2596
2597
76
bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2598
76
2599
76
  if (isReleased(Sym, C)) {
2600
16
    ReportDoubleDelete(C, Sym);
2601
16
    return true;
2602
16
  }
2603
60
  return false;
2604
60
}
2605
2606
// Check if the location is a freed symbolic region.
2607
void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2608
84.9k
                                  CheckerContext &C) const {
2609
84.9k
  SymbolRef Sym = l.getLocSymbolInBase();
2610
84.9k
  if (Sym) {
2611
13.5k
    checkUseAfterFree(Sym, C, S);
2612
13.5k
    checkUseZeroAllocated(Sym, C, S);
2613
13.5k
  }
2614
84.9k
}
2615
2616
// If a symbolic region is assumed to NULL (or another constant), stop tracking
2617
// it - assuming that allocation failed on this path.
2618
ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2619
                                              SVal Cond,
2620
156k
                                              bool Assumption) const {
2621
156k
  RegionStateTy RS = state->get<RegionState>();
2622
170k
  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; 
++I13.8k
) {
2623
13.8k
    // If the symbol is assumed to be NULL, remove it from consideration.
2624
13.8k
    ConstraintManager &CMgr = state->getConstraintManager();
2625
13.8k
    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2626
13.8k
    if (AllocFailed.isConstrainedTrue())
2627
668
      state = state->remove<RegionState>(I.getKey());
2628
13.8k
  }
2629
156k
2630
156k
  // Realloc returns 0 when reallocation fails, which means that we should
2631
156k
  // restore the state of the pointer being reallocated.
2632
156k
  ReallocPairsTy RP = state->get<ReallocPairs>();
2633
157k
  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; 
++I936
) {
2634
936
    // If the symbol is assumed to be NULL, remove it from consideration.
2635
936
    ConstraintManager &CMgr = state->getConstraintManager();
2636
936
    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2637
936
    if (!AllocFailed.isConstrainedTrue())
2638
898
      continue;
2639
38
2640
38
    SymbolRef ReallocSym = I.getData().ReallocatedSym;
2641
38
    if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2642
38
      if (RS->isReleased()) {
2643
38
        if (I.getData().Kind == RPToBeFreedAfterFailure)
2644
31
          state = state->set<RegionState>(ReallocSym,
2645
31
              RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2646
7
        else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2647
5
          state = state->remove<RegionState>(ReallocSym);
2648
7
        else
2649
7
          assert(I.getData().Kind == RPIsFreeOnFailure);
2650
38
      }
2651
38
    }
2652
38
    state = state->remove<ReallocPairs>(I.getKey());
2653
38
  }
2654
156k
2655
156k
  return state;
2656
156k
}
2657
2658
bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2659
                                              const CallEvent *Call,
2660
                                              ProgramStateRef State,
2661
1.24k
                                              SymbolRef &EscapingSymbol) const {
2662
1.24k
  assert(Call);
2663
1.24k
  EscapingSymbol = nullptr;
2664
1.24k
2665
1.24k
  // For now, assume that any C++ or block call can free memory.
2666
1.24k
  // TODO: If we want to be more optimistic here, we'll need to make sure that
2667
1.24k
  // regions escape to C++ containers. They seem to do that even now, but for
2668
1.24k
  // mysterious reasons.
2669
1.24k
  if (!(isa<SimpleFunctionCall>(Call) || 
isa<ObjCMethodCall>(Call)602
))
2670
534
    return true;
2671
707
2672
707
  // Check Objective-C messages by selector name.
2673
707
  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2674
68
    // If it's not a framework call, or if it takes a callback, assume it
2675
68
    // can free memory.
2676
68
    if (!Call->isInSystemHeader() || 
Call->argumentsMayEscape()57
)
2677
12
      return true;
2678
56
2679
56
    // If it's a method we know about, handle it explicitly post-call.
2680
56
    // This should happen before the "freeWhenDone" check below.
2681
56
    if (isKnownDeallocObjCMethodName(*Msg))
2682
31
      return false;
2683
25
2684
25
    // If there's a "freeWhenDone" parameter, but the method isn't one we know
2685
25
    // about, we can't be sure that the object will use free() to deallocate the
2686
25
    // memory, so we can't model it explicitly. The best we can do is use it to
2687
25
    // decide whether the pointer escapes.
2688
25
    if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2689
4
      return *FreeWhenDone;
2690
21
2691
21
    // If the first selector piece ends with "NoCopy", and there is no
2692
21
    // "freeWhenDone" parameter set to zero, we know ownership is being
2693
21
    // transferred. Again, though, we can't be sure that the object will use
2694
21
    // free() to deallocate the memory, so we can't model it explicitly.
2695
21
    StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2696
21
    if (FirstSlot.endswith("NoCopy"))
2697
1
      return true;
2698
20
2699
20
    // If the first selector starts with addPointer, insertPointer,
2700
20
    // or replacePointer, assume we are dealing with NSPointerArray or similar.
2701
20
    // This is similar to C++ containers (vector); we still might want to check
2702
20
    // that the pointers get freed by following the container itself.
2703
20
    if (FirstSlot.startswith("addPointer") ||
2704
20
        
FirstSlot.startswith("insertPointer")19
||
2705
20
        
FirstSlot.startswith("replacePointer")17
||
2706
20
        
FirstSlot.equals("valueWithPointer")14
) {
2707
6
      return true;
2708
6
    }
2709
14
2710
14
    // We should escape receiver on call to 'init'. This is especially relevant
2711
14
    // to the receiver, as the corresponding symbol is usually not referenced
2712
14
    // after the call.
2713
14
    if (Msg->getMethodFamily() == OMF_init) {
2714
8
      EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2715
8
      return true;
2716
8
    }
2717
6
2718
6
    // Otherwise, assume that the method does not free memory.
2719
6
    // Most framework methods do not free memory.
2720
6
    return false;
2721
6
  }
2722
639
2723
639
  // At this point the only thing left to handle is straight function calls.
2724
639
  const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2725
639
  if (!FD)
2726
0
    return true;
2727
639
2728
639
  ASTContext &ASTC = State->getStateManager().getContext();
2729
639
2730
639
  // If it's one of the allocation functions we can reason about, we model
2731
639
  // its behavior explicitly.
2732
639
  if (isMemFunction(FD, ASTC))
2733
483
    return false;
2734
156
2735
156
  // If it's not a system call, assume it frees memory.
2736
156
  if (!Call->isInSystemHeader())
2737
118
    return true;
2738
38
2739
38
  // White list the system functions whose arguments escape.
2740
38
  const IdentifierInfo *II = FD->getIdentifier();
2741
38
  if (!II)
2742
0
    return true;
2743
38
  StringRef FName = II->getName();
2744
38
2745
38
  // White list the 'XXXNoCopy' CoreFoundation functions.
2746
38
  // We specifically check these before
2747
38
  if (FName.endswith("NoCopy")) {
2748
2
    // Look for the deallocator argument. We know that the memory ownership
2749
2
    // is not transferred only if the deallocator argument is
2750
2
    // 'kCFAllocatorNull'.
2751
8
    for (unsigned i = 1; i < Call->getNumArgs(); 
++i6
) {
2752
7
      const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2753
7
      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2754
4
        StringRef DeallocatorName = DE->getFoundDecl()->getName();
2755
4
        if (DeallocatorName == "kCFAllocatorNull")
2756
1
          return false;
2757
4
      }
2758
7
    }
2759
2
    
return true1
;
2760
36
  }
2761
36
2762
36
  // Associating streams with malloced buffers. The pointer can escape if
2763
36
  // 'closefn' is specified (and if that function does free memory),
2764
36
  // but it will not if closefn is not specified.
2765
36
  // Currently, we do not inspect the 'closefn' function (PR12101).
2766
36
  if (FName == "funopen")
2767
3
    if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2768
2
      return false;
2769
34
2770
34
  // Do not warn on pointers passed to 'setbuf' when used with std streams,
2771
34
  // these leaks might be intentional when setting the buffer for stdio.
2772
34
  // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2773
34
  if (FName == "setbuf" || 
FName =="setbuffer"33
||
2774
34
      
FName == "setlinebuf"33
||
FName == "setvbuf"33
) {
2775
3
    if (Call->getNumArgs() >= 1) {
2776
3
      const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2777
3
      if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2778
3
        if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2779
3
          if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2780
2
            return true;
2781
32
    }
2782
3
  }
2783
32
2784
32
  // A bunch of other functions which either take ownership of a pointer or
2785
32
  // wrap the result up in a struct or object, meaning it can be freed later.
2786
32
  // (See RetainCountChecker.) Not all the parameters here are invalidated,
2787
32
  // but the Malloc checker cannot differentiate between them. The right way
2788
32
  // of doing this would be to implement a pointer escapes callback.
2789
32
  if (FName == "CGBitmapContextCreate" ||
2790
32
      
FName == "CGBitmapContextCreateWithData"30
||
2791
32
      
FName == "CVPixelBufferCreateWithBytes"30
||
2792
32
      
FName == "CVPixelBufferCreateWithPlanarBytes"30
||
2793
32
      
FName == "OSAtomicEnqueue"30
) {
2794
2
    return true;
2795
2
  }
2796
30
2797
30
  if (FName == "postEvent" &&
2798
30
      
FD->getQualifiedNameAsString() == "QCoreApplication::postEvent"4
) {
2799
4
    return true;
2800
4
  }
2801
26
2802
26
  if (FName == "postEvent" &&
2803
26
      
FD->getQualifiedNameAsString() == "QCoreApplication::postEvent"0
) {
2804
0
    return true;
2805
0
  }
2806
26
2807
26
  if (FName == "connectImpl" &&
2808
26
      
FD->getQualifiedNameAsString() == "QObject::connectImpl"1
) {
2809
1
    return true;
2810
1
  }
2811
25
2812
25
  // Handle cases where we know a buffer's /address/ can escape.
2813
25
  // Note that the above checks handle some special cases where we know that
2814
25
  // even though the address escapes, it's still our responsibility to free the
2815
25
  // buffer.
2816
25
  if (Call->argumentsMayEscape())
2817
15
    return true;
2818
10
2819
10
  // Otherwise, assume that the function does not free memory.
2820
10
  // Most system calls do not free the memory.
2821
10
  return false;
2822
10
}
2823
2824
368
static bool retTrue(const RefState *RS) {
2825
368
  return true;
2826
368
}
2827
2828
52
static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2829
52
  return (RS->getAllocationFamily() == AF_CXXNewArray ||
2830
52
          
RS->getAllocationFamily() == AF_CXXNew51
);
2831
52
}
2832
2833
ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2834
                                             const InvalidatedSymbols &Escaped,
2835
                                             const CallEvent *Call,
2836
10.9k
                                             PointerEscapeKind Kind) const {
2837
10.9k
  return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2838
10.9k
}
2839
2840
ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2841
                                              const InvalidatedSymbols &Escaped,
2842
                                              const CallEvent *Call,
2843
308
                                              PointerEscapeKind Kind) const {
2844
308
  return checkPointerEscapeAux(State, Escaped, Call, Kind,
2845
308
                               &checkIfNewOrNewArrayFamily);
2846
308
}
2847
2848
ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2849
                                              const InvalidatedSymbols &Escaped,
2850
                                              const CallEvent *Call,
2851
                                              PointerEscapeKind Kind,
2852
11.2k
                                  bool(*CheckRefState)(const RefState*)) const {
2853
11.2k
  // If we know that the call does not free memory, or we want to process the
2854
11.2k
  // call later, keep tracking the top level arguments.
2855
11.2k
  SymbolRef EscapingSymbol = nullptr;
2856
11.2k
  if (Kind == PSK_DirectEscapeOnCall &&
2857
11.2k
      !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2858
1.24k
                                                    EscapingSymbol) &&
2859
11.2k
      
!EscapingSymbol535
) {
2860
535
    return State;
2861
535
  }
2862
10.6k
2863
10.6k
  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2864
10.6k
       E = Escaped.end();
2865
32.8k
       I != E; 
++I22.1k
) {
2866
22.1k
    SymbolRef sym = *I;
2867
22.1k
2868
22.1k
    if (EscapingSymbol && 
EscapingSymbol != sym9
)
2869
1
      continue;
2870
22.1k
2871
22.1k
    if (const RefState *RS = State->get<RegionState>(sym)) {
2872
558
      if ((RS->isAllocated() || 
RS->isAllocatedOfSizeZero()138
) &&
2873
558
          
CheckRefState(RS)420
) {
2874
405
        State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2875
405
      }
2876
558
    }
2877
22.1k
  }
2878
10.6k
  return State;
2879
10.6k
}
2880
2881
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2882
6
                                         ProgramStateRef prevState) {
2883
6
  ReallocPairsTy currMap = currState->get<ReallocPairs>();
2884
6
  ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2885
6
2886
6
  for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2887
6
       I != E; 
++I0
) {
2888
6
    SymbolRef sym = I.getKey();
2889
6
    if (!currMap.lookup(sym))
2890
6
      return sym;
2891
6
  }
2892
6
2893
6
  
return nullptr0
;
2894
6
}
2895
2896
33
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
2897
33
  if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
2898
33
    StringRef N = II->getName();
2899
33
    if (N.contains_lower("ptr") || 
N.contains_lower("pointer")17
) {
2900
24
      if (N.contains_lower("ref") || N.contains_lower("cnt") ||
2901
24
          N.contains_lower("intrusive") || 
N.contains_lower("shared")8
) {
2902
16
        return true;
2903
16
      }
2904
17
    }
2905
33
  }
2906
17
  return false;
2907
17
}
2908
2909
std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2910
27.2k
    const ExplodedNode *N, BugReporterContext &BRC, BugReport &BR) {
2911
27.2k
2912
27.2k
  ProgramStateRef state = N->getState();
2913
27.2k
  ProgramStateRef statePrev = N->getFirstPred()->getState();
2914
27.2k
2915
27.2k
  const RefState *RS = state->get<RegionState>(Sym);
2916
27.2k
  const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2917
27.2k
2918
27.2k
  const Stmt *S = PathDiagnosticLocation::getStmt(N);
2919
27.2k
  // When dealing with containers, we sometimes want to give a note
2920
27.2k
  // even if the statement is missing.
2921
27.2k
  if (!S && 
(1.73k
!RS1.73k
||
RS->getAllocationFamily() != AF_InnerBuffer779
))
2922
1.71k
    return nullptr;
2923
25.5k
2924
25.5k
  const LocationContext *CurrentLC = N->getLocationContext();
2925
25.5k
2926
25.5k
  // If we find an atomic fetch_add or fetch_sub within the destructor in which
2927
25.5k
  // the pointer was released (before the release), this is likely a destructor
2928
25.5k
  // of a shared pointer.
2929
25.5k
  // Because we don't model atomics, and also because we don't know that the
2930
25.5k
  // original reference count is positive, we should not report use-after-frees
2931
25.5k
  // on objects deleted in such destructors. This can probably be improved
2932
25.5k
  // through better shared pointer modeling.
2933
25.5k
  if (ReleaseDestructorLC) {
2934
835
    if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
2935
0
      AtomicExpr::AtomicOp Op = AE->getOp();
2936
0
      if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2937
0
          Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2938
0
        if (ReleaseDestructorLC == CurrentLC ||
2939
0
            ReleaseDestructorLC->isParentOf(CurrentLC)) {
2940
0
          BR.markInvalid(getTag(), S);
2941
0
        }
2942
0
      }
2943
0
    }
2944
835
  }
2945
25.5k
2946
25.5k
  // FIXME: We will eventually need to handle non-statement-based events
2947
25.5k
  // (__attribute__((cleanup))).
2948
25.5k
2949
25.5k
  // Find out if this is an interesting point and what is the kind.
2950
25.5k
  StringRef Msg;
2951
25.5k
  StackHintGeneratorForSymbol *StackHint = nullptr;
2952
25.5k
  SmallString<256> Buf;
2953
25.5k
  llvm::raw_svector_ostream OS(Buf);
2954
25.5k
2955
25.5k
  if (Mode == Normal) {
2956
25.4k
    if (isAllocated(RS, RSPrev, S)) {
2957
440
      Msg = "Memory is allocated";
2958
440
      StackHint = new StackHintGeneratorForSymbol(Sym,
2959
440
                                                  "Returned allocated memory");
2960
25.0k
    } else if (isReleased(RS, RSPrev, S)) {
2961
224
      const auto Family = RS->getAllocationFamily();
2962
224
      switch (Family) {
2963
224
        case AF_Alloca:
2964
194
        case AF_Malloc:
2965
194
        case AF_CXXNew:
2966
194
        case AF_CXXNewArray:
2967
194
        case AF_IfNameIndex:
2968
194
          Msg = "Memory is released";
2969
194
          StackHint = new StackHintGeneratorForSymbol(Sym,
2970
194
                                              "Returning; memory was released");
2971
194
          break;
2972
194
        case AF_InnerBuffer: {
2973
30
          const MemRegion *ObjRegion =
2974
30
              allocation_state::getContainerObjRegion(statePrev, Sym);
2975
30
          const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
2976
30
          QualType ObjTy = TypedRegion->getValueType();
2977
30
          OS << "Inner buffer of '" << ObjTy.getAsString() << "' ";
2978
30
2979
30
          if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
2980
12
            OS << "deallocated by call to destructor";
2981
12
            StackHint = new StackHintGeneratorForSymbol(Sym,
2982
12
                                      "Returning; inner buffer was deallocated");
2983
18
          } else {
2984
18
            OS << "reallocated by call to '";
2985
18
            const Stmt *S = RS->getStmt();
2986
18
            if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
2987
13
              OS << MemCallE->getMethodDecl()->getNameAsString();
2988
13
            } else 
if (const auto *5
OpCallE5
= dyn_cast<CXXOperatorCallExpr>(S)) {
2989
2
              OS << OpCallE->getDirectCallee()->getNameAsString();
2990
3
            } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
2991
3
              auto &CEMgr = BRC.getStateManager().getCallEventManager();
2992
3
              CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
2993
3
              const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
2994
3
              OS << (D ? D->getNameAsString() : 
"unknown"0
);
2995
3
            }
2996
18
            OS << "'";
2997
18
            StackHint = new StackHintGeneratorForSymbol(Sym,
2998
18
                                      "Returning; inner buffer was reallocated");
2999
18
          }
3000
30
          Msg = OS.str();
3001
30
          break;
3002
194
        }
3003
194
        case AF_None:
3004
0
          llvm_unreachable("Unhandled allocation family!");
3005
224
      }
3006
224
3007
224
      // See if we're releasing memory while inlining a destructor
3008
224
      // (or one of its callees). This turns on various common
3009
224
      // false positive suppressions.
3010
224
      bool FoundAnyDestructor = false;
3011
496
      for (const LocationContext *LC = CurrentLC; LC; 
LC = LC->getParent()272
) {
3012
272
        if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3013
33
          if (isReferenceCountingPointerDestructor(DD)) {
3014
16
            // This immediately looks like a reference-counting destructor.
3015
16
            // We're bad at guessing the original reference count of the object,
3016
16
            // so suppress the report for now.
3017
16
            BR.markInvalid(getTag(), DD);
3018
17
          } else if (!FoundAnyDestructor) {
3019
11
            assert(!ReleaseDestructorLC &&
3020
11
                   "There can be only one release point!");
3021
11
            // Suspect that it's a reference counting pointer destructor.
3022
11
            // On one of the next nodes might find out that it has atomic
3023
11
            // reference counting operations within it (see the code above),
3024
11
            // and if so, we'd conclude that it likely is a reference counting
3025
11
            // pointer destructor.
3026
11
            ReleaseDestructorLC = LC->getStackFrame();
3027
11
            // It is unlikely that releasing memory is delegated to a destructor
3028
11
            // inside a destructor of a shared pointer, because it's fairly hard
3029
11
            // to pass the information that the pointer indeed needs to be
3030
11
            // released into it. So we're only interested in the innermost
3031
11
            // destructor.
3032
11
            FoundAnyDestructor = true;
3033
11
          }
3034
33
        }
3035
272
      }
3036
24.8k
    } else if (isRelinquished(RS, RSPrev, S)) {
3037
5
      Msg = "Memory ownership is transferred";
3038
5
      StackHint = new StackHintGeneratorForSymbol(Sym, "");
3039
24.7k
    } else if (isReallocFailedCheck(RS, RSPrev, S)) {
3040
6
      Mode = ReallocationFailed;
3041
6
      Msg = "Reallocation failed";
3042
6
      StackHint = new StackHintGeneratorForReallocationFailed(Sym,
3043
6
                                                       "Reallocation failed");
3044
6
3045
6
      if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3046
6
        // Is it possible to fail two reallocs WITHOUT testing in between?
3047
6
        assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3048
6
          "We only support one failed realloc at a time.");
3049
6
        BR.markInteresting(sym);
3050
6
        FailedReallocSymbol = sym;
3051
6
      }
3052
6
    }
3053
25.4k
3054
25.4k
  // We are in a special mode if a reallocation failed later in the path.
3055
25.4k
  } else 
if (73
Mode == ReallocationFailed73
) {
3056
73
    assert(FailedReallocSymbol && "No symbol to look for.");
3057
73
3058
73
    // Is this is the first appearance of the reallocated symbol?
3059
73
    if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3060
6
      // We're at the reallocation point.
3061
6
      Msg = "Attempt to reallocate memory";
3062
6
      StackHint = new StackHintGeneratorForSymbol(Sym,
3063
6
                                                 "Returned reallocated memory");
3064
6
      FailedReallocSymbol = nullptr;
3065
6
      Mode = Normal;
3066
6
    }
3067
73
  }
3068
25.5k
3069
25.5k
  if (Msg.empty())
3070
24.8k
    return nullptr;
3071
681
  assert(StackHint);
3072
681
3073
681
  // Generate the extra diagnostic.
3074
681
  PathDiagnosticLocation Pos;
3075
681
  if (!S) {
3076
12
    assert(RS->getAllocationFamily() == AF_InnerBuffer);
3077
12
    auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3078
12
    if (!PostImplCall)
3079
0
      return nullptr;
3080
12
    Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3081
12
                                 BRC.getSourceManager());
3082
669
  } else {
3083
669
    Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3084
669
                                 N->getLocationContext());
3085
669
  }
3086
681
3087
681
  return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
3088
681
}
3089
3090
void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3091
0
                               const char *NL, const char *Sep) const {
3092
0
3093
0
  RegionStateTy RS = State->get<RegionState>();
3094
0
3095
0
  if (!RS.isEmpty()) {
3096
0
    Out << Sep << "MallocChecker :" << NL;
3097
0
    for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3098
0
      const RefState *RefS = State->get<RegionState>(I.getKey());
3099
0
      AllocationFamily Family = RefS->getAllocationFamily();
3100
0
      Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
3101
0
      if (!CheckKind.hasValue())
3102
0
         CheckKind = getCheckIfTracked(Family, true);
3103
0
3104
0
      I.getKey()->dumpToStream(Out);
3105
0
      Out << " : ";
3106
0
      I.getData().dump(Out);
3107
0
      if (CheckKind.hasValue())
3108
0
        Out << " (" << CheckNames[*CheckKind].getName() << ")";
3109
0
      Out << NL;
3110
0
    }
3111
0
  }
3112
0
}
3113
3114
namespace clang {
3115
namespace ento {
3116
namespace allocation_state {
3117
3118
ProgramStateRef
3119
36
markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3120
36
  AllocationFamily Family = AF_InnerBuffer;
3121
36
  return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3122
36
}
3123
3124
} // end namespace allocation_state
3125
} // end namespace ento
3126
} // end namespace clang
3127
3128
// Intended to be used in InnerPointerChecker to register the part of
3129
// MallocChecker connected to it.
3130
40
void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3131
40
  MallocChecker *checker = mgr.getChecker<MallocChecker>();
3132
40
  checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3133
40
  checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3134
40
      mgr.getCurrentCheckName();
3135
40
}
3136
3137
179
void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3138
179
  auto *checker = mgr.registerChecker<MallocChecker>();
3139
179
  checker->IsOptimistic = mgr.getAnalyzerOptions().getCheckerBooleanOption(
3140
179
                                                         checker, "Optimistic");
3141
179
}
3142
3143
25
bool ento::shouldRegisterDynamicMemoryModeling(const LangOptions &LO) {
3144
25
  return true;
3145
25
}
3146
3147
#define REGISTER_CHECKER(name)                                                 \
3148
304
  void ento::register##name(CheckerManager &mgr) {                             \
3149
304
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3150
304
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3151
304
    checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3152
304
  }                                                                            \
clang::ento::registerMallocChecker(clang::ento::CheckerManager&)
Line
Count
Source
3148
112
  void ento::register##name(CheckerManager &mgr) {                             \
3149
112
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3150
112
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3151
112
    checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3152
112
  }                                                                            \
clang::ento::registerNewDeleteChecker(clang::ento::CheckerManager&)
Line
Count
Source
3148
93
  void ento::register##name(CheckerManager &mgr) {                             \
3149
93
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3150
93
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3151
93
    checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3152
93
  }                                                                            \
clang::ento::registerNewDeleteLeaksChecker(clang::ento::CheckerManager&)
Line
Count
Source
3148
64
  void ento::register##name(CheckerManager &mgr) {                             \
3149
64
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3150
64
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3151
64
    checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3152
64
  }                                                                            \
clang::ento::registerMismatchedDeallocatorChecker(clang::ento::CheckerManager&)
Line
Count
Source
3148
35
  void ento::register##name(CheckerManager &mgr) {                             \
3149
35
    MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3150
35
    checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3151
35
    checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3152
35
  }                                                                            \
3153
                                                                               \
3154
288
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
3155
288
    return true;                                                               \
3156
288
  }
clang::ento::shouldRegisterMallocChecker(clang::LangOptions const&)
Line
Count
Source
3154
112
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
3155
112
    return true;                                                               \
3156
112
  }
clang::ento::shouldRegisterNewDeleteChecker(clang::LangOptions const&)
Line
Count
Source
3154
77
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
3155
77
    return true;                                                               \
3156
77
  }
clang::ento::shouldRegisterNewDeleteLeaksChecker(clang::LangOptions const&)
Line
Count
Source
3154
64
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
3155
64
    return true;                                                               \
3156
64
  }
clang::ento::shouldRegisterMismatchedDeallocatorChecker(clang::LangOptions const&)
Line
Count
Source
3154
35
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
3155
35
    return true;                                                               \
3156
35
  }
3157
3158
REGISTER_CHECKER(MallocChecker)
3159
REGISTER_CHECKER(NewDeleteChecker)
3160
REGISTER_CHECKER(NewDeleteLeaksChecker)
3161
REGISTER_CHECKER(MismatchedDeallocatorChecker)