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