xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 //===-- PlatformOpenBSD.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 "PlatformOpenBSD.h"
10 #include "lldb/Host/Config.h"
11 
12 #include <stdio.h>
13 #if LLDB_ENABLE_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 OpenBSD mman.h for use when targeting remote
29 // openbsd systems even when host has different values.
30 #define MAP_PRIVATE 0x0002
31 #define MAP_ANON 0x1000
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 using namespace lldb_private::platform_openbsd;
36 
37 LLDB_PLUGIN_DEFINE(PlatformOpenBSD)
38 
39 static uint32_t g_initialize_count = 0;
40 
41 
42 PlatformSP PlatformOpenBSD::CreateInstance(bool force, const ArchSpec *arch) {
43   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
44   LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force,
45            arch ? arch->GetArchitectureName() : "<null>",
46            arch ? arch->GetTriple().getTriple() : "<null>");
47 
48   bool create = force;
49   if (!create && arch && arch->IsValid()) {
50     const llvm::Triple &triple = arch->GetTriple();
51     switch (triple.getOS()) {
52     case llvm::Triple::OpenBSD:
53       create = true;
54       break;
55 
56 #if defined(__OpenBSD__)
57     // Only accept "unknown" for the OS if the host is BSD and it "unknown"
58     // wasn't specified (it was just returned because it was NOT specified)
59     case llvm::Triple::OSType::UnknownOS:
60       create = !arch->TripleOSWasSpecified();
61       break;
62 #endif
63     default:
64       break;
65     }
66   }
67   LLDB_LOG(log, "create = {0}", create);
68   if (create) {
69     return PlatformSP(new PlatformOpenBSD(false));
70   }
71   return PlatformSP();
72 }
73 
74 ConstString PlatformOpenBSD::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-openbsd");
80     return g_remote_name;
81   }
82 }
83 
84 const char *PlatformOpenBSD::GetPluginDescriptionStatic(bool is_host) {
85   if (is_host)
86     return "Local OpenBSD user platform plug-in.";
87   else
88     return "Remote OpenBSD user platform plug-in.";
89 }
90 
91 ConstString PlatformOpenBSD::GetPluginName() {
92   return GetPluginNameStatic(IsHost());
93 }
94 
95 void PlatformOpenBSD::Initialize() {
96   PlatformPOSIX::Initialize();
97 
98   if (g_initialize_count++ == 0) {
99 #if defined(__OpenBSD__)
100     PlatformSP default_platform_sp(new PlatformOpenBSD(true));
101     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
102     Platform::SetHostPlatform(default_platform_sp);
103 #endif
104     PluginManager::RegisterPlugin(
105         PlatformOpenBSD::GetPluginNameStatic(false),
106         PlatformOpenBSD::GetPluginDescriptionStatic(false),
107         PlatformOpenBSD::CreateInstance, nullptr);
108   }
109 }
110 
111 void PlatformOpenBSD::Terminate() {
112   if (g_initialize_count > 0) {
113     if (--g_initialize_count == 0) {
114       PluginManager::UnregisterPlugin(PlatformOpenBSD::CreateInstance);
115     }
116   }
117 
118   PlatformPOSIX::Terminate();
119 }
120 
121 /// Default Constructor
122 PlatformOpenBSD::PlatformOpenBSD(bool is_host)
123     : PlatformPOSIX(is_host) // This is the local host platform
124 {}
125 
126 PlatformOpenBSD::~PlatformOpenBSD() = default;
127 
128 bool PlatformOpenBSD::GetSupportedArchitectureAtIndex(uint32_t idx,
129                                                       ArchSpec &arch) {
130   if (IsHost()) {
131     ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
132     if (hostArch.GetTriple().isOSOpenBSD()) {
133       if (idx == 0) {
134         arch = hostArch;
135         return arch.IsValid();
136       }
137     }
138   } else {
139     if (m_remote_platform_sp)
140       return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch);
141 
142     llvm::Triple triple;
143     // Set the OS to OpenBSD
144     triple.setOS(llvm::Triple::OpenBSD);
145     // Set the architecture
146     switch (idx) {
147     case 0:
148       triple.setArchName("x86_64");
149       break;
150     case 1:
151       triple.setArchName("i386");
152       break;
153     case 2:
154       triple.setArchName("aarch64");
155       break;
156     case 3:
157       triple.setArchName("arm");
158       break;
159     default:
160       return false;
161     }
162     // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the
163     // vendor by calling triple.SetVendorName("unknown") so that it is a
164     // "unspecified unknown". This means when someone calls
165     // triple.GetVendorName() it will return an empty string which indicates
166     // that the vendor can be set when two architectures are merged
167 
168     // Now set the triple into "arch" and return true
169     arch.SetTriple(triple);
170     return true;
171   }
172   return false;
173 }
174 
175 void PlatformOpenBSD::GetStatus(Stream &strm) {
176   Platform::GetStatus(strm);
177 
178 #if LLDB_ENABLE_POSIX
179   // Display local kernel information only when we are running in host mode.
180   // Otherwise, we would end up printing non-OpenBSD information (when running
181   // on Mac OS for example).
182   if (IsHost()) {
183     struct utsname un;
184 
185     if (uname(&un))
186       return;
187 
188     strm.Printf("    Kernel: %s\n", un.sysname);
189     strm.Printf("   Release: %s\n", un.release);
190     strm.Printf("   Version: %s\n", un.version);
191   }
192 #endif
193 }
194 
195 bool PlatformOpenBSD::CanDebugProcess() {
196 	if (IsHost()) {
197 		return true;
198 	} else {
199 		// If we're connected, we can debug.
200 		return IsConnected();
201 	}
202 }
203 
204 // For local debugging, OpenBSD will override the debug logic to use llgs-launch
205 // rather than lldb-launch, llgs-attach.  This differs from current lldb-
206 // launch, debugserver-attach approach on MacOSX.
207 lldb::ProcessSP
208 PlatformOpenBSD::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
209                              Target *target, // Can be NULL, if NULL create a new
210                                              // target, else use existing one
211                              Status &error) {
212   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
213   LLDB_LOG(log, "target {0}", target);
214 
215   // If we're a remote host, use standard behavior from parent class.
216   if (!IsHost())
217     return PlatformPOSIX::DebugProcess(launch_info, debugger, target, error);
218 
219   //
220   // For local debugging, we'll insist on having ProcessGDBRemote create the
221   // process.
222   //
223 
224   ProcessSP process_sp;
225 
226   // Make sure we stop at the entry point
227   launch_info.GetFlags().Set(eLaunchFlagDebug);
228 
229   // We always launch the process we are going to debug in a separate process
230   // group, since then we can handle ^C interrupts ourselves w/o having to
231   // worry about the target getting them as well.
232   launch_info.SetLaunchInSeparateProcessGroup(true);
233 
234   // Ensure we have a target.
235   if (target == nullptr) {
236     LLDB_LOG(log, "creating new target");
237     TargetSP new_target_sp;
238     error = debugger.GetTargetList().CreateTarget(debugger, "", "", eLoadDependentsNo,
239                                                   nullptr, new_target_sp);
240     if (error.Fail()) {
241       LLDB_LOG(log, "failed to create new target: {0}", error);
242       return process_sp;
243     }
244 
245     target = new_target_sp.get();
246     if (!target) {
247       error.SetErrorString("CreateTarget() returned nullptr");
248       LLDB_LOG(log, "error: {0}", error);
249       return process_sp;
250     }
251   }
252 
253   // Mark target as currently selected target.
254   debugger.GetTargetList().SetSelectedTarget(target);
255 
256   // Now create the gdb-remote process.
257   LLDB_LOG(log, "having target create process with gdb-remote plugin");
258   process_sp = target->CreateProcess(
259       launch_info.GetListener(), "gdb-remote", nullptr);
260 
261   if (!process_sp) {
262     error.SetErrorString("CreateProcess() failed for gdb-remote process");
263     LLDB_LOG(log, "error: {0}", error);
264     return process_sp;
265   }
266 
267   LLDB_LOG(log, "successfully created process");
268   // Adjust launch for a hijacker.
269   ListenerSP listener_sp;
270   if (!launch_info.GetHijackListener()) {
271     LLDB_LOG(log, "setting up hijacker");
272     listener_sp =
273         Listener::MakeListener("lldb.PlatformOpenBSD.DebugProcess.hijack");
274     launch_info.SetHijackListener(listener_sp);
275     process_sp->HijackProcessEvents(listener_sp);
276   }
277 
278   // Log file actions.
279   if (log) {
280     LLDB_LOG(log, "launching process with the following file actions:");
281     StreamString stream;
282     size_t i = 0;
283     const FileAction *file_action;
284     while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
285       file_action->Dump(stream);
286       LLDB_LOG(log, "{0}", stream.GetData());
287       stream.Clear();
288     }
289   }
290 
291   // Do the launch.
292   error = process_sp->Launch(launch_info);
293   if (error.Success()) {
294     // Handle the hijacking of process events.
295     if (listener_sp) {
296       const StateType state = process_sp->WaitForProcessToStop(
297           llvm::None, NULL, false, listener_sp);
298 
299       LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
300     }
301 
302     // Hook up process PTY if we have one (which we should for local debugging
303     // with llgs).
304     int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
305     if (pty_fd != PseudoTerminal::invalid_fd) {
306       process_sp->SetSTDIOFileDescriptor(pty_fd);
307       LLDB_LOG(log, "hooked up STDIO pty to process");
308     } else
309       LLDB_LOG(log, "not using process STDIO pty");
310   } else {
311     LLDB_LOG(log, "process launch failed: {0}", error);
312     // FIXME figure out appropriate cleanup here.  Do we delete the target? Do
313     // we delete the process?  Does our caller do that?
314   }
315 
316   return process_sp;
317 }
318 
319 void PlatformOpenBSD::CalculateTrapHandlerSymbolNames() {
320   m_trap_handlers.push_back(ConstString("_sigtramp"));
321 }
322 
323 MmapArgList PlatformOpenBSD::GetMmapArgumentList(const ArchSpec &arch,
324                                                  addr_t addr, addr_t length,
325                                                  unsigned prot, unsigned flags,
326                                                  addr_t fd, addr_t offset) {
327   uint64_t flags_platform = 0;
328 
329   if (flags & eMmapFlagsPrivate)
330     flags_platform |= MAP_PRIVATE;
331   if (flags & eMmapFlagsAnon)
332     flags_platform |= MAP_ANON;
333 
334   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
335   return args;
336 }
337 
338 FileSpec PlatformOpenBSD::LocateExecutable(const char *basename) {
339 
340   std::string check = std::string("/usr/bin/") + basename;
341   if (access(check.c_str(), X_OK) == 0) {
342     return FileSpec(check);
343   }
344 
345   return FileSpec();
346 }
347