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