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