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