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