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;
132 std::string raw_path = lldb_file_spec.
GetPath();
134 size_t framework_pos = raw_path.find(
"LLDB.framework");
135 if (framework_pos != std::string::npos) {
136 framework_pos += strlen(
"LLDB.framework");
139 raw_path.resize(framework_pos);
142 raw_path.resize(framework_pos);
143 raw_path.append(
"/Resources");
153 raw_path.append(
"/../bin");
154 FileSpec support_dir_spec(raw_path);
158 LLDB_LOG(log,
"failed to find support directory");
164 char *
const dir_realpath =
165 realpath(support_dir_spec.
GetPath().c_str(), NULL);
167 raw_path = dir_realpath;
170 raw_path = support_dir_spec.
GetPath();
183 std::string raw_path = lldb_file_spec.
GetPath();
185 size_t framework_pos = raw_path.find(
"LLDB.framework");
186 if (framework_pos != std::string::npos) {
187 framework_pos += strlen(
"LLDB.framework");
188 raw_path.resize(framework_pos);
189 raw_path.append(
"/Headers");
200 std::string raw_path = lldb_file_spec.
GetPath();
202 size_t framework_pos = raw_path.find(
"LLDB.framework");
203 if (framework_pos == std::string::npos)
206 framework_pos += strlen(
"LLDB.framework");
207 raw_path.resize(framework_pos);
208 raw_path.append(
"/Resources/PlugIns");
214 FileSpec temp_file(
"~/Library/Application Support/LLDB/PlugIns");
223 uint32_t cputype, cpusubtype;
224 uint32_t is_64_bit_capable =
false;
225 size_t len =
sizeof(cputype);
229 if (::sysctlbyname(
"hw.cputype", &cputype, &len, NULL, 0) == 0) {
230 len =
sizeof(cpusubtype);
231 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
232 cpusubtype = CPU_TYPE_ANY;
234 len =
sizeof(is_64_bit_capable);
235 ::sysctlbyname(
"hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0);
237 if (cputype ==
CPU_TYPE_ARM64 && cpusubtype == CPU_SUBTYPE_ARM64E) {
240 cpusubtype = CPU_SUBTYPE_ARM64_ALL;
243 if (is_64_bit_capable) {
244 if (cputype & CPU_ARCH_ABI64) {
255 uint32_t cpusubtype32 = cpusubtype;
256#if defined(__i386__) || defined(__x86_64__)
258 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
259#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
261 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
266 if (cputype == CPU_TYPE_ARM ||
270#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
271 arch_32.
GetTriple().setOS(llvm::Triple::TvOS);
272 arch_64.
GetTriple().setOS(llvm::Triple::TvOS);
273#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
274 arch_32.
GetTriple().setOS(llvm::Triple::BridgeOS);
275 arch_64.
GetTriple().setOS(llvm::Triple::BridgeOS);
276#elif defined(TARGET_OS_WATCHOS) && TARGET_OS_WATCHOS == 1
277 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
278 arch_64.
GetTriple().setOS(llvm::Triple::WatchOS);
279#elif defined(TARGET_OS_XR) && TARGET_OS_XR == 1
280 arch_32.
GetTriple().setOS(llvm::Triple::XROS);
281 arch_64.
GetTriple().setOS(llvm::Triple::XROS);
282#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1
283 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
284 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
286 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
287 arch_64.
GetTriple().setOS(llvm::Triple::IOS);
290 arch_32.
GetTriple().setOS(llvm::Triple::MacOSX);
291 arch_64.
GetTriple().setOS(llvm::Triple::MacOSX);
296#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
297 arch_32.
GetTriple().setOS(llvm::Triple::WatchOS);
299 arch_32.
GetTriple().setOS(llvm::Triple::IOS);
308 static std::string g_env_developer_dir;
309 static std::once_flag g_once_flag;
310 std::call_once(g_once_flag, [&]() {
311 if (
const char *developer_dir_env_var = getenv(
"DEVELOPER_DIR")) {
312 FileSpec fspec(developer_dir_env_var);
314 g_env_developer_dir = fspec.
GetPath();
316 return g_env_developer_dir;
320 static FileSpec g_xcode_contents_path;
321 static std::once_flag g_once_flag;
322 std::call_once(g_once_flag, [&]() {
324 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
326 std::string xcode_contents_dir =
328 if (!xcode_contents_dir.empty()) {
329 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
336 if (!env_developer_dir.empty()) {
337 llvm::sys::path::append(env_developer_dir,
"Contents");
338 std::string xcode_contents_dir =
340 if (!xcode_contents_dir.empty()) {
341 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
346 auto sdk_path_or_err =
348 if (!sdk_path_or_err) {
351 "Error while searching for Xcode SDK: {0}");
357 std::string xcode_contents_dir =
359 if (!xcode_contents_dir.empty()) {
360 g_xcode_contents_path =
FileSpec(xcode_contents_dir);
366 return g_xcode_contents_path;
371 static llvm::once_flag g_once_flag;
372 llvm::call_once(g_once_flag, []() {
374 fspec.AppendPathComponent(
"Developer");
376 g_developer_directory = fspec;
379 return g_developer_directory;
382static llvm::Expected<std::string>
383xcrun(
const std::string &sdk, llvm::ArrayRef<llvm::StringRef> arguments,
384 llvm::StringRef developer_dir =
"") {
386 if (!developer_dir.empty()) {
393 for (
auto arg: arguments)
400 LLDB_LOG(log,
"GetXcodeSDK() running shell cmd '{0}'", cmdstr);
405 std::string output_str;
408 auto timeout = std::chrono::seconds(60);
409 bool run_in_shell =
false;
411 args,
FileSpec(), &status, &signo, &output_str, timeout, run_in_shell);
417 return error.ToError();
422 LLDB_LOG(log,
"xcrun returned exit code {0}", status);
423 if (!output_str.empty())
424 LLDB_LOG(log,
"xcrun output was:\n{0}", output_str);
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);
450 if (sdk_name.empty())
451 return llvm::createStringError(llvm::inconvertibleErrorCode(),
452 "Unrecognized SDK type: " + sdk.
GetString());
457 [](
const std::string &sdk_name) -> llvm::Expected<std::string> {
458 llvm::SmallVector<llvm::StringRef, 1> show_sdk_path = {
"--show-sdk-path"};
461 if (!developer_dir.empty()) {
463 return xcrun(sdk_name, show_sdk_path, developer_dir);
467 if (
FileSpec fspec = HostInfo::GetShlibDir()) {
469 llvm::SmallString<0> shlib_developer_dir(
471 llvm::sys::path::append(shlib_developer_dir,
"Developer");
473 auto sdk =
xcrun(sdk_name, show_sdk_path, shlib_developer_dir);
475 return sdk.takeError();
483 return xcrun(sdk_name, show_sdk_path);
486 auto path_or_err = find_sdk(sdk_name);
488 return path_or_err.takeError();
489 std::string path = *path_or_err;
490 while (path.empty()) {
494 llvm::StringRef fixed(sdk_name);
495 if (fixed.consume_back(
".internal"))
496 sdk_name = fixed.str() +
"internal";
497 path_or_err = find_sdk(sdk_name);
499 return path_or_err.takeError();
504 LLDB_LOG(log,
"Couldn't find SDK {0} on host", sdk_name);
510 path_or_err = find_sdk(sdk_name);
512 return path_or_err.takeError();
518 LLDB_LOG(log,
"Couldn't find any matching SDK on host");
524 LLDB_LOG(log,
"SDK returned by xcrun doesn't exist");
525 return llvm::createStringError(llvm::inconvertibleErrorCode(),
526 "SDK returned by xcrun doesn't exist");
538static llvm::Expected<llvm::StringRef>
541 std::function<llvm::Expected<std::string>(
void)> compute) {
542 std::lock_guard<std::mutex> guard(mutex);
545 auto it = cache.find(key);
546 if (it != cache.end()) {
547 if (it->second.is_error)
548 return llvm::createStringError(llvm::inconvertibleErrorCode(),
550 return it->second.str;
552 auto path_or_err = compute();
555 cache.insert({key, {
error,
true}});
556 return llvm::createStringError(llvm::inconvertibleErrorCode(),
error);
558 auto it_new = cache.insert({key, {*path_or_err,
false}});
559 return it_new.first->second.str;
563 static llvm::StringMap<ErrorOrPath> g_sdk_path;
564 static std::mutex g_sdk_path_mutex;
566 return llvm::createStringError(llvm::inconvertibleErrorCode(),
567 "XcodeSDK not specified");
575llvm::Expected<llvm::StringRef>
577 static llvm::StringMap<ErrorOrPath> g_tool_path;
578 static std::mutex g_tool_path_mutex;
580 llvm::raw_string_ostream(key) << sdk.
GetString() <<
":" << tool;
582 g_tool_path, g_tool_path_mutex, key,
583 [&]() -> llvm::Expected<std::string> {
585 if (sdk_name.empty())
586 return llvm::createStringError(llvm::inconvertibleErrorCode(),
587 "Unrecognized SDK type: " +
589 llvm::SmallVector<llvm::StringRef, 2> find = {
"-find", tool};
590 return xcrun(sdk_name, find);
595struct dyld_shared_cache_dylib_text_info {
598 uint64_t loadAddressUnslid;
599 uint64_t textSegmentSize;
603 uint64_t textSegmentOffset;
605typedef struct dyld_shared_cache_dylib_text_info
606 dyld_shared_cache_dylib_text_info;
611 void (^callback)(
const dyld_shared_cache_dylib_text_info *info));
616class SharedCacheInfo {
618 const UUID &GetUUID()
const {
return m_uuid; }
619 const llvm::StringMap<SharedCacheImageInfo> &GetImages()
const {
626 bool CreateSharedCacheInfoWithInstrospectionSPIs();
628 llvm::StringMap<SharedCacheImageInfo> m_images;
633bool SharedCacheInfo::CreateSharedCacheInfoWithInstrospectionSPIs() {
634#if defined(SDK_HAS_NEW_DYLD_INTROSPECTION_SPIS)
635 dyld_process_t dyld_process = dyld_process_create_for_current_task();
639 dyld_process_snapshot_t snapshot =
640 dyld_process_snapshot_create_for_process(dyld_process,
nullptr);
645 llvm::make_scope_exit([&]() { dyld_process_snapshot_dispose(snapshot); });
647 dyld_shared_cache_t shared_cache =
648 dyld_process_snapshot_get_shared_cache(snapshot);
652 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
654 __block uint64_t maxVmAddr = 0;
656 __block
uuid_t *uuid = &uuidStore;
658 dyld_image_for_each_segment_info(
660 ^(
const char *segmentName, uint64_t vmAddr, uint64_t vmSize,
int perm) {
661 minVmAddr = std::min(minVmAddr, vmAddr);
662 maxVmAddr = std::max(maxVmAddr, vmAddr + vmSize);
663 dyld_image_copy_uuid(image, uuid);
665 assert(minVmAddr != UINT_MAX);
666 assert(maxVmAddr != 0);
668 UUID(uuid, 16), std::make_shared<DataBufferUnowned>(
669 (uint8_t *)minVmAddr, maxVmAddr - minVmAddr)};
676SharedCacheInfo::SharedCacheInfo() {
677 if (CreateSharedCacheInfoWithInstrospectionSPIs())
680 size_t shared_cache_size;
681 uint8_t *shared_cache_start =
685 m_uuid =
UUID(dsc_uuid);
688 dsc_uuid, ^(
const dyld_shared_cache_dylib_text_info *info) {
690 UUID(info->dylibUuid, 16),
691 std::make_shared<DataBufferUnowned>(
692 shared_cache_start + info->textSegmentOffset,
693 shared_cache_size - info->textSegmentOffset)};
699 static SharedCacheInfo g_shared_cache_info;
700 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.
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