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_LOG(log,
"failed to find support directory");
161 char *
const dir_realpath =
162 realpath(support_dir_spec.
GetPath().c_str(), NULL);
164 raw_path = dir_realpath;
167 raw_path = support_dir_spec.
GetPath();
180 std::string raw_path = lldb_file_spec.
GetPath();
182 size_t framework_pos = raw_path.find(
"LLDB.framework");
183 if (framework_pos != std::string::npos) {
184 framework_pos += strlen(
"LLDB.framework");
185 raw_path.resize(framework_pos);
186 raw_path.append(
"/Headers");
197 std::string raw_path = lldb_file_spec.
GetPath();
199 size_t framework_pos = raw_path.find(
"LLDB.framework");
200 if (framework_pos == std::string::npos)
203 framework_pos += strlen(
"LLDB.framework");
204 raw_path.resize(framework_pos);
205 raw_path.append(
"/Resources/PlugIns");
211 FileSpec temp_file(
"~/Library/Application Support/LLDB/PlugIns");
222 size_t len =
sizeof(cputype);
226 if (::sysctlbyname(
"hw.cputype", &cputype, &len, NULL, 0) == 0) {
227 len =
sizeof(cpusubtype);
228 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
229 cpusubtype = CPU_TYPE_ANY;
231 len =
sizeof(is_64_bit_capable);
232 ::sysctlbyname(
"hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0);
234 if (cputype ==
CPU_TYPE_ARM64 && cpusubtype == CPU_SUBTYPE_ARM64E) {
237 cpusubtype = CPU_SUBTYPE_ARM64_ALL;
240 if (is_64_bit_capable) {
241 if (cputype & CPU_ARCH_ABI64) {
253#if defined(__i386__) || defined(__x86_64__)
255 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
256#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
258 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
263 if (cputype == CPU_TYPE_ARM ||
267#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
268 arch_32.
GetTriple().setOS(llvm::Triple::TvOS);
269 arch_64.
GetTriple().setOS(llvm::Triple::TvOS);
270#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
271 arch_32.
GetTriple().setOS(llvm::Triple::BridgeOS);
272 arch_64.
GetTriple().setOS(llvm::Triple::BridgeOS);
273#elif defined(TARGET_OS_WATCHOS) && TARGET_OS_WATCHOS == 1
274 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
275 arch_64.
GetTriple().setOS(llvm::Triple::WatchOS);
276#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1
277 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
278 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
280 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
281 arch_64.
GetTriple().setOS(llvm::Triple::IOS);
284 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
285 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
290#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
291 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
293 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
302 static std::string g_env_developer_dir;
303 static std::once_flag g_once_flag;
304 std::call_once(g_once_flag, [&]() {
305 if (
const char *developer_dir_env_var = getenv(
"DEVELOPER_DIR")) {
306 FileSpec fspec(developer_dir_env_var);
308 g_env_developer_dir = fspec.
GetPath();
310 return g_env_developer_dir;
314 static FileSpec g_xcode_contents_path;
315 static std::once_flag g_once_flag;
316 std::call_once(g_once_flag, [&]() {
318 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
320 std::string xcode_contents_dir =
322 if (!xcode_contents_dir.empty()) {
323 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
330 if (!env_developer_dir.empty()) {
331 llvm::sys::path::append(env_developer_dir,
"Contents");
332 std::string xcode_contents_dir =
334 if (!xcode_contents_dir.empty()) {
335 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
340 auto sdk_path_or_err =
342 if (!sdk_path_or_err) {
345 "Error while searching for Xcode SDK: {0}");
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;
376static llvm::Expected<std::string>
377xcrun(
const std::string &sdk, llvm::ArrayRef<llvm::StringRef> arguments,
378 llvm::StringRef developer_dir =
"") {
380 if (!developer_dir.empty()) {
387 for (
auto arg: arguments)
394 log->
Printf(
"GetXcodeSDK() running shell cmd '%s'", cmdstr.c_str());
399 std::string output_str;
402 auto timeout = std::chrono::seconds(60);
403 bool run_in_shell =
false;
405 args,
FileSpec(), &status, &signo, &output_str, timeout, run_in_shell);
410 LLDB_LOG(log,
"xcrun failed to execute: %s",
error.AsCString());
411 return error.ToError();
416 LLDB_LOG(log,
"xcrun returned exit code %d", status);
419 if (output_str.empty()) {
420 LLDB_LOG(log,
"xcrun returned no results");
426 llvm::StringRef output(output_str);
429 output = output.rtrim();
432 const size_t last_newline = output.rfind(
'\n');
433 if (last_newline != llvm::StringRef::npos)
434 output = output.substr(last_newline + 1);
442 if (sdk_name.empty())
443 return llvm::createStringError(llvm::inconvertibleErrorCode(),
444 "Unrecognized SDK type: " + sdk.
GetString());
449 [](
const std::string &sdk_name) -> llvm::Expected<std::string> {
450 llvm::SmallVector<llvm::StringRef, 1> show_sdk_path = {
"--show-sdk-path"};
453 if (!developer_dir.empty()) {
455 return xcrun(sdk_name, show_sdk_path, developer_dir);
459 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
461 std::string contents_dir =
463 llvm::StringRef shlib_developer_dir =
464 llvm::sys::path::parent_path(contents_dir);
465 if (!shlib_developer_dir.empty()) {
467 xcrun(sdk_name, show_sdk_path, std::move(shlib_developer_dir));
469 return sdk.takeError();
477 return xcrun(sdk_name, show_sdk_path);
480 auto path_or_err = find_sdk(sdk_name);
482 return path_or_err.takeError();
483 std::string path = *path_or_err;
484 while (path.empty()) {
488 llvm::StringRef fixed(sdk_name);
489 if (fixed.consume_back(
".internal"))
490 sdk_name = fixed.str() +
"internal";
491 path_or_err = find_sdk(sdk_name);
493 return path_or_err.takeError();
498 LLDB_LOG(log,
"Couldn't find SDK {0} on host", sdk_name);
504 path_or_err = find_sdk(sdk_name);
506 return path_or_err.takeError();
512 LLDB_LOG(log,
"Couldn't find any matching SDK on host");
518 LLDB_LOG(log,
"SDK returned by xcrun doesn't exist");
519 return llvm::createStringError(llvm::inconvertibleErrorCode(),
520 "SDK returned by xcrun doesn't exist");
532static llvm::Expected<llvm::StringRef>
535 std::function<llvm::Expected<std::string>(
void)> compute) {
536 std::lock_guard<std::mutex> guard(mutex);
539 auto it = cache.find(key);
540 if (it != cache.end()) {
541 if (it->second.is_error)
542 return llvm::createStringError(llvm::inconvertibleErrorCode(),
544 return it->second.str;
546 auto path_or_err = compute();
549 cache.insert({key, {
error,
true}});
550 return llvm::createStringError(llvm::inconvertibleErrorCode(),
error);
552 auto it_new = cache.insert({key, {*path_or_err,
false}});
553 return it_new.first->second.str;
557 static llvm::StringMap<ErrorOrPath> g_sdk_path;
558 static std::mutex g_sdk_path_mutex;
560 return llvm::createStringError(llvm::inconvertibleErrorCode(),
561 "XcodeSDK not specified");
569llvm::Expected<llvm::StringRef>
571 static llvm::StringMap<ErrorOrPath> g_tool_path;
572 static std::mutex g_tool_path_mutex;
574 llvm::raw_string_ostream(key) << sdk.
GetString() <<
":" << tool;
576 g_tool_path, g_tool_path_mutex, key,
577 [&]() -> llvm::Expected<std::string> {
579 if (sdk_name.empty())
580 return llvm::createStringError(llvm::inconvertibleErrorCode(),
581 "Unrecognized SDK type: " +
583 llvm::SmallVector<llvm::StringRef, 2> find = {
"-find", tool};
584 return xcrun(sdk_name, find);
589struct dyld_shared_cache_dylib_text_info {
592 uint64_t loadAddressUnslid;
593 uint64_t textSegmentSize;
597 uint64_t textSegmentOffset;
599typedef struct dyld_shared_cache_dylib_text_info
600 dyld_shared_cache_dylib_text_info;
605 void (^callback)(
const dyld_shared_cache_dylib_text_info *info));
610class SharedCacheInfo {
612 const UUID &GetUUID()
const {
return m_uuid; }
613 const llvm::StringMap<SharedCacheImageInfo> &GetImages()
const {
620 bool CreateSharedCacheInfoWithInstrospectionSPIs();
622 llvm::StringMap<SharedCacheImageInfo> m_images;
627bool SharedCacheInfo::CreateSharedCacheInfoWithInstrospectionSPIs() {
628#if defined(SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS)
629 dyld_process_t dyld_process = dyld_process_create_for_current_task();
633 dyld_process_snapshot_t snapshot =
634 dyld_process_snapshot_create_for_process(dyld_process,
nullptr);
639 llvm::make_scope_exit([&]() { dyld_process_snapshot_dispose(snapshot); });
641 dyld_shared_cache_t shared_cache =
642 dyld_process_snapshot_get_shared_cache(snapshot);
646 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
648 __block uint64_t maxVmAddr = 0;
650 __block
uuid_t *uuid = &uuidStore;
652 dyld_image_for_each_segment_info(
654 ^(
const char *segmentName, uint64_t vmAddr, uint64_t vmSize,
int perm) {
655 minVmAddr = std::min(minVmAddr, vmAddr);
656 maxVmAddr = std::max(maxVmAddr, vmAddr + vmSize);
657 dyld_image_copy_uuid(image, uuid);
659 assert(minVmAddr != UINT_MAX);
660 assert(maxVmAddr != 0);
662 UUID(uuid, 16), std::make_shared<DataBufferUnowned>(
663 (uint8_t *)minVmAddr, maxVmAddr - minVmAddr)};
670SharedCacheInfo::SharedCacheInfo() {
671 if (CreateSharedCacheInfoWithInstrospectionSPIs())
674 size_t shared_cache_size;
675 uint8_t *shared_cache_start =
679 m_uuid =
UUID(dsc_uuid);
682 dsc_uuid, ^(
const dyld_shared_cache_dylib_text_info *info) {
684 UUID(info->dylibUuid, 16),
685 std::make_shared<DataBufferUnowned>(
686 shared_cache_start + info->textSegmentOffset,
687 shared_cache_size - info->textSegmentOffset)};
693 static SharedCacheInfo g_shared_cache_info;
694 return g_shared_cache_info.GetImages().lookup(image_name);
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)
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_LOG_ERROR(log, error,...)
#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 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 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 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 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.
void 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)
std::optional< XcodeSDK > XcodeSDKSelection
A parsed SDK directory name.
llvm::VersionTuple version