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