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