18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/raw_ostream.h"
31#include <sys/sysctl.h>
32#include <sys/syslimits.h>
37#include <AvailabilityMacros.h>
38#include <CoreFoundation/CoreFoundation.h>
39#include <Foundation/Foundation.h>
40#include <mach-o/dyld.h>
41#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && \
42 MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_VERSION_12_0
43#if __has_include(<mach-o/dyld_introspection.h>)
44#include <mach-o/dyld_introspection.h>
45#define SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS
48#include <objc/objc-auto.h>
52#ifndef CPU_SUBTYPE_X86_64_H
53#define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
56#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
59#ifndef CPU_TYPE_ARM64_32
60#define CPU_ARCH_ABI64_32 0x02000000
61#define CPU_TYPE_ARM64_32 (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)
64#include <TargetConditionals.h>
69 int mib[2] = {CTL_KERN, KERN_OSVERSION};
71 size_t cstr_len =
sizeof(cstr);
72 if (::sysctl(mib, 2, cstr, &cstr_len, NULL, 0) == 0)
73 return std::string(cstr, cstr_len - 1);
80 NSDictionary *version_info =
81 [NSDictionary dictionaryWithContentsOfFile:
82 @"/System/Library/CoreServices/SystemVersion.plist"];
83 NSString *version_value = [version_info objectForKey: Key];
84 const char *version_str = [version_value UTF8String];
85 version.tryParse(version_str);
90 static llvm::VersionTuple g_version;
91 if (g_version.empty())
97 static llvm::VersionTuple g_version;
98 if (g_version.empty())
106 if (!g_program_filespec) {
109 uint32_t len =
sizeof(program_fullpath);
110 int err = _NSGetExecutablePath(program_fullpath, &len);
112 g_program_filespec.
SetFile(program_fullpath, FileSpec::Style::native);
113 else if (err == -1) {
114 char *large_program_fullpath = (
char *)::malloc(len + 1);
116 err = _NSGetExecutablePath(large_program_fullpath, &len);
118 g_program_filespec.
SetFile(large_program_fullpath,
119 FileSpec::Style::native);
121 ::free(large_program_fullpath);
124 return g_program_filespec;
138 std::string raw_path = lldb_file_spec.
GetPath();
140 size_t framework_pos = raw_path.find(
"LLDB.framework");
141 if (framework_pos != std::string::npos) {
142 framework_pos += strlen(
"LLDB.framework");
145 raw_path.resize(framework_pos);
148 raw_path.resize(framework_pos);
149 raw_path.append(
"/Resources");
161 FileSpec support_dir_spec_lib(raw_path);
167 support_dir_spec = support_dir_spec_bin;
169 support_dir_spec = support_dir_spec_lib;
172 LLDB_LOG(log,
"failed to find support directory");
178 char *
const dir_realpath =
179 realpath(support_dir_spec.
GetPath().c_str(), NULL);
181 raw_path = dir_realpath;
184 raw_path = support_dir_spec.
GetPath();
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) {
201 framework_pos += strlen(
"LLDB.framework");
202 raw_path.resize(framework_pos);
203 raw_path.append(
"/Headers");
214 std::string raw_path = lldb_file_spec.
GetPath();
216 size_t framework_pos = raw_path.find(
"LLDB.framework");
217 if (framework_pos == std::string::npos)
220 framework_pos += strlen(
"LLDB.framework");
221 raw_path.resize(framework_pos);
222 raw_path.append(
"/Resources/PlugIns");
237 uint32_t cputype, cpusubtype;
238 uint32_t is_64_bit_capable =
false;
239 size_t len =
sizeof(cputype);
243 if (::sysctlbyname(
"hw.cputype", &cputype, &len, NULL, 0) == 0) {
244 len =
sizeof(cpusubtype);
245 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
246 cpusubtype = CPU_TYPE_ANY;
248 len =
sizeof(is_64_bit_capable);
249 ::sysctlbyname(
"hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0);
251 if (cputype ==
CPU_TYPE_ARM64 && cpusubtype == CPU_SUBTYPE_ARM64E) {
254 cpusubtype = CPU_SUBTYPE_ARM64_ALL;
257 if (is_64_bit_capable) {
258 if (cputype & CPU_ARCH_ABI64) {
269 uint32_t cpusubtype32 = cpusubtype;
270#if defined(__i386__) || defined(__x86_64__)
272 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
273#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
275 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
280 if (cputype == CPU_TYPE_ARM ||
284#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
285 arch_32.
GetTriple().setOS(llvm::Triple::TvOS);
286 arch_64.
GetTriple().setOS(llvm::Triple::TvOS);
287#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
288 arch_32.
GetTriple().setOS(llvm::Triple::BridgeOS);
289 arch_64.
GetTriple().setOS(llvm::Triple::BridgeOS);
290#elif defined(TARGET_OS_WATCHOS) && TARGET_OS_WATCHOS == 1
291 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
292 arch_64.
GetTriple().setOS(llvm::Triple::WatchOS);
293#elif defined(TARGET_OS_XR) && TARGET_OS_XR == 1
294 arch_32.
GetTriple().setOS(llvm::Triple::XROS);
295 arch_64.
GetTriple().setOS(llvm::Triple::XROS);
296#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1
297 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
298 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
300 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
301 arch_64.
GetTriple().setOS(llvm::Triple::IOS);
304 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
305 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
310#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
311 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
313 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
322 static std::string g_env_developer_dir;
323 static std::once_flag g_once_flag;
324 std::call_once(g_once_flag, [&]() {
325 if (
const char *developer_dir_env_var = getenv(
"DEVELOPER_DIR")) {
326 FileSpec fspec(developer_dir_env_var);
328 g_env_developer_dir = fspec.
GetPath();
330 return g_env_developer_dir;
334 static FileSpec g_xcode_contents_path;
335 static std::once_flag g_once_flag;
336 std::call_once(g_once_flag, [&]() {
338 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
340 std::string xcode_contents_dir =
342 if (!xcode_contents_dir.empty()) {
343 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
350 if (!env_developer_dir.empty()) {
351 llvm::sys::path::append(env_developer_dir,
"Contents");
352 std::string xcode_contents_dir =
354 if (!xcode_contents_dir.empty()) {
355 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
360 auto sdk_path_or_err =
362 if (!sdk_path_or_err) {
365 "Error while searching for Xcode SDK: {0}");
371 std::string xcode_contents_dir =
373 if (!xcode_contents_dir.empty()) {
374 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
380 return g_xcode_contents_path;
385 static llvm::once_flag g_once_flag;
386 llvm::call_once(g_once_flag, []() {
388 fspec.AppendPathComponent(
"Developer");
390 g_developer_directory = fspec;
393 return g_developer_directory;
397 llvm::StringRef component) {
398 auto begin = llvm::sys::path::begin(path);
399 auto end = llvm::sys::path::end(path);
400 for (
auto it = begin; it != end; ++it) {
401 if (it->contains(component)) {
402 llvm::SmallString<128> buffer;
403 llvm::sys::path::append(buffer, begin, ++it,
404 llvm::sys::path::Style::posix);
405 return buffer.str().str();
412 if (
FileSpec fspec = HostInfo::GetShlibDir())
418 if (
FileSpec fspec = HostInfo::GetShlibDir())
423static llvm::Expected<std::string>
424xcrun(
const std::string &sdk, llvm::ArrayRef<llvm::StringRef> arguments,
425 llvm::StringRef developer_dir =
"") {
427 if (!developer_dir.empty()) {
434 for (
auto arg: arguments)
441 LLDB_LOG(log,
"GetXcodeSDK() running shell cmd '{0}'", cmdstr);
446 std::string output_str;
449 auto timeout = std::chrono::seconds(60);
450 bool run_in_shell =
false;
452 args,
FileSpec(), &status, &signo, &output_str, timeout, run_in_shell);
458 return error.ToError();
463 LLDB_LOG(log,
"xcrun returned exit code {0}", status);
464 if (!output_str.empty())
465 LLDB_LOG(log,
"xcrun output was:\n{0}", output_str);
468 if (output_str.empty()) {
469 LLDB_LOG(log,
"xcrun returned no results");
475 llvm::StringRef output(output_str);
478 output = output.rtrim();
481 const size_t last_newline = output.rfind(
'\n');
482 if (last_newline != llvm::StringRef::npos)
483 output = output.substr(last_newline + 1);
491 if (sdk_name.empty())
492 return llvm::createStringError(llvm::inconvertibleErrorCode(),
493 "Unrecognized SDK type: " + sdk.
GetString());
498 [](
const std::string &sdk_name) -> llvm::Expected<std::string> {
499 llvm::SmallVector<llvm::StringRef, 1> show_sdk_path = {
"--show-sdk-path"};
502 if (!developer_dir.empty()) {
504 return xcrun(sdk_name, show_sdk_path, developer_dir);
508 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
510 llvm::SmallString<0> shlib_developer_dir(
512 llvm::sys::path::append(shlib_developer_dir,
"Developer");
514 auto sdk =
xcrun(sdk_name, show_sdk_path, shlib_developer_dir);
516 return sdk.takeError();
524 return xcrun(sdk_name, show_sdk_path);
527 auto path_or_err = find_sdk(sdk_name);
529 return path_or_err.takeError();
530 std::string path = *path_or_err;
531 while (path.empty()) {
535 llvm::StringRef fixed(sdk_name);
536 if (fixed.consume_back(
".internal"))
537 sdk_name = fixed.str() +
"internal";
538 path_or_err = find_sdk(sdk_name);
540 return path_or_err.takeError();
545 LLDB_LOG(log,
"Couldn't find SDK {0} on host", sdk_name);
551 path_or_err = find_sdk(sdk_name);
553 return path_or_err.takeError();
559 LLDB_LOG(log,
"Couldn't find any matching SDK on host");
565 LLDB_LOG(log,
"SDK returned by xcrun doesn't exist");
566 return llvm::createStringError(llvm::inconvertibleErrorCode(),
567 "SDK returned by xcrun doesn't exist");
579static llvm::Expected<llvm::StringRef>
582 std::function<llvm::Expected<std::string>(
void)> compute) {
583 std::lock_guard<std::mutex> guard(mutex);
586 auto it = cache.find(key);
587 if (it != cache.end()) {
588 if (it->second.is_error)
589 return llvm::createStringError(llvm::inconvertibleErrorCode(),
591 return it->second.str;
593 auto path_or_err = compute();
596 cache.insert({key, {
error,
true}});
597 return llvm::createStringError(llvm::inconvertibleErrorCode(),
error);
599 auto it_new = cache.insert({key, {*path_or_err,
false}});
600 return it_new.first->second.str;
604 static llvm::StringMap<ErrorOrPath> g_sdk_path;
605 static std::mutex g_sdk_path_mutex;
607 return llvm::createStringError(llvm::inconvertibleErrorCode(),
608 "XcodeSDK not specified");
616llvm::Expected<llvm::StringRef>
618 static llvm::StringMap<ErrorOrPath> g_tool_path;
619 static std::mutex g_tool_path_mutex;
621 llvm::raw_string_ostream(key) << sdk.
GetString() <<
":" << tool;
623 g_tool_path, g_tool_path_mutex, key,
624 [&]() -> llvm::Expected<std::string> {
626 if (sdk_name.empty())
627 return llvm::createStringError(llvm::inconvertibleErrorCode(),
628 "Unrecognized SDK type: " +
630 llvm::SmallVector<llvm::StringRef, 2> find = {
"-find", tool};
631 return xcrun(sdk_name, find);
636struct dyld_shared_cache_dylib_text_info {
639 uint64_t loadAddressUnslid;
640 uint64_t textSegmentSize;
644 uint64_t textSegmentOffset;
646typedef struct dyld_shared_cache_dylib_text_info
647 dyld_shared_cache_dylib_text_info;
652 void (^callback)(
const dyld_shared_cache_dylib_text_info *info));
657class SharedCacheInfo {
659 const UUID &GetUUID()
const {
return m_uuid; }
660 const llvm::StringMap<SharedCacheImageInfo> &GetImages()
const {
667 bool CreateSharedCacheInfoWithInstrospectionSPIs();
669 llvm::StringMap<SharedCacheImageInfo> m_images;
674bool SharedCacheInfo::CreateSharedCacheInfoWithInstrospectionSPIs() {
675#if defined(SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS)
676 dyld_process_t dyld_process = dyld_process_create_for_current_task();
680 auto cleanup_process_on_exit =
681 llvm::make_scope_exit([&]() { dyld_process_dispose(dyld_process); });
683 dyld_process_snapshot_t snapshot =
684 dyld_process_snapshot_create_for_process(dyld_process,
nullptr);
688 auto cleanup_snapshot_on_exit =
689 llvm::make_scope_exit([&]() { dyld_process_snapshot_dispose(snapshot); });
691 dyld_shared_cache_t shared_cache =
692 dyld_process_snapshot_get_shared_cache(snapshot);
696 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
698 __block uint64_t maxVmAddr = 0;
700 __block
uuid_t *uuid = &uuidStore;
702 dyld_image_for_each_segment_info(
704 ^(
const char *segmentName, uint64_t vmAddr, uint64_t vmSize,
int perm) {
705 minVmAddr = std::min(minVmAddr, vmAddr);
706 maxVmAddr = std::max(maxVmAddr, vmAddr + vmSize);
707 dyld_image_copy_uuid(image, uuid);
709 assert(minVmAddr != UINT_MAX);
710 assert(maxVmAddr != 0);
712 UUID(uuid, 16), std::make_shared<DataBufferUnowned>(
713 (uint8_t *)minVmAddr, maxVmAddr - minVmAddr)};
720SharedCacheInfo::SharedCacheInfo() {
721 if (CreateSharedCacheInfoWithInstrospectionSPIs())
724 size_t shared_cache_size;
725 uint8_t *shared_cache_start =
729 m_uuid =
UUID(dsc_uuid);
732 dsc_uuid, ^(
const dyld_shared_cache_dylib_text_info *info) {
734 UUID(info->dylibUuid, 16),
735 std::make_shared<DataBufferUnowned>(
736 shared_cache_start + info->textSegmentOffset,
737 shared_cache_size - info->textSegmentOffset)};
743 static SharedCacheInfo g_shared_cache_info;
744 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)
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_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.
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
void AppendPathComponent(llvm::StringRef component)
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.
bool IsDirectory(const FileSpec &file_spec) const
Returns whether the given path is a directory.
static FileSystem & Instance()
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.
Represents UUID's of various sizes.
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