1 //===-- IRDynamicChecks.cpp -------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Expression/IRDynamicChecks.h"
12 #include "lldb/Core/ConstString.h"
13 #include "lldb/Core/Log.h"
14 #include "lldb/Expression/ClangUtilityFunction.h"
15 #include "lldb/Target/ExecutionContext.h"
16 #include "lldb/Target/ObjCLanguageRuntime.h"
17 #include "lldb/Target/Process.h"
18 #include "lldb/Target/StackFrame.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Value.h"
29 using namespace lldb_private;
33 #define VALID_POINTER_CHECK_NAME "$__lldb_valid_pointer_check"
34 #define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"
36 static const char g_valid_pointer_check_text[] =
38 "$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
40 " unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n"
43 DynamicCheckerFunctions::DynamicCheckerFunctions ()
47 DynamicCheckerFunctions::~DynamicCheckerFunctions ()
52 DynamicCheckerFunctions::Install(Stream &error_stream,
53 ExecutionContext &exe_ctx)
55 m_valid_pointer_check.reset(new ClangUtilityFunction(g_valid_pointer_check_text,
56 VALID_POINTER_CHECK_NAME));
57 if (!m_valid_pointer_check->Install(error_stream, exe_ctx))
60 Process *process = exe_ctx.GetProcessPtr();
64 ObjCLanguageRuntime *objc_language_runtime = process->GetObjCLanguageRuntime();
66 if (objc_language_runtime)
68 m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker(VALID_OBJC_OBJECT_CHECK_NAME));
70 if (!m_objc_object_check->Install(error_stream, exe_ctx))
79 DynamicCheckerFunctions::DoCheckersExplainStop (lldb::addr_t addr, Stream &message)
81 // FIXME: We have to get the checkers to know why they scotched the call in more detail,
82 // so we can print a better message here.
83 if (m_valid_pointer_check.get() != NULL && m_valid_pointer_check->ContainsAddress(addr))
85 message.Printf ("Attempted to dereference an invalid pointer.");
88 else if (m_objc_object_check.get() != NULL && m_objc_object_check->ContainsAddress(addr))
90 message.Printf ("Attempted to dereference an invalid ObjC Object or send it an unrecognized selector");
98 PrintValue(llvm::Value *V, bool truncate = false)
101 raw_string_ostream rso(s);
105 s.resize(s.length() - 1);
109 //----------------------------------------------------------------------
110 /// @class Instrumenter IRDynamicChecks.cpp
111 /// @brief Finds and instruments individual LLVM IR instructions
113 /// When instrumenting LLVM IR, it is frequently desirable to first search
114 /// for instructions, and then later modify them. This way iterators
115 /// remain intact, and multiple passes can look at the same code base without
116 /// treading on each other's toes.
118 /// The Instrumenter class implements this functionality. A client first
119 /// calls Inspect on a function, which populates a list of instructions to
120 /// be instrumented. Then, later, when all passes' Inspect functions have
121 /// been called, the client calls Instrument, which adds the desired
124 /// A subclass of Instrumenter must override InstrumentInstruction, which
125 /// is responsible for adding whatever instrumentation is necessary.
127 /// A subclass of Instrumenter may override:
129 /// - InspectInstruction [default: does nothing]
131 /// - InspectBasicBlock [default: iterates through the instructions in a
132 /// basic block calling InspectInstruction]
134 /// - InspectFunction [default: iterates through the basic blocks in a
135 /// function calling InspectBasicBlock]
136 //----------------------------------------------------------------------
139 //------------------------------------------------------------------
142 /// @param[in] module
143 /// The module being instrumented.
144 //------------------------------------------------------------------
145 Instrumenter (llvm::Module &module,
146 DynamicCheckerFunctions &checker_functions) :
148 m_checker_functions(checker_functions),
154 virtual~Instrumenter ()
158 //------------------------------------------------------------------
159 /// Inspect a function to find instructions to instrument
161 /// @param[in] function
162 /// The function to inspect.
165 /// True on success; false on error.
166 //------------------------------------------------------------------
167 bool Inspect (llvm::Function &function)
169 return InspectFunction(function);
172 //------------------------------------------------------------------
173 /// Instrument all the instructions found by Inspect()
176 /// True on success; false on error.
177 //------------------------------------------------------------------
180 for (InstIterator ii = m_to_instrument.begin(), last_ii = m_to_instrument.end();
184 if (!InstrumentInstruction(*ii))
191 //------------------------------------------------------------------
192 /// Add instrumentation to a single instruction
195 /// The instruction to be instrumented.
198 /// True on success; false otherwise.
199 //------------------------------------------------------------------
200 virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
202 //------------------------------------------------------------------
203 /// Register a single instruction to be instrumented
206 /// The instruction to be instrumented.
207 //------------------------------------------------------------------
208 void RegisterInstruction(llvm::Instruction &i)
210 m_to_instrument.push_back(&i);
213 //------------------------------------------------------------------
214 /// Determine whether a single instruction is interesting to
215 /// instrument, and, if so, call RegisterInstruction
218 /// The instruction to be inspected.
221 /// False if there was an error scanning; true otherwise.
222 //------------------------------------------------------------------
223 virtual bool InspectInstruction(llvm::Instruction &i)
228 //------------------------------------------------------------------
229 /// Scan a basic block to see if any instructions are interesting
232 /// The basic block to be inspected.
235 /// False if there was an error scanning; true otherwise.
236 //------------------------------------------------------------------
237 virtual bool InspectBasicBlock(llvm::BasicBlock &bb)
239 for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end();
243 if (!InspectInstruction(*ii))
250 //------------------------------------------------------------------
251 /// Scan a function to see if any instructions are interesting
254 /// The function to be inspected.
257 /// False if there was an error scanning; true otherwise.
258 //------------------------------------------------------------------
259 virtual bool InspectFunction(llvm::Function &f)
261 for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end();
265 if (!InspectBasicBlock(*bbi))
272 //------------------------------------------------------------------
273 /// Build a function pointer for a function with signature
274 /// void (*)(uint8_t*) with a given address
276 /// @param[in] start_address
277 /// The address of the function.
280 /// The function pointer, for use in a CallInst.
281 //------------------------------------------------------------------
282 llvm::Value *BuildPointerValidatorFunc(lldb::addr_t start_address)
284 llvm::Type *param_array[1];
286 param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
288 ArrayRef<llvm::Type*> params(param_array, 1);
290 FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
291 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
292 Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false);
293 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
296 //------------------------------------------------------------------
297 /// Build a function pointer for a function with signature
298 /// void (*)(uint8_t*, uint8_t*) with a given address
300 /// @param[in] start_address
301 /// The address of the function.
304 /// The function pointer, for use in a CallInst.
305 //------------------------------------------------------------------
306 llvm::Value *BuildObjectCheckerFunc(lldb::addr_t start_address)
308 llvm::Type *param_array[2];
310 param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
311 param_array[1] = const_cast<llvm::PointerType*>(GetI8PtrTy());
313 ArrayRef<llvm::Type*> params(param_array, 2);
315 FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
316 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
317 Constant *fun_addr_int = ConstantInt::get(GetIntptrTy(), start_address, false);
318 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
321 PointerType *GetI8PtrTy()
324 m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
329 IntegerType *GetIntptrTy()
333 llvm::DataLayout data_layout(&m_module);
335 m_intptr_ty = llvm::Type::getIntNTy(m_module.getContext(), data_layout.getPointerSizeInBits());
341 typedef std::vector <llvm::Instruction *> InstVector;
342 typedef InstVector::iterator InstIterator;
344 InstVector m_to_instrument; ///< List of instructions the inspector found
345 llvm::Module &m_module; ///< The module which is being instrumented
346 DynamicCheckerFunctions &m_checker_functions; ///< The dynamic checker functions for the process
348 PointerType *m_i8ptr_ty;
349 IntegerType *m_intptr_ty;
352 class ValidPointerChecker : public Instrumenter
355 ValidPointerChecker (llvm::Module &module,
356 DynamicCheckerFunctions &checker_functions) :
357 Instrumenter(module, checker_functions),
358 m_valid_pointer_check_func(NULL)
362 virtual ~ValidPointerChecker ()
366 bool InstrumentInstruction(llvm::Instruction *inst)
368 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
371 log->Printf("Instrumenting load/store instruction: %s\n",
372 PrintValue(inst).c_str());
374 if (!m_valid_pointer_check_func)
375 m_valid_pointer_check_func = BuildPointerValidatorFunc(m_checker_functions.m_valid_pointer_check->StartAddress());
377 llvm::Value *dereferenced_ptr = NULL;
379 if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst> (inst))
380 dereferenced_ptr = li->getPointerOperand();
381 else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst> (inst))
382 dereferenced_ptr = si->getPointerOperand();
386 // Insert an instruction to cast the loaded value to int8_t*
388 BitCastInst *bit_cast = new BitCastInst(dereferenced_ptr,
393 // Insert an instruction to call the helper with the result
395 llvm::Value *arg_array[1];
397 arg_array[0] = bit_cast;
399 llvm::ArrayRef<llvm::Value *> args(arg_array, 1);
401 CallInst::Create(m_valid_pointer_check_func,
409 bool InspectInstruction(llvm::Instruction &i)
411 if (dyn_cast<llvm::LoadInst> (&i) ||
412 dyn_cast<llvm::StoreInst> (&i))
413 RegisterInstruction(i);
418 llvm::Value *m_valid_pointer_check_func;
421 class ObjcObjectChecker : public Instrumenter
424 ObjcObjectChecker(llvm::Module &module,
425 DynamicCheckerFunctions &checker_functions) :
426 Instrumenter(module, checker_functions),
427 m_objc_object_check_func(NULL)
432 ~ObjcObjectChecker ()
445 std::map <llvm::Instruction *, msgSend_type> msgSend_types;
448 bool InstrumentInstruction(llvm::Instruction *inst)
450 CallInst *call_inst = dyn_cast<CallInst>(inst);
453 return false; // call_inst really shouldn't be NULL, because otherwise InspectInstruction wouldn't have registered it
455 if (!m_objc_object_check_func)
456 m_objc_object_check_func = BuildObjectCheckerFunc(m_checker_functions.m_objc_object_check->StartAddress());
458 // id objc_msgSend(id theReceiver, SEL theSelector, ...)
460 llvm::Value *target_object;
461 llvm::Value *selector;
463 switch (msgSend_types[inst])
467 target_object = call_inst->getArgOperand(0);
468 selector = call_inst->getArgOperand(1);
471 target_object = call_inst->getArgOperand(1);
472 selector = call_inst->getArgOperand(2);
475 case eMsgSendSuper_stret:
479 // These objects should always be valid according to Sean Calannan
480 assert (target_object);
483 // Insert an instruction to cast the receiver id to int8_t*
485 BitCastInst *bit_cast = new BitCastInst(target_object,
490 // Insert an instruction to call the helper with the result
492 llvm::Value *arg_array[2];
494 arg_array[0] = bit_cast;
495 arg_array[1] = selector;
497 ArrayRef<llvm::Value*> args(arg_array, 2);
499 CallInst::Create(m_objc_object_check_func,
507 bool InspectInstruction(llvm::Instruction &i)
509 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
511 CallInst *call_inst = dyn_cast<CallInst>(&i);
515 // This metadata is set by IRForTarget::MaybeHandleCall().
517 MDNode *metadata = call_inst->getMetadata("lldb.call.realName");
522 if (metadata->getNumOperands() != 1)
525 log->Printf("Function call metadata has %d operands for [%p] %s", metadata->getNumOperands(), call_inst, PrintValue(call_inst).c_str());
529 MDString *real_name = dyn_cast<MDString>(metadata->getOperand(0));
534 log->Printf("Function call metadata is not an MDString for [%p] %s", call_inst, PrintValue(call_inst).c_str());
538 std::string name_str = real_name->getString();
539 const char* name_cstr = name_str.c_str();
542 log->Printf("Found call to %s: %s\n", name_cstr, PrintValue(call_inst).c_str());
544 if (name_str.find("objc_msgSend") == std::string::npos)
547 if (!strcmp(name_cstr, "objc_msgSend"))
549 RegisterInstruction(i);
550 msgSend_types[&i] = eMsgSend;
554 if (!strcmp(name_cstr, "objc_msgSend_stret"))
556 RegisterInstruction(i);
557 msgSend_types[&i] = eMsgSend_stret;
561 if (!strcmp(name_cstr, "objc_msgSend_fpret"))
563 RegisterInstruction(i);
564 msgSend_types[&i] = eMsgSend_fpret;
568 if (!strcmp(name_cstr, "objc_msgSendSuper"))
570 RegisterInstruction(i);
571 msgSend_types[&i] = eMsgSendSuper;
575 if (!strcmp(name_cstr, "objc_msgSendSuper_stret"))
577 RegisterInstruction(i);
578 msgSend_types[&i] = eMsgSendSuper_stret;
583 log->Printf("Function name '%s' contains 'objc_msgSend' but is not handled", name_str.c_str());
591 llvm::Value *m_objc_object_check_func;
594 IRDynamicChecks::IRDynamicChecks(DynamicCheckerFunctions &checker_functions,
595 const char *func_name) :
597 m_func_name(func_name),
598 m_checker_functions(checker_functions)
602 IRDynamicChecks::~IRDynamicChecks()
607 IRDynamicChecks::runOnModule(llvm::Module &M)
609 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
611 llvm::Function* function = M.getFunction(StringRef(m_func_name.c_str()));
616 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
621 if (m_checker_functions.m_valid_pointer_check.get())
623 ValidPointerChecker vpc(M, m_checker_functions);
625 if (!vpc.Inspect(*function))
628 if (!vpc.Instrument())
632 if (m_checker_functions.m_objc_object_check.get())
634 ObjcObjectChecker ooc(M, m_checker_functions);
636 if (!ooc.Inspect(*function))
639 if (!ooc.Instrument())
643 if (log && log->GetVerbose())
646 raw_string_ostream oss(s);
652 log->Printf ("Module after dynamic checks: \n%s", s.c_str());
659 IRDynamicChecks::assignPassManager(PMStack &PMS,
665 IRDynamicChecks::getPotentialPassManagerType() const
667 return PMT_ModulePassManager;