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