Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- DynamicLoaderDarwin.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 "DynamicLoaderDarwin.h"
10
11
#include "lldb/Breakpoint/StoppointCallbackContext.h"
12
#include "lldb/Core/Debugger.h"
13
#include "lldb/Core/Module.h"
14
#include "lldb/Core/ModuleSpec.h"
15
#include "lldb/Core/PluginManager.h"
16
#include "lldb/Core/Section.h"
17
#include "lldb/Expression/DiagnosticManager.h"
18
#include "lldb/Host/FileSystem.h"
19
#include "lldb/Host/HostInfo.h"
20
#include "lldb/Symbol/Function.h"
21
#include "lldb/Symbol/ObjectFile.h"
22
#include "lldb/Target/ABI.h"
23
#include "lldb/Target/RegisterContext.h"
24
#include "lldb/Target/StackFrame.h"
25
#include "lldb/Target/Target.h"
26
#include "lldb/Target/Thread.h"
27
#include "lldb/Target/ThreadPlanCallFunction.h"
28
#include "lldb/Target/ThreadPlanRunToAddress.h"
29
#include "lldb/Utility/DataBuffer.h"
30
#include "lldb/Utility/DataBufferHeap.h"
31
#include "lldb/Utility/Log.h"
32
#include "lldb/Utility/State.h"
33
34
#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
35
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
36
37
//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
38
#ifdef ENABLE_DEBUG_PRINTF
39
#include <cstdio>
40
#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
41
#else
42
#define DEBUG_PRINTF(fmt, ...)
43
#endif
44
45
#ifndef __APPLE__
46
#include "Utility/UuidCompatibility.h"
47
#else
48
#include <uuid/uuid.h>
49
#endif
50
51
#include <memory>
52
53
using namespace lldb;
54
using namespace lldb_private;
55
56
// Constructor
57
DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process)
58
    : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(),
59
      m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(),
60
2.60k
      m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {}
61
62
// Destructor
63
2.60k
DynamicLoaderDarwin::~DynamicLoaderDarwin() = default;
64
65
/// Called after attaching a process.
66
///
67
/// Allow DynamicLoader plug-ins to execute some code after
68
/// attaching to a process.
69
2.59k
void DynamicLoaderDarwin::DidAttach() {
70
2.59k
  PrivateInitialize(m_process);
71
2.59k
  DoInitialImageFetch();
72
2.59k
  SetNotificationBreakpoint();
73
2.59k
}
74
75
/// Called after attaching a process.
76
///
77
/// Allow DynamicLoader plug-ins to execute some code after
78
/// attaching to a process.
79
2
void DynamicLoaderDarwin::DidLaunch() {
80
2
  PrivateInitialize(m_process);
81
2
  DoInitialImageFetch();
82
2
  SetNotificationBreakpoint();
83
2
}
84
85
// Clear out the state of this class.
86
2.60k
void DynamicLoaderDarwin::Clear(bool clear_process) {
87
2.60k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
88
2.60k
  if (clear_process)
89
2.60k
    m_process = nullptr;
90
2.60k
  m_dyld_image_infos.clear();
91
2.60k
  m_dyld_image_infos_stop_id = UINT32_MAX;
92
2.60k
  m_dyld.Clear(false);
93
2.60k
}
94
95
ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
96
141k
    ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
97
141k
  if (did_create_ptr)
98
0
    *did_create_ptr = false;
99
100
141k
  Target &target = m_process->GetTarget();
101
141k
  const ModuleList &target_images = target.GetImages();
102
141k
  ModuleSpec module_spec(image_info.file_spec);
103
141k
  module_spec.GetUUID() = image_info.uuid;
104
105
  // macCatalyst support: Request matching os/environment.
106
141k
  {
107
141k
    auto &target_triple = target.GetArchitecture().GetTriple();
108
141k
    if (target_triple.getOS() == llvm::Triple::IOS &&
109
141k
        
target_triple.getEnvironment() == llvm::Triple::MacABI129
) {
110
      // Request the macCatalyst variant of frameworks that have both
111
      // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
112
129
      module_spec.GetArchitecture() = ArchSpec(target_triple);
113
129
    }
114
141k
  }
115
116
141k
  ModuleSP module_sp(target_images.FindFirstModule(module_spec));
117
118
141k
  if (module_sp && 
!module_spec.GetUUID().IsValid()7.74k
&&
119
141k
      
!module_sp->GetUUID().IsValid()0
) {
120
    // No UUID, we must rely upon the cached module modification time and the
121
    // modification time of the file on disk
122
0
    if (module_sp->GetModificationTime() !=
123
0
        FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
124
0
      module_sp.reset();
125
0
  }
126
127
141k
  if (module_sp || 
!can_create133k
)
128
7.74k
    return module_sp;
129
130
133k
  if (HostInfo::GetArchitecture().IsCompatibleMatch(target.GetArchitecture())) {
131
    // When debugging on the host, we are most likely using the same shared
132
    // cache as our inferior. The dylibs from the shared cache might not
133
    // exist on the filesystem, so let's use the images in our own memory
134
    // to create the modules.
135
    // Check if the requested image is in our shared cache.
136
133k
    SharedCacheImageInfo image_info =
137
133k
        HostInfo::GetSharedCacheImageInfo(module_spec.GetFileSpec().GetPath());
138
139
    // If we found it and it has the correct UUID, let's proceed with
140
    // creating a module from the memory contents.
141
133k
    if (image_info.uuid &&
142
133k
        
(127k
!module_spec.GetUUID()127k
||
module_spec.GetUUID() == image_info.uuid127k
)) {
143
127k
      ModuleSpec shared_cache_spec(module_spec.GetFileSpec(), image_info.uuid,
144
127k
                                   image_info.data_sp);
145
127k
      module_sp =
146
127k
          target.GetOrCreateModule(shared_cache_spec, false /* notify */);
147
127k
    }
148
133k
  }
149
  // We'll call Target::ModulesDidLoad after all the modules have been
150
  // added to the target, don't let it be called for every one.
151
133k
  if (!module_sp)
152
5.40k
    module_sp = target.GetOrCreateModule(module_spec, false /* notify */);
153
133k
  if (!module_sp || 
module_sp->GetObjectFile() == nullptr133k
)
154
2
    module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
155
2
                                                image_info.address);
156
157
133k
  if (did_create_ptr)
158
0
    *did_create_ptr = (bool)module_sp;
159
160
133k
  return module_sp;
161
141k
}
162
163
void DynamicLoaderDarwin::UnloadImages(
164
27
    const std::vector<lldb::addr_t> &solib_addresses) {
165
27
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
166
27
  if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
167
0
    return;
168
169
27
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
170
27
  Target &target = m_process->GetTarget();
171
27
  LLDB_LOGF(log, "Removing %" PRId64 " modules.",
172
27
            (uint64_t)solib_addresses.size());
173
174
27
  ModuleList unloaded_module_list;
175
176
27
  for (addr_t solib_addr : solib_addresses) {
177
27
    Address header;
178
27
    if (header.SetLoadAddress(solib_addr, &target)) {
179
27
      if (header.GetOffset() == 0) {
180
27
        ModuleSP module_to_remove(header.GetModule());
181
27
        if (module_to_remove.get()) {
182
27
          LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
183
          // remove the sections from the Target
184
27
          UnloadSections(module_to_remove);
185
          // add this to the list of modules to remove
186
27
          unloaded_module_list.AppendIfNeeded(module_to_remove);
187
          // remove the entry from the m_dyld_image_infos
188
27
          ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
189
1.16k
          for (pos = m_dyld_image_infos.begin(); pos != end; 
pos++1.13k
) {
190
1.16k
            if (solib_addr == (*pos).address) {
191
27
              m_dyld_image_infos.erase(pos);
192
27
              break;
193
27
            }
194
1.16k
          }
195
27
        }
196
27
      }
197
27
    }
198
27
  }
199
200
27
  if (unloaded_module_list.GetSize() > 0) {
201
27
    if (log) {
202
0
      log->PutCString("Unloaded:");
203
0
      unloaded_module_list.LogUUIDAndPaths(
204
0
          log, "DynamicLoaderDarwin::UnloadModules");
205
0
    }
206
27
    m_process->GetTarget().GetImages().Remove(unloaded_module_list);
207
27
    m_dyld_image_infos_stop_id = m_process->GetStopID();
208
27
  }
209
27
}
210
211
2.59k
void DynamicLoaderDarwin::UnloadAllImages() {
212
2.59k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
213
2.59k
  ModuleList unloaded_modules_list;
214
215
2.59k
  Target &target = m_process->GetTarget();
216
2.59k
  const ModuleList &target_modules = target.GetImages();
217
2.59k
  std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
218
219
2.59k
  ModuleSP dyld_sp(GetDYLDModule());
220
132k
  for (ModuleSP module_sp : target_modules.Modules()) {
221
    // Don't remove dyld - else we'll lose our breakpoint notifying us about
222
    // libraries being re-loaded...
223
132k
    if (module_sp && module_sp != dyld_sp) {
224
132k
      UnloadSections(module_sp);
225
132k
      unloaded_modules_list.Append(module_sp);
226
132k
    }
227
132k
  }
228
229
2.59k
  if (unloaded_modules_list.GetSize() != 0) {
230
2.56k
    if (log) {
231
0
      log->PutCString("Unloaded:");
232
0
      unloaded_modules_list.LogUUIDAndPaths(
233
0
          log, "DynamicLoaderDarwin::UnloadAllImages");
234
0
    }
235
2.56k
    target.GetImages().Remove(unloaded_modules_list);
236
2.56k
    m_dyld_image_infos.clear();
237
2.56k
    m_dyld_image_infos_stop_id = m_process->GetStopID();
238
2.56k
  }
239
2.59k
}
240
241
// Update the load addresses for all segments in MODULE using the updated INFO
242
// that is passed in.
243
bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
244
141k
                                                 ImageInfo &info) {
245
141k
  bool changed = false;
246
141k
  if (module) {
247
141k
    ObjectFile *image_object_file = module->GetObjectFile();
248
141k
    if (
image_object_file141k
) {
249
141k
      SectionList *section_list = image_object_file->GetSectionList();
250
141k
      if (section_list) {
251
141k
        std::vector<uint32_t> inaccessible_segment_indexes;
252
        // We now know the slide amount, so go through all sections and update
253
        // the load addresses with the correct values.
254
141k
        const size_t num_segments = info.segments.size();
255
584k
        for (size_t i = 0; i < num_segments; 
++i443k
) {
256
          // Only load a segment if it has protections. Things like __PAGEZERO
257
          // don't have any protections, and they shouldn't be slid
258
443k
          SectionSP section_sp(
259
443k
              section_list->FindSectionByName(info.segments[i].name));
260
261
443k
          if (info.segments[i].maxprot == 0) {
262
7.74k
            inaccessible_segment_indexes.push_back(i);
263
435k
          } else {
264
435k
            const addr_t new_section_load_addr =
265
435k
                info.segments[i].vmaddr + info.slide;
266
435k
            static ConstString g_section_name_LINKEDIT("__LINKEDIT");
267
268
435k
            if (section_sp) {
269
              // __LINKEDIT sections from files in the shared cache can overlap
270
              // so check to see what the segment name is and pass "false" so
271
              // we don't warn of overlapping "Section" objects, and "true" for
272
              // all other sections.
273
435k
              const bool warn_multiple =
274
435k
                  section_sp->GetName() != g_section_name_LINKEDIT;
275
276
435k
              changed = m_process->GetTarget().SetSectionLoadAddress(
277
435k
                  section_sp, new_section_load_addr, warn_multiple);
278
435k
            } 
279
435k
          }
280
443k
        }
281
282
        // If the loaded the file (it changed) and we have segments that are
283
        // not readable or writeable, add them to the invalid memory region
284
        // cache for the process. This will typically only be the __PAGEZERO
285
        // segment in the main executable. We might be able to apply this more
286
        // generally to more sections that have no protections in the future,
287
        // but for now we are going to just do __PAGEZERO.
288
141k
        if (changed && 
!inaccessible_segment_indexes.empty()133k
) {
289
5.17k
          for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); 
++i2.58k
) {
290
2.58k
            const uint32_t seg_idx = inaccessible_segment_indexes[i];
291
2.58k
            SectionSP section_sp(
292
2.58k
                section_list->FindSectionByName(info.segments[seg_idx].name));
293
294
2.58k
            if (section_sp) {
295
2.58k
              static ConstString g_pagezero_section_name("__PAGEZERO");
296
2.58k
              if (g_pagezero_section_name == section_sp->GetName()) {
297
                // __PAGEZERO never slides...
298
2.58k
                const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
299
2.58k
                const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
300
2.58k
                Process::LoadRange pagezero_range(vmaddr, vmsize);
301
2.58k
                m_process->AddInvalidMemoryRegion(pagezero_range);
302
2.58k
              }
303
2.58k
            }
304
2.58k
          }
305
2.58k
        }
306
141k
      }
307
141k
    }
308
141k
  }
309
  // We might have an in memory image that was loaded as soon as it was created
310
141k
  if (info.load_stop_id == m_process->GetStopID())
311
5.17k
    changed = true;
312
135k
  else if (changed) {
313
    // Update the stop ID when this library was updated
314
133k
    info.load_stop_id = m_process->GetStopID();
315
133k
  }
316
141k
  return changed;
317
141k
}
318
319
// Unload the segments in MODULE using the INFO that is passed in.
320
bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
321
0
                                               ImageInfo &info) {
322
0
  bool changed = false;
323
0
  if (module) {
324
0
    ObjectFile *image_object_file = module->GetObjectFile();
325
0
    if (image_object_file) {
326
0
      SectionList *section_list = image_object_file->GetSectionList();
327
0
      if (section_list) {
328
0
        const size_t num_segments = info.segments.size();
329
0
        for (size_t i = 0; i < num_segments; ++i) {
330
0
          SectionSP section_sp(
331
0
              section_list->FindSectionByName(info.segments[i].name));
332
0
          if (section_sp) {
333
0
            const addr_t old_section_load_addr =
334
0
                info.segments[i].vmaddr + info.slide;
335
0
            if (m_process->GetTarget().SetSectionUnloaded(
336
0
                    section_sp, old_section_load_addr))
337
0
              changed = true;
338
0
          } else {
339
0
            Host::SystemLog(Host::eSystemLogWarning,
340
0
                            "warning: unable to find and unload segment named "
341
0
                            "'%s' in '%s' in macosx dynamic loader plug-in.\n",
342
0
                            info.segments[i].name.AsCString("<invalid>"),
343
0
                            image_object_file->GetFileSpec().GetPath().c_str());
344
0
          }
345
0
        }
346
0
      }
347
0
    }
348
0
  }
349
0
  return changed;
350
0
}
351
352
// Given a JSON dictionary (from debugserver, most likely) of binary images
353
// loaded in the inferior process, add the images to the ImageInfo collection.
354
355
bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
356
    StructuredData::ObjectSP image_details,
357
5.20k
    ImageInfo::collection &image_infos) {
358
5.20k
  StructuredData::ObjectSP images_sp =
359
5.20k
      image_details->GetAsDictionary()->GetValueForKey("images");
360
5.20k
  if (images_sp.get() == nullptr)
361
0
    return false;
362
363
5.20k
  image_infos.resize(images_sp->GetAsArray()->GetSize());
364
365
141k
  for (size_t i = 0; i < image_infos.size(); 
i++135k
) {
366
135k
    StructuredData::ObjectSP image_sp =
367
135k
        images_sp->GetAsArray()->GetItemAtIndex(i);
368
135k
    if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
369
0
      return false;
370
135k
    StructuredData::Dictionary *image = image_sp->GetAsDictionary();
371
    // clang-format off
372
135k
    if (!image->HasKey("load_address") ||
373
135k
        !image->HasKey("pathname") ||
374
135k
        !image->HasKey("mod_date") ||
375
135k
        !image->HasKey("mach_header") ||
376
135k
        image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
377
135k
        !image->HasKey("segments") ||
378
135k
        image->GetValueForKey("segments")->GetAsArray() == nullptr ||
379
135k
        !image->HasKey("uuid")) {
380
0
      return false;
381
0
    }
382
    // clang-format on
383
135k
    image_infos[i].address =
384
135k
        image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
385
135k
    image_infos[i].mod_date =
386
135k
        image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
387
135k
    image_infos[i].file_spec.SetFile(
388
135k
        image->GetValueForKey("pathname")->GetAsString()->GetValue(),
389
135k
        FileSpec::Style::native);
390
391
135k
    StructuredData::Dictionary *mh =
392
135k
        image->GetValueForKey("mach_header")->GetAsDictionary();
393
135k
    image_infos[i].header.magic =
394
135k
        mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
395
135k
    image_infos[i].header.cputype =
396
135k
        mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
397
135k
    image_infos[i].header.cpusubtype =
398
135k
        mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
399
135k
    image_infos[i].header.filetype =
400
135k
        mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
401
402
135k
    if (image->HasKey("min_version_os_name")) {
403
135k
      std::string os_name =
404
135k
          std::string(image->GetValueForKey("min_version_os_name")
405
135k
                          ->GetAsString()
406
135k
                          ->GetValue());
407
135k
      if (os_name == "macosx")
408
135k
        image_infos[i].os_type = llvm::Triple::MacOSX;
409
117
      else if (os_name == "ios" || os_name == "iphoneos")
410
0
        image_infos[i].os_type = llvm::Triple::IOS;
411
117
      else if (os_name == "tvos")
412
0
        image_infos[i].os_type = llvm::Triple::TvOS;
413
117
      else if (os_name == "watchos")
414
0
        image_infos[i].os_type = llvm::Triple::WatchOS;
415
      // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
416
      // NEED_BRIDGEOS_TRIPLE   image_infos[i].os_type = llvm::Triple::BridgeOS;
417
117
      else if (os_name == "maccatalyst") {
418
117
        image_infos[i].os_type = llvm::Triple::IOS;
419
117
        image_infos[i].os_env = llvm::Triple::MacABI;
420
117
      } else 
if (0
os_name == "iossimulator"0
) {
421
0
        image_infos[i].os_type = llvm::Triple::IOS;
422
0
        image_infos[i].os_env = llvm::Triple::Simulator;
423
0
      } else if (os_name == "tvossimulator") {
424
0
        image_infos[i].os_type = llvm::Triple::TvOS;
425
0
        image_infos[i].os_env = llvm::Triple::Simulator;
426
0
      } else if (os_name == "watchossimulator") {
427
0
        image_infos[i].os_type = llvm::Triple::WatchOS;
428
0
        image_infos[i].os_env = llvm::Triple::Simulator;
429
0
      }
430
135k
    }
431
135k
    if (image->HasKey("min_version_os_sdk")) {
432
135k
      image_infos[i].min_version_os_sdk =
433
135k
          std::string(image->GetValueForKey("min_version_os_sdk")
434
135k
                          ->GetAsString()
435
135k
                          ->GetValue());
436
135k
    }
437
438
    // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
439
    // currently send them in the reply.
440
441
135k
    if (mh->HasKey("flags"))
442
135k
      image_infos[i].header.flags =
443
135k
          mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
444
0
    else
445
0
      image_infos[i].header.flags = 0;
446
447
135k
    if (mh->HasKey("ncmds"))
448
0
      image_infos[i].header.ncmds =
449
0
          mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
450
135k
    else
451
135k
      image_infos[i].header.ncmds = 0;
452
453
135k
    if (mh->HasKey("sizeofcmds"))
454
0
      image_infos[i].header.sizeofcmds =
455
0
          mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
456
135k
    else
457
135k
      image_infos[i].header.sizeofcmds = 0;
458
459
135k
    StructuredData::Array *segments =
460
135k
        image->GetValueForKey("segments")->GetAsArray();
461
135k
    uint32_t segcount = segments->GetSize();
462
556k
    for (size_t j = 0; j < segcount; 
j++420k
) {
463
420k
      Segment segment;
464
420k
      StructuredData::Dictionary *seg =
465
420k
          segments->GetItemAtIndex(j)->GetAsDictionary();
466
420k
      segment.name =
467
420k
          ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
468
420k
      segment.vmaddr =
469
420k
          seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
470
420k
      segment.vmsize =
471
420k
          seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
472
420k
      segment.fileoff =
473
420k
          seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
474
420k
      segment.filesize =
475
420k
          seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
476
420k
      segment.maxprot =
477
420k
          seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
478
479
      // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
480
      // currently send them in the reply.
481
482
420k
      if (seg->HasKey("initprot"))
483
0
        segment.initprot =
484
0
            seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
485
420k
      else
486
420k
        segment.initprot = 0;
487
488
420k
      if (seg->HasKey("flags"))
489
0
        segment.flags =
490
0
            seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
491
420k
      else
492
420k
        segment.flags = 0;
493
494
420k
      if (seg->HasKey("nsects"))
495
0
        segment.nsects =
496
0
            seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
497
420k
      else
498
420k
        segment.nsects = 0;
499
500
420k
      image_infos[i].segments.push_back(segment);
501
420k
    }
502
503
135k
    image_infos[i].uuid.SetFromOptionalStringRef(
504
135k
        image->GetValueForKey("uuid")->GetAsString()->GetValue());
505
506
    // All sections listed in the dyld image info structure will all either be
507
    // fixed up already, or they will all be off by a single slide amount that
508
    // is determined by finding the first segment that is at file offset zero
509
    // which also has bytes (a file size that is greater than zero) in the
510
    // object file.
511
512
    // Determine the slide amount (if any)
513
135k
    const size_t num_sections = image_infos[i].segments.size();
514
141k
    for (size_t k = 0; k < num_sections; 
++k5.15k
) {
515
      // Iterate through the object file sections to find the first section
516
      // that starts of file offset zero and that has bytes in the file...
517
141k
      if ((image_infos[i].segments[k].fileoff == 0 &&
518
141k
           
image_infos[i].segments[k].filesize > 013.1k
) ||
519
141k
          
(image_infos[i].segments[k].name == "__TEXT")133k
) {
520
135k
        image_infos[i].slide =
521
135k
            image_infos[i].address - image_infos[i].segments[k].vmaddr;
522
        // We have found the slide amount, so we can exit this for loop.
523
135k
        break;
524
135k
      }
525
141k
    }
526
135k
  }
527
528
5.20k
  return true;
529
5.20k
}
530
531
void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
532
5.20k
    ImageInfo::collection &image_infos) {
533
5.20k
  uint32_t exe_idx = UINT32_MAX;
534
5.20k
  uint32_t dyld_idx = UINT32_MAX;
535
5.20k
  Target &target = m_process->GetTarget();
536
5.20k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
537
5.20k
  ConstString g_dyld_sim_filename("dyld_sim");
538
539
5.20k
  ArchSpec target_arch = target.GetArchitecture();
540
5.20k
  const size_t image_infos_size = image_infos.size();
541
141k
  for (size_t i = 0; i < image_infos_size; 
i++135k
) {
542
135k
    if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
543
      // In a "simulator" process we will have two dyld modules -- 
544
      // a "dyld" that we want to keep track of, and a "dyld_sim" which 
545
      // we don't need to keep track of here.  dyld_sim will have a non-macosx
546
      // OS.
547
2.58k
      if (target_arch.GetTriple().getEnvironment() == llvm::Triple::Simulator &&
548
2.58k
          
image_infos[i].os_type != llvm::Triple::OSType::MacOSX0
) {
549
0
        continue;
550
0
      }
551
552
2.58k
      dyld_idx = i;
553
2.58k
    } 
554
135k
    if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
555
5.15k
      exe_idx = i;
556
5.15k
    }
557
135k
  }
558
559
  // Set the target executable if we haven't found one so far.
560
5.20k
  if (exe_idx != UINT32_MAX && 
!target.GetExecutableModule()5.15k
) {
561
2.58k
    const bool can_create = true;
562
2.58k
    ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
563
2.58k
                                                        can_create, nullptr));
564
2.58k
    if (exe_module_sp) {
565
2.58k
      LLDB_LOGF(log, "Found executable module: %s",
566
2.58k
                exe_module_sp->GetFileSpec().GetPath().c_str());
567
2.58k
      target.GetImages().AppendIfNeeded(exe_module_sp);
568
2.58k
      UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
569
2.58k
      if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
570
0
        target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
571
0
      }
572
2.58k
    }
573
2.58k
  }
574
575
5.20k
  if (dyld_idx != UINT32_MAX) {
576
2.58k
    const bool can_create = true;
577
2.58k
    ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx],
578
2.58k
                                                    can_create, nullptr);
579
2.58k
    if (dyld_sp.get()) {
580
2.58k
      LLDB_LOGF(log, "Found dyld module: %s",
581
2.58k
                dyld_sp->GetFileSpec().GetPath().c_str());
582
2.58k
      target.GetImages().AppendIfNeeded(dyld_sp);
583
2.58k
      UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
584
2.58k
      SetDYLDModule(dyld_sp);
585
2.58k
    }
586
2.58k
  }
587
5.20k
}
588
589
void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
590
0
    ImageInfo &image_info) {
591
0
  if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
592
0
    const bool can_create = true;
593
0
    ModuleSP dyld_sp =
594
0
        FindTargetModuleForImageInfo(image_info, can_create, nullptr);
595
0
    if (dyld_sp.get()) {
596
0
      Target &target = m_process->GetTarget();
597
0
      target.GetImages().AppendIfNeeded(dyld_sp);
598
0
      UpdateImageLoadAddress(dyld_sp.get(), image_info);
599
0
      SetDYLDModule(dyld_sp);
600
0
    }
601
0
  }
602
0
}
603
604
2.58k
void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
605
2.58k
  m_dyld_module_wp = dyld_module_sp;
606
2.58k
}
607
608
5.18k
ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
609
5.18k
  ModuleSP dyld_sp(m_dyld_module_wp.lock());
610
5.18k
  return dyld_sp;
611
5.18k
}
612
613
bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
614
5.20k
    ImageInfo::collection &image_infos) {
615
5.20k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
616
  // Now add these images to the main list.
617
5.20k
  ModuleList loaded_module_list;
618
5.20k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
619
5.20k
  Target &target = m_process->GetTarget();
620
5.20k
  ModuleList &target_images = target.GetImages();
621
622
141k
  for (uint32_t idx = 0; idx < image_infos.size(); 
++idx135k
) {
623
135k
    if (log) {
624
0
      LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
625
0
                image_infos[idx].address);
626
0
      image_infos[idx].PutToLog(log);
627
0
    }
628
629
135k
    m_dyld_image_infos.push_back(image_infos[idx]);
630
631
135k
    ModuleSP image_module_sp(
632
135k
        FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
633
634
135k
    if (image_module_sp) {
635
135k
      ObjectFile *objfile = image_module_sp->GetObjectFile();
636
135k
      if (objfile) {
637
135k
        SectionList *sections = objfile->GetSectionList();
638
135k
        if (sections) {
639
135k
          ConstString commpage_dbstr("__commpage");
640
135k
          Section *commpage_section =
641
135k
              sections->FindSectionByName(commpage_dbstr).get();
642
135k
          if (commpage_section) {
643
0
            ModuleSpec module_spec(objfile->GetFileSpec(),
644
0
                                   image_infos[idx].GetArchitecture());
645
0
            module_spec.GetObjectName() = commpage_dbstr;
646
0
            ModuleSP commpage_image_module_sp(
647
0
                target_images.FindFirstModule(module_spec));
648
0
            if (!commpage_image_module_sp) {
649
0
              module_spec.SetObjectOffset(objfile->GetFileOffset() +
650
0
                                          commpage_section->GetFileOffset());
651
0
              module_spec.SetObjectSize(objfile->GetByteSize());
652
0
              commpage_image_module_sp = target.GetOrCreateModule(module_spec, 
653
0
                                                               true /* notify */);
654
0
              if (!commpage_image_module_sp ||
655
0
                  commpage_image_module_sp->GetObjectFile() == nullptr) {
656
0
                commpage_image_module_sp = m_process->ReadModuleFromMemory(
657
0
                    image_infos[idx].file_spec, image_infos[idx].address);
658
                // Always load a memory image right away in the target in case
659
                // we end up trying to read the symbol table from memory... The
660
                // __LINKEDIT will need to be mapped so we can figure out where
661
                // the symbol table bits are...
662
0
                bool changed = false;
663
0
                UpdateImageLoadAddress(commpage_image_module_sp.get(),
664
0
                                       image_infos[idx]);
665
0
                target.GetImages().Append(commpage_image_module_sp);
666
0
                if (changed) {
667
0
                  image_infos[idx].load_stop_id = m_process->GetStopID();
668
0
                  loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
669
0
                }
670
0
              }
671
0
            }
672
0
          }
673
135k
        }
674
135k
      }
675
676
      // UpdateImageLoadAddress will return true if any segments change load
677
      // address. We need to check this so we don't mention that all loaded
678
      // shared libraries are newly loaded each time we hit out dyld breakpoint
679
      // since dyld will list all shared libraries each time.
680
135k
      if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
681
133k
        target_images.AppendIfNeeded(image_module_sp);
682
133k
        loaded_module_list.AppendIfNeeded(image_module_sp);
683
133k
      }
684
685
      // To support macCatalyst and legacy iOS simulator,
686
      // update the module's platform with the DYLD info.
687
135k
      ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
688
135k
      auto &dyld_triple = dyld_spec.GetTriple();
689
135k
      if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
690
135k
           
dyld_triple.getOS() == llvm::Triple::IOS117
) ||
691
135k
          
(135k
dyld_triple.getEnvironment() == llvm::Triple::Simulator135k
&&
692
135k
           
(0
dyld_triple.getOS() == llvm::Triple::IOS0
||
693
0
            dyld_triple.getOS() == llvm::Triple::TvOS ||
694
0
            dyld_triple.getOS() == llvm::Triple::WatchOS)))
695
117
        image_module_sp->MergeArchitecture(dyld_spec);
696
135k
    }
697
135k
  }
698
699
5.20k
  if (loaded_module_list.GetSize() > 0) {
700
5.20k
    if (log)
701
0
      loaded_module_list.LogUUIDAndPaths(log,
702
0
                                         "DynamicLoaderDarwin::ModulesDidLoad");
703
5.20k
    m_process->GetTarget().ModulesDidLoad(loaded_module_list);
704
5.20k
  }
705
5.20k
  return true;
706
5.20k
}
707
708
// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
709
// functions written in hand-written assembly, and also have hand-written
710
// unwind information in the eh_frame section.  Normally we prefer analyzing
711
// the assembly instructions of a currently executing frame to unwind from that
712
// frame -- but on hand-written functions this profiling can fail.  We should
713
// use the eh_frame instructions for these functions all the time.
714
//
715
// As an aside, it would be better if the eh_frame entries had a flag (or were
716
// extensible so they could have an Apple-specific flag) which indicates that
717
// the instructions are asynchronous -- accurate at every instruction, instead
718
// of our normal default assumption that they are not.
719
720
46.1k
bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
721
46.1k
  ModuleSP module_sp;
722
46.1k
  if (sym_ctx.symbol) {
723
46.1k
    module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
724
46.1k
  }
725
46.1k
  if (module_sp.get() == nullptr && 
sym_ctx.function1
) {
726
1
    module_sp =
727
1
        sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
728
1
  }
729
46.1k
  if (module_sp.get() == nullptr)
730
0
    return false;
731
732
46.1k
  ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
733
46.1k
  return objc_runtime != nullptr &&
734
46.1k
         
objc_runtime->IsModuleObjCLibrary(module_sp)40.9k
;
735
46.1k
}
736
737
// Dump a Segment to the file handle provided.
738
void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
739
0
                                            lldb::addr_t slide) const {
740
0
  if (log) {
741
0
    if (slide == 0)
742
0
      LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
743
0
                name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
744
0
    else
745
0
      LLDB_LOGF(log,
746
0
                "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
747
0
                ") slide = 0x%" PRIx64,
748
0
                name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
749
0
                slide);
750
0
  }
751
0
}
752
753
135k
lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
754
  // Update the module's platform with the DYLD info.
755
135k
  lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
756
135k
                                   header.cpusubtype);
757
135k
  if (os_env == llvm::Triple::MacABI && 
os_type == llvm::Triple::IOS117
) {
758
117
    llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
759
117
                        "-apple-ios" + min_version_os_sdk + "-macabi");
760
117
    ArchSpec maccatalyst_spec(triple);
761
117
    if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
762
117
      arch_spec.MergeFrom(maccatalyst_spec);
763
117
  }
764
135k
  if (os_env == llvm::Triple::Simulator &&
765
135k
      
(0
os_type == llvm::Triple::IOS0
||
os_type == llvm::Triple::TvOS0
||
766
0
       os_type == llvm::Triple::WatchOS)) {
767
0
    llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
768
0
                        "-apple-" + llvm::Triple::getOSTypeName(os_type) +
769
0
                        min_version_os_sdk + "-simulator");
770
0
    ArchSpec sim_spec(triple);
771
0
    if (arch_spec.IsCompatibleMatch(sim_spec))
772
0
      arch_spec.MergeFrom(sim_spec);
773
0
  }
774
135k
  return arch_spec;
775
135k
}
776
777
const DynamicLoaderDarwin::Segment *
778
0
DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
779
0
  const size_t num_segments = segments.size();
780
0
  for (size_t i = 0; i < num_segments; ++i) {
781
0
    if (segments[i].name == name)
782
0
      return &segments[i];
783
0
  }
784
0
  return nullptr;
785
0
}
786
787
// Dump an image info structure to the file handle provided.
788
0
void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
789
0
  if (!log)
790
0
    return;
791
0
  if (address == LLDB_INVALID_ADDRESS) {
792
0
    LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
793
0
             uuid.GetAsString(), file_spec.GetPath());
794
0
  } else {
795
0
    LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
796
0
             address, mod_date, uuid.GetAsString(), file_spec.GetPath());
797
0
    for (uint32_t i = 0; i < segments.size(); ++i)
798
0
      segments[i].PutToLog(log, slide);
799
0
  }
800
0
}
801
802
2.60k
void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
803
2.60k
  DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
804
2.60k
               StateAsCString(m_process->GetState()));
805
2.60k
  Clear(true);
806
2.60k
  m_process = process;
807
2.60k
  m_process->GetTarget().ClearAllLoadedSections();
808
2.60k
}
809
810
// Member function that gets called when the process state changes.
811
void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
812
0
                                                     StateType state) {
813
0
  DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
814
0
               StateAsCString(state));
815
0
  switch (state) {
816
0
  case eStateConnected:
817
0
  case eStateAttaching:
818
0
  case eStateLaunching:
819
0
  case eStateInvalid:
820
0
  case eStateUnloaded:
821
0
  case eStateExited:
822
0
  case eStateDetached:
823
0
    Clear(false);
824
0
    break;
825
826
0
  case eStateStopped:
827
    // Keep trying find dyld and set our notification breakpoint each time we
828
    // stop until we succeed
829
0
    if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
830
0
      if (NeedToDoInitialImageFetch())
831
0
        DoInitialImageFetch();
832
833
0
      SetNotificationBreakpoint();
834
0
    }
835
0
    break;
836
837
0
  case eStateRunning:
838
0
  case eStateStepping:
839
0
  case eStateCrashed:
840
0
  case eStateSuspended:
841
0
    break;
842
0
  }
843
0
}
844
845
ThreadPlanSP
846
DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
847
513
                                                  bool stop_others) {
848
513
  ThreadPlanSP thread_plan_sp;
849
513
  StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
850
513
  const SymbolContext &current_context =
851
513
      current_frame->GetSymbolContext(eSymbolContextSymbol);
852
513
  Symbol *current_symbol = current_context.symbol;
853
513
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
854
513
  TargetSP target_sp(thread.CalculateTarget());
855
856
513
  if (current_symbol != nullptr) {
857
513
    std::vector<Address> addresses;
858
859
513
    if (current_symbol->IsTrampoline()) {
860
43
      ConstString trampoline_name =
861
43
          current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
862
863
43
      if (trampoline_name) {
864
43
        const ModuleList &images = target_sp->GetImages();
865
866
43
        SymbolContextList code_symbols;
867
43
        images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
868
43
                                          code_symbols);
869
43
        size_t num_code_symbols = code_symbols.GetSize();
870
871
43
        if (num_code_symbols > 0) {
872
74
          for (uint32_t i = 0; i < num_code_symbols; 
i++37
) {
873
37
            SymbolContext context;
874
37
            AddressRange addr_range;
875
37
            if (code_symbols.GetContextAtIndex(i, context)) {
876
37
              context.GetAddressRange(eSymbolContextEverything, 0, false,
877
37
                                      addr_range);
878
37
              addresses.push_back(addr_range.GetBaseAddress());
879
37
              if (log) {
880
0
                addr_t load_addr =
881
0
                    addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
882
883
0
                LLDB_LOGF(log,
884
0
                          "Found a trampoline target symbol at 0x%" PRIx64 ".",
885
0
                          load_addr);
886
0
              }
887
37
            }
888
37
          }
889
37
        }
890
891
43
        SymbolContextList reexported_symbols;
892
43
        images.FindSymbolsWithNameAndType(
893
43
            trampoline_name, eSymbolTypeReExported, reexported_symbols);
894
43
        size_t num_reexported_symbols = reexported_symbols.GetSize();
895
43
        if (num_reexported_symbols > 0) {
896
6
          for (uint32_t i = 0; i < num_reexported_symbols; 
i++3
) {
897
3
            SymbolContext context;
898
3
            if (reexported_symbols.GetContextAtIndex(i, context)) {
899
3
              if (context.symbol) {
900
3
                Symbol *actual_symbol =
901
3
                    context.symbol->ResolveReExportedSymbol(*target_sp.get());
902
3
                if (actual_symbol) {
903
3
                  const Address actual_symbol_addr =
904
3
                      actual_symbol->GetAddress();
905
3
                  if (actual_symbol_addr.IsValid()) {
906
3
                    addresses.push_back(actual_symbol_addr);
907
3
                    if (log) {
908
0
                      lldb::addr_t load_addr =
909
0
                          actual_symbol_addr.GetLoadAddress(target_sp.get());
910
0
                      LLDB_LOGF(
911
0
                          log,
912
0
                          "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
913
0
                          actual_symbol->GetName().GetCString(), load_addr);
914
0
                    }
915
3
                  }
916
3
                }
917
3
              }
918
3
            }
919
3
          }
920
3
        }
921
922
43
        SymbolContextList indirect_symbols;
923
43
        images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
924
43
                                          indirect_symbols);
925
43
        size_t num_indirect_symbols = indirect_symbols.GetSize();
926
43
        if (num_indirect_symbols > 0) {
927
6
          for (uint32_t i = 0; i < num_indirect_symbols; 
i++3
) {
928
3
            SymbolContext context;
929
3
            AddressRange addr_range;
930
3
            if (indirect_symbols.GetContextAtIndex(i, context)) {
931
3
              context.GetAddressRange(eSymbolContextEverything, 0, false,
932
3
                                      addr_range);
933
3
              addresses.push_back(addr_range.GetBaseAddress());
934
3
              if (log) {
935
0
                addr_t load_addr =
936
0
                    addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
937
938
0
                LLDB_LOGF(log,
939
0
                          "Found an indirect target symbol at 0x%" PRIx64 ".",
940
0
                          load_addr);
941
0
              }
942
3
            }
943
3
          }
944
3
        }
945
43
      }
946
470
    } else if (current_symbol->GetType() == eSymbolTypeReExported) {
947
      // I am not sure we could ever end up stopped AT a re-exported symbol.
948
      // But just in case:
949
950
0
      const Symbol *actual_symbol =
951
0
          current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
952
0
      if (actual_symbol) {
953
0
        Address target_addr(actual_symbol->GetAddress());
954
0
        if (target_addr.IsValid()) {
955
0
          LLDB_LOGF(
956
0
              log,
957
0
              "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
958
0
              ".",
959
0
              current_symbol->GetName().GetCString(),
960
0
              actual_symbol->GetName().GetCString(),
961
0
              target_addr.GetLoadAddress(target_sp.get()));
962
0
          addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
963
0
        }
964
0
      }
965
0
    }
966
967
513
    if (addresses.size() > 0) {
968
      // First check whether any of the addresses point to Indirect symbols,
969
      // and if they do, resolve them:
970
43
      std::vector<lldb::addr_t> load_addrs;
971
43
      for (Address address : addresses) {
972
43
        Symbol *symbol = address.CalculateSymbolContextSymbol();
973
43
        if (symbol && symbol->IsIndirect()) {
974
6
          Status error;
975
6
          Address symbol_address = symbol->GetAddress();
976
6
          addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
977
6
              &symbol_address, error);
978
6
          if (error.Success()) {
979
6
            load_addrs.push_back(resolved_addr);
980
6
            LLDB_LOGF(log,
981
6
                      "ResolveIndirectFunction found resolved target for "
982
6
                      "%s at 0x%" PRIx64 ".",
983
6
                      symbol->GetName().GetCString(), resolved_addr);
984
6
          }
985
37
        } else {
986
37
          load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
987
37
        }
988
43
      }
989
43
      thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
990
43
          thread, load_addrs, stop_others);
991
43
    }
992
513
  } else {
993
0
    LLDB_LOGF(log, "Could not find symbol for step through.");
994
0
  }
995
996
513
  return thread_plan_sp;
997
513
}
998
999
void DynamicLoaderDarwin::FindEquivalentSymbols(
1000
    lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
1001
0
    lldb_private::SymbolContextList &equivalent_symbols) {
1002
0
  ConstString trampoline_name =
1003
0
      original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1004
0
  if (!trampoline_name)
1005
0
    return;
1006
1007
0
  static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1008
0
  std::string equivalent_regex_buf("^");
1009
0
  equivalent_regex_buf.append(trampoline_name.GetCString());
1010
0
  equivalent_regex_buf.append(resolver_name_regex);
1011
1012
0
  RegularExpression equivalent_name_regex(equivalent_regex_buf);
1013
0
  images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1014
0
                                         equivalent_symbols);
1015
1016
0
}
1017
1018
9
lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1019
9
  ModuleSP module_sp = m_libpthread_module_wp.lock();
1020
9
  if (!module_sp) {
1021
9
    SymbolContextList sc_list;
1022
9
    ModuleSpec module_spec;
1023
9
    module_spec.GetFileSpec().GetFilename().SetCString(
1024
9
        "libsystem_pthread.dylib");
1025
9
    ModuleList module_list;
1026
9
    m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1027
9
    if (!module_list.IsEmpty()) {
1028
9
      if (module_list.GetSize() == 1) {
1029
9
        module_sp = module_list.GetModuleAtIndex(0);
1030
9
        if (module_sp)
1031
9
          m_libpthread_module_wp = module_sp;
1032
9
      }
1033
9
    }
1034
9
  }
1035
9
  return module_sp;
1036
9
}
1037
1038
21
Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1039
21
  if (!m_pthread_getspecific_addr.IsValid()) {
1040
9
    ModuleSP module_sp = GetPThreadLibraryModule();
1041
9
    if (module_sp) {
1042
9
      lldb_private::SymbolContextList sc_list;
1043
9
      module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1044
9
                                            eSymbolTypeCode, sc_list);
1045
9
      SymbolContext sc;
1046
9
      if (sc_list.GetContextAtIndex(0, sc)) {
1047
9
        if (sc.symbol)
1048
9
          m_pthread_getspecific_addr = sc.symbol->GetAddress();
1049
9
      }
1050
9
    }
1051
9
  }
1052
21
  return m_pthread_getspecific_addr;
1053
21
}
1054
1055
lldb::addr_t
1056
DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1057
                                        const lldb::ThreadSP thread_sp,
1058
45
                                        lldb::addr_t tls_file_addr) {
1059
45
  if (!thread_sp || !module_sp)
1060
0
    return LLDB_INVALID_ADDRESS;
1061
1062
45
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
1063
1064
45
  const uint32_t addr_size = m_process->GetAddressByteSize();
1065
45
  uint8_t buf[sizeof(lldb::addr_t) * 3];
1066
1067
45
  lldb_private::Address tls_addr;
1068
45
  if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
1069
45
    Status error;
1070
45
    const size_t tsl_data_size = addr_size * 3;
1071
45
    Target &target = m_process->GetTarget();
1072
45
    if (target.ReadMemory(tls_addr, buf, tsl_data_size, error, true) ==
1073
45
        tsl_data_size) {
1074
45
      const ByteOrder byte_order = m_process->GetByteOrder();
1075
45
      DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1076
45
      lldb::offset_t offset = addr_size; // Skip the first pointer
1077
45
      const lldb::addr_t pthread_key = data.GetAddress(&offset);
1078
45
      const lldb::addr_t tls_offset = data.GetAddress(&offset);
1079
45
      if (pthread_key != 0) {
1080
        // First check to see if we have already figured out the location of
1081
        // TLS data for the pthread_key on a specific thread yet. If we have we
1082
        // can re-use it since its location will not change unless the process
1083
        // execs.
1084
45
        const tid_t tid = thread_sp->GetID();
1085
45
        auto tid_pos = m_tid_to_tls_map.find(tid);
1086
45
        if (tid_pos != m_tid_to_tls_map.end()) {
1087
30
          auto tls_pos = tid_pos->second.find(pthread_key);
1088
30
          if (tls_pos != tid_pos->second.end()) {
1089
24
            return tls_pos->second + tls_offset;
1090
24
          }
1091
30
        }
1092
21
        StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1093
21
        if (frame_sp) {
1094
21
          TypeSystemClang *clang_ast_context =
1095
21
              ScratchTypeSystemClang::GetForTarget(target);
1096
1097
21
          if (!clang_ast_context)
1098
0
            return LLDB_INVALID_ADDRESS;
1099
1100
21
          CompilerType clang_void_ptr_type =
1101
21
              clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1102
21
          Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1103
21
          if (pthread_getspecific_addr.IsValid()) {
1104
21
            EvaluateExpressionOptions options;
1105
1106
21
            lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1107
21
                *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1108
21
                llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1109
1110
21
            DiagnosticManager execution_errors;
1111
21
            ExecutionContext exe_ctx(thread_sp);
1112
21
            lldb::ExpressionResults results = m_process->RunThreadPlan(
1113
21
                exe_ctx, thread_plan_sp, options, execution_errors);
1114
1115
21
            if (results == lldb::eExpressionCompleted) {
1116
21
              lldb::ValueObjectSP result_valobj_sp =
1117
21
                  thread_plan_sp->GetReturnValueObject();
1118
21
              if (result_valobj_sp) {
1119
21
                const lldb::addr_t pthread_key_data =
1120
21
                    result_valobj_sp->GetValueAsUnsigned(0);
1121
21
                if (pthread_key_data) {
1122
15
                  m_tid_to_tls_map[tid].insert(
1123
15
                      std::make_pair(pthread_key, pthread_key_data));
1124
15
                  return pthread_key_data + tls_offset;
1125
15
                }
1126
21
              }
1127
21
            }
1128
21
          }
1129
21
        }
1130
21
      }
1131
45
    }
1132
45
  }
1133
6
  return LLDB_INVALID_ADDRESS;
1134
45
}
1135
1136
5.31k
bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1137
5.31k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1138
5.31k
  bool use_new_spi_interface = false;
1139
1140
5.31k
  llvm::VersionTuple version = process->GetHostOSVersion();
1141
5.31k
  if (!version.empty()) {
1142
5.18k
    const llvm::Triple::OSType os_type =
1143
5.18k
        process->GetTarget().GetArchitecture().GetTriple().getOS();
1144
1145
    // macOS 10.12 and newer
1146
5.18k
    if (os_type == llvm::Triple::MacOSX &&
1147
5.18k
        
version >= llvm::VersionTuple(10, 12)5.17k
)
1148
5.17k
      use_new_spi_interface = true;
1149
1150
    // iOS 10 and newer
1151
5.18k
    if (os_type == llvm::Triple::IOS && 
version >= llvm::VersionTuple(10)10
)
1152
10
      use_new_spi_interface = true;
1153
1154
    // tvOS 10 and newer
1155
5.18k
    if (os_type == llvm::Triple::TvOS && 
version >= llvm::VersionTuple(10)0
)
1156
0
      use_new_spi_interface = true;
1157
1158
    // watchOS 3 and newer
1159
5.18k
    if (os_type == llvm::Triple::WatchOS && 
version >= llvm::VersionTuple(3)2
)
1160
2
      use_new_spi_interface = true;
1161
1162
    // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1163
    // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1164
    // NEED_BRIDGEOS_TRIPLE   use_new_spi_interface = true;
1165
5.18k
  }
1166
1167
5.31k
  if (log) {
1168
0
    if (use_new_spi_interface)
1169
0
      LLDB_LOGF(
1170
0
          log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1171
0
    else
1172
0
      LLDB_LOGF(
1173
0
          log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1174
0
  }
1175
5.31k
  return use_new_spi_interface;
1176
5.31k
}