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/AST/ParentMap.h"
18 #include "clang/Analysis/ProgramPoint.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace clang;
25 using namespace ento;
26
getResultType() const27 QualType CallEvent::getResultType() const {
28 const Expr *E = getOriginExpr();
29 assert(E && "Calls without origin expressions do not have results");
30 QualType ResultTy = E->getType();
31
32 ASTContext &Ctx = getState()->getStateManager().getContext();
33
34 // A function that returns a reference to 'int' will have a result type
35 // of simply 'int'. Check the origin expr's value kind to recover the
36 // proper type.
37 switch (E->getValueKind()) {
38 case VK_LValue:
39 ResultTy = Ctx.getLValueReferenceType(ResultTy);
40 break;
41 case VK_XValue:
42 ResultTy = Ctx.getRValueReferenceType(ResultTy);
43 break;
44 case VK_RValue:
45 // No adjustment is necessary.
46 break;
47 }
48
49 return ResultTy;
50 }
51
isCallbackArg(SVal V,QualType T)52 static bool isCallbackArg(SVal V, QualType T) {
53 // If the parameter is 0, it's harmless.
54 if (V.isZeroConstant())
55 return false;
56
57 // If a parameter is a block or a callback, assume it can modify pointer.
58 if (T->isBlockPointerType() ||
59 T->isFunctionPointerType() ||
60 T->isObjCSelType())
61 return true;
62
63 // Check if a callback is passed inside a struct (for both, struct passed by
64 // reference and by value). Dig just one level into the struct for now.
65
66 if (T->isAnyPointerType() || T->isReferenceType())
67 T = T->getPointeeType();
68
69 if (const RecordType *RT = T->getAsStructureType()) {
70 const RecordDecl *RD = RT->getDecl();
71 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
72 I != E; ++I) {
73 QualType FieldT = I->getType();
74 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
75 return true;
76 }
77 }
78
79 return false;
80 }
81
hasNonZeroCallbackArg() const82 bool CallEvent::hasNonZeroCallbackArg() const {
83 unsigned NumOfArgs = getNumArgs();
84
85 // If calling using a function pointer, assume the function does not
86 // have a callback. TODO: We could check the types of the arguments here.
87 if (!getDecl())
88 return false;
89
90 unsigned Idx = 0;
91 for (CallEvent::param_type_iterator I = param_type_begin(),
92 E = param_type_end();
93 I != E && Idx < NumOfArgs; ++I, ++Idx) {
94 if (NumOfArgs <= Idx)
95 break;
96
97 if (isCallbackArg(getArgSVal(Idx), *I))
98 return true;
99 }
100
101 return false;
102 }
103
isGlobalCFunction(StringRef FunctionName) const104 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
105 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
106 if (!FD)
107 return false;
108
109 return CheckerContext::isCLibraryFunction(FD, FunctionName);
110 }
111
112 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
113 /// with no further indirection.
isPointerToConst(QualType Ty)114 static bool isPointerToConst(QualType Ty) {
115 QualType PointeeTy = Ty->getPointeeType();
116 if (PointeeTy == QualType())
117 return false;
118 if (!PointeeTy.isConstQualified())
119 return false;
120 if (PointeeTy->isAnyPointerType())
121 return false;
122 return true;
123 }
124
125 // Try to retrieve the function declaration and find the function parameter
126 // types which are pointers/references to a non-pointer const.
127 // We will not invalidate the corresponding argument regions.
findPtrToConstParams(llvm::SmallSet<unsigned,4> & PreserveArgs,const CallEvent & Call)128 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
129 const CallEvent &Call) {
130 unsigned Idx = 0;
131 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
132 E = Call.param_type_end();
133 I != E; ++I, ++Idx) {
134 if (isPointerToConst(*I))
135 PreserveArgs.insert(Idx);
136 }
137 }
138
invalidateRegions(unsigned BlockCount,ProgramStateRef Orig) const139 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
140 ProgramStateRef Orig) const {
141 ProgramStateRef Result = (Orig ? Orig : getState());
142
143 SmallVector<SVal, 8> ConstValues;
144 SmallVector<SVal, 8> ValuesToInvalidate;
145
146 getExtraInvalidatedValues(ValuesToInvalidate);
147
148 // Indexes of arguments whose values will be preserved by the call.
149 llvm::SmallSet<unsigned, 4> PreserveArgs;
150 if (!argumentsMayEscape())
151 findPtrToConstParams(PreserveArgs, *this);
152
153 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
154 // Mark this region for invalidation. We batch invalidate regions
155 // below for efficiency.
156 if (PreserveArgs.count(Idx))
157 ConstValues.push_back(getArgSVal(Idx));
158 else
159 ValuesToInvalidate.push_back(getArgSVal(Idx));
160 }
161
162 // Invalidate designated regions using the batch invalidation API.
163 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
164 // global variables.
165 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
166 BlockCount, getLocationContext(),
167 /*CausedByPointerEscape*/ true,
168 /*Symbols=*/0, this, ConstValues);
169 }
170
getProgramPoint(bool IsPreVisit,const ProgramPointTag * Tag) const171 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
172 const ProgramPointTag *Tag) const {
173 if (const Expr *E = getOriginExpr()) {
174 if (IsPreVisit)
175 return PreStmt(E, getLocationContext(), Tag);
176 return PostStmt(E, getLocationContext(), Tag);
177 }
178
179 const Decl *D = getDecl();
180 assert(D && "Cannot get a program point without a statement or decl");
181
182 SourceLocation Loc = getSourceRange().getBegin();
183 if (IsPreVisit)
184 return PreImplicitCall(D, Loc, getLocationContext(), Tag);
185 return PostImplicitCall(D, Loc, getLocationContext(), Tag);
186 }
187
getArgSVal(unsigned Index) const188 SVal CallEvent::getArgSVal(unsigned Index) const {
189 const Expr *ArgE = getArgExpr(Index);
190 if (!ArgE)
191 return UnknownVal();
192 return getSVal(ArgE);
193 }
194
getArgSourceRange(unsigned Index) const195 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
196 const Expr *ArgE = getArgExpr(Index);
197 if (!ArgE)
198 return SourceRange();
199 return ArgE->getSourceRange();
200 }
201
getReturnValue() const202 SVal CallEvent::getReturnValue() const {
203 const Expr *E = getOriginExpr();
204 if (!E)
205 return UndefinedVal();
206 return getSVal(E);
207 }
208
dump() const209 void CallEvent::dump() const {
210 dump(llvm::errs());
211 }
212
dump(raw_ostream & Out) const213 void CallEvent::dump(raw_ostream &Out) const {
214 ASTContext &Ctx = getState()->getStateManager().getContext();
215 if (const Expr *E = getOriginExpr()) {
216 E->printPretty(Out, 0, Ctx.getPrintingPolicy());
217 Out << "\n";
218 return;
219 }
220
221 if (const Decl *D = getDecl()) {
222 Out << "Call to ";
223 D->print(Out, Ctx.getPrintingPolicy());
224 return;
225 }
226
227 // FIXME: a string representation of the kind would be nice.
228 Out << "Unknown call (type " << getKind() << ")";
229 }
230
231
isCallStmt(const Stmt * S)232 bool CallEvent::isCallStmt(const Stmt *S) {
233 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
234 || isa<CXXConstructExpr>(S)
235 || isa<CXXNewExpr>(S);
236 }
237
getDeclaredResultType(const Decl * D)238 QualType CallEvent::getDeclaredResultType(const Decl *D) {
239 assert(D);
240 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
241 return FD->getResultType();
242 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
243 return MD->getResultType();
244 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
245 // Blocks are difficult because the return type may not be stored in the
246 // BlockDecl itself. The AST should probably be enhanced, but for now we
247 // just do what we can.
248 // If the block is declared without an explicit argument list, the
249 // signature-as-written just includes the return type, not the entire
250 // function type.
251 // FIXME: All blocks should have signatures-as-written, even if the return
252 // type is inferred. (That's signified with a dependent result type.)
253 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
254 QualType Ty = TSI->getType();
255 if (const FunctionType *FT = Ty->getAs<FunctionType>())
256 Ty = FT->getResultType();
257 if (!Ty->isDependentType())
258 return Ty;
259 }
260
261 return QualType();
262 }
263
264 return QualType();
265 }
266
addParameterValuesToBindings(const StackFrameContext * CalleeCtx,CallEvent::BindingsTy & Bindings,SValBuilder & SVB,const CallEvent & Call,CallEvent::param_iterator I,CallEvent::param_iterator E)267 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
268 CallEvent::BindingsTy &Bindings,
269 SValBuilder &SVB,
270 const CallEvent &Call,
271 CallEvent::param_iterator I,
272 CallEvent::param_iterator E) {
273 MemRegionManager &MRMgr = SVB.getRegionManager();
274
275 // If the function has fewer parameters than the call has arguments, we simply
276 // do not bind any values to them.
277 unsigned NumArgs = Call.getNumArgs();
278 unsigned Idx = 0;
279 for (; I != E && Idx < NumArgs; ++I, ++Idx) {
280 const ParmVarDecl *ParamDecl = *I;
281 assert(ParamDecl && "Formal parameter has no decl?");
282
283 SVal ArgVal = Call.getArgSVal(Idx);
284 if (!ArgVal.isUnknown()) {
285 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
286 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
287 }
288 }
289
290 // FIXME: Variadic arguments are not handled at all right now.
291 }
292
293
param_begin() const294 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
295 const FunctionDecl *D = getDecl();
296 if (!D)
297 return 0;
298
299 return D->param_begin();
300 }
301
param_end() const302 CallEvent::param_iterator AnyFunctionCall::param_end() const {
303 const FunctionDecl *D = getDecl();
304 if (!D)
305 return 0;
306
307 return D->param_end();
308 }
309
getInitialStackFrameContents(const StackFrameContext * CalleeCtx,BindingsTy & Bindings) const310 void AnyFunctionCall::getInitialStackFrameContents(
311 const StackFrameContext *CalleeCtx,
312 BindingsTy &Bindings) const {
313 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
314 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
315 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
316 D->param_begin(), D->param_end());
317 }
318
argumentsMayEscape() const319 bool AnyFunctionCall::argumentsMayEscape() const {
320 if (hasNonZeroCallbackArg())
321 return true;
322
323 const FunctionDecl *D = getDecl();
324 if (!D)
325 return true;
326
327 const IdentifierInfo *II = D->getIdentifier();
328 if (!II)
329 return false;
330
331 // This set of "escaping" APIs is
332
333 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
334 // value into thread local storage. The value can later be retrieved with
335 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
336 // parameter is 'const void *', the region escapes through the call.
337 if (II->isStr("pthread_setspecific"))
338 return true;
339
340 // - xpc_connection_set_context stores a value which can be retrieved later
341 // with xpc_connection_get_context.
342 if (II->isStr("xpc_connection_set_context"))
343 return true;
344
345 // - funopen - sets a buffer for future IO calls.
346 if (II->isStr("funopen"))
347 return true;
348
349 StringRef FName = II->getName();
350
351 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
352 // buffer even if it is const.
353 if (FName.endswith("NoCopy"))
354 return true;
355
356 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
357 // be deallocated by NSMapRemove.
358 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
359 return true;
360
361 // - Many CF containers allow objects to escape through custom
362 // allocators/deallocators upon container construction. (PR12101)
363 if (FName.startswith("CF") || FName.startswith("CG")) {
364 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
365 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
366 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
367 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
368 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
369 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
370 }
371
372 return false;
373 }
374
375
getDecl() const376 const FunctionDecl *SimpleCall::getDecl() const {
377 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
378 if (D)
379 return D;
380
381 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
382 }
383
384
getDecl() const385 const FunctionDecl *CXXInstanceCall::getDecl() const {
386 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
387 if (!CE)
388 return AnyFunctionCall::getDecl();
389
390 const FunctionDecl *D = CE->getDirectCallee();
391 if (D)
392 return D;
393
394 return getSVal(CE->getCallee()).getAsFunctionDecl();
395 }
396
getExtraInvalidatedValues(ValueList & Values) const397 void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const {
398 Values.push_back(getCXXThisVal());
399 }
400
getCXXThisVal() const401 SVal CXXInstanceCall::getCXXThisVal() const {
402 const Expr *Base = getCXXThisExpr();
403 // FIXME: This doesn't handle an overloaded ->* operator.
404 if (!Base)
405 return UnknownVal();
406
407 SVal ThisVal = getSVal(Base);
408 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
409 return ThisVal;
410 }
411
412
getRuntimeDefinition() const413 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
414 // Do we have a decl at all?
415 const Decl *D = getDecl();
416 if (!D)
417 return RuntimeDefinition();
418
419 // If the method is non-virtual, we know we can inline it.
420 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
421 if (!MD->isVirtual())
422 return AnyFunctionCall::getRuntimeDefinition();
423
424 // Do we know the implicit 'this' object being called?
425 const MemRegion *R = getCXXThisVal().getAsRegion();
426 if (!R)
427 return RuntimeDefinition();
428
429 // Do we know anything about the type of 'this'?
430 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
431 if (!DynType.isValid())
432 return RuntimeDefinition();
433
434 // Is the type a C++ class? (This is mostly a defensive check.)
435 QualType RegionType = DynType.getType()->getPointeeType();
436 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
437
438 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
439 if (!RD || !RD->hasDefinition())
440 return RuntimeDefinition();
441
442 // Find the decl for this method in that class.
443 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
444 if (!Result) {
445 // We might not even get the original statically-resolved method due to
446 // some particularly nasty casting (e.g. casts to sister classes).
447 // However, we should at least be able to search up and down our own class
448 // hierarchy, and some real bugs have been caught by checking this.
449 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
450
451 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
452 // the static type. However, because we currently don't update
453 // DynamicTypeInfo when an object is cast, we can't actually be sure the
454 // DynamicTypeInfo is up to date. This assert should be re-enabled once
455 // this is fixed. <rdar://problem/12287087>
456 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
457
458 return RuntimeDefinition();
459 }
460
461 // Does the decl that we found have an implementation?
462 const FunctionDecl *Definition;
463 if (!Result->hasBody(Definition))
464 return RuntimeDefinition();
465
466 // We found a definition. If we're not sure that this devirtualization is
467 // actually what will happen at runtime, make sure to provide the region so
468 // that ExprEngine can decide what to do with it.
469 if (DynType.canBeASubClass())
470 return RuntimeDefinition(Definition, R->StripCasts());
471 return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
472 }
473
getInitialStackFrameContents(const StackFrameContext * CalleeCtx,BindingsTy & Bindings) const474 void CXXInstanceCall::getInitialStackFrameContents(
475 const StackFrameContext *CalleeCtx,
476 BindingsTy &Bindings) const {
477 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
478
479 // Handle the binding of 'this' in the new stack frame.
480 SVal ThisVal = getCXXThisVal();
481 if (!ThisVal.isUnknown()) {
482 ProgramStateManager &StateMgr = getState()->getStateManager();
483 SValBuilder &SVB = StateMgr.getSValBuilder();
484
485 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
486 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
487
488 // If we devirtualized to a different member function, we need to make sure
489 // we have the proper layering of CXXBaseObjectRegions.
490 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
491 ASTContext &Ctx = SVB.getContext();
492 const CXXRecordDecl *Class = MD->getParent();
493 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
494
495 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
496 bool Failed;
497 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
498 assert(!Failed && "Calling an incorrectly devirtualized method");
499 }
500
501 if (!ThisVal.isUnknown())
502 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
503 }
504 }
505
506
507
getCXXThisExpr() const508 const Expr *CXXMemberCall::getCXXThisExpr() const {
509 return getOriginExpr()->getImplicitObjectArgument();
510 }
511
getRuntimeDefinition() const512 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
513 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
514 // id-expression in the class member access expression is a qualified-id,
515 // that function is called. Otherwise, its final overrider in the dynamic type
516 // of the object expression is called.
517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
518 if (ME->hasQualifier())
519 return AnyFunctionCall::getRuntimeDefinition();
520
521 return CXXInstanceCall::getRuntimeDefinition();
522 }
523
524
getCXXThisExpr() const525 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
526 return getOriginExpr()->getArg(0);
527 }
528
529
getBlockRegion() const530 const BlockDataRegion *BlockCall::getBlockRegion() const {
531 const Expr *Callee = getOriginExpr()->getCallee();
532 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
533
534 return dyn_cast_or_null<BlockDataRegion>(DataReg);
535 }
536
param_begin() const537 CallEvent::param_iterator BlockCall::param_begin() const {
538 const BlockDecl *D = getBlockDecl();
539 if (!D)
540 return 0;
541 return D->param_begin();
542 }
543
param_end() const544 CallEvent::param_iterator BlockCall::param_end() const {
545 const BlockDecl *D = getBlockDecl();
546 if (!D)
547 return 0;
548 return D->param_end();
549 }
550
getExtraInvalidatedValues(ValueList & Values) const551 void BlockCall::getExtraInvalidatedValues(ValueList &Values) const {
552 // FIXME: This also needs to invalidate captured globals.
553 if (const MemRegion *R = getBlockRegion())
554 Values.push_back(loc::MemRegionVal(R));
555 }
556
getInitialStackFrameContents(const StackFrameContext * CalleeCtx,BindingsTy & Bindings) const557 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
558 BindingsTy &Bindings) const {
559 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
560 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
561 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
562 D->param_begin(), D->param_end());
563 }
564
565
getCXXThisVal() const566 SVal CXXConstructorCall::getCXXThisVal() const {
567 if (Data)
568 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
569 return UnknownVal();
570 }
571
getExtraInvalidatedValues(ValueList & Values) const572 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const {
573 if (Data)
574 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
575 }
576
getInitialStackFrameContents(const StackFrameContext * CalleeCtx,BindingsTy & Bindings) const577 void CXXConstructorCall::getInitialStackFrameContents(
578 const StackFrameContext *CalleeCtx,
579 BindingsTy &Bindings) const {
580 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
581
582 SVal ThisVal = getCXXThisVal();
583 if (!ThisVal.isUnknown()) {
584 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
585 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
586 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
587 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
588 }
589 }
590
591
592
getCXXThisVal() const593 SVal CXXDestructorCall::getCXXThisVal() const {
594 if (Data)
595 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
596 return UnknownVal();
597 }
598
getRuntimeDefinition() const599 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
600 // Base destructors are always called non-virtually.
601 // Skip CXXInstanceCall's devirtualization logic in this case.
602 if (isBaseDestructor())
603 return AnyFunctionCall::getRuntimeDefinition();
604
605 return CXXInstanceCall::getRuntimeDefinition();
606 }
607
608
param_begin() const609 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
610 const ObjCMethodDecl *D = getDecl();
611 if (!D)
612 return 0;
613
614 return D->param_begin();
615 }
616
param_end() const617 CallEvent::param_iterator ObjCMethodCall::param_end() const {
618 const ObjCMethodDecl *D = getDecl();
619 if (!D)
620 return 0;
621
622 return D->param_end();
623 }
624
625 void
getExtraInvalidatedValues(ValueList & Values) const626 ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const {
627 Values.push_back(getReceiverSVal());
628 }
629
getSelfSVal() const630 SVal ObjCMethodCall::getSelfSVal() const {
631 const LocationContext *LCtx = getLocationContext();
632 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
633 if (!SelfDecl)
634 return SVal();
635 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
636 }
637
getReceiverSVal() const638 SVal ObjCMethodCall::getReceiverSVal() const {
639 // FIXME: Is this the best way to handle class receivers?
640 if (!isInstanceMessage())
641 return UnknownVal();
642
643 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
644 return getSVal(RecE);
645
646 // An instance message with no expression means we are sending to super.
647 // In this case the object reference is the same as 'self'.
648 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
649 SVal SelfVal = getSelfSVal();
650 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
651 return SelfVal;
652 }
653
isReceiverSelfOrSuper() const654 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
655 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
656 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
657 return true;
658
659 if (!isInstanceMessage())
660 return false;
661
662 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
663
664 return (RecVal == getSelfSVal());
665 }
666
getSourceRange() const667 SourceRange ObjCMethodCall::getSourceRange() const {
668 switch (getMessageKind()) {
669 case OCM_Message:
670 return getOriginExpr()->getSourceRange();
671 case OCM_PropertyAccess:
672 case OCM_Subscript:
673 return getContainingPseudoObjectExpr()->getSourceRange();
674 }
675 llvm_unreachable("unknown message kind");
676 }
677
678 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
679
getContainingPseudoObjectExpr() const680 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
681 assert(Data != 0 && "Lazy lookup not yet performed.");
682 assert(getMessageKind() != OCM_Message && "Explicit message send.");
683 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
684 }
685
getMessageKind() const686 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
687 if (Data == 0) {
688 ParentMap &PM = getLocationContext()->getParentMap();
689 const Stmt *S = PM.getParent(getOriginExpr());
690 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
691 const Expr *Syntactic = POE->getSyntacticForm();
692
693 // This handles the funny case of assigning to the result of a getter.
694 // This can happen if the getter returns a non-const reference.
695 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
696 Syntactic = BO->getLHS();
697
698 ObjCMessageKind K;
699 switch (Syntactic->getStmtClass()) {
700 case Stmt::ObjCPropertyRefExprClass:
701 K = OCM_PropertyAccess;
702 break;
703 case Stmt::ObjCSubscriptRefExprClass:
704 K = OCM_Subscript;
705 break;
706 default:
707 // FIXME: Can this ever happen?
708 K = OCM_Message;
709 break;
710 }
711
712 if (K != OCM_Message) {
713 const_cast<ObjCMethodCall *>(this)->Data
714 = ObjCMessageDataTy(POE, K).getOpaqueValue();
715 assert(getMessageKind() == K);
716 return K;
717 }
718 }
719
720 const_cast<ObjCMethodCall *>(this)->Data
721 = ObjCMessageDataTy(0, 1).getOpaqueValue();
722 assert(getMessageKind() == OCM_Message);
723 return OCM_Message;
724 }
725
726 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
727 if (!Info.getPointer())
728 return OCM_Message;
729 return static_cast<ObjCMessageKind>(Info.getInt());
730 }
731
732
canBeOverridenInSubclass(ObjCInterfaceDecl * IDecl,Selector Sel) const733 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
734 Selector Sel) const {
735 assert(IDecl);
736 const SourceManager &SM =
737 getState()->getStateManager().getContext().getSourceManager();
738
739 // If the class interface is declared inside the main file, assume it is not
740 // subcassed.
741 // TODO: It could actually be subclassed if the subclass is private as well.
742 // This is probably very rare.
743 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
744 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
745 return false;
746
747 // Assume that property accessors are not overridden.
748 if (getMessageKind() == OCM_PropertyAccess)
749 return false;
750
751 // We assume that if the method is public (declared outside of main file) or
752 // has a parent which publicly declares the method, the method could be
753 // overridden in a subclass.
754
755 // Find the first declaration in the class hierarchy that declares
756 // the selector.
757 ObjCMethodDecl *D = 0;
758 while (true) {
759 D = IDecl->lookupMethod(Sel, true);
760
761 // Cannot find a public definition.
762 if (!D)
763 return false;
764
765 // If outside the main file,
766 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
767 return true;
768
769 if (D->isOverriding()) {
770 // Search in the superclass on the next iteration.
771 IDecl = D->getClassInterface();
772 if (!IDecl)
773 return false;
774
775 IDecl = IDecl->getSuperClass();
776 if (!IDecl)
777 return false;
778
779 continue;
780 }
781
782 return false;
783 };
784
785 llvm_unreachable("The while loop should always terminate.");
786 }
787
getRuntimeDefinition() const788 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
789 const ObjCMessageExpr *E = getOriginExpr();
790 assert(E);
791 Selector Sel = E->getSelector();
792
793 if (E->isInstanceMessage()) {
794
795 // Find the the receiver type.
796 const ObjCObjectPointerType *ReceiverT = 0;
797 bool CanBeSubClassed = false;
798 QualType SupersType = E->getSuperType();
799 const MemRegion *Receiver = 0;
800
801 if (!SupersType.isNull()) {
802 // Super always means the type of immediate predecessor to the method
803 // where the call occurs.
804 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
805 } else {
806 Receiver = getReceiverSVal().getAsRegion();
807 if (!Receiver)
808 return RuntimeDefinition();
809
810 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
811 QualType DynType = DTI.getType();
812 CanBeSubClassed = DTI.canBeASubClass();
813 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
814
815 if (ReceiverT && CanBeSubClassed)
816 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
817 if (!canBeOverridenInSubclass(IDecl, Sel))
818 CanBeSubClassed = false;
819 }
820
821 // Lookup the method implementation.
822 if (ReceiverT)
823 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
824 // Repeatedly calling lookupPrivateMethod() is expensive, especially
825 // when in many cases it returns null. We cache the results so
826 // that repeated queries on the same ObjCIntefaceDecl and Selector
827 // don't incur the same cost. On some test cases, we can see the
828 // same query being issued thousands of times.
829 //
830 // NOTE: This cache is essentially a "global" variable, but it
831 // only gets lazily created when we get here. The value of the
832 // cache probably comes from it being global across ExprEngines,
833 // where the same queries may get issued. If we are worried about
834 // concurrency, or possibly loading/unloading ASTs, etc., we may
835 // need to revisit this someday. In terms of memory, this table
836 // stays around until clang quits, which also may be bad if we
837 // need to release memory.
838 typedef std::pair<const ObjCInterfaceDecl*, Selector>
839 PrivateMethodKey;
840 typedef llvm::DenseMap<PrivateMethodKey,
841 Optional<const ObjCMethodDecl *> >
842 PrivateMethodCache;
843
844 static PrivateMethodCache PMC;
845 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
846
847 // Query lookupPrivateMethod() if the cache does not hit.
848 if (!Val.hasValue())
849 Val = IDecl->lookupPrivateMethod(Sel);
850
851 const ObjCMethodDecl *MD = Val.getValue();
852 if (CanBeSubClassed)
853 return RuntimeDefinition(MD, Receiver);
854 else
855 return RuntimeDefinition(MD, 0);
856 }
857
858 } else {
859 // This is a class method.
860 // If we have type info for the receiver class, we are calling via
861 // class name.
862 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
863 // Find/Return the method implementation.
864 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
865 }
866 }
867
868 return RuntimeDefinition();
869 }
870
getInitialStackFrameContents(const StackFrameContext * CalleeCtx,BindingsTy & Bindings) const871 void ObjCMethodCall::getInitialStackFrameContents(
872 const StackFrameContext *CalleeCtx,
873 BindingsTy &Bindings) const {
874 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
875 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
876 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
877 D->param_begin(), D->param_end());
878
879 SVal SelfVal = getReceiverSVal();
880 if (!SelfVal.isUnknown()) {
881 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
882 MemRegionManager &MRMgr = SVB.getRegionManager();
883 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
884 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
885 }
886 }
887
888 CallEventRef<>
getSimpleCall(const CallExpr * CE,ProgramStateRef State,const LocationContext * LCtx)889 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
890 const LocationContext *LCtx) {
891 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
892 return create<CXXMemberCall>(MCE, State, LCtx);
893
894 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
895 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
897 if (MD->isInstance())
898 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
899
900 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
901 return create<BlockCall>(CE, State, LCtx);
902 }
903
904 // Otherwise, it's a normal function call, static member function call, or
905 // something we can't reason about.
906 return create<FunctionCall>(CE, State, LCtx);
907 }
908
909
910 CallEventRef<>
getCaller(const StackFrameContext * CalleeCtx,ProgramStateRef State)911 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
912 ProgramStateRef State) {
913 const LocationContext *ParentCtx = CalleeCtx->getParent();
914 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
915 assert(CallerCtx && "This should not be used for top-level stack frames");
916
917 const Stmt *CallSite = CalleeCtx->getCallSite();
918
919 if (CallSite) {
920 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
921 return getSimpleCall(CE, State, CallerCtx);
922
923 switch (CallSite->getStmtClass()) {
924 case Stmt::CXXConstructExprClass:
925 case Stmt::CXXTemporaryObjectExprClass: {
926 SValBuilder &SVB = State->getStateManager().getSValBuilder();
927 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
928 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
929 SVal ThisVal = State->getSVal(ThisPtr);
930
931 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
932 ThisVal.getAsRegion(), State, CallerCtx);
933 }
934 case Stmt::CXXNewExprClass:
935 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
936 case Stmt::ObjCMessageExprClass:
937 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
938 State, CallerCtx);
939 default:
940 llvm_unreachable("This is not an inlineable statement.");
941 }
942 }
943
944 // Fall back to the CFG. The only thing we haven't handled yet is
945 // destructors, though this could change in the future.
946 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
947 CFGElement E = (*B)[CalleeCtx->getIndex()];
948 assert(E.getAs<CFGImplicitDtor>() &&
949 "All other CFG elements should have exprs");
950 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
951
952 SValBuilder &SVB = State->getStateManager().getSValBuilder();
953 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
954 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
955 SVal ThisVal = State->getSVal(ThisPtr);
956
957 const Stmt *Trigger;
958 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
959 Trigger = AutoDtor->getTriggerStmt();
960 else
961 Trigger = Dtor->getBody();
962
963 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
964 E.getAs<CFGBaseDtor>().hasValue(), State,
965 CallerCtx);
966 }
967