1 //===-- PlatformMacOSX.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 "PlatformMacOSX.h"
10 #include "PlatformRemoteiOS.h"
11 #if defined(__APPLE__)
12 #include "PlatformAppleTVSimulator.h"
13 #include "PlatformAppleWatchSimulator.h"
14 #include "PlatformDarwinKernel.h"
15 #include "PlatformRemoteAppleBridge.h"
16 #include "PlatformRemoteAppleTV.h"
17 #include "PlatformRemoteAppleWatch.h"
18 #include "PlatformiOSSimulator.h"
19 #endif
20 #include "lldb/Breakpoint/BreakpointLocation.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleList.h"
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Host/Config.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Host/HostInfo.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Utility/DataBufferHeap.h"
32 #include "lldb/Utility/FileSpec.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/Status.h"
35 #include "lldb/Utility/StreamString.h"
36 
37 #include <sstream>
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 LLDB_PLUGIN_DEFINE(PlatformMacOSX)
43 
44 static uint32_t g_initialize_count = 0;
45 
46 void PlatformMacOSX::Initialize() {
47   PlatformDarwin::Initialize();
48   PlatformRemoteiOS::Initialize();
49 #if defined(__APPLE__)
50   PlatformiOSSimulator::Initialize();
51   PlatformDarwinKernel::Initialize();
52   PlatformAppleTVSimulator::Initialize();
53   PlatformAppleWatchSimulator::Initialize();
54   PlatformRemoteAppleTV::Initialize();
55   PlatformRemoteAppleWatch::Initialize();
56   PlatformRemoteAppleBridge::Initialize();
57 #endif
58 
59   if (g_initialize_count++ == 0) {
60 #if defined(__APPLE__)
61     PlatformSP default_platform_sp(new PlatformMacOSX(true));
62     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
63     Platform::SetHostPlatform(default_platform_sp);
64 #endif
65     PluginManager::RegisterPlugin(PlatformMacOSX::GetPluginNameStatic(false),
66                                   PlatformMacOSX::GetDescriptionStatic(false),
67                                   PlatformMacOSX::CreateInstance);
68   }
69 }
70 
71 void PlatformMacOSX::Terminate() {
72   if (g_initialize_count > 0) {
73     if (--g_initialize_count == 0) {
74       PluginManager::UnregisterPlugin(PlatformMacOSX::CreateInstance);
75     }
76   }
77 
78 #if defined(__APPLE__)
79   PlatformRemoteAppleBridge::Terminate();
80   PlatformRemoteAppleWatch::Terminate();
81   PlatformRemoteAppleTV::Terminate();
82   PlatformAppleWatchSimulator::Terminate();
83   PlatformAppleTVSimulator::Terminate();
84   PlatformDarwinKernel::Terminate();
85   PlatformiOSSimulator::Terminate();
86 #endif
87   PlatformRemoteiOS::Terminate();
88   PlatformDarwin::Terminate();
89 }
90 
91 PlatformSP PlatformMacOSX::CreateInstance(bool force, const ArchSpec *arch) {
92   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
93   if (log) {
94     const char *arch_name;
95     if (arch && arch->GetArchitectureName())
96       arch_name = arch->GetArchitectureName();
97     else
98       arch_name = "<null>";
99 
100     const char *triple_cstr =
101         arch ? arch->GetTriple().getTriple().c_str() : "<null>";
102 
103     LLDB_LOGF(log, "PlatformMacOSX::%s(force=%s, arch={%s,%s})", __FUNCTION__,
104               force ? "true" : "false", arch_name, triple_cstr);
105   }
106 
107   // The only time we create an instance is when we are creating a remote
108   // macosx platform
109   const bool is_host = false;
110 
111   bool create = force;
112   if (!create && arch && arch->IsValid()) {
113     const llvm::Triple &triple = arch->GetTriple();
114     switch (triple.getVendor()) {
115     case llvm::Triple::Apple:
116       create = true;
117       break;
118 
119 #if defined(__APPLE__)
120     // Only accept "unknown" for vendor if the host is Apple and it "unknown"
121     // wasn't specified (it was just returned because it was NOT specified)
122     case llvm::Triple::UnknownVendor:
123       create = !arch->TripleVendorWasSpecified();
124       break;
125 #endif
126     default:
127       break;
128     }
129 
130     if (create) {
131       switch (triple.getOS()) {
132       case llvm::Triple::Darwin: // Deprecated, but still support Darwin for
133                                  // historical reasons
134       case llvm::Triple::MacOSX:
135         break;
136 #if defined(__APPLE__)
137       // Only accept "vendor" for vendor if the host is Apple and it "unknown"
138       // wasn't specified (it was just returned because it was NOT specified)
139       case llvm::Triple::UnknownOS:
140         create = !arch->TripleOSWasSpecified();
141         break;
142 #endif
143       default:
144         create = false;
145         break;
146       }
147     }
148   }
149   if (create) {
150     LLDB_LOGF(log, "PlatformMacOSX::%s() creating platform", __FUNCTION__);
151     return PlatformSP(new PlatformMacOSX(is_host));
152   }
153 
154   LLDB_LOGF(log, "PlatformMacOSX::%s() aborting creation of platform",
155             __FUNCTION__);
156 
157   return PlatformSP();
158 }
159 
160 lldb_private::ConstString PlatformMacOSX::GetPluginNameStatic(bool is_host) {
161   if (is_host) {
162     static ConstString g_host_name(Platform::GetHostPlatformName());
163     return g_host_name;
164   } else {
165     static ConstString g_remote_name("remote-macosx");
166     return g_remote_name;
167   }
168 }
169 
170 const char *PlatformMacOSX::GetDescriptionStatic(bool is_host) {
171   if (is_host)
172     return "Local Mac OS X user platform plug-in.";
173   else
174     return "Remote Mac OS X user platform plug-in.";
175 }
176 
177 /// Default Constructor
178 PlatformMacOSX::PlatformMacOSX(bool is_host) : PlatformDarwin(is_host) {}
179 
180 /// Destructor.
181 ///
182 /// The destructor is virtual since this class is designed to be
183 /// inherited from by the plug-in instance.
184 PlatformMacOSX::~PlatformMacOSX() {}
185 
186 ConstString PlatformMacOSX::GetSDKDirectory(lldb_private::Target &target) {
187   ModuleSP exe_module_sp(target.GetExecutableModule());
188   if (!exe_module_sp)
189     return {};
190 
191   ObjectFile *objfile = exe_module_sp->GetObjectFile();
192   if (!objfile)
193     return {};
194 
195   llvm::VersionTuple version = objfile->GetSDKVersion();
196   if (version.empty())
197     return {};
198 
199   // First try to find an SDK that matches the given SDK version.
200   if (FileSpec fspec = GetXcodeContentsDirectory()) {
201     StreamString sdk_path;
202     sdk_path.Printf("%s/Developer/Platforms/MacOSX.platform/Developer/"
203                     "SDKs/MacOSX%u.%u.sdk",
204                     fspec.GetPath().c_str(), version.getMajor(),
205                     version.getMinor().getValue());
206     if (FileSystem::Instance().Exists(fspec))
207       return ConstString(sdk_path.GetString());
208   }
209 
210   // Use the default SDK as a fallback.
211   if (FileSpec fspec = GetXcodeSDK(SDKType::MacOSX)) {
212     if (FileSystem::Instance().Exists(fspec))
213       return ConstString(fspec.GetPath());
214   }
215 
216   return {};
217 }
218 
219 Status PlatformMacOSX::GetSymbolFile(const FileSpec &platform_file,
220                                      const UUID *uuid_ptr,
221                                      FileSpec &local_file) {
222   if (IsRemote()) {
223     if (m_remote_platform_sp)
224       return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
225                                                    local_file);
226   }
227 
228   // Default to the local case
229   local_file = platform_file;
230   return Status();
231 }
232 
233 lldb_private::Status
234 PlatformMacOSX::GetFileWithUUID(const lldb_private::FileSpec &platform_file,
235                                 const lldb_private::UUID *uuid_ptr,
236                                 lldb_private::FileSpec &local_file) {
237   if (IsRemote() && m_remote_platform_sp) {
238     std::string local_os_build;
239 #if !defined(__linux__)
240     HostInfo::GetOSBuildString(local_os_build);
241 #endif
242     std::string remote_os_build;
243     m_remote_platform_sp->GetOSBuildString(remote_os_build);
244     if (local_os_build == remote_os_build) {
245       // same OS version: the local file is good enough
246       local_file = platform_file;
247       return Status();
248     } else {
249       // try to find the file in the cache
250       std::string cache_path(GetLocalCacheDirectory());
251       std::string module_path(platform_file.GetPath());
252       cache_path.append(module_path);
253       FileSpec module_cache_spec(cache_path);
254       if (FileSystem::Instance().Exists(module_cache_spec)) {
255         local_file = module_cache_spec;
256         return Status();
257       }
258       // bring in the remote module file
259       FileSpec module_cache_folder =
260           module_cache_spec.CopyByRemovingLastPathComponent();
261       // try to make the local directory first
262       Status err(
263           llvm::sys::fs::create_directory(module_cache_folder.GetPath()));
264       if (err.Fail())
265         return err;
266       err = GetFile(platform_file, module_cache_spec);
267       if (err.Fail())
268         return err;
269       if (FileSystem::Instance().Exists(module_cache_spec)) {
270         local_file = module_cache_spec;
271         return Status();
272       } else
273         return Status("unable to obtain valid module file");
274     }
275   }
276   local_file = platform_file;
277   return Status();
278 }
279 
280 bool PlatformMacOSX::GetSupportedArchitectureAtIndex(uint32_t idx,
281                                                      ArchSpec &arch) {
282 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
283   return ARMGetSupportedArchitectureAtIndex(idx, arch);
284 #else
285   return x86GetSupportedArchitectureAtIndex(idx, arch);
286 #endif
287 }
288 
289 lldb_private::Status PlatformMacOSX::GetSharedModule(
290     const lldb_private::ModuleSpec &module_spec, Process *process,
291     lldb::ModuleSP &module_sp,
292     const lldb_private::FileSpecList *module_search_paths_ptr,
293     lldb::ModuleSP *old_module_sp_ptr, bool *did_create_ptr) {
294   Status error = GetSharedModuleWithLocalCache(
295       module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
296       did_create_ptr);
297 
298   if (module_sp) {
299     if (module_spec.GetArchitecture().GetCore() ==
300         ArchSpec::eCore_x86_64_x86_64h) {
301       ObjectFile *objfile = module_sp->GetObjectFile();
302       if (objfile == nullptr) {
303         // We didn't find an x86_64h slice, fall back to a x86_64 slice
304         ModuleSpec module_spec_x86_64(module_spec);
305         module_spec_x86_64.GetArchitecture() = ArchSpec("x86_64-apple-macosx");
306         lldb::ModuleSP x86_64_module_sp;
307         lldb::ModuleSP old_x86_64_module_sp;
308         bool did_create = false;
309         Status x86_64_error = GetSharedModuleWithLocalCache(
310             module_spec_x86_64, x86_64_module_sp, module_search_paths_ptr,
311             &old_x86_64_module_sp, &did_create);
312         if (x86_64_module_sp && x86_64_module_sp->GetObjectFile()) {
313           module_sp = x86_64_module_sp;
314           if (old_module_sp_ptr)
315             *old_module_sp_ptr = old_x86_64_module_sp;
316           if (did_create_ptr)
317             *did_create_ptr = did_create;
318           return x86_64_error;
319         }
320       }
321     }
322   }
323 
324   if (!module_sp) {
325       error = FindBundleBinaryInExecSearchPaths (module_spec, process, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr);
326   }
327   return error;
328 }
329