1 //===-- AppleObjCRuntime.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "AppleObjCRuntime.h"
10 #include "AppleObjCRuntimeV1.h"
11 #include "AppleObjCRuntimeV2.h"
12 #include "AppleObjCTrampolineHandler.h"
13 #include "Plugins/Language/ObjC/NSString.h"
14 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
15 #include "Plugins/Process/Utility/HistoryThread.h"
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/Section.h"
21 #include "lldb/Core/ValueObject.h"
22 #include "lldb/Core/ValueObjectConstResult.h"
23 #include "lldb/DataFormatters/FormattersHelpers.h"
24 #include "lldb/Expression/DiagnosticManager.h"
25 #include "lldb/Expression/FunctionCaller.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/ErrorMessages.h"
35 #include "lldb/Utility/LLDBLog.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/Scalar.h"
38 #include "lldb/Utility/Status.h"
39 #include "lldb/Utility/StreamString.h"
40 #include "clang/AST/Type.h"
41 
42 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
43 
44 #include <vector>
45 
46 using namespace lldb;
47 using namespace lldb_private;
48 
49 LLDB_PLUGIN_DEFINE(AppleObjCRuntime)
50 
51 char AppleObjCRuntime::ID = 0;
52 
53 AppleObjCRuntime::~AppleObjCRuntime() = default;
54 
AppleObjCRuntime(Process * process)55 AppleObjCRuntime::AppleObjCRuntime(Process *process)
56     : ObjCLanguageRuntime(process), m_read_objc_library(false),
57       m_objc_trampoline_handler_up(), m_Foundation_major() {
58   ReadObjCLibraryIfNeeded(process->GetTarget().GetImages());
59 }
60 
Initialize()61 void AppleObjCRuntime::Initialize() {
62   AppleObjCRuntimeV2::Initialize();
63   AppleObjCRuntimeV1::Initialize();
64 }
65 
Terminate()66 void AppleObjCRuntime::Terminate() {
67   AppleObjCRuntimeV2::Terminate();
68   AppleObjCRuntimeV1::Terminate();
69 }
70 
GetObjectDescription(Stream & str,ValueObject & valobj)71 llvm::Error AppleObjCRuntime::GetObjectDescription(Stream &str,
72                                                    ValueObject &valobj) {
73   CompilerType compiler_type(valobj.GetCompilerType());
74   bool is_signed;
75   // ObjC objects can only be pointers (or numbers that actually represents
76   // pointers but haven't been typecast, because reasons..)
77   if (!compiler_type.IsIntegerType(is_signed) && !compiler_type.IsPointerType())
78     return llvm::createStringError("not a pointer type");
79 
80   // Make the argument list: we pass one arg, the address of our pointer, to
81   // the print function.
82   Value val;
83 
84   if (!valobj.ResolveValue(val.GetScalar()))
85     return llvm::createStringError("pointer value could not be resolved");
86 
87   // Value Objects may not have a process in their ExecutionContextRef.  But we
88   // need to have one in the ref we pass down to eventually call description.
89   // Get it from the target if it isn't present.
90   ExecutionContext exe_ctx;
91   if (valobj.GetProcessSP()) {
92     exe_ctx = ExecutionContext(valobj.GetExecutionContextRef());
93   } else {
94     exe_ctx.SetContext(valobj.GetTargetSP(), true);
95     if (!exe_ctx.HasProcessScope())
96       return llvm::createStringError("no process");
97   }
98   return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
99 }
100 
101 llvm::Error
GetObjectDescription(Stream & strm,Value & value,ExecutionContextScope * exe_scope)102 AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value,
103                                        ExecutionContextScope *exe_scope) {
104   if (!m_read_objc_library)
105     return llvm::createStringError("Objective-C runtime not loaded");
106 
107   ExecutionContext exe_ctx;
108   exe_scope->CalculateExecutionContext(exe_ctx);
109   Process *process = exe_ctx.GetProcessPtr();
110   if (!process)
111     return llvm::createStringError("no process");
112 
113   // We need other parts of the exe_ctx, but the processes have to match.
114   assert(m_process == process);
115 
116   // Get the function address for the print function.
117   const Address *function_address = GetPrintForDebuggerAddr();
118   if (!function_address)
119     return llvm::createStringError("no print function");
120 
121   Target *target = exe_ctx.GetTargetPtr();
122   CompilerType compiler_type = value.GetCompilerType();
123   if (compiler_type) {
124     if (!TypeSystemClang::IsObjCObjectPointerType(compiler_type))
125       return llvm::createStringError(
126           "Value doesn't point to an ObjC object.\n");
127   } else {
128     // If it is not a pointer, see if we can make it into a pointer.
129     TypeSystemClangSP scratch_ts_sp =
130         ScratchTypeSystemClang::GetForTarget(*target);
131     if (!scratch_ts_sp)
132       return llvm::createStringError("no scratch type system");
133 
134     CompilerType opaque_type = scratch_ts_sp->GetBasicType(eBasicTypeObjCID);
135     if (!opaque_type)
136       opaque_type =
137           scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
138     // value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
139     value.SetCompilerType(opaque_type);
140   }
141 
142   ValueList arg_value_list;
143   arg_value_list.PushValue(value);
144 
145   // This is the return value:
146   TypeSystemClangSP scratch_ts_sp =
147       ScratchTypeSystemClang::GetForTarget(*target);
148   if (!scratch_ts_sp)
149     return llvm::createStringError("no scratch type system");
150 
151   CompilerType return_compiler_type = scratch_ts_sp->GetCStringType(true);
152   Value ret;
153   //    ret.SetContext(Value::eContextTypeClangType, return_compiler_type);
154   ret.SetCompilerType(return_compiler_type);
155 
156   if (!exe_ctx.GetFramePtr()) {
157     Thread *thread = exe_ctx.GetThreadPtr();
158     if (thread == nullptr) {
159       exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
160       thread = exe_ctx.GetThreadPtr();
161     }
162     if (thread) {
163       exe_ctx.SetFrameSP(thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));
164     }
165   }
166 
167   // Now we're ready to call the function:
168 
169   DiagnosticManager diagnostics;
170   lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
171 
172   if (!m_print_object_caller_up) {
173     Status error;
174     m_print_object_caller_up.reset(
175         exe_scope->CalculateTarget()->GetFunctionCallerForLanguage(
176             eLanguageTypeObjC, return_compiler_type, *function_address,
177             arg_value_list, "objc-object-description", error));
178     if (error.Fail()) {
179       m_print_object_caller_up.reset();
180       return llvm::createStringError(
181           llvm::Twine(
182               "could not get function runner to call print for debugger "
183               "function: ") +
184           error.AsCString());
185     }
186     m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr,
187                                              diagnostics);
188   } else {
189     m_print_object_caller_up->WriteFunctionArguments(
190         exe_ctx, wrapper_struct_addr, arg_value_list, diagnostics);
191   }
192 
193   EvaluateExpressionOptions options;
194   options.SetUnwindOnError(true);
195   options.SetTryAllThreads(true);
196   options.SetStopOthers(true);
197   options.SetIgnoreBreakpoints(true);
198   options.SetTimeout(process->GetUtilityExpressionTimeout());
199   options.SetIsForUtilityExpr(true);
200 
201   ExpressionResults results = m_print_object_caller_up->ExecuteFunction(
202       exe_ctx, &wrapper_struct_addr, options, diagnostics, ret);
203   if (results != eExpressionCompleted)
204     return llvm::createStringError(
205         "could not evaluate print object function: " + toString(results));
206 
207   addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
208 
209   char buf[512];
210   size_t cstr_len = 0;
211   size_t full_buffer_len = sizeof(buf) - 1;
212   size_t curr_len = full_buffer_len;
213   while (curr_len == full_buffer_len) {
214     Status error;
215     curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf,
216                                               sizeof(buf), error);
217     strm.Write(buf, curr_len);
218     cstr_len += curr_len;
219   }
220   if (cstr_len > 0)
221     return llvm::Error::success();
222   return llvm::createStringError("empty object description");
223 }
224 
GetObjCModule()225 lldb::ModuleSP AppleObjCRuntime::GetObjCModule() {
226   ModuleSP module_sp(m_objc_module_wp.lock());
227   if (module_sp)
228     return module_sp;
229 
230   Process *process = GetProcess();
231   if (process) {
232     const ModuleList &modules = process->GetTarget().GetImages();
233     for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
234       module_sp = modules.GetModuleAtIndex(idx);
235       if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) {
236         m_objc_module_wp = module_sp;
237         return module_sp;
238       }
239     }
240   }
241   return ModuleSP();
242 }
243 
GetPrintForDebuggerAddr()244 Address *AppleObjCRuntime::GetPrintForDebuggerAddr() {
245   if (!m_PrintForDebugger_addr) {
246     const ModuleList &modules = m_process->GetTarget().GetImages();
247 
248     SymbolContextList contexts;
249     SymbolContext context;
250 
251     modules.FindSymbolsWithNameAndType(ConstString("_NSPrintForDebugger"),
252                                         eSymbolTypeCode, contexts);
253     if (contexts.IsEmpty()) {
254       modules.FindSymbolsWithNameAndType(ConstString("_CFPrintForDebugger"),
255                                          eSymbolTypeCode, contexts);
256       if (contexts.IsEmpty())
257         return nullptr;
258     }
259 
260     contexts.GetContextAtIndex(0, context);
261 
262     m_PrintForDebugger_addr =
263         std::make_unique<Address>(context.symbol->GetAddress());
264   }
265 
266   return m_PrintForDebugger_addr.get();
267 }
268 
CouldHaveDynamicValue(ValueObject & in_value)269 bool AppleObjCRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
270   return in_value.GetCompilerType().IsPossibleDynamicType(
271       nullptr,
272       false, // do not check C++
273       true); // check ObjC
274 }
275 
GetDynamicTypeAndAddress(ValueObject & in_value,lldb::DynamicValueType use_dynamic,TypeAndOrName & class_type_or_name,Address & address,Value::ValueType & value_type)276 bool AppleObjCRuntime::GetDynamicTypeAndAddress(
277     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
278     TypeAndOrName &class_type_or_name, Address &address,
279     Value::ValueType &value_type) {
280   return false;
281 }
282 
283 TypeAndOrName
FixUpDynamicType(const TypeAndOrName & type_and_or_name,ValueObject & static_value)284 AppleObjCRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
285                                    ValueObject &static_value) {
286   CompilerType static_type(static_value.GetCompilerType());
287   Flags static_type_flags(static_type.GetTypeInfo());
288 
289   TypeAndOrName ret(type_and_or_name);
290   if (type_and_or_name.HasType()) {
291     // The type will always be the type of the dynamic object.  If our parent's
292     // type was a pointer, then our type should be a pointer to the type of the
293     // dynamic object.  If a reference, then the original type should be
294     // okay...
295     CompilerType orig_type = type_and_or_name.GetCompilerType();
296     CompilerType corrected_type = orig_type;
297     if (static_type_flags.AllSet(eTypeIsPointer))
298       corrected_type = orig_type.GetPointerType();
299     ret.SetCompilerType(corrected_type);
300   } else {
301     // If we are here we need to adjust our dynamic type name to include the
302     // correct & or * symbol
303     std::string corrected_name(type_and_or_name.GetName().GetCString());
304     if (static_type_flags.AllSet(eTypeIsPointer))
305       corrected_name.append(" *");
306     // the parent type should be a correctly pointer'ed or referenc'ed type
307     ret.SetCompilerType(static_type);
308     ret.SetName(corrected_name.c_str());
309   }
310   return ret;
311 }
312 
AppleIsModuleObjCLibrary(const ModuleSP & module_sp)313 bool AppleObjCRuntime::AppleIsModuleObjCLibrary(const ModuleSP &module_sp) {
314   if (module_sp) {
315     const FileSpec &module_file_spec = module_sp->GetFileSpec();
316     static ConstString ObjCName("libobjc.A.dylib");
317 
318     if (module_file_spec) {
319       if (module_file_spec.GetFilename() == ObjCName)
320         return true;
321     }
322   }
323   return false;
324 }
325 
326 // we use the version of Foundation to make assumptions about the ObjC runtime
327 // on a target
GetFoundationVersion()328 uint32_t AppleObjCRuntime::GetFoundationVersion() {
329   if (!m_Foundation_major) {
330     const ModuleList &modules = m_process->GetTarget().GetImages();
331     for (uint32_t idx = 0; idx < modules.GetSize(); idx++) {
332       lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx);
333       if (!module_sp)
334         continue;
335       if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),
336                  "Foundation") == 0) {
337         m_Foundation_major = module_sp->GetVersion().getMajor();
338         return *m_Foundation_major;
339       }
340     }
341     return LLDB_INVALID_MODULE_VERSION;
342   } else
343     return *m_Foundation_major;
344 }
345 
GetValuesForGlobalCFBooleans(lldb::addr_t & cf_true,lldb::addr_t & cf_false)346 void AppleObjCRuntime::GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true,
347                                                     lldb::addr_t &cf_false) {
348   cf_true = cf_false = LLDB_INVALID_ADDRESS;
349 }
350 
IsModuleObjCLibrary(const ModuleSP & module_sp)351 bool AppleObjCRuntime::IsModuleObjCLibrary(const ModuleSP &module_sp) {
352   return AppleIsModuleObjCLibrary(module_sp);
353 }
354 
ReadObjCLibrary(const ModuleSP & module_sp)355 bool AppleObjCRuntime::ReadObjCLibrary(const ModuleSP &module_sp) {
356   // Maybe check here and if we have a handler already, and the UUID of this
357   // module is the same as the one in the current module, then we don't have to
358   // reread it?
359   m_objc_trampoline_handler_up = std::make_unique<AppleObjCTrampolineHandler>(
360       m_process->shared_from_this(), module_sp);
361   if (m_objc_trampoline_handler_up != nullptr) {
362     m_read_objc_library = true;
363     return true;
364   } else
365     return false;
366 }
367 
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)368 ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan(Thread &thread,
369                                                             bool stop_others) {
370   ThreadPlanSP thread_plan_sp;
371   if (m_objc_trampoline_handler_up)
372     thread_plan_sp = m_objc_trampoline_handler_up->GetStepThroughDispatchPlan(
373         thread, stop_others);
374   return thread_plan_sp;
375 }
376 
377 // Static Functions
378 ObjCLanguageRuntime::ObjCRuntimeVersions
GetObjCVersion(Process * process,ModuleSP & objc_module_sp)379 AppleObjCRuntime::GetObjCVersion(Process *process, ModuleSP &objc_module_sp) {
380   if (!process)
381     return ObjCRuntimeVersions::eObjC_VersionUnknown;
382 
383   Target &target = process->GetTarget();
384   if (target.GetArchitecture().GetTriple().getVendor() !=
385       llvm::Triple::VendorType::Apple)
386     return ObjCRuntimeVersions::eObjC_VersionUnknown;
387 
388   for (ModuleSP module_sp : target.GetImages().Modules()) {
389     // One tricky bit here is that we might get called as part of the initial
390     // module loading, but before all the pre-run libraries get winnowed from
391     // the module list.  So there might actually be an old and incorrect ObjC
392     // library sitting around in the list, and we don't want to look at that.
393     // That's why we call IsLoadedInTarget.
394 
395     if (AppleIsModuleObjCLibrary(module_sp) &&
396         module_sp->IsLoadedInTarget(&target)) {
397       objc_module_sp = module_sp;
398       ObjectFile *ofile = module_sp->GetObjectFile();
399       if (!ofile)
400         return ObjCRuntimeVersions::eObjC_VersionUnknown;
401 
402       SectionList *sections = module_sp->GetSectionList();
403       if (!sections)
404         return ObjCRuntimeVersions::eObjC_VersionUnknown;
405       SectionSP v1_telltale_section_sp =
406           sections->FindSectionByName(ConstString("__OBJC"));
407       if (v1_telltale_section_sp) {
408         return ObjCRuntimeVersions::eAppleObjC_V1;
409       }
410       return ObjCRuntimeVersions::eAppleObjC_V2;
411     }
412   }
413 
414   return ObjCRuntimeVersions::eObjC_VersionUnknown;
415 }
416 
SetExceptionBreakpoints()417 void AppleObjCRuntime::SetExceptionBreakpoints() {
418   const bool catch_bp = false;
419   const bool throw_bp = true;
420   const bool is_internal = true;
421 
422   if (!m_objc_exception_bp_sp) {
423     m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint(
424         m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp,
425         is_internal);
426     if (m_objc_exception_bp_sp)
427       m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception");
428   } else
429     m_objc_exception_bp_sp->SetEnabled(true);
430 }
431 
ClearExceptionBreakpoints()432 void AppleObjCRuntime::ClearExceptionBreakpoints() {
433   if (!m_process)
434     return;
435 
436   if (m_objc_exception_bp_sp.get()) {
437     m_objc_exception_bp_sp->SetEnabled(false);
438   }
439 }
440 
ExceptionBreakpointsAreSet()441 bool AppleObjCRuntime::ExceptionBreakpointsAreSet() {
442   return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled();
443 }
444 
ExceptionBreakpointsExplainStop(lldb::StopInfoSP stop_reason)445 bool AppleObjCRuntime::ExceptionBreakpointsExplainStop(
446     lldb::StopInfoSP stop_reason) {
447   if (!m_process)
448     return false;
449 
450   if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
451     return false;
452 
453   uint64_t break_site_id = stop_reason->GetValue();
454   return m_process->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
455       break_site_id, m_objc_exception_bp_sp->GetID());
456 }
457 
CalculateHasNewLiteralsAndIndexing()458 bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() {
459   if (!m_process)
460     return false;
461 
462   Target &target(m_process->GetTarget());
463 
464   static ConstString s_method_signature(
465       "-[NSDictionary objectForKeyedSubscript:]");
466   static ConstString s_arclite_method_signature(
467       "__arclite_objectForKeyedSubscript");
468 
469   SymbolContextList sc_list;
470 
471   target.GetImages().FindSymbolsWithNameAndType(s_method_signature,
472                                                 eSymbolTypeCode, sc_list);
473   if (sc_list.IsEmpty())
474     target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature,
475                                                   eSymbolTypeCode, sc_list);
476   return !sc_list.IsEmpty();
477 }
478 
CreateExceptionSearchFilter()479 lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter() {
480   Target &target = m_process->GetTarget();
481 
482   FileSpecList filter_modules;
483   if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
484     filter_modules.Append(std::get<0>(GetExceptionThrowLocation()));
485   }
486   return target.GetSearchFilterForModuleList(&filter_modules);
487 }
488 
GetExceptionObjectForThread(ThreadSP thread_sp)489 ValueObjectSP AppleObjCRuntime::GetExceptionObjectForThread(
490     ThreadSP thread_sp) {
491   auto *cpp_runtime = m_process->GetLanguageRuntime(eLanguageTypeC_plus_plus);
492   if (!cpp_runtime) return ValueObjectSP();
493   auto cpp_exception = cpp_runtime->GetExceptionObjectForThread(thread_sp);
494   if (!cpp_exception) return ValueObjectSP();
495 
496   auto descriptor = GetClassDescriptor(*cpp_exception);
497   if (!descriptor || !descriptor->IsValid()) return ValueObjectSP();
498 
499   while (descriptor) {
500     ConstString class_name(descriptor->GetClassName());
501     if (class_name == "NSException")
502       return cpp_exception;
503     descriptor = descriptor->GetSuperclass();
504   }
505 
506   return ValueObjectSP();
507 }
508 
509 /// Utility method for error handling in GetBacktraceThreadFromException.
510 /// \param msg The message to add to the log.
511 /// \return An invalid ThreadSP to be returned from
512 ///         GetBacktraceThreadFromException.
513 [[nodiscard]]
FailExceptionParsing(llvm::StringRef msg)514 static ThreadSP FailExceptionParsing(llvm::StringRef msg) {
515   Log *log = GetLog(LLDBLog::Language);
516   LLDB_LOG(log, "Failed getting backtrace from exception: {0}", msg);
517   return ThreadSP();
518 }
519 
GetBacktraceThreadFromException(lldb::ValueObjectSP exception_sp)520 ThreadSP AppleObjCRuntime::GetBacktraceThreadFromException(
521     lldb::ValueObjectSP exception_sp) {
522   ValueObjectSP reserved_dict =
523       exception_sp->GetChildMemberWithName("reserved");
524   if (!reserved_dict)
525     return FailExceptionParsing("Failed to get 'reserved' member.");
526 
527   reserved_dict = reserved_dict->GetSyntheticValue();
528   if (!reserved_dict)
529     return FailExceptionParsing("Failed to get synthetic value.");
530 
531   TypeSystemClangSP scratch_ts_sp =
532       ScratchTypeSystemClang::GetForTarget(*exception_sp->GetTargetSP());
533   if (!scratch_ts_sp)
534     return FailExceptionParsing("Failed to get scratch AST.");
535   CompilerType objc_id = scratch_ts_sp->GetBasicType(lldb::eBasicTypeObjCID);
536   ValueObjectSP return_addresses;
537 
538   auto objc_object_from_address = [&exception_sp, &objc_id](uint64_t addr,
539                                                             const char *name) {
540     Value value(addr);
541     value.SetCompilerType(objc_id);
542     auto object = ValueObjectConstResult::Create(
543         exception_sp->GetTargetSP().get(), value, ConstString(name));
544     object = object->GetDynamicValue(eDynamicDontRunTarget);
545     return object;
546   };
547 
548   for (size_t idx = 0; idx < reserved_dict->GetNumChildrenIgnoringErrors();
549        idx++) {
550     ValueObjectSP dict_entry = reserved_dict->GetChildAtIndex(idx);
551 
552     DataExtractor data;
553     data.SetAddressByteSize(dict_entry->GetProcessSP()->GetAddressByteSize());
554     Status error;
555     dict_entry->GetData(data, error);
556     if (error.Fail()) return ThreadSP();
557 
558     lldb::offset_t data_offset = 0;
559     auto dict_entry_key = data.GetAddress(&data_offset);
560     auto dict_entry_value = data.GetAddress(&data_offset);
561 
562     auto key_nsstring = objc_object_from_address(dict_entry_key, "key");
563     StreamString key_summary;
564     if (lldb_private::formatters::NSStringSummaryProvider(
565             *key_nsstring, key_summary, TypeSummaryOptions()) &&
566         !key_summary.Empty()) {
567       if (key_summary.GetString() == "\"callStackReturnAddresses\"") {
568         return_addresses = objc_object_from_address(dict_entry_value,
569                                                     "callStackReturnAddresses");
570         break;
571       }
572     }
573   }
574 
575   if (!return_addresses)
576     return FailExceptionParsing("Failed to get return addresses.");
577   auto frames_value = return_addresses->GetChildMemberWithName("_frames");
578   if (!frames_value)
579     return FailExceptionParsing("Failed to get frames_value.");
580   addr_t frames_addr = frames_value->GetValueAsUnsigned(0);
581   auto count_value = return_addresses->GetChildMemberWithName("_cnt");
582   if (!count_value)
583     return FailExceptionParsing("Failed to get count_value.");
584   size_t count = count_value->GetValueAsUnsigned(0);
585   auto ignore_value = return_addresses->GetChildMemberWithName("_ignore");
586   if (!ignore_value)
587     return FailExceptionParsing("Failed to get ignore_value.");
588   size_t ignore = ignore_value->GetValueAsUnsigned(0);
589 
590   size_t ptr_size = m_process->GetAddressByteSize();
591   std::vector<lldb::addr_t> pcs;
592   for (size_t idx = 0; idx < count; idx++) {
593     Status error;
594     addr_t pc = m_process->ReadPointerFromMemory(
595         frames_addr + (ignore + idx) * ptr_size, error);
596     pcs.push_back(pc);
597   }
598 
599   if (pcs.empty())
600     return FailExceptionParsing("Failed to get PC list.");
601 
602   ThreadSP new_thread_sp(new HistoryThread(*m_process, 0, pcs));
603   m_process->GetExtendedThreadList().AddThread(new_thread_sp);
604   return new_thread_sp;
605 }
606 
607 std::tuple<FileSpec, ConstString>
GetExceptionThrowLocation()608 AppleObjCRuntime::GetExceptionThrowLocation() {
609   return std::make_tuple(
610       FileSpec("libobjc.A.dylib"), ConstString("objc_exception_throw"));
611 }
612 
ReadObjCLibraryIfNeeded(const ModuleList & module_list)613 void AppleObjCRuntime::ReadObjCLibraryIfNeeded(const ModuleList &module_list) {
614   if (!HasReadObjCLibrary()) {
615     std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
616 
617     size_t num_modules = module_list.GetSize();
618     for (size_t i = 0; i < num_modules; i++) {
619       auto mod = module_list.GetModuleAtIndex(i);
620       if (IsModuleObjCLibrary(mod)) {
621         ReadObjCLibrary(mod);
622         break;
623       }
624     }
625   }
626 }
627 
ModulesDidLoad(const ModuleList & module_list)628 void AppleObjCRuntime::ModulesDidLoad(const ModuleList &module_list) {
629   ReadObjCLibraryIfNeeded(module_list);
630 }
631