LLDB mainline
HostInfoMacOSX.mm
Go to the documentation of this file.
1//===-- HostInfoMacOSX.mm ---------------------------------------*- C++ -*-===//
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
11#include "lldb/Host/Host.h"
12#include "lldb/Host/HostInfo.h"
13#include "lldb/Utility/Args.h"
17#include "lldb/Utility/Log.h"
18#include "lldb/Utility/Timer.h"
19
20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/raw_ostream.h"
26
27// C++ Includes
28#include <optional>
29#include <string>
30
31// C inclues
32#include <cstdlib>
33#include <sys/sysctl.h>
34#include <sys/syslimits.h>
35#include <sys/types.h>
36#include <uuid/uuid.h>
37
38// Objective-C/C++ includes
39#include <AvailabilityMacros.h>
40#include <CoreFoundation/CoreFoundation.h>
41#include <Foundation/Foundation.h>
42#include <mach-o/dyld.h>
43#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && \
44 MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_VERSION_12_0
45#if __has_include(<mach-o/dyld_introspection.h>)
46#include <mach-o/dyld_introspection.h>
47#define SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS
48#endif
49#endif
50#include <objc/objc-auto.h>
51
52// These are needed when compiling on systems
53// that do not yet have these definitions
54#ifndef CPU_SUBTYPE_X86_64_H
55#define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
56#endif
57#ifndef CPU_TYPE_ARM64
58#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
59#endif
60
61#ifndef CPU_TYPE_ARM64_32
62#define CPU_ARCH_ABI64_32 0x02000000
63#define CPU_TYPE_ARM64_32 (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)
64#endif
65
66#include <TargetConditionals.h> // for TARGET_OS_TV, TARGET_OS_WATCH
67
68using namespace lldb_private;
69
70std::optional<std::string> HostInfoMacOSX::GetOSBuildString() {
71 int mib[2] = {CTL_KERN, KERN_OSVERSION};
72 char cstr[PATH_MAX];
73 size_t cstr_len = sizeof(cstr);
74 if (::sysctl(mib, 2, cstr, &cstr_len, NULL, 0) == 0)
75 return std::string(cstr, cstr_len - 1);
76
77 return std::nullopt;
78}
79
80static void ParseOSVersion(llvm::VersionTuple &version, NSString *Key) {
81 @autoreleasepool {
82 NSDictionary *version_info =
83 [NSDictionary dictionaryWithContentsOfFile:
84 @"/System/Library/CoreServices/SystemVersion.plist"];
85 NSString *version_value = [version_info objectForKey: Key];
86 const char *version_str = [version_value UTF8String];
87 version.tryParse(version_str);
88 }
89}
90
91llvm::VersionTuple HostInfoMacOSX::GetOSVersion() {
92 static llvm::VersionTuple g_version;
93 if (g_version.empty())
94 ParseOSVersion(g_version, @"ProductVersion");
95 return g_version;
96}
97
99 static llvm::VersionTuple g_version;
100 if (g_version.empty())
101 ParseOSVersion(g_version, @"iOSSupportVersion");
102 return g_version;
103}
104
105
107 static FileSpec g_program_filespec;
108 if (!g_program_filespec) {
109 char program_fullpath[PATH_MAX];
110 // If DST is NULL, then return the number of bytes needed.
111 uint32_t len = sizeof(program_fullpath);
112 int err = _NSGetExecutablePath(program_fullpath, &len);
113 if (err == 0)
114 g_program_filespec.SetFile(program_fullpath, FileSpec::Style::native);
115 else if (err == -1) {
116 char *large_program_fullpath = (char *)::malloc(len + 1);
117
118 err = _NSGetExecutablePath(large_program_fullpath, &len);
119 if (err == 0)
120 g_program_filespec.SetFile(large_program_fullpath,
121 FileSpec::Style::native);
122
123 ::free(large_program_fullpath);
124 }
125 }
126 return g_program_filespec;
127}
128
129/// Resolve the given candidate support dir and return true if it's valid.
134
136 FileSpec lldb_file_spec = GetShlibDir();
137 if (!lldb_file_spec)
138 return false;
139
140 std::string raw_path = lldb_file_spec.GetPath();
141
142 size_t framework_pos = raw_path.find("LLDB.framework");
143 if (framework_pos != std::string::npos) {
144 framework_pos += strlen("LLDB.framework");
145#if TARGET_OS_IPHONE
146 // Shallow bundle
147 raw_path.resize(framework_pos);
148#else
149 // Normal bundle
150 raw_path.resize(framework_pos);
151 raw_path.append("/Resources");
152#endif
153 } else {
154 // Find the bin path relative to the lib path where the cmake-based
155 // OS X .dylib lives. We try looking first at a possible sibling `bin`
156 // directory, and then at the `lib` directory itself. This last case is
157 // useful for supporting build systems like Bazel which in many cases prefer
158 // to place support binaries right next to dylibs.
159 //
160 // It is not going to work to do it by the executable path,
161 // as in the case of a python script, the executable is python, not
162 // the lldb driver.
163 FileSpec support_dir_spec_lib(raw_path);
164 FileSpec support_dir_spec_bin =
165 support_dir_spec_lib.CopyByAppendingPathComponent("/../bin");
166 FileSpec support_dir_spec;
167
168 if (ResolveAndVerifyCandidateSupportDir(support_dir_spec_bin)) {
169 support_dir_spec = support_dir_spec_bin;
170 } else if (ResolveAndVerifyCandidateSupportDir(support_dir_spec_lib)) {
171 support_dir_spec = support_dir_spec_lib;
172 } else {
173 Log *log = GetLog(LLDBLog::Host);
174 LLDB_LOG(log, "failed to find support directory");
175 return false;
176 }
177
178 // Get normalization from support_dir_spec. Note the FileSpec resolve
179 // does not remove '..' in the path.
180 char *const dir_realpath =
181 realpath(support_dir_spec.GetPath().c_str(), NULL);
182 if (dir_realpath) {
183 raw_path = dir_realpath;
184 free(dir_realpath);
185 } else {
186 raw_path = support_dir_spec.GetPath();
187 }
188 }
189
190 file_spec.SetDirectory(raw_path);
191 return (bool)file_spec.GetDirectory();
192}
193
195 FileSpec lldb_file_spec = GetShlibDir();
196 if (!lldb_file_spec)
197 return false;
198
199 std::string raw_path = lldb_file_spec.GetPath();
200
201 size_t framework_pos = raw_path.find("LLDB.framework");
202 if (framework_pos != std::string::npos) {
203 framework_pos += strlen("LLDB.framework");
204 raw_path.resize(framework_pos);
205 raw_path.append("/Headers");
206 }
207 file_spec.SetDirectory(raw_path);
208 return true;
209}
210
212 FileSpec lldb_file_spec = GetShlibDir();
213 if (!lldb_file_spec)
214 return false;
215
216 std::string raw_path = lldb_file_spec.GetPath();
217
218 size_t framework_pos = raw_path.find("LLDB.framework");
219 if (framework_pos == std::string::npos)
220 return false;
221
222 framework_pos += strlen("LLDB.framework");
223 raw_path.resize(framework_pos);
224 raw_path.append("/Resources/PlugIns");
225 file_spec.SetDirectory(raw_path);
226 return true;
227}
228
230 FileSpec home_dir_spec = GetUserHomeDir();
231 home_dir_spec.AppendPathComponent("Library/Application Support/LLDB/PlugIns");
232 file_spec.SetDirectory(home_dir_spec.GetPathAsConstString());
233 return true;
234}
235
237 ArchSpec &arch_64) {
238 // All apple systems support 32 bit execution.
239 uint32_t cputype, cpusubtype;
240 uint32_t is_64_bit_capable = false;
241 size_t len = sizeof(cputype);
242 ArchSpec host_arch;
243 // These will tell us about the kernel architecture, which even on a 64
244 // bit machine can be 32 bit...
245 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0) {
246 len = sizeof(cpusubtype);
247 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
248 cpusubtype = CPU_TYPE_ANY;
249
250 len = sizeof(is_64_bit_capable);
251 ::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0);
252
253 if (cputype == CPU_TYPE_ARM64 && cpusubtype == CPU_SUBTYPE_ARM64E) {
254 // The arm64e architecture is a preview. Pretend the host architecture
255 // is arm64.
256 cpusubtype = CPU_SUBTYPE_ARM64_ALL;
257 }
258
259 if (is_64_bit_capable) {
260 if (cputype & CPU_ARCH_ABI64) {
261 // We have a 64 bit kernel on a 64 bit system
262 arch_64.SetArchitecture(eArchTypeMachO, cputype, cpusubtype);
263 } else {
264 // We have a 64 bit kernel that is returning a 32 bit cputype, the
265 // cpusubtype will be correct as if it were for a 64 bit architecture
266 arch_64.SetArchitecture(eArchTypeMachO, cputype | CPU_ARCH_ABI64,
267 cpusubtype);
268 }
269
270 // Now we need modify the cpusubtype for the 32 bit slices.
271 uint32_t cpusubtype32 = cpusubtype;
272#if defined(__i386__) || defined(__x86_64__)
273 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
274 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
275#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
276 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
277 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
278#endif
279 arch_32.SetArchitecture(eArchTypeMachO, cputype & ~(CPU_ARCH_MASK),
280 cpusubtype32);
281
282 if (cputype == CPU_TYPE_ARM ||
283 cputype == CPU_TYPE_ARM64 ||
284 cputype == CPU_TYPE_ARM64_32) {
285// When running on a watch or tv, report the host os correctly
286#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
287 arch_32.GetTriple().setOS(llvm::Triple::TvOS);
288 arch_64.GetTriple().setOS(llvm::Triple::TvOS);
289#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
290 arch_32.GetTriple().setOS(llvm::Triple::BridgeOS);
291 arch_64.GetTriple().setOS(llvm::Triple::BridgeOS);
292#elif defined(TARGET_OS_WATCHOS) && TARGET_OS_WATCHOS == 1
293 arch_32.GetTriple().setOS(llvm::Triple::WatchOS);
294 arch_64.GetTriple().setOS(llvm::Triple::WatchOS);
295#elif defined(TARGET_OS_XR) && TARGET_OS_XR == 1
296 arch_32.GetTriple().setOS(llvm::Triple::XROS);
297 arch_64.GetTriple().setOS(llvm::Triple::XROS);
298#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1
299 arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
300 arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
301#else
302 arch_32.GetTriple().setOS(llvm::Triple::IOS);
303 arch_64.GetTriple().setOS(llvm::Triple::IOS);
304#endif
305 } else {
306 arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
307 arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
308 }
309 } else {
310 // We have a 32 bit kernel on a 32 bit system
311 arch_32.SetArchitecture(eArchTypeMachO, cputype, cpusubtype);
312#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
313 arch_32.GetTriple().setOS(llvm::Triple::WatchOS);
314#else
315 arch_32.GetTriple().setOS(llvm::Triple::IOS);
316#endif
317 arch_64.Clear();
318 }
319 }
320}
321
322/// Return and cache $DEVELOPER_DIR if it is set and exists.
323static std::string GetEnvDeveloperDir() {
324 static std::string g_env_developer_dir;
325 static std::once_flag g_once_flag;
326 std::call_once(g_once_flag, [&]() {
327 if (const char *developer_dir_env_var = getenv("DEVELOPER_DIR")) {
328 FileSpec fspec(developer_dir_env_var);
329 if (FileSystem::Instance().Exists(fspec))
330 g_env_developer_dir = fspec.GetPath();
331 }});
332 return g_env_developer_dir;
333}
334
336 static FileSpec g_xcode_contents_path;
337 static std::once_flag g_once_flag;
338 std::call_once(g_once_flag, [&]() {
339 // Try the shlib dir first.
340 if (FileSpec fspec = HostInfo::GetShlibDir()) {
341 if (FileSystem::Instance().Exists(fspec)) {
342 std::string xcode_contents_dir =
344 if (!xcode_contents_dir.empty()) {
345 g_xcode_contents_path = FileSpec(xcode_contents_dir);
346 return;
347 }
348 }
349 }
350
351 llvm::SmallString<128> env_developer_dir(GetEnvDeveloperDir());
352 if (!env_developer_dir.empty()) {
353 llvm::sys::path::append(env_developer_dir, "Contents");
354 std::string xcode_contents_dir =
356 if (!xcode_contents_dir.empty()) {
357 g_xcode_contents_path = FileSpec(xcode_contents_dir);
358 return;
359 }
360 }
361
362 auto sdk_path_or_err =
363 HostInfo::GetSDKRoot(SDKOptions{XcodeSDK::GetAnyMacOS()});
364 if (!sdk_path_or_err) {
365 Log *log = GetLog(LLDBLog::Host);
366 LLDB_LOG_ERROR(log, sdk_path_or_err.takeError(),
367 "Error while searching for Xcode SDK: {0}");
368 return;
369 }
370 FileSpec fspec(*sdk_path_or_err);
371 if (fspec) {
372 if (FileSystem::Instance().Exists(fspec)) {
373 std::string xcode_contents_dir =
375 if (!xcode_contents_dir.empty()) {
376 g_xcode_contents_path = FileSpec(xcode_contents_dir);
377 return;
378 }
379 }
380 }
381 });
382 return g_xcode_contents_path;
383}
384
386 static lldb_private::FileSpec g_developer_directory;
387 static llvm::once_flag g_once_flag;
388 llvm::call_once(g_once_flag, []() {
389 if (FileSpec fspec = GetXcodeContentsDirectory()) {
390 fspec.AppendPathComponent("Developer");
391 if (FileSystem::Instance().Exists(fspec))
392 g_developer_directory = fspec;
393 }
394 });
395 return g_developer_directory;
396}
397
398std::string HostInfoMacOSX::FindComponentInPath(llvm::StringRef path,
399 llvm::StringRef component) {
400 auto begin = llvm::sys::path::begin(path);
401 auto end = llvm::sys::path::end(path);
402 for (auto it = begin; it != end; ++it) {
403 if (it->contains(component)) {
404 llvm::SmallString<128> buffer;
405 llvm::sys::path::append(buffer, begin, ++it,
406 llvm::sys::path::Style::posix);
407 return buffer.str().str();
408 }
409 }
410 return {};
411}
412
414 if (FileSpec fspec = HostInfo::GetShlibDir())
415 return FileSpec(FindComponentInPath(fspec.GetPath(), ".xctoolchain"));
416 return {};
417}
418
420 if (FileSpec fspec = HostInfo::GetShlibDir())
421 return FileSpec(FindComponentInPath(fspec.GetPath(), "CommandLineTools"));
422 return {};
423}
424
425static llvm::Expected<std::string>
426xcrun(const std::string &sdk, llvm::ArrayRef<llvm::StringRef> arguments,
427 llvm::StringRef developer_dir = "") {
428 Args args;
429 if (!developer_dir.empty()) {
430 args.AppendArgument("/usr/bin/env");
431 args.AppendArgument("DEVELOPER_DIR=" + developer_dir.str());
432 }
433 args.AppendArgument("/usr/bin/xcrun");
434 args.AppendArgument("--sdk");
435 args.AppendArgument(sdk);
436 for (auto arg: arguments)
437 args.AppendArgument(arg);
438
439 Log *log = GetLog(LLDBLog::Host);
440 if (log) {
441 std::string cmdstr;
442 args.GetCommandString(cmdstr);
443 LLDB_LOG(log, "GetXcodeSDK() running shell cmd '{0}'", cmdstr);
444 }
445
446 int status = 0;
447 int signo = 0;
448 std::string output_str;
449 // The first time after Xcode was updated or freshly installed,
450 // xcrun can take surprisingly long to build up its database.
451 auto timeout = std::chrono::seconds(60);
452 bool run_in_shell = false;
454 args, FileSpec(), &status, &signo, &output_str, timeout, run_in_shell);
455
456 // Check that xcrun returned something useful.
457 if (error.Fail()) {
458 // Catastrophic error.
459 LLDB_LOG(log, "xcrun failed to execute: {0}", error);
460 return error.ToError();
461 }
462 if (status != 0) {
463 // xcrun didn't find a matching SDK. Not an error, we'll try
464 // different spellings.
465 LLDB_LOG(log, "xcrun returned exit code {0}", status);
466 if (!output_str.empty())
467 LLDB_LOG(log, "xcrun output was:\n{0}", output_str);
468 return "";
469 }
470 if (output_str.empty()) {
471 LLDB_LOG(log, "xcrun returned no results");
472 return "";
473 }
474
475 // Convert to a StringRef so we can manipulate the string without modifying
476 // the underlying data.
477 llvm::StringRef output(output_str);
478
479 // Remove any trailing newline characters.
480 output = output.rtrim();
481
482 // Strip any leading newline characters and everything before them.
483 const size_t last_newline = output.rfind('\n');
484 if (last_newline != llvm::StringRef::npos)
485 output = output.substr(last_newline + 1);
486
487 return output.str();
488}
489
490static llvm::Expected<std::string> GetXcodeSDK(XcodeSDK sdk) {
491 XcodeSDK::Info info = sdk.Parse();
492 std::string sdk_name = XcodeSDK::GetCanonicalName(info);
493 if (sdk_name.empty())
494 return llvm::createStringError(llvm::inconvertibleErrorCode(),
495 "Unrecognized SDK type: " + sdk.GetString());
496
497 Log *log = GetLog(LLDBLog::Host);
498
499 auto find_sdk =
500 [](const std::string &sdk_name) -> llvm::Expected<std::string> {
501 llvm::SmallVector<llvm::StringRef, 1> show_sdk_path = {"--show-sdk-path"};
502 // Invoke xcrun with the developer dir specified in the environment.
503 std::string developer_dir = GetEnvDeveloperDir();
504 if (!developer_dir.empty()) {
505 // Don't fallback if DEVELOPER_DIR was set.
506 return xcrun(sdk_name, show_sdk_path, developer_dir);
507 }
508
509 // Invoke xcrun with the shlib dir.
510 if (FileSpec fspec = HostInfo::GetShlibDir()) {
511 if (FileSystem::Instance().Exists(fspec)) {
512 llvm::SmallString<0> shlib_developer_dir(
514 llvm::sys::path::append(shlib_developer_dir, "Developer");
515 if (FileSystem::Instance().Exists(shlib_developer_dir)) {
516 auto sdk = xcrun(sdk_name, show_sdk_path, shlib_developer_dir);
517 if (!sdk)
518 return sdk.takeError();
519 if (!sdk->empty())
520 return sdk;
521 }
522 }
523 }
524
525 // Invoke xcrun without a developer dir as a last resort.
526 return xcrun(sdk_name, show_sdk_path);
527 };
528
529 auto path_or_err = find_sdk(sdk_name);
530 if (!path_or_err)
531 return path_or_err.takeError();
532 std::string path = *path_or_err;
533 while (path.empty()) {
534 // Try an alternate spelling of the name ("macosx10.9internal").
535 if (info.type == XcodeSDK::Type::MacOSX && !info.version.empty() &&
536 info.internal) {
537 llvm::StringRef fixed(sdk_name);
538 if (fixed.consume_back(".internal"))
539 sdk_name = fixed.str() + "internal";
540 path_or_err = find_sdk(sdk_name);
541 if (!path_or_err)
542 return path_or_err.takeError();
543 path = *path_or_err;
544 if (!path.empty())
545 break;
546 }
547 LLDB_LOG(log, "Couldn't find SDK {0} on host", sdk_name);
548
549 // Try without the version.
550 if (!info.version.empty()) {
551 info.version = {};
552 sdk_name = XcodeSDK::GetCanonicalName(info);
553 path_or_err = find_sdk(sdk_name);
554 if (!path_or_err)
555 return path_or_err.takeError();
556 path = *path_or_err;
557 if (!path.empty())
558 break;
559 }
560
561 LLDB_LOG(log, "Couldn't find any matching SDK on host");
562 return "";
563 }
564
565 // Whatever is left in output should be a valid path.
566 if (!FileSystem::Instance().Exists(path)) {
567 LLDB_LOG(log, "SDK returned by xcrun doesn't exist");
568 return llvm::createStringError(llvm::inconvertibleErrorCode(),
569 "SDK returned by xcrun doesn't exist");
570 }
571 return path;
572}
573
574namespace {
575struct ErrorOrPath {
576 std::string str;
577 bool is_error;
578};
579} // namespace
580
581static llvm::Expected<llvm::StringRef>
582find_cached_path(llvm::StringMap<ErrorOrPath> &cache, std::mutex &mutex,
583 llvm::StringRef key,
584 std::function<llvm::Expected<std::string>(void)> compute) {
585 std::lock_guard<std::mutex> guard(mutex);
587
588 auto it = cache.find(key);
589 if (it != cache.end()) {
590 if (it->second.is_error)
591 return llvm::createStringError(llvm::inconvertibleErrorCode(),
592 it->second.str);
593 return it->second.str;
594 }
595 auto path_or_err = compute();
596 if (!path_or_err) {
597 std::string error = toString(path_or_err.takeError());
598 cache.insert({key, {error, true}});
599 return llvm::createStringError(llvm::inconvertibleErrorCode(), error);
600 }
601 auto it_new = cache.insert({key, {*path_or_err, false}});
602 return it_new.first->second.str;
603}
604
605llvm::Expected<llvm::StringRef> HostInfoMacOSX::GetSDKRoot(SDKOptions options) {
606 static llvm::StringMap<ErrorOrPath> g_sdk_path;
607 static std::mutex g_sdk_path_mutex;
608 if (!options.XcodeSDKSelection)
609 return llvm::createStringError(llvm::inconvertibleErrorCode(),
610 "XcodeSDK not specified");
611 XcodeSDK sdk = *options.XcodeSDKSelection;
612 auto key = sdk.GetString();
613 return find_cached_path(g_sdk_path, g_sdk_path_mutex, key, [&](){
614 return GetXcodeSDK(sdk);
615 });
616}
617
618llvm::Expected<llvm::StringRef>
619HostInfoMacOSX::FindSDKTool(XcodeSDK sdk, llvm::StringRef tool) {
620 static llvm::StringMap<ErrorOrPath> g_tool_path;
621 static std::mutex g_tool_path_mutex;
622 std::string key;
623 llvm::raw_string_ostream(key) << sdk.GetString() << ":" << tool;
624 return find_cached_path(
625 g_tool_path, g_tool_path_mutex, key,
626 [&]() -> llvm::Expected<std::string> {
627 std::string sdk_name = XcodeSDK::GetCanonicalName(sdk.Parse());
628 if (sdk_name.empty())
629 return llvm::createStringError(llvm::inconvertibleErrorCode(),
630 "Unrecognized SDK type: " +
631 sdk.GetString());
632 llvm::SmallVector<llvm::StringRef, 2> find = {"-find", tool};
633 return xcrun(sdk_name, find);
634 });
635}
636
637namespace {
638struct dyld_shared_cache_dylib_text_info {
639 uint64_t version; // current version 1
640 // following fields all exist in version 1
641 uint64_t loadAddressUnslid;
642 uint64_t textSegmentSize;
643 uuid_t dylibUuid;
644 const char *path; // pointer invalid at end of iterations
645 // following fields all exist in version 2
646 uint64_t textSegmentOffset; // offset from start of cache
647};
648typedef struct dyld_shared_cache_dylib_text_info
649 dyld_shared_cache_dylib_text_info;
650}
651
653 const uuid_t cacheUuid,
654 void (^callback)(const dyld_shared_cache_dylib_text_info *info));
655extern "C" uint8_t *_dyld_get_shared_cache_range(size_t *length);
657
658namespace {
659class SharedCacheInfo {
660public:
661 const UUID &GetUUID() const { return m_uuid; }
662 const llvm::StringMap<SharedCacheImageInfo> &GetImages() const {
663 return m_images;
664 }
665
666 SharedCacheInfo();
667
668private:
669 bool CreateSharedCacheInfoWithInstrospectionSPIs();
670
671 llvm::StringMap<SharedCacheImageInfo> m_images;
672 UUID m_uuid;
673};
674}
675
676bool SharedCacheInfo::CreateSharedCacheInfoWithInstrospectionSPIs() {
677#if defined(SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS)
678 dyld_process_t dyld_process = dyld_process_create_for_current_task();
679 if (!dyld_process)
680 return false;
681
682 llvm::scope_exit cleanup_process_on_exit(
683 [&]() { dyld_process_dispose(dyld_process); });
684
685 dyld_process_snapshot_t snapshot =
686 dyld_process_snapshot_create_for_process(dyld_process, nullptr);
687 if (!snapshot)
688 return false;
689
690 llvm::scope_exit cleanup_snapshot_on_exit(
691 [&]() { dyld_process_snapshot_dispose(snapshot); });
692
693 dyld_shared_cache_t shared_cache =
694 dyld_process_snapshot_get_shared_cache(snapshot);
695 if (!shared_cache)
696 return false;
697
698 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
699 __block uint64_t minVmAddr = UINT64_MAX;
700 __block uint64_t maxVmAddr = 0;
701 uuid_t uuidStore;
702 __block uuid_t *uuid = &uuidStore;
703
704 dyld_image_for_each_segment_info(
705 image,
706 ^(const char *segmentName, uint64_t vmAddr, uint64_t vmSize, int perm) {
707 minVmAddr = std::min(minVmAddr, vmAddr);
708 maxVmAddr = std::max(maxVmAddr, vmAddr + vmSize);
709 dyld_image_copy_uuid(image, uuid);
710 });
711 assert(minVmAddr != UINT_MAX);
712 assert(maxVmAddr != 0);
713 lldb::DataBufferSP data_sp = std::make_shared<DataBufferUnowned>(
714 (uint8_t *)minVmAddr, maxVmAddr - minVmAddr);
715 lldb::DataExtractorSP extractor_sp = std::make_shared<DataExtractor>(data_sp);
716 m_images[dyld_image_get_installname(image)] = SharedCacheImageInfo{
717 UUID(uuid, 16), extractor_sp};
718 });
719 return true;
720#endif
721 return false;
722}
723
724SharedCacheInfo::SharedCacheInfo() {
725 if (CreateSharedCacheInfoWithInstrospectionSPIs())
726 return;
727
728 size_t shared_cache_size;
729 uint8_t *shared_cache_start =
730 _dyld_get_shared_cache_range(&shared_cache_size);
731 uuid_t dsc_uuid;
733 m_uuid = UUID(dsc_uuid);
734
736 dsc_uuid, ^(const dyld_shared_cache_dylib_text_info *info) {
737 lldb::DataBufferSP data_sp = std::make_shared<DataBufferUnowned>(
738 shared_cache_start + info->textSegmentOffset,
739 shared_cache_size - info->textSegmentOffset);
740 lldb::DataExtractorSP extractor_sp =
741 std::make_shared<DataExtractor>(data_sp);
742 m_images[info->path] =
743 SharedCacheImageInfo{UUID(info->dylibUuid, 16), extractor_sp};
744 });
745}
746
748HostInfoMacOSX::GetSharedCacheImageInfo(llvm::StringRef image_name) {
749 static SharedCacheInfo g_shared_cache_info;
750 return g_shared_cache_info.GetImages().lookup(image_name);
751}
unsigned char uuid_t[16]
static llvm::raw_ostream & error(Stream &strm)
#define CPU_SUBTYPE_X86_64_H
static llvm::Expected< std::string > GetXcodeSDK(XcodeSDK sdk)
static llvm::Expected< std::string > xcrun(const std::string &sdk, llvm::ArrayRef< llvm::StringRef > arguments, llvm::StringRef developer_dir="")
uint8_t * _dyld_get_shared_cache_range(size_t *length)
static std::string GetEnvDeveloperDir()
Return and cache $DEVELOPER_DIR if it is set and exists.
static llvm::Expected< llvm::StringRef > find_cached_path(llvm::StringMap< ErrorOrPath > &cache, std::mutex &mutex, llvm::StringRef key, std::function< llvm::Expected< std::string >(void)> compute)
static bool ResolveAndVerifyCandidateSupportDir(FileSpec &path)
Resolve the given candidate support dir and return true if it's valid.
int dyld_shared_cache_iterate_text(const uuid_t cacheUuid, void(^callback)(const dyld_shared_cache_dylib_text_info *info))
#define CPU_TYPE_ARM64
#define CPU_TYPE_ARM64_32
bool _dyld_get_shared_cache_uuid(uuid_t uuid)
static void ParseOSVersion(llvm::VersionTuple &version, NSString *Key)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
An architecture specification class.
Definition ArchSpec.h:31
void Clear()
Clears the object state.
Definition ArchSpec.cpp:538
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition ArchSpec.cpp:845
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
bool GetCommandString(std::string &command) const
Definition Args.cpp:215
A file utility class.
Definition FileSpec.h:57
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
ConstString GetPathAsConstString(bool denormalize=true) const
Get the full path as a ConstString.
Definition FileSpec.cpp:390
bool IsDirectory(const FileSpec &file_spec) const
Returns whether the given path is a directory.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
static FileSpec GetShlibDir()
Returns the directory containing the lldb shared library.
static FileSpec GetUserHomeDir()
Returns the directory containing the users home (e.g.
static llvm::Expected< llvm::StringRef > GetSDKRoot(SDKOptions options)
Query xcrun to find an Xcode SDK directory.
static FileSpec GetProgramFileSpec()
static std::optional< std::string > GetOSBuildString()
static FileSpec GetCurrentXcodeToolchainDirectory()
static FileSpec GetXcodeContentsDirectory()
static bool ComputeSupportExeDirectory(FileSpec &file_spec)
static std::string FindComponentInPath(llvm::StringRef path, llvm::StringRef component)
static SharedCacheImageInfo GetSharedCacheImageInfo(llvm::StringRef image_name)
Shared cache utilities.
static void ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)
static bool ComputeUserPluginsDirectory(FileSpec &file_spec)
static FileSpec GetCurrentCommandLineToolsDirectory()
static llvm::VersionTuple GetMacCatalystVersion()
static bool ComputeSystemPluginsDirectory(FileSpec &file_spec)
static bool ComputeHeaderDirectory(FileSpec &file_spec)
static FileSpec GetXcodeDeveloperDirectory()
static llvm::VersionTuple GetOSVersion()
static llvm::Expected< llvm::StringRef > FindSDKTool(XcodeSDK sdk, llvm::StringRef tool)
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, const Timeout< std::micro > &timeout, bool run_in_shell=true, bool hide_stderr=false)
Run a shell command.
An error handling class.
Definition Status.h:118
Represents UUID's of various sizes.
Definition UUID.h:27
An abstraction for Xcode-style SDKs that works like ArchSpec.
Definition XcodeSDK.h:25
static std::string FindXcodeContentsDirectoryInPath(llvm::StringRef path)
Definition XcodeSDK.cpp:293
static XcodeSDK GetAnyMacOS()
Definition XcodeSDK.h:71
llvm::StringRef GetString() const
Definition XcodeSDK.cpp:143
static std::string GetCanonicalName(Info info)
Return the canonical SDK name, such as "macosx" for the macOS SDK.
Definition XcodeSDK.cpp:177
Info Parse() const
Return parsed SDK type and version number.
Definition XcodeSDK.cpp:116
#define UINT64_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
const char * toString(AppleArm64ExceptionClass EC)
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::optional< XcodeSDK > XcodeSDKSelection
A parsed SDK directory name.
Definition XcodeSDK.h:48
llvm::VersionTuple version
Definition XcodeSDK.h:50
#define PATH_MAX