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