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