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