xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //== MIGChecker.cpp - MIG calling convention checker ------------*- C++ -*--==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines MIGChecker, a Mach Interface Generator calling convention
100b57cec5SDimitry Andric // checker. Namely, in MIG callback implementation the following rules apply:
110b57cec5SDimitry Andric // - When a server routine returns an error code that represents success, it
120b57cec5SDimitry Andric //   must take ownership of resources passed to it (and eventually release
130b57cec5SDimitry Andric //   them).
140b57cec5SDimitry Andric // - Additionally, when returning success, all out-parameters must be
150b57cec5SDimitry Andric //   initialized.
160b57cec5SDimitry Andric // - When it returns any other error code, it must not take ownership,
170b57cec5SDimitry Andric //   because the message and its out-of-line parameters will be destroyed
180b57cec5SDimitry Andric //   by the client that called the function.
190b57cec5SDimitry Andric // For now we only check the last rule, as its violations lead to dangerous
200b57cec5SDimitry Andric // use-after-free exploits.
210b57cec5SDimitry Andric //
220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
230b57cec5SDimitry Andric 
24*480093f4SDimitry Andric #include "clang/AST/Attr.h"
250b57cec5SDimitry Andric #include "clang/Analysis/AnyCall.h"
260b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
280b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
290b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
300b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric using namespace clang;
340b57cec5SDimitry Andric using namespace ento;
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric namespace {
370b57cec5SDimitry Andric class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
380b57cec5SDimitry Andric                                   check::EndFunction> {
390b57cec5SDimitry Andric   BugType BT{this, "Use-after-free (MIG calling convention violation)",
400b57cec5SDimitry Andric              categories::MemoryError};
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric   // The checker knows that an out-of-line object is deallocated if it is
430b57cec5SDimitry Andric   // passed as an argument to one of these functions. If this object is
440b57cec5SDimitry Andric   // additionally an argument of a MIG routine, the checker keeps track of that
450b57cec5SDimitry Andric   // information and issues a warning when an error is returned from the
460b57cec5SDimitry Andric   // respective routine.
470b57cec5SDimitry Andric   std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
480b57cec5SDimitry Andric #define CALL(required_args, deallocated_arg, ...)                              \
490b57cec5SDimitry Andric   {{{__VA_ARGS__}, required_args}, deallocated_arg}
500b57cec5SDimitry Andric       // E.g., if the checker sees a C function 'vm_deallocate' that is
510b57cec5SDimitry Andric       // defined on class 'IOUserClient' that has exactly 3 parameters, it knows
520b57cec5SDimitry Andric       // that argument #1 (starting from 0, i.e. the second argument) is going
530b57cec5SDimitry Andric       // to be consumed in the sense of the MIG consume-on-success convention.
540b57cec5SDimitry Andric       CALL(3, 1, "vm_deallocate"),
550b57cec5SDimitry Andric       CALL(3, 1, "mach_vm_deallocate"),
560b57cec5SDimitry Andric       CALL(2, 0, "mig_deallocate"),
570b57cec5SDimitry Andric       CALL(2, 1, "mach_port_deallocate"),
580b57cec5SDimitry Andric       CALL(1, 0, "device_deallocate"),
590b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_connect_reference"),
600b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_reference"),
610b57cec5SDimitry Andric       CALL(1, 0, "iokit_release_port"),
620b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release"),
630b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release_sonce"),
640b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_attr_control_release"),
650b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_release"),
660b57cec5SDimitry Andric       CALL(1, 0, "lock_set_dereference"),
670b57cec5SDimitry Andric       CALL(1, 0, "memory_object_control_deallocate"),
680b57cec5SDimitry Andric       CALL(1, 0, "pset_deallocate"),
690b57cec5SDimitry Andric       CALL(1, 0, "semaphore_dereference"),
700b57cec5SDimitry Andric       CALL(1, 0, "space_deallocate"),
710b57cec5SDimitry Andric       CALL(1, 0, "space_inspect_deallocate"),
720b57cec5SDimitry Andric       CALL(1, 0, "task_deallocate"),
730b57cec5SDimitry Andric       CALL(1, 0, "task_inspect_deallocate"),
740b57cec5SDimitry Andric       CALL(1, 0, "task_name_deallocate"),
750b57cec5SDimitry Andric       CALL(1, 0, "thread_deallocate"),
760b57cec5SDimitry Andric       CALL(1, 0, "thread_inspect_deallocate"),
770b57cec5SDimitry Andric       CALL(1, 0, "upl_deallocate"),
780b57cec5SDimitry Andric       CALL(1, 0, "vm_map_deallocate"),
790b57cec5SDimitry Andric       // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
800b57cec5SDimitry Andric       // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
810b57cec5SDimitry Andric       // that the argument is going to be consumed in the sense of the MIG
820b57cec5SDimitry Andric       // consume-on-success convention.
830b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
840b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
850b57cec5SDimitry Andric #undef CALL
860b57cec5SDimitry Andric   };
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   CallDescription OsRefRetain{"os_ref_retain", 1};
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric public:
930b57cec5SDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   // HACK: We're making two attempts to find the bug: checkEndFunction
960b57cec5SDimitry Andric   // should normally be enough but it fails when the return value is a literal
970b57cec5SDimitry Andric   // that never gets put into the Environment and ends of function with multiple
980b57cec5SDimitry Andric   // returns get agglutinated across returns, preventing us from obtaining
990b57cec5SDimitry Andric   // the return value. The problem is similar to https://reviews.llvm.org/D25326
1000b57cec5SDimitry Andric   // but now we step into it in the top-level function.
1010b57cec5SDimitry Andric   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
1020b57cec5SDimitry Andric     checkReturnAux(RS, C);
1030b57cec5SDimitry Andric   }
1040b57cec5SDimitry Andric   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
1050b57cec5SDimitry Andric     checkReturnAux(RS, C);
1060b57cec5SDimitry Andric   }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric };
1090b57cec5SDimitry Andric } // end anonymous namespace
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric // A flag that says that the programmer has called a MIG destructor
1120b57cec5SDimitry Andric // for at least one parameter.
1130b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
1140b57cec5SDimitry Andric // A set of parameters for which the check is suppressed because
1150b57cec5SDimitry Andric // reference counting is being performed.
1160b57cec5SDimitry Andric REGISTER_SET_WITH_PROGRAMSTATE(RefCountedParameters, const ParmVarDecl *)
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C,
1190b57cec5SDimitry Andric                                          bool IncludeBaseRegions = false) {
1200b57cec5SDimitry Andric   // TODO: We should most likely always include base regions here.
1210b57cec5SDimitry Andric   SymbolRef Sym = V.getAsSymbol(IncludeBaseRegions);
1220b57cec5SDimitry Andric   if (!Sym)
1230b57cec5SDimitry Andric     return nullptr;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // If we optimistically assume that the MIG routine never re-uses the storage
1260b57cec5SDimitry Andric   // that was passed to it as arguments when it invalidates it (but at most when
1270b57cec5SDimitry Andric   // it assigns to parameter variables directly), this procedure correctly
1280b57cec5SDimitry Andric   // determines if the value was loaded from the transitive closure of MIG
1290b57cec5SDimitry Andric   // routine arguments in the heap.
1300b57cec5SDimitry Andric   while (const MemRegion *MR = Sym->getOriginRegion()) {
1310b57cec5SDimitry Andric     const auto *VR = dyn_cast<VarRegion>(MR);
1320b57cec5SDimitry Andric     if (VR && VR->hasStackParametersStorage() &&
1330b57cec5SDimitry Andric            VR->getStackFrame()->inTopFrame())
1340b57cec5SDimitry Andric       return cast<ParmVarDecl>(VR->getDecl());
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric     const SymbolicRegion *SR = MR->getSymbolicBase();
1370b57cec5SDimitry Andric     if (!SR)
1380b57cec5SDimitry Andric       return nullptr;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     Sym = SR->getSymbol();
1410b57cec5SDimitry Andric   }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   return nullptr;
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric static bool isInMIGCall(CheckerContext &C) {
1470b57cec5SDimitry Andric   const LocationContext *LC = C.getLocationContext();
1480b57cec5SDimitry Andric   assert(LC && "Unknown location context");
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   const StackFrameContext *SFC;
1510b57cec5SDimitry Andric   // Find the top frame.
1520b57cec5SDimitry Andric   while (LC) {
1530b57cec5SDimitry Andric     SFC = LC->getStackFrame();
1540b57cec5SDimitry Andric     LC = SFC->getParent();
1550b57cec5SDimitry Andric   }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   const Decl *D = SFC->getDecl();
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
1600b57cec5SDimitry Andric     // Even though there's a Sema warning when the return type of an annotated
1610b57cec5SDimitry Andric     // function is not a kern_return_t, this warning isn't an error, so we need
1620b57cec5SDimitry Andric     // an extra sanity check here.
1630b57cec5SDimitry Andric     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
1640b57cec5SDimitry Andric     // for now.
1650b57cec5SDimitry Andric     if (!AC->getReturnType(C.getASTContext())
1660b57cec5SDimitry Andric              .getCanonicalType()->isSignedIntegerType())
1670b57cec5SDimitry Andric       return false;
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   if (D->hasAttr<MIGServerRoutineAttr>())
1710b57cec5SDimitry Andric     return true;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // See if there's an annotated method in the superclass.
1740b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
1750b57cec5SDimitry Andric     for (const auto *OMD: MD->overridden_methods())
1760b57cec5SDimitry Andric       if (OMD->hasAttr<MIGServerRoutineAttr>())
1770b57cec5SDimitry Andric         return true;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   return false;
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
1830b57cec5SDimitry Andric   if (Call.isCalled(OsRefRetain)) {
1840b57cec5SDimitry Andric     // If the code is doing reference counting over the parameter,
1850b57cec5SDimitry Andric     // it opens up an opportunity for safely calling a destructor function.
1860b57cec5SDimitry Andric     // TODO: We should still check for over-releases.
1870b57cec5SDimitry Andric     if (const ParmVarDecl *PVD =
1880b57cec5SDimitry Andric             getOriginParam(Call.getArgSVal(0), C, /*IncludeBaseRegions=*/true)) {
1890b57cec5SDimitry Andric       // We never need to clean up the program state because these are
1900b57cec5SDimitry Andric       // top-level parameters anyway, so they're always live.
1910b57cec5SDimitry Andric       C.addTransition(C.getState()->add<RefCountedParameters>(PVD));
1920b57cec5SDimitry Andric     }
1930b57cec5SDimitry Andric     return;
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   if (!isInMIGCall(C))
1970b57cec5SDimitry Andric     return;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   auto I = llvm::find_if(Deallocators,
2000b57cec5SDimitry Andric                          [&](const std::pair<CallDescription, unsigned> &Item) {
2010b57cec5SDimitry Andric                            return Call.isCalled(Item.first);
2020b57cec5SDimitry Andric                          });
2030b57cec5SDimitry Andric   if (I == Deallocators.end())
2040b57cec5SDimitry Andric     return;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2070b57cec5SDimitry Andric   unsigned ArgIdx = I->second;
2080b57cec5SDimitry Andric   SVal Arg = Call.getArgSVal(ArgIdx);
2090b57cec5SDimitry Andric   const ParmVarDecl *PVD = getOriginParam(Arg, C);
2100b57cec5SDimitry Andric   if (!PVD || State->contains<RefCountedParameters>(PVD))
2110b57cec5SDimitry Andric     return;
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   const NoteTag *T = C.getNoteTag([this, PVD](BugReport &BR) -> std::string {
2140b57cec5SDimitry Andric     if (&BR.getBugType() != &BT)
2150b57cec5SDimitry Andric       return "";
2160b57cec5SDimitry Andric     SmallString<64> Str;
2170b57cec5SDimitry Andric     llvm::raw_svector_ostream OS(Str);
2180b57cec5SDimitry Andric     OS << "Value passed through parameter '" << PVD->getName()
2190b57cec5SDimitry Andric        << "\' is deallocated";
2200b57cec5SDimitry Andric     return OS.str();
2210b57cec5SDimitry Andric   });
2220b57cec5SDimitry Andric   C.addTransition(State->set<ReleasedParameter>(true), T);
2230b57cec5SDimitry Andric }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric // Returns true if V can potentially represent a "successful" kern_return_t.
2260b57cec5SDimitry Andric static bool mayBeSuccess(SVal V, CheckerContext &C) {
2270b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   // Can V represent KERN_SUCCESS?
2300b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedFalse())
2310b57cec5SDimitry Andric     return true;
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   SValBuilder &SVB = C.getSValBuilder();
2340b57cec5SDimitry Andric   ASTContext &ACtx = C.getASTContext();
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   // Can V represent MIG_NO_REPLY?
2370b57cec5SDimitry Andric   static const int MigNoReply = -305;
2380b57cec5SDimitry Andric   V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
2390b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedTrue())
2400b57cec5SDimitry Andric     return true;
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   // If none of the above, it's definitely an error.
2430b57cec5SDimitry Andric   return false;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
2470b57cec5SDimitry Andric   // It is very unlikely that a MIG callback will be called from anywhere
2480b57cec5SDimitry Andric   // within the project under analysis and the caller isn't itself a routine
2490b57cec5SDimitry Andric   // that follows the MIG calling convention. Therefore we're safe to believe
2500b57cec5SDimitry Andric   // that it's always the top frame that is of interest. There's a slight chance
2510b57cec5SDimitry Andric   // that the user would want to enforce the MIG calling convention upon
2520b57cec5SDimitry Andric   // a random routine in the middle of nowhere, but given that the convention is
2530b57cec5SDimitry Andric   // fairly weird and hard to follow in the first place, there's relatively
2540b57cec5SDimitry Andric   // little motivation to spread it this way.
2550b57cec5SDimitry Andric   if (!C.inTopFrame())
2560b57cec5SDimitry Andric     return;
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   if (!isInMIGCall(C))
2590b57cec5SDimitry Andric     return;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   // We know that the function is non-void, but what if the return statement
2620b57cec5SDimitry Andric   // is not there in the code? It's not a compile error, we should not crash.
2630b57cec5SDimitry Andric   if (!RS)
2640b57cec5SDimitry Andric     return;
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2670b57cec5SDimitry Andric   if (!State->get<ReleasedParameter>())
2680b57cec5SDimitry Andric     return;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   SVal V = C.getSVal(RS);
2710b57cec5SDimitry Andric   if (mayBeSuccess(V, C))
2720b57cec5SDimitry Andric     return;
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   ExplodedNode *N = C.generateErrorNode();
2750b57cec5SDimitry Andric   if (!N)
2760b57cec5SDimitry Andric     return;
2770b57cec5SDimitry Andric 
278a7dea167SDimitry Andric   auto R = std::make_unique<PathSensitiveBugReport>(
2790b57cec5SDimitry Andric       BT,
2800b57cec5SDimitry Andric       "MIG callback fails with error after deallocating argument value. "
2810b57cec5SDimitry Andric       "This is a use-after-free vulnerability because the caller will try to "
2820b57cec5SDimitry Andric       "deallocate it again",
2830b57cec5SDimitry Andric       N);
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   R->addRange(RS->getSourceRange());
286a7dea167SDimitry Andric   bugreporter::trackExpressionValue(N, RS->getRetValue(), *R,
287a7dea167SDimitry Andric                                     bugreporter::TrackingKind::Thorough, false);
2880b57cec5SDimitry Andric   C.emitReport(std::move(R));
2890b57cec5SDimitry Andric }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric void ento::registerMIGChecker(CheckerManager &Mgr) {
2920b57cec5SDimitry Andric   Mgr.registerChecker<MIGChecker>();
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric bool ento::shouldRegisterMIGChecker(const LangOptions &LO) {
2960b57cec5SDimitry Andric   return true;
2970b57cec5SDimitry Andric }
298