]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / LanguageRuntime / ObjC / AppleObjCRuntime / AppleObjCRuntime.cpp
1 //===-- AppleObjCRuntime.cpp -------------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "AppleObjCRuntime.h"
12 #include "AppleObjCTrampolineHandler.h"
13
14 #include "clang/AST/Type.h"
15
16 #include "lldb/Breakpoint/BreakpointLocation.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Scalar.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/ValueObject.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/FunctionCaller.h"
25 #include "lldb/Symbol/ClangASTContext.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Utility/ConstString.h"
34 #include "lldb/Utility/Log.h"
35 #include "lldb/Utility/Status.h"
36 #include "lldb/Utility/StreamString.h"
37
38 #include <vector>
39
40 using namespace lldb;
41 using namespace lldb_private;
42
43 static constexpr std::chrono::seconds g_po_function_timeout(15);
44
45 AppleObjCRuntime::~AppleObjCRuntime() {}
46
47 AppleObjCRuntime::AppleObjCRuntime(Process *process)
48     : ObjCLanguageRuntime(process), m_read_objc_library(false),
49       m_objc_trampoline_handler_ap(), m_Foundation_major() {
50   ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());
51 }
52
53 bool AppleObjCRuntime::GetObjectDescription(Stream &str, ValueObject &valobj) {
54   CompilerType compiler_type(valobj.GetCompilerType());
55   bool is_signed;
56   // ObjC objects can only be pointers (or numbers that actually represents
57   // pointers but haven't been typecast, because reasons..)
58   if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
59     return false;
60
61   // Make the argument list: we pass one arg, the address of our pointer, to
62   // the print function.
63   Value val;
64
65   if (!valobj.ResolveValue(val.GetScalar()))
66     return false;
67
68   // Value Objects may not have a process in their ExecutionContextRef.  But we
69   // need to have one in the ref we pass down to eventually call description.
70   // Get it from the target if it isn't present.
71   ExecutionContext exe_ctx;
72   if (valobj.GetProcessSP()) {
73     exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
74   } else {
75     exe_ctx.SetContext(valobj.GetTargetSP(), true);
76     if (!exe_ctx.HasProcessScope())
77       return false;
78   }
79   return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
80 }
81 bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
82                                             ExecutionContextScope *exe_scope) {
83   if (!m_read_objc_library)
84     return false;
85
86   ExecutionContext exe_ctx;
87   exe_scope->CalculateExecutionContext(exe_ctx);
88   Process *process = exe_ctx.GetProcessPtr();
89   if (!process)
90     return false;
91
92   // We need other parts of the exe_ctx, but the processes have to match.
93   assert(m_process == process);
94
95   // Get the function address for the print function.
96   const Address *function_address = GetPrintForDebuggerAddr();
97   if (!function_address)
98     return false;
99
100   Target *target = exe_ctx.GetTargetPtr();
101   CompilerType compiler_type = value.GetCompilerType();
102   if (compiler_type) {
103     if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) {
104       strm.Printf("Value doesn't point to an ObjC object.\n");
105       return false;
106     }
107   } else {
108     // If it is not a pointer, see if we can make it into a pointer.
109     ClangASTContext *ast_context = target->GetScratchClangASTContext();
110     CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID);
111     if (!opaque_type)
112       opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
113     // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
114     value.SetCompilerType(opaque_type);
115   }
116
117   ValueList arg_value_list;
118   arg_value_list.PushValue(value);
119
120   // This is the return value:
121   ClangASTContext *ast_context = target->GetScratchClangASTContext();
122
123   CompilerType return_compiler_type = ast_context->GetCStringType(true);
124   Value ret;
125   //    ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
126   ret.SetCompilerType(return_compiler_type);
127
128   if (exe_ctx.GetFramePtr() == NULL) {
129     Thread *thread = exe_ctx.GetThreadPtr();
130     if (thread == NULL) {
131       exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
132       thread = exe_ctx.GetThreadPtr();
133     }
134     if (thread) {
135       exe_ctx.SetFrameSP(thread->GetSelectedFrame());
136     }
137   }
138
139   // Now we're ready to call the function:
140
141   DiagnosticManager diagnostics;
142   lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
143
144   if (!m_print_object_caller_up) {
145     Status error;
146     m_print_object_caller_up.reset(
147         exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
148             eLanguageTypeObjC, return_compiler_type, *function_address,
149             arg_value_list, "objc-object-description", error));
150     if (error.Fail()) {
151       m_print_object_caller_up.reset();
152       strm.Printf("Could not get function runner to call print for debugger "
153                   "function: %s.",
154                   error.AsCString());
155       return false;
156     }
157     m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
158                                              diagnostics);
159   } else {
160     m_print_object_caller_up->WriteFunctionArguments(
161         exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
162   }
163
164   EvaluateExpressionOptions options;
165   options.SetUnwindOnError(true);
166   options.SetTryAllThreads(true);
167   options.SetStopOthers(true);
168   options.SetIgnoreBreakpoints(true);
169   options.SetTimeout(g_po_function_timeout);
170
171   ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
172       exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
173   if (results != eExpressionCompleted) {
174     strm.Printf("Error evaluating Print Object function: %d.\n", results);
175     return false;
176   }
177
178   addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
179
180   char buf[512];
181   size_t cstr_len = 0;
182   size_t full_buffer_len = sizeof(buf) - 1;
183   size_t curr_len = full_buffer_len;
184   while (curr_len == full_buffer_len) {
185     Status error;
186     curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
187                                               sizeof(buf), error);
188     strm.Write(buf, curr_len);
189     cstr_len += curr_len;
190   }
191   return cstr_len > 0;
192 }
193
194 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
195   ModuleSP module_sp(m_objc_module_wp.lock());
196   if (module_sp)
197     return module_sp;
198
199   Process *process = GetProcess();
200   if (process) {
201     const ModuleList &modules = process->GetTarget().GetImages();
202     for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
203       module_sp = modules.GetModuleAtIndex(idx);
204       if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
205         m_objc_module_wp = module_sp;
206         return module_sp;
207       }
208     }
209   }
210   return ModuleSP();
211 }
212
213 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
214   if (!m_PrintForDebugger_addr.get()) {
215     const ModuleList &modules = m_process->GetTarget().GetImages();
216
217     SymbolContextList contexts;
218     SymbolContext context;
219
220     if ((!modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
221                                              eSymbolTypeCode, contexts)) &&
222         (!modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
223                                              eSymbolTypeCode, contexts)))
224       return NULL;
225
226     contexts.GetContextAtIndex(0, context);
227
228     m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
229   }
230
231   return m_PrintForDebugger_addr.get();
232 }
233
234 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
235   return in_value.GetCompilerType().IsPossibleDynamicType(
236       NULL,
237       false, // do not check C++
238       true); // check ObjC
239 }
240
241 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
242     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
243     TypeAndOrName &class_type_or_name, Address &address,
244     Value::ValueType &value_type) {
245   return false;
246 }
247
248 TypeAndOrName
249 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
250                                    ValueObject &static_value) {
251   CompilerType static_type(static_value.GetCompilerType());
252   Flags static_type_flags(static_type.GetTypeInfo());
253
254   TypeAndOrName ret(type_and_or_name);
255   if (type_and_or_name.HasType()) {
256     // The type will always be the type of the dynamic object.  If our parent's
257     // type was a pointer, then our type should be a pointer to the type of the
258     // dynamic object.  If a reference, then the original type should be
259     // okay...
260     CompilerType orig_type = type_and_or_name.GetCompilerType();
261     CompilerType corrected_type = orig_type;
262     if (static_type_flags.AllSet(eTypeIsPointer))
263       corrected_type = orig_type.GetPointerType();
264     ret.SetCompilerType(corrected_type);
265   } else {
266     // If we are here we need to adjust our dynamic type name to include the
267     // correct & or * symbol
268     std::string corrected_name(type_and_or_name.GetName().GetCString());
269     if (static_type_flags.AllSet(eTypeIsPointer))
270       corrected_name.append(" *");
271     // the parent type should be a correctly pointer'ed or referenc'ed type
272     ret.SetCompilerType(static_type);
273     ret.SetName(corrected_name.c_str());
274   }
275   return ret;
276 }
277
278 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
279   if (module_sp) {
280     const FileSpec &module_file_spec = module_sp->GetFileSpec();
281     static ConstString ObjCName("libobjc.A.dylib");
282
283     if (module_file_spec) {
284       if (module_file_spec.GetFilename() == ObjCName)
285         return true;
286     }
287   }
288   return false;
289 }
290
291 // we use the version of Foundation to make assumptions about the ObjC runtime
292 // on a target
293 uint32_t AppleObjCRuntime::GetFoundationVersion() {
294   if (!m_Foundation_major.hasValue()) {
295     const ModuleList &modules = m_process->GetTarget().GetImages();
296     for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
297       lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
298       if (!module_sp)
299         continue;
300       if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
301                  "Foundation") == 0) {
302         m_Foundation_major = module_sp->GetVersion().getMajor();
303         return *m_Foundation_major;
304       }
305     }
306     return LLDB_INVALID_MODULE_VERSION;
307   } else
308     return m_Foundation_major.getValue();
309 }
310
311 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
312                                                     lldb::addr_t &cf_false) {
313   cf_true = cf_false = LLDB_INVALID_ADDRESS;
314 }
315
316 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
317   return AppleIsModuleObjCLibrary(module_sp);
318 }
319
320 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
321   // Maybe check here and if we have a handler already, and the UUID of this
322   // module is the same as the one in the current module, then we don't have to
323   // reread it?
324   m_objc_trampoline_handler_ap.reset(
325       new AppleObjCTrampolineHandler(m_process->shared_from_this(), module_sp));
326   if (m_objc_trampoline_handler_ap.get() != NULL) {
327     m_read_objc_library = true;
328     return true;
329   } else
330     return false;
331 }
332
333 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
334                                                             bool stop_others) {
335   ThreadPlanSP thread_plan_sp;
336   if (m_objc_trampoline_handler_ap.get())
337     thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan(
338         thread, stop_others);
339   return thread_plan_sp;
340 }
341
342 //------------------------------------------------------------------
343 // Static Functions
344 //------------------------------------------------------------------
345 ObjCLanguageRuntime::ObjCRuntimeVersions
346 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
347   if (!process)
348     return ObjCRuntimeVersions::eObjC_VersionUnknown;
349
350   Target &target = process->GetTarget();
351   if (target.GetArchitecture().GetTriple().getVendor() !=
352       llvm::Triple::VendorType::Apple)
353     return ObjCRuntimeVersions::eObjC_VersionUnknown;
354
355   const ModuleList &target_modules = target.GetImages();
356   std::lock_guard<std::recursive_mutex> gaurd(target_modules.GetMutex());
357
358   size_t num_images = target_modules.GetSize();
359   for (size_t i = 0; i < num_images; i++) {
360     ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
361     // One tricky bit here is that we might get called as part of the initial
362     // module loading, but before all the pre-run libraries get winnowed from
363     // the module list.  So there might actually be an old and incorrect ObjC
364     // library sitting around in the list, and we don't want to look at that.
365     // That's why we call IsLoadedInTarget.
366
367     if (AppleIsModuleObjCLibrary(module_sp) &&
368         module_sp->IsLoadedInTarget(&target)) {
369       objc_module_sp = module_sp;
370       ObjectFile *ofile = module_sp->GetObjectFile();
371       if (!ofile)
372         return ObjCRuntimeVersions::eObjC_VersionUnknown;
373
374       SectionList *sections = module_sp->GetSectionList();
375       if (!sections)
376         return ObjCRuntimeVersions::eObjC_VersionUnknown;
377       SectionSP v1_telltale_section_sp =
378           sections->FindSectionByName(ConstString("__OBJC"));
379       if (v1_telltale_section_sp) {
380         return ObjCRuntimeVersions::eAppleObjC_V1;
381       }
382       return ObjCRuntimeVersions::eAppleObjC_V2;
383     }
384   }
385
386   return ObjCRuntimeVersions::eObjC_VersionUnknown;
387 }
388
389 void AppleObjCRuntime::SetExceptionBreakpoints() {
390   const bool catch_bp = false;
391   const bool throw_bp = true;
392   const bool is_internal = true;
393
394   if (!m_objc_exception_bp_sp) {
395     m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
396         m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
397         is_internal);
398     if (m_objc_exception_bp_sp)
399       m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
400   } else
401     m_objc_exception_bp_sp->SetEnabled(true);
402 }
403
404 void AppleObjCRuntime::ClearExceptionBreakpoints() {
405   if (!m_process)
406     return;
407
408   if (m_objc_exception_bp_sp.get()) {
409     m_objc_exception_bp_sp->SetEnabled(false);
410   }
411 }
412
413 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
414   return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
415 }
416
417 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
418     lldb::StopInfoSP stop_reason) {
419   if (!m_process)
420     return false;
421
422   if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
423     return false;
424
425   uint64_t break_site_id = stop_reason->GetValue();
426   return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
427       break_site_id, m_objc_exception_bp_sp->GetID());
428 }
429
430 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
431   if (!m_process)
432     return false;
433
434   Target &target(m_process->GetTarget());
435
436   static ConstString s_method_signature(
437       "-[NSDictionary objectForKeyedSubscript:]");
438   static ConstString s_arclite_method_signature(
439       "__arclite_objectForKeyedSubscript");
440
441   SymbolContextList sc_list;
442
443   if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature,
444                                                     eSymbolTypeCode, sc_list) ||
445       target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,
446                                                     eSymbolTypeCode, sc_list))
447     return true;
448   else
449     return false;
450 }
451
452 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
453   Target &target = m_process->GetTarget();
454
455   if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
456     FileSpecList filter_modules;
457     filter_modules.Append(FileSpec("libobjc.A.dylib", false));
458     return target.GetSearchFilterForModuleList(&filter_modules);
459   } else {
460     return LanguageRuntime::CreateExceptionSearchFilter();
461   }
462 }
463
464 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
465   if (!HasReadObjCLibrary()) {
466     std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
467
468     size_t num_modules = module_list.GetSize();
469     for (size_t i = 0; i < num_modules; i++) {
470       auto mod = module_list.GetModuleAtIndex(i);
471       if (IsModuleObjCLibrary(mod)) {
472         ReadObjCLibrary(mod);
473         break;
474       }
475     }
476   }
477 }
478
479 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
480   ReadObjCLibraryIfNeeded(module_list);
481 }