Coverage Report

Created: 2022-01-25 06:29

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