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-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PlatformAppleSimulator.h"
10 
11 #if defined(__APPLE__)
12 #include <dlfcn.h>
13 #endif
14 
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Host/HostInfo.h"
18 #include "lldb/Host/PseudoTerminal.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Utility/LLDBAssert.h"
21 #include "lldb/Utility/Log.h"
22 #include "lldb/Utility/Status.h"
23 #include "lldb/Utility/StreamString.h"
24 
25 #include "llvm/Support/Threading.h"
26 
27 #include <mutex>
28 #include <thread>
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 #if !defined(__APPLE__)
34 #define UNSUPPORTED_ERROR ("Apple simulators aren't supported on this platform")
35 #endif
36 
37 /// Default Constructor
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)38 PlatformAppleSimulator::PlatformAppleSimulator(
39     const char *class_name, const char *description, ConstString plugin_name,
40     llvm::Triple::OSType preferred_os,
41     llvm::SmallVector<llvm::StringRef, 4> supported_triples,
42     llvm::StringRef sdk, lldb_private::XcodeSDK::Type sdk_type,
43     CoreSimulatorSupport::DeviceType::ProductFamilyID kind)
44     : PlatformDarwin(true), m_class_name(class_name),
45       m_description(description), m_plugin_name(plugin_name), m_kind(kind),
46       m_os_type(preferred_os), m_supported_triples(supported_triples),
47       m_sdk(sdk), m_sdk_type(sdk_type) {}
48 
49 /// Destructor.
50 ///
51 /// The destructor is virtual since this class is designed to be
52 /// inherited from by the plug-in instance.
~PlatformAppleSimulator()53 PlatformAppleSimulator::~PlatformAppleSimulator() {}
54 
LaunchProcess(lldb_private::ProcessLaunchInfo & launch_info)55 lldb_private::Status PlatformAppleSimulator::LaunchProcess(
56     lldb_private::ProcessLaunchInfo &launch_info) {
57 #if defined(__APPLE__)
58   LoadCoreSimulator();
59   CoreSimulatorSupport::Device device(GetSimulatorDevice());
60 
61   if (device.GetState() != CoreSimulatorSupport::Device::State::Booted) {
62     Status boot_err;
63     device.Boot(boot_err);
64     if (boot_err.Fail())
65       return boot_err;
66   }
67 
68   auto spawned = device.Spawn(launch_info);
69 
70   if (spawned) {
71     launch_info.SetProcessID(spawned.GetPID());
72     return Status();
73   } else
74     return spawned.GetError();
75 #else
76   Status err;
77   err.SetErrorString(UNSUPPORTED_ERROR);
78   return err;
79 #endif
80 }
81 
GetStatus(Stream & strm)82 void PlatformAppleSimulator::GetStatus(Stream &strm) {
83   Platform::GetStatus(strm);
84   if (!m_sdk.empty())
85     strm << "  SDK Path: \"" << m_sdk << "\"\n";
86   else
87     strm << "  SDK Path: error: unable to locate SDK\n";
88 
89 #if defined(__APPLE__)
90   // This will get called by subclasses, so just output status on the current
91   // simulator
92   PlatformAppleSimulator::LoadCoreSimulator();
93 
94   std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
95   CoreSimulatorSupport::DeviceSet devices =
96       CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
97           developer_dir.c_str());
98   const size_t num_devices = devices.GetNumDevices();
99   if (num_devices) {
100     strm.Printf("Available devices:\n");
101     for (size_t i = 0; i < num_devices; ++i) {
102       CoreSimulatorSupport::Device device = devices.GetDeviceAtIndex(i);
103       strm << "   " << device.GetUDID() << ": " << device.GetName() << "\n";
104     }
105 
106     if (m_device.hasValue() && m_device->operator bool()) {
107       strm << "Current device: " << m_device->GetUDID() << ": "
108            << m_device->GetName();
109       if (m_device->GetState() == CoreSimulatorSupport::Device::State::Booted) {
110         strm << " state = booted";
111       }
112       strm << "\nType \"platform connect <ARG>\" where <ARG> is a device "
113               "UDID or a device name to disconnect and connect to a "
114               "different device.\n";
115 
116     } else {
117       strm << "No current device is selected, \"platform connect <ARG>\" "
118               "where <ARG> is a device UDID or a device name to connect to "
119               "a specific device.\n";
120     }
121 
122   } else {
123     strm << "No devices are available.\n";
124   }
125 #else
126   strm << UNSUPPORTED_ERROR;
127 #endif
128 }
129 
ConnectRemote(Args & args)130 Status PlatformAppleSimulator::ConnectRemote(Args &args) {
131 #if defined(__APPLE__)
132   Status error;
133   if (args.GetArgumentCount() == 1) {
134     if (m_device)
135       DisconnectRemote();
136     PlatformAppleSimulator::LoadCoreSimulator();
137     const char *arg_cstr = args.GetArgumentAtIndex(0);
138     if (arg_cstr) {
139       std::string arg_str(arg_cstr);
140       std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
141       CoreSimulatorSupport::DeviceSet devices =
142           CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
143               developer_dir.c_str());
144       devices.ForEach(
145           [this, &arg_str](const CoreSimulatorSupport::Device &device) -> bool {
146             if (arg_str == device.GetUDID() || arg_str == device.GetName()) {
147               m_device = device;
148               return false; // Stop iterating
149             } else {
150               return true; // Keep iterating
151             }
152           });
153       if (!m_device)
154         error.SetErrorStringWithFormat(
155             "no device with UDID or name '%s' was found", arg_cstr);
156     }
157   } else {
158     error.SetErrorString("this command take a single UDID argument of the "
159                          "device you want to connect to.");
160   }
161   return error;
162 #else
163   Status err;
164   err.SetErrorString(UNSUPPORTED_ERROR);
165   return err;
166 #endif
167 }
168 
DisconnectRemote()169 Status PlatformAppleSimulator::DisconnectRemote() {
170 #if defined(__APPLE__)
171   m_device.reset();
172   return Status();
173 #else
174   Status err;
175   err.SetErrorString(UNSUPPORTED_ERROR);
176   return err;
177 #endif
178 }
179 
DebugProcess(ProcessLaunchInfo & launch_info,Debugger & debugger,Target * target,Status & error)180 lldb::ProcessSP PlatformAppleSimulator::DebugProcess(
181     ProcessLaunchInfo &launch_info, Debugger &debugger,
182     Target *target, // Can be NULL, if NULL create a new target, else use
183                     // existing one
184     Status &error) {
185 #if defined(__APPLE__)
186   ProcessSP process_sp;
187   // Make sure we stop at the entry point
188   launch_info.GetFlags().Set(eLaunchFlagDebug);
189   // We always launch the process we are going to debug in a separate process
190   // group, since then we can handle ^C interrupts ourselves w/o having to
191   // worry about the target getting them as well.
192   launch_info.SetLaunchInSeparateProcessGroup(true);
193 
194   error = LaunchProcess(launch_info);
195   if (error.Success()) {
196     if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
197       ProcessAttachInfo attach_info(launch_info);
198       process_sp = Attach(attach_info, debugger, target, error);
199       if (process_sp) {
200         launch_info.SetHijackListener(attach_info.GetHijackListener());
201 
202         // Since we attached to the process, it will think it needs to detach
203         // if the process object just goes away without an explicit call to
204         // Process::Kill() or Process::Detach(), so let it know to kill the
205         // process if this happens.
206         process_sp->SetShouldDetach(false);
207 
208         // If we didn't have any file actions, the pseudo terminal might have
209         // been used where the secondary side was given as the file to open for
210         // stdin/out/err after we have already opened the primary so we can
211         // read/write stdin/out/err.
212         int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
213         if (pty_fd != PseudoTerminal::invalid_fd) {
214           process_sp->SetSTDIOFileDescriptor(pty_fd);
215         }
216       }
217     }
218   }
219 
220   return process_sp;
221 #else
222   return ProcessSP();
223 #endif
224 }
225 
GetCoreSimulatorPath()226 FileSpec PlatformAppleSimulator::GetCoreSimulatorPath() {
227 #if defined(__APPLE__)
228   std::lock_guard<std::mutex> guard(m_core_sim_path_mutex);
229   if (!m_core_simulator_framework_path.hasValue()) {
230     m_core_simulator_framework_path =
231         FileSpec("/Library/Developer/PrivateFrameworks/CoreSimulator.framework/"
232                  "CoreSimulator");
233     FileSystem::Instance().Resolve(*m_core_simulator_framework_path);
234   }
235   return m_core_simulator_framework_path.getValue();
236 #else
237   return FileSpec();
238 #endif
239 }
240 
LoadCoreSimulator()241 void PlatformAppleSimulator::LoadCoreSimulator() {
242 #if defined(__APPLE__)
243   static llvm::once_flag g_load_core_sim_flag;
244   llvm::call_once(g_load_core_sim_flag, [this] {
245     const std::string core_sim_path(GetCoreSimulatorPath().GetPath());
246     if (core_sim_path.size())
247       dlopen(core_sim_path.c_str(), RTLD_LAZY);
248   });
249 #endif
250 }
251 
252 #if defined(__APPLE__)
GetSimulatorDevice()253 CoreSimulatorSupport::Device PlatformAppleSimulator::GetSimulatorDevice() {
254   if (!m_device.hasValue()) {
255     const CoreSimulatorSupport::DeviceType::ProductFamilyID dev_id = m_kind;
256     std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
257     m_device = CoreSimulatorSupport::DeviceSet::GetAvailableDevices(
258                    developer_dir.c_str())
259                    .GetFanciest(dev_id);
260   }
261 
262   if (m_device.hasValue())
263     return m_device.getValue();
264   else
265     return CoreSimulatorSupport::Device();
266 }
267 #endif
268 
GetSupportedArchitectureAtIndex(uint32_t idx,ArchSpec & arch)269 bool PlatformAppleSimulator::GetSupportedArchitectureAtIndex(uint32_t idx,
270                                                              ArchSpec &arch) {
271   if (idx >= m_supported_triples.size())
272     return false;
273   arch = ArchSpec(m_supported_triples[idx]);
274   return true;
275 }
276 
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)277 PlatformSP PlatformAppleSimulator::CreateInstance(
278     const char *class_name, const char *description, ConstString plugin_name,
279     llvm::SmallVector<llvm::Triple::ArchType, 4> supported_arch,
280     llvm::Triple::OSType preferred_os,
281     llvm::SmallVector<llvm::Triple::OSType, 4> supported_os,
282     llvm::SmallVector<llvm::StringRef, 4> supported_triples,
283     llvm::StringRef sdk, lldb_private::XcodeSDK::Type sdk_type,
284     CoreSimulatorSupport::DeviceType::ProductFamilyID kind, bool force,
285     const ArchSpec *arch) {
286   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
287   if (log) {
288     const char *arch_name;
289     if (arch && arch->GetArchitectureName())
290       arch_name = arch->GetArchitectureName();
291     else
292       arch_name = "<null>";
293 
294     const char *triple_cstr =
295         arch ? arch->GetTriple().getTriple().c_str() : "<null>";
296 
297     LLDB_LOGF(log, "%s::%s(force=%s, arch={%s,%s})", class_name, __FUNCTION__,
298               force ? "true" : "false", arch_name, triple_cstr);
299   }
300 
301   bool create = force;
302   if (!create && arch && arch->IsValid()) {
303     if (std::count(supported_arch.begin(), supported_arch.end(),
304                    arch->GetMachine())) {
305       const llvm::Triple &triple = arch->GetTriple();
306       switch (triple.getVendor()) {
307       case llvm::Triple::Apple:
308         create = true;
309         break;
310 
311 #if defined(__APPLE__)
312       // Only accept "unknown" for the vendor if the host is Apple and if
313       // "unknown" wasn't specified (it was just returned because it was NOT
314       // specified)
315       case llvm::Triple::UnknownVendor:
316         create = !arch->TripleVendorWasSpecified();
317         break;
318 #endif
319       default:
320         break;
321       }
322 
323       if (create) {
324         if (std::count(supported_os.begin(), supported_os.end(), triple.getOS()))
325           create = true;
326 #if defined(__APPLE__)
327         // Only accept "unknown" for the OS if the host is Apple and it
328         // "unknown" wasn't specified (it was just returned because it was NOT
329         // specified)
330         else if (triple.getOS() == llvm::Triple::UnknownOS)
331           create = !arch->TripleOSWasSpecified();
332 #endif
333         else
334           create = false;
335       }
336     }
337   }
338   if (create) {
339     LLDB_LOGF(log, "%s::%s() creating platform", class_name, __FUNCTION__);
340 
341     return PlatformSP(new PlatformAppleSimulator(
342         class_name, description, plugin_name, preferred_os, supported_triples,
343         sdk, sdk_type, kind));
344   }
345 
346   LLDB_LOGF(log, "%s::%s() aborting creation of platform", class_name,
347             __FUNCTION__);
348 
349   return PlatformSP();
350 }
351 
ResolveExecutable(const ModuleSpec & module_spec,lldb::ModuleSP & exe_module_sp,const FileSpecList * module_search_paths_ptr)352 Status PlatformAppleSimulator::ResolveExecutable(
353     const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp,
354     const FileSpecList *module_search_paths_ptr) {
355   Status error;
356   // Nothing special to do here, just use the actual file and architecture
357 
358   ModuleSpec resolved_module_spec(module_spec);
359 
360   // If we have "ls" as the exe_file, resolve the executable loation based on
361   // the current path variables
362   // TODO: resolve bare executables in the Platform SDK
363   //    if (!resolved_exe_file.Exists())
364   //        resolved_exe_file.ResolveExecutableLocation ();
365 
366   // Resolve any executable within a bundle on MacOSX
367   // TODO: verify that this handles shallow bundles, if not then implement one
368   // ourselves
369   Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
370 
371   if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec())) {
372     if (resolved_module_spec.GetArchitecture().IsValid()) {
373       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
374                                           NULL, NULL, NULL);
375 
376       if (exe_module_sp && exe_module_sp->GetObjectFile())
377         return error;
378       exe_module_sp.reset();
379     }
380     // No valid architecture was specified or the exact ARM slice wasn't found
381     // so ask the platform for the architectures that we should be using (in
382     // the correct order) and see if we can find a match that way
383     StreamString arch_names;
384     ArchSpec platform_arch;
385     for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
386              idx, resolved_module_spec.GetArchitecture());
387          ++idx) {
388       // Only match x86 with x86 and x86_64 with x86_64...
389       if (!module_spec.GetArchitecture().IsValid() ||
390           module_spec.GetArchitecture().GetCore() ==
391               resolved_module_spec.GetArchitecture().GetCore()) {
392         error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
393                                             NULL, NULL, NULL);
394         // Did we find an executable using one of the
395         if (error.Success()) {
396           if (exe_module_sp && exe_module_sp->GetObjectFile())
397             break;
398           else
399             error.SetErrorToGenericError();
400         }
401 
402         if (idx > 0)
403           arch_names.PutCString(", ");
404         arch_names.PutCString(platform_arch.GetArchitectureName());
405       }
406     }
407 
408     if (error.Fail() || !exe_module_sp) {
409       if (FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec())) {
410         error.SetErrorStringWithFormat(
411             "'%s' doesn't contain any '%s' platform architectures: %s",
412             resolved_module_spec.GetFileSpec().GetPath().c_str(),
413             GetPluginName().GetCString(), arch_names.GetString().str().c_str());
414       } else {
415         error.SetErrorStringWithFormat(
416             "'%s' is not readable",
417             resolved_module_spec.GetFileSpec().GetPath().c_str());
418       }
419     }
420   } else {
421     error.SetErrorStringWithFormat("'%s' does not exist",
422                                    module_spec.GetFileSpec().GetPath().c_str());
423   }
424 
425   return error;
426 }
427 
GetSymbolFile(const FileSpec & platform_file,const UUID * uuid_ptr,FileSpec & local_file)428 Status PlatformAppleSimulator::GetSymbolFile(const FileSpec &platform_file,
429                                              const UUID *uuid_ptr,
430                                              FileSpec &local_file) {
431   Status error;
432   char platform_file_path[PATH_MAX];
433   if (platform_file.GetPath(platform_file_path, sizeof(platform_file_path))) {
434     char resolved_path[PATH_MAX];
435 
436     if (!m_sdk.empty()) {
437       ::snprintf(resolved_path, sizeof(resolved_path), "%s/%s",
438                  m_sdk.str().c_str(), platform_file_path);
439 
440       // First try in the SDK and see if the file is in there
441       local_file.SetFile(resolved_path, FileSpec::Style::native);
442       FileSystem::Instance().Resolve(local_file);
443       if (FileSystem::Instance().Exists(local_file))
444         return error;
445 
446       // Else fall back to the actual path itself
447       local_file.SetFile(platform_file_path, FileSpec::Style::native);
448       FileSystem::Instance().Resolve(local_file);
449       if (FileSystem::Instance().Exists(local_file))
450         return error;
451     }
452     error.SetErrorStringWithFormat(
453         "unable to locate a platform file for '%s' in platform '%s'",
454         platform_file_path, GetPluginName().GetCString());
455   } else {
456     error.SetErrorString("invalid platform file argument");
457   }
458   return error;
459 }
460 
GetSharedModule(const ModuleSpec & module_spec,Process * process,ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr,llvm::SmallVectorImpl<lldb::ModuleSP> * old_modules,bool * did_create_ptr)461 Status PlatformAppleSimulator::GetSharedModule(
462     const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
463     const FileSpecList *module_search_paths_ptr,
464     llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) {
465   // For iOS/tvOS/watchOS, the SDK files are all cached locally on the
466   // host system. So first we ask for the file in the cached SDK, then
467   // we attempt to get a shared module for the right architecture with
468   // the right UUID.
469   Status error;
470   ModuleSpec platform_module_spec(module_spec);
471   const FileSpec &platform_file = module_spec.GetFileSpec();
472   error = GetSymbolFile(platform_file, module_spec.GetUUIDPtr(),
473                         platform_module_spec.GetFileSpec());
474   if (error.Success()) {
475     error = ResolveExecutable(platform_module_spec, module_sp,
476                               module_search_paths_ptr);
477   } else {
478     const bool always_create = false;
479     error = ModuleList::GetSharedModule(module_spec, module_sp,
480                                         module_search_paths_ptr, old_modules,
481                                         did_create_ptr, always_create);
482   }
483   if (module_sp)
484     module_sp->SetPlatformFileSpec(platform_file);
485 
486   return error;
487 }
488 
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)489 uint32_t PlatformAppleSimulator::FindProcesses(
490     const ProcessInstanceInfoMatch &match_info,
491     ProcessInstanceInfoList &process_infos) {
492   ProcessInstanceInfoList all_osx_process_infos;
493   // First we get all OSX processes
494   const uint32_t n = Host::FindProcesses(match_info, all_osx_process_infos);
495 
496   // Now we filter them down to only the matching triples.
497   for (uint32_t i = 0; i < n; ++i) {
498     const ProcessInstanceInfo &proc_info = all_osx_process_infos[i];
499     const llvm::Triple &triple = proc_info.GetArchitecture().GetTriple();
500     if (triple.getOS() == m_os_type &&
501         triple.getEnvironment() == llvm::Triple::Simulator) {
502       process_infos.push_back(proc_info);
503     }
504   }
505   return process_infos.size();
506 }
507 
GetXcodeSDKDir(std::string preferred,std::string secondary)508 static llvm::StringRef GetXcodeSDKDir(std::string preferred,
509                                       std::string secondary) {
510   llvm::StringRef sdk;
511   sdk = HostInfo::GetXcodeSDKPath(XcodeSDK(std::move(preferred)));
512   if (sdk.empty())
513     sdk = HostInfo::GetXcodeSDKPath(XcodeSDK(std::move(secondary)));
514   return sdk;
515 }
516 
517 static const char *g_ios_plugin_name = "ios-simulator";
518 static const char *g_ios_description = "iPhone simulator platform plug-in.";
519 
520 /// IPhone Simulator Plugin.
521 struct PlatformiOSSimulator {
InitializePlatformiOSSimulator522   static void Initialize() {
523     PluginManager::RegisterPlugin(ConstString(g_ios_plugin_name),
524                                   g_ios_description,
525                                   PlatformiOSSimulator::CreateInstance);
526   }
527 
TerminatePlatformiOSSimulator528   static void Terminate() {
529     PluginManager::UnregisterPlugin(PlatformiOSSimulator::CreateInstance);
530   }
531 
CreateInstancePlatformiOSSimulator532   static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
533     llvm::StringRef sdk;
534     sdk = HostInfo::GetXcodeSDKPath(XcodeSDK("iPhoneSimulator.Internal.sdk"));
535     if (sdk.empty())
536       sdk = HostInfo::GetXcodeSDKPath(XcodeSDK("iPhoneSimulator.sdk"));
537 
538     return PlatformAppleSimulator::CreateInstance(
539         "PlatformiOSSimulator", g_ios_description,
540         ConstString(g_ios_plugin_name),
541         {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},
542         llvm::Triple::IOS,
543         {// Deprecated, but still support Darwin for historical reasons.
544          llvm::Triple::Darwin, llvm::Triple::MacOSX,
545          // IOS is not used for simulator triples, but accept it just in
546          // case.
547          llvm::Triple::IOS},
548         {
549 #ifdef __APPLE__
550 #if __arm64__
551           "arm64e-apple-ios-simulator", "arm64-apple-ios-simulator",
552               "x86_64-apple-ios-simulator", "x86_64h-apple-ios-simulator",
553 #else
554           "x86_64h-apple-ios-simulator", "x86_64-apple-ios-simulator",
555               "i386-apple-ios-simulator",
556 #endif
557 #endif
558         },
559         GetXcodeSDKDir("iPhoneSimulator.Internal.sdk", "iPhoneSimulator.sdk"),
560         XcodeSDK::Type::iPhoneSimulator,
561         CoreSimulatorSupport::DeviceType::ProductFamilyID::iPhone, force, arch);
562   }
563 };
564 
565 static const char *g_tvos_plugin_name = "tvos-simulator";
566 static const char *g_tvos_description = "tvOS simulator platform plug-in.";
567 
568 /// Apple TV Simulator Plugin.
569 struct PlatformAppleTVSimulator {
InitializePlatformAppleTVSimulator570   static void Initialize() {
571     PluginManager::RegisterPlugin(ConstString(g_tvos_plugin_name),
572                                   g_tvos_description,
573                                   PlatformAppleTVSimulator::CreateInstance);
574   }
575 
TerminatePlatformAppleTVSimulator576   static void Terminate() {
577     PluginManager::UnregisterPlugin(PlatformAppleTVSimulator::CreateInstance);
578   }
579 
CreateInstancePlatformAppleTVSimulator580   static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
581     return PlatformAppleSimulator::CreateInstance(
582         "PlatformAppleTVSimulator", g_tvos_description,
583         ConstString(g_tvos_plugin_name),
584         {llvm::Triple::aarch64, llvm::Triple::x86_64}, llvm::Triple::TvOS,
585         {llvm::Triple::TvOS},
586         {
587 #ifdef __APPLE__
588 #if __arm64__
589           "arm64e-apple-tvos-simulator", "arm64-apple-tvos-simulator",
590               "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",
591 #else
592           "x86_64h-apple-tvos-simulator", "x86_64-apple-tvos-simulator",
593 #endif
594 #endif
595         },
596         GetXcodeSDKDir("AppleTVSimulator.Internal.sdk", "AppleTVSimulator.sdk"),
597         XcodeSDK::Type::AppleTVSimulator,
598         CoreSimulatorSupport::DeviceType::ProductFamilyID::appleTV, force,
599         arch);
600   }
601 };
602 
603 
604 static const char *g_watchos_plugin_name = "watchos-simulator";
605 static const char *g_watchos_description =
606     "Apple Watch simulator platform plug-in.";
607 
608 /// Apple Watch Simulator Plugin.
609 struct PlatformAppleWatchSimulator {
InitializePlatformAppleWatchSimulator610   static void Initialize() {
611     PluginManager::RegisterPlugin(ConstString(g_watchos_plugin_name),
612                                   g_watchos_description,
613                                   PlatformAppleWatchSimulator::CreateInstance);
614   }
615 
TerminatePlatformAppleWatchSimulator616   static void Terminate() {
617     PluginManager::UnregisterPlugin(
618         PlatformAppleWatchSimulator::CreateInstance);
619   }
620 
CreateInstancePlatformAppleWatchSimulator621   static PlatformSP CreateInstance(bool force, const ArchSpec *arch) {
622     return PlatformAppleSimulator::CreateInstance(
623         "PlatformAppleWatchSimulator", g_watchos_description,
624         ConstString(g_watchos_plugin_name),
625         {llvm::Triple::aarch64, llvm::Triple::x86_64, llvm::Triple::x86},
626         llvm::Triple::WatchOS, {llvm::Triple::WatchOS},
627         {
628 #ifdef __APPLE__
629 #if __arm64__
630           "arm64e-apple-watchos-simulator", "arm64-apple-watchos-simulator",
631 #else
632           "x86_64-apple-watchos-simulator", "x86_64h-apple-watchos-simulator",
633               "i386-apple-watchos-simulator",
634 #endif
635 #endif
636         },
637         GetXcodeSDKDir("WatchSimulator.Internal.sdk", "WatchSimulator.sdk"),
638         XcodeSDK::Type::WatchSimulator,
639         CoreSimulatorSupport::DeviceType::ProductFamilyID::appleWatch, force,
640         arch);
641   }
642 };
643 
644 
645 static unsigned g_initialize_count = 0;
646 
647 // Static Functions
Initialize()648 void PlatformAppleSimulator::Initialize() {
649   if (g_initialize_count++ == 0) {
650     PlatformDarwin::Initialize();
651     PlatformiOSSimulator::Initialize();
652     PlatformAppleTVSimulator::Initialize();
653     PlatformAppleWatchSimulator::Initialize();
654   }
655 }
656 
Terminate()657 void PlatformAppleSimulator::Terminate() {
658   if (g_initialize_count > 0)
659     if (--g_initialize_count == 0) {
660       PlatformAppleWatchSimulator::Terminate();
661       PlatformAppleTVSimulator::Terminate();
662       PlatformiOSSimulator::Terminate();
663       PlatformDarwin::Terminate();
664     }
665 }
666 
667