19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/StringMap.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/raw_ostream.h"
32#include <sys/sysctl.h>
33#include <sys/syslimits.h>
37#include <CoreFoundation/CoreFoundation.h>
38#include <Foundation/Foundation.h>
39#include <mach-o/dyld.h>
40#if __has_include(<mach-o/dyld_introspection.h>)
41#include <mach-o/dyld_introspection.h>
42#define SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS
44#include <objc/objc-auto.h>
48#include <AvailabilityMacros.h>
49#ifndef CPU_SUBTYPE_X86_64_H
50#define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
53#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
56#ifndef CPU_TYPE_ARM64_32
57#define CPU_ARCH_ABI64_32 0x02000000
58#define CPU_TYPE_ARM64_32 (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)
61#include <TargetConditionals.h>
66 int mib[2] = {CTL_KERN, KERN_OSVERSION};
68 size_t cstr_len =
sizeof(cstr);
69 if (::sysctl(mib, 2, cstr, &cstr_len, NULL, 0) == 0)
70 return std::string(cstr, cstr_len - 1);
77 NSDictionary *version_info =
78 [NSDictionary dictionaryWithContentsOfFile:
79 @"/System/Library/CoreServices/SystemVersion.plist"];
80 NSString *version_value = [version_info objectForKey: Key];
81 const char *version_str = [version_value UTF8String];
82 version.tryParse(version_str);
87 static llvm::VersionTuple g_version;
88 if (g_version.empty())
94 static llvm::VersionTuple g_version;
95 if (g_version.empty())
103 if (!g_program_filespec) {
106 uint32_t len =
sizeof(program_fullpath);
107 int err = _NSGetExecutablePath(program_fullpath, &len);
109 g_program_filespec.
SetFile(program_fullpath, FileSpec::Style::native);
110 else if (err == -1) {
111 char *large_program_fullpath = (
char *)::malloc(len + 1);
113 err = _NSGetExecutablePath(large_program_fullpath, &len);
115 g_program_filespec.
SetFile(large_program_fullpath,
116 FileSpec::Style::native);
118 ::free(large_program_fullpath);
121 return g_program_filespec;
129 std::string raw_path = lldb_file_spec.
GetPath();
131 size_t framework_pos = raw_path.find(
"LLDB.framework");
132 if (framework_pos != std::string::npos) {
133 framework_pos += strlen(
"LLDB.framework");
136 raw_path.resize(framework_pos);
139 raw_path.resize(framework_pos);
140 raw_path.append(
"/Resources");
150 raw_path.append(
"/../bin");
151 FileSpec support_dir_spec(raw_path);
155 LLDB_LOGF(log,
"HostInfoMacOSX::%s(): failed to find support directory",
162 char *
const dir_realpath =
163 realpath(support_dir_spec.
GetPath().c_str(), NULL);
165 raw_path = dir_realpath;
168 raw_path = support_dir_spec.
GetPath();
181 std::string raw_path = lldb_file_spec.
GetPath();
183 size_t framework_pos = raw_path.find(
"LLDB.framework");
184 if (framework_pos != std::string::npos) {
185 framework_pos += strlen(
"LLDB.framework");
186 raw_path.resize(framework_pos);
187 raw_path.append(
"/Headers");
198 std::string raw_path = lldb_file_spec.
GetPath();
200 size_t framework_pos = raw_path.find(
"LLDB.framework");
201 if (framework_pos == std::string::npos)
204 framework_pos += strlen(
"LLDB.framework");
205 raw_path.resize(framework_pos);
206 raw_path.append(
"/Resources/PlugIns");
212 FileSpec temp_file(
"~/Library/Application Support/LLDB/PlugIns");
223 size_t len =
sizeof(cputype);
227 if (::sysctlbyname(
"hw.cputype", &cputype, &len, NULL, 0) == 0) {
228 len =
sizeof(cpusubtype);
229 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
230 cpusubtype = CPU_TYPE_ANY;
232 len =
sizeof(is_64_bit_capable);
233 ::sysctlbyname(
"hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0);
235 if (cputype ==
CPU_TYPE_ARM64 && cpusubtype == CPU_SUBTYPE_ARM64E) {
238 cpusubtype = CPU_SUBTYPE_ARM64_ALL;
241 if (is_64_bit_capable) {
242 if (cputype & CPU_ARCH_ABI64) {
254#if defined(__i386__) || defined(__x86_64__)
256 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
257#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
259 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
264 if (cputype == CPU_TYPE_ARM ||
268#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
269 arch_32.
GetTriple().setOS(llvm::Triple::TvOS);
270 arch_64.
GetTriple().setOS(llvm::Triple::TvOS);
271#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
272 arch_32.
GetTriple().setOS(llvm::Triple::BridgeOS);
273 arch_64.
GetTriple().setOS(llvm::Triple::BridgeOS);
274#elif defined(TARGET_OS_WATCHOS) && TARGET_OS_WATCHOS == 1
275 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
276 arch_64.
GetTriple().setOS(llvm::Triple::WatchOS);
277#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1
278 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
279 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
281 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
282 arch_64.
GetTriple().setOS(llvm::Triple::IOS);
285 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
286 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
291#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
292 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
294 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
303 static std::string g_env_developer_dir;
304 static std::once_flag g_once_flag;
305 std::call_once(g_once_flag, [&]() {
306 if (
const char *developer_dir_env_var = getenv(
"DEVELOPER_DIR")) {
307 FileSpec fspec(developer_dir_env_var);
309 g_env_developer_dir = fspec.
GetPath();
311 return g_env_developer_dir;
315 static FileSpec g_xcode_contents_path;
316 static std::once_flag g_once_flag;
317 std::call_once(g_once_flag, [&]() {
319 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
321 std::string xcode_contents_dir =
323 if (!xcode_contents_dir.empty()) {
324 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
331 if (!env_developer_dir.empty()) {
332 llvm::sys::path::append(env_developer_dir,
"Contents");
333 std::string xcode_contents_dir =
335 if (!xcode_contents_dir.empty()) {
336 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
342 if (!sdk_path_or_err) {
344 LLDB_LOGF(log,
"Error while searching for Xcode SDK: %s",
345 toString(sdk_path_or_err.takeError()).c_str());
351 std::string xcode_contents_dir =
353 if (!xcode_contents_dir.empty()) {
354 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
360 return g_xcode_contents_path;
365 static llvm::once_flag g_once_flag;
366 llvm::call_once(g_once_flag, []() {
368 fspec.AppendPathComponent(
"Developer");
370 g_developer_directory = fspec;
373 return g_developer_directory;
379 if (sdk_name.empty())
380 return llvm::createStringError(llvm::inconvertibleErrorCode(),
381 "Unrecognized SDK type: " + sdk.
GetString());
385 auto xcrun = [](
const std::string &sdk,
386 llvm::StringRef developer_dir =
387 "") -> llvm::Expected<std::string> {
389 if (!developer_dir.empty()) {
402 log->
Printf(
"GetXcodeSDK() running shell cmd '%s'", cmdstr.c_str());
407 std::string output_str;
410 auto timeout = std::chrono::seconds(60);
411 bool run_in_shell =
false;
413 args,
FileSpec(), &status, &signo, &output_str, timeout, run_in_shell);
418 LLDB_LOG(log,
"xcrun failed to execute: %s",
error.AsCString());
419 return error.ToError();
424 LLDB_LOG(log,
"xcrun returned exit code %d", status);
427 if (output_str.empty()) {
428 LLDB_LOG(log,
"xcrun returned no results");
434 llvm::StringRef output(output_str);
437 output = output.rtrim();
440 const size_t last_newline = output.rfind(
'\n');
441 if (last_newline != llvm::StringRef::npos)
442 output = output.substr(last_newline + 1);
448 [&xcrun](
const std::string &sdk_name) -> llvm::Expected<std::string> {
451 if (!developer_dir.empty()) {
453 return xcrun(sdk_name, developer_dir);
457 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
459 std::string contents_dir =
461 llvm::StringRef shlib_developer_dir =
462 llvm::sys::path::parent_path(contents_dir);
463 if (!shlib_developer_dir.empty()) {
464 auto sdk = xcrun(sdk_name, std::move(shlib_developer_dir));
466 return sdk.takeError();
474 return xcrun(sdk_name);
477 auto path_or_err = find_sdk(sdk_name);
479 return path_or_err.takeError();
480 std::string path = *path_or_err;
481 while (path.empty()) {
485 llvm::StringRef fixed(sdk_name);
486 if (fixed.consume_back(
".internal"))
487 sdk_name = fixed.str() +
"internal";
488 path_or_err = find_sdk(sdk_name);
490 return path_or_err.takeError();
495 LLDB_LOGF(log,
"Couldn't find SDK %s on host", sdk_name.c_str());
501 path_or_err = find_sdk(sdk_name);
503 return path_or_err.takeError();
509 LLDB_LOGF(log,
"Couldn't find any matching SDK on host");
515 LLDB_LOGF(log,
"SDK returned by xcrun doesn't exist");
516 return llvm::createStringError(llvm::inconvertibleErrorCode(),
517 "SDK returned by xcrun doesn't exist");
527 static llvm::StringMap<ErrorOrPath> g_sdk_path;
528 static std::mutex g_sdk_path_mutex;
530 std::lock_guard<std::mutex> guard(g_sdk_path_mutex);
534 auto it = g_sdk_path.find(key);
535 if (it != g_sdk_path.end()) {
536 if (it->second.is_error)
537 return llvm::createStringError(llvm::inconvertibleErrorCode(),
540 return it->second.str;
545 g_sdk_path.insert({key, {
error,
true}});
546 return llvm::createStringError(llvm::inconvertibleErrorCode(),
error);
548 auto it_new = g_sdk_path.insert({key, {*path_or_err,
false}});
549 return it_new.first->second.str;
553struct dyld_shared_cache_dylib_text_info {
556 uint64_t loadAddressUnslid;
557 uint64_t textSegmentSize;
561 uint64_t textSegmentOffset;
563typedef struct dyld_shared_cache_dylib_text_info
564 dyld_shared_cache_dylib_text_info;
569 void (^callback)(
const dyld_shared_cache_dylib_text_info *info));
574class SharedCacheInfo {
576 const UUID &GetUUID()
const {
return m_uuid; }
577 const llvm::StringMap<SharedCacheImageInfo> &GetImages()
const {
584 bool CreateSharedCacheInfoWithInstrospectionSPIs();
586 llvm::StringMap<SharedCacheImageInfo> m_images;
591bool SharedCacheInfo::CreateSharedCacheInfoWithInstrospectionSPIs() {
592#if defined(SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS)
593 dyld_process_t dyld_process = dyld_process_create_for_current_task();
597 dyld_process_snapshot_t snapshot =
598 dyld_process_snapshot_create_for_process(dyld_process,
nullptr);
603 llvm::make_scope_exit([&]() { dyld_process_snapshot_dispose(snapshot); });
605 dyld_shared_cache_t shared_cache =
606 dyld_process_snapshot_get_shared_cache(snapshot);
610 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
612 __block uint64_t maxVmAddr = 0;
614 __block
uuid_t *uuid = &uuidStore;
616 dyld_image_for_each_segment_info(
618 ^(
const char *segmentName, uint64_t vmAddr, uint64_t vmSize,
int perm) {
619 minVmAddr = std::min(minVmAddr, vmAddr);
620 maxVmAddr = std::max(maxVmAddr, vmAddr + vmSize);
621 dyld_image_copy_uuid(image, uuid);
623 assert(minVmAddr != UINT_MAX);
624 assert(maxVmAddr != 0);
626 UUID(uuid, 16), std::make_shared<DataBufferUnowned>(
627 (uint8_t *)minVmAddr, maxVmAddr - minVmAddr)};
634SharedCacheInfo::SharedCacheInfo() {
635 if (CreateSharedCacheInfoWithInstrospectionSPIs())
638 size_t shared_cache_size;
639 uint8_t *shared_cache_start =
643 m_uuid =
UUID(dsc_uuid);
646 dsc_uuid, ^(
const dyld_shared_cache_dylib_text_info *info) {
648 UUID(info->dylibUuid, 16),
649 std::make_shared<DataBufferUnowned>(
650 shared_cache_start + info->textSegmentOffset,
651 shared_cache_size - info->textSegmentOffset)};
657 static SharedCacheInfo g_shared_cache_info;
658 return g_shared_cache_info.GetImages().lookup(image_name);
static llvm::raw_ostream & error(Stream &strm)
#define CPU_SUBTYPE_X86_64_H
llvm::Expected< std::string > GetXcodeSDK(XcodeSDK sdk)
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.
int dyld_shared_cache_iterate_text(const uuid_t cacheUuid, void(^callback)(const dyld_shared_cache_dylib_text_info *info))
#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.
#define LLDB_LOGF(log,...)
#define LLDB_SCOPED_TIMER()
An architecture specification class.
void Clear()
Clears the object state.
llvm::Triple & GetTriple()
Architecture triple accessor.
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.
A command line argument class.
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
bool GetCommandString(std::string &command) const
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
void SetDirectory(ConstString directory)
Directory string set accessor.
const ConstString & GetDirectory() const
Directory string const get accessor.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
ConstString GetPathAsConstString(bool denormalize=true) const
Get the full path as a ConstString.
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
static FileSystem & Instance()
static FileSpec GetShlibDir()
Returns the directory containing the lldb shared library.
static FileSpec GetProgramFileSpec()
static std::optional< std::string > GetOSBuildString()
static FileSpec GetXcodeContentsDirectory()
static bool ComputeSupportExeDirectory(FileSpec &file_spec)
static SharedCacheImageInfo GetSharedCacheImageInfo(llvm::StringRef image_name)
Shared cache utilities.
static void ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)
static llvm::Expected< llvm::StringRef > GetXcodeSDKPath(XcodeSDK sdk)
Query xcrun to find an Xcode SDK directory.
static bool ComputeUserPluginsDirectory(FileSpec &file_spec)
static llvm::VersionTuple GetMacCatalystVersion()
static bool ComputeSystemPluginsDirectory(FileSpec &file_spec)
static bool ComputeHeaderDirectory(FileSpec &file_spec)
static FileSpec GetXcodeDeveloperDirectory()
static llvm::VersionTuple GetOSVersion()
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.
void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
An abstraction for Xcode-style SDKs that works like ArchSpec.
static std::string FindXcodeContentsDirectoryInPath(llvm::StringRef path)
static XcodeSDK GetAnyMacOS()
llvm::StringRef GetString() const
static std::string GetCanonicalName(Info info)
Return the canonical SDK name, such as "macosx" for the macOS SDK.
Info Parse() const
Return parsed SDK type and version number.
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.
const char * toString(AppleArm64ExceptionClass EC)
A parsed SDK directory name.
llvm::VersionTuple version