1 //===-- PlatformLinux.cpp -------------------------------------------------===//
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 <cstdio>
13 #if LLDB_ENABLE_POSIX
14 #include <sys/utsname.h>
15 #endif
16 
17 #include "Utility/ARM64_DWARF_Registers.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Host/HostInfo.h"
21 #include "lldb/Symbol/UnwindPlan.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Utility/FileSpec.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/State.h"
27 #include "lldb/Utility/Status.h"
28 #include "lldb/Utility/StreamString.h"
29 
30 // Define these constants from Linux mman.h for use when targeting remote linux
31 // systems even when host has different values.
32 #define MAP_PRIVATE 2
33 #define MAP_ANON 0x20
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 using namespace lldb_private::platform_linux;
38 
39 LLDB_PLUGIN_DEFINE(PlatformLinux)
40 
41 static uint32_t g_initialize_count = 0;
42 
43 
44 PlatformSP PlatformLinux::CreateInstance(bool force, const ArchSpec *arch) {
45   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
46   LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force,
47            arch ? arch->GetArchitectureName() : "<null>",
48            arch ? arch->GetTriple().getTriple() : "<null>");
49 
50   bool create = force;
51   if (!create && arch && arch->IsValid()) {
52     const llvm::Triple &triple = arch->GetTriple();
53     switch (triple.getOS()) {
54     case llvm::Triple::Linux:
55       create = true;
56       break;
57 
58 #if defined(__linux__)
59     // Only accept "unknown" for the OS if the host is linux and it "unknown"
60     // wasn't specified (it was just returned because it was NOT specified)
61     case llvm::Triple::OSType::UnknownOS:
62       create = !arch->TripleOSWasSpecified();
63       break;
64 #endif
65     default:
66       break;
67     }
68   }
69 
70   LLDB_LOG(log, "create = {0}", create);
71   if (create) {
72     return PlatformSP(new PlatformLinux(false));
73   }
74   return PlatformSP();
75 }
76 
77 llvm::StringRef PlatformLinux::GetPluginDescriptionStatic(bool is_host) {
78   if (is_host)
79     return "Local Linux user platform plug-in.";
80   return "Remote Linux user platform plug-in.";
81 }
82 
83 void PlatformLinux::Initialize() {
84   PlatformPOSIX::Initialize();
85 
86   if (g_initialize_count++ == 0) {
87 #if defined(__linux__) && !defined(__ANDROID__)
88     PlatformSP default_platform_sp(new PlatformLinux(true));
89     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
90     Platform::SetHostPlatform(default_platform_sp);
91 #endif
92     PluginManager::RegisterPlugin(
93         PlatformLinux::GetPluginNameStatic(false),
94         PlatformLinux::GetPluginDescriptionStatic(false),
95         PlatformLinux::CreateInstance, nullptr);
96   }
97 }
98 
99 void PlatformLinux::Terminate() {
100   if (g_initialize_count > 0) {
101     if (--g_initialize_count == 0) {
102       PluginManager::UnregisterPlugin(PlatformLinux::CreateInstance);
103     }
104   }
105 
106   PlatformPOSIX::Terminate();
107 }
108 
109 /// Default Constructor
110 PlatformLinux::PlatformLinux(bool is_host)
111     : PlatformPOSIX(is_host) // This is the local host platform
112 {
113   if (is_host) {
114     ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
115     m_supported_architectures.push_back(hostArch);
116     if (hostArch.GetTriple().isArch64Bit()) {
117       m_supported_architectures.push_back(
118           HostInfo::GetArchitecture(HostInfo::eArchKind32));
119     }
120   } else {
121     m_supported_architectures = CreateArchList(
122         {llvm::Triple::x86_64, llvm::Triple::x86, llvm::Triple::arm,
123          llvm::Triple::aarch64, llvm::Triple::mips64, llvm::Triple::mips64,
124          llvm::Triple::hexagon, llvm::Triple::mips, llvm::Triple::mips64el,
125          llvm::Triple::mipsel, llvm::Triple::systemz},
126         llvm::Triple::Linux);
127   }
128 }
129 
130 std::vector<ArchSpec> PlatformLinux::GetSupportedArchitectures() {
131   if (m_remote_platform_sp)
132     return m_remote_platform_sp->GetSupportedArchitectures();
133   return m_supported_architectures;
134 }
135 
136 void PlatformLinux::GetStatus(Stream &strm) {
137   Platform::GetStatus(strm);
138 
139 #if LLDB_ENABLE_POSIX
140   // Display local kernel information only when we are running in host mode.
141   // Otherwise, we would end up printing non-Linux information (when running on
142   // Mac OS for example).
143   if (IsHost()) {
144     struct utsname un;
145 
146     if (uname(&un))
147       return;
148 
149     strm.Printf("    Kernel: %s\n", un.sysname);
150     strm.Printf("   Release: %s\n", un.release);
151     strm.Printf("   Version: %s\n", un.version);
152   }
153 #endif
154 }
155 
156 uint32_t
157 PlatformLinux::GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) {
158   uint32_t resume_count = 0;
159 
160   // Always resume past the initial stop when we use eLaunchFlagDebug
161   if (launch_info.GetFlags().Test(eLaunchFlagDebug)) {
162     // Resume past the stop for the final exec into the true inferior.
163     ++resume_count;
164   }
165 
166   // If we're not launching a shell, we're done.
167   const FileSpec &shell = launch_info.GetShell();
168   if (!shell)
169     return resume_count;
170 
171   std::string shell_string = shell.GetPath();
172   // We're in a shell, so for sure we have to resume past the shell exec.
173   ++resume_count;
174 
175   // Figure out what shell we're planning on using.
176   const char *shell_name = strrchr(shell_string.c_str(), '/');
177   if (shell_name == nullptr)
178     shell_name = shell_string.c_str();
179   else
180     shell_name++;
181 
182   if (strcmp(shell_name, "csh") == 0 || strcmp(shell_name, "tcsh") == 0 ||
183       strcmp(shell_name, "zsh") == 0 || strcmp(shell_name, "sh") == 0) {
184     // These shells seem to re-exec themselves.  Add another resume.
185     ++resume_count;
186   }
187 
188   return resume_count;
189 }
190 
191 bool PlatformLinux::CanDebugProcess() {
192   if (IsHost()) {
193     return true;
194   } else {
195     // If we're connected, we can debug.
196     return IsConnected();
197   }
198 }
199 
200 void PlatformLinux::CalculateTrapHandlerSymbolNames() {
201   m_trap_handlers.push_back(ConstString("_sigtramp"));
202   m_trap_handlers.push_back(ConstString("__kernel_rt_sigreturn"));
203   m_trap_handlers.push_back(ConstString("__restore_rt"));
204 }
205 
206 static lldb::UnwindPlanSP GetAArch64TrapHanlderUnwindPlan(ConstString name) {
207   UnwindPlanSP unwind_plan_sp;
208   if (name != "__kernel_rt_sigreturn")
209     return unwind_plan_sp;
210 
211   UnwindPlan::RowSP row = std::make_shared<UnwindPlan::Row>();
212   row->SetOffset(0);
213 
214   // In the signal trampoline frame, sp points to an rt_sigframe[1], which is:
215   //  - 128-byte siginfo struct
216   //  - ucontext struct:
217   //     - 8-byte long (uc_flags)
218   //     - 8-byte pointer (uc_link)
219   //     - 24-byte stack_t
220   //     - 128-byte signal set
221   //     - 8 bytes of padding because sigcontext has 16-byte alignment
222   //     - sigcontext/mcontext_t
223   // [1]
224   // https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/signal.c
225   int32_t offset = 128 + 8 + 8 + 24 + 128 + 8;
226   // Then sigcontext[2] is:
227   // - 8 byte fault address
228   // - 31 8 byte registers
229   // - 8 byte sp
230   // - 8 byte pc
231   // [2]
232   // https://github.com/torvalds/linux/blob/master/arch/arm64/include/uapi/asm/sigcontext.h
233 
234   // Skip fault address
235   offset += 8;
236   row->GetCFAValue().SetIsRegisterPlusOffset(arm64_dwarf::sp, offset);
237 
238   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x0, 0 * 8, false);
239   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x1, 1 * 8, false);
240   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x2, 2 * 8, false);
241   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x3, 3 * 8, false);
242   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x4, 4 * 8, false);
243   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x5, 5 * 8, false);
244   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x6, 6 * 8, false);
245   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x7, 7 * 8, false);
246   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x8, 8 * 8, false);
247   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x9, 9 * 8, false);
248   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x10, 10 * 8, false);
249   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x11, 11 * 8, false);
250   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x12, 12 * 8, false);
251   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x13, 13 * 8, false);
252   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x14, 14 * 8, false);
253   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x15, 15 * 8, false);
254   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x16, 16 * 8, false);
255   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x17, 17 * 8, false);
256   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x18, 18 * 8, false);
257   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x19, 19 * 8, false);
258   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x20, 20 * 8, false);
259   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x21, 21 * 8, false);
260   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x22, 22 * 8, false);
261   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x23, 23 * 8, false);
262   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x24, 24 * 8, false);
263   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x25, 25 * 8, false);
264   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x26, 26 * 8, false);
265   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x27, 27 * 8, false);
266   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x28, 28 * 8, false);
267   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::fp, 29 * 8, false);
268   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::x30, 30 * 8, false);
269   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::sp, 31 * 8, false);
270   row->SetRegisterLocationToAtCFAPlusOffset(arm64_dwarf::pc, 32 * 8, false);
271 
272   // The sigcontext may also contain floating point and SVE registers.
273   // However this would require a dynamic unwind plan so they are not included
274   // here.
275 
276   unwind_plan_sp = std::make_shared<UnwindPlan>(eRegisterKindDWARF);
277   unwind_plan_sp->AppendRow(row);
278   unwind_plan_sp->SetSourceName("AArch64 Linux sigcontext");
279   unwind_plan_sp->SetSourcedFromCompiler(eLazyBoolYes);
280   // Because sp is the same throughout the function
281   unwind_plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
282   unwind_plan_sp->SetUnwindPlanForSignalTrap(eLazyBoolYes);
283 
284   return unwind_plan_sp;
285 }
286 
287 lldb::UnwindPlanSP
288 PlatformLinux::GetTrapHandlerUnwindPlan(const llvm::Triple &triple,
289                                         ConstString name) {
290   if (triple.isAArch64())
291     return GetAArch64TrapHanlderUnwindPlan(name);
292 
293   return {};
294 }
295 
296 MmapArgList PlatformLinux::GetMmapArgumentList(const ArchSpec &arch,
297                                                addr_t addr, addr_t length,
298                                                unsigned prot, unsigned flags,
299                                                addr_t fd, addr_t offset) {
300   uint64_t flags_platform = 0;
301   uint64_t map_anon = arch.IsMIPS() ? 0x800 : MAP_ANON;
302 
303   if (flags & eMmapFlagsPrivate)
304     flags_platform |= MAP_PRIVATE;
305   if (flags & eMmapFlagsAnon)
306     flags_platform |= map_anon;
307 
308   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
309   return args;
310 }
311 
312