Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CallAndMessageChecker.cpp ------------------------------*- 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 defines CallAndMessageChecker, a builtin checker that checks for various
10
// errors of call and objc message expressions.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/AST/ParentMap.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18
#include "clang/StaticAnalyzer/Core/Checker.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
#include "llvm/ADT/SmallString.h"
23
#include "llvm/ADT/StringExtras.h"
24
#include "llvm/Support/raw_ostream.h"
25
26
using namespace clang;
27
using namespace ento;
28
29
namespace {
30
31
class CallAndMessageChecker
32
  : public Checker< check::PreStmt<CallExpr>,
33
                    check::PreStmt<CXXDeleteExpr>,
34
                    check::PreObjCMessage,
35
                    check::ObjCMessageNil,
36
                    check::PreCall > {
37
  mutable std::unique_ptr<BugType> BT_call_null;
38
  mutable std::unique_ptr<BugType> BT_call_undef;
39
  mutable std::unique_ptr<BugType> BT_cxx_call_null;
40
  mutable std::unique_ptr<BugType> BT_cxx_call_undef;
41
  mutable std::unique_ptr<BugType> BT_call_arg;
42
  mutable std::unique_ptr<BugType> BT_cxx_delete_undef;
43
  mutable std::unique_ptr<BugType> BT_msg_undef;
44
  mutable std::unique_ptr<BugType> BT_objc_prop_undef;
45
  mutable std::unique_ptr<BugType> BT_objc_subscript_undef;
46
  mutable std::unique_ptr<BugType> BT_msg_arg;
47
  mutable std::unique_ptr<BugType> BT_msg_ret;
48
  mutable std::unique_ptr<BugType> BT_call_few_args;
49
50
public:
51
  DefaultBool Check_CallAndMessageUnInitRefArg;
52
  CheckName CheckName_CallAndMessageUnInitRefArg;
53
54
  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
55
  void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
56
  void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
57
58
  /// Fill in the return value that results from messaging nil based on the
59
  /// return type and architecture and diagnose if the return value will be
60
  /// garbage.
61
  void checkObjCMessageNil(const ObjCMethodCall &msg, CheckerContext &C) const;
62
63
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
64
65
private:
66
  bool PreVisitProcessArg(CheckerContext &C, SVal V, SourceRange ArgRange,
67
                          const Expr *ArgEx, int ArgumentNumber,
68
                          bool CheckUninitFields, const CallEvent &Call,
69
                          std::unique_ptr<BugType> &BT,
70
                          const ParmVarDecl *ParamDecl) const;
71
72
  static void emitBadCall(BugType *BT, CheckerContext &C, const Expr *BadE);
73
  void emitNilReceiverBug(CheckerContext &C, const ObjCMethodCall &msg,
74
                          ExplodedNode *N) const;
75
76
  void HandleNilReceiver(CheckerContext &C,
77
                         ProgramStateRef state,
78
                         const ObjCMethodCall &msg) const;
79
80
80
  void LazyInit_BT(const char *desc, std::unique_ptr<BugType> &BT) const {
81
80
    if (!BT)
82
43
      BT.reset(new BuiltinBug(this, desc));
83
80
  }
84
  bool uninitRefOrPointer(CheckerContext &C, const SVal &V,
85
                          SourceRange ArgRange, const Expr *ArgEx,
86
                          std::unique_ptr<BugType> &BT,
87
                          const ParmVarDecl *ParamDecl, const char *BD,
88
                          int ArgumentNumber) const;
89
};
90
} // end anonymous namespace
91
92
void CallAndMessageChecker::emitBadCall(BugType *BT, CheckerContext &C,
93
60
                                        const Expr *BadE) {
94
60
  ExplodedNode *N = C.generateErrorNode();
95
60
  if (!N)
96
0
    return;
97
60
98
60
  auto R = llvm::make_unique<BugReport>(*BT, BT->getName(), N);
99
60
  if (BadE) {
100
60
    R->addRange(BadE->getSourceRange());
101
60
    if (BadE->isGLValue())
102
11
      BadE = bugreporter::getDerefExpr(BadE);
103
60
    bugreporter::trackExpressionValue(N, BadE, *R);
104
60
  }
105
60
  C.emitReport(std::move(R));
106
60
}
107
108
static void describeUninitializedArgumentInCall(const CallEvent &Call,
109
                                                int ArgumentNumber,
110
47
                                                llvm::raw_svector_ostream &Os) {
111
47
  switch (Call.getKind()) {
112
47
  case CE_ObjCMessage: {
113
10
    const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
114
10
    switch (Msg.getMessageKind()) {
115
10
    case OCM_Message:
116
3
      Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
117
3
         << " argument in message expression is an uninitialized value";
118
3
      return;
119
10
    case OCM_PropertyAccess:
120
1
      assert(Msg.isSetter() && "Getters have no args");
121
1
      Os << "Argument for property setter is an uninitialized value";
122
1
      return;
123
10
    case OCM_Subscript:
124
6
      if (Msg.isSetter() && 
(ArgumentNumber == 0)4
)
125
2
        Os << "Argument for subscript setter is an uninitialized value";
126
4
      else
127
4
        Os << "Subscript index is an uninitialized value";
128
6
      return;
129
0
    }
130
0
    llvm_unreachable("Unknown message kind.");
131
0
  }
132
2
  case CE_Block:
133
2
    Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
134
2
       << " block call argument is an uninitialized value";
135
2
    return;
136
35
  default:
137
35
    Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
138
35
       << " function call argument is an uninitialized value";
139
35
    return;
140
47
  }
141
47
}
142
143
bool CallAndMessageChecker::uninitRefOrPointer(
144
    CheckerContext &C, const SVal &V, SourceRange ArgRange, const Expr *ArgEx,
145
    std::unique_ptr<BugType> &BT, const ParmVarDecl *ParamDecl, const char *BD,
146
64.3k
    int ArgumentNumber) const {
147
64.3k
  if (!Check_CallAndMessageUnInitRefArg)
148
62.7k
    return false;
149
1.56k
150
1.56k
  // No parameter declaration available, i.e. variadic function argument.
151
1.56k
  if(!ParamDecl)
152
180
    return false;
153
1.38k
154
1.38k
  // If parameter is declared as pointer to const in function declaration,
155
1.38k
  // then check if corresponding argument in function call is
156
1.38k
  // pointing to undefined symbol value (uninitialized memory).
157
1.38k
  SmallString<200> Buf;
158
1.38k
  llvm::raw_svector_ostream Os(Buf);
159
1.38k
160
1.38k
  if (ParamDecl->getType()->isPointerType()) {
161
343
    Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
162
343
       << " function call argument is a pointer to uninitialized value";
163
1.03k
  } else if (ParamDecl->getType()->isReferenceType()) {
164
195
    Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1)
165
195
       << " function call argument is an uninitialized value";
166
195
  } else
167
844
    return false;
168
538
169
538
  if(!ParamDecl->getType()->getPointeeType().isConstQualified())
170
285
    return false;
171
253
172
253
  if (const MemRegion *SValMemRegion = V.getAsRegion()) {
173
222
    const ProgramStateRef State = C.getState();
174
222
    const SVal PSV = State->getSVal(SValMemRegion, C.getASTContext().CharTy);
175
222
    if (PSV.isUndef()) {
176
23
      if (ExplodedNode *N = C.generateErrorNode()) {
177
23
        LazyInit_BT(BD, BT);
178
23
        auto R = llvm::make_unique<BugReport>(*BT, Os.str(), N);
179
23
        R->addRange(ArgRange);
180
23
        if (ArgEx)
181
23
          bugreporter::trackExpressionValue(N, ArgEx, *R);
182
23
183
23
        C.emitReport(std::move(R));
184
23
      }
185
23
      return true;
186
23
    }
187
230
  }
188
230
  return false;
189
230
}
190
191
namespace {
192
class FindUninitializedField {
193
public:
194
  SmallVector<const FieldDecl *, 10> FieldChain;
195
196
private:
197
  StoreManager &StoreMgr;
198
  MemRegionManager &MrMgr;
199
  Store store;
200
201
public:
202
  FindUninitializedField(StoreManager &storeMgr, MemRegionManager &mrMgr,
203
                         Store s)
204
9.34k
      : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
205
206
9.36k
  bool Find(const TypedValueRegion *R) {
207
9.36k
    QualType T = R->getValueType();
208
9.36k
    if (const RecordType *RT = T->getAsStructureType()) {
209
9.31k
      const RecordDecl *RD = RT->getDecl()->getDefinition();
210
9.31k
      assert(RD && "Referred record has no definition");
211
9.36k
      for (const auto *I : RD->fields()) {
212
9.36k
        const FieldRegion *FR = MrMgr.getFieldRegion(I, R);
213
9.36k
        FieldChain.push_back(I);
214
9.36k
        T = I->getType();
215
9.36k
        if (T->getAsStructureType()) {
216
14
          if (Find(FR))
217
0
            return true;
218
9.34k
        } else {
219
9.34k
          const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
220
9.34k
          if (V.isUndef())
221
5
            return true;
222
9.35k
        }
223
9.35k
        FieldChain.pop_back();
224
9.35k
      }
225
9.31k
    }
226
9.36k
227
9.36k
    
return false9.35k
;
228
9.36k
  }
229
};
230
} // namespace
231
232
bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
233
                                               SVal V,
234
                                               SourceRange ArgRange,
235
                                               const Expr *ArgEx,
236
                                               int ArgumentNumber,
237
                                               bool CheckUninitFields,
238
                                               const CallEvent &Call,
239
                                               std::unique_ptr<BugType> &BT,
240
                                               const ParmVarDecl *ParamDecl
241
64.3k
                                               ) const {
242
64.3k
  const char *BD = "Uninitialized argument value";
243
64.3k
244
64.3k
  if (uninitRefOrPointer(C, V, ArgRange, ArgEx, BT, ParamDecl, BD,
245
64.3k
                         ArgumentNumber))
246
23
    return true;
247
64.3k
248
64.3k
  if (V.isUndef()) {
249
47
    if (ExplodedNode *N = C.generateErrorNode()) {
250
47
      LazyInit_BT(BD, BT);
251
47
      // Generate a report for this bug.
252
47
      SmallString<200> Buf;
253
47
      llvm::raw_svector_ostream Os(Buf);
254
47
      describeUninitializedArgumentInCall(Call, ArgumentNumber, Os);
255
47
      auto R = llvm::make_unique<BugReport>(*BT, Os.str(), N);
256
47
257
47
      R->addRange(ArgRange);
258
47
      if (ArgEx)
259
47
        bugreporter::trackExpressionValue(N, ArgEx, *R);
260
47
      C.emitReport(std::move(R));
261
47
    }
262
47
    return true;
263
47
  }
264
64.2k
265
64.2k
  if (!CheckUninitFields)
266
34.8k
    return false;
267
29.3k
268
29.3k
  if (auto LV = V.getAs<nonloc::LazyCompoundVal>()) {
269
9.34k
    const LazyCompoundValData *D = LV->getCVData();
270
9.34k
    FindUninitializedField F(C.getState()->getStateManager().getStoreManager(),
271
9.34k
                             C.getSValBuilder().getRegionManager(),
272
9.34k
                             D->getStore());
273
9.34k
274
9.34k
    if (F.Find(D->getRegion())) {
275
5
      if (ExplodedNode *N = C.generateErrorNode()) {
276
5
        LazyInit_BT(BD, BT);
277
5
        SmallString<512> Str;
278
5
        llvm::raw_svector_ostream os(Str);
279
5
        os << "Passed-by-value struct argument contains uninitialized data";
280
5
281
5
        if (F.FieldChain.size() == 1)
282
5
          os << " (e.g., field: '" << *F.FieldChain[0] << "')";
283
0
        else {
284
0
          os << " (e.g., via the field chain: '";
285
0
          bool first = true;
286
0
          for (SmallVectorImpl<const FieldDecl *>::iterator
287
0
               DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
288
0
            if (first)
289
0
              first = false;
290
0
            else
291
0
              os << '.';
292
0
            os << **DI;
293
0
          }
294
0
          os << "')";
295
0
        }
296
5
297
5
        // Generate a report for this bug.
298
5
        auto R = llvm::make_unique<BugReport>(*BT, os.str(), N);
299
5
        R->addRange(ArgRange);
300
5
301
5
        if (ArgEx)
302
5
          bugreporter::trackExpressionValue(N, ArgEx, *R);
303
5
        // FIXME: enhance track back for uninitialized value for arbitrary
304
5
        // memregions
305
5
        C.emitReport(std::move(R));
306
5
      }
307
5
      return true;
308
5
    }
309
29.3k
  }
310
29.3k
311
29.3k
  return false;
312
29.3k
}
313
314
void CallAndMessageChecker::checkPreStmt(const CallExpr *CE,
315
50.5k
                                         CheckerContext &C) const{
316
50.5k
317
50.5k
  const Expr *Callee = CE->getCallee()->IgnoreParens();
318
50.5k
  ProgramStateRef State = C.getState();
319
50.5k
  const LocationContext *LCtx = C.getLocationContext();
320
50.5k
  SVal L = State->getSVal(Callee, LCtx);
321
50.5k
322
50.5k
  if (L.isUndef()) {
323
1
    if (!BT_call_undef)
324
1
      BT_call_undef.reset(new BuiltinBug(
325
1
          this, "Called function pointer is an uninitialized pointer value"));
326
1
    emitBadCall(BT_call_undef.get(), C, Callee);
327
1
    return;
328
1
  }
329
50.5k
330
50.5k
  ProgramStateRef StNonNull, StNull;
331
50.5k
  std::tie(StNonNull, StNull) = State->assume(L.castAs<DefinedOrUnknownSVal>());
332
50.5k
333
50.5k
  if (StNull && 
!StNonNull36
) {
334
2
    if (!BT_call_null)
335
1
      BT_call_null.reset(new BuiltinBug(
336
1
          this, "Called function pointer is null (null dereference)"));
337
2
    emitBadCall(BT_call_null.get(), C, Callee);
338
2
    return;
339
2
  }
340
50.5k
341
50.5k
  C.addTransition(StNonNull);
342
50.5k
}
343
344
void CallAndMessageChecker::checkPreStmt(const CXXDeleteExpr *DE,
345
441
                                         CheckerContext &C) const {
346
441
347
441
  SVal Arg = C.getSVal(DE->getArgument());
348
441
  if (Arg.isUndef()) {
349
32
    StringRef Desc;
350
32
    ExplodedNode *N = C.generateErrorNode();
351
32
    if (!N)
352
0
      return;
353
32
    if (!BT_cxx_delete_undef)
354
8
      BT_cxx_delete_undef.reset(
355
8
          new BuiltinBug(this, "Uninitialized argument value"));
356
32
    if (DE->isArrayFormAsWritten())
357
16
      Desc = "Argument to 'delete[]' is uninitialized";
358
16
    else
359
16
      Desc = "Argument to 'delete' is uninitialized";
360
32
    BugType *BT = BT_cxx_delete_undef.get();
361
32
    auto R = llvm::make_unique<BugReport>(*BT, Desc, N);
362
32
    bugreporter::trackExpressionValue(N, DE, *R);
363
32
    C.emitReport(std::move(R));
364
32
    return;
365
32
  }
366
441
}
367
368
void CallAndMessageChecker::checkPreCall(const CallEvent &Call,
369
75.7k
                                         CheckerContext &C) const {
370
75.7k
  ProgramStateRef State = C.getState();
371
75.7k
372
75.7k
  // If this is a call to a C++ method, check if the callee is null or
373
75.7k
  // undefined.
374
75.7k
  if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
375
8.95k
    SVal V = CC->getCXXThisVal();
376
8.95k
    if (V.isUndef()) {
377
6
      if (!BT_cxx_call_undef)
378
6
        BT_cxx_call_undef.reset(
379
6
            new BuiltinBug(this, "Called C++ object pointer is uninitialized"));
380
6
      emitBadCall(BT_cxx_call_undef.get(), C, CC->getCXXThisExpr());
381
6
      return;
382
6
    }
383
8.95k
384
8.95k
    ProgramStateRef StNonNull, StNull;
385
8.95k
    std::tie(StNonNull, StNull) =
386
8.95k
        State->assume(V.castAs<DefinedOrUnknownSVal>());
387
8.95k
388
8.95k
    if (StNull && 
!StNonNull300
) {
389
51
      if (!BT_cxx_call_null)
390
21
        BT_cxx_call_null.reset(
391
21
            new BuiltinBug(this, "Called C++ object pointer is null"));
392
51
      emitBadCall(BT_cxx_call_null.get(), C, CC->getCXXThisExpr());
393
51
      return;
394
51
    }
395
8.90k
396
8.90k
    State = StNonNull;
397
8.90k
  }
398
75.7k
399
75.7k
  const Decl *D = Call.getDecl();
400
75.7k
  if (D && 
(75.6k
isa<FunctionDecl>(D)75.6k
||
isa<BlockDecl>(D)3.51k
)) {
401
72.3k
    // If we have a function or block declaration, we can make sure we pass
402
72.3k
    // enough parameters.
403
72.3k
    unsigned Params = Call.parameters().size();
404
72.3k
    if (Call.getNumArgs() < Params) {
405
5
      ExplodedNode *N = C.generateErrorNode();
406
5
      if (!N)
407
0
        return;
408
5
409
5
      LazyInit_BT("Function call with too few arguments", BT_call_few_args);
410
5
411
5
      SmallString<512> Str;
412
5
      llvm::raw_svector_ostream os(Str);
413
5
      if (isa<FunctionDecl>(D)) {
414
3
        os << "Function ";
415
3
      } else {
416
2
        assert(isa<BlockDecl>(D));
417
2
        os << "Block ";
418
2
      }
419
5
      os << "taking " << Params << " argument"
420
5
         << (Params == 1 ? 
""3
:
"s"2
) << " is called with fewer ("
421
5
         << Call.getNumArgs() << ")";
422
5
423
5
      C.emitReport(
424
5
          llvm::make_unique<BugReport>(*BT_call_few_args, os.str(), N));
425
5
    }
426
72.3k
  }
427
75.7k
428
75.7k
  // Don't check for uninitialized field values in arguments if the
429
75.7k
  // caller has a body that is available and we have the chance to inline it.
430
75.7k
  // This is a hack, but is a reasonable compromise betweens sometimes warning
431
75.7k
  // and sometimes not depending on if we decide to inline a function.
432
75.7k
  const bool checkUninitFields =
433
75.7k
    !(C.getAnalysisManager().shouldInlineCall() && 
(75.6k
D75.6k
&&
D->getBody()75.6k
));
434
75.7k
435
75.7k
  std::unique_ptr<BugType> *BT;
436
75.7k
  if (isa<ObjCMethodCall>(Call))
437
3.36k
    BT = &BT_msg_arg;
438
72.3k
  else
439
72.3k
    BT = &BT_call_arg;
440
75.7k
441
75.7k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
442
139k
  for (unsigned i = 0, e = Call.getNumArgs(); i != e; 
++i64.2k
) {
443
64.3k
    const ParmVarDecl *ParamDecl = nullptr;
444
64.3k
    if(FD && 
i < FD->getNumParams()63.3k
)
445
63.0k
      ParamDecl = FD->getParamDecl(i);
446
64.3k
    if (PreVisitProcessArg(C, Call.getArgSVal(i), Call.getArgSourceRange(i),
447
64.3k
                           Call.getArgExpr(i), i,
448
64.3k
                           checkUninitFields, Call, *BT, ParamDecl))
449
75
      return;
450
64.3k
  }
451
75.7k
452
75.7k
  // If we make it here, record our assumptions about the callee.
453
75.7k
  C.addTransition(State);
454
75.6k
}
455
456
void CallAndMessageChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
457
3.41k
                                                CheckerContext &C) const {
458
3.41k
  SVal recVal = msg.getReceiverSVal();
459
3.41k
  if (recVal.isUndef()) {
460
5
    if (ExplodedNode *N = C.generateErrorNode()) {
461
5
      BugType *BT = nullptr;
462
5
      switch (msg.getMessageKind()) {
463
5
      case OCM_Message:
464
2
        if (!BT_msg_undef)
465
2
          BT_msg_undef.reset(new BuiltinBug(this,
466
2
                                            "Receiver in message expression "
467
2
                                            "is an uninitialized value"));
468
2
        BT = BT_msg_undef.get();
469
2
        break;
470
5
      case OCM_PropertyAccess:
471
1
        if (!BT_objc_prop_undef)
472
1
          BT_objc_prop_undef.reset(new BuiltinBug(
473
1
              this, "Property access on an uninitialized object pointer"));
474
1
        BT = BT_objc_prop_undef.get();
475
1
        break;
476
5
      case OCM_Subscript:
477
2
        if (!BT_objc_subscript_undef)
478
1
          BT_objc_subscript_undef.reset(new BuiltinBug(
479
1
              this, "Subscript access on an uninitialized object pointer"));
480
2
        BT = BT_objc_subscript_undef.get();
481
2
        break;
482
5
      }
483
5
      assert(BT && "Unknown message kind.");
484
5
485
5
      auto R = llvm::make_unique<BugReport>(*BT, BT->getName(), N);
486
5
      const ObjCMessageExpr *ME = msg.getOriginExpr();
487
5
      R->addRange(ME->getReceiverRange());
488
5
489
5
      // FIXME: getTrackNullOrUndefValueVisitor can't handle "super" yet.
490
5
      if (const Expr *ReceiverE = ME->getInstanceReceiver())
491
5
        bugreporter::trackExpressionValue(N, ReceiverE, *R);
492
5
      C.emitReport(std::move(R));
493
5
    }
494
5
    return;
495
5
  }
496
3.41k
}
497
498
void CallAndMessageChecker::checkObjCMessageNil(const ObjCMethodCall &msg,
499
95
                                                CheckerContext &C) const {
500
95
  HandleNilReceiver(C, C.getState(), msg);
501
95
}
502
503
void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
504
                                               const ObjCMethodCall &msg,
505
7
                                               ExplodedNode *N) const {
506
7
507
7
  if (!BT_msg_ret)
508
2
    BT_msg_ret.reset(
509
2
        new BuiltinBug(this, "Receiver in message expression is 'nil'"));
510
7
511
7
  const ObjCMessageExpr *ME = msg.getOriginExpr();
512
7
513
7
  QualType ResTy = msg.getResultType();
514
7
515
7
  SmallString<200> buf;
516
7
  llvm::raw_svector_ostream os(buf);
517
7
  os << "The receiver of message '";
518
7
  ME->getSelector().print(os);
519
7
  os << "' is nil";
520
7
  if (ResTy->isReferenceType()) {
521
2
    os << ", which results in forming a null reference";
522
5
  } else {
523
5
    os << " and returns a value of type '";
524
5
    msg.getResultType().print(os, C.getLangOpts());
525
5
    os << "' that will be garbage";
526
5
  }
527
7
528
7
  auto report = llvm::make_unique<BugReport>(*BT_msg_ret, os.str(), N);
529
7
  report->addRange(ME->getReceiverRange());
530
7
  // FIXME: This won't track "self" in messages to super.
531
7
  if (const Expr *receiver = ME->getInstanceReceiver()) {
532
7
    bugreporter::trackExpressionValue(N, receiver, *report);
533
7
  }
534
7
  C.emitReport(std::move(report));
535
7
}
536
537
15
static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
538
15
  return (triple.getVendor() == llvm::Triple::Apple &&
539
15
          (triple.isiOS() || 
triple.isWatchOS()10
||
540
15
           
!triple.isMacOSXVersionLT(10,5)10
));
541
15
}
542
543
void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
544
                                              ProgramStateRef state,
545
95
                                              const ObjCMethodCall &Msg) const {
546
95
  ASTContext &Ctx = C.getASTContext();
547
95
  static CheckerProgramPointTag Tag(this, "NilReceiver");
548
95
549
95
  // Check the return type of the message expression.  A message to nil will
550
95
  // return different values depending on the return type and the architecture.
551
95
  QualType RetTy = Msg.getResultType();
552
95
  CanQualType CanRetTy = Ctx.getCanonicalType(RetTy);
553
95
  const LocationContext *LCtx = C.getLocationContext();
554
95
555
95
  if (CanRetTy->isStructureOrClassType()) {
556
4
    // Structure returns are safe since the compiler zeroes them out.
557
4
    SVal V = C.getSValBuilder().makeZeroVal(RetTy);
558
4
    C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
559
4
    return;
560
4
  }
561
91
562
91
  // Other cases: check if sizeof(return type) > sizeof(void*)
563
91
  if (CanRetTy != Ctx.VoidTy && C.getLocationContext()->getParentMap()
564
78
                                  .isConsumedExpr(Msg.getOriginExpr())) {
565
73
    // Compute: sizeof(void *) and sizeof(return type)
566
73
    const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
567
73
    const uint64_t returnTypeSize = Ctx.getTypeSize(CanRetTy);
568
73
569
73
    if (CanRetTy.getTypePtr()->isReferenceType()||
570
73
        
(71
voidPtrSize < returnTypeSize71
&&
571
71
         
!(15
supportsNilWithFloatRet(Ctx.getTargetInfo().getTriple())15
&&
572
15
           
(10
Ctx.FloatTy == CanRetTy10
||
573
10
            Ctx.DoubleTy == CanRetTy ||
574
10
            
Ctx.LongDoubleTy == CanRetTy8
||
575
10
            
Ctx.LongLongTy == CanRetTy6
||
576
10
            
Ctx.UnsignedLongLongTy == CanRetTy2
)))) {
577
7
      if (ExplodedNode *N = C.generateErrorNode(state, &Tag))
578
7
        emitNilReceiverBug(C, Msg, N);
579
7
      return;
580
7
    }
581
66
582
66
    // Handle the safe cases where the return value is 0 if the
583
66
    // receiver is nil.
584
66
    //
585
66
    // FIXME: For now take the conservative approach that we only
586
66
    // return null values if we *know* that the receiver is nil.
587
66
    // This is because we can have surprises like:
588
66
    //
589
66
    //   ... = [[NSScreens screens] objectAtIndex:0];
590
66
    //
591
66
    // What can happen is that [... screens] could return nil, but
592
66
    // it most likely isn't nil.  We should assume the semantics
593
66
    // of this case unless we have *a lot* more knowledge.
594
66
    //
595
66
    SVal V = C.getSValBuilder().makeZeroVal(RetTy);
596
66
    C.addTransition(state->BindExpr(Msg.getOriginExpr(), LCtx, V), &Tag);
597
66
    return;
598
66
  }
599
18
600
18
  C.addTransition(state);
601
18
}
602
603
675
void ento::registerCallAndMessageChecker(CheckerManager &mgr) {
604
675
  mgr.registerChecker<CallAndMessageChecker>();
605
675
}
606
607
676
bool ento::shouldRegisterCallAndMessageChecker(const LangOptions &LO) {
608
676
  return true;
609
676
}
610
611
73
void ento::registerCallAndMessageUnInitRefArg(CheckerManager &mgr) {
612
73
  CallAndMessageChecker *Checker = mgr.getChecker<CallAndMessageChecker>();
613
73
  Checker->Check_CallAndMessageUnInitRefArg = true;
614
73
  Checker->CheckName_CallAndMessageUnInitRefArg = mgr.getCurrentCheckName();
615
73
}
616
617
73
bool ento::shouldRegisterCallAndMessageUnInitRefArg(const LangOptions &LO) {
618
73
  return true;
619
73
}