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