1 //===-- PlatformLinux.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 "PlatformLinux.h"
11 
12 // C Includes
13 #include <stdio.h>
14 #include <sys/utsname.h>
15 
16 // C++ Includes
17 // Other libraries and framework includes
18 // Project includes
19 #include "lldb/Core/Error.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleList.h"
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/StreamString.h"
26 #include "lldb/Host/FileSpec.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Process.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 static uint32_t g_initialize_count = 0;
35 
36 Platform *
37 PlatformLinux::CreateInstance (bool force, const ArchSpec *arch)
38 {
39     bool create = force;
40     if (create == false && arch && arch->IsValid())
41     {
42         const llvm::Triple &triple = arch->GetTriple();
43         switch (triple.getVendor())
44         {
45             case llvm::Triple::PC:
46                 create = true;
47                 break;
48 
49 #if defined(__linux__)
50             // Only accept "unknown" for the vendor if the host is linux and
51             // it "unknown" wasn't specified (it was just returned becasue it
52             // was NOT specified_
53             case llvm::Triple::UnknownArch:
54                 create = !arch->TripleVendorWasSpecified();
55                 break;
56 #endif
57             default:
58                 break;
59         }
60 
61         if (create)
62         {
63             switch (triple.getOS())
64             {
65                 case llvm::Triple::Linux:
66                     break;
67 
68 #if defined(__linux__)
69                 // Only accept "unknown" for the OS if the host is linux and
70                 // it "unknown" wasn't specified (it was just returned becasue it
71                 // was NOT specified)
72                 case llvm::Triple::UnknownOS:
73                     create = !arch->TripleOSWasSpecified();
74                     break;
75 #endif
76                 default:
77                     create = false;
78                     break;
79             }
80         }
81     }
82     if (create)
83         return new PlatformLinux(true);
84     return NULL;
85 }
86 
87 const char *
88 PlatformLinux::GetPluginNameStatic()
89 {
90     return "plugin.platform.linux";
91 }
92 
93 const char *
94 PlatformLinux::GetShortPluginNameStatic (bool is_host)
95 {
96     if (is_host)
97         return Platform::GetHostPlatformName ();
98     else
99         return "remote-linux";
100 }
101 
102 const char *
103 PlatformLinux::GetPluginDescriptionStatic (bool is_host)
104 {
105     if (is_host)
106         return "Local Linux user platform plug-in.";
107     else
108         return "Remote Linux user platform plug-in.";
109 }
110 
111 void
112 PlatformLinux::Initialize ()
113 {
114     if (g_initialize_count++ == 0)
115     {
116 #if defined(__linux__)
117         PlatformSP default_platform_sp (new PlatformLinux(true));
118         default_platform_sp->SetSystemArchitecture (Host::GetArchitecture());
119         Platform::SetDefaultPlatform (default_platform_sp);
120 #endif
121         PluginManager::RegisterPlugin(PlatformLinux::GetShortPluginNameStatic(false),
122                                       PlatformLinux::GetPluginDescriptionStatic(false),
123                                       PlatformLinux::CreateInstance);
124     }
125 }
126 
127 void
128 PlatformLinux::Terminate ()
129 {
130     if (g_initialize_count > 0)
131     {
132         if (--g_initialize_count == 0)
133         {
134             PluginManager::UnregisterPlugin (PlatformLinux::CreateInstance);
135         }
136     }
137 }
138 
139 Error
140 PlatformLinux::ResolveExecutable (const FileSpec &exe_file,
141                                   const ArchSpec &exe_arch,
142                                   lldb::ModuleSP &exe_module_sp,
143                                   const FileSpecList *module_search_paths_ptr)
144 {
145     Error error;
146     // Nothing special to do here, just use the actual file and architecture
147 
148     char exe_path[PATH_MAX];
149     FileSpec resolved_exe_file (exe_file);
150 
151     if (IsHost())
152     {
153         // If we have "ls" as the exe_file, resolve the executable location based on
154         // the current path variables
155         if (!resolved_exe_file.Exists())
156         {
157             exe_file.GetPath(exe_path, sizeof(exe_path));
158             resolved_exe_file.SetFile(exe_path, true);
159         }
160 
161         if (!resolved_exe_file.Exists())
162             resolved_exe_file.ResolveExecutableLocation ();
163 
164         if (resolved_exe_file.Exists())
165             error.Clear();
166         else
167         {
168             exe_file.GetPath(exe_path, sizeof(exe_path));
169             error.SetErrorStringWithFormat("unable to find executable for '%s'", exe_path);
170         }
171     }
172     else
173     {
174         if (m_remote_platform_sp)
175         {
176             error = m_remote_platform_sp->ResolveExecutable (exe_file,
177                                                              exe_arch,
178                                                              exe_module_sp,
179                                                              NULL);
180         }
181         else
182         {
183             // We may connect to a process and use the provided executable (Don't use local $PATH).
184 
185             if (resolved_exe_file.Exists())
186                 error.Clear();
187             else
188                 error.SetErrorStringWithFormat("the platform is not currently connected, and '%s' doesn't exist in the system root.", exe_path);
189         }
190     }
191 
192     if (error.Success())
193     {
194         ModuleSpec module_spec (resolved_exe_file, exe_arch);
195         if (exe_arch.IsValid())
196         {
197             error = ModuleList::GetSharedModule (module_spec,
198                                                  exe_module_sp,
199                                                  NULL,
200                                                  NULL,
201                                                  NULL);
202 
203             // TODO find out why exe_module_sp might be NULL
204             if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL)
205             {
206                 exe_module_sp.reset();
207                 error.SetErrorStringWithFormat ("'%s%s%s' doesn't contain the architecture %s",
208                                                 exe_file.GetDirectory().AsCString(""),
209                                                 exe_file.GetDirectory() ? "/" : "",
210                                                 exe_file.GetFilename().AsCString(""),
211                                                 exe_arch.GetArchitectureName());
212             }
213         }
214         else
215         {
216             // No valid architecture was specified, ask the platform for
217             // the architectures that we should be using (in the correct order)
218             // and see if we can find a match that way
219             StreamString arch_names;
220             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, module_spec.GetArchitecture()); ++idx)
221             {
222                 error = ModuleList::GetSharedModule (module_spec,
223                                                      exe_module_sp,
224                                                      NULL,
225                                                      NULL,
226                                                      NULL);
227                 // Did we find an executable using one of the
228                 if (error.Success())
229                 {
230                     if (exe_module_sp && exe_module_sp->GetObjectFile())
231                         break;
232                     else
233                         error.SetErrorToGenericError();
234                 }
235 
236                 if (idx > 0)
237                     arch_names.PutCString (", ");
238                 arch_names.PutCString (module_spec.GetArchitecture().GetArchitectureName());
239             }
240 
241             if (error.Fail() || !exe_module_sp)
242             {
243                 error.SetErrorStringWithFormat ("'%s%s%s' doesn't contain any '%s' platform architectures: %s",
244                                                 exe_file.GetDirectory().AsCString(""),
245                                                 exe_file.GetDirectory() ? "/" : "",
246                                                 exe_file.GetFilename().AsCString(""),
247                                                 GetShortPluginName(),
248                                                 arch_names.GetString().c_str());
249             }
250         }
251     }
252 
253     return error;
254 }
255 
256 Error
257 PlatformLinux::GetFile (const FileSpec &platform_file,
258                         const UUID *uuid_ptr, FileSpec &local_file)
259 {
260     if (IsRemote())
261     {
262         if (m_remote_platform_sp)
263             return m_remote_platform_sp->GetFile (platform_file, uuid_ptr, local_file);
264     }
265 
266     // Default to the local case
267     local_file = platform_file;
268     return Error();
269 }
270 
271 
272 //------------------------------------------------------------------
273 /// Default Constructor
274 //------------------------------------------------------------------
275 PlatformLinux::PlatformLinux (bool is_host) :
276     Platform(is_host),  // This is the local host platform
277     m_remote_platform_sp ()
278 {
279 }
280 
281 //------------------------------------------------------------------
282 /// Destructor.
283 ///
284 /// The destructor is virtual since this class is designed to be
285 /// inherited from by the plug-in instance.
286 //------------------------------------------------------------------
287 PlatformLinux::~PlatformLinux()
288 {
289 }
290 
291 bool
292 PlatformLinux::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
293 {
294     bool success = false;
295     if (IsHost())
296     {
297         success = Platform::GetProcessInfo (pid, process_info);
298     }
299     else
300     {
301         if (m_remote_platform_sp)
302             success = m_remote_platform_sp->GetProcessInfo (pid, process_info);
303     }
304     return success;
305 }
306 
307 bool
308 PlatformLinux::GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch)
309 {
310     if (idx == 0)
311     {
312         arch = Host::GetArchitecture (Host::eSystemDefaultArchitecture);
313         return arch.IsValid();
314     }
315     else if (idx == 1)
316     {
317         // If the default host architecture is 64-bit, look for a 32-bit variant
318         ArchSpec hostArch
319                       = Host::GetArchitecture(Host::eSystemDefaultArchitecture);
320         if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit())
321         {
322             arch = Host::GetArchitecture (Host::eSystemDefaultArchitecture32);
323             return arch.IsValid();
324         }
325     }
326     return false;
327 }
328 
329 void
330 PlatformLinux::GetStatus (Stream &strm)
331 {
332     struct utsname un;
333 
334     if (uname(&un)) {
335         strm << "Linux";
336         return;
337     }
338 
339     strm << un.sysname << ' ' << un.release << ' ' << un.version << '\n';
340 }
341 
342 size_t
343 PlatformLinux::GetSoftwareBreakpointTrapOpcode (Target &target,
344                                                 BreakpointSite *bp_site)
345 {
346     ArchSpec arch = target.GetArchitecture();
347     const uint8_t *trap_opcode = NULL;
348     size_t trap_opcode_size = 0;
349 
350     switch (arch.GetCore())
351     {
352     default:
353         assert(false && "CPU type not supported!");
354         break;
355 
356     case ArchSpec::eCore_x86_32_i386:
357     case ArchSpec::eCore_x86_64_x86_64:
358         {
359             static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
360             trap_opcode = g_i386_breakpoint_opcode;
361             trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
362         }
363         break;
364     }
365 
366     if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
367         return trap_opcode_size;
368     return 0;
369 }
370 
371 Error
372 PlatformLinux::LaunchProcess (ProcessLaunchInfo &launch_info)
373 {
374     Error error;
375 
376     if (IsHost())
377     {
378         if (launch_info.GetFlags().Test (eLaunchFlagLaunchInShell))
379         {
380             const bool is_localhost = true;
381             const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
382             const bool first_arg_is_full_shell_command = false;
383             if (!launch_info.ConvertArgumentsForLaunchingInShell (error,
384                                                                   is_localhost,
385                                                                   will_debug,
386                                                                   first_arg_is_full_shell_command))
387                 return error;
388         }
389         error = Platform::LaunchProcess (launch_info);
390     }
391     else
392     {
393         error.SetErrorString ("the platform is not currently connected");
394     }
395     return error;
396 }
397 
398 lldb::ProcessSP
399 PlatformLinux::Attach(ProcessAttachInfo &attach_info,
400                       Debugger &debugger,
401                       Target *target,
402                       Listener &listener,
403                       Error &error)
404 {
405     lldb::ProcessSP process_sp;
406     if (IsHost())
407     {
408         if (target == NULL)
409         {
410             TargetSP new_target_sp;
411             ArchSpec emptyArchSpec;
412 
413             error = debugger.GetTargetList().CreateTarget (debugger,
414                                                            NULL,
415                                                            emptyArchSpec,
416                                                            false,
417                                                            m_remote_platform_sp,
418                                                            new_target_sp);
419             target = new_target_sp.get();
420         }
421         else
422             error.Clear();
423 
424         if (target && error.Success())
425         {
426             debugger.GetTargetList().SetSelectedTarget(target);
427 
428             process_sp = target->CreateProcess (listener,
429                                                 attach_info.GetProcessPluginName(),
430                                                 NULL);
431 
432             if (process_sp)
433                 error = process_sp->Attach (attach_info);
434         }
435     }
436     else
437     {
438         if (m_remote_platform_sp)
439             process_sp = m_remote_platform_sp->Attach (attach_info, debugger, target, listener, error);
440         else
441             error.SetErrorString ("the platform is not currently connected");
442     }
443     return process_sp;
444 }
445