xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.cpp (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1dda28197Spatrick //===-- IRDynamicChecks.cpp -----------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9061da546Spatrick #include "llvm/IR/Constants.h"
10061da546Spatrick #include "llvm/IR/DataLayout.h"
11061da546Spatrick #include "llvm/IR/Function.h"
12061da546Spatrick #include "llvm/IR/Instructions.h"
13061da546Spatrick #include "llvm/IR/Module.h"
14061da546Spatrick #include "llvm/IR/Value.h"
15061da546Spatrick #include "llvm/Support/raw_ostream.h"
16061da546Spatrick 
17061da546Spatrick #include "IRDynamicChecks.h"
18061da546Spatrick 
19061da546Spatrick #include "lldb/Expression/UtilityFunction.h"
20061da546Spatrick #include "lldb/Target/ExecutionContext.h"
21061da546Spatrick #include "lldb/Target/Process.h"
22061da546Spatrick #include "lldb/Target/StackFrame.h"
23061da546Spatrick #include "lldb/Target/Target.h"
24061da546Spatrick #include "lldb/Utility/ConstString.h"
25*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
26061da546Spatrick #include "lldb/Utility/Log.h"
27061da546Spatrick 
28061da546Spatrick #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
29061da546Spatrick 
30061da546Spatrick using namespace llvm;
31061da546Spatrick using namespace lldb_private;
32061da546Spatrick 
33061da546Spatrick static char ID;
34061da546Spatrick 
35061da546Spatrick #define VALID_POINTER_CHECK_NAME "_$__lldb_valid_pointer_check"
36061da546Spatrick #define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"
37061da546Spatrick 
38061da546Spatrick static const char g_valid_pointer_check_text[] =
39061da546Spatrick     "extern \"C\" void\n"
40061da546Spatrick     "_$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
41061da546Spatrick     "{\n"
42061da546Spatrick     "    unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n"
43061da546Spatrick     "}";
44061da546Spatrick 
ClangDynamicCheckerFunctions()45061da546Spatrick ClangDynamicCheckerFunctions::ClangDynamicCheckerFunctions()
46061da546Spatrick     : DynamicCheckerFunctions(DCF_Clang) {}
47061da546Spatrick 
48061da546Spatrick ClangDynamicCheckerFunctions::~ClangDynamicCheckerFunctions() = default;
49061da546Spatrick 
Install(DiagnosticManager & diagnostic_manager,ExecutionContext & exe_ctx)50061da546Spatrick bool ClangDynamicCheckerFunctions::Install(
51061da546Spatrick     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
52be691f3bSpatrick   auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
53be691f3bSpatrick       g_valid_pointer_check_text, VALID_POINTER_CHECK_NAME,
54be691f3bSpatrick       lldb::eLanguageTypeC, exe_ctx);
55be691f3bSpatrick   if (!utility_fn_or_error) {
56be691f3bSpatrick     llvm::consumeError(utility_fn_or_error.takeError());
57061da546Spatrick     return false;
58be691f3bSpatrick   }
59be691f3bSpatrick   m_valid_pointer_check = std::move(*utility_fn_or_error);
60061da546Spatrick 
61be691f3bSpatrick   if (Process *process = exe_ctx.GetProcessPtr()) {
62061da546Spatrick     ObjCLanguageRuntime *objc_language_runtime =
63061da546Spatrick         ObjCLanguageRuntime::Get(*process);
64061da546Spatrick 
65061da546Spatrick     if (objc_language_runtime) {
66be691f3bSpatrick       auto utility_fn_or_error = objc_language_runtime->CreateObjectChecker(
67be691f3bSpatrick           VALID_OBJC_OBJECT_CHECK_NAME, exe_ctx);
68be691f3bSpatrick       if (!utility_fn_or_error) {
69be691f3bSpatrick         llvm::consumeError(utility_fn_or_error.takeError());
70061da546Spatrick         return false;
71061da546Spatrick       }
72be691f3bSpatrick       m_objc_object_check = std::move(*utility_fn_or_error);
73be691f3bSpatrick     }
74061da546Spatrick   }
75061da546Spatrick 
76061da546Spatrick   return true;
77061da546Spatrick }
78061da546Spatrick 
DoCheckersExplainStop(lldb::addr_t addr,Stream & message)79061da546Spatrick bool ClangDynamicCheckerFunctions::DoCheckersExplainStop(lldb::addr_t addr,
80061da546Spatrick                                                          Stream &message) {
81061da546Spatrick   // FIXME: We have to get the checkers to know why they scotched the call in
82061da546Spatrick   // more detail,
83061da546Spatrick   // so we can print a better message here.
84061da546Spatrick   if (m_valid_pointer_check && m_valid_pointer_check->ContainsAddress(addr)) {
85061da546Spatrick     message.Printf("Attempted to dereference an invalid pointer.");
86061da546Spatrick     return true;
87061da546Spatrick   } else if (m_objc_object_check &&
88061da546Spatrick              m_objc_object_check->ContainsAddress(addr)) {
89061da546Spatrick     message.Printf("Attempted to dereference an invalid ObjC Object or send it "
90061da546Spatrick                    "an unrecognized selector");
91061da546Spatrick     return true;
92061da546Spatrick   }
93061da546Spatrick   return false;
94061da546Spatrick }
95061da546Spatrick 
PrintValue(llvm::Value * V,bool truncate=false)96061da546Spatrick static std::string PrintValue(llvm::Value *V, bool truncate = false) {
97061da546Spatrick   std::string s;
98061da546Spatrick   raw_string_ostream rso(s);
99061da546Spatrick   V->print(rso);
100061da546Spatrick   rso.flush();
101061da546Spatrick   if (truncate)
102061da546Spatrick     s.resize(s.length() - 1);
103061da546Spatrick   return s;
104061da546Spatrick }
105061da546Spatrick 
106061da546Spatrick /// \class Instrumenter IRDynamicChecks.cpp
107061da546Spatrick /// Finds and instruments individual LLVM IR instructions
108061da546Spatrick ///
109061da546Spatrick /// When instrumenting LLVM IR, it is frequently desirable to first search for
110061da546Spatrick /// instructions, and then later modify them.  This way iterators remain
111061da546Spatrick /// intact, and multiple passes can look at the same code base without
112061da546Spatrick /// treading on each other's toes.
113061da546Spatrick ///
114061da546Spatrick /// The Instrumenter class implements this functionality.  A client first
115061da546Spatrick /// calls Inspect on a function, which populates a list of instructions to be
116061da546Spatrick /// instrumented.  Then, later, when all passes' Inspect functions have been
117061da546Spatrick /// called, the client calls Instrument, which adds the desired
118061da546Spatrick /// instrumentation.
119061da546Spatrick ///
120061da546Spatrick /// A subclass of Instrumenter must override InstrumentInstruction, which
121061da546Spatrick /// is responsible for adding whatever instrumentation is necessary.
122061da546Spatrick ///
123061da546Spatrick /// A subclass of Instrumenter may override:
124061da546Spatrick ///
125061da546Spatrick /// - InspectInstruction [default: does nothing]
126061da546Spatrick ///
127061da546Spatrick /// - InspectBasicBlock [default: iterates through the instructions in a
128061da546Spatrick ///   basic block calling InspectInstruction]
129061da546Spatrick ///
130061da546Spatrick /// - InspectFunction [default: iterates through the basic blocks in a
131061da546Spatrick ///   function calling InspectBasicBlock]
132061da546Spatrick class Instrumenter {
133061da546Spatrick public:
134061da546Spatrick   /// Constructor
135061da546Spatrick   ///
136061da546Spatrick   /// \param[in] module
137061da546Spatrick   ///     The module being instrumented.
Instrumenter(llvm::Module & module,std::shared_ptr<UtilityFunction> checker_function)138061da546Spatrick   Instrumenter(llvm::Module &module,
139061da546Spatrick                std::shared_ptr<UtilityFunction> checker_function)
140*f6aab3d8Srobert       : m_module(module), m_checker_function(checker_function) {}
141061da546Spatrick 
142061da546Spatrick   virtual ~Instrumenter() = default;
143061da546Spatrick 
144061da546Spatrick   /// Inspect a function to find instructions to instrument
145061da546Spatrick   ///
146061da546Spatrick   /// \param[in] function
147061da546Spatrick   ///     The function to inspect.
148061da546Spatrick   ///
149061da546Spatrick   /// \return
150061da546Spatrick   ///     True on success; false on error.
Inspect(llvm::Function & function)151061da546Spatrick   bool Inspect(llvm::Function &function) { return InspectFunction(function); }
152061da546Spatrick 
153061da546Spatrick   /// Instrument all the instructions found by Inspect()
154061da546Spatrick   ///
155061da546Spatrick   /// \return
156061da546Spatrick   ///     True on success; false on error.
Instrument()157061da546Spatrick   bool Instrument() {
158061da546Spatrick     for (InstIterator ii = m_to_instrument.begin(),
159061da546Spatrick                       last_ii = m_to_instrument.end();
160061da546Spatrick          ii != last_ii; ++ii) {
161061da546Spatrick       if (!InstrumentInstruction(*ii))
162061da546Spatrick         return false;
163061da546Spatrick     }
164061da546Spatrick 
165061da546Spatrick     return true;
166061da546Spatrick   }
167061da546Spatrick 
168061da546Spatrick protected:
169061da546Spatrick   /// Add instrumentation to a single instruction
170061da546Spatrick   ///
171061da546Spatrick   /// \param[in] inst
172061da546Spatrick   ///     The instruction to be instrumented.
173061da546Spatrick   ///
174061da546Spatrick   /// \return
175061da546Spatrick   ///     True on success; false otherwise.
176061da546Spatrick   virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
177061da546Spatrick 
178061da546Spatrick   /// Register a single instruction to be instrumented
179061da546Spatrick   ///
180061da546Spatrick   /// \param[in] inst
181061da546Spatrick   ///     The instruction to be instrumented.
RegisterInstruction(llvm::Instruction & inst)182dda28197Spatrick   void RegisterInstruction(llvm::Instruction &inst) {
183dda28197Spatrick     m_to_instrument.push_back(&inst);
184061da546Spatrick   }
185061da546Spatrick 
186061da546Spatrick   /// Determine whether a single instruction is interesting to instrument,
187061da546Spatrick   /// and, if so, call RegisterInstruction
188061da546Spatrick   ///
189061da546Spatrick   /// \param[in] i
190061da546Spatrick   ///     The instruction to be inspected.
191061da546Spatrick   ///
192061da546Spatrick   /// \return
193061da546Spatrick   ///     False if there was an error scanning; true otherwise.
InspectInstruction(llvm::Instruction & i)194061da546Spatrick   virtual bool InspectInstruction(llvm::Instruction &i) { return true; }
195061da546Spatrick 
196061da546Spatrick   /// Scan a basic block to see if any instructions are interesting
197061da546Spatrick   ///
198061da546Spatrick   /// \param[in] bb
199061da546Spatrick   ///     The basic block to be inspected.
200061da546Spatrick   ///
201061da546Spatrick   /// \return
202061da546Spatrick   ///     False if there was an error scanning; true otherwise.
InspectBasicBlock(llvm::BasicBlock & bb)203061da546Spatrick   virtual bool InspectBasicBlock(llvm::BasicBlock &bb) {
204061da546Spatrick     for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end();
205061da546Spatrick          ii != last_ii; ++ii) {
206061da546Spatrick       if (!InspectInstruction(*ii))
207061da546Spatrick         return false;
208061da546Spatrick     }
209061da546Spatrick 
210061da546Spatrick     return true;
211061da546Spatrick   }
212061da546Spatrick 
213061da546Spatrick   /// Scan a function to see if any instructions are interesting
214061da546Spatrick   ///
215061da546Spatrick   /// \param[in] f
216061da546Spatrick   ///     The function to be inspected.
217061da546Spatrick   ///
218061da546Spatrick   /// \return
219061da546Spatrick   ///     False if there was an error scanning; true otherwise.
InspectFunction(llvm::Function & f)220061da546Spatrick   virtual bool InspectFunction(llvm::Function &f) {
221061da546Spatrick     for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end();
222061da546Spatrick          bbi != last_bbi; ++bbi) {
223061da546Spatrick       if (!InspectBasicBlock(*bbi))
224061da546Spatrick         return false;
225061da546Spatrick     }
226061da546Spatrick 
227061da546Spatrick     return true;
228061da546Spatrick   }
229061da546Spatrick 
230061da546Spatrick   /// Build a function pointer for a function with signature void
231061da546Spatrick   /// (*)(uint8_t*) with a given address
232061da546Spatrick   ///
233061da546Spatrick   /// \param[in] start_address
234061da546Spatrick   ///     The address of the function.
235061da546Spatrick   ///
236061da546Spatrick   /// \return
237061da546Spatrick   ///     The function pointer, for use in a CallInst.
BuildPointerValidatorFunc(lldb::addr_t start_address)238061da546Spatrick   llvm::FunctionCallee BuildPointerValidatorFunc(lldb::addr_t start_address) {
239061da546Spatrick     llvm::Type *param_array[1];
240061da546Spatrick 
241061da546Spatrick     param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy());
242061da546Spatrick 
243061da546Spatrick     ArrayRef<llvm::Type *> params(param_array, 1);
244061da546Spatrick 
245061da546Spatrick     FunctionType *fun_ty = FunctionType::get(
246061da546Spatrick         llvm::Type::getVoidTy(m_module.getContext()), params, true);
247061da546Spatrick     PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
248061da546Spatrick     Constant *fun_addr_int =
249061da546Spatrick         ConstantInt::get(GetIntptrTy(), start_address, false);
250061da546Spatrick     return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)};
251061da546Spatrick   }
252061da546Spatrick 
253061da546Spatrick   /// Build a function pointer for a function with signature void
254061da546Spatrick   /// (*)(uint8_t*, uint8_t*) with a given address
255061da546Spatrick   ///
256061da546Spatrick   /// \param[in] start_address
257061da546Spatrick   ///     The address of the function.
258061da546Spatrick   ///
259061da546Spatrick   /// \return
260061da546Spatrick   ///     The function pointer, for use in a CallInst.
BuildObjectCheckerFunc(lldb::addr_t start_address)261061da546Spatrick   llvm::FunctionCallee BuildObjectCheckerFunc(lldb::addr_t start_address) {
262061da546Spatrick     llvm::Type *param_array[2];
263061da546Spatrick 
264061da546Spatrick     param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy());
265061da546Spatrick     param_array[1] = const_cast<llvm::PointerType *>(GetI8PtrTy());
266061da546Spatrick 
267061da546Spatrick     ArrayRef<llvm::Type *> params(param_array, 2);
268061da546Spatrick 
269061da546Spatrick     FunctionType *fun_ty = FunctionType::get(
270061da546Spatrick         llvm::Type::getVoidTy(m_module.getContext()), params, true);
271061da546Spatrick     PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
272061da546Spatrick     Constant *fun_addr_int =
273061da546Spatrick         ConstantInt::get(GetIntptrTy(), start_address, false);
274061da546Spatrick     return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)};
275061da546Spatrick   }
276061da546Spatrick 
GetI8PtrTy()277061da546Spatrick   PointerType *GetI8PtrTy() {
278061da546Spatrick     if (!m_i8ptr_ty)
279061da546Spatrick       m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
280061da546Spatrick 
281061da546Spatrick     return m_i8ptr_ty;
282061da546Spatrick   }
283061da546Spatrick 
GetIntptrTy()284061da546Spatrick   IntegerType *GetIntptrTy() {
285061da546Spatrick     if (!m_intptr_ty) {
286061da546Spatrick       llvm::DataLayout data_layout(&m_module);
287061da546Spatrick 
288061da546Spatrick       m_intptr_ty = llvm::Type::getIntNTy(m_module.getContext(),
289061da546Spatrick                                           data_layout.getPointerSizeInBits());
290061da546Spatrick     }
291061da546Spatrick 
292061da546Spatrick     return m_intptr_ty;
293061da546Spatrick   }
294061da546Spatrick 
295061da546Spatrick   typedef std::vector<llvm::Instruction *> InstVector;
296061da546Spatrick   typedef InstVector::iterator InstIterator;
297061da546Spatrick 
298061da546Spatrick   InstVector m_to_instrument; ///< List of instructions the inspector found
299061da546Spatrick   llvm::Module &m_module;     ///< The module which is being instrumented
300061da546Spatrick   std::shared_ptr<UtilityFunction>
301061da546Spatrick       m_checker_function; ///< The dynamic checker function for the process
302061da546Spatrick 
303061da546Spatrick private:
304*f6aab3d8Srobert   PointerType *m_i8ptr_ty = nullptr;
305*f6aab3d8Srobert   IntegerType *m_intptr_ty = nullptr;
306061da546Spatrick };
307061da546Spatrick 
308061da546Spatrick class ValidPointerChecker : public Instrumenter {
309061da546Spatrick public:
ValidPointerChecker(llvm::Module & module,std::shared_ptr<UtilityFunction> checker_function)310061da546Spatrick   ValidPointerChecker(llvm::Module &module,
311061da546Spatrick                       std::shared_ptr<UtilityFunction> checker_function)
312061da546Spatrick       : Instrumenter(module, checker_function),
313061da546Spatrick         m_valid_pointer_check_func(nullptr) {}
314061da546Spatrick 
315061da546Spatrick   ~ValidPointerChecker() override = default;
316061da546Spatrick 
317061da546Spatrick protected:
InstrumentInstruction(llvm::Instruction * inst)318061da546Spatrick   bool InstrumentInstruction(llvm::Instruction *inst) override {
319*f6aab3d8Srobert     Log *log = GetLog(LLDBLog::Expressions);
320061da546Spatrick 
321061da546Spatrick     LLDB_LOGF(log, "Instrumenting load/store instruction: %s\n",
322061da546Spatrick               PrintValue(inst).c_str());
323061da546Spatrick 
324061da546Spatrick     if (!m_valid_pointer_check_func)
325061da546Spatrick       m_valid_pointer_check_func =
326061da546Spatrick           BuildPointerValidatorFunc(m_checker_function->StartAddress());
327061da546Spatrick 
328061da546Spatrick     llvm::Value *dereferenced_ptr = nullptr;
329061da546Spatrick 
330061da546Spatrick     if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst>(inst))
331061da546Spatrick       dereferenced_ptr = li->getPointerOperand();
332061da546Spatrick     else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst>(inst))
333061da546Spatrick       dereferenced_ptr = si->getPointerOperand();
334061da546Spatrick     else
335061da546Spatrick       return false;
336061da546Spatrick 
337061da546Spatrick     // Insert an instruction to cast the loaded value to int8_t*
338061da546Spatrick 
339061da546Spatrick     BitCastInst *bit_cast =
340061da546Spatrick         new BitCastInst(dereferenced_ptr, GetI8PtrTy(), "", inst);
341061da546Spatrick 
342061da546Spatrick     // Insert an instruction to call the helper with the result
343061da546Spatrick 
344061da546Spatrick     llvm::Value *arg_array[1];
345061da546Spatrick 
346061da546Spatrick     arg_array[0] = bit_cast;
347061da546Spatrick 
348061da546Spatrick     llvm::ArrayRef<llvm::Value *> args(arg_array, 1);
349061da546Spatrick 
350061da546Spatrick     CallInst::Create(m_valid_pointer_check_func, args, "", inst);
351061da546Spatrick 
352061da546Spatrick     return true;
353061da546Spatrick   }
354061da546Spatrick 
InspectInstruction(llvm::Instruction & i)355061da546Spatrick   bool InspectInstruction(llvm::Instruction &i) override {
356*f6aab3d8Srobert     if (isa<llvm::LoadInst>(&i) || isa<llvm::StoreInst>(&i))
357061da546Spatrick       RegisterInstruction(i);
358061da546Spatrick 
359061da546Spatrick     return true;
360061da546Spatrick   }
361061da546Spatrick 
362061da546Spatrick private:
363061da546Spatrick   llvm::FunctionCallee m_valid_pointer_check_func;
364061da546Spatrick };
365061da546Spatrick 
366061da546Spatrick class ObjcObjectChecker : public Instrumenter {
367061da546Spatrick public:
ObjcObjectChecker(llvm::Module & module,std::shared_ptr<UtilityFunction> checker_function)368061da546Spatrick   ObjcObjectChecker(llvm::Module &module,
369061da546Spatrick                     std::shared_ptr<UtilityFunction> checker_function)
370061da546Spatrick       : Instrumenter(module, checker_function),
371061da546Spatrick         m_objc_object_check_func(nullptr) {}
372061da546Spatrick 
373061da546Spatrick   ~ObjcObjectChecker() override = default;
374061da546Spatrick 
375061da546Spatrick   enum msgSend_type {
376061da546Spatrick     eMsgSend = 0,
377061da546Spatrick     eMsgSendSuper,
378061da546Spatrick     eMsgSendSuper_stret,
379061da546Spatrick     eMsgSend_fpret,
380061da546Spatrick     eMsgSend_stret
381061da546Spatrick   };
382061da546Spatrick 
383061da546Spatrick   std::map<llvm::Instruction *, msgSend_type> msgSend_types;
384061da546Spatrick 
385061da546Spatrick protected:
InstrumentInstruction(llvm::Instruction * inst)386061da546Spatrick   bool InstrumentInstruction(llvm::Instruction *inst) override {
387061da546Spatrick     CallInst *call_inst = dyn_cast<CallInst>(inst);
388061da546Spatrick 
389061da546Spatrick     if (!call_inst)
390061da546Spatrick       return false; // call_inst really shouldn't be nullptr, because otherwise
391061da546Spatrick                     // InspectInstruction wouldn't have registered it
392061da546Spatrick 
393061da546Spatrick     if (!m_objc_object_check_func)
394061da546Spatrick       m_objc_object_check_func =
395061da546Spatrick           BuildObjectCheckerFunc(m_checker_function->StartAddress());
396061da546Spatrick 
397061da546Spatrick     // id objc_msgSend(id theReceiver, SEL theSelector, ...)
398061da546Spatrick 
399061da546Spatrick     llvm::Value *target_object;
400061da546Spatrick     llvm::Value *selector;
401061da546Spatrick 
402061da546Spatrick     switch (msgSend_types[inst]) {
403061da546Spatrick     case eMsgSend:
404061da546Spatrick     case eMsgSend_fpret:
405061da546Spatrick       // On arm64, clang uses objc_msgSend for scalar and struct return
406061da546Spatrick       // calls.  The call instruction will record which was used.
407061da546Spatrick       if (call_inst->hasStructRetAttr()) {
408061da546Spatrick         target_object = call_inst->getArgOperand(1);
409061da546Spatrick         selector = call_inst->getArgOperand(2);
410061da546Spatrick       } else {
411061da546Spatrick         target_object = call_inst->getArgOperand(0);
412061da546Spatrick         selector = call_inst->getArgOperand(1);
413061da546Spatrick       }
414061da546Spatrick       break;
415061da546Spatrick     case eMsgSend_stret:
416061da546Spatrick       target_object = call_inst->getArgOperand(1);
417061da546Spatrick       selector = call_inst->getArgOperand(2);
418061da546Spatrick       break;
419061da546Spatrick     case eMsgSendSuper:
420061da546Spatrick     case eMsgSendSuper_stret:
421061da546Spatrick       return true;
422061da546Spatrick     }
423061da546Spatrick 
424061da546Spatrick     // These objects should always be valid according to Sean Calannan
425061da546Spatrick     assert(target_object);
426061da546Spatrick     assert(selector);
427061da546Spatrick 
428061da546Spatrick     // Insert an instruction to cast the receiver id to int8_t*
429061da546Spatrick 
430061da546Spatrick     BitCastInst *bit_cast =
431061da546Spatrick         new BitCastInst(target_object, GetI8PtrTy(), "", inst);
432061da546Spatrick 
433061da546Spatrick     // Insert an instruction to call the helper with the result
434061da546Spatrick 
435061da546Spatrick     llvm::Value *arg_array[2];
436061da546Spatrick 
437061da546Spatrick     arg_array[0] = bit_cast;
438061da546Spatrick     arg_array[1] = selector;
439061da546Spatrick 
440061da546Spatrick     ArrayRef<llvm::Value *> args(arg_array, 2);
441061da546Spatrick 
442061da546Spatrick     CallInst::Create(m_objc_object_check_func, args, "", inst);
443061da546Spatrick 
444061da546Spatrick     return true;
445061da546Spatrick   }
446061da546Spatrick 
GetFunction(llvm::Value * value)447061da546Spatrick   static llvm::Function *GetFunction(llvm::Value *value) {
448061da546Spatrick     if (llvm::Function *function = llvm::dyn_cast<llvm::Function>(value)) {
449061da546Spatrick       return function;
450061da546Spatrick     }
451061da546Spatrick 
452061da546Spatrick     if (llvm::ConstantExpr *const_expr =
453061da546Spatrick             llvm::dyn_cast<llvm::ConstantExpr>(value)) {
454061da546Spatrick       switch (const_expr->getOpcode()) {
455061da546Spatrick       default:
456061da546Spatrick         return nullptr;
457061da546Spatrick       case llvm::Instruction::BitCast:
458061da546Spatrick         return GetFunction(const_expr->getOperand(0));
459061da546Spatrick       }
460061da546Spatrick     }
461061da546Spatrick 
462061da546Spatrick     return nullptr;
463061da546Spatrick   }
464061da546Spatrick 
GetCalledFunction(llvm::CallInst * inst)465061da546Spatrick   static llvm::Function *GetCalledFunction(llvm::CallInst *inst) {
466dda28197Spatrick     return GetFunction(inst->getCalledOperand());
467061da546Spatrick   }
468061da546Spatrick 
InspectInstruction(llvm::Instruction & i)469061da546Spatrick   bool InspectInstruction(llvm::Instruction &i) override {
470*f6aab3d8Srobert     Log *log = GetLog(LLDBLog::Expressions);
471061da546Spatrick 
472061da546Spatrick     CallInst *call_inst = dyn_cast<CallInst>(&i);
473061da546Spatrick 
474061da546Spatrick     if (call_inst) {
475061da546Spatrick       const llvm::Function *called_function = GetCalledFunction(call_inst);
476061da546Spatrick 
477061da546Spatrick       if (!called_function)
478061da546Spatrick         return true;
479061da546Spatrick 
480061da546Spatrick       std::string name_str = called_function->getName().str();
481061da546Spatrick       const char *name_cstr = name_str.c_str();
482061da546Spatrick 
483061da546Spatrick       LLDB_LOGF(log, "Found call to %s: %s\n", name_cstr,
484061da546Spatrick                 PrintValue(call_inst).c_str());
485061da546Spatrick 
486061da546Spatrick       if (name_str.find("objc_msgSend") == std::string::npos)
487061da546Spatrick         return true;
488061da546Spatrick 
489061da546Spatrick       if (!strcmp(name_cstr, "objc_msgSend")) {
490061da546Spatrick         RegisterInstruction(i);
491061da546Spatrick         msgSend_types[&i] = eMsgSend;
492061da546Spatrick         return true;
493061da546Spatrick       }
494061da546Spatrick 
495061da546Spatrick       if (!strcmp(name_cstr, "objc_msgSend_stret")) {
496061da546Spatrick         RegisterInstruction(i);
497061da546Spatrick         msgSend_types[&i] = eMsgSend_stret;
498061da546Spatrick         return true;
499061da546Spatrick       }
500061da546Spatrick 
501061da546Spatrick       if (!strcmp(name_cstr, "objc_msgSend_fpret")) {
502061da546Spatrick         RegisterInstruction(i);
503061da546Spatrick         msgSend_types[&i] = eMsgSend_fpret;
504061da546Spatrick         return true;
505061da546Spatrick       }
506061da546Spatrick 
507061da546Spatrick       if (!strcmp(name_cstr, "objc_msgSendSuper")) {
508061da546Spatrick         RegisterInstruction(i);
509061da546Spatrick         msgSend_types[&i] = eMsgSendSuper;
510061da546Spatrick         return true;
511061da546Spatrick       }
512061da546Spatrick 
513061da546Spatrick       if (!strcmp(name_cstr, "objc_msgSendSuper_stret")) {
514061da546Spatrick         RegisterInstruction(i);
515061da546Spatrick         msgSend_types[&i] = eMsgSendSuper_stret;
516061da546Spatrick         return true;
517061da546Spatrick       }
518061da546Spatrick 
519061da546Spatrick       LLDB_LOGF(log,
520061da546Spatrick                 "Function name '%s' contains 'objc_msgSend' but is not handled",
521061da546Spatrick                 name_str.c_str());
522061da546Spatrick 
523061da546Spatrick       return true;
524061da546Spatrick     }
525061da546Spatrick 
526061da546Spatrick     return true;
527061da546Spatrick   }
528061da546Spatrick 
529061da546Spatrick private:
530061da546Spatrick   llvm::FunctionCallee m_objc_object_check_func;
531061da546Spatrick };
532061da546Spatrick 
IRDynamicChecks(ClangDynamicCheckerFunctions & checker_functions,const char * func_name)533061da546Spatrick IRDynamicChecks::IRDynamicChecks(
534061da546Spatrick     ClangDynamicCheckerFunctions &checker_functions, const char *func_name)
535061da546Spatrick     : ModulePass(ID), m_func_name(func_name),
536061da546Spatrick       m_checker_functions(checker_functions) {}
537061da546Spatrick 
538061da546Spatrick IRDynamicChecks::~IRDynamicChecks() = default;
539061da546Spatrick 
runOnModule(llvm::Module & M)540061da546Spatrick bool IRDynamicChecks::runOnModule(llvm::Module &M) {
541*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Expressions);
542061da546Spatrick 
543061da546Spatrick   llvm::Function *function = M.getFunction(StringRef(m_func_name));
544061da546Spatrick 
545061da546Spatrick   if (!function) {
546061da546Spatrick     LLDB_LOGF(log, "Couldn't find %s() in the module", m_func_name.c_str());
547061da546Spatrick 
548061da546Spatrick     return false;
549061da546Spatrick   }
550061da546Spatrick 
551061da546Spatrick   if (m_checker_functions.m_valid_pointer_check) {
552061da546Spatrick     ValidPointerChecker vpc(M, m_checker_functions.m_valid_pointer_check);
553061da546Spatrick 
554061da546Spatrick     if (!vpc.Inspect(*function))
555061da546Spatrick       return false;
556061da546Spatrick 
557061da546Spatrick     if (!vpc.Instrument())
558061da546Spatrick       return false;
559061da546Spatrick   }
560061da546Spatrick 
561061da546Spatrick   if (m_checker_functions.m_objc_object_check) {
562061da546Spatrick     ObjcObjectChecker ooc(M, m_checker_functions.m_objc_object_check);
563061da546Spatrick 
564061da546Spatrick     if (!ooc.Inspect(*function))
565061da546Spatrick       return false;
566061da546Spatrick 
567061da546Spatrick     if (!ooc.Instrument())
568061da546Spatrick       return false;
569061da546Spatrick   }
570061da546Spatrick 
571061da546Spatrick   if (log && log->GetVerbose()) {
572061da546Spatrick     std::string s;
573061da546Spatrick     raw_string_ostream oss(s);
574061da546Spatrick 
575061da546Spatrick     M.print(oss, nullptr);
576061da546Spatrick 
577061da546Spatrick     oss.flush();
578061da546Spatrick 
579061da546Spatrick     LLDB_LOGF(log, "Module after dynamic checks: \n%s", s.c_str());
580061da546Spatrick   }
581061da546Spatrick 
582061da546Spatrick   return true;
583061da546Spatrick }
584061da546Spatrick 
assignPassManager(PMStack & PMS,PassManagerType T)585061da546Spatrick void IRDynamicChecks::assignPassManager(PMStack &PMS, PassManagerType T) {}
586061da546Spatrick 
getPotentialPassManagerType() const587061da546Spatrick PassManagerType IRDynamicChecks::getPotentialPassManagerType() const {
588061da546Spatrick   return PMT_ModulePassManager;
589061da546Spatrick }
590