xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/OpenBSD/NativeProcessOpenBSD.cpp (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 //===-- NativeProcessOpenBSD.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 "NativeProcessOpenBSD.h"
11 
12 // C Includes
13 #include <errno.h>
14 #define _DYN_LOADER
15 #include <elf.h>
16 #include <util.h>
17 
18 // C++ Includes
19 
20 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
21 #include "lldb/Host/HostProcess.h"
22 #include "lldb/Host/common/NativeRegisterContext.h"
23 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
24 #include "llvm/Support/Errno.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Utility/State.h"
27 
28 // System includes - They have to be included after framework includes because
29 // they define some macros which collide with variable names in other modules
30 // clang-format off
31 #include <sys/types.h>
32 #include <sys/ptrace.h>
33 #include <sys/sysctl.h>
34 #include <sys/wait.h>
35 // clang-format on
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 using namespace lldb_private::process_openbsd;
40 using namespace llvm;
41 
42 // Simple helper function to ensure flags are enabled on the given file
43 // descriptor.
44 static Status EnsureFDFlags(int fd, int flags) {
45   Status error;
46 
47   int status = fcntl(fd, F_GETFL);
48   if (status == -1) {
49     error.SetErrorToErrno();
50     return error;
51   }
52 
53   if (fcntl(fd, F_SETFL, status | flags) == -1) {
54     error.SetErrorToErrno();
55     return error;
56   }
57 
58   return error;
59 }
60 
61 // -----------------------------------------------------------------------------
62 // Public Static Methods
63 // -----------------------------------------------------------------------------
64 
65 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
66 NativeProcessOpenBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
67                                      NativeDelegate &native_delegate,
68                                      MainLoop &mainloop) const {
69   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
70 
71   Status status;
72   ::pid_t pid = ProcessLauncherPosixFork()
73                     .LaunchProcess(launch_info, status)
74                     .GetProcessId();
75   LLDB_LOG(log, "pid = {0:x}", pid);
76   if (status.Fail()) {
77     LLDB_LOG(log, "failed to launch process: {0}", status);
78     return status.ToError();
79   }
80 
81   // Wait for the child process to trap on its call to execve.
82   int wstatus;
83   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
84   assert(wpid == pid);
85   (void)wpid;
86   if (!WIFSTOPPED(wstatus)) {
87     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
88              WaitStatus::Decode(wstatus));
89     return llvm::make_error<StringError>("Could not sync with inferior process",
90                                          llvm::inconvertibleErrorCode());
91   }
92   LLDB_LOG(log, "inferior started, now in stopped state");
93 
94   ProcessInstanceInfo Info;
95   if (!Host::GetProcessInfo(pid, Info)) {
96     return llvm::make_error<StringError>("Cannot get process architecture",
97                                          llvm::inconvertibleErrorCode());
98   }
99 
100   // Set the architecture to the exe architecture.
101   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
102            Info.GetArchitecture().GetArchitectureName());
103 
104   std::unique_ptr<NativeProcessOpenBSD> process_up(new NativeProcessOpenBSD(
105       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
106       Info.GetArchitecture(), mainloop));
107 
108   status = process_up->ReinitializeThreads();
109   if (status.Fail())
110     return status.ToError();
111 
112   for (const auto &thread : process_up->m_threads)
113     static_cast<NativeThreadOpenBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
114   process_up->SetState(StateType::eStateStopped, false);
115 
116   return std::move(process_up);
117 }
118 
119 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
120 NativeProcessOpenBSD::Factory::Attach(
121     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
122     MainLoop &mainloop) const {
123 
124   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
125   LLDB_LOG(log, "pid = {0:x}", pid);
126 
127   // Retrieve the architecture for the running process.
128   ProcessInstanceInfo Info;
129   if (!Host::GetProcessInfo(pid, Info)) {
130     return llvm::make_error<StringError>("Cannot get process architecture",
131                                          llvm::inconvertibleErrorCode());
132   }
133 
134   std::unique_ptr<NativeProcessOpenBSD> process_up(new NativeProcessOpenBSD(
135       pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
136 
137   Status status = process_up->Attach();
138   if (!status.Success())
139     return status.ToError();
140 
141   return std::move(process_up);
142 }
143 
144 // -----------------------------------------------------------------------------
145 // Public Instance Methods
146 // -----------------------------------------------------------------------------
147 
148 NativeProcessOpenBSD::NativeProcessOpenBSD(::pid_t pid, int terminal_fd,
149                                          NativeDelegate &delegate,
150                                          const ArchSpec &arch,
151                                          MainLoop &mainloop)
152     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
153   if (m_terminal_fd != -1) {
154     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
155     assert(status.Success());
156   }
157 
158   Status status;
159   m_sigchld_handle = mainloop.RegisterSignal(
160       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
161   assert(m_sigchld_handle && status.Success());
162 }
163 
164 // Handles all waitpid events from the inferior process.
165 void NativeProcessOpenBSD::MonitorCallback(lldb::pid_t pid, int signal) {
166   switch (signal) {
167     case SIGTRAP:
168       return MonitorSIGTRAP(pid);
169     default:
170       return MonitorSignal(pid, signal);
171   }
172 }
173 
174 void NativeProcessOpenBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
175   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
176 
177   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
178 
179   /* Stop Tracking All Threads attached to Process */
180   m_threads.clear();
181 
182   SetExitStatus(status, true);
183 
184   // Notify delegate that our process has exited.
185   SetState(StateType::eStateExited, true);
186 }
187 
188 void NativeProcessOpenBSD::MonitorSIGTRAP(lldb::pid_t pid) {
189   for (const auto &thread : m_threads) {
190     static_cast<NativeThreadOpenBSD &>(*thread).SetStoppedByBreakpoint();
191     FixupBreakpointPCAsNeeded(static_cast<NativeThreadOpenBSD &>(*thread));
192   }
193   SetState(StateType::eStateStopped, true);
194 }
195 
196 
197 void NativeProcessOpenBSD::MonitorSignal(lldb::pid_t pid, int signal) {
198   for (const auto &thread : m_threads) {
199     static_cast<NativeThreadOpenBSD &>(*thread).SetStoppedBySignal(signal);
200   }
201   SetState(StateType::eStateStopped, true);
202 }
203 
204 Status NativeProcessOpenBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
205                                           int data, int *result) {
206   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
207   Status error;
208   int ret;
209 
210   errno = 0;
211   ret = ptrace(req, static_cast<::pid_t>(pid), (caddr_t)addr, data);
212 
213   if (ret == -1)
214     error.SetErrorToErrno();
215 
216   if (result)
217     *result = ret;
218 
219   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
220 
221   if (error.Fail())
222     LLDB_LOG(log, "ptrace() failed: {0}", error);
223 
224   return error;
225 }
226 
227 Status NativeProcessOpenBSD::Resume(const ResumeActionList &resume_actions) {
228   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
229   LLDB_LOG(log, "pid {0}", GetID());
230 
231   const auto &thread = m_threads[0];
232   const ResumeAction *const action =
233       resume_actions.GetActionForThread(thread->GetID(), true);
234 
235   if (action == nullptr) {
236     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
237              thread->GetID());
238     return Status();
239   }
240 
241   Status error;
242 
243   switch (action->state) {
244   case eStateRunning: {
245     // Run the thread, possibly feeding it the signal.
246     error = NativeProcessOpenBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
247                                                action->signal);
248     if (!error.Success())
249       return error;
250     for (const auto &thread : m_threads)
251       static_cast<NativeThreadOpenBSD &>(*thread).SetRunning();
252     SetState(eStateRunning, true);
253     break;
254   }
255   case eStateStepping:
256 #ifdef PT_STEP
257     // Run the thread, possibly feeding it the signal.
258     error = NativeProcessOpenBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
259                                                action->signal);
260     if (!error.Success())
261       return error;
262     for (const auto &thread : m_threads)
263       static_cast<NativeThreadOpenBSD &>(*thread).SetStepping();
264     SetState(eStateStepping, true);
265     break;
266 #else
267     return Status("NativeProcessOpenBSD stepping not supported on this platform");
268 #endif
269 
270   case eStateSuspended:
271   case eStateStopped:
272     llvm_unreachable("Unexpected state");
273 
274   default:
275     return Status("NativeProcessOpenBSD::%s (): unexpected state %s specified "
276                   "for pid %" PRIu64 ", tid %" PRIu64,
277                   __FUNCTION__, StateAsCString(action->state), GetID(),
278                   thread->GetID());
279   }
280 
281   return Status();
282 }
283 
284 Status NativeProcessOpenBSD::Halt() {
285   Status error;
286 
287   if (kill(GetID(), SIGSTOP) != 0)
288     error.SetErrorToErrno();
289 
290   return error;
291 }
292 
293 Status NativeProcessOpenBSD::Detach() {
294   Status error;
295 
296   // Stop monitoring the inferior.
297   m_sigchld_handle.reset();
298 
299   // Tell ptrace to detach from the process.
300   if (GetID() == LLDB_INVALID_PROCESS_ID)
301     return error;
302 
303   return PtraceWrapper(PT_DETACH, GetID());
304 }
305 
306 Status NativeProcessOpenBSD::Signal(int signo) {
307   Status error;
308 
309   if (kill(GetID(), signo))
310     error.SetErrorToErrno();
311 
312   return error;
313 }
314 
315 Status NativeProcessOpenBSD::Kill() {
316   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
317   LLDB_LOG(log, "pid {0}", GetID());
318 
319   Status error;
320 
321   switch (m_state) {
322   case StateType::eStateInvalid:
323   case StateType::eStateExited:
324   case StateType::eStateCrashed:
325   case StateType::eStateDetached:
326   case StateType::eStateUnloaded:
327     // Nothing to do - the process is already dead.
328     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
329              StateAsCString(m_state));
330     return error;
331 
332   case StateType::eStateConnected:
333   case StateType::eStateAttaching:
334   case StateType::eStateLaunching:
335   case StateType::eStateStopped:
336   case StateType::eStateRunning:
337   case StateType::eStateStepping:
338   case StateType::eStateSuspended:
339     // We can try to kill a process in these states.
340     break;
341   }
342 
343   if (kill(GetID(), SIGKILL) != 0) {
344     error.SetErrorToErrno();
345     return error;
346   }
347 
348   return error;
349 }
350 
351 Status NativeProcessOpenBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
352                                                 MemoryRegionInfo &range_info) {
353   return Status("Unimplemented");
354 }
355 
356 Status NativeProcessOpenBSD::PopulateMemoryRegionCache() {
357   return Status("Unimplemented");
358 }
359 
360 Status NativeProcessOpenBSD::AllocateMemory(size_t size, uint32_t permissions,
361                                            lldb::addr_t &addr) {
362   return Status("Unimplemented");
363 }
364 
365 Status NativeProcessOpenBSD::DeallocateMemory(lldb::addr_t addr) {
366   return Status("Unimplemented");
367 }
368 
369 lldb::addr_t NativeProcessOpenBSD::GetSharedLibraryInfoAddress() {
370   // punt on this for now
371   return LLDB_INVALID_ADDRESS;
372 }
373 
374 size_t NativeProcessOpenBSD::UpdateThreads() { return m_threads.size(); }
375 
376 Status NativeProcessOpenBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
377                                           bool hardware) {
378   if (hardware)
379     return Status("NativeProcessOpenBSD does not support hardware breakpoints");
380   else
381     return SetSoftwareBreakpoint(addr, size);
382 }
383 
384 Status NativeProcessOpenBSD::GetLoadedModuleFileSpec(const char *module_path,
385                                                     FileSpec &file_spec) {
386   return Status("Unimplemented");
387 }
388 
389 Status NativeProcessOpenBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
390                                                lldb::addr_t &load_addr) {
391   load_addr = LLDB_INVALID_ADDRESS;
392   return Status();
393 }
394 
395 void NativeProcessOpenBSD::SigchldHandler() {
396   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
397   // Process all pending waitpid notifications.
398   int status;
399   ::pid_t wait_pid =
400       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WNOHANG);
401 
402   if (wait_pid == 0)
403     return; // We are done.
404 
405   if (wait_pid == -1) {
406     Status error(errno, eErrorTypePOSIX);
407     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
408   }
409 
410   WaitStatus wait_status = WaitStatus::Decode(status);
411   bool exited = wait_status.type == WaitStatus::Exit ||
412                 (wait_status.type == WaitStatus::Signal &&
413                  wait_pid == static_cast<::pid_t>(GetID()));
414 
415   LLDB_LOG(log,
416            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
417            GetID(), wait_pid, status, exited);
418 
419   if (exited)
420     MonitorExited(wait_pid, wait_status);
421   else {
422     assert(wait_status.type == WaitStatus::Stop);
423     MonitorCallback(wait_pid, wait_status.status);
424   }
425 }
426 
427 bool NativeProcessOpenBSD::HasThreadNoLock(lldb::tid_t thread_id) {
428   for (const auto &thread : m_threads) {
429     assert(thread && "thread list should not contain NULL threads");
430     if (thread->GetID() == thread_id) {
431       // We have this thread.
432       return true;
433     }
434   }
435 
436   // We don't have this thread.
437   return false;
438 }
439 
440 NativeThreadOpenBSD &NativeProcessOpenBSD::AddThread(lldb::tid_t thread_id) {
441 
442   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
443   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
444 
445   assert(!HasThreadNoLock(thread_id) &&
446          "attempted to add a thread by id that already exists");
447 
448   // If this is the first thread, save it as the current thread
449   if (m_threads.empty())
450     SetCurrentThreadID(thread_id);
451 
452   m_threads.push_back(std::make_unique<NativeThreadOpenBSD>(*this, thread_id));
453   return static_cast<NativeThreadOpenBSD &>(*m_threads.back());
454 }
455 
456 Status NativeProcessOpenBSD::Attach() {
457   // Attach to the requested process.
458   // An attach will cause the thread to stop with a SIGSTOP.
459   Status status = PtraceWrapper(PT_ATTACH, m_pid);
460   if (status.Fail())
461     return status;
462 
463   int wstatus;
464   // At this point we should have a thread stopped if waitpid succeeds.
465   if ((wstatus = waitpid(m_pid, NULL, 0)) < 0)
466     return Status(errno, eErrorTypePOSIX);
467 
468   /* Initialize threads */
469   status = ReinitializeThreads();
470   if (status.Fail())
471     return status;
472 
473   for (const auto &thread : m_threads)
474     static_cast<NativeThreadOpenBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
475 
476   // Let our process instance know the thread has stopped.
477   SetState(StateType::eStateStopped);
478   return Status();
479 }
480 
481 Status NativeProcessOpenBSD::ReadMemory(lldb::addr_t addr, void *buf,
482                                        size_t size, size_t &bytes_read) {
483   unsigned char *dst = static_cast<unsigned char *>(buf);
484   struct ptrace_io_desc io;
485 
486   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
487   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
488 
489   bytes_read = 0;
490   io.piod_op = PIOD_READ_D;
491   io.piod_len = size;
492 
493   do {
494     io.piod_offs = (void *)(addr + bytes_read);
495     io.piod_addr = dst + bytes_read;
496 
497     Status error = NativeProcessOpenBSD::PtraceWrapper(PT_IO, GetID(), &io);
498     if (error.Fail())
499       return error;
500 
501     bytes_read = io.piod_len;
502     io.piod_len = size - bytes_read;
503   } while (bytes_read < size);
504 
505   return Status();
506 }
507 
508 Status NativeProcessOpenBSD::WriteMemory(lldb::addr_t addr, const void *buf,
509                                         size_t size, size_t &bytes_written) {
510   const unsigned char *src = static_cast<const unsigned char *>(buf);
511   Status error;
512   struct ptrace_io_desc io;
513 
514   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
515   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
516 
517   bytes_written = 0;
518   io.piod_op = PIOD_WRITE_D;
519   io.piod_len = size;
520 
521   do {
522     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
523     io.piod_offs = (void *)(addr + bytes_written);
524 
525     Status error = NativeProcessOpenBSD::PtraceWrapper(PT_IO, GetID(), &io);
526     if (error.Fail())
527       return error;
528 
529     bytes_written = io.piod_len;
530     io.piod_len = size - bytes_written;
531   } while (bytes_written < size);
532 
533   return error;
534 }
535 
536 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
537 NativeProcessOpenBSD::GetAuxvData() const {
538   size_t auxv_size = 100 * sizeof(AuxInfo);
539 
540   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
541       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
542 
543   struct ptrace_io_desc io;
544   io.piod_op = PIOD_READ_AUXV;
545   io.piod_offs = 0;
546   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
547   io.piod_len = auxv_size;
548 
549   Status error = NativeProcessOpenBSD::PtraceWrapper(PT_IO, GetID(), &io);
550 
551   if (error.Fail())
552     return std::error_code(error.GetError(), std::generic_category());
553 
554   if (io.piod_len < 1)
555     return std::error_code(ECANCELED, std::generic_category());
556 
557   return std::move(buf);
558 }
559 
560 Status NativeProcessOpenBSD::ReinitializeThreads() {
561   // Clear old threads
562   m_threads.clear();
563 
564   // Initialize new thread
565   struct ptrace_thread_state info = {};
566   Status error = PtraceWrapper(PT_GET_THREAD_FIRST, GetID(), &info, sizeof(info));
567   if (error.Fail()) {
568     return error;
569   }
570   // Reinitialize from scratch threads and register them in process
571   while (info.pts_tid > 0) {
572     AddThread(info.pts_tid);
573     error = PtraceWrapper(PT_GET_THREAD_NEXT, GetID(), &info, sizeof(info));
574     if (error.Fail() && errno != 0) {
575       return error;
576     }
577   }
578 
579   return error;
580 }
581