]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/Process/FreeBSD/ProcessMonitor.cpp
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / source / Plugins / Process / FreeBSD / ProcessMonitor.cpp
1 //===-- ProcessMonitor.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 // C Includes
11 #include <errno.h>
12 #include <poll.h>
13 #include <signal.h>
14 #include <stdint.h>
15 #include <string.h>
16 #include <sys/ptrace.h>
17 #include <sys/socket.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <unistd.h>
21
22 // C++ Includes
23 // Other libraries and framework includes
24 #include "lldb/Core/Error.h"
25 #include "lldb/Core/RegisterValue.h"
26 #include "lldb/Core/Scalar.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Host/ThreadLauncher.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Target/UnixSignals.h"
32 #include "lldb/Utility/PseudoTerminal.h"
33
34 #include "FreeBSDThread.h"
35 #include "Plugins/Process/POSIX/CrashReason.h"
36 #include "ProcessFreeBSD.h"
37 #include "ProcessMonitor.h"
38 #include "ProcessPOSIXLog.h"
39
40 extern "C" {
41 extern char **environ;
42 }
43
44 using namespace lldb;
45 using namespace lldb_private;
46
47 // We disable the tracing of ptrace calls for integration builds to
48 // avoid the additional indirection and checks.
49 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
50 // Wrapper for ptrace to catch errors and log calls.
51
52 const char *Get_PT_IO_OP(int op) {
53   switch (op) {
54   case PIOD_READ_D:
55     return "READ_D";
56   case PIOD_WRITE_D:
57     return "WRITE_D";
58   case PIOD_READ_I:
59     return "READ_I";
60   case PIOD_WRITE_I:
61     return "WRITE_I";
62   default:
63     return "Unknown op";
64   }
65 }
66
67 // Wrapper for ptrace to catch errors and log calls.
68 // Note that ptrace sets errno on error because -1 is reserved as a valid
69 // result.
70 extern long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data,
71                           const char *reqName, const char *file, int line) {
72   long int result;
73
74   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
75
76   if (log) {
77     log->Printf("ptrace(%s, %" PRIu64 ", %p, %x) called from file %s line %d",
78                 reqName, pid, addr, data, file, line);
79     if (req == PT_IO) {
80       struct ptrace_io_desc *pi = (struct ptrace_io_desc *)addr;
81
82       log->Printf("PT_IO: op=%s offs=%zx size=%zu", Get_PT_IO_OP(pi->piod_op),
83                   (size_t)pi->piod_offs, pi->piod_len);
84     }
85   }
86
87   // PtraceDisplayBytes(req, data);
88
89   errno = 0;
90   result = ptrace(req, pid, (caddr_t)addr, data);
91
92   // PtraceDisplayBytes(req, data);
93
94   if (log && errno != 0) {
95     const char *str;
96     switch (errno) {
97     case ESRCH:
98       str = "ESRCH";
99       break;
100     case EINVAL:
101       str = "EINVAL";
102       break;
103     case EBUSY:
104       str = "EBUSY";
105       break;
106     case EPERM:
107       str = "EPERM";
108       break;
109     default:
110       str = "<unknown>";
111     }
112     log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
113   }
114
115   if (log) {
116 #ifdef __amd64__
117     if (req == PT_GETREGS) {
118       struct reg *r = (struct reg *)addr;
119
120       log->Printf("PT_GETREGS: rip=0x%lx rsp=0x%lx rbp=0x%lx rax=0x%lx",
121                   r->r_rip, r->r_rsp, r->r_rbp, r->r_rax);
122     }
123     if (req == PT_GETDBREGS || req == PT_SETDBREGS) {
124       struct dbreg *r = (struct dbreg *)addr;
125       char setget = (req == PT_GETDBREGS) ? 'G' : 'S';
126
127       for (int i = 0; i <= 7; i++)
128         log->Printf("PT_%cETDBREGS: dr[%d]=0x%lx", setget, i, r->dr[i]);
129     }
130 #endif
131   }
132
133   return result;
134 }
135
136 // Wrapper for ptrace when logging is not required.
137 // Sets errno to 0 prior to calling ptrace.
138 extern long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data) {
139   long result = 0;
140   errno = 0;
141   result = ptrace(req, pid, (caddr_t)addr, data);
142   return result;
143 }
144
145 #define PTRACE(req, pid, addr, data)                                           \
146   PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
147 #else
148 PtraceWrapper((req), (pid), (addr), (data))
149 #endif
150
151 //------------------------------------------------------------------------------
152 // Static implementations of ProcessMonitor::ReadMemory and
153 // ProcessMonitor::WriteMemory.  This enables mutual recursion between these
154 // functions without needed to go thru the thread funnel.
155
156 static size_t DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf,
157                            size_t size, Error &error) {
158   struct ptrace_io_desc pi_desc;
159
160   pi_desc.piod_op = PIOD_READ_D;
161   pi_desc.piod_offs = (void *)vm_addr;
162   pi_desc.piod_addr = buf;
163   pi_desc.piod_len = size;
164
165   if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
166     error.SetErrorToErrno();
167   return pi_desc.piod_len;
168 }
169
170 static size_t DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr,
171                             const void *buf, size_t size, Error &error) {
172   struct ptrace_io_desc pi_desc;
173
174   pi_desc.piod_op = PIOD_WRITE_D;
175   pi_desc.piod_offs = (void *)vm_addr;
176   pi_desc.piod_addr = (void *)buf;
177   pi_desc.piod_len = size;
178
179   if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
180     error.SetErrorToErrno();
181   return pi_desc.piod_len;
182 }
183
184 // Simple helper function to ensure flags are enabled on the given file
185 // descriptor.
186 static bool EnsureFDFlags(int fd, int flags, Error &error) {
187   int status;
188
189   if ((status = fcntl(fd, F_GETFL)) == -1) {
190     error.SetErrorToErrno();
191     return false;
192   }
193
194   if (fcntl(fd, F_SETFL, status | flags) == -1) {
195     error.SetErrorToErrno();
196     return false;
197   }
198
199   return true;
200 }
201
202 //------------------------------------------------------------------------------
203 /// @class Operation
204 /// @brief Represents a ProcessMonitor operation.
205 ///
206 /// Under FreeBSD, it is not possible to ptrace() from any other thread but the
207 /// one that spawned or attached to the process from the start.  Therefore, when
208 /// a ProcessMonitor is asked to deliver or change the state of an inferior
209 /// process the operation must be "funneled" to a specific thread to perform the
210 /// task.  The Operation class provides an abstract base for all services the
211 /// ProcessMonitor must perform via the single virtual function Execute, thus
212 /// encapsulating the code that needs to run in the privileged context.
213 class Operation {
214 public:
215   virtual ~Operation() {}
216   virtual void Execute(ProcessMonitor *monitor) = 0;
217 };
218
219 //------------------------------------------------------------------------------
220 /// @class ReadOperation
221 /// @brief Implements ProcessMonitor::ReadMemory.
222 class ReadOperation : public Operation {
223 public:
224   ReadOperation(lldb::addr_t addr, void *buff, size_t size, Error &error,
225                 size_t &result)
226       : m_addr(addr), m_buff(buff), m_size(size), m_error(error),
227         m_result(result) {}
228
229   void Execute(ProcessMonitor *monitor);
230
231 private:
232   lldb::addr_t m_addr;
233   void *m_buff;
234   size_t m_size;
235   Error &m_error;
236   size_t &m_result;
237 };
238
239 void ReadOperation::Execute(ProcessMonitor *monitor) {
240   lldb::pid_t pid = monitor->GetPID();
241
242   m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
243 }
244
245 //------------------------------------------------------------------------------
246 /// @class WriteOperation
247 /// @brief Implements ProcessMonitor::WriteMemory.
248 class WriteOperation : public Operation {
249 public:
250   WriteOperation(lldb::addr_t addr, const void *buff, size_t size, Error &error,
251                  size_t &result)
252       : m_addr(addr), m_buff(buff), m_size(size), m_error(error),
253         m_result(result) {}
254
255   void Execute(ProcessMonitor *monitor);
256
257 private:
258   lldb::addr_t m_addr;
259   const void *m_buff;
260   size_t m_size;
261   Error &m_error;
262   size_t &m_result;
263 };
264
265 void WriteOperation::Execute(ProcessMonitor *monitor) {
266   lldb::pid_t pid = monitor->GetPID();
267
268   m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
269 }
270
271 //------------------------------------------------------------------------------
272 /// @class ReadRegOperation
273 /// @brief Implements ProcessMonitor::ReadRegisterValue.
274 class ReadRegOperation : public Operation {
275 public:
276   ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
277                    RegisterValue &value, bool &result)
278       : m_tid(tid), m_offset(offset), m_size(size), m_value(value),
279         m_result(result) {}
280
281   void Execute(ProcessMonitor *monitor);
282
283 private:
284   lldb::tid_t m_tid;
285   unsigned m_offset;
286   unsigned m_size;
287   RegisterValue &m_value;
288   bool &m_result;
289 };
290
291 void ReadRegOperation::Execute(ProcessMonitor *monitor) {
292   struct reg regs;
293   int rc;
294
295   if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0)) < 0) {
296     m_result = false;
297   } else {
298     // 'struct reg' contains only 32- or 64-bit register values.  Punt on
299     // others.  Also, not all entries may be uintptr_t sized, such as 32-bit
300     // processes on powerpc64 (probably the same for i386 on amd64)
301     if (m_size == sizeof(uint32_t))
302       m_value = *(uint32_t *)(((caddr_t)&regs) + m_offset);
303     else if (m_size == sizeof(uint64_t))
304       m_value = *(uint64_t *)(((caddr_t)&regs) + m_offset);
305     else
306       memcpy((void *)&m_value, (((caddr_t)&regs) + m_offset), m_size);
307     m_result = true;
308   }
309 }
310
311 //------------------------------------------------------------------------------
312 /// @class WriteRegOperation
313 /// @brief Implements ProcessMonitor::WriteRegisterValue.
314 class WriteRegOperation : public Operation {
315 public:
316   WriteRegOperation(lldb::tid_t tid, unsigned offset,
317                     const RegisterValue &value, bool &result)
318       : m_tid(tid), m_offset(offset), m_value(value), m_result(result) {}
319
320   void Execute(ProcessMonitor *monitor);
321
322 private:
323   lldb::tid_t m_tid;
324   unsigned m_offset;
325   const RegisterValue &m_value;
326   bool &m_result;
327 };
328
329 void WriteRegOperation::Execute(ProcessMonitor *monitor) {
330   struct reg regs;
331
332   if (PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0) < 0) {
333     m_result = false;
334     return;
335   }
336   *(uintptr_t *)(((caddr_t)&regs) + m_offset) =
337       (uintptr_t)m_value.GetAsUInt64();
338   if (PTRACE(PT_SETREGS, m_tid, (caddr_t)&regs, 0) < 0)
339     m_result = false;
340   else
341     m_result = true;
342 }
343
344 //------------------------------------------------------------------------------
345 /// @class ReadDebugRegOperation
346 /// @brief Implements ProcessMonitor::ReadDebugRegisterValue.
347 class ReadDebugRegOperation : public Operation {
348 public:
349   ReadDebugRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
350                         RegisterValue &value, bool &result)
351       : m_tid(tid), m_offset(offset), m_size(size), m_value(value),
352         m_result(result) {}
353
354   void Execute(ProcessMonitor *monitor);
355
356 private:
357   lldb::tid_t m_tid;
358   unsigned m_offset;
359   unsigned m_size;
360   RegisterValue &m_value;
361   bool &m_result;
362 };
363
364 void ReadDebugRegOperation::Execute(ProcessMonitor *monitor) {
365   struct dbreg regs;
366   int rc;
367
368   if ((rc = PTRACE(PT_GETDBREGS, m_tid, (caddr_t)&regs, 0)) < 0) {
369     m_result = false;
370   } else {
371     if (m_size == sizeof(uintptr_t))
372       m_value = *(uintptr_t *)(((caddr_t)&regs) + m_offset);
373     else
374       memcpy((void *)&m_value, (((caddr_t)&regs) + m_offset), m_size);
375     m_result = true;
376   }
377 }
378
379 //------------------------------------------------------------------------------
380 /// @class WriteDebugRegOperation
381 /// @brief Implements ProcessMonitor::WriteDebugRegisterValue.
382 class WriteDebugRegOperation : public Operation {
383 public:
384   WriteDebugRegOperation(lldb::tid_t tid, unsigned offset,
385                          const RegisterValue &value, bool &result)
386       : m_tid(tid), m_offset(offset), m_value(value), m_result(result) {}
387
388   void Execute(ProcessMonitor *monitor);
389
390 private:
391   lldb::tid_t m_tid;
392   unsigned m_offset;
393   const RegisterValue &m_value;
394   bool &m_result;
395 };
396
397 void WriteDebugRegOperation::Execute(ProcessMonitor *monitor) {
398   struct dbreg regs;
399
400   if (PTRACE(PT_GETDBREGS, m_tid, (caddr_t)&regs, 0) < 0) {
401     m_result = false;
402     return;
403   }
404   *(uintptr_t *)(((caddr_t)&regs) + m_offset) =
405       (uintptr_t)m_value.GetAsUInt64();
406   if (PTRACE(PT_SETDBREGS, m_tid, (caddr_t)&regs, 0) < 0)
407     m_result = false;
408   else
409     m_result = true;
410 }
411
412 //------------------------------------------------------------------------------
413 /// @class ReadGPROperation
414 /// @brief Implements ProcessMonitor::ReadGPR.
415 class ReadGPROperation : public Operation {
416 public:
417   ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
418       : m_tid(tid), m_buf(buf), m_result(result) {}
419
420   void Execute(ProcessMonitor *monitor);
421
422 private:
423   lldb::tid_t m_tid;
424   void *m_buf;
425   bool &m_result;
426 };
427
428 void ReadGPROperation::Execute(ProcessMonitor *monitor) {
429   int rc;
430
431   errno = 0;
432   rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
433   if (errno != 0)
434     m_result = false;
435   else
436     m_result = true;
437 }
438
439 //------------------------------------------------------------------------------
440 /// @class ReadFPROperation
441 /// @brief Implements ProcessMonitor::ReadFPR.
442 class ReadFPROperation : public Operation {
443 public:
444   ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
445       : m_tid(tid), m_buf(buf), m_result(result) {}
446
447   void Execute(ProcessMonitor *monitor);
448
449 private:
450   lldb::tid_t m_tid;
451   void *m_buf;
452   bool &m_result;
453 };
454
455 void ReadFPROperation::Execute(ProcessMonitor *monitor) {
456   if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
457     m_result = false;
458   else
459     m_result = true;
460 }
461
462 //------------------------------------------------------------------------------
463 /// @class WriteGPROperation
464 /// @brief Implements ProcessMonitor::WriteGPR.
465 class WriteGPROperation : public Operation {
466 public:
467   WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
468       : m_tid(tid), m_buf(buf), m_result(result) {}
469
470   void Execute(ProcessMonitor *monitor);
471
472 private:
473   lldb::tid_t m_tid;
474   void *m_buf;
475   bool &m_result;
476 };
477
478 void WriteGPROperation::Execute(ProcessMonitor *monitor) {
479   if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
480     m_result = false;
481   else
482     m_result = true;
483 }
484
485 //------------------------------------------------------------------------------
486 /// @class WriteFPROperation
487 /// @brief Implements ProcessMonitor::WriteFPR.
488 class WriteFPROperation : public Operation {
489 public:
490   WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
491       : m_tid(tid), m_buf(buf), m_result(result) {}
492
493   void Execute(ProcessMonitor *monitor);
494
495 private:
496   lldb::tid_t m_tid;
497   void *m_buf;
498   bool &m_result;
499 };
500
501 void WriteFPROperation::Execute(ProcessMonitor *monitor) {
502   if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
503     m_result = false;
504   else
505     m_result = true;
506 }
507
508 //------------------------------------------------------------------------------
509 /// @class ResumeOperation
510 /// @brief Implements ProcessMonitor::Resume.
511 class ResumeOperation : public Operation {
512 public:
513   ResumeOperation(uint32_t signo, bool &result)
514       : m_signo(signo), m_result(result) {}
515
516   void Execute(ProcessMonitor *monitor);
517
518 private:
519   uint32_t m_signo;
520   bool &m_result;
521 };
522
523 void ResumeOperation::Execute(ProcessMonitor *monitor) {
524   lldb::pid_t pid = monitor->GetPID();
525   int data = 0;
526
527   if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
528     data = m_signo;
529
530   if (PTRACE(PT_CONTINUE, pid, (caddr_t)1, data)) {
531     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
532
533     if (log)
534       log->Printf("ResumeOperation (%" PRIu64 ") failed: %s", pid,
535                   strerror(errno));
536     m_result = false;
537   } else
538     m_result = true;
539 }
540
541 //------------------------------------------------------------------------------
542 /// @class SingleStepOperation
543 /// @brief Implements ProcessMonitor::SingleStep.
544 class SingleStepOperation : public Operation {
545 public:
546   SingleStepOperation(uint32_t signo, bool &result)
547       : m_signo(signo), m_result(result) {}
548
549   void Execute(ProcessMonitor *monitor);
550
551 private:
552   uint32_t m_signo;
553   bool &m_result;
554 };
555
556 void SingleStepOperation::Execute(ProcessMonitor *monitor) {
557   lldb::pid_t pid = monitor->GetPID();
558   int data = 0;
559
560   if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
561     data = m_signo;
562
563   if (PTRACE(PT_STEP, pid, NULL, data))
564     m_result = false;
565   else
566     m_result = true;
567 }
568
569 //------------------------------------------------------------------------------
570 /// @class LwpInfoOperation
571 /// @brief Implements ProcessMonitor::GetLwpInfo.
572 class LwpInfoOperation : public Operation {
573 public:
574   LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
575       : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) {}
576
577   void Execute(ProcessMonitor *monitor);
578
579 private:
580   lldb::tid_t m_tid;
581   void *m_info;
582   bool &m_result;
583   int &m_err;
584 };
585
586 void LwpInfoOperation::Execute(ProcessMonitor *monitor) {
587   struct ptrace_lwpinfo plwp;
588
589   if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
590     m_result = false;
591     m_err = errno;
592   } else {
593     memcpy(m_info, &plwp, sizeof(plwp));
594     m_result = true;
595   }
596 }
597
598 //------------------------------------------------------------------------------
599 /// @class ThreadSuspendOperation
600 /// @brief Implements ProcessMonitor::ThreadSuspend.
601 class ThreadSuspendOperation : public Operation {
602 public:
603   ThreadSuspendOperation(lldb::tid_t tid, bool suspend, bool &result)
604       : m_tid(tid), m_suspend(suspend), m_result(result) {}
605
606   void Execute(ProcessMonitor *monitor);
607
608 private:
609   lldb::tid_t m_tid;
610   bool m_suspend;
611   bool &m_result;
612 };
613
614 void ThreadSuspendOperation::Execute(ProcessMonitor *monitor) {
615   m_result = !PTRACE(m_suspend ? PT_SUSPEND : PT_RESUME, m_tid, NULL, 0);
616 }
617
618 //------------------------------------------------------------------------------
619 /// @class EventMessageOperation
620 /// @brief Implements ProcessMonitor::GetEventMessage.
621 class EventMessageOperation : public Operation {
622 public:
623   EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
624       : m_tid(tid), m_message(message), m_result(result) {}
625
626   void Execute(ProcessMonitor *monitor);
627
628 private:
629   lldb::tid_t m_tid;
630   unsigned long *m_message;
631   bool &m_result;
632 };
633
634 void EventMessageOperation::Execute(ProcessMonitor *monitor) {
635   struct ptrace_lwpinfo plwp;
636
637   if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
638     m_result = false;
639   else {
640     if (plwp.pl_flags & PL_FLAG_FORKED) {
641       *m_message = plwp.pl_child_pid;
642       m_result = true;
643     } else
644       m_result = false;
645   }
646 }
647
648 //------------------------------------------------------------------------------
649 /// @class KillOperation
650 /// @brief Implements ProcessMonitor::Kill.
651 class KillOperation : public Operation {
652 public:
653   KillOperation(bool &result) : m_result(result) {}
654
655   void Execute(ProcessMonitor *monitor);
656
657 private:
658   bool &m_result;
659 };
660
661 void KillOperation::Execute(ProcessMonitor *monitor) {
662   lldb::pid_t pid = monitor->GetPID();
663
664   if (PTRACE(PT_KILL, pid, NULL, 0))
665     m_result = false;
666   else
667     m_result = true;
668 }
669
670 //------------------------------------------------------------------------------
671 /// @class DetachOperation
672 /// @brief Implements ProcessMonitor::Detach.
673 class DetachOperation : public Operation {
674 public:
675   DetachOperation(Error &result) : m_error(result) {}
676
677   void Execute(ProcessMonitor *monitor);
678
679 private:
680   Error &m_error;
681 };
682
683 void DetachOperation::Execute(ProcessMonitor *monitor) {
684   lldb::pid_t pid = monitor->GetPID();
685
686   if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
687     m_error.SetErrorToErrno();
688 }
689
690 ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
691     : m_monitor(monitor) {
692   sem_init(&m_semaphore, 0, 0);
693 }
694
695 ProcessMonitor::OperationArgs::~OperationArgs() { sem_destroy(&m_semaphore); }
696
697 ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
698                                        lldb_private::Module *module,
699                                        char const **argv, char const **envp,
700                                        const FileSpec &stdin_file_spec,
701                                        const FileSpec &stdout_file_spec,
702                                        const FileSpec &stderr_file_spec,
703                                        const FileSpec &working_dir)
704     : OperationArgs(monitor), m_module(module), m_argv(argv), m_envp(envp),
705       m_stdin_file_spec(stdin_file_spec), m_stdout_file_spec(stdout_file_spec),
706       m_stderr_file_spec(stderr_file_spec), m_working_dir(working_dir) {}
707
708 ProcessMonitor::LaunchArgs::~LaunchArgs() {}
709
710 ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor, lldb::pid_t pid)
711     : OperationArgs(monitor), m_pid(pid) {}
712
713 ProcessMonitor::AttachArgs::~AttachArgs() {}
714
715 //------------------------------------------------------------------------------
716 /// The basic design of the ProcessMonitor is built around two threads.
717 ///
718 /// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
719 /// for changes in the debugee state.  When a change is detected a
720 /// ProcessMessage is sent to the associated ProcessFreeBSD instance.  This
721 /// thread
722 /// "drives" state changes in the debugger.
723 ///
724 /// The second thread (@see OperationThread) is responsible for two things 1)
725 /// launching or attaching to the inferior process, and then 2) servicing
726 /// operations such as register reads/writes, stepping, etc.  See the comments
727 /// on the Operation class for more info as to why this is needed.
728 ProcessMonitor::ProcessMonitor(
729     ProcessFreeBSD *process, Module *module, const char *argv[],
730     const char *envp[], const FileSpec &stdin_file_spec,
731     const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec,
732     const FileSpec &working_dir,
733     const lldb_private::ProcessLaunchInfo & /* launch_info */,
734     lldb_private::Error &error)
735     : m_process(static_cast<ProcessFreeBSD *>(process)),
736       m_pid(LLDB_INVALID_PROCESS_ID), m_terminal_fd(-1), m_operation(0) {
737   using namespace std::placeholders;
738
739   std::unique_ptr<LaunchArgs> args(
740       new LaunchArgs(this, module, argv, envp, stdin_file_spec,
741                      stdout_file_spec, stderr_file_spec, working_dir));
742
743   sem_init(&m_operation_pending, 0, 0);
744   sem_init(&m_operation_done, 0, 0);
745
746   StartLaunchOpThread(args.get(), error);
747   if (!error.Success())
748     return;
749
750 WAIT_AGAIN:
751   // Wait for the operation thread to initialize.
752   if (sem_wait(&args->m_semaphore)) {
753     if (errno == EINTR)
754       goto WAIT_AGAIN;
755     else {
756       error.SetErrorToErrno();
757       return;
758     }
759   }
760
761   // Check that the launch was a success.
762   if (!args->m_error.Success()) {
763     StopOpThread();
764     error = args->m_error;
765     return;
766   }
767
768   // Finally, start monitoring the child process for change in state.
769   m_monitor_thread = Host::StartMonitoringChildProcess(
770       std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4),
771       GetPID(), true);
772   if (!m_monitor_thread.IsJoinable()) {
773     error.SetErrorToGenericError();
774     error.SetErrorString("Process launch failed.");
775     return;
776   }
777 }
778
779 ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid,
780                                lldb_private::Error &error)
781     : m_process(static_cast<ProcessFreeBSD *>(process)), m_pid(pid),
782       m_terminal_fd(-1), m_operation(0) {
783   using namespace std::placeholders;
784
785   sem_init(&m_operation_pending, 0, 0);
786   sem_init(&m_operation_done, 0, 0);
787
788   std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
789
790   StartAttachOpThread(args.get(), error);
791   if (!error.Success())
792     return;
793
794 WAIT_AGAIN:
795   // Wait for the operation thread to initialize.
796   if (sem_wait(&args->m_semaphore)) {
797     if (errno == EINTR)
798       goto WAIT_AGAIN;
799     else {
800       error.SetErrorToErrno();
801       return;
802     }
803   }
804
805   // Check that the attach was a success.
806   if (!args->m_error.Success()) {
807     StopOpThread();
808     error = args->m_error;
809     return;
810   }
811
812   // Finally, start monitoring the child process for change in state.
813   m_monitor_thread = Host::StartMonitoringChildProcess(
814       std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4),
815       GetPID(), true);
816   if (!m_monitor_thread.IsJoinable()) {
817     error.SetErrorToGenericError();
818     error.SetErrorString("Process attach failed.");
819     return;
820   }
821 }
822
823 ProcessMonitor::~ProcessMonitor() { StopMonitor(); }
824
825 //------------------------------------------------------------------------------
826 // Thread setup and tear down.
827 void ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error) {
828   static const char *g_thread_name = "lldb.process.freebsd.operation";
829
830   if (m_operation_thread.IsJoinable())
831     return;
832
833   m_operation_thread =
834       ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
835 }
836
837 void *ProcessMonitor::LaunchOpThread(void *arg) {
838   LaunchArgs *args = static_cast<LaunchArgs *>(arg);
839
840   if (!Launch(args)) {
841     sem_post(&args->m_semaphore);
842     return NULL;
843   }
844
845   ServeOperation(args);
846   return NULL;
847 }
848
849 bool ProcessMonitor::Launch(LaunchArgs *args) {
850   ProcessMonitor *monitor = args->m_monitor;
851   ProcessFreeBSD &process = monitor->GetProcess();
852   const char **argv = args->m_argv;
853   const char **envp = args->m_envp;
854   const FileSpec &stdin_file_spec = args->m_stdin_file_spec;
855   const FileSpec &stdout_file_spec = args->m_stdout_file_spec;
856   const FileSpec &stderr_file_spec = args->m_stderr_file_spec;
857   const FileSpec &working_dir = args->m_working_dir;
858
859   lldb_utility::PseudoTerminal terminal;
860   const size_t err_len = 1024;
861   char err_str[err_len];
862   ::pid_t pid;
863
864   // Propagate the environment if one is not supplied.
865   if (envp == NULL || envp[0] == NULL)
866     envp = const_cast<const char **>(environ);
867
868   if ((pid = terminal.Fork(err_str, err_len)) == -1) {
869     args->m_error.SetErrorToGenericError();
870     args->m_error.SetErrorString("Process fork failed.");
871     goto FINISH;
872   }
873
874   // Recognized child exit status codes.
875   enum {
876     ePtraceFailed = 1,
877     eDupStdinFailed,
878     eDupStdoutFailed,
879     eDupStderrFailed,
880     eChdirFailed,
881     eExecFailed,
882     eSetGidFailed
883   };
884
885   // Child process.
886   if (pid == 0) {
887     // Trace this process.
888     if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
889       exit(ePtraceFailed);
890
891     // terminal has already dupped the tty descriptors to stdin/out/err.
892     // This closes original fd from which they were copied (and avoids
893     // leaking descriptors to the debugged process.
894     terminal.CloseSlaveFileDescriptor();
895
896     // Do not inherit setgid powers.
897     if (setgid(getgid()) != 0)
898       exit(eSetGidFailed);
899
900     // Let us have our own process group.
901     setpgid(0, 0);
902
903     // Dup file descriptors if needed.
904     //
905     // FIXME: If two or more of the paths are the same we needlessly open
906     // the same file multiple times.
907     if (stdin_file_spec)
908       if (!DupDescriptor(stdin_file_spec, STDIN_FILENO, O_RDONLY))
909         exit(eDupStdinFailed);
910
911     if (stdout_file_spec)
912       if (!DupDescriptor(stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT))
913         exit(eDupStdoutFailed);
914
915     if (stderr_file_spec)
916       if (!DupDescriptor(stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT))
917         exit(eDupStderrFailed);
918
919     // Change working directory
920     if (working_dir && 0 != ::chdir(working_dir.GetCString()))
921       exit(eChdirFailed);
922
923     // Execute.  We should never return.
924     execve(argv[0], const_cast<char *const *>(argv),
925            const_cast<char *const *>(envp));
926     exit(eExecFailed);
927   }
928
929   // Wait for the child process to to trap on its call to execve.
930   ::pid_t wpid;
931   int status;
932   if ((wpid = waitpid(pid, &status, 0)) < 0) {
933     args->m_error.SetErrorToErrno();
934     goto FINISH;
935   } else if (WIFEXITED(status)) {
936     // open, dup or execve likely failed for some reason.
937     args->m_error.SetErrorToGenericError();
938     switch (WEXITSTATUS(status)) {
939     case ePtraceFailed:
940       args->m_error.SetErrorString("Child ptrace failed.");
941       break;
942     case eDupStdinFailed:
943       args->m_error.SetErrorString("Child open stdin failed.");
944       break;
945     case eDupStdoutFailed:
946       args->m_error.SetErrorString("Child open stdout failed.");
947       break;
948     case eDupStderrFailed:
949       args->m_error.SetErrorString("Child open stderr failed.");
950       break;
951     case eChdirFailed:
952       args->m_error.SetErrorString("Child failed to set working directory.");
953       break;
954     case eExecFailed:
955       args->m_error.SetErrorString("Child exec failed.");
956       break;
957     case eSetGidFailed:
958       args->m_error.SetErrorString("Child setgid failed.");
959       break;
960     default:
961       args->m_error.SetErrorString("Child returned unknown exit status.");
962       break;
963     }
964     goto FINISH;
965   }
966   assert(WIFSTOPPED(status) && wpid == (::pid_t)pid &&
967          "Could not sync with inferior process.");
968
969 #ifdef notyet
970   // Have the child raise an event on exit.  This is used to keep the child in
971   // limbo until it is destroyed.
972   if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0) {
973     args->m_error.SetErrorToErrno();
974     goto FINISH;
975   }
976 #endif
977   // Release the master terminal descriptor and pass it off to the
978   // ProcessMonitor instance.  Similarly stash the inferior pid.
979   monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
980   monitor->m_pid = pid;
981
982   // Set the terminal fd to be in non blocking mode (it simplifies the
983   // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
984   // descriptor to read from).
985   if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
986     goto FINISH;
987
988   process.SendMessage(ProcessMessage::Attach(pid));
989
990 FINISH:
991   return args->m_error.Success();
992 }
993
994 void ProcessMonitor::StartAttachOpThread(AttachArgs *args,
995                                          lldb_private::Error &error) {
996   static const char *g_thread_name = "lldb.process.freebsd.operation";
997
998   if (m_operation_thread.IsJoinable())
999     return;
1000
1001   m_operation_thread =
1002       ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
1003 }
1004
1005 void *ProcessMonitor::AttachOpThread(void *arg) {
1006   AttachArgs *args = static_cast<AttachArgs *>(arg);
1007
1008   Attach(args);
1009
1010   ServeOperation(args);
1011   return NULL;
1012 }
1013
1014 void ProcessMonitor::Attach(AttachArgs *args) {
1015   lldb::pid_t pid = args->m_pid;
1016
1017   ProcessMonitor *monitor = args->m_monitor;
1018   ProcessFreeBSD &process = monitor->GetProcess();
1019
1020   if (pid <= 1) {
1021     args->m_error.SetErrorToGenericError();
1022     args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1023     return;
1024   }
1025
1026   // Attach to the requested process.
1027   if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0) {
1028     args->m_error.SetErrorToErrno();
1029     return;
1030   }
1031
1032   int status;
1033   if ((status = waitpid(pid, NULL, 0)) < 0) {
1034     args->m_error.SetErrorToErrno();
1035     return;
1036   }
1037
1038   process.SendMessage(ProcessMessage::Attach(pid));
1039 }
1040
1041 size_t
1042 ProcessMonitor::GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids) {
1043   lwpid_t *tids;
1044   int tdcnt;
1045
1046   thread_ids.clear();
1047
1048   tdcnt = PTRACE(PT_GETNUMLWPS, m_pid, NULL, 0);
1049   if (tdcnt <= 0)
1050     return 0;
1051   tids = (lwpid_t *)malloc(tdcnt * sizeof(*tids));
1052   if (tids == NULL)
1053     return 0;
1054   if (PTRACE(PT_GETLWPLIST, m_pid, (void *)tids, tdcnt) < 0) {
1055     free(tids);
1056     return 0;
1057   }
1058   thread_ids = std::vector<lldb::tid_t>(tids, tids + tdcnt);
1059   free(tids);
1060   return thread_ids.size();
1061 }
1062
1063 bool ProcessMonitor::MonitorCallback(ProcessMonitor *monitor, lldb::pid_t pid,
1064                                      bool exited, int signal, int status) {
1065   ProcessMessage message;
1066   ProcessFreeBSD *process = monitor->m_process;
1067   assert(process);
1068   bool stop_monitoring;
1069   struct ptrace_lwpinfo plwp;
1070   int ptrace_err;
1071
1072   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1073
1074   if (exited) {
1075     if (log)
1076       log->Printf("ProcessMonitor::%s() got exit signal, tid = %" PRIu64,
1077                   __FUNCTION__, pid);
1078     message = ProcessMessage::Exit(pid, status);
1079     process->SendMessage(message);
1080     return pid == process->GetID();
1081   }
1082
1083   if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
1084     stop_monitoring = true; // pid is gone.  Bail.
1085   else {
1086     switch (plwp.pl_siginfo.si_signo) {
1087     case SIGTRAP:
1088       message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1089       break;
1090
1091     default:
1092       message = MonitorSignal(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1093       break;
1094     }
1095
1096     process->SendMessage(message);
1097     stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1098   }
1099
1100   return stop_monitoring;
1101 }
1102
1103 ProcessMessage ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1104                                               const siginfo_t *info,
1105                                               lldb::tid_t tid) {
1106   ProcessMessage message;
1107
1108   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1109
1110   assert(monitor);
1111   assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1112
1113   switch (info->si_code) {
1114   default:
1115     assert(false && "Unexpected SIGTRAP code!");
1116     break;
1117
1118   case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */): {
1119     // The inferior process is about to exit.  Maintain the process in a
1120     // state of "limbo" until we are explicitly commanded to detach,
1121     // destroy, resume, etc.
1122     unsigned long data = 0;
1123     if (!monitor->GetEventMessage(tid, &data))
1124       data = -1;
1125     if (log)
1126       log->Printf("ProcessMonitor::%s() received exit? event, data = %lx, tid "
1127                   "= %" PRIu64,
1128                   __FUNCTION__, data, tid);
1129     message = ProcessMessage::Limbo(tid, (data >> 8));
1130     break;
1131   }
1132
1133   case 0:
1134   case TRAP_TRACE:
1135     if (log)
1136       log->Printf("ProcessMonitor::%s() received trace event, tid = %" PRIu64
1137                   "  : si_code = %d",
1138                   __FUNCTION__, tid, info->si_code);
1139     message = ProcessMessage::Trace(tid);
1140     break;
1141
1142   case SI_KERNEL:
1143   case TRAP_BRKPT:
1144     if (log)
1145       log->Printf(
1146           "ProcessMonitor::%s() received breakpoint event, tid = %" PRIu64,
1147           __FUNCTION__, tid);
1148     message = ProcessMessage::Break(tid);
1149     break;
1150   }
1151
1152   return message;
1153 }
1154
1155 ProcessMessage ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1156                                              const siginfo_t *info,
1157                                              lldb::tid_t tid) {
1158   ProcessMessage message;
1159   int signo = info->si_signo;
1160
1161   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1162
1163   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1164   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1165   // kill(2) or raise(3).  Similarly for tgkill(2) on FreeBSD.
1166   //
1167   // IOW, user generated signals never generate what we consider to be a
1168   // "crash".
1169   //
1170   // Similarly, ACK signals generated by this monitor.
1171   if (info->si_code == SI_USER) {
1172     if (log)
1173       log->Printf(
1174           "ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1175           __FUNCTION__,
1176           monitor->m_process->GetUnixSignals()->GetSignalAsCString(signo),
1177           "SI_USER", info->si_pid);
1178     if (info->si_pid == getpid())
1179       return ProcessMessage::SignalDelivered(tid, signo);
1180     else
1181       return ProcessMessage::Signal(tid, signo);
1182   }
1183
1184   if (log)
1185     log->Printf(
1186         "ProcessMonitor::%s() received signal %s", __FUNCTION__,
1187         monitor->m_process->GetUnixSignals()->GetSignalAsCString(signo));
1188
1189   switch (signo) {
1190   case SIGSEGV:
1191   case SIGILL:
1192   case SIGFPE:
1193   case SIGBUS:
1194     lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1195     const auto reason = GetCrashReason(*info);
1196     return ProcessMessage::Crash(tid, reason, signo, fault_addr);
1197   }
1198
1199   // Everything else is "normal" and does not require any special action on
1200   // our part.
1201   return ProcessMessage::Signal(tid, signo);
1202 }
1203
1204 void ProcessMonitor::ServeOperation(OperationArgs *args) {
1205   ProcessMonitor *monitor = args->m_monitor;
1206
1207   // We are finised with the arguments and are ready to go.  Sync with the
1208   // parent thread and start serving operations on the inferior.
1209   sem_post(&args->m_semaphore);
1210
1211   for (;;) {
1212     // wait for next pending operation
1213     sem_wait(&monitor->m_operation_pending);
1214
1215     monitor->m_operation->Execute(monitor);
1216
1217     // notify calling thread that operation is complete
1218     sem_post(&monitor->m_operation_done);
1219   }
1220 }
1221
1222 void ProcessMonitor::DoOperation(Operation *op) {
1223   std::lock_guard<std::mutex> guard(m_operation_mutex);
1224
1225   m_operation = op;
1226
1227   // notify operation thread that an operation is ready to be processed
1228   sem_post(&m_operation_pending);
1229
1230   // wait for operation to complete
1231   sem_wait(&m_operation_done);
1232 }
1233
1234 size_t ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1235                                   Error &error) {
1236   size_t result;
1237   ReadOperation op(vm_addr, buf, size, error, result);
1238   DoOperation(&op);
1239   return result;
1240 }
1241
1242 size_t ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf,
1243                                    size_t size, lldb_private::Error &error) {
1244   size_t result;
1245   WriteOperation op(vm_addr, buf, size, error, result);
1246   DoOperation(&op);
1247   return result;
1248 }
1249
1250 bool ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset,
1251                                        const char *reg_name, unsigned size,
1252                                        RegisterValue &value) {
1253   bool result;
1254   ReadRegOperation op(tid, offset, size, value, result);
1255   DoOperation(&op);
1256   return result;
1257 }
1258
1259 bool ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1260                                         const char *reg_name,
1261                                         const RegisterValue &value) {
1262   bool result;
1263   WriteRegOperation op(tid, offset, value, result);
1264   DoOperation(&op);
1265   return result;
1266 }
1267
1268 bool ProcessMonitor::ReadDebugRegisterValue(
1269     lldb::tid_t tid, unsigned offset, const char *reg_name, unsigned size,
1270     lldb_private::RegisterValue &value) {
1271   bool result;
1272   ReadDebugRegOperation op(tid, offset, size, value, result);
1273   DoOperation(&op);
1274   return result;
1275 }
1276
1277 bool ProcessMonitor::WriteDebugRegisterValue(
1278     lldb::tid_t tid, unsigned offset, const char *reg_name,
1279     const lldb_private::RegisterValue &value) {
1280   bool result;
1281   WriteDebugRegOperation op(tid, offset, value, result);
1282   DoOperation(&op);
1283   return result;
1284 }
1285
1286 bool ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1287   bool result;
1288   ReadGPROperation op(tid, buf, result);
1289   DoOperation(&op);
1290   return result;
1291 }
1292
1293 bool ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1294   bool result;
1295   ReadFPROperation op(tid, buf, result);
1296   DoOperation(&op);
1297   return result;
1298 }
1299
1300 bool ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf,
1301                                      size_t buf_size, unsigned int regset) {
1302   return false;
1303 }
1304
1305 bool ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1306   bool result;
1307   WriteGPROperation op(tid, buf, result);
1308   DoOperation(&op);
1309   return result;
1310 }
1311
1312 bool ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1313   bool result;
1314   WriteFPROperation op(tid, buf, result);
1315   DoOperation(&op);
1316   return result;
1317 }
1318
1319 bool ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf,
1320                                       size_t buf_size, unsigned int regset) {
1321   return false;
1322 }
1323
1324 bool ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value) {
1325   return false;
1326 }
1327
1328 bool ProcessMonitor::Resume(lldb::tid_t unused, uint32_t signo) {
1329   bool result;
1330   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1331
1332   if (log) {
1333     const char *signame =
1334         m_process->GetUnixSignals()->GetSignalAsCString(signo);
1335     if (signame == nullptr)
1336       signame = "<none>";
1337     log->Printf("ProcessMonitor::%s() resuming pid %" PRIu64 " with signal %s",
1338                 __FUNCTION__, GetPID(), signame);
1339   }
1340   ResumeOperation op(signo, result);
1341   DoOperation(&op);
1342   if (log)
1343     log->Printf("ProcessMonitor::%s() resuming result = %s", __FUNCTION__,
1344                 result ? "true" : "false");
1345   return result;
1346 }
1347
1348 bool ProcessMonitor::SingleStep(lldb::tid_t unused, uint32_t signo) {
1349   bool result;
1350   SingleStepOperation op(signo, result);
1351   DoOperation(&op);
1352   return result;
1353 }
1354
1355 bool ProcessMonitor::Kill() {
1356   bool result;
1357   KillOperation op(result);
1358   DoOperation(&op);
1359   return result;
1360 }
1361
1362 bool ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo,
1363                                 int &ptrace_err) {
1364   bool result;
1365   LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
1366   DoOperation(&op);
1367   return result;
1368 }
1369
1370 bool ProcessMonitor::ThreadSuspend(lldb::tid_t tid, bool suspend) {
1371   bool result;
1372   ThreadSuspendOperation op(tid, suspend, result);
1373   DoOperation(&op);
1374   return result;
1375 }
1376
1377 bool ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message) {
1378   bool result;
1379   EventMessageOperation op(tid, message, result);
1380   DoOperation(&op);
1381   return result;
1382 }
1383
1384 lldb_private::Error ProcessMonitor::Detach(lldb::tid_t tid) {
1385   lldb_private::Error error;
1386   if (tid != LLDB_INVALID_THREAD_ID) {
1387     DetachOperation op(error);
1388     DoOperation(&op);
1389   }
1390   return error;
1391 }
1392
1393 bool ProcessMonitor::DupDescriptor(const FileSpec &file_spec, int fd,
1394                                    int flags) {
1395   int target_fd = open(file_spec.GetCString(), flags, 0666);
1396
1397   if (target_fd == -1)
1398     return false;
1399
1400   if (dup2(target_fd, fd) == -1)
1401     return false;
1402
1403   return (close(target_fd) == -1) ? false : true;
1404 }
1405
1406 void ProcessMonitor::StopMonitoringChildProcess() {
1407   if (m_monitor_thread.IsJoinable()) {
1408     m_monitor_thread.Cancel();
1409     m_monitor_thread.Join(nullptr);
1410     m_monitor_thread.Reset();
1411   }
1412 }
1413
1414 void ProcessMonitor::StopMonitor() {
1415   StopMonitoringChildProcess();
1416   StopOpThread();
1417   sem_destroy(&m_operation_pending);
1418   sem_destroy(&m_operation_done);
1419   if (m_terminal_fd >= 0) {
1420     close(m_terminal_fd);
1421     m_terminal_fd = -1;
1422   }
1423 }
1424
1425 // FIXME: On Linux, when a new thread is created, we receive to notifications,
1426 // (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1427 // child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1428 // the new child thread indicating that it has is stopped because we attached.
1429 // We have no guarantee of the order in which these arrive, but we need both
1430 // before we are ready to proceed.  We currently keep a list of threads which
1431 // have sent the initial SIGSTOP|SI_USER event.  Then when we receive the
1432 // SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1433 // we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1434 //
1435 // Right now, the above logic is in ProcessPOSIX, so we need a definition of
1436 // this function in the FreeBSD ProcessMonitor implementation even if it isn't
1437 // logically needed.
1438 //
1439 // We really should figure out what actually happens on FreeBSD and move the
1440 // Linux-specific logic out of ProcessPOSIX as needed.
1441
1442 bool ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid) { return true; }
1443
1444 void ProcessMonitor::StopOpThread() {
1445   if (!m_operation_thread.IsJoinable())
1446     return;
1447
1448   m_operation_thread.Cancel();
1449   m_operation_thread.Join(nullptr);
1450   m_operation_thread.Reset();
1451 }