xref: /freebsd-src/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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 
24480093f4SDimitry 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"
30349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
33bdd1243dSDimitry Andric #include <optional>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace clang;
360b57cec5SDimitry Andric using namespace ento;
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric namespace {
390b57cec5SDimitry Andric class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
400b57cec5SDimitry Andric                                   check::EndFunction> {
410b57cec5SDimitry Andric   BugType BT{this, "Use-after-free (MIG calling convention violation)",
420b57cec5SDimitry Andric              categories::MemoryError};
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric   // The checker knows that an out-of-line object is deallocated if it is
450b57cec5SDimitry Andric   // passed as an argument to one of these functions. If this object is
460b57cec5SDimitry Andric   // additionally an argument of a MIG routine, the checker keeps track of that
470b57cec5SDimitry Andric   // information and issues a warning when an error is returned from the
480b57cec5SDimitry Andric   // respective routine.
49*0fca6ea1SDimitry Andric   CallDescriptionMap<unsigned> Deallocators = {
500b57cec5SDimitry Andric #define CALL(required_args, deallocated_arg, ...)                              \
51*0fca6ea1SDimitry Andric   {{CDM::SimpleFunc, {__VA_ARGS__}, required_args}, deallocated_arg}
52*0fca6ea1SDimitry Andric       // E.g., if the checker sees a C function 'vm_deallocate' that has
53*0fca6ea1SDimitry Andric       // exactly 3 parameters, it knows that argument #1 (starting from 0, i.e.
54*0fca6ea1SDimitry Andric       // the second argument) is going to be consumed in the sense of the MIG
55*0fca6ea1SDimitry Andric       // consume-on-success convention.
560b57cec5SDimitry Andric       CALL(3, 1, "vm_deallocate"),
570b57cec5SDimitry Andric       CALL(3, 1, "mach_vm_deallocate"),
580b57cec5SDimitry Andric       CALL(2, 0, "mig_deallocate"),
590b57cec5SDimitry Andric       CALL(2, 1, "mach_port_deallocate"),
600b57cec5SDimitry Andric       CALL(1, 0, "device_deallocate"),
610b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_connect_reference"),
620b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_reference"),
630b57cec5SDimitry Andric       CALL(1, 0, "iokit_release_port"),
640b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release"),
650b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release_sonce"),
660b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_attr_control_release"),
670b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_release"),
680b57cec5SDimitry Andric       CALL(1, 0, "lock_set_dereference"),
690b57cec5SDimitry Andric       CALL(1, 0, "memory_object_control_deallocate"),
700b57cec5SDimitry Andric       CALL(1, 0, "pset_deallocate"),
710b57cec5SDimitry Andric       CALL(1, 0, "semaphore_dereference"),
720b57cec5SDimitry Andric       CALL(1, 0, "space_deallocate"),
730b57cec5SDimitry Andric       CALL(1, 0, "space_inspect_deallocate"),
740b57cec5SDimitry Andric       CALL(1, 0, "task_deallocate"),
750b57cec5SDimitry Andric       CALL(1, 0, "task_inspect_deallocate"),
760b57cec5SDimitry Andric       CALL(1, 0, "task_name_deallocate"),
770b57cec5SDimitry Andric       CALL(1, 0, "thread_deallocate"),
780b57cec5SDimitry Andric       CALL(1, 0, "thread_inspect_deallocate"),
790b57cec5SDimitry Andric       CALL(1, 0, "upl_deallocate"),
800b57cec5SDimitry Andric       CALL(1, 0, "vm_map_deallocate"),
81*0fca6ea1SDimitry Andric #undef CALL
82*0fca6ea1SDimitry Andric #define CALL(required_args, deallocated_arg, ...)                              \
83*0fca6ea1SDimitry Andric   {{CDM::CXXMethod, {__VA_ARGS__}, required_args}, deallocated_arg}
840b57cec5SDimitry Andric       // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
850b57cec5SDimitry Andric       // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
860b57cec5SDimitry Andric       // that the argument is going to be consumed in the sense of the MIG
870b57cec5SDimitry Andric       // consume-on-success convention.
880b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
890b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
900b57cec5SDimitry Andric #undef CALL
910b57cec5SDimitry Andric   };
920b57cec5SDimitry Andric 
93*0fca6ea1SDimitry Andric   CallDescription OsRefRetain{CDM::SimpleFunc, {"os_ref_retain"}, 1};
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric public:
980b57cec5SDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   // HACK: We're making two attempts to find the bug: checkEndFunction
1010b57cec5SDimitry Andric   // should normally be enough but it fails when the return value is a literal
1020b57cec5SDimitry Andric   // that never gets put into the Environment and ends of function with multiple
1030b57cec5SDimitry Andric   // returns get agglutinated across returns, preventing us from obtaining
1040b57cec5SDimitry Andric   // the return value. The problem is similar to https://reviews.llvm.org/D25326
1050b57cec5SDimitry Andric   // but now we step into it in the top-level function.
1060b57cec5SDimitry Andric   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
1070b57cec5SDimitry Andric     checkReturnAux(RS, C);
1080b57cec5SDimitry Andric   }
1090b57cec5SDimitry Andric   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
1100b57cec5SDimitry Andric     checkReturnAux(RS, C);
1110b57cec5SDimitry Andric   }
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric };
1140b57cec5SDimitry Andric } // end anonymous namespace
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric // A flag that says that the programmer has called a MIG destructor
1170b57cec5SDimitry Andric // for at least one parameter.
1180b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
1190b57cec5SDimitry Andric // A set of parameters for which the check is suppressed because
1200b57cec5SDimitry Andric // reference counting is being performed.
1210b57cec5SDimitry Andric REGISTER_SET_WITH_PROGRAMSTATE(RefCountedParameters, const ParmVarDecl *)
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C,
1240b57cec5SDimitry Andric                                          bool IncludeBaseRegions = false) {
1250b57cec5SDimitry Andric   // TODO: We should most likely always include base regions here.
1260b57cec5SDimitry Andric   SymbolRef Sym = V.getAsSymbol(IncludeBaseRegions);
1270b57cec5SDimitry Andric   if (!Sym)
1280b57cec5SDimitry Andric     return nullptr;
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   // If we optimistically assume that the MIG routine never re-uses the storage
1310b57cec5SDimitry Andric   // that was passed to it as arguments when it invalidates it (but at most when
1320b57cec5SDimitry Andric   // it assigns to parameter variables directly), this procedure correctly
1330b57cec5SDimitry Andric   // determines if the value was loaded from the transitive closure of MIG
1340b57cec5SDimitry Andric   // routine arguments in the heap.
1350b57cec5SDimitry Andric   while (const MemRegion *MR = Sym->getOriginRegion()) {
1360b57cec5SDimitry Andric     const auto *VR = dyn_cast<VarRegion>(MR);
1370b57cec5SDimitry Andric     if (VR && VR->hasStackParametersStorage() &&
1380b57cec5SDimitry Andric            VR->getStackFrame()->inTopFrame())
1390b57cec5SDimitry Andric       return cast<ParmVarDecl>(VR->getDecl());
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric     const SymbolicRegion *SR = MR->getSymbolicBase();
1420b57cec5SDimitry Andric     if (!SR)
1430b57cec5SDimitry Andric       return nullptr;
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric     Sym = SR->getSymbol();
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   return nullptr;
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric static bool isInMIGCall(CheckerContext &C) {
1520b57cec5SDimitry Andric   const LocationContext *LC = C.getLocationContext();
1530b57cec5SDimitry Andric   assert(LC && "Unknown location context");
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   const StackFrameContext *SFC;
1560b57cec5SDimitry Andric   // Find the top frame.
1570b57cec5SDimitry Andric   while (LC) {
1580b57cec5SDimitry Andric     SFC = LC->getStackFrame();
1590b57cec5SDimitry Andric     LC = SFC->getParent();
1600b57cec5SDimitry Andric   }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   const Decl *D = SFC->getDecl();
1630b57cec5SDimitry Andric 
164bdd1243dSDimitry Andric   if (std::optional<AnyCall> AC = AnyCall::forDecl(D)) {
1650b57cec5SDimitry Andric     // Even though there's a Sema warning when the return type of an annotated
1660b57cec5SDimitry Andric     // function is not a kern_return_t, this warning isn't an error, so we need
1675e801ac6SDimitry Andric     // an extra check here.
1680b57cec5SDimitry Andric     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
1690b57cec5SDimitry Andric     // for now.
1700b57cec5SDimitry Andric     if (!AC->getReturnType(C.getASTContext())
1710b57cec5SDimitry Andric              .getCanonicalType()->isSignedIntegerType())
1720b57cec5SDimitry Andric       return false;
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   if (D->hasAttr<MIGServerRoutineAttr>())
1760b57cec5SDimitry Andric     return true;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   // See if there's an annotated method in the superclass.
1790b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
1800b57cec5SDimitry Andric     for (const auto *OMD: MD->overridden_methods())
1810b57cec5SDimitry Andric       if (OMD->hasAttr<MIGServerRoutineAttr>())
1820b57cec5SDimitry Andric         return true;
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   return false;
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
188349cc55cSDimitry Andric   if (OsRefRetain.matches(Call)) {
1890b57cec5SDimitry Andric     // If the code is doing reference counting over the parameter,
1900b57cec5SDimitry Andric     // it opens up an opportunity for safely calling a destructor function.
1910b57cec5SDimitry Andric     // TODO: We should still check for over-releases.
1920b57cec5SDimitry Andric     if (const ParmVarDecl *PVD =
1930b57cec5SDimitry Andric             getOriginParam(Call.getArgSVal(0), C, /*IncludeBaseRegions=*/true)) {
1940b57cec5SDimitry Andric       // We never need to clean up the program state because these are
1950b57cec5SDimitry Andric       // top-level parameters anyway, so they're always live.
1960b57cec5SDimitry Andric       C.addTransition(C.getState()->add<RefCountedParameters>(PVD));
1970b57cec5SDimitry Andric     }
1980b57cec5SDimitry Andric     return;
1990b57cec5SDimitry Andric   }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   if (!isInMIGCall(C))
2020b57cec5SDimitry Andric     return;
2030b57cec5SDimitry Andric 
204*0fca6ea1SDimitry Andric   const unsigned *ArgIdxPtr = Deallocators.lookup(Call);
205*0fca6ea1SDimitry Andric   if (!ArgIdxPtr)
2060b57cec5SDimitry Andric     return;
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
209*0fca6ea1SDimitry Andric   unsigned ArgIdx = *ArgIdxPtr;
2100b57cec5SDimitry Andric   SVal Arg = Call.getArgSVal(ArgIdx);
2110b57cec5SDimitry Andric   const ParmVarDecl *PVD = getOriginParam(Arg, C);
2120b57cec5SDimitry Andric   if (!PVD || State->contains<RefCountedParameters>(PVD))
2130b57cec5SDimitry Andric     return;
2140b57cec5SDimitry Andric 
2155ffd83dbSDimitry Andric   const NoteTag *T =
2165ffd83dbSDimitry Andric     C.getNoteTag([this, PVD](PathSensitiveBugReport &BR) -> std::string {
2170b57cec5SDimitry Andric         if (&BR.getBugType() != &BT)
2180b57cec5SDimitry Andric           return "";
2190b57cec5SDimitry Andric         SmallString<64> Str;
2200b57cec5SDimitry Andric         llvm::raw_svector_ostream OS(Str);
2210b57cec5SDimitry Andric         OS << "Value passed through parameter '" << PVD->getName()
2220b57cec5SDimitry Andric            << "\' is deallocated";
2235ffd83dbSDimitry Andric         return std::string(OS.str());
2240b57cec5SDimitry Andric       });
2250b57cec5SDimitry Andric   C.addTransition(State->set<ReleasedParameter>(true), T);
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric // Returns true if V can potentially represent a "successful" kern_return_t.
2290b57cec5SDimitry Andric static bool mayBeSuccess(SVal V, CheckerContext &C) {
2300b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   // Can V represent KERN_SUCCESS?
2330b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedFalse())
2340b57cec5SDimitry Andric     return true;
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   SValBuilder &SVB = C.getSValBuilder();
2370b57cec5SDimitry Andric   ASTContext &ACtx = C.getASTContext();
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   // Can V represent MIG_NO_REPLY?
2400b57cec5SDimitry Andric   static const int MigNoReply = -305;
2410b57cec5SDimitry Andric   V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
2420b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedTrue())
2430b57cec5SDimitry Andric     return true;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   // If none of the above, it's definitely an error.
2460b57cec5SDimitry Andric   return false;
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
2500b57cec5SDimitry Andric   // It is very unlikely that a MIG callback will be called from anywhere
2510b57cec5SDimitry Andric   // within the project under analysis and the caller isn't itself a routine
2520b57cec5SDimitry Andric   // that follows the MIG calling convention. Therefore we're safe to believe
2530b57cec5SDimitry Andric   // that it's always the top frame that is of interest. There's a slight chance
2540b57cec5SDimitry Andric   // that the user would want to enforce the MIG calling convention upon
2550b57cec5SDimitry Andric   // a random routine in the middle of nowhere, but given that the convention is
2560b57cec5SDimitry Andric   // fairly weird and hard to follow in the first place, there's relatively
2570b57cec5SDimitry Andric   // little motivation to spread it this way.
2580b57cec5SDimitry Andric   if (!C.inTopFrame())
2590b57cec5SDimitry Andric     return;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   if (!isInMIGCall(C))
2620b57cec5SDimitry Andric     return;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // We know that the function is non-void, but what if the return statement
2650b57cec5SDimitry Andric   // is not there in the code? It's not a compile error, we should not crash.
2660b57cec5SDimitry Andric   if (!RS)
2670b57cec5SDimitry Andric     return;
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2700b57cec5SDimitry Andric   if (!State->get<ReleasedParameter>())
2710b57cec5SDimitry Andric     return;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   SVal V = C.getSVal(RS);
2740b57cec5SDimitry Andric   if (mayBeSuccess(V, C))
2750b57cec5SDimitry Andric     return;
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   ExplodedNode *N = C.generateErrorNode();
2780b57cec5SDimitry Andric   if (!N)
2790b57cec5SDimitry Andric     return;
2800b57cec5SDimitry Andric 
281a7dea167SDimitry Andric   auto R = std::make_unique<PathSensitiveBugReport>(
2820b57cec5SDimitry Andric       BT,
2830b57cec5SDimitry Andric       "MIG callback fails with error after deallocating argument value. "
2840b57cec5SDimitry Andric       "This is a use-after-free vulnerability because the caller will try to "
2850b57cec5SDimitry Andric       "deallocate it again",
2860b57cec5SDimitry Andric       N);
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   R->addRange(RS->getSourceRange());
289fe6060f1SDimitry Andric   bugreporter::trackExpressionValue(
290fe6060f1SDimitry Andric       N, RS->getRetValue(), *R,
291fe6060f1SDimitry Andric       {bugreporter::TrackingKind::Thorough, /*EnableNullFPSuppression=*/false});
2920b57cec5SDimitry Andric   C.emitReport(std::move(R));
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric void ento::registerMIGChecker(CheckerManager &Mgr) {
2960b57cec5SDimitry Andric   Mgr.registerChecker<MIGChecker>();
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric 
2995ffd83dbSDimitry Andric bool ento::shouldRegisterMIGChecker(const CheckerManager &mgr) {
3000b57cec5SDimitry Andric   return true;
3010b57cec5SDimitry Andric }
302