xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 6b39f10a00c07bae84d7458e6a616351017bb7c0)
1 //== MIGChecker.cpp - MIG calling convention checker ------------*- C++ -*--==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines MIGChecker, a Mach Interface Generator calling convention
10 // checker. Namely, in MIG callback implementation the following rules apply:
11 // - When a server routine returns an error code that represents success, it
12 //   must take ownership of resources passed to it (and eventually release
13 //   them).
14 // - Additionally, when returning success, all out-parameters must be
15 //   initialized.
16 // - When it returns any other error code, it must not take ownership,
17 //   because the message and its out-of-line parameters will be destroyed
18 //   by the client that called the function.
19 // For now we only check the last rule, as its violations lead to dangerous
20 // use-after-free exploits.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "clang/Analysis/AnyCall.h"
25 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/Checker.h"
28 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
31 
32 using namespace clang;
33 using namespace ento;
34 
35 namespace {
36 class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
37                                   check::EndFunction> {
38   BugType BT{this, "Use-after-free (MIG calling convention violation)",
39              categories::MemoryError};
40 
41   // The checker knows that an out-of-line object is deallocated if it is
42   // passed as an argument to one of these functions. If this object is
43   // additionally an argument of a MIG routine, the checker keeps track of that
44   // information and issues a warning when an error is returned from the
45   // respective routine.
46   std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
47 #define CALL(required_args, deallocated_arg, ...)                              \
48   {{{__VA_ARGS__}, required_args}, deallocated_arg}
49       // E.g., if the checker sees a C function 'vm_deallocate' that is
50       // defined on class 'IOUserClient' that has exactly 3 parameters, it knows
51       // that argument #1 (starting from 0, i.e. the second argument) is going
52       // to be consumed in the sense of the MIG consume-on-success convention.
53       CALL(3, 1, "vm_deallocate"),
54       CALL(3, 1, "mach_vm_deallocate"),
55       CALL(2, 0, "mig_deallocate"),
56       CALL(2, 1, "mach_port_deallocate"),
57       // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
58       // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
59       // that the argument is going to be consumed in the sense of the MIG
60       // consume-on-success convention.
61       CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
62 #undef CALL
63   };
64 
65   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
66 
67 public:
68   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
69 
70   // HACK: We're making two attempts to find the bug: checkEndFunction
71   // should normally be enough but it fails when the return value is a literal
72   // that never gets put into the Environment and ends of function with multiple
73   // returns get agglutinated across returns, preventing us from obtaining
74   // the return value. The problem is similar to https://reviews.llvm.org/D25326
75   // but now we step into it in the top-level function.
76   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
77     checkReturnAux(RS, C);
78   }
79   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
80     checkReturnAux(RS, C);
81   }
82 
83 };
84 } // end anonymous namespace
85 
86 REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
87 
88 static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C) {
89   SymbolRef Sym = V.getAsSymbol();
90   if (!Sym)
91     return nullptr;
92 
93   // If we optimistically assume that the MIG routine never re-uses the storage
94   // that was passed to it as arguments when it invalidates it (but at most when
95   // it assigns to parameter variables directly), this procedure correctly
96   // determines if the value was loaded from the transitive closure of MIG
97   // routine arguments in the heap.
98   while (const MemRegion *MR = Sym->getOriginRegion()) {
99     const auto *VR = dyn_cast<VarRegion>(MR);
100     if (VR && VR->hasStackParametersStorage() &&
101            VR->getStackFrame()->inTopFrame())
102       return cast<ParmVarDecl>(VR->getDecl());
103 
104     const SymbolicRegion *SR = MR->getSymbolicBase();
105     if (!SR)
106       return nullptr;
107 
108     Sym = SR->getSymbol();
109   }
110 
111   return nullptr;
112 }
113 
114 static bool isInMIGCall(CheckerContext &C) {
115   const LocationContext *LC = C.getLocationContext();
116   const StackFrameContext *SFC;
117   // Find the top frame.
118   while (LC) {
119     SFC = LC->getStackFrame();
120     LC = SFC->getParent();
121   }
122 
123   const Decl *D = SFC->getDecl();
124 
125   if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
126     // Even though there's a Sema warning when the return type of an annotated
127     // function is not a kern_return_t, this warning isn't an error, so we need
128     // an extra sanity check here.
129     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
130     // for now.
131     if (!AC->getReturnType(C.getASTContext())
132              .getCanonicalType()->isSignedIntegerType())
133       return false;
134   }
135 
136   if (D->hasAttr<MIGServerRoutineAttr>())
137     return true;
138 
139   // See if there's an annotated method in the superclass.
140   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
141     for (const auto *OMD: MD->overridden_methods())
142       if (OMD->hasAttr<MIGServerRoutineAttr>())
143         return true;
144 
145   return false;
146 }
147 
148 void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
149   if (!isInMIGCall(C))
150     return;
151 
152   auto I = std::find_if(Deallocators.begin(), Deallocators.end(),
153                         [&](const std::pair<CallDescription, unsigned> &Item) {
154                           return Call.isCalled(Item.first);
155                         });
156   if (I == Deallocators.end())
157     return;
158 
159   unsigned ArgIdx = I->second;
160   SVal Arg = Call.getArgSVal(ArgIdx);
161   const ParmVarDecl *PVD = getOriginParam(Arg, C);
162   if (!PVD)
163     return;
164 
165   const NoteTag *T = C.getNoteTag([this, PVD](BugReport &BR) -> std::string {
166     if (&BR.getBugType() != &BT)
167       return "";
168     SmallString<64> Str;
169     llvm::raw_svector_ostream OS(Str);
170     OS << "Value passed through parameter '" << PVD->getName()
171        << "\' is deallocated";
172     return OS.str();
173   });
174   C.addTransition(C.getState()->set<ReleasedParameter>(true), T);
175 }
176 
177 // Returns true if V can potentially represent a "successful" kern_return_t.
178 static bool mayBeSuccess(SVal V, CheckerContext &C) {
179   ProgramStateRef State = C.getState();
180 
181   // Can V represent KERN_SUCCESS?
182   if (!State->isNull(V).isConstrainedFalse())
183     return true;
184 
185   SValBuilder &SVB = C.getSValBuilder();
186   ASTContext &ACtx = C.getASTContext();
187 
188   // Can V represent MIG_NO_REPLY?
189   static const int MigNoReply = -305;
190   V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
191   if (!State->isNull(V).isConstrainedTrue())
192     return true;
193 
194   // If none of the above, it's definitely an error.
195   return false;
196 }
197 
198 void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
199   // It is very unlikely that a MIG callback will be called from anywhere
200   // within the project under analysis and the caller isn't itself a routine
201   // that follows the MIG calling convention. Therefore we're safe to believe
202   // that it's always the top frame that is of interest. There's a slight chance
203   // that the user would want to enforce the MIG calling convention upon
204   // a random routine in the middle of nowhere, but given that the convention is
205   // fairly weird and hard to follow in the first place, there's relatively
206   // little motivation to spread it this way.
207   if (!C.inTopFrame())
208     return;
209 
210   if (!isInMIGCall(C))
211     return;
212 
213   // We know that the function is non-void, but what if the return statement
214   // is not there in the code? It's not a compile error, we should not crash.
215   if (!RS)
216     return;
217 
218   ProgramStateRef State = C.getState();
219   if (!State->get<ReleasedParameter>())
220     return;
221 
222   SVal V = C.getSVal(RS);
223   if (mayBeSuccess(V, C))
224     return;
225 
226   ExplodedNode *N = C.generateErrorNode();
227   if (!N)
228     return;
229 
230   auto R = llvm::make_unique<BugReport>(
231       BT,
232       "MIG callback fails with error after deallocating argument value. "
233       "This is a use-after-free vulnerability because the caller will try to "
234       "deallocate it again",
235       N);
236 
237   R->addRange(RS->getSourceRange());
238   bugreporter::trackExpressionValue(N, RS->getRetValue(), *R, false);
239   C.emitReport(std::move(R));
240 }
241 
242 void ento::registerMIGChecker(CheckerManager &Mgr) {
243   Mgr.registerChecker<MIGChecker>();
244 }
245 
246 bool ento::shouldRegisterMIGChecker(const LangOptions &LO) {
247   return true;
248 }
249