1 //===-- IRDynamicChecks.cpp -------------------------------------*- 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 #include "llvm/IR/Constants.h"
10 #include "llvm/IR/DataLayout.h"
11 #include "llvm/IR/Function.h"
12 #include "llvm/IR/Instructions.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Value.h"
15 #include "llvm/Support/raw_ostream.h"
16 
17 #include "IRDynamicChecks.h"
18 
19 #include "lldb/Expression/UtilityFunction.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/ObjCLanguageRuntime.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/StackFrame.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/ConstString.h"
26 #include "lldb/Utility/Log.h"
27 
28 using namespace llvm;
29 using namespace lldb_private;
30 
31 static char ID;
32 
33 #define VALID_POINTER_CHECK_NAME "_$__lldb_valid_pointer_check"
34 #define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"
35 
36 static const char g_valid_pointer_check_text[] =
37     "extern \"C\" void\n"
38     "_$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
39     "{\n"
40     "    unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n"
41     "}";
42 
43 ClangDynamicCheckerFunctions::ClangDynamicCheckerFunctions()
44     : DynamicCheckerFunctions(DCF_Clang) {}
45 
46 ClangDynamicCheckerFunctions::~ClangDynamicCheckerFunctions() = default;
47 
48 bool ClangDynamicCheckerFunctions::Install(
49     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
50   Status error;
51   m_valid_pointer_check.reset(
52       exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
53           g_valid_pointer_check_text, lldb::eLanguageTypeC,
54           VALID_POINTER_CHECK_NAME, error));
55   if (error.Fail())
56     return false;
57 
58   if (!m_valid_pointer_check->Install(diagnostic_manager, exe_ctx))
59     return false;
60 
61   Process *process = exe_ctx.GetProcessPtr();
62 
63   if (process) {
64     ObjCLanguageRuntime *objc_language_runtime =
65         ObjCLanguageRuntime::Get(*process);
66 
67     if (objc_language_runtime) {
68       m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker(
69           VALID_OBJC_OBJECT_CHECK_NAME));
70 
71       if (!m_objc_object_check->Install(diagnostic_manager, exe_ctx))
72         return false;
73     }
74   }
75 
76   return true;
77 }
78 
79 bool ClangDynamicCheckerFunctions::DoCheckersExplainStop(lldb::addr_t addr,
80                                                          Stream &message) {
81   // FIXME: We have to get the checkers to know why they scotched the call in
82   // more detail,
83   // so we can print a better message here.
84   if (m_valid_pointer_check && m_valid_pointer_check->ContainsAddress(addr)) {
85     message.Printf("Attempted to dereference an invalid pointer.");
86     return true;
87   } else if (m_objc_object_check &&
88              m_objc_object_check->ContainsAddress(addr)) {
89     message.Printf("Attempted to dereference an invalid ObjC Object or send it "
90                    "an unrecognized selector");
91     return true;
92   }
93   return false;
94 }
95 
96 static std::string PrintValue(llvm::Value *V, bool truncate = false) {
97   std::string s;
98   raw_string_ostream rso(s);
99   V->print(rso);
100   rso.flush();
101   if (truncate)
102     s.resize(s.length() - 1);
103   return s;
104 }
105 
106 /// \class Instrumenter IRDynamicChecks.cpp
107 /// Finds and instruments individual LLVM IR instructions
108 ///
109 /// When instrumenting LLVM IR, it is frequently desirable to first search for
110 /// instructions, and then later modify them.  This way iterators remain
111 /// intact, and multiple passes can look at the same code base without
112 /// treading on each other's toes.
113 ///
114 /// The Instrumenter class implements this functionality.  A client first
115 /// calls Inspect on a function, which populates a list of instructions to be
116 /// instrumented.  Then, later, when all passes' Inspect functions have been
117 /// called, the client calls Instrument, which adds the desired
118 /// instrumentation.
119 ///
120 /// A subclass of Instrumenter must override InstrumentInstruction, which
121 /// is responsible for adding whatever instrumentation is necessary.
122 ///
123 /// A subclass of Instrumenter may override:
124 ///
125 /// - InspectInstruction [default: does nothing]
126 ///
127 /// - InspectBasicBlock [default: iterates through the instructions in a
128 ///   basic block calling InspectInstruction]
129 ///
130 /// - InspectFunction [default: iterates through the basic blocks in a
131 ///   function calling InspectBasicBlock]
132 class Instrumenter {
133 public:
134   /// Constructor
135   ///
136   /// \param[in] module
137   ///     The module being instrumented.
138   Instrumenter(llvm::Module &module,
139                std::shared_ptr<UtilityFunction> checker_function)
140       : m_module(module), m_checker_function(checker_function),
141         m_i8ptr_ty(nullptr), m_intptr_ty(nullptr) {}
142 
143   virtual ~Instrumenter() = default;
144 
145   /// Inspect a function to find instructions to instrument
146   ///
147   /// \param[in] function
148   ///     The function to inspect.
149   ///
150   /// \return
151   ///     True on success; false on error.
152   bool Inspect(llvm::Function &function) { return InspectFunction(function); }
153 
154   /// Instrument all the instructions found by Inspect()
155   ///
156   /// \return
157   ///     True on success; false on error.
158   bool Instrument() {
159     for (InstIterator ii = m_to_instrument.begin(),
160                       last_ii = m_to_instrument.end();
161          ii != last_ii; ++ii) {
162       if (!InstrumentInstruction(*ii))
163         return false;
164     }
165 
166     return true;
167   }
168 
169 protected:
170   /// Add instrumentation to a single instruction
171   ///
172   /// \param[in] inst
173   ///     The instruction to be instrumented.
174   ///
175   /// \return
176   ///     True on success; false otherwise.
177   virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
178 
179   /// Register a single instruction to be instrumented
180   ///
181   /// \param[in] inst
182   ///     The instruction to be instrumented.
183   void RegisterInstruction(llvm::Instruction &i) {
184     m_to_instrument.push_back(&i);
185   }
186 
187   /// Determine whether a single instruction is interesting to instrument,
188   /// and, if so, call RegisterInstruction
189   ///
190   /// \param[in] i
191   ///     The instruction to be inspected.
192   ///
193   /// \return
194   ///     False if there was an error scanning; true otherwise.
195   virtual bool InspectInstruction(llvm::Instruction &i) { return true; }
196 
197   /// Scan a basic block to see if any instructions are interesting
198   ///
199   /// \param[in] bb
200   ///     The basic block to be inspected.
201   ///
202   /// \return
203   ///     False if there was an error scanning; true otherwise.
204   virtual bool InspectBasicBlock(llvm::BasicBlock &bb) {
205     for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end();
206          ii != last_ii; ++ii) {
207       if (!InspectInstruction(*ii))
208         return false;
209     }
210 
211     return true;
212   }
213 
214   /// Scan a function to see if any instructions are interesting
215   ///
216   /// \param[in] f
217   ///     The function to be inspected.
218   ///
219   /// \return
220   ///     False if there was an error scanning; true otherwise.
221   virtual bool InspectFunction(llvm::Function &f) {
222     for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end();
223          bbi != last_bbi; ++bbi) {
224       if (!InspectBasicBlock(*bbi))
225         return false;
226     }
227 
228     return true;
229   }
230 
231   /// Build a function pointer for a function with signature void
232   /// (*)(uint8_t*) with a given address
233   ///
234   /// \param[in] start_address
235   ///     The address of the function.
236   ///
237   /// \return
238   ///     The function pointer, for use in a CallInst.
239   llvm::FunctionCallee BuildPointerValidatorFunc(lldb::addr_t start_address) {
240     llvm::Type *param_array[1];
241 
242     param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy());
243 
244     ArrayRef<llvm::Type *> params(param_array, 1);
245 
246     FunctionType *fun_ty = FunctionType::get(
247         llvm::Type::getVoidTy(m_module.getContext()), params, true);
248     PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
249     Constant *fun_addr_int =
250         ConstantInt::get(GetIntptrTy(), start_address, false);
251     return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)};
252   }
253 
254   /// Build a function pointer for a function with signature void
255   /// (*)(uint8_t*, uint8_t*) with a given address
256   ///
257   /// \param[in] start_address
258   ///     The address of the function.
259   ///
260   /// \return
261   ///     The function pointer, for use in a CallInst.
262   llvm::FunctionCallee BuildObjectCheckerFunc(lldb::addr_t start_address) {
263     llvm::Type *param_array[2];
264 
265     param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy());
266     param_array[1] = const_cast<llvm::PointerType *>(GetI8PtrTy());
267 
268     ArrayRef<llvm::Type *> params(param_array, 2);
269 
270     FunctionType *fun_ty = FunctionType::get(
271         llvm::Type::getVoidTy(m_module.getContext()), params, true);
272     PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
273     Constant *fun_addr_int =
274         ConstantInt::get(GetIntptrTy(), start_address, false);
275     return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)};
276   }
277 
278   PointerType *GetI8PtrTy() {
279     if (!m_i8ptr_ty)
280       m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
281 
282     return m_i8ptr_ty;
283   }
284 
285   IntegerType *GetIntptrTy() {
286     if (!m_intptr_ty) {
287       llvm::DataLayout data_layout(&m_module);
288 
289       m_intptr_ty = llvm::Type::getIntNTy(m_module.getContext(),
290                                           data_layout.getPointerSizeInBits());
291     }
292 
293     return m_intptr_ty;
294   }
295 
296   typedef std::vector<llvm::Instruction *> InstVector;
297   typedef InstVector::iterator InstIterator;
298 
299   InstVector m_to_instrument; ///< List of instructions the inspector found
300   llvm::Module &m_module;     ///< The module which is being instrumented
301   std::shared_ptr<UtilityFunction>
302       m_checker_function; ///< The dynamic checker function for the process
303 
304 private:
305   PointerType *m_i8ptr_ty;
306   IntegerType *m_intptr_ty;
307 };
308 
309 class ValidPointerChecker : public Instrumenter {
310 public:
311   ValidPointerChecker(llvm::Module &module,
312                       std::shared_ptr<UtilityFunction> checker_function)
313       : Instrumenter(module, checker_function),
314         m_valid_pointer_check_func(nullptr) {}
315 
316   ~ValidPointerChecker() override = default;
317 
318 protected:
319   bool InstrumentInstruction(llvm::Instruction *inst) override {
320     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
321 
322     if (log)
323       log->Printf("Instrumenting load/store instruction: %s\n",
324                   PrintValue(inst).c_str());
325 
326     if (!m_valid_pointer_check_func)
327       m_valid_pointer_check_func =
328           BuildPointerValidatorFunc(m_checker_function->StartAddress());
329 
330     llvm::Value *dereferenced_ptr = nullptr;
331 
332     if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst>(inst))
333       dereferenced_ptr = li->getPointerOperand();
334     else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst>(inst))
335       dereferenced_ptr = si->getPointerOperand();
336     else
337       return false;
338 
339     // Insert an instruction to cast the loaded value to int8_t*
340 
341     BitCastInst *bit_cast =
342         new BitCastInst(dereferenced_ptr, GetI8PtrTy(), "", inst);
343 
344     // Insert an instruction to call the helper with the result
345 
346     llvm::Value *arg_array[1];
347 
348     arg_array[0] = bit_cast;
349 
350     llvm::ArrayRef<llvm::Value *> args(arg_array, 1);
351 
352     CallInst::Create(m_valid_pointer_check_func, args, "", inst);
353 
354     return true;
355   }
356 
357   bool InspectInstruction(llvm::Instruction &i) override {
358     if (dyn_cast<llvm::LoadInst>(&i) || dyn_cast<llvm::StoreInst>(&i))
359       RegisterInstruction(i);
360 
361     return true;
362   }
363 
364 private:
365   llvm::FunctionCallee m_valid_pointer_check_func;
366 };
367 
368 class ObjcObjectChecker : public Instrumenter {
369 public:
370   ObjcObjectChecker(llvm::Module &module,
371                     std::shared_ptr<UtilityFunction> checker_function)
372       : Instrumenter(module, checker_function),
373         m_objc_object_check_func(nullptr) {}
374 
375   ~ObjcObjectChecker() override = default;
376 
377   enum msgSend_type {
378     eMsgSend = 0,
379     eMsgSendSuper,
380     eMsgSendSuper_stret,
381     eMsgSend_fpret,
382     eMsgSend_stret
383   };
384 
385   std::map<llvm::Instruction *, msgSend_type> msgSend_types;
386 
387 protected:
388   bool InstrumentInstruction(llvm::Instruction *inst) override {
389     CallInst *call_inst = dyn_cast<CallInst>(inst);
390 
391     if (!call_inst)
392       return false; // call_inst really shouldn't be nullptr, because otherwise
393                     // InspectInstruction wouldn't have registered it
394 
395     if (!m_objc_object_check_func)
396       m_objc_object_check_func =
397           BuildObjectCheckerFunc(m_checker_function->StartAddress());
398 
399     // id objc_msgSend(id theReceiver, SEL theSelector, ...)
400 
401     llvm::Value *target_object;
402     llvm::Value *selector;
403 
404     switch (msgSend_types[inst]) {
405     case eMsgSend:
406     case eMsgSend_fpret:
407       // On arm64, clang uses objc_msgSend for scalar and struct return
408       // calls.  The call instruction will record which was used.
409       if (call_inst->hasStructRetAttr()) {
410         target_object = call_inst->getArgOperand(1);
411         selector = call_inst->getArgOperand(2);
412       } else {
413         target_object = call_inst->getArgOperand(0);
414         selector = call_inst->getArgOperand(1);
415       }
416       break;
417     case eMsgSend_stret:
418       target_object = call_inst->getArgOperand(1);
419       selector = call_inst->getArgOperand(2);
420       break;
421     case eMsgSendSuper:
422     case eMsgSendSuper_stret:
423       return true;
424     }
425 
426     // These objects should always be valid according to Sean Calannan
427     assert(target_object);
428     assert(selector);
429 
430     // Insert an instruction to cast the receiver id to int8_t*
431 
432     BitCastInst *bit_cast =
433         new BitCastInst(target_object, GetI8PtrTy(), "", inst);
434 
435     // Insert an instruction to call the helper with the result
436 
437     llvm::Value *arg_array[2];
438 
439     arg_array[0] = bit_cast;
440     arg_array[1] = selector;
441 
442     ArrayRef<llvm::Value *> args(arg_array, 2);
443 
444     CallInst::Create(m_objc_object_check_func, args, "", inst);
445 
446     return true;
447   }
448 
449   static llvm::Function *GetFunction(llvm::Value *value) {
450     if (llvm::Function *function = llvm::dyn_cast<llvm::Function>(value)) {
451       return function;
452     }
453 
454     if (llvm::ConstantExpr *const_expr =
455             llvm::dyn_cast<llvm::ConstantExpr>(value)) {
456       switch (const_expr->getOpcode()) {
457       default:
458         return nullptr;
459       case llvm::Instruction::BitCast:
460         return GetFunction(const_expr->getOperand(0));
461       }
462     }
463 
464     return nullptr;
465   }
466 
467   static llvm::Function *GetCalledFunction(llvm::CallInst *inst) {
468     return GetFunction(inst->getCalledValue());
469   }
470 
471   bool InspectInstruction(llvm::Instruction &i) override {
472     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
473 
474     CallInst *call_inst = dyn_cast<CallInst>(&i);
475 
476     if (call_inst) {
477       const llvm::Function *called_function = GetCalledFunction(call_inst);
478 
479       if (!called_function)
480         return true;
481 
482       std::string name_str = called_function->getName().str();
483       const char *name_cstr = name_str.c_str();
484 
485       if (log)
486         log->Printf("Found call to %s: %s\n", name_cstr,
487                     PrintValue(call_inst).c_str());
488 
489       if (name_str.find("objc_msgSend") == std::string::npos)
490         return true;
491 
492       if (!strcmp(name_cstr, "objc_msgSend")) {
493         RegisterInstruction(i);
494         msgSend_types[&i] = eMsgSend;
495         return true;
496       }
497 
498       if (!strcmp(name_cstr, "objc_msgSend_stret")) {
499         RegisterInstruction(i);
500         msgSend_types[&i] = eMsgSend_stret;
501         return true;
502       }
503 
504       if (!strcmp(name_cstr, "objc_msgSend_fpret")) {
505         RegisterInstruction(i);
506         msgSend_types[&i] = eMsgSend_fpret;
507         return true;
508       }
509 
510       if (!strcmp(name_cstr, "objc_msgSendSuper")) {
511         RegisterInstruction(i);
512         msgSend_types[&i] = eMsgSendSuper;
513         return true;
514       }
515 
516       if (!strcmp(name_cstr, "objc_msgSendSuper_stret")) {
517         RegisterInstruction(i);
518         msgSend_types[&i] = eMsgSendSuper_stret;
519         return true;
520       }
521 
522       if (log)
523         log->Printf(
524             "Function name '%s' contains 'objc_msgSend' but is not handled",
525             name_str.c_str());
526 
527       return true;
528     }
529 
530     return true;
531   }
532 
533 private:
534   llvm::FunctionCallee m_objc_object_check_func;
535 };
536 
537 IRDynamicChecks::IRDynamicChecks(
538     ClangDynamicCheckerFunctions &checker_functions, const char *func_name)
539     : ModulePass(ID), m_func_name(func_name),
540       m_checker_functions(checker_functions) {}
541 
542 IRDynamicChecks::~IRDynamicChecks() = default;
543 
544 bool IRDynamicChecks::runOnModule(llvm::Module &M) {
545   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
546 
547   llvm::Function *function = M.getFunction(StringRef(m_func_name));
548 
549   if (!function) {
550     if (log)
551       log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
552 
553     return false;
554   }
555 
556   if (m_checker_functions.m_valid_pointer_check) {
557     ValidPointerChecker vpc(M, m_checker_functions.m_valid_pointer_check);
558 
559     if (!vpc.Inspect(*function))
560       return false;
561 
562     if (!vpc.Instrument())
563       return false;
564   }
565 
566   if (m_checker_functions.m_objc_object_check) {
567     ObjcObjectChecker ooc(M, m_checker_functions.m_objc_object_check);
568 
569     if (!ooc.Inspect(*function))
570       return false;
571 
572     if (!ooc.Instrument())
573       return false;
574   }
575 
576   if (log && log->GetVerbose()) {
577     std::string s;
578     raw_string_ostream oss(s);
579 
580     M.print(oss, nullptr);
581 
582     oss.flush();
583 
584     log->Printf("Module after dynamic checks: \n%s", s.c_str());
585   }
586 
587   return true;
588 }
589 
590 void IRDynamicChecks::assignPassManager(PMStack &PMS, PassManagerType T) {}
591 
592 PassManagerType IRDynamicChecks::getPotentialPassManagerType() const {
593   return PMT_ModulePassManager;
594 }
595