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