LLDB  mainline
PlatformNetBSD.cpp
Go to the documentation of this file.
1 //===-- PlatformNetBSD.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 "PlatformNetBSD.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"
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"
27 
28 // Define these constants from NetBSD mman.h for use when targeting remote
29 // netbsd 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_netbsd;
36 
38 
39 
40 PlatformSP PlatformNetBSD::CreateInstance(bool force, const ArchSpec *arch) {
42  LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force,
43  arch ? arch->GetArchitectureName() : "<null>",
44  arch ? arch->GetTriple().getTriple() : "<null>");
45 
46  bool create = force;
47  if (!create && arch && arch->IsValid()) {
48  const llvm::Triple &triple = arch->GetTriple();
49  switch (triple.getOS()) {
50  case llvm::Triple::NetBSD:
51  create = true;
52  break;
53 
54  default:
55  break;
56  }
57  }
58 
59  LLDB_LOG(log, "create = {0}", create);
60  if (create) {
61  return PlatformSP(new PlatformNetBSD(false));
62  }
63  return PlatformSP();
64 }
65 
66 ConstString PlatformNetBSD::GetPluginNameStatic(bool is_host) {
67  if (is_host) {
68  static ConstString g_host_name(Platform::GetHostPlatformName());
69  return g_host_name;
70  } else {
71  static ConstString g_remote_name("remote-netbsd");
72  return g_remote_name;
73  }
74 }
75 
76 const char *PlatformNetBSD::GetPluginDescriptionStatic(bool is_host) {
77  if (is_host)
78  return "Local NetBSD user platform plug-in.";
79  else
80  return "Remote NetBSD user platform plug-in.";
81 }
82 
83 ConstString PlatformNetBSD::GetPluginName() {
84  return GetPluginNameStatic(IsHost());
85 }
86 
87 void PlatformNetBSD::Initialize() {
89 
90  if (g_initialize_count++ == 0) {
91 #if defined(__NetBSD__)
92  PlatformSP default_platform_sp(new PlatformNetBSD(true));
93  default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
94  Platform::SetHostPlatform(default_platform_sp);
95 #endif
96  PluginManager::RegisterPlugin(
97  PlatformNetBSD::GetPluginNameStatic(false),
98  PlatformNetBSD::GetPluginDescriptionStatic(false),
99  PlatformNetBSD::CreateInstance, nullptr);
100  }
101 }
102 
103 void PlatformNetBSD::Terminate() {
104  if (g_initialize_count > 0) {
105  if (--g_initialize_count == 0) {
106  PluginManager::UnregisterPlugin(PlatformNetBSD::CreateInstance);
107  }
108  }
109 
111 }
112 
113 /// Default Constructor
114 PlatformNetBSD::PlatformNetBSD(bool is_host)
115  : PlatformPOSIX(is_host) // This is the local host platform
116 {}
117 
119 
121  ArchSpec &arch) {
122  if (IsHost()) {
123  ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
124  if (hostArch.GetTriple().isOSNetBSD()) {
125  if (idx == 0) {
126  arch = hostArch;
127  return arch.IsValid();
128  } else if (idx == 1) {
129  // If the default host architecture is 64-bit, look for a 32-bit
130  // variant
131  if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit()) {
132  arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
133  return arch.IsValid();
134  }
135  }
136  }
137  } else {
139  return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch);
140 
141  llvm::Triple triple;
142  // Set the OS to NetBSD
143  triple.setOS(llvm::Triple::NetBSD);
144  // Set the architecture
145  switch (idx) {
146  case 0:
147  triple.setArchName("x86_64");
148  break;
149  case 1:
150  triple.setArchName("i386");
151  break;
152  default:
153  return false;
154  }
155  // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the
156  // vendor by calling triple.SetVendorName("unknown") so that it is a
157  // "unspecified unknown". This means when someone calls
158  // triple.GetVendorName() it will return an empty string which indicates
159  // that the vendor can be set when two architectures are merged
160 
161  // Now set the triple into "arch" and return true
162  arch.SetTriple(triple);
163  return true;
164  }
165  return false;
166 }
167 
169  Platform::GetStatus(strm);
170 
171 #ifndef LLDB_DISABLE_POSIX
172  // Display local kernel information only when we are running in host mode.
173  // Otherwise, we would end up printing non-NetBSD information (when running
174  // on Mac OS for example).
175  if (IsHost()) {
176  struct utsname un;
177 
178  if (uname(&un))
179  return;
180 
181  strm.Printf(" Kernel: %s\n", un.sysname);
182  strm.Printf(" Release: %s\n", un.release);
183  strm.Printf(" Version: %s\n", un.version);
184  }
185 #endif
186 }
187 
188 int32_t
190  int32_t resume_count = 0;
191 
192  // Always resume past the initial stop when we use eLaunchFlagDebug
193  if (launch_info.GetFlags().Test(eLaunchFlagDebug)) {
194  // Resume past the stop for the final exec into the true inferior.
195  ++resume_count;
196  }
197 
198  // If we're not launching a shell, we're done.
199  const FileSpec &shell = launch_info.GetShell();
200  if (!shell)
201  return resume_count;
202 
203  std::string shell_string = shell.GetPath();
204  // We're in a shell, so for sure we have to resume past the shell exec.
205  ++resume_count;
206 
207  // Figure out what shell we're planning on using.
208  const char *shell_name = strrchr(shell_string.c_str(), '/');
209  if (shell_name == NULL)
210  shell_name = shell_string.c_str();
211  else
212  shell_name++;
213 
214  if (strcmp(shell_name, "csh") == 0 || strcmp(shell_name, "tcsh") == 0 ||
215  strcmp(shell_name, "zsh") == 0 || strcmp(shell_name, "sh") == 0) {
216  // These shells seem to re-exec themselves. Add another resume.
217  ++resume_count;
218  }
219 
220  return resume_count;
221 }
222 
224  if (IsHost()) {
225  return true;
226  } else {
227  // If we're connected, we can debug.
228  return IsConnected();
229  }
230 }
231 
232 // For local debugging, NetBSD will override the debug logic to use llgs-launch
233 // rather than lldb-launch, llgs-attach. This differs from current lldb-
234 // launch, debugserver-attach approach on MacOSX.
235 lldb::ProcessSP
237  Target *target, // Can be NULL, if NULL create a new
238  // target, else use existing one
239  Status &error) {
241  LLDB_LOG(log, "target {0}", target);
242 
243  // If we're a remote host, use standard behavior from parent class.
244  if (!IsHost())
245  return PlatformPOSIX::DebugProcess(launch_info, debugger, target, error);
246 
247  //
248  // For local debugging, we'll insist on having ProcessGDBRemote create the
249  // process.
250  //
251 
252  ProcessSP process_sp;
253 
254  // Make sure we stop at the entry point
255  launch_info.GetFlags().Set(eLaunchFlagDebug);
256 
257  // We always launch the process we are going to debug in a separate process
258  // group, since then we can handle ^C interrupts ourselves w/o having to
259  // worry about the target getting them as well.
260  launch_info.SetLaunchInSeparateProcessGroup(true);
261 
262  // Ensure we have a target.
263  if (target == nullptr) {
264  LLDB_LOG(log, "creating new target");
265  TargetSP new_target_sp;
266  error = debugger.GetTargetList().CreateTarget(
267  debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
268  if (error.Fail()) {
269  LLDB_LOG(log, "failed to create new target: {0}", error);
270  return process_sp;
271  }
272 
273  target = new_target_sp.get();
274  if (!target) {
275  error.SetErrorString("CreateTarget() returned nullptr");
276  LLDB_LOG(log, "error: {0}", error);
277  return process_sp;
278  }
279  }
280 
281  // Mark target as currently selected target.
282  debugger.GetTargetList().SetSelectedTarget(target);
283 
284  // Now create the gdb-remote process.
285  LLDB_LOG(log, "having target create process with gdb-remote plugin");
286  process_sp =
287  target->CreateProcess(launch_info.GetListener(), "gdb-remote", nullptr);
288 
289  if (!process_sp) {
290  error.SetErrorString("CreateProcess() failed for gdb-remote process");
291  LLDB_LOG(log, "error: {0}", error);
292  return process_sp;
293  }
294 
295  LLDB_LOG(log, "successfully created process");
296  // Adjust launch for a hijacker.
297  ListenerSP listener_sp;
298  if (!launch_info.GetHijackListener()) {
299  LLDB_LOG(log, "setting up hijacker");
300  listener_sp =
301  Listener::MakeListener("lldb.PlatformNetBSD.DebugProcess.hijack");
302  launch_info.SetHijackListener(listener_sp);
303  process_sp->HijackProcessEvents(listener_sp);
304  }
305 
306  // Log file actions.
307  if (log) {
308  LLDB_LOG(log, "launching process with the following file actions:");
309  StreamString stream;
310  size_t i = 0;
311  const FileAction *file_action;
312  while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
313  file_action->Dump(stream);
314  LLDB_LOG(log, "{0}", stream.GetData());
315  stream.Clear();
316  }
317  }
318 
319  // Do the launch.
320  error = process_sp->Launch(launch_info);
321  if (error.Success()) {
322  // Handle the hijacking of process events.
323  if (listener_sp) {
324  const StateType state = process_sp->WaitForProcessToStop(
325  llvm::None, NULL, false, listener_sp);
326 
327  LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
328  }
329 
330  // Hook up process PTY if we have one (which we should for local debugging
331  // with llgs).
332  int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
333  if (pty_fd != PseudoTerminal::invalid_fd) {
334  process_sp->SetSTDIOFileDescriptor(pty_fd);
335  LLDB_LOG(log, "hooked up STDIO pty to process");
336  } else
337  LLDB_LOG(log, "not using process STDIO pty");
338  } else {
339  LLDB_LOG(log, "process launch failed: {0}", error);
340  // FIXME figure out appropriate cleanup here. Do we delete the target? Do
341  // we delete the process? Does our caller do that?
342  }
343 
344  return process_sp;
345 }
346 
348  m_trap_handlers.push_back(ConstString("_sigtramp"));
349 }
350 
352  addr_t addr, addr_t length,
353  unsigned prot, unsigned flags,
354  addr_t fd, addr_t offset) {
355  uint64_t flags_platform = 0;
356 
357  if (flags & eMmapFlagsPrivate)
358  flags_platform |= MAP_PRIVATE;
359  if (flags & eMmapFlagsAnon)
360  flags_platform |= MAP_ANON;
361 
362  MmapArgList args({addr, length, prot, flags_platform, fd, offset});
363  return args;
364 }
A class to manage flag bits.
Definition: Debugger.h:82
void GetStatus(Stream &strm) override
Report the current status for this platform.
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition: ArchSpec.cpp:797
lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override
Get the platform&#39;s supported architectures in the order in which they should be searched.
void Dump(Stream &stream) const
Definition: FileAction.cpp:71
#define MAP_ANON
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file)
Definition: Target.cpp:195
bool IsHost() const
Definition: Platform.h:450
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
llvm::SmallVector< lldb::addr_t, 6 > MmapArgList
Definition: Platform.h:54
#define LIBLLDB_LOG_PLATFORM
Definition: Logging.h:39
lldb::ListenerSP GetListener() const
static void Terminate()
Definition: Platform.cpp:142
const char * GetData() const
Definition: StreamString.h:43
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:329
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
#define LLDB_LOG(log,...)
Definition: Log.h:209
int ReleaseMasterFileDescriptor()
Release the master file descriptor.
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:431
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:591
static lldb::ListenerSP MakeListener(const char *name)
Definition: Listener.cpp:465
bool Test(ValueType bit) const
Test a single flag bit.
Definition: Flags.h:107
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
static void Initialize()
Definition: Platform.cpp:140
void SetHijackListener(const lldb::ListenerSP &listener_sp)
void SetLaunchInSeparateProcessGroup(bool separate)
int32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) override
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
#define MAP_PRIVATE
void CalculateTrapHandlerSymbolNames() override
Ask the Platform subclass to fill in the list of trap handler names.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
bool Success() const
Test for success condition.
Definition: Status.cpp:287
TargetList & GetTargetList()
Get accessor for the target list.
Definition: Debugger.h:180
ValueType Set(ValueType mask)
Set one or more flags by logical OR&#39;ing mask with the current flags.
Definition: Flags.h:84
static uint32_t g_initialize_count
bool CanDebugProcess() override
Not all platforms will support debugging a process by spawning somehow halted for a debugger (specifi...
uint64_t addr_t
Definition: lldb-types.h:83
A uniqued constant string class.
Definition: ConstString.h:38
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
Invalid file descriptor value.
Definition: SBAddress.h:15
lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
uint32_t SetSelectedTarget(Target *target)
Definition: TargetList.cpp:601
lldb::ListenerSP GetHijackListener() const
MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr, lldb::addr_t length, unsigned prot, unsigned flags, lldb::addr_t fd, lldb::addr_t offset) override
const FileSpec & GetShell() const
const FileAction * GetFileActionAtIndex(size_t idx) const
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:376
std::vector< ConstString > m_trap_handlers
Definition: Platform.h:872
An error handling class.
Definition: Status.h:44
virtual void GetStatus(Stream &strm)
Report the current status for this platform.
Definition: Platform.cpp:403