CallAndMessageChecker.cpp revision b673a41c92aa276f2e37164d0747be1cfb0c402b
1//===--- CallAndMessageChecker.cpp ------------------------------*- C++ -*--==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines CallAndMessageChecker, a builtin checker that checks for various
11// errors of call and objc message expressions.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/StaticAnalyzer/Core/Checker.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/Basic/TargetInfo.h"
23#include "llvm/ADT/SmallString.h"
24
25using namespace clang;
26using namespace ento;
27
28namespace {
29class CallAndMessageChecker
30  : public Checker< check::PreStmt<CallExpr>, check::PreObjCMessage > {
31  mutable OwningPtr<BugType> BT_call_null;
32  mutable OwningPtr<BugType> BT_call_undef;
33  mutable OwningPtr<BugType> BT_call_arg;
34  mutable OwningPtr<BugType> BT_msg_undef;
35  mutable OwningPtr<BugType> BT_objc_prop_undef;
36  mutable OwningPtr<BugType> BT_msg_arg;
37  mutable OwningPtr<BugType> BT_msg_ret;
38public:
39
40  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
41  void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
42
43private:
44  static void PreVisitProcessArgs(CheckerContext &C,CallOrObjCMessage callOrMsg,
45                             const char *BT_desc, OwningPtr<BugType> &BT);
46  static bool PreVisitProcessArg(CheckerContext &C, SVal V,SourceRange argRange,
47          const Expr *argEx, const char *BT_desc, OwningPtr<BugType> &BT);
48
49  static void EmitBadCall(BugType *BT, CheckerContext &C, const CallExpr *CE);
50  void emitNilReceiverBug(CheckerContext &C, const ObjCMessage &msg,
51                          ExplodedNode *N) const;
52
53  void HandleNilReceiver(CheckerContext &C,
54                         ProgramStateRef state,
55                         ObjCMessage msg) const;
56
57  static void LazyInit_BT(const char *desc, OwningPtr<BugType> &BT) {
58    if (!BT)
59      BT.reset(new BuiltinBug(desc));
60  }
61};
62} // end anonymous namespace
63
64void CallAndMessageChecker::EmitBadCall(BugType *BT, CheckerContext &C,
65                                        const CallExpr *CE) {
66  ExplodedNode *N = C.generateSink();
67  if (!N)
68    return;
69
70  BugReport *R = new BugReport(*BT, BT->getName(), N);
71  R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
72                               bugreporter::GetCalleeExpr(N)));
73  C.EmitReport(R);
74}
75
76void CallAndMessageChecker::PreVisitProcessArgs(CheckerContext &C,
77                                                CallOrObjCMessage callOrMsg,
78                                                const char *BT_desc,
79                                                OwningPtr<BugType> &BT) {
80  for (unsigned i = 0, e = callOrMsg.getNumArgs(); i != e; ++i)
81    if (PreVisitProcessArg(C, callOrMsg.getArgSVal(i),
82                           callOrMsg.getArgSourceRange(i), callOrMsg.getArg(i),
83                           BT_desc, BT))
84      return;
85}
86
87bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
88                                               SVal V, SourceRange argRange,
89                                               const Expr *argEx,
90                                               const char *BT_desc,
91                                               OwningPtr<BugType> &BT) {
92
93  if (V.isUndef()) {
94    if (ExplodedNode *N = C.generateSink()) {
95      LazyInit_BT(BT_desc, BT);
96
97      // Generate a report for this bug.
98      BugReport *R = new BugReport(*BT, BT->getName(), N);
99      R->addRange(argRange);
100      if (argEx)
101        R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, argEx));
102      C.EmitReport(R);
103    }
104    return true;
105  }
106
107  if (const nonloc::LazyCompoundVal *LV =
108        dyn_cast<nonloc::LazyCompoundVal>(&V)) {
109
110    class FindUninitializedField {
111    public:
112      SmallVector<const FieldDecl *, 10> FieldChain;
113    private:
114      ASTContext &C;
115      StoreManager &StoreMgr;
116      MemRegionManager &MrMgr;
117      Store store;
118    public:
119      FindUninitializedField(ASTContext &c, StoreManager &storeMgr,
120                             MemRegionManager &mrMgr, Store s)
121      : C(c), StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
122
123      bool Find(const TypedValueRegion *R) {
124        QualType T = R->getValueType();
125        if (const RecordType *RT = T->getAsStructureType()) {
126          const RecordDecl *RD = RT->getDecl()->getDefinition();
127          assert(RD && "Referred record has no definition");
128          for (RecordDecl::field_iterator I =
129               RD->field_begin(), E = RD->field_end(); I!=E; ++I) {
130            const FieldRegion *FR = MrMgr.getFieldRegion(*I, R);
131            FieldChain.push_back(*I);
132            T = (*I)->getType();
133            if (T->getAsStructureType()) {
134              if (Find(FR))
135                return true;
136            }
137            else {
138              const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
139              if (V.isUndef())
140                return true;
141            }
142            FieldChain.pop_back();
143          }
144        }
145
146        return false;
147      }
148    };
149
150    const LazyCompoundValData *D = LV->getCVData();
151    FindUninitializedField F(C.getASTContext(),
152                             C.getState()->getStateManager().getStoreManager(),
153                             C.getSValBuilder().getRegionManager(),
154                             D->getStore());
155
156    if (F.Find(D->getRegion())) {
157      if (ExplodedNode *N = C.generateSink()) {
158        LazyInit_BT(BT_desc, BT);
159        SmallString<512> Str;
160        llvm::raw_svector_ostream os(Str);
161        os << "Passed-by-value struct argument contains uninitialized data";
162
163        if (F.FieldChain.size() == 1)
164          os << " (e.g., field: '" << *F.FieldChain[0] << "')";
165        else {
166          os << " (e.g., via the field chain: '";
167          bool first = true;
168          for (SmallVectorImpl<const FieldDecl *>::iterator
169               DI = F.FieldChain.begin(), DE = F.FieldChain.end(); DI!=DE;++DI){
170            if (first)
171              first = false;
172            else
173              os << '.';
174            os << **DI;
175          }
176          os << "')";
177        }
178
179        // Generate a report for this bug.
180        BugReport *R = new BugReport(*BT, os.str(), N);
181        R->addRange(argRange);
182
183        // FIXME: enhance track back for uninitialized value for arbitrary
184        // memregions
185        C.EmitReport(R);
186      }
187      return true;
188    }
189  }
190
191  return false;
192}
193
194void CallAndMessageChecker::checkPreStmt(const CallExpr *CE,
195                                         CheckerContext &C) const{
196
197  const Expr *Callee = CE->getCallee()->IgnoreParens();
198  const LocationContext *LCtx = C.getLocationContext();
199  SVal L = C.getState()->getSVal(Callee, LCtx);
200
201  if (L.isUndef()) {
202    if (!BT_call_undef)
203      BT_call_undef.reset(new BuiltinBug("Called function pointer is an "
204                                         "uninitalized pointer value"));
205    EmitBadCall(BT_call_undef.get(), C, CE);
206    return;
207  }
208
209  if (isa<loc::ConcreteInt>(L)) {
210    if (!BT_call_null)
211      BT_call_null.reset(
212        new BuiltinBug("Called function pointer is null (null dereference)"));
213    EmitBadCall(BT_call_null.get(), C, CE);
214  }
215
216  PreVisitProcessArgs(C, CallOrObjCMessage(CE, C.getState(), LCtx),
217                      "Function call argument is an uninitialized value",
218                      BT_call_arg);
219}
220
221void CallAndMessageChecker::checkPreObjCMessage(ObjCMessage msg,
222                                                CheckerContext &C) const {
223
224  ProgramStateRef state = C.getState();
225  const LocationContext *LCtx = C.getLocationContext();
226
227  // FIXME: Handle 'super'?
228  if (const Expr *receiver = msg.getInstanceReceiver()) {
229    SVal recVal = state->getSVal(receiver, LCtx);
230    if (recVal.isUndef()) {
231      if (ExplodedNode *N = C.generateSink()) {
232        BugType *BT = 0;
233        if (msg.isPureMessageExpr()) {
234          if (!BT_msg_undef)
235            BT_msg_undef.reset(new BuiltinBug("Receiver in message expression "
236                                              "is an uninitialized value"));
237          BT = BT_msg_undef.get();
238        }
239        else {
240          if (!BT_objc_prop_undef)
241            BT_objc_prop_undef.reset(new BuiltinBug("Property access on an "
242                                              "uninitialized object pointer"));
243          BT = BT_objc_prop_undef.get();
244        }
245        BugReport *R =
246          new BugReport(*BT, BT->getName(), N);
247        R->addRange(receiver->getSourceRange());
248        R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
249                                                                   receiver));
250        C.EmitReport(R);
251      }
252      return;
253    } else {
254      // Bifurcate the state into nil and non-nil ones.
255      DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
256
257      ProgramStateRef notNilState, nilState;
258      llvm::tie(notNilState, nilState) = state->assume(receiverVal);
259
260      // Handle receiver must be nil.
261      if (nilState && !notNilState) {
262        HandleNilReceiver(C, state, msg);
263        return;
264      }
265    }
266  }
267
268  const char *bugDesc = msg.isPropertySetter() ?
269                     "Argument for property setter is an uninitialized value"
270                   : "Argument in message expression is an uninitialized value";
271  // Check for any arguments that are uninitialized/undefined.
272  PreVisitProcessArgs(C, CallOrObjCMessage(msg, state, LCtx),
273                      bugDesc, BT_msg_arg);
274}
275
276void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
277                                               const ObjCMessage &msg,
278                                               ExplodedNode *N) const {
279
280  if (!BT_msg_ret)
281    BT_msg_ret.reset(
282      new BuiltinBug("Receiver in message expression is "
283                     "'nil' and returns a garbage value"));
284
285  SmallString<200> buf;
286  llvm::raw_svector_ostream os(buf);
287  os << "The receiver of message '" << msg.getSelector().getAsString()
288     << "' is nil and returns a value of type '"
289     << msg.getType(C.getASTContext()).getAsString() << "' that will be garbage";
290
291  BugReport *report = new BugReport(*BT_msg_ret, os.str(), N);
292  if (const Expr *receiver = msg.getInstanceReceiver()) {
293    report->addRange(receiver->getSourceRange());
294    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
295                                                                    receiver));
296  }
297  C.EmitReport(report);
298}
299
300static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
301  return (triple.getVendor() == llvm::Triple::Apple &&
302          (triple.getOS() == llvm::Triple::IOS ||
303           !triple.isMacOSXVersionLT(10,5)));
304}
305
306void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
307                                              ProgramStateRef state,
308                                              ObjCMessage msg) const {
309  ASTContext &Ctx = C.getASTContext();
310
311  // Check the return type of the message expression.  A message to nil will
312  // return different values depending on the return type and the architecture.
313  QualType RetTy = msg.getType(Ctx);
314  CanQualType CanRetTy = Ctx.getCanonicalType(RetTy);
315  const LocationContext *LCtx = C.getLocationContext();
316
317  if (CanRetTy->isStructureOrClassType()) {
318    // Structure returns are safe since the compiler zeroes them out.
319    SVal V = C.getSValBuilder().makeZeroVal(msg.getType(Ctx));
320    C.addTransition(state->BindExpr(msg.getMessageExpr(), LCtx, V));
321    return;
322  }
323
324  // Other cases: check if sizeof(return type) > sizeof(void*)
325  if (CanRetTy != Ctx.VoidTy && C.getLocationContext()->getParentMap()
326                                  .isConsumedExpr(msg.getMessageExpr())) {
327    // Compute: sizeof(void *) and sizeof(return type)
328    const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
329    const uint64_t returnTypeSize = Ctx.getTypeSize(CanRetTy);
330
331    if (voidPtrSize < returnTypeSize &&
332        !(supportsNilWithFloatRet(Ctx.getTargetInfo().getTriple()) &&
333          (Ctx.FloatTy == CanRetTy ||
334           Ctx.DoubleTy == CanRetTy ||
335           Ctx.LongDoubleTy == CanRetTy ||
336           Ctx.LongLongTy == CanRetTy ||
337           Ctx.UnsignedLongLongTy == CanRetTy))) {
338      if (ExplodedNode *N = C.generateSink(state))
339        emitNilReceiverBug(C, msg, N);
340      return;
341    }
342
343    // Handle the safe cases where the return value is 0 if the
344    // receiver is nil.
345    //
346    // FIXME: For now take the conservative approach that we only
347    // return null values if we *know* that the receiver is nil.
348    // This is because we can have surprises like:
349    //
350    //   ... = [[NSScreens screens] objectAtIndex:0];
351    //
352    // What can happen is that [... screens] could return nil, but
353    // it most likely isn't nil.  We should assume the semantics
354    // of this case unless we have *a lot* more knowledge.
355    //
356    SVal V = C.getSValBuilder().makeZeroVal(msg.getType(Ctx));
357    C.addTransition(state->BindExpr(msg.getMessageExpr(), LCtx, V));
358    return;
359  }
360
361  C.addTransition(state);
362}
363
364void ento::registerCallAndMessageChecker(CheckerManager &mgr) {
365  mgr.registerChecker<CallAndMessageChecker>();
366}
367