PlatformAppleSimulator.cpp 23 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
//===-- PlatformAppleSimulator.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "PlatformAppleSimulator.h"

#if defined(__APPLE__)
#include <dlfcn.h>
#endif

#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"

#include "llvm/Support/Threading.h"

#include <mutex>
#include <thread>

using namespace lldb;
using namespace lldb_private;

#if !defined(__APPLE__)
#define UNSUPPORTED_ERROR ("Apple simulators aren't supported on this platform")
#endif

/// Default Constructor
PlatformAppleSimulator::PlatformAppleSimulator(
    const char *class_name, const char *description, ConstString plugin_name,
    llvm::Triple::OSType preferred_os,
    llvm::SmallVector<llvm::StringRef, 4> supported_triples,
    llvm::StringRef sdk, lldb_private::XcodeSDK::Type sdk_type,
    CoreSimulatorSupport::DeviceType::ProductFamilyID kind)
    : PlatformDarwin(true), m_class_name(class_name),
      m_description(description), m_plugin_name(plugin_name), m_kind(kind),
      m_os_type(preferred_os), m_supported_triples(supported_triples),
      m_sdk(sdk), m_sdk_type(sdk_type) {}

/// Destructor.
///
/// The destructor is virtual since this class is designed to be
/// inherited from by the plug-in instance.
PlatformAppleSimulator::~PlatformAppleSimulator() {}

lldb_private::Status PlatformAppleSimulator::LaunchProcess(
    lldb_private::ProcessLaunchInfo &launch_info) {
#if defined(__APPLE__)
  LoadCoreSimulator();
  CoreSimulatorSupport::Device device(GetSimulatorDevice());

  if (device.GetState() != CoreSimulatorSupport::Device::State::Booted) {
    Status boot_err;
    device.Boot(boot_err);
    if (boot_err.Fail())
      return boot_err;
  }

  auto spawned = device.Spawn(launch_info);

  if (spawned) {
    launch_info.SetProcessID(spawned.GetPID());
    return Status();
  } else
    return spawned.GetError();
#else
  Status err;
  err.SetErrorString(UNSUPPORTED_ERROR);
  return err;
#endif
}

void PlatformAppleSimulator::GetStatus(Stream &strm) {
  Platform::GetStatus(strm);
  if (!m_sdk.empty())
    strm << "  SDK Path: \"" << m_sdk << "\"\n";
  else
    strm << "  SDK Path: error: unable to locate SDK\n";

#if defined(__APPLE__)
  // This will get called by subclasses, so just output status on the current
  // simulator
  PlatformAppleSimulator::LoadCoreSimulator();

  std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
  CoreSimulatorSupport::DeviceSet devices =
      CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
          developer_dir.c_str());
  const size_t num_devices = devices.GetNumDevices();
  if (num_devices) {
    strm.Printf("Available devices:\n");
    for (size_t i = 0; i < num_devices; ++i) {
      CoreSimulatorSupport::Device device = devices.GetDeviceAtIndex(i);
      strm << "   " << device.GetUDID() << ": " << device.GetName() << "\n";
    }

    if (m_device.hasValue() && m_device->operator bool()) {
      strm << "Current device: " << m_device->GetUDID() << ": "
           << m_device->GetName();
      if (m_device->GetState() == CoreSimulatorSupport::Device::State::Booted) {
        strm << " state = booted";
      }
      strm << "\nType \"platform connect <ARG>\" where <ARG> is a device "
              "UDID or a device name to disconnect and connect to a "
              "different device.\n";

    } else {
      strm << "No current device is selected, \"platform connect <ARG>\" "
              "where <ARG> is a device UDID or a device name to connect to "
              "a specific device.\n";
    }

  } else {
    strm << "No devices are available.\n";
  }
#else
  strm << UNSUPPORTED_ERROR;
#endif
}

Status PlatformAppleSimulator::ConnectRemote(Args &args) {
#if defined(__APPLE__)
  Status error;
  if (args.GetArgumentCount() == 1) {
    if (m_device)
      DisconnectRemote();
    PlatformAppleSimulator::LoadCoreSimulator();
    const char *arg_cstr = args.GetArgumentAtIndex(0);
    if (arg_cstr) {
      std::string arg_str(arg_cstr);
      std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
      CoreSimulatorSupport::DeviceSet devices =
          CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
              developer_dir.c_str());
      devices.ForEach(
          [this, &arg_str](const CoreSimulatorSupport::Device &device) -> bool {
            if (arg_str == device.GetUDID() || arg_str == device.GetName()) {
              m_device = device;
              return false; // Stop iterating
            } else {
              return true; // Keep iterating
            }
          });
      if (!m_device)
        error.SetErrorStringWithFormat(
            "no device with UDID or name '%s' was found", arg_cstr);
    }
  } else {
    error.SetErrorString("this command take a single UDID argument of the "
                         "device you want to connect to.");
  }
  return error;
#else
  Status err;
  err.SetErrorString(UNSUPPORTED_ERROR);
  return err;
#endif
}

Status PlatformAppleSimulator::DisconnectRemote() {
#if defined(__APPLE__)
  m_device.reset();
  return Status();
#else
  Status err;
  err.SetErrorString(UNSUPPORTED_ERROR);
  return err;
#endif
}

lldb::ProcessSP PlatformAppleSimulator::DebugProcess(
    ProcessLaunchInfo &launch_info, Debugger &debugger,
    Target *target, // Can be NULL, if NULL create a new target, else use
                    // existing one
    Status &error) {
#if defined(__APPLE__)
  ProcessSP process_sp;
  // Make sure we stop at the entry point
  launch_info.GetFlags().Set(eLaunchFlagDebug);
  // We always launch the process we are going to debug in a separate process
  // group, since then we can handle ^C interrupts ourselves w/o having to
  // worry about the target getting them as well.
  launch_info.SetLaunchInSeparateProcessGroup(true);

  error = LaunchProcess(launch_info);
  if (error.Success()) {
    if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
      ProcessAttachInfo attach_info(launch_info);
      process_sp = Attach(attach_info, debugger, target, error);
      if (process_sp) {
        launch_info.SetHijackListener(attach_info.GetHijackListener());

        // Since we attached to the process, it will think it needs to detach
        // if the process object just goes away without an explicit call to
        // Process::Kill() or Process::Detach(), so let it know to kill the
        // process if this happens.
        process_sp->SetShouldDetach(false);

        // If we didn't have any file actions, the pseudo terminal might have
        // been used where the secondary side was given as the file to open for
        // stdin/out/err after we have already opened the primary so we can
        // read/write stdin/out/err.
        int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
        if (pty_fd != PseudoTerminal::invalid_fd) {
          process_sp->SetSTDIOFileDescriptor(pty_fd);
        }
      }
    }
  }

  return process_sp;
#else
  return ProcessSP();
#endif
}

FileSpec PlatformAppleSimulator::GetCoreSimulatorPath() {
#if defined(__APPLE__)
  std::lock_guard<std::mutex> guard(m_core_sim_path_mutex);
  if (!m_core_simulator_framework_path.hasValue()) {
    m_core_simulator_framework_path =
        FileSpec("/Library/Developer/PrivateFrameworks/CoreSimulator.framework/"
                 "CoreSimulator");
    FileSystem::Instance().Resolve(*m_core_simulator_framework_path);
  }
  return m_core_simulator_framework_path.getValue();
#else
  return FileSpec();
#endif
}

void PlatformAppleSimulator::LoadCoreSimulator() {
#if defined(__APPLE__)
  static llvm::once_flag g_load_core_sim_flag;
  llvm::call_once(g_load_core_sim_flag, [this] {
    const std::string core_sim_path(GetCoreSimulatorPath().GetPath());
    if (core_sim_path.size())
      dlopen(core_sim_path.c_str(), RTLD_LAZY);
  });
#endif
}

#if defined(__APPLE__)
CoreSimulatorSupport::Device PlatformAppleSimulator::GetSimulatorDevice() {
  if (!m_device.hasValue()) {
    const CoreSimulatorSupport::DeviceType::ProductFamilyID dev_id = m_kind;
    std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
    m_device = CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
                   developer_dir.c_str())
                   .GetFanciest(dev_id);
  }

  if (m_device.hasValue())
    return m_device.getValue();
  else
    return CoreSimulatorSupport::Device();
}
#endif

bool PlatformAppleSimulator::GetSupportedArchitectureAtIndex(uint32_t idx,
                                                             ArchSpec &arch) {
  if (idx >= m_supported_triples.size())
    return false;
  arch = ArchSpec(m_supported_triples[idx]);
  return true;
}

PlatformSP PlatformAppleSimulator::CreateInstance(
    const char *class_name, const char *description, ConstString plugin_name,
    llvm::SmallVector<llvm::Triple::ArchType, 4> supported_arch,
    llvm::Triple::OSType preferred_os,
    llvm::SmallVector<llvm::Triple::OSType, 4> supported_os,
    llvm::SmallVector<llvm::StringRef, 4> supported_triples,
    llvm::StringRef sdk, lldb_private::XcodeSDK::Type sdk_type,
    CoreSimulatorSupport::DeviceType::ProductFamilyID kind, bool force,
    const ArchSpec *arch) {
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
  if (log) {
    const char *arch_name;
    if (arch && arch->GetArchitectureName())
      arch_name = arch->GetArchitectureName();
    else
      arch_name = "<null>";

    const char *triple_cstr =
        arch ? arch->GetTriple().getTriple().c_str() : "<null>";

    LLDB_LOGF(log, "%s::%s(force=%s, arch={%s,%s})", class_name, __FUNCTION__,
              force ? "true" : "false", arch_name, triple_cstr);
  }

  bool create = force;
  if (!create && arch && arch->IsValid()) {
    if (std::count(supported_arch.begin(), supported_arch.end(),
                   arch->GetMachine())) {
      const llvm::Triple &triple = arch->GetTriple();
      switch (triple.getVendor()) {
      case llvm::Triple::Apple:
        create = true;
        break;

#if defined(__APPLE__)
      // Only accept "unknown" for the vendor if the host is Apple and if
      // "unknown" wasn't specified (it was just returned because it was NOT
      // specified)
      case llvm::Triple::UnknownVendor:
        create = !arch->TripleVendorWasSpecified();
        break;
#endif
      default:
        break;
      }

      if (create) {
        if (std::count(supported_os.begin(), supported_os.end(), triple.getOS()))
          create = true;
#if defined(__APPLE__)
        // Only accept "unknown" for the OS if the host is Apple and it
        // "unknown" wasn't specified (it was just returned because it was NOT
        // specified)
        else if (triple.getOS() == llvm::Triple::UnknownOS)
          create = !arch->TripleOSWasSpecified();
#endif
        else
          create = false;
      }
    }
  }
  if (create) {
    LLDB_LOGF(log, "%s::%s() creating platform", class_name, __FUNCTION__);

    return PlatformSP(new PlatformAppleSimulator(
        class_name, description, plugin_name, preferred_os, supported_triples,
        sdk, sdk_type, kind));
  }

  LLDB_LOGF(log, "%s::%s() aborting creation of platform", class_name,
            __FUNCTION__);

  return PlatformSP();
}

Status PlatformAppleSimulator::ResolveExecutable(
    const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp,
    const FileSpecList *module_search_paths_ptr) {
  Status error;
  // Nothing special to do here, just use the actual file and architecture

  ModuleSpec resolved_module_spec(module_spec);

  // If we have "ls" as the exe_file, resolve the executable loation based on
  // the current path variables
  // TODO: resolve bare executables in the Platform SDK
  //    if (!resolved_exe_file.Exists())
  //        resolved_exe_file.ResolveExecutableLocation ();

  // Resolve any executable within a bundle on MacOSX
  // TODO: verify that this handles shallow bundles, if not then implement one
  // ourselves
  Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());

  if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec())) {
    if (resolved_module_spec.GetArchitecture().IsValid()) {
      error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
                                          NULL, NULL, NULL);

      if (exe_module_sp && exe_module_sp->GetObjectFile())
        return error;
      exe_module_sp.reset();
    }
    // No valid architecture was specified or the exact ARM slice wasn't found
    // so ask the platform for the architectures that we should be using (in
    // the correct order) and see if we can find a match that way
    StreamString arch_names;
    ArchSpec platform_arch;
    for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
             idx, resolved_module_spec.GetArchitecture());
         ++idx) {
      // Only match x86 with x86 and x86_64 with x86_64...
      if (!module_spec.GetArchitecture().IsValid() ||
          module_spec.GetArchitecture().GetCore() ==
              resolved_module_spec.GetArchitecture().GetCore()) {
        error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
                                            NULL, NULL, NULL);
        // Did we find an executable using one of the
        if (error.Success()) {
          if (exe_module_sp && exe_module_sp->GetObjectFile())
            break;
          else
            error.SetErrorToGenericError();
        }

        if (idx > 0)
          arch_names.PutCString(", ");
        arch_names.PutCString(platform_arch.GetArchitectureName());
      }
    }

    if (error.Fail() || !exe_module_sp) {
      if (FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec())) {
        error.SetErrorStringWithFormat(
            "'%s' doesn't contain any '%s' platform architectures: %s",
            resolved_module_spec.GetFileSpec().GetPath().c_str(),
            GetPluginName().GetCString(), arch_names.GetString().str().c_str());
      } else {
        error.SetErrorStringWithFormat(
            "'%s' is not readable",
            resolved_module_spec.GetFileSpec().GetPath().c_str());
      }
    }
  } else {
    error.SetErrorStringWithFormat("'%s' does not exist",
                                   module_spec.GetFileSpec().GetPath().c_str());
  }

  return error;
}

Status PlatformAppleSimulator::GetSymbolFile(const FileSpec &platform_file,
                                             const UUID *uuid_ptr,
                                             FileSpec &local_file) {
  Status error;
  char platform_file_path[PATH_MAX];
  if (platform_file.GetPath(platform_file_path, sizeof(platform_file_path))) {
    char resolved_path[PATH_MAX];

    if (!m_sdk.empty()) {
      ::snprintf(resolved_path, sizeof(resolved_path), "%s/%s",
                 m_sdk.str().c_str(), platform_file_path);

      // First try in the SDK and see if the file is in there
      local_file.SetFile(resolved_path, FileSpec::Style::native);
      FileSystem::Instance().Resolve(local_file);
      if (FileSystem::Instance().Exists(local_file))
        return error;

      // Else fall back to the actual path itself
      local_file.SetFile(platform_file_path, FileSpec::Style::native);
      FileSystem::Instance().Resolve(local_file);
      if (FileSystem::Instance().Exists(local_file))
        return error;
    }
    error.SetErrorStringWithFormat(
        "unable to locate a platform file for '%s' in platform '%s'",
        platform_file_path, GetPluginName().GetCString());
  } else {
    error.SetErrorString("invalid platform file argument");
  }
  return error;
}

Status PlatformAppleSimulator::GetSharedModule(
    const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
    const FileSpecList *module_search_paths_ptr, ModuleSP *old_module_sp_ptr,
    bool *did_create_ptr) {
  // For iOS/tvOS/watchOS, the SDK files are all cached locally on the
  // host system. So first we ask for the file in the cached SDK, then
  // we attempt to get a shared module for the right architecture with
  // the right UUID.
  Status error;
  ModuleSpec platform_module_spec(module_spec);
  const FileSpec &platform_file = module_spec.GetFileSpec();
  error = GetSymbolFile(platform_file, module_spec.GetUUIDPtr(),
                        platform_module_spec.GetFileSpec());
  if (error.Success()) {
    error = ResolveExecutable(platform_module_spec, module_sp,
                              module_search_paths_ptr);
  } else {
    const bool always_create = false;
    error = ModuleList::GetSharedModule(
        module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
        did_create_ptr, always_create);
  }
  if (module_sp)
    module_sp->SetPlatformFileSpec(platform_file);

  return error;
}

uint32_t PlatformAppleSimulator::FindProcesses(
    const ProcessInstanceInfoMatch &match_info,
    ProcessInstanceInfoList &process_infos) {
  ProcessInstanceInfoList all_osx_process_infos;
  // First we get all OSX processes
  const uint32_t n = Host::FindProcesses(match_info, all_osx_process_infos);

  // Now we filter them down to only the matching triples.
  for (uint32_t i = 0; i < n; ++i) {
    const ProcessInstanceInfo &proc_info = all_osx_process_infos[i];
    const llvm::Triple &triple = proc_info.GetArchitecture().GetTriple();
    if (triple.getOS() == m_os_type &&
        triple.getEnvironment() == llvm::Triple::Simulator) {
      process_infos.push_back(proc_info);
    }
  }
  return process_infos.size();
}

static llvm::StringRef GetXcodeSDKDir(std::string preferred,
                                      std::string secondary) {
  llvm::StringRef sdk;
  sdk = HostInfo::GetXcodeSDKPath(XcodeSDK(std::move(preferred)));
  if (sdk.empty())
    sdk = HostInfo::GetXcodeSDKPath(XcodeSDK(std::move(secondary)));
  return sdk;
}

static const char *g_ios_plugin_name = "ios-simulator";
static const char *g_ios_description = "iPhone simulator platform plug-in.";

/// IPhone Simulator Plugin.
struct PlatformiOSSimulator {
  static void Initialize() {
    PluginManager::RegisterPlugin(ConstString(g_ios_plugin_name),
                                  g_ios_description,
                                  PlatformiOSSimulator::CreateInstance);
  }

  static void Terminate() {
    PluginManager::UnregisterPlugin(PlatformiOSSimulator::CreateInstance);
  }

  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
    llvm::StringRef sdk;
    sdk = HostInfo::GetXcodeSDKPath(XcodeSDK("iPhoneSimulator.Internal.sdk"));
    if (sdk.empty())
      sdk = HostInfo::GetXcodeSDKPath(XcodeSDK("iPhoneSimulator.sdk"));

    return PlatformAppleSimulator::CreateInstance(
        "PlatformiOSSimulator", g_ios_description,
        ConstString(g_ios_plugin_name),
        {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},
        llvm::Triple::IOS,
        {// Deprecated, but still support Darwin for historical reasons.
         llvm::Triple::Darwin, llvm::Triple::MacOSX,
         // IOS is not used for simulator triples, but accept it just in
         // case.
         llvm::Triple::IOS},
        {
#ifdef __APPLE__
#if __arm64__
          "arm64e-apple-ios-simulator", "arm64-apple-ios-simulator",
              "x86_64-apple-ios-simulator", "x86_64h-apple-ios-simulator",
#else
          "x86_64h-apple-ios-simulator", "x86_64-apple-ios-simulator",
              "i386-apple-ios-simulator",
#endif
#endif
        },
        GetXcodeSDKDir("iPhoneSimulator.Internal.sdk", "iPhoneSimulator.sdk"),
        XcodeSDK::Type::iPhoneSimulator,
        CoreSimulatorSupport::DeviceType::ProductFamilyID::iPhone, force, arch);
  }
};

static const char *g_tvos_plugin_name = "tvos-simulator";
static const char *g_tvos_description = "tvOS simulator platform plug-in.";

/// Apple TV Simulator Plugin.
struct PlatformAppleTVSimulator {
  static void Initialize() {
    PluginManager::RegisterPlugin(ConstString(g_tvos_plugin_name),
                                  g_tvos_description,
                                  PlatformAppleTVSimulator::CreateInstance);
  }

  static void Terminate() {
    PluginManager::UnregisterPlugin(PlatformAppleTVSimulator::CreateInstance);
  }

  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
    return PlatformAppleSimulator::CreateInstance(
        "PlatformAppleTVSimulator", g_tvos_description,
        ConstString(g_tvos_plugin_name),
        {llvm::Triple::aarch64, llvm::Triple::x86_64}, llvm::Triple::TvOS,
        {llvm::Triple::TvOS},
        {
#ifdef __APPLE__
#if __arm64__
          "arm64e-apple-tvos-simulator", "arm64-apple-tvos-simulator",
              "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",
#else
          "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",
#endif
#endif
        },
        GetXcodeSDKDir("AppleTVSimulator.Internal.sdk", "AppleTVSimulator.sdk"),
        XcodeSDK::Type::AppleTVSimulator,
        CoreSimulatorSupport::DeviceType::ProductFamilyID::appleTV, force,
        arch);
  }
};


static const char *g_watchos_plugin_name = "watchos-simulator";
static const char *g_watchos_description =
    "Apple Watch simulator platform plug-in.";

/// Apple Watch Simulator Plugin.
struct PlatformAppleWatchSimulator {
  static void Initialize() {
    PluginManager::RegisterPlugin(ConstString(g_watchos_plugin_name),
                                  g_watchos_description,
                                  PlatformAppleWatchSimulator::CreateInstance);
  }

  static void Terminate() {
    PluginManager::UnregisterPlugin(
        PlatformAppleWatchSimulator::CreateInstance);
  }

  static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
    return PlatformAppleSimulator::CreateInstance(
        "PlatformAppleWatchSimulator", g_watchos_description,
        ConstString(g_watchos_plugin_name),
        {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},
        llvm::Triple::WatchOS, {llvm::Triple::WatchOS},
        {
#ifdef __APPLE__
#if __arm64__
          "arm64e-apple-watchos-simulator", "arm64-apple-watchos-simulator",
#else
          "x86_64-apple-watchos-simulator", "x86_64h-apple-watchos-simulator",
              "i386-apple-watchos-simulator",
#endif
#endif
        },
        GetXcodeSDKDir("WatchSimulator.Internal.sdk", "WatchSimulator.sdk"),
        XcodeSDK::Type::WatchSimulator,
        CoreSimulatorSupport::DeviceType::ProductFamilyID::appleWatch, force,
        arch);
  }
};


static unsigned g_initialize_count = 0;

// Static Functions
void PlatformAppleSimulator::Initialize() {
  if (g_initialize_count++ == 0) {
    PlatformDarwin::Initialize();
    PlatformiOSSimulator::Initialize();
    PlatformAppleTVSimulator::Initialize();
    PlatformAppleWatchSimulator::Initialize();
  }
}

void PlatformAppleSimulator::Terminate() {
  if (g_initialize_count > 0)
    if (--g_initialize_count == 0) {
      PlatformAppleWatchSimulator::Terminate();
      PlatformAppleTVSimulator::Terminate();
      PlatformiOSSimulator::Terminate();
      PlatformDarwin::Terminate();
    }
}