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 #include "lldb/Host/Config.h"
12 
13 // C Includes
14 #include <stdio.h>
15 #ifndef LLDB_DISABLE_POSIX
16 #include <sys/utsname.h>
17 #endif
18 
19 // C++ Includes
20 // Other libraries and framework includes
21 // Project includes
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Log.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Host/FileSpec.h"
27 #include "lldb/Host/HostInfo.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Utility/Error.h"
31 #include "lldb/Utility/StreamString.h"
32 
33 // Define these constants from Linux mman.h for use when targeting
34 // remote linux systems even when host has different values.
35 #define MAP_PRIVATE 2
36 #define MAP_ANON 0x20
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 using namespace lldb_private::platform_linux;
41 
42 static uint32_t g_initialize_count = 0;
43 
44 //------------------------------------------------------------------
45 
46 PlatformSP PlatformLinux::CreateInstance(bool force, const ArchSpec *arch) {
47   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
48   LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force,
49            arch ? arch->GetArchitectureName() : "<null>",
50            arch ? arch->GetTriple().getTriple() : "<null>");
51 
52   bool create = force;
53   if (create == false && arch && arch->IsValid()) {
54     const llvm::Triple &triple = arch->GetTriple();
55     switch (triple.getOS()) {
56     case llvm::Triple::Linux:
57       create = true;
58       break;
59 
60 #if defined(__linux__)
61     // Only accept "unknown" for the OS if the host is linux and
62     // it "unknown" wasn't specified (it was just returned because it
63     // was NOT specified)
64     case llvm::Triple::OSType::UnknownOS:
65       create = !arch->TripleOSWasSpecified();
66       break;
67 #endif
68     default:
69       break;
70     }
71   }
72 
73   LLDB_LOG(log, "create = {0}", create);
74   if (create) {
75     return PlatformSP(new PlatformLinux(false));
76   }
77   return PlatformSP();
78 }
79 
80 ConstString PlatformLinux::GetPluginNameStatic(bool is_host) {
81   if (is_host) {
82     static ConstString g_host_name(Platform::GetHostPlatformName());
83     return g_host_name;
84   } else {
85     static ConstString g_remote_name("remote-linux");
86     return g_remote_name;
87   }
88 }
89 
90 const char *PlatformLinux::GetPluginDescriptionStatic(bool is_host) {
91   if (is_host)
92     return "Local Linux user platform plug-in.";
93   else
94     return "Remote Linux user platform plug-in.";
95 }
96 
97 ConstString PlatformLinux::GetPluginName() {
98   return GetPluginNameStatic(IsHost());
99 }
100 
101 void PlatformLinux::Initialize() {
102   PlatformPOSIX::Initialize();
103 
104   if (g_initialize_count++ == 0) {
105 #if defined(__linux__) && !defined(__ANDROID__)
106     PlatformSP default_platform_sp(new PlatformLinux(true));
107     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
108     Platform::SetHostPlatform(default_platform_sp);
109 #endif
110     PluginManager::RegisterPlugin(
111         PlatformLinux::GetPluginNameStatic(false),
112         PlatformLinux::GetPluginDescriptionStatic(false),
113         PlatformLinux::CreateInstance, nullptr);
114   }
115 }
116 
117 void PlatformLinux::Terminate() {
118   if (g_initialize_count > 0) {
119     if (--g_initialize_count == 0) {
120       PluginManager::UnregisterPlugin(PlatformLinux::CreateInstance);
121     }
122   }
123 
124   PlatformPOSIX::Terminate();
125 }
126 
127 //------------------------------------------------------------------
128 /// Default Constructor
129 //------------------------------------------------------------------
130 PlatformLinux::PlatformLinux(bool is_host)
131     : PlatformPOSIX(is_host) // This is the local host platform
132 {}
133 
134 PlatformLinux::~PlatformLinux() = default;
135 
136 bool PlatformLinux::GetSupportedArchitectureAtIndex(uint32_t idx,
137                                                     ArchSpec &arch) {
138   if (IsHost()) {
139     ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
140     if (hostArch.GetTriple().isOSLinux()) {
141       if (idx == 0) {
142         arch = hostArch;
143         return arch.IsValid();
144       } else if (idx == 1) {
145         // If the default host architecture is 64-bit, look for a 32-bit variant
146         if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit()) {
147           arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
148           return arch.IsValid();
149         }
150       }
151     }
152   } else {
153     if (m_remote_platform_sp)
154       return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch);
155 
156     llvm::Triple triple;
157     // Set the OS to linux
158     triple.setOS(llvm::Triple::Linux);
159     // Set the architecture
160     switch (idx) {
161     case 0:
162       triple.setArchName("x86_64");
163       break;
164     case 1:
165       triple.setArchName("i386");
166       break;
167     case 2:
168       triple.setArchName("arm");
169       break;
170     case 3:
171       triple.setArchName("aarch64");
172       break;
173     case 4:
174       triple.setArchName("mips64");
175       break;
176     case 5:
177       triple.setArchName("hexagon");
178       break;
179     case 6:
180       triple.setArchName("mips");
181       break;
182     case 7:
183       triple.setArchName("mips64el");
184       break;
185     case 8:
186       triple.setArchName("mipsel");
187       break;
188     case 9:
189       triple.setArchName("s390x");
190       break;
191     default:
192       return false;
193     }
194     // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the
195     // vendor by
196     // calling triple.SetVendorName("unknown") so that it is a "unspecified
197     // unknown".
198     // This means when someone calls triple.GetVendorName() it will return an
199     // empty string
200     // which indicates that the vendor can be set when two architectures are
201     // merged
202 
203     // Now set the triple into "arch" and return true
204     arch.SetTriple(triple);
205     return true;
206   }
207   return false;
208 }
209 
210 void PlatformLinux::GetStatus(Stream &strm) {
211   Platform::GetStatus(strm);
212 
213 #ifndef LLDB_DISABLE_POSIX
214   // Display local kernel information only when we are running in host mode.
215   // Otherwise, we would end up printing non-Linux information (when running
216   // on Mac OS for example).
217   if (IsHost()) {
218     struct utsname un;
219 
220     if (uname(&un))
221       return;
222 
223     strm.Printf("    Kernel: %s\n", un.sysname);
224     strm.Printf("   Release: %s\n", un.release);
225     strm.Printf("   Version: %s\n", un.version);
226   }
227 #endif
228 }
229 
230 int32_t
231 PlatformLinux::GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) {
232   int32_t resume_count = 0;
233 
234   // Always resume past the initial stop when we use eLaunchFlagDebug
235   if (launch_info.GetFlags().Test(eLaunchFlagDebug)) {
236     // Resume past the stop for the final exec into the true inferior.
237     ++resume_count;
238   }
239 
240   // If we're not launching a shell, we're done.
241   const FileSpec &shell = launch_info.GetShell();
242   if (!shell)
243     return resume_count;
244 
245   std::string shell_string = shell.GetPath();
246   // We're in a shell, so for sure we have to resume past the shell exec.
247   ++resume_count;
248 
249   // Figure out what shell we're planning on using.
250   const char *shell_name = strrchr(shell_string.c_str(), '/');
251   if (shell_name == NULL)
252     shell_name = shell_string.c_str();
253   else
254     shell_name++;
255 
256   if (strcmp(shell_name, "csh") == 0 || strcmp(shell_name, "tcsh") == 0 ||
257       strcmp(shell_name, "zsh") == 0 || strcmp(shell_name, "sh") == 0) {
258     // These shells seem to re-exec themselves.  Add another resume.
259     ++resume_count;
260   }
261 
262   return resume_count;
263 }
264 
265 bool PlatformLinux::CanDebugProcess() {
266   if (IsHost()) {
267     return true;
268   } else {
269     // If we're connected, we can debug.
270     return IsConnected();
271   }
272 }
273 
274 // For local debugging, Linux will override the debug logic to use llgs-launch
275 // rather than lldb-launch, llgs-attach.  This differs from current lldb-launch,
276 // debugserver-attach approach on MacOSX.
277 lldb::ProcessSP
278 PlatformLinux::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
279                             Target *target, // Can be NULL, if NULL create a new
280                                             // target, else use existing one
281                             Error &error) {
282   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
283   LLDB_LOG(log, "target {0}", target);
284 
285   // If we're a remote host, use standard behavior from parent class.
286   if (!IsHost())
287     return PlatformPOSIX::DebugProcess(launch_info, debugger, target, error);
288 
289   //
290   // For local debugging, we'll insist on having ProcessGDBRemote create the
291   // process.
292   //
293 
294   ProcessSP process_sp;
295 
296   // Make sure we stop at the entry point
297   launch_info.GetFlags().Set(eLaunchFlagDebug);
298 
299   // We always launch the process we are going to debug in a separate process
300   // group, since then we can handle ^C interrupts ourselves w/o having to worry
301   // about the target getting them as well.
302   launch_info.SetLaunchInSeparateProcessGroup(true);
303 
304   // Ensure we have a target.
305   if (target == nullptr) {
306     LLDB_LOG(log, "creating new target");
307     TargetSP new_target_sp;
308     error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
309                                                   nullptr, new_target_sp);
310     if (error.Fail()) {
311       LLDB_LOG(log, "failed to create new target: {0}", error);
312       return process_sp;
313     }
314 
315     target = new_target_sp.get();
316     if (!target) {
317       error.SetErrorString("CreateTarget() returned nullptr");
318       LLDB_LOG(log, "error: {0}", error);
319       return process_sp;
320     }
321   }
322 
323   // Mark target as currently selected target.
324   debugger.GetTargetList().SetSelectedTarget(target);
325 
326   // Now create the gdb-remote process.
327   LLDB_LOG(log, "having target create process with gdb-remote plugin");
328   process_sp = target->CreateProcess(
329       launch_info.GetListenerForProcess(debugger), "gdb-remote", nullptr);
330 
331   if (!process_sp) {
332     error.SetErrorString("CreateProcess() failed for gdb-remote process");
333     LLDB_LOG(log, "error: {0}", error);
334     return process_sp;
335   }
336 
337   LLDB_LOG(log, "successfully created process");
338   // Adjust launch for a hijacker.
339   ListenerSP listener_sp;
340   if (!launch_info.GetHijackListener()) {
341     LLDB_LOG(log, "setting up hijacker");
342     listener_sp =
343         Listener::MakeListener("lldb.PlatformLinux.DebugProcess.hijack");
344     launch_info.SetHijackListener(listener_sp);
345     process_sp->HijackProcessEvents(listener_sp);
346   }
347 
348   // Log file actions.
349   if (log) {
350     LLDB_LOG(log, "launching process with the following file actions:");
351     StreamString stream;
352     size_t i = 0;
353     const FileAction *file_action;
354     while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
355       file_action->Dump(stream);
356       LLDB_LOG(log, "{0}", stream.GetData());
357       stream.Clear();
358     }
359   }
360 
361   // Do the launch.
362   error = process_sp->Launch(launch_info);
363   if (error.Success()) {
364     // Handle the hijacking of process events.
365     if (listener_sp) {
366       const StateType state = process_sp->WaitForProcessToStop(
367           llvm::None, NULL, false, listener_sp);
368 
369       LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
370     }
371 
372     // Hook up process PTY if we have one (which we should for local debugging
373     // with llgs).
374     int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
375     if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd) {
376       process_sp->SetSTDIOFileDescriptor(pty_fd);
377       LLDB_LOG(log, "hooked up STDIO pty to process");
378     } else
379       LLDB_LOG(log, "not using process STDIO pty");
380   } else {
381     LLDB_LOG(log, "process launch failed: {0}", error);
382     // FIXME figure out appropriate cleanup here.  Do we delete the target? Do
383     // we delete the process?  Does our caller do that?
384   }
385 
386   return process_sp;
387 }
388 
389 void PlatformLinux::CalculateTrapHandlerSymbolNames() {
390   m_trap_handlers.push_back(ConstString("_sigtramp"));
391 }
392 
393 uint64_t PlatformLinux::ConvertMmapFlagsToPlatform(const ArchSpec &arch,
394                                                    unsigned flags) {
395   uint64_t flags_platform = 0;
396   uint64_t map_anon = MAP_ANON;
397 
398   // To get correct flags for MIPS Architecture
399   if (arch.GetTriple().getArch() == llvm::Triple::mips64 ||
400       arch.GetTriple().getArch() == llvm::Triple::mips64el ||
401       arch.GetTriple().getArch() == llvm::Triple::mips ||
402       arch.GetTriple().getArch() == llvm::Triple::mipsel)
403     map_anon = 0x800;
404 
405   if (flags & eMmapFlagsPrivate)
406     flags_platform |= MAP_PRIVATE;
407   if (flags & eMmapFlagsAnon)
408     flags_platform |= map_anon;
409   return flags_platform;
410 }
411 
412