brintos

brintos / llvm-project-archived public Read only

0
0
Text · 22.4 KiB · 47111c9 Raw
660 lines · cpp
1//===-- PlatformAppleSimulator.cpp ----------------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "PlatformAppleSimulator.h"10 11#if defined(__APPLE__)12#include <dlfcn.h>13#endif14 15#include "lldb/Core/Debugger.h"16#include "lldb/Core/Module.h"17#include "lldb/Core/PluginManager.h"18#include "lldb/Host/HostInfo.h"19#include "lldb/Host/PseudoTerminal.h"20#include "lldb/Target/Process.h"21#include "lldb/Utility/LLDBAssert.h"22#include "lldb/Utility/LLDBLog.h"23#include "lldb/Utility/Log.h"24#include "lldb/Utility/Status.h"25#include "lldb/Utility/StreamString.h"26 27#include "llvm/Support/Threading.h"28 29#include <mutex>30#include <thread>31 32using namespace lldb;33using namespace lldb_private;34 35#if !defined(__APPLE__)36#define UNSUPPORTED_ERROR ("Apple simulators aren't supported on this platform")37#endif38 39/// Default Constructor40PlatformAppleSimulator::PlatformAppleSimulator(41    const char *class_name, const char *description, ConstString plugin_name,42    llvm::Triple::OSType preferred_os,43    llvm::SmallVector<llvm::StringRef, 4> supported_triples,44    std::string sdk_name_primary, std::string sdk_name_secondary,45    lldb_private::XcodeSDK::Type sdk_type,46    CoreSimulatorSupport::DeviceType::ProductFamilyID kind)47    : PlatformDarwin(true), m_class_name(class_name),48      m_description(description), m_plugin_name(plugin_name), m_kind(kind),49      m_os_type(preferred_os), m_supported_triples(supported_triples),50      m_sdk_name_primary(std::move(sdk_name_primary)),51      m_sdk_name_secondary(std::move(sdk_name_secondary)),52      m_sdk_type(sdk_type) {}53 54/// Destructor.55///56/// The destructor is virtual since this class is designed to be57/// inherited from by the plug-in instance.58PlatformAppleSimulator::~PlatformAppleSimulator() = default;59 60lldb_private::Status PlatformAppleSimulator::LaunchProcess(61    lldb_private::ProcessLaunchInfo &launch_info) {62#if defined(__APPLE__)63  LoadCoreSimulator();64  CoreSimulatorSupport::Device device(GetSimulatorDevice());65 66  if (device.GetState() != CoreSimulatorSupport::Device::State::Booted) {67    Status boot_err;68    device.Boot(boot_err);69    if (boot_err.Fail())70      return boot_err;71  }72 73  auto spawned = device.Spawn(launch_info);74 75  if (spawned) {76    launch_info.SetProcessID(spawned.GetPID());77    return Status();78  } else79    return spawned.GetError();80#else81  Status err;82  err = Status::FromErrorString(UNSUPPORTED_ERROR);83  return err;84#endif85}86 87void PlatformAppleSimulator::GetStatus(Stream &strm) {88  Platform::GetStatus(strm);89  llvm::StringRef sdk = GetSDKFilepath();90  if (!sdk.empty())91    strm << "  SDK Path: \"" << sdk << "\"\n";92  else93    strm << "  SDK Path: <unable to locate SDK>\n";94 95#if defined(__APPLE__)96  // This will get called by subclasses, so just output status on the current97  // simulator98  PlatformAppleSimulator::LoadCoreSimulator();99 100  std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();101  CoreSimulatorSupport::DeviceSet devices =102      CoreSimulatorSupport::DeviceSet::GetAvailableDevices(103          developer_dir.c_str());104  const size_t num_devices = devices.GetNumDevices();105  if (num_devices) {106    strm.Printf("Available devices:\n");107    for (size_t i = 0; i < num_devices; ++i) {108      CoreSimulatorSupport::Device device = devices.GetDeviceAtIndex(i);109      strm << "   " << device.GetUDID() << ": " << device.GetName() << "\n";110    }111 112    if (m_device.has_value() && m_device->operator bool()) {113      strm << "Current device: " << m_device->GetUDID() << ": "114           << m_device->GetName();115      if (m_device->GetState() == CoreSimulatorSupport::Device::State::Booted) {116        strm << " state = booted";117      }118      strm << "\nType \"platform connect <ARG>\" where <ARG> is a device "119              "UDID or a device name to disconnect and connect to a "120              "different device.\n";121 122    } else {123      strm << "No current device is selected, \"platform connect <ARG>\" "124              "where <ARG> is a device UDID or a device name to connect to "125              "a specific device.\n";126    }127 128  } else {129    strm << "No devices are available.\n";130  }131#else132  strm << UNSUPPORTED_ERROR;133#endif134}135 136Status PlatformAppleSimulator::ConnectRemote(Args &args) {137#if defined(__APPLE__)138  Status error;139  if (args.GetArgumentCount() == 1) {140    if (m_device)141      DisconnectRemote();142    PlatformAppleSimulator::LoadCoreSimulator();143    const char *arg_cstr = args.GetArgumentAtIndex(0);144    if (arg_cstr) {145      std::string arg_str(arg_cstr);146      std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();147      CoreSimulatorSupport::DeviceSet devices =148          CoreSimulatorSupport::DeviceSet::GetAvailableDevices(149              developer_dir.c_str());150      devices.ForEach(151          [this, &arg_str](const CoreSimulatorSupport::Device &device) -> bool {152            if (arg_str == device.GetUDID() || arg_str == device.GetName()) {153              m_device = device;154              return false; // Stop iterating155            } else {156              return true; // Keep iterating157            }158          });159      if (!m_device)160        error = Status::FromErrorStringWithFormat(161            "no device with UDID or name '%s' was found", arg_cstr);162    }163  } else {164    error = Status::FromErrorString(165        "this command take a single UDID argument of the "166        "device you want to connect to.");167  }168  return error;169#else170  Status err;171  err = Status::FromErrorString(UNSUPPORTED_ERROR);172  return err;173#endif174}175 176Status PlatformAppleSimulator::DisconnectRemote() {177#if defined(__APPLE__)178  m_device.reset();179  return Status();180#else181  Status err;182  err = Status::FromErrorString(UNSUPPORTED_ERROR);183  return err;184#endif185}186 187lldb::ProcessSP188PlatformAppleSimulator::DebugProcess(ProcessLaunchInfo &launch_info,189                                     Debugger &debugger, Target &target,190                                     Status &error) {191#if defined(__APPLE__)192  ProcessSP process_sp;193  // Make sure we stop at the entry point194  launch_info.GetFlags().Set(eLaunchFlagDebug);195  // We always launch the process we are going to debug in a separate process196  // group, since then we can handle ^C interrupts ourselves w/o having to197  // worry about the target getting them as well.198  launch_info.SetLaunchInSeparateProcessGroup(true);199 200  error = LaunchProcess(launch_info);201  if (error.Success()) {202    if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {203      ProcessAttachInfo attach_info(launch_info);204      process_sp = Attach(attach_info, debugger, &target, error);205      if (process_sp) {206        launch_info.SetHijackListener(attach_info.GetHijackListener());207 208        // Since we attached to the process, it will think it needs to detach209        // if the process object just goes away without an explicit call to210        // Process::Kill() or Process::Detach(), so let it know to kill the211        // process if this happens.212        process_sp->SetShouldDetach(false);213 214        // If we didn't have any file actions, the pseudo terminal might have215        // been used where the secondary side was given as the file to open for216        // stdin/out/err after we have already opened the primary so we can217        // read/write stdin/out/err.218        int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();219        if (pty_fd != PseudoTerminal::invalid_fd) {220          process_sp->SetSTDIOFileDescriptor(pty_fd);221        }222      }223    }224  }225 226  return process_sp;227#else228  return ProcessSP();229#endif230}231 232FileSpec PlatformAppleSimulator::GetCoreSimulatorPath() {233#if defined(__APPLE__)234  std::lock_guard<std::mutex> guard(m_core_sim_path_mutex);235  if (!m_core_simulator_framework_path.has_value()) {236    m_core_simulator_framework_path =237        FileSpec("/Library/Developer/PrivateFrameworks/CoreSimulator.framework/"238                 "CoreSimulator");239    FileSystem::Instance().Resolve(*m_core_simulator_framework_path);240  }241  return m_core_simulator_framework_path.value();242#else243  return FileSpec();244#endif245}246 247void PlatformAppleSimulator::LoadCoreSimulator() {248#if defined(__APPLE__)249  static llvm::once_flag g_load_core_sim_flag;250  llvm::call_once(g_load_core_sim_flag, [this] {251    const std::string core_sim_path(GetCoreSimulatorPath().GetPath());252    if (core_sim_path.size())253      dlopen(core_sim_path.c_str(), RTLD_LAZY);254  });255#endif256}257 258#if defined(__APPLE__)259CoreSimulatorSupport::Device PlatformAppleSimulator::GetSimulatorDevice() {260  if (!m_device.has_value()) {261    const CoreSimulatorSupport::DeviceType::ProductFamilyID dev_id = m_kind;262    std::string developer_dir =263        HostInfo::GetXcodeDeveloperDirectory().GetPath();264    m_device = CoreSimulatorSupport::DeviceSet::GetAvailableDevices(265                   developer_dir.c_str())266                   .GetFanciest(dev_id);267  }268 269  if (m_device.has_value())270    return m_device.value();271  else272    return CoreSimulatorSupport::Device();273}274#endif275 276std::vector<ArchSpec> PlatformAppleSimulator::GetSupportedArchitectures(277    const ArchSpec &process_host_arch) {278  std::vector<ArchSpec> result(m_supported_triples.size());279  llvm::transform(m_supported_triples, result.begin(),280                  [](llvm::StringRef triple) { return ArchSpec(triple); });281  return result;282}283 284static llvm::StringRef GetXcodeSDKDir(std::string preferred,285                                      std::string secondary) {286  llvm::StringRef sdk;287  auto get_sdk = [&](std::string sdk) -> llvm::StringRef {288    auto sdk_path_or_err =289        HostInfo::GetSDKRoot(HostInfo::SDKOptions{XcodeSDK(std::move(sdk))});290    if (!sdk_path_or_err) {291      Debugger::ReportError("Error while searching for Xcode SDK: " +292                            toString(sdk_path_or_err.takeError()));293      return {};294    }295    return *sdk_path_or_err;296  };297 298  sdk = get_sdk(preferred);299  if (sdk.empty())300    sdk = get_sdk(secondary);301  return sdk;302}303 304llvm::StringRef PlatformAppleSimulator::GetSDKFilepath() {305  if (!m_have_searched_for_sdk) {306    m_sdk = GetXcodeSDKDir(m_sdk_name_primary, m_sdk_name_secondary);307    m_have_searched_for_sdk = true;308  }309  return m_sdk;310}311 312PlatformSP PlatformAppleSimulator::CreateInstance(313    const char *class_name, const char *description, ConstString plugin_name,314    llvm::SmallVector<llvm::Triple::ArchType, 4> supported_arch,315    llvm::Triple::OSType preferred_os,316    llvm::SmallVector<llvm::Triple::OSType, 4> supported_os,317    llvm::SmallVector<llvm::StringRef, 4> supported_triples,318    std::string sdk_name_primary, std::string sdk_name_secondary,319    lldb_private::XcodeSDK::Type sdk_type,320    CoreSimulatorSupport::DeviceType::ProductFamilyID kind, bool force,321    const ArchSpec *arch) {322  Log *log = GetLog(LLDBLog::Platform);323  if (log) {324    const char *arch_name;325    if (arch && arch->GetArchitectureName())326      arch_name = arch->GetArchitectureName();327    else328      arch_name = "<null>";329 330    const char *triple_cstr =331        arch ? arch->GetTriple().getTriple().c_str() : "<null>";332 333    LLDB_LOGF(log, "%s::%s(force=%s, arch={%s,%s})", class_name, __FUNCTION__,334              force ? "true" : "false", arch_name, triple_cstr);335  }336 337  bool create = force;338  if (!create && arch && arch->IsValid()) {339    if (llvm::is_contained(supported_arch, arch->GetMachine())) {340      const llvm::Triple &triple = arch->GetTriple();341      switch (triple.getVendor()) {342      case llvm::Triple::Apple:343        create = true;344        break;345 346#if defined(__APPLE__)347      // Only accept "unknown" for the vendor if the host is Apple and if348      // "unknown" wasn't specified (it was just returned because it was NOT349      // specified)350      case llvm::Triple::UnknownVendor:351        create = !arch->TripleVendorWasSpecified();352        break;353#endif354      default:355        break;356      }357 358      if (create) {359        if (llvm::is_contained(supported_os, triple.getOS()))360          create = true;361#if defined(__APPLE__)362        // Only accept "unknown" for the OS if the host is Apple and it363        // "unknown" wasn't specified (it was just returned because it was NOT364        // specified)365        else if (triple.getOS() == llvm::Triple::UnknownOS)366          create = !arch->TripleOSWasSpecified();367#endif368        else369          create = false;370      }371    }372  }373  if (create) {374    LLDB_LOGF(log, "%s::%s() creating platform", class_name, __FUNCTION__);375 376    return PlatformSP(new PlatformAppleSimulator(377        class_name, description, plugin_name, preferred_os, supported_triples,378        sdk_name_primary, sdk_name_secondary, sdk_type, kind));379  }380 381  LLDB_LOGF(log, "%s::%s() aborting creation of platform", class_name,382            __FUNCTION__);383 384  return PlatformSP();385}386 387Status PlatformAppleSimulator::GetSymbolFile(const FileSpec &platform_file,388                                             const UUID *uuid_ptr,389                                             FileSpec &local_file) {390  Status error;391  char platform_file_path[PATH_MAX];392  if (platform_file.GetPath(platform_file_path, sizeof(platform_file_path))) {393    char resolved_path[PATH_MAX];394 395    llvm::StringRef sdk = GetSDKFilepath();396    if (!sdk.empty()) {397      ::snprintf(resolved_path, sizeof(resolved_path), "%s/%s",398                 sdk.str().c_str(), platform_file_path);399 400      // First try in the SDK and see if the file is in there401      local_file.SetFile(resolved_path, FileSpec::Style::native);402      FileSystem::Instance().Resolve(local_file);403      if (FileSystem::Instance().Exists(local_file))404        return error;405 406      // Else fall back to the actual path itself407      local_file.SetFile(platform_file_path, FileSpec::Style::native);408      FileSystem::Instance().Resolve(local_file);409      if (FileSystem::Instance().Exists(local_file))410        return error;411    }412    error = Status::FromErrorStringWithFormatv(413        "unable to locate a platform file for '{0}' in platform '{1}'",414        platform_file_path, GetPluginName());415  } else {416    error = Status::FromErrorString("invalid platform file argument");417  }418  return error;419}420 421Status PlatformAppleSimulator::GetSharedModule(422    const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,423    llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) {424  // For iOS/tvOS/watchOS, the SDK files are all cached locally on the425  // host system. So first we ask for the file in the cached SDK, then426  // we attempt to get a shared module for the right architecture with427  // the right UUID.428  Status error;429  ModuleSpec platform_module_spec(module_spec);430  const FileSpec &platform_file = module_spec.GetFileSpec();431  error = GetSymbolFile(platform_file, module_spec.GetUUIDPtr(),432                        platform_module_spec.GetFileSpec());433  if (error.Success()) {434    error = ResolveExecutable(platform_module_spec, module_sp);435  } else {436    const bool always_create = false;437    error = ModuleList::GetSharedModule(module_spec, module_sp, old_modules,438                                        did_create_ptr, always_create);439  }440  if (module_sp)441    module_sp->SetPlatformFileSpec(platform_file);442 443  return error;444}445 446uint32_t PlatformAppleSimulator::FindProcesses(447    const ProcessInstanceInfoMatch &match_info,448    ProcessInstanceInfoList &process_infos) {449  ProcessInstanceInfoList all_osx_process_infos;450  // First we get all OSX processes451  const uint32_t n = Host::FindProcesses(match_info, all_osx_process_infos);452 453  // Now we filter them down to only the matching triples.454  for (uint32_t i = 0; i < n; ++i) {455    const ProcessInstanceInfo &proc_info = all_osx_process_infos[i];456    const llvm::Triple &triple = proc_info.GetArchitecture().GetTriple();457    if (triple.getOS() == m_os_type &&458        triple.getEnvironment() == llvm::Triple::Simulator) {459      process_infos.push_back(proc_info);460    }461  }462  return process_infos.size();463}464 465/// Whether to skip creating a simulator platform.466static bool shouldSkipSimulatorPlatform(bool force, const ArchSpec *arch) {467  // If the arch is known not to specify a simulator environment, skip creating468  // the simulator platform (we can create it later if there's a matching arch).469  // This avoids very slow xcrun queries for non-simulator archs (the slowness470  // is due to xcrun not caching negative queries.471  return !force && arch && arch->IsValid() &&472         !arch->TripleEnvironmentWasSpecified();473}474 475static const char *g_ios_plugin_name = "ios-simulator";476static const char *g_ios_description = "iPhone simulator platform plug-in.";477 478/// IPhone Simulator Plugin.479struct PlatformiOSSimulator {480  static void Initialize() {481    PluginManager::RegisterPlugin(g_ios_plugin_name, g_ios_description,482                                  PlatformiOSSimulator::CreateInstance);483  }484 485  static void Terminate() {486    PluginManager::UnregisterPlugin(PlatformiOSSimulator::CreateInstance);487  }488 489  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {490    if (shouldSkipSimulatorPlatform(force, arch))491      return nullptr;492 493    return PlatformAppleSimulator::CreateInstance(494        "PlatformiOSSimulator", g_ios_description,495        ConstString(g_ios_plugin_name),496        {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},497        llvm::Triple::IOS,498        {// Deprecated, but still support Darwin for historical reasons.499         llvm::Triple::Darwin, llvm::Triple::MacOSX,500         // IOS is not used for simulator triples, but accept it just in501         // case.502         llvm::Triple::IOS},503        {504#ifdef __APPLE__505#if __arm64__506          "arm64e-apple-ios-simulator", "arm64-apple-ios-simulator",507              "x86_64-apple-ios-simulator", "x86_64h-apple-ios-simulator",508#else509          "x86_64h-apple-ios-simulator", "x86_64-apple-ios-simulator",510              "i386-apple-ios-simulator",511#endif512#endif513        },514        "iPhoneSimulator.Internal.sdk", "iPhoneSimulator.sdk",515        XcodeSDK::Type::iPhoneSimulator,516        CoreSimulatorSupport::DeviceType::ProductFamilyID::iPhone, force, arch);517  }518};519 520static const char *g_tvos_plugin_name = "tvos-simulator";521static const char *g_tvos_description = "tvOS simulator platform plug-in.";522 523/// Apple TV Simulator Plugin.524struct PlatformAppleTVSimulator {525  static void Initialize() {526    PluginManager::RegisterPlugin(g_tvos_plugin_name, g_tvos_description,527                                  PlatformAppleTVSimulator::CreateInstance);528  }529 530  static void Terminate() {531    PluginManager::UnregisterPlugin(PlatformAppleTVSimulator::CreateInstance);532  }533 534  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {535    if (shouldSkipSimulatorPlatform(force, arch))536      return nullptr;537    return PlatformAppleSimulator::CreateInstance(538        "PlatformAppleTVSimulator", g_tvos_description,539        ConstString(g_tvos_plugin_name),540        {llvm::Triple::aarch64, llvm::Triple::x86_64}, llvm::Triple::TvOS,541        {llvm::Triple::TvOS},542        {543#ifdef __APPLE__544#if __arm64__545          "arm64e-apple-tvos-simulator", "arm64-apple-tvos-simulator",546              "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",547#else548          "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",549#endif550#endif551        },552        "AppleTVSimulator.Internal.sdk", "AppleTVSimulator.sdk",553        XcodeSDK::Type::AppleTVSimulator,554        CoreSimulatorSupport::DeviceType::ProductFamilyID::appleTV, force,555        arch);556  }557};558 559 560static const char *g_watchos_plugin_name = "watchos-simulator";561static const char *g_watchos_description =562    "Apple Watch simulator platform plug-in.";563 564/// Apple Watch Simulator Plugin.565struct PlatformAppleWatchSimulator {566  static void Initialize() {567    PluginManager::RegisterPlugin(g_watchos_plugin_name, g_watchos_description,568                                  PlatformAppleWatchSimulator::CreateInstance);569  }570 571  static void Terminate() {572    PluginManager::UnregisterPlugin(573        PlatformAppleWatchSimulator::CreateInstance);574  }575 576  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {577    if (shouldSkipSimulatorPlatform(force, arch))578      return nullptr;579    return PlatformAppleSimulator::CreateInstance(580        "PlatformAppleWatchSimulator", g_watchos_description,581        ConstString(g_watchos_plugin_name),582        {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},583        llvm::Triple::WatchOS, {llvm::Triple::WatchOS},584        {585#ifdef __APPLE__586#if __arm64__587          "arm64e-apple-watchos-simulator", "arm64-apple-watchos-simulator",588#else589          "x86_64-apple-watchos-simulator", "x86_64h-apple-watchos-simulator",590              "i386-apple-watchos-simulator",591#endif592#endif593        },594        "WatchSimulator.Internal.sdk", "WatchSimulator.sdk",595        XcodeSDK::Type::WatchSimulator,596        CoreSimulatorSupport::DeviceType::ProductFamilyID::appleWatch, force,597        arch);598  }599};600 601static const char *g_xros_plugin_name = "xros-simulator";602static const char *g_xros_description = "XROS simulator platform plug-in.";603 604/// XRSimulator Plugin.605struct PlatformXRSimulator {606  static void Initialize() {607    PluginManager::RegisterPlugin(g_xros_plugin_name, g_xros_description,608                                  PlatformXRSimulator::CreateInstance);609  }610 611  static void Terminate() {612    PluginManager::UnregisterPlugin(PlatformXRSimulator::CreateInstance);613  }614 615  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {616    return PlatformAppleSimulator::CreateInstance(617        "PlatformXRSimulator", g_xros_description,618        ConstString(g_xros_plugin_name),619        {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},620        llvm::Triple::XROS, {llvm::Triple::XROS},621        {622#ifdef __APPLE__623#if __arm64__624          "arm64e-apple-xros-simulator", "arm64-apple-xros-simulator",625#else626          "x86_64-apple-xros-simulator", "x86_64h-apple-xros-simulator",627#endif628#endif629        },630        "XRSimulator.Internal.sdk", "XRSimulator.sdk",631        XcodeSDK::Type::XRSimulator,632        CoreSimulatorSupport::DeviceType::ProductFamilyID::appleXR, force,633        arch);634  }635};636 637static unsigned g_initialize_count = 0;638 639// Static Functions640void PlatformAppleSimulator::Initialize() {641  if (g_initialize_count++ == 0) {642    PlatformDarwin::Initialize();643    PlatformiOSSimulator::Initialize();644    PlatformAppleTVSimulator::Initialize();645    PlatformAppleWatchSimulator::Initialize();646    PlatformXRSimulator::Initialize();647  }648}649 650void PlatformAppleSimulator::Terminate() {651  if (g_initialize_count > 0)652    if (--g_initialize_count == 0) {653      PlatformXRSimulator::Terminate();654      PlatformAppleWatchSimulator::Terminate();655      PlatformAppleTVSimulator::Terminate();656      PlatformiOSSimulator::Terminate();657      PlatformDarwin::Terminate();658    }659}660