blob: b5a706d67ece451b10afa29b5f00f731ece13860 [file] [log] [blame]
Sean Callananf18d91c2010-09-01 00:58:00 +00001//===-- IRDynamicChecks.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRDynamicChecks.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000011
Sean Callanane8a59a82010-09-13 21:34:21 +000012#include "lldb/Core/ConstString.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000013#include "lldb/Core/Log.h"
Sean Callanane8a59a82010-09-13 21:34:21 +000014#include "lldb/Expression/ClangUtilityFunction.h"
15#include "lldb/Target/ExecutionContext.h"
16#include "lldb/Target/StackFrame.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000017
18#include "llvm/Support/raw_ostream.h"
19#include "llvm/Function.h"
Sean Callanan05262332010-09-02 00:37:32 +000020#include "llvm/Instructions.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000021#include "llvm/Module.h"
22#include "llvm/Value.h"
23
24using namespace llvm;
25using namespace lldb_private;
26
27static char ID;
28
Sean Callanane8a59a82010-09-13 21:34:21 +000029static const char valid_pointer_check_name[] =
30"___clang_valid_pointer_check";
31
Sean Callananf18d91c2010-09-01 00:58:00 +000032static const char valid_pointer_check_text[] =
33 "extern \"C\" void "
34 "___clang_valid_pointer_check (unsigned char *ptr)"
35 "{"
36 "unsigned char val = *ptr;"
37 "}";
38
Sean Callanane8a59a82010-09-13 21:34:21 +000039static const char objc_object_check_name[] =
40 "___clang_objc_object_check";
41
42static bool FunctionExists(const SymbolContext &sym_ctx, const char *name)
43{
44 ConstString name_cs(name);
45
46 SymbolContextList sym_ctxs;
47
48 sym_ctx.FindFunctionsByName(name_cs, false, sym_ctxs);
49
50 return (sym_ctxs.GetSize() != 0);
51}
52
53static const char *objc_object_check_text(ExecutionContext &exe_ctx)
54{
55 std::string ret;
56
57 if (!exe_ctx.frame)
58 return "extern \"C\" void ___clang_objc_object_check (unsigned char *obj) { }";
59
60 const SymbolContext &sym_ctx(exe_ctx.frame->GetSymbolContext(lldb::eSymbolContextEverything));
61
62 if (FunctionExists(sym_ctx, "gdb_object_getClass"))
63 {
64 return "extern \"C\" void "
65 "___clang_objc_object_check(uint8_t *obj)"
66 "{"
67 ""
68 "}";
69 }
70 else if (FunctionExists(sym_ctx, "gdb_class_getClass"))
71 {
72 return "extern \"C\" void "
73 "___clang_objc_object_check(uint8_t *obj)"
74 "{"
75 ""
76 "}";
77 }
78 else
79 {
80 return "extern \"C\" void "
81 "___clang_objc_object_check(uint8_t *obj)"
82 "{"
83 ""
84 "}";
85 }
86}
Sean Callananf18d91c2010-09-01 00:58:00 +000087
88DynamicCheckerFunctions::DynamicCheckerFunctions ()
89{
Sean Callananf18d91c2010-09-01 00:58:00 +000090}
91
92DynamicCheckerFunctions::~DynamicCheckerFunctions ()
93{
94}
95
96bool
97DynamicCheckerFunctions::Install(Stream &error_stream,
98 ExecutionContext &exe_ctx)
99{
Sean Callanane8a59a82010-09-13 21:34:21 +0000100 m_valid_pointer_check.reset(new ClangUtilityFunction(valid_pointer_check_text,
101 valid_pointer_check_name));
102
Sean Callananf18d91c2010-09-01 00:58:00 +0000103 if (!m_valid_pointer_check->Install(error_stream, exe_ctx))
104 return false;
105
106 return true;
107}
108
Sean Callananf18d91c2010-09-01 00:58:00 +0000109static std::string
110PrintValue(llvm::Value *V, bool truncate = false)
111{
112 std::string s;
113 raw_string_ostream rso(s);
114 V->print(rso);
115 rso.flush();
116 if (truncate)
117 s.resize(s.length() - 1);
118 return s;
119}
120
Sean Callanan05262332010-09-02 00:37:32 +0000121//----------------------------------------------------------------------
122/// @class Instrumenter IRDynamicChecks.cpp
123/// @brief Finds and instruments individual LLVM IR instructions
124///
125/// When instrumenting LLVM IR, it is frequently desirable to first search
126/// for instructions, and then later modify them. This way iterators
127/// remain intact, and multiple passes can look at the same code base without
128/// treading on each other's toes.
129///
130/// The Instrumenter class implements this functionality. A client first
131/// calls Inspect on a function, which populates a list of instructions to
132/// be instrumented. Then, later, when all passes' Inspect functions have
133/// been called, the client calls Instrument, which adds the desired
134/// instrumentation.
135///
136/// A subclass of Instrumenter must override InstrumentInstruction, which
137/// is responsible for adding whatever instrumentation is necessary.
138///
139/// A subclass of Instrumenter may override:
140///
141/// - InspectInstruction [default: does nothing]
142///
143/// - InspectBasicBlock [default: iterates through the instructions in a
144/// basic block calling InspectInstruction]
145///
146/// - InspectFunction [default: iterates through the basic blocks in a
147/// function calling InspectBasicBlock]
148//----------------------------------------------------------------------
149class Instrumenter {
150public:
151 //------------------------------------------------------------------
152 /// Constructor
153 ///
154 /// @param[in] module
155 /// The module being instrumented.
156 //------------------------------------------------------------------
157 Instrumenter (llvm::Module &module,
158 DynamicCheckerFunctions &checker_functions) :
159 m_module(module),
Sean Callanane8a59a82010-09-13 21:34:21 +0000160 m_checker_functions(checker_functions),
161 m_i8ptr_ty(NULL)
Sean Callanan05262332010-09-02 00:37:32 +0000162 {
163 }
164
165 //------------------------------------------------------------------
166 /// Inspect a function to find instructions to instrument
167 ///
168 /// @param[in] function
169 /// The function to inspect.
170 ///
171 /// @return
172 /// True on success; false on error.
173 //------------------------------------------------------------------
174 bool Inspect (llvm::Function &function)
175 {
176 return InspectFunction(function);
177 }
178
179 //------------------------------------------------------------------
180 /// Instrument all the instructions found by Inspect()
181 ///
182 /// @return
183 /// True on success; false on error.
184 //------------------------------------------------------------------
185 bool Instrument ()
186 {
187 for (InstIterator ii = m_to_instrument.begin(), last_ii = m_to_instrument.end();
188 ii != last_ii;
189 ++ii)
190 {
191 if (!InstrumentInstruction(*ii))
192 return false;
193 }
194
195 return true;
196 }
197protected:
198 //------------------------------------------------------------------
199 /// Add instrumentation to a single instruction
200 ///
201 /// @param[in] inst
202 /// The instruction to be instrumented.
203 ///
204 /// @return
205 /// True on success; false otherwise.
206 //------------------------------------------------------------------
207 virtual bool InstrumentInstruction(llvm::Instruction *inst) = 0;
208
209 //------------------------------------------------------------------
210 /// Register a single instruction to be instrumented
211 ///
212 /// @param[in] inst
213 /// The instruction to be instrumented.
214 //------------------------------------------------------------------
215 void RegisterInstruction(llvm::Instruction &i)
216 {
217 m_to_instrument.push_back(&i);
218 }
219
220 //------------------------------------------------------------------
221 /// Determine whether a single instruction is interesting to
222 /// instrument, and, if so, call RegisterInstruction
223 ///
224 /// @param[in] i
225 /// The instruction to be inspected.
226 ///
227 /// @return
228 /// False if there was an error scanning; true otherwise.
229 //------------------------------------------------------------------
230 virtual bool InspectInstruction(llvm::Instruction &i)
231 {
232 return true;
233 }
234
235 //------------------------------------------------------------------
236 /// Scan a basic block to see if any instructions are interesting
237 ///
238 /// @param[in] bb
239 /// The basic block to be inspected.
240 ///
241 /// @return
242 /// False if there was an error scanning; true otherwise.
243 //------------------------------------------------------------------
244 virtual bool InspectBasicBlock(llvm::BasicBlock &bb)
245 {
246 for (llvm::BasicBlock::iterator ii = bb.begin(), last_ii = bb.end();
247 ii != last_ii;
248 ++ii)
249 {
250 if (!InspectInstruction(*ii))
251 return false;
252 }
253
254 return true;
255 }
256
257 //------------------------------------------------------------------
258 /// Scan a function to see if any instructions are interesting
259 ///
260 /// @param[in] f
261 /// The function to be inspected.
262 ///
263 /// @return
264 /// False if there was an error scanning; true otherwise.
265 //------------------------------------------------------------------
266 virtual bool InspectFunction(llvm::Function &f)
267 {
268 for (llvm::Function::iterator bbi = f.begin(), last_bbi = f.end();
269 bbi != last_bbi;
270 ++bbi)
271 {
272 if (!InspectBasicBlock(*bbi))
273 return false;
274 }
275
276 return true;
277 }
278
Sean Callanane8a59a82010-09-13 21:34:21 +0000279 //------------------------------------------------------------------
280 /// Build a function pointer for a function with signature
281 /// void (*)(uint8_t*) with a given address
282 ///
283 /// @param[in] start_address
284 /// The address of the function.
285 ///
286 /// @return
287 /// The function pointer, for use in a CallInst.
288 //------------------------------------------------------------------
289 llvm::Value *BuildPointerValidatorFunc(lldb::addr_t start_address)
290 {
291 std::vector<const llvm::Type*> params;
292
293 const IntegerType *intptr_ty = llvm::Type::getIntNTy(m_module.getContext(),
294 (m_module.getPointerSize() == llvm::Module::Pointer64) ? 64 : 32);
295
296 if (!m_i8ptr_ty)
297 m_i8ptr_ty = llvm::Type::getInt8PtrTy(m_module.getContext());
298
299 params.push_back(m_i8ptr_ty);
300
301 FunctionType *fun_ty = FunctionType::get(llvm::Type::getVoidTy(m_module.getContext()), params, true);
302 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
303 Constant *fun_addr_int = ConstantInt::get(intptr_ty, start_address, false);
304 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
305 }
306
Sean Callanan05262332010-09-02 00:37:32 +0000307 typedef std::vector <llvm::Instruction *> InstVector;
308 typedef InstVector::iterator InstIterator;
309
310 InstVector m_to_instrument; ///< List of instructions the inspector found
311 llvm::Module &m_module; ///< The module which is being instrumented
312 DynamicCheckerFunctions &m_checker_functions; ///< The dynamic checker functions for the process
Sean Callanane8a59a82010-09-13 21:34:21 +0000313
314 const PointerType *m_i8ptr_ty;
Sean Callanan05262332010-09-02 00:37:32 +0000315};
316
317class ValidPointerChecker : public Instrumenter
318{
319public:
320 ValidPointerChecker(llvm::Module &module,
321 DynamicCheckerFunctions &checker_functions) :
322 Instrumenter(module, checker_functions),
323 m_valid_pointer_check_func(NULL)
324 {
325 }
326private:
327 bool InstrumentInstruction(llvm::Instruction *inst)
328 {
329 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
330
331 if(log)
332 log->Printf("Instrumenting load/store instruction: %s\n",
333 PrintValue(inst).c_str());
334
335 if (!m_valid_pointer_check_func)
Sean Callanane8a59a82010-09-13 21:34:21 +0000336 m_valid_pointer_check_func = BuildPointerValidatorFunc(m_checker_functions.m_valid_pointer_check->StartAddress());
Sean Callanan05262332010-09-02 00:37:32 +0000337
338 llvm::Value *dereferenced_ptr;
339
340 if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst> (inst))
341 dereferenced_ptr = li->getPointerOperand();
342 else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst> (inst))
343 dereferenced_ptr = si->getPointerOperand();
344 else
345 return false;
346
347 // Insert an instruction to cast the loaded value to int8_t*
348
349 BitCastInst *bit_cast = new BitCastInst(dereferenced_ptr,
350 m_i8ptr_ty,
351 "",
352 inst);
353
354 // Insert an instruction to call the helper with the result
355
356 SmallVector <llvm::Value*, 1> args;
357 args.push_back(bit_cast);
358
359 CallInst::Create(m_valid_pointer_check_func,
360 args.begin(),
361 args.end(),
362 "",
363 inst);
364
365 return true;
366 }
367
368 bool InspectInstruction(llvm::Instruction &i)
369 {
370 if (dyn_cast<llvm::LoadInst> (&i) ||
371 dyn_cast<llvm::StoreInst> (&i))
372 RegisterInstruction(i);
373
374 return true;
375 }
376
377 llvm::Value *m_valid_pointer_check_func;
Sean Callanane8a59a82010-09-13 21:34:21 +0000378};
379
380class ObjcObjectChecker : public Instrumenter
381{
382public:
383 ObjcObjectChecker(llvm::Module &module,
384 DynamicCheckerFunctions &checker_functions) :
385 Instrumenter(module, checker_functions),
386 m_objc_object_check_func(NULL)
387 {
388 }
389private:
390 bool InstrumentInstruction(llvm::Instruction *inst)
391 {
392 CallInst *call_inst = dyn_cast<CallInst>(inst);
393
394 if (!call_inst)
395 return false; // this really should be true, because otherwise InspectInstruction wouldn't have registered it
396
397 if (!m_objc_object_check_func)
398 m_objc_object_check_func = BuildPointerValidatorFunc(m_checker_functions.m_objc_object_check->StartAddress());
399
400 llvm::Value *target_object;
401
402 // id objc_msgSend(id theReceiver, SEL theSelector, ...)
403
404 target_object = call_inst->getArgOperand(0);
405
406 // Insert an instruction to cast the receiver id to int8_t*
407
408 BitCastInst *bit_cast = new BitCastInst(target_object,
409 m_i8ptr_ty,
410 "",
411 inst);
412
413 // Insert an instruction to call the helper with the result
414
415 SmallVector <llvm::Value*, 1> args;
416 args.push_back(bit_cast);
417
418 CallInst::Create(m_objc_object_check_func,
419 args.begin(),
420 args.end(),
421 "",
422 inst);
423
424 return true;
425 }
426
427 bool InspectInstruction(llvm::Instruction &i)
428 {
429 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
430
431 CallInst *call_inst = dyn_cast<CallInst>(&i);
432
433 if (call_inst)
434 {
435 // This metadata is set by IRForTarget::MaybeHandleCall().
436
437 MDNode *metadata = call_inst->getMetadata("lldb.call.realName");
438
439 if (!metadata)
440 return true;
441
442 if (metadata->getNumOperands() != 1)
443 {
444 if (log)
445 log->Printf("Function call metadata has %d operands for [%p] %s", metadata->getNumOperands(), call_inst, PrintValue(call_inst).c_str());
446 return false;
447 }
448
449 ConstantArray *real_name = dyn_cast<ConstantArray>(metadata->getOperand(0));
450
451 if (!real_name)
452 {
453 if (log)
454 log->Printf("Function call metadata is not a ConstantArray for [%p] %s", call_inst, PrintValue(call_inst).c_str());
455 return false;
456 }
457
458 if (!real_name->isString())
459 {
460 if (log)
461 log->Printf("Function call metadata is not a string for [%p] %s", call_inst, PrintValue(call_inst).c_str());
462 return false;
463 }
464
465 if (log)
466 log->Printf("Found call to %s: %s\n", real_name->getAsString().c_str(), PrintValue(call_inst).c_str());
467
468 if (real_name->getAsString().find("objc_msgSend") != std::string::npos)
469 RegisterInstruction(i);
470 }
471
472 return true;
473 }
474
475 llvm::Value *m_objc_object_check_func;
Sean Callanan05262332010-09-02 00:37:32 +0000476 const PointerType *m_i8ptr_ty;
477};
478
479IRDynamicChecks::IRDynamicChecks(DynamicCheckerFunctions &checker_functions,
480 const char *func_name) :
481 ModulePass(&ID),
482 m_checker_functions(checker_functions),
483 m_func_name(func_name)
484{
485}
486
Sean Callananf18d91c2010-09-01 00:58:00 +0000487IRDynamicChecks::~IRDynamicChecks()
488{
489}
490
491bool
492IRDynamicChecks::runOnModule(llvm::Module &M)
493{
494 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
495
496 llvm::Function* function = M.getFunction(StringRef(m_func_name.c_str()));
497
498 if (!function)
499 {
500 if (log)
501 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
502
503 return false;
504 }
Sean Callanan05262332010-09-02 00:37:32 +0000505
506 ValidPointerChecker vpc(M, m_checker_functions);
Sean Callananf18d91c2010-09-01 00:58:00 +0000507
Sean Callanan05262332010-09-02 00:37:32 +0000508 if (!vpc.Inspect(*function))
509 return false;
Sean Callananf18d91c2010-09-01 00:58:00 +0000510
Sean Callanan05262332010-09-02 00:37:32 +0000511 if (!vpc.Instrument())
512 return false;
Sean Callananf18d91c2010-09-01 00:58:00 +0000513
Sean Callanane8a59a82010-09-13 21:34:21 +0000514 /*
515 ObjcObjectChecker ooc(M, m_checker_functions);
516
517 if (!ooc.Inspect(*function))
518 return false;
519
520 if (!ooc.Instrument())
521 return false;
522 */
523
Sean Callanan65af7342010-09-08 20:04:08 +0000524 if (log)
525 {
526 std::string s;
527 raw_string_ostream oss(s);
528
529 M.print(oss, NULL);
530
531 oss.flush();
532
533 log->Printf("Module after dynamic checks: \n%s", s.c_str());
534 }
535
Sean Callananf18d91c2010-09-01 00:58:00 +0000536 return true;
537}
538
539void
540IRDynamicChecks::assignPassManager(PMStack &PMS,
541 PassManagerType T)
542{
543}
544
545PassManagerType
546IRDynamicChecks::getPotentialPassManagerType() const
547{
548 return PMT_ModulePassManager;
549}