CallEvent.cpp revision 42c72c258e08ca79c9267346b4badcddd8fcd001
1//===- Calls.cpp - Wrapper for all function and method calls ------*- 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/// \file This file defines CallEvent and its subclasses, which represent path-
11/// sensitive instances of different kinds of function and method calls
12/// (C, C++, and Objective-C).
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17#include "clang/Analysis/ProgramPoint.h"
18#include "clang/AST/ParentMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/StringExtras.h"
21
22using namespace clang;
23using namespace ento;
24
25QualType CallEvent::getResultType() const {
26  QualType ResultTy = getDeclaredResultType();
27
28  if (ResultTy.isNull())
29    ResultTy = getOriginExpr()->getType();
30
31  return ResultTy;
32}
33
34static bool isCallbackArg(SVal V, QualType T) {
35  // If the parameter is 0, it's harmless.
36  if (V.isZeroConstant())
37    return false;
38
39  // If a parameter is a block or a callback, assume it can modify pointer.
40  if (T->isBlockPointerType() ||
41      T->isFunctionPointerType() ||
42      T->isObjCSelType())
43    return true;
44
45  // Check if a callback is passed inside a struct (for both, struct passed by
46  // reference and by value). Dig just one level into the struct for now.
47
48  if (isa<PointerType>(T) || isa<ReferenceType>(T))
49    T = T->getPointeeType();
50
51  if (const RecordType *RT = T->getAsStructureType()) {
52    const RecordDecl *RD = RT->getDecl();
53    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
54         I != E; ++I) {
55      QualType FieldT = I->getType();
56      if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
57        return true;
58    }
59  }
60
61  return false;
62}
63
64bool CallEvent::hasNonZeroCallbackArg() const {
65  unsigned NumOfArgs = getNumArgs();
66
67  // If calling using a function pointer, assume the function does not
68  // have a callback. TODO: We could check the types of the arguments here.
69  if (!getDecl())
70    return false;
71
72  unsigned Idx = 0;
73  for (CallEvent::param_type_iterator I = param_type_begin(),
74                                       E = param_type_end();
75       I != E && Idx < NumOfArgs; ++I, ++Idx) {
76    if (NumOfArgs <= Idx)
77      break;
78
79    if (isCallbackArg(getArgSVal(Idx), *I))
80      return true;
81  }
82
83  return false;
84}
85
86/// \brief Returns true if a type is a pointer-to-const or reference-to-const
87/// with no further indirection.
88static bool isPointerToConst(QualType Ty) {
89  QualType PointeeTy = Ty->getPointeeType();
90  if (PointeeTy == QualType())
91    return false;
92  if (!PointeeTy.isConstQualified())
93    return false;
94  if (PointeeTy->isAnyPointerType())
95    return false;
96  return true;
97}
98
99// Try to retrieve the function declaration and find the function parameter
100// types which are pointers/references to a non-pointer const.
101// We will not invalidate the corresponding argument regions.
102static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
103                                 const CallEvent &Call) {
104  unsigned Idx = 0;
105  for (CallEvent::param_type_iterator I = Call.param_type_begin(),
106                                      E = Call.param_type_end();
107       I != E; ++I, ++Idx) {
108    if (isPointerToConst(*I))
109      PreserveArgs.insert(Idx);
110  }
111}
112
113ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
114                                              ProgramStateRef Orig) const {
115  ProgramStateRef Result = (Orig ? Orig : getState());
116
117  SmallVector<const MemRegion *, 8> RegionsToInvalidate;
118  getExtraInvalidatedRegions(RegionsToInvalidate);
119
120  // Indexes of arguments whose values will be preserved by the call.
121  llvm::SmallSet<unsigned, 1> PreserveArgs;
122  if (!argumentsMayEscape())
123    findPtrToConstParams(PreserveArgs, *this);
124
125  for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
126    if (PreserveArgs.count(Idx))
127      continue;
128
129    SVal V = getArgSVal(Idx);
130
131    // If we are passing a location wrapped as an integer, unwrap it and
132    // invalidate the values referred by the location.
133    if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
134      V = Wrapped->getLoc();
135    else if (!isa<Loc>(V))
136      continue;
137
138    if (const MemRegion *R = V.getAsRegion()) {
139      // Invalidate the value of the variable passed by reference.
140
141      // Are we dealing with an ElementRegion?  If the element type is
142      // a basic integer type (e.g., char, int) and the underlying region
143      // is a variable region then strip off the ElementRegion.
144      // FIXME: We really need to think about this for the general case
145      //   as sometimes we are reasoning about arrays and other times
146      //   about (char*), etc., is just a form of passing raw bytes.
147      //   e.g., void *p = alloca(); foo((char*)p);
148      if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
149        // Checking for 'integral type' is probably too promiscuous, but
150        // we'll leave it in for now until we have a systematic way of
151        // handling all of these cases.  Eventually we need to come up
152        // with an interface to StoreManager so that this logic can be
153        // appropriately delegated to the respective StoreManagers while
154        // still allowing us to do checker-specific logic (e.g.,
155        // invalidating reference counts), probably via callbacks.
156        if (ER->getElementType()->isIntegralOrEnumerationType()) {
157          const MemRegion *superReg = ER->getSuperRegion();
158          if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
159              isa<ObjCIvarRegion>(superReg))
160            R = cast<TypedRegion>(superReg);
161        }
162        // FIXME: What about layers of ElementRegions?
163      }
164
165      // Mark this region for invalidation.  We batch invalidate regions
166      // below for efficiency.
167      RegionsToInvalidate.push_back(R);
168    }
169  }
170
171  // Invalidate designated regions using the batch invalidation API.
172  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
173  //  global variables.
174  return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(),
175                                   BlockCount, getLocationContext(),
176                                   /*Symbols=*/0, this);
177}
178
179ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
180                                        const ProgramPointTag *Tag) const {
181  if (const Expr *E = getOriginExpr()) {
182    if (IsPreVisit)
183      return PreStmt(E, getLocationContext(), Tag);
184    return PostStmt(E, getLocationContext(), Tag);
185  }
186
187  const Decl *D = getDecl();
188  assert(D && "Cannot get a program point without a statement or decl");
189
190  SourceLocation Loc = getSourceRange().getBegin();
191  if (IsPreVisit)
192    return PreImplicitCall(D, Loc, getLocationContext(), Tag);
193  return PostImplicitCall(D, Loc, getLocationContext(), Tag);
194}
195
196SVal CallEvent::getArgSVal(unsigned Index) const {
197  const Expr *ArgE = getArgExpr(Index);
198  if (!ArgE)
199    return UnknownVal();
200  return getSVal(ArgE);
201}
202
203SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
204  const Expr *ArgE = getArgExpr(Index);
205  if (!ArgE)
206    return SourceRange();
207  return ArgE->getSourceRange();
208}
209
210void CallEvent::dump() const {
211  dump(llvm::errs());
212}
213
214void CallEvent::dump(raw_ostream &Out) const {
215  ASTContext &Ctx = getState()->getStateManager().getContext();
216  if (const Expr *E = getOriginExpr()) {
217    E->printPretty(Out, Ctx, 0, Ctx.getPrintingPolicy());
218    Out << "\n";
219    return;
220  }
221
222  if (const Decl *D = getDecl()) {
223    Out << "Call to ";
224    D->print(Out, Ctx.getPrintingPolicy());
225    return;
226  }
227
228  // FIXME: a string representation of the kind would be nice.
229  Out << "Unknown call (type " << getKind() << ")";
230}
231
232
233bool CallEvent::mayBeInlined(const Stmt *S) {
234  // FIXME: Kill this.
235  return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
236                          || isa<CXXConstructExpr>(S);
237}
238
239static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
240                                         CallEvent::BindingsTy &Bindings,
241                                         SValBuilder &SVB,
242                                         const CallEvent &Call,
243                                         CallEvent::param_iterator I,
244                                         CallEvent::param_iterator E) {
245  MemRegionManager &MRMgr = SVB.getRegionManager();
246
247  unsigned Idx = 0;
248  for (; I != E; ++I, ++Idx) {
249    const ParmVarDecl *ParamDecl = *I;
250    assert(ParamDecl && "Formal parameter has no decl?");
251
252    SVal ArgVal = Call.getArgSVal(Idx);
253    if (!ArgVal.isUnknown()) {
254      Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
255      Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
256    }
257  }
258
259  // FIXME: Variadic arguments are not handled at all right now.
260}
261
262
263CallEvent::param_iterator AnyFunctionCall::param_begin() const {
264  const FunctionDecl *D = getDecl();
265  if (!D)
266    return 0;
267
268  return D->param_begin();
269}
270
271CallEvent::param_iterator AnyFunctionCall::param_end() const {
272  const FunctionDecl *D = getDecl();
273  if (!D)
274    return 0;
275
276  return D->param_end();
277}
278
279void AnyFunctionCall::getInitialStackFrameContents(
280                                        const StackFrameContext *CalleeCtx,
281                                        BindingsTy &Bindings) const {
282  const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
283  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
284  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
285                               D->param_begin(), D->param_end());
286}
287
288QualType AnyFunctionCall::getDeclaredResultType() const {
289  const FunctionDecl *D = getDecl();
290  if (!D)
291    return QualType();
292
293  return D->getResultType();
294}
295
296bool AnyFunctionCall::argumentsMayEscape() const {
297  if (hasNonZeroCallbackArg())
298    return true;
299
300  const FunctionDecl *D = getDecl();
301  if (!D)
302    return true;
303
304  const IdentifierInfo *II = D->getIdentifier();
305  if (!II)
306    return true;
307
308  // This set of "escaping" APIs is
309
310  // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
311  //   value into thread local storage. The value can later be retrieved with
312  //   'void *ptheread_getspecific(pthread_key)'. So even thought the
313  //   parameter is 'const void *', the region escapes through the call.
314  if (II->isStr("pthread_setspecific"))
315    return true;
316
317  // - xpc_connection_set_context stores a value which can be retrieved later
318  //   with xpc_connection_get_context.
319  if (II->isStr("xpc_connection_set_context"))
320    return true;
321
322  // - funopen - sets a buffer for future IO calls.
323  if (II->isStr("funopen"))
324    return true;
325
326  StringRef FName = II->getName();
327
328  // - CoreFoundation functions that end with "NoCopy" can free a passed-in
329  //   buffer even if it is const.
330  if (FName.endswith("NoCopy"))
331    return true;
332
333  // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
334  //   be deallocated by NSMapRemove.
335  if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
336    return true;
337
338  // - Many CF containers allow objects to escape through custom
339  //   allocators/deallocators upon container construction. (PR12101)
340  if (FName.startswith("CF") || FName.startswith("CG")) {
341    return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
342           StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
343           StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
344           StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
345           StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
346           StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
347  }
348
349  return false;
350}
351
352
353const FunctionDecl *SimpleCall::getDecl() const {
354  const FunctionDecl *D = getOriginExpr()->getDirectCallee();
355  if (D)
356    return D;
357
358  return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
359}
360
361
362const FunctionDecl *CXXInstanceCall::getDecl() const {
363  const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
364  if (!CE)
365    return AnyFunctionCall::getDecl();
366
367  const FunctionDecl *D = CE->getDirectCallee();
368  if (D)
369    return D;
370
371  return getSVal(CE->getCallee()).getAsFunctionDecl();
372}
373
374void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
375  if (const MemRegion *R = getCXXThisVal().getAsRegion())
376    Regions.push_back(R);
377}
378
379static const CXXMethodDecl *devirtualize(const CXXMethodDecl *MD, SVal ThisVal){
380  const MemRegion *R = ThisVal.getAsRegion();
381  if (!R)
382    return 0;
383
384  const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R->StripCasts());
385  if (!TR)
386    return 0;
387
388  const CXXRecordDecl *RD = TR->getValueType()->getAsCXXRecordDecl();
389  if (!RD)
390    return 0;
391
392  const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD);
393  const FunctionDecl *Definition;
394  if (!Result->hasBody(Definition))
395    return 0;
396
397  return cast<CXXMethodDecl>(Definition);
398}
399
400
401RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
402  const Decl *D = getDecl();
403  if (!D)
404    return RuntimeDefinition();
405
406  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
407  if (!MD->isVirtual())
408    return AnyFunctionCall::getRuntimeDefinition();
409
410  // If the method is virtual, see if we can find the actual implementation
411  // based on context-sensitivity.
412  // FIXME: Virtual method calls behave differently when an object is being
413  // constructed or destructed. It's not as simple as "no devirtualization"
414  // because a /partially/ constructed object can be referred to through a
415  // base pointer. We'll eventually want to use DynamicTypeInfo here.
416  if (const CXXMethodDecl *Devirtualized = devirtualize(MD, getCXXThisVal()))
417    return RuntimeDefinition(Devirtualized);
418
419  return RuntimeDefinition();
420}
421
422void CXXInstanceCall::getInitialStackFrameContents(
423                                            const StackFrameContext *CalleeCtx,
424                                            BindingsTy &Bindings) const {
425  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
426
427  // Handle the binding of 'this' in the new stack frame.
428  // We need to make sure we have the proper layering of CXXBaseObjectRegions.
429  SVal ThisVal = getCXXThisVal();
430  if (!ThisVal.isUnknown()) {
431    ProgramStateManager &StateMgr = getState()->getStateManager();
432    SValBuilder &SVB = StateMgr.getSValBuilder();
433
434    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
435    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
436
437    if (const MemRegion *ThisReg = ThisVal.getAsRegion()) {
438      ASTContext &Ctx = SVB.getContext();
439      const CXXRecordDecl *Class = MD->getParent();
440      QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
441
442      // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
443      bool Failed;
444      ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
445      assert(!Failed && "Calling an incorrectly devirtualized method");
446
447      // If we couldn't build the correct cast, just strip off all casts.
448      if (ThisVal.isUnknown())
449        ThisVal = loc::MemRegionVal(ThisReg->StripCasts());
450    }
451
452    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
453  }
454}
455
456
457
458const Expr *CXXMemberCall::getCXXThisExpr() const {
459  return getOriginExpr()->getImplicitObjectArgument();
460}
461
462
463const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
464  return getOriginExpr()->getArg(0);
465}
466
467
468const BlockDataRegion *BlockCall::getBlockRegion() const {
469  const Expr *Callee = getOriginExpr()->getCallee();
470  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
471
472  return dyn_cast_or_null<BlockDataRegion>(DataReg);
473}
474
475CallEvent::param_iterator BlockCall::param_begin() const {
476  const BlockDecl *D = getBlockDecl();
477  if (!D)
478    return 0;
479  return D->param_begin();
480}
481
482CallEvent::param_iterator BlockCall::param_end() const {
483  const BlockDecl *D = getBlockDecl();
484  if (!D)
485    return 0;
486  return D->param_end();
487}
488
489void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
490  // FIXME: This also needs to invalidate captured globals.
491  if (const MemRegion *R = getBlockRegion())
492    Regions.push_back(R);
493}
494
495void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
496                                             BindingsTy &Bindings) const {
497  const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
498  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
499  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
500                               D->param_begin(), D->param_end());
501}
502
503
504QualType BlockCall::getDeclaredResultType() const {
505  const BlockDataRegion *BR = getBlockRegion();
506  if (!BR)
507    return QualType();
508  QualType BlockTy = BR->getCodeRegion()->getLocationType();
509  return cast<FunctionType>(BlockTy->getPointeeType())->getResultType();
510}
511
512
513SVal CXXConstructorCall::getCXXThisVal() const {
514  if (Data)
515    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
516  return UnknownVal();
517}
518
519void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
520  if (Data)
521    Regions.push_back(static_cast<const MemRegion *>(Data));
522}
523
524void CXXConstructorCall::getInitialStackFrameContents(
525                                             const StackFrameContext *CalleeCtx,
526                                             BindingsTy &Bindings) const {
527  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
528
529  SVal ThisVal = getCXXThisVal();
530  if (!ThisVal.isUnknown()) {
531    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
532    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
533    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
534    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
535  }
536}
537
538
539
540SVal CXXDestructorCall::getCXXThisVal() const {
541  if (Data)
542    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
543  return UnknownVal();
544}
545
546
547CallEvent::param_iterator ObjCMethodCall::param_begin() const {
548  const ObjCMethodDecl *D = getDecl();
549  if (!D)
550    return 0;
551
552  return D->param_begin();
553}
554
555CallEvent::param_iterator ObjCMethodCall::param_end() const {
556  const ObjCMethodDecl *D = getDecl();
557  if (!D)
558    return 0;
559
560  return D->param_end();
561}
562
563void
564ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
565  if (const MemRegion *R = getReceiverSVal().getAsRegion())
566    Regions.push_back(R);
567}
568
569QualType ObjCMethodCall::getDeclaredResultType() const {
570  const ObjCMethodDecl *D = getDecl();
571  if (!D)
572    return QualType();
573
574  return D->getResultType();
575}
576
577SVal ObjCMethodCall::getReceiverSVal() const {
578  // FIXME: Is this the best way to handle class receivers?
579  if (!isInstanceMessage())
580    return UnknownVal();
581
582  if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
583    return getSVal(RecE);
584
585  // An instance message with no expression means we are sending to super.
586  // In this case the object reference is the same as 'self'.
587  const LocationContext *LCtx = getLocationContext();
588  const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
589  assert(SelfDecl && "No message receiver Expr, but not in an ObjC method");
590  return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
591}
592
593SourceRange ObjCMethodCall::getSourceRange() const {
594  switch (getMessageKind()) {
595  case OCM_Message:
596    return getOriginExpr()->getSourceRange();
597  case OCM_PropertyAccess:
598  case OCM_Subscript:
599    return getContainingPseudoObjectExpr()->getSourceRange();
600  }
601  llvm_unreachable("unknown message kind");
602}
603
604typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
605
606const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
607  assert(Data != 0 && "Lazy lookup not yet performed.");
608  assert(getMessageKind() != OCM_Message && "Explicit message send.");
609  return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
610}
611
612ObjCMessageKind ObjCMethodCall::getMessageKind() const {
613  if (Data == 0) {
614    ParentMap &PM = getLocationContext()->getParentMap();
615    const Stmt *S = PM.getParent(getOriginExpr());
616    if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
617      const Expr *Syntactic = POE->getSyntacticForm();
618
619      // This handles the funny case of assigning to the result of a getter.
620      // This can happen if the getter returns a non-const reference.
621      if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
622        Syntactic = BO->getLHS();
623
624      ObjCMessageKind K;
625      switch (Syntactic->getStmtClass()) {
626      case Stmt::ObjCPropertyRefExprClass:
627        K = OCM_PropertyAccess;
628        break;
629      case Stmt::ObjCSubscriptRefExprClass:
630        K = OCM_Subscript;
631        break;
632      default:
633        // FIXME: Can this ever happen?
634        K = OCM_Message;
635        break;
636      }
637
638      if (K != OCM_Message) {
639        const_cast<ObjCMethodCall *>(this)->Data
640          = ObjCMessageDataTy(POE, K).getOpaqueValue();
641        assert(getMessageKind() == K);
642        return K;
643      }
644    }
645
646    const_cast<ObjCMethodCall *>(this)->Data
647      = ObjCMessageDataTy(0, 1).getOpaqueValue();
648    assert(getMessageKind() == OCM_Message);
649    return OCM_Message;
650  }
651
652  ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
653  if (!Info.getPointer())
654    return OCM_Message;
655  return static_cast<ObjCMessageKind>(Info.getInt());
656}
657
658
659bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
660                                             Selector Sel) const {
661  assert(IDecl);
662  const SourceManager &SM =
663    getState()->getStateManager().getContext().getSourceManager();
664
665  // If the class interface is declared inside the main file, assume it is not
666  // subcassed.
667  // TODO: It could actually be subclassed if the subclass is private as well.
668  // This is probably very rare.
669  SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
670  if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
671    return false;
672
673
674  // We assume that if the method is public (declared outside of main file) or
675  // has a parent which publicly declares the method, the method could be
676  // overridden in a subclass.
677
678  // Find the first declaration in the class hierarchy that declares
679  // the selector.
680  ObjCMethodDecl *D = 0;
681  while (true) {
682    D = IDecl->lookupMethod(Sel, true);
683
684    // Cannot find a public definition.
685    if (!D)
686      return false;
687
688    // If outside the main file,
689    if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
690      return true;
691
692    if (D->isOverriding()) {
693      // Search in the superclass on the next iteration.
694      IDecl = D->getClassInterface();
695      if (!IDecl)
696        return false;
697
698      IDecl = IDecl->getSuperClass();
699      if (!IDecl)
700        return false;
701
702      continue;
703    }
704
705    return false;
706  };
707
708  llvm_unreachable("The while loop should always terminate.");
709}
710
711RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
712  const ObjCMessageExpr *E = getOriginExpr();
713  assert(E);
714  Selector Sel = E->getSelector();
715
716  if (E->isInstanceMessage()) {
717
718    // Find the the receiver type.
719    const ObjCObjectPointerType *ReceiverT = 0;
720    bool CanBeSubClassed = false;
721    QualType SupersType = E->getSuperType();
722    const MemRegion *Receiver = 0;
723
724    if (!SupersType.isNull()) {
725      // Super always means the type of immediate predecessor to the method
726      // where the call occurs.
727      ReceiverT = cast<ObjCObjectPointerType>(SupersType);
728    } else {
729      Receiver = getReceiverSVal().getAsRegion();
730      if (!Receiver)
731        return RuntimeDefinition();
732
733      DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
734      QualType DynType = DTI.getType();
735      CanBeSubClassed = DTI.canBeASubClass();
736      ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
737
738      if (ReceiverT && CanBeSubClassed)
739        if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
740          if (!canBeOverridenInSubclass(IDecl, Sel))
741            CanBeSubClassed = false;
742    }
743
744    // Lookup the method implementation.
745    if (ReceiverT)
746      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
747        const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
748        if (CanBeSubClassed)
749          return RuntimeDefinition(MD, Receiver);
750        else
751          return RuntimeDefinition(MD, 0);
752      }
753
754  } else {
755    // This is a class method.
756    // If we have type info for the receiver class, we are calling via
757    // class name.
758    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
759      // Find/Return the method implementation.
760      return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
761    }
762  }
763
764  return RuntimeDefinition();
765}
766
767void ObjCMethodCall::getInitialStackFrameContents(
768                                             const StackFrameContext *CalleeCtx,
769                                             BindingsTy &Bindings) const {
770  const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
771  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
772  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
773                               D->param_begin(), D->param_end());
774
775  SVal SelfVal = getReceiverSVal();
776  if (!SelfVal.isUnknown()) {
777    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
778    MemRegionManager &MRMgr = SVB.getRegionManager();
779    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
780    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
781  }
782}
783
784CallEventRef<>
785CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
786                                const LocationContext *LCtx) {
787  if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
788    return create<CXXMemberCall>(MCE, State, LCtx);
789
790  if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
791    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
792    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
793      if (MD->isInstance())
794        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
795
796  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
797    return create<BlockCall>(CE, State, LCtx);
798  }
799
800  // Otherwise, it's a normal function call, static member function call, or
801  // something we can't reason about.
802  return create<FunctionCall>(CE, State, LCtx);
803}
804
805
806CallEventRef<>
807CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
808                            ProgramStateRef State) {
809  const LocationContext *ParentCtx = CalleeCtx->getParent();
810  const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
811  assert(CallerCtx && "This should not be used for top-level stack frames");
812
813  const Stmt *CallSite = CalleeCtx->getCallSite();
814
815  if (CallSite) {
816    if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
817      return getSimpleCall(CE, State, CallerCtx);
818
819    switch (CallSite->getStmtClass()) {
820    case Stmt::CXXConstructExprClass: {
821      SValBuilder &SVB = State->getStateManager().getSValBuilder();
822      const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
823      Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
824      SVal ThisVal = State->getSVal(ThisPtr);
825
826      return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
827                                   ThisVal.getAsRegion(), State, CallerCtx);
828    }
829    case Stmt::CXXNewExprClass:
830      return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
831    case Stmt::ObjCMessageExprClass:
832      return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
833                               State, CallerCtx);
834    default:
835      llvm_unreachable("This is not an inlineable statement.");
836    }
837  }
838
839  // Fall back to the CFG. The only thing we haven't handled yet is
840  // destructors, though this could change in the future.
841  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
842  CFGElement E = (*B)[CalleeCtx->getIndex()];
843  assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
844  assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
845
846  SValBuilder &SVB = State->getStateManager().getSValBuilder();
847  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
848  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
849  SVal ThisVal = State->getSVal(ThisPtr);
850
851  const Stmt *Trigger;
852  if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
853    Trigger = AutoDtor->getTriggerStmt();
854  else
855    Trigger = Dtor->getBody();
856
857  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
858                              State, CallerCtx);
859}
860
861