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/Function.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Value.h"
28 using namespace lldb_private;
32 #define VALID_POINTER_CHECK_NAME "$__lldb_valid_pointer_check"
33 #define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"
35 static const char g_valid_pointer_check_text[] =
37 "$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
39 " unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n"
42 DynamicCheckerFunctions::DynamicCheckerFunctions ()
46 DynamicCheckerFunctions::~DynamicCheckerFunctions ()
51 DynamicCheckerFunctions::Install(Stream &error_stream,
52 ExecutionContext &exe_ctx)
54 m_valid_pointer_check.reset(new ClangUtilityFunction(g_valid_pointer_check_text,
55 VALID_POINTER_CHECK_NAME));
56 if (!m_valid_pointer_check->Install(error_stream, exe_ctx))
59 Process *process = exe_ctx.GetProcessPtr();
63 ObjCLanguageRuntime *objc_language_runtime = process->GetObjCLanguageRuntime();
65 if (objc_language_runtime)
67 m_objc_object_check.reset(objc_language_runtime->CreateObjectChecker(VALID_OBJC_OBJECT_CHECK_NAME));
69 if (!m_objc_object_check->Install(error_stream, exe_ctx))
78 DynamicCheckerFunctions::DoCheckersExplainStop (lldb::addr_t addr, Stream &message)
80 // FIXME: We have to get the checkers to know why they scotched the call in more detail,
81 // so we can print a better message here.
82 if (m_valid_pointer_check.get() != NULL && m_valid_pointer_check->ContainsAddress(addr))
84 message.Printf ("Attempted to dereference an invalid pointer.");
87 else if (m_objc_object_check.get() != NULL && m_objc_object_check->ContainsAddress(addr))
89 message.Printf ("Attempted to dereference an invalid ObjC Object or send it an unrecognized selector");
97 PrintValue(llvm::Value *V, bool truncate = false)
100 raw_string_ostream rso(s);
104 s.resize(s.length() - 1);
108 //----------------------------------------------------------------------
109 /// @class Instrumenter IRDynamicChecks.cpp
110 /// @brief Finds and instruments individual LLVM IR instructions
112 /// When instrumenting LLVM IR, it is frequently desirable to first search
113 /// for instructions, and then later modify them. This way iterators
114 /// remain intact, and multiple passes can look at the same code base without
115 /// treading on each other's toes.
117 /// The Instrumenter class implements this functionality. A client first
118 /// calls Inspect on a function, which populates a list of instructions to
119 /// be instrumented. Then, later, when all passes' Inspect functions have
120 /// been called, the client calls Instrument, which adds the desired
123 /// A subclass of Instrumenter must override InstrumentInstruction, which
124 /// is responsible for adding whatever instrumentation is necessary.
126 /// A subclass of Instrumenter may override:
128 /// - InspectInstruction [default: does nothing]
130 /// - InspectBasicBlock [default: iterates through the instructions in a
131 /// basic block calling InspectInstruction]
133 /// - InspectFunction [default: iterates through the basic blocks in a
134 /// function calling InspectBasicBlock]
135 //----------------------------------------------------------------------
138 //------------------------------------------------------------------
141 /// @param[in] module
142 /// The module being instrumented.
143 //------------------------------------------------------------------
144 Instrumenter (llvm::Module &module,
145 DynamicCheckerFunctions &checker_functions) :
147 m_checker_functions(checker_functions),
152 virtual~Instrumenter ()
156 //------------------------------------------------------------------
157 /// Inspect a function to find instructions to instrument
159 /// @param[in] function
160 /// The function to inspect.
163 /// True on success; false on error.
164 //------------------------------------------------------------------
165 bool Inspect (llvm::Function &function)
167 return InspectFunction(function);
170 //------------------------------------------------------------------
171 /// Instrument all the instructions found by Inspect()
174 /// True on success; false on error.
175 //------------------------------------------------------------------
178 for (InstIterator ii = m_to_instrument.begin(), last_ii = m_to_instrument.end();
182 if (!InstrumentInstruction(*ii))
189 //------------------------------------------------------------------
190 /// Add instrumentation to a single instruction
193 /// The instruction to be instrumented.
196 /// True on success; false otherwise.
197 //------------------------------------------------------------------
198 virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
200 //------------------------------------------------------------------
201 /// Register a single instruction to be instrumented
204 /// The instruction to be instrumented.
205 //------------------------------------------------------------------
206 void RegisterInstruction(llvm::Instruction &i)
208 m_to_instrument.push_back(&i);
211 //------------------------------------------------------------------
212 /// Determine whether a single instruction is interesting to
213 /// instrument, and, if so, call RegisterInstruction
216 /// The instruction to be inspected.
219 /// False if there was an error scanning; true otherwise.
220 //------------------------------------------------------------------
221 virtual bool InspectInstruction(llvm::Instruction &i)
226 //------------------------------------------------------------------
227 /// Scan a basic block to see if any instructions are interesting
230 /// The basic block to be inspected.
233 /// False if there was an error scanning; true otherwise.
234 //------------------------------------------------------------------
235 virtual bool InspectBasicBlock(llvm::BasicBlock &bb)
237 for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end();
241 if (!InspectInstruction(*ii))
248 //------------------------------------------------------------------
249 /// Scan a function to see if any instructions are interesting
252 /// The function to be inspected.
255 /// False if there was an error scanning; true otherwise.
256 //------------------------------------------------------------------
257 virtual bool InspectFunction(llvm::Function &f)
259 for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end();
263 if (!InspectBasicBlock(*bbi))
270 //------------------------------------------------------------------
271 /// Build a function pointer for a function with signature
272 /// void (*)(uint8_t*) with a given address
274 /// @param[in] start_address
275 /// The address of the function.
278 /// The function pointer, for use in a CallInst.
279 //------------------------------------------------------------------
280 llvm::Value *BuildPointerValidatorFunc(lldb::addr_t start_address)
282 IntegerType *intptr_ty = llvm::Type::getIntNTy(m_module.getContext(),
283 (m_module.getPointerSize() == llvm::Module::Pointer64) ? 64 : 32);
285 llvm::Type *param_array[1];
287 param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
289 ArrayRef<llvm::Type*> params(param_array, 1);
291 FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
292 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
293 Constant *fun_addr_int = ConstantInt::get(intptr_ty, start_address, false);
294 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
297 //------------------------------------------------------------------
298 /// Build a function pointer for a function with signature
299 /// void (*)(uint8_t*, uint8_t*) with a given address
301 /// @param[in] start_address
302 /// The address of the function.
305 /// The function pointer, for use in a CallInst.
306 //------------------------------------------------------------------
307 llvm::Value *BuildObjectCheckerFunc(lldb::addr_t start_address)
309 IntegerType *intptr_ty = llvm::Type::getIntNTy(m_module.getContext(),
310 (m_module.getPointerSize() == llvm::Module::Pointer64) ? 64 : 32);
312 llvm::Type *param_array[2];
314 param_array[0] = const_cast<llvm::PointerType*>(GetI8PtrTy());
315 param_array[1] = const_cast<llvm::PointerType*>(GetI8PtrTy());
317 ArrayRef<llvm::Type*> params(param_array, 2);
319 FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
320 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
321 Constant *fun_addr_int = ConstantInt::get(intptr_ty, start_address, false);
322 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
325 PointerType *GetI8PtrTy()
328 m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
333 typedef std::vector <llvm::Instruction *> InstVector;
334 typedef InstVector::iterator InstIterator;
336 InstVector m_to_instrument; ///< List of instructions the inspector found
337 llvm::Module &m_module; ///< The module which is being instrumented
338 DynamicCheckerFunctions &m_checker_functions; ///< The dynamic checker functions for the process
340 PointerType *m_i8ptr_ty;
343 class ValidPointerChecker : public Instrumenter
346 ValidPointerChecker (llvm::Module &module,
347 DynamicCheckerFunctions &checker_functions) :
348 Instrumenter(module, checker_functions),
349 m_valid_pointer_check_func(NULL)
353 virtual ~ValidPointerChecker ()
357 bool InstrumentInstruction(llvm::Instruction *inst)
359 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
362 log->Printf("Instrumenting load/store instruction: %s\n",
363 PrintValue(inst).c_str());
365 if (!m_valid_pointer_check_func)
366 m_valid_pointer_check_func = BuildPointerValidatorFunc(m_checker_functions.m_valid_pointer_check->StartAddress());
368 llvm::Value *dereferenced_ptr = NULL;
370 if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst> (inst))
371 dereferenced_ptr = li->getPointerOperand();
372 else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst> (inst))
373 dereferenced_ptr = si->getPointerOperand();
377 // Insert an instruction to cast the loaded value to int8_t*
379 BitCastInst *bit_cast = new BitCastInst(dereferenced_ptr,
384 // Insert an instruction to call the helper with the result
386 llvm::Value *arg_array[1];
388 arg_array[0] = bit_cast;
390 llvm::ArrayRef<llvm::Value *> args(arg_array, 1);
392 CallInst::Create(m_valid_pointer_check_func,
400 bool InspectInstruction(llvm::Instruction &i)
402 if (dyn_cast<llvm::LoadInst> (&i) ||
403 dyn_cast<llvm::StoreInst> (&i))
404 RegisterInstruction(i);
409 llvm::Value *m_valid_pointer_check_func;
412 class ObjcObjectChecker : public Instrumenter
415 ObjcObjectChecker(llvm::Module &module,
416 DynamicCheckerFunctions &checker_functions) :
417 Instrumenter(module, checker_functions),
418 m_objc_object_check_func(NULL)
423 ~ObjcObjectChecker ()
436 std::map <llvm::Instruction *, msgSend_type> msgSend_types;
439 bool InstrumentInstruction(llvm::Instruction *inst)
441 CallInst *call_inst = dyn_cast<CallInst>(inst);
444 return false; // call_inst really shouldn't be NULL, because otherwise InspectInstruction wouldn't have registered it
446 if (!m_objc_object_check_func)
447 m_objc_object_check_func = BuildObjectCheckerFunc(m_checker_functions.m_objc_object_check->StartAddress());
449 // id objc_msgSend(id theReceiver, SEL theSelector, ...)
451 llvm::Value *target_object;
452 llvm::Value *selector;
454 switch (msgSend_types[inst])
458 target_object = call_inst->getArgOperand(0);
459 selector = call_inst->getArgOperand(1);
462 target_object = call_inst->getArgOperand(1);
463 selector = call_inst->getArgOperand(2);
466 case eMsgSendSuper_stret:
470 // These objects should always be valid according to Sean Calannan
471 assert (target_object);
474 // Insert an instruction to cast the receiver id to int8_t*
476 BitCastInst *bit_cast = new BitCastInst(target_object,
481 // Insert an instruction to call the helper with the result
483 llvm::Value *arg_array[2];
485 arg_array[0] = bit_cast;
486 arg_array[1] = selector;
488 ArrayRef<llvm::Value*> args(arg_array, 2);
490 CallInst::Create(m_objc_object_check_func,
498 bool InspectInstruction(llvm::Instruction &i)
500 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
502 CallInst *call_inst = dyn_cast<CallInst>(&i);
506 // This metadata is set by IRForTarget::MaybeHandleCall().
508 MDNode *metadata = call_inst->getMetadata("lldb.call.realName");
513 if (metadata->getNumOperands() != 1)
516 log->Printf("Function call metadata has %d operands for [%p] %s", metadata->getNumOperands(), call_inst, PrintValue(call_inst).c_str());
520 MDString *real_name = dyn_cast<MDString>(metadata->getOperand(0));
525 log->Printf("Function call metadata is not an MDString for [%p] %s", call_inst, PrintValue(call_inst).c_str());
529 std::string name_str = real_name->getString();
530 const char* name_cstr = name_str.c_str();
533 log->Printf("Found call to %s: %s\n", name_cstr, PrintValue(call_inst).c_str());
535 if (name_str.find("objc_msgSend") == std::string::npos)
538 if (!strcmp(name_cstr, "objc_msgSend"))
540 RegisterInstruction(i);
541 msgSend_types[&i] = eMsgSend;
545 if (!strcmp(name_cstr, "objc_msgSend_stret"))
547 RegisterInstruction(i);
548 msgSend_types[&i] = eMsgSend_stret;
552 if (!strcmp(name_cstr, "objc_msgSend_fpret"))
554 RegisterInstruction(i);
555 msgSend_types[&i] = eMsgSend_fpret;
559 if (!strcmp(name_cstr, "objc_msgSendSuper"))
561 RegisterInstruction(i);
562 msgSend_types[&i] = eMsgSendSuper;
566 if (!strcmp(name_cstr, "objc_msgSendSuper_stret"))
568 RegisterInstruction(i);
569 msgSend_types[&i] = eMsgSendSuper_stret;
574 log->Printf("Function name '%s' contains 'objc_msgSend' but is not handled", name_str.c_str());
582 llvm::Value *m_objc_object_check_func;
585 IRDynamicChecks::IRDynamicChecks(DynamicCheckerFunctions &checker_functions,
586 const char *func_name) :
588 m_func_name(func_name),
589 m_checker_functions(checker_functions)
593 IRDynamicChecks::~IRDynamicChecks()
598 IRDynamicChecks::runOnModule(llvm::Module &M)
600 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
602 llvm::Function* function = M.getFunction(StringRef(m_func_name.c_str()));
607 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
612 if (m_checker_functions.m_valid_pointer_check.get())
614 ValidPointerChecker vpc(M, m_checker_functions);
616 if (!vpc.Inspect(*function))
619 if (!vpc.Instrument())
623 if (m_checker_functions.m_objc_object_check.get())
625 ObjcObjectChecker ooc(M, m_checker_functions);
627 if (!ooc.Inspect(*function))
630 if (!ooc.Instrument())
634 if (log && log->GetVerbose())
637 raw_string_ostream oss(s);
643 log->Printf ("Module after dynamic checks: \n%s", s.c_str());
650 IRDynamicChecks::assignPassManager(PMStack &PMS,
656 IRDynamicChecks::getPotentialPassManagerType() const
658 return PMT_ModulePassManager;