MachProcess.h revision dc8ff30b6dbe28c851e99712e20c1358eca4709d
1//===-- MachProcess.h -------------------------------------------*- 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//  Created by Greg Clayton on 6/15/07.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef __MachProcess_h__
15#define __MachProcess_h__
16
17#include "DNBDefs.h"
18#include "DNBBreakpoint.h"
19#include "DNBError.h"
20#include "DNBThreadResumeActions.h"
21//#include "MachDYLD.h"
22#include "MachException.h"
23#include "MachVMMemory.h"
24#include "MachTask.h"
25#include "MachThreadList.h"
26#include "PThreadCondition.h"
27#include "PThreadEvent.h"
28#include "PThreadMutex.h"
29
30#include <mach/mach.h>
31#include <sys/signal.h>
32#include <pthread.h>
33#include <vector>
34
35class DNBThreadResumeActions;
36
37class MachProcess
38{
39public:
40    //----------------------------------------------------------------------
41    // Constructors and Destructors
42    //----------------------------------------------------------------------
43    MachProcess ();
44    ~MachProcess ();
45
46    //----------------------------------------------------------------------
47    // Child process control
48    //----------------------------------------------------------------------
49    pid_t                   AttachForDebug (pid_t pid, char *err_str, size_t err_len);
50    pid_t                   LaunchForDebug (const char *path,
51                                            char const *argv[],
52                                            char const *envp[],
53                                            const char *working_directory,
54                                            const char *stdin_path,
55                                            const char *stdout_path,
56                                            const char *stderr_path,
57                                            bool no_stdio,
58                                            nub_launch_flavor_t launch_flavor,
59                                            int disable_aslr,
60                                            DNBError &err);
61
62    static uint32_t         GetCPUTypeForLocalProcess (pid_t pid);
63    static pid_t            ForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], MachProcess* process, DNBError &err);
64    static pid_t            PosixSpawnChildForPTraceDebugging (const char *path,
65                                                               cpu_type_t cpu_type,
66                                                               char const *argv[],
67                                                               char const *envp[],
68                                                               const char *working_directory,
69                                                               const char *stdin_path,
70                                                               const char *stdout_path,
71                                                               const char *stderr_path,
72                                                               bool no_stdio,
73                                                               MachProcess* process,
74                                                               int disable_aslr,
75                                                               DNBError& err);
76    nub_addr_t              GetDYLDAllImageInfosAddress ();
77    static const void *     PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str);
78    static void             CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str);
79    static nub_process_t    CheckForProcess (const void *attach_token);
80#if defined (__arm__)
81    pid_t                   SBLaunchForDebug (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, DNBError &launch_err);
82    static pid_t            SBForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err);
83#endif
84    nub_addr_t              LookupSymbol (const char *name, const char *shlib);
85    void                    SetNameToAddressCallback (DNBCallbackNameToAddress callback, void *baton)
86                            {
87                                m_name_to_addr_callback = callback;
88                                m_name_to_addr_baton    = baton;
89                            }
90    void                    SetSharedLibraryInfoCallback (DNBCallbackCopyExecutableImageInfos callback, void *baton)
91                            {
92                                m_image_infos_callback    = callback;
93                                m_image_infos_baton        = baton;
94                            }
95
96    bool                    Resume (const DNBThreadResumeActions& thread_actions);
97    bool                    Signal  (int signal, const struct timespec *timeout_abstime = NULL);
98    bool                    Kill (const struct timespec *timeout_abstime = NULL);
99    bool                    Detach ();
100    nub_size_t              ReadMemory (nub_addr_t addr, nub_size_t size, void *buf);
101    nub_size_t              WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf);
102    bool                    IsAddressExecutable(nub_addr_t address);
103
104    //----------------------------------------------------------------------
105    // Path and arg accessors
106    //----------------------------------------------------------------------
107    const char *            Path () const { return m_path.c_str(); }
108    size_t                  ArgumentCount () const { return m_args.size(); }
109    const char *            ArgumentAtIndex (size_t arg_idx) const
110                            {
111                                if (arg_idx < m_args.size())
112                                    return m_args[arg_idx].c_str();
113                                return NULL;
114                            }
115
116    //----------------------------------------------------------------------
117    // Breakpoint functions
118    //----------------------------------------------------------------------
119    nub_break_t             CreateBreakpoint (nub_addr_t addr, nub_size_t length, bool hardware, thread_t thread);
120    bool                    DisableBreakpoint (nub_break_t breakID, bool remove);
121    nub_size_t              DisableAllBreakpoints (bool remove);
122    bool                    EnableBreakpoint (nub_break_t breakID);
123    void                    DumpBreakpoint(nub_break_t breakID) const;
124    DNBBreakpointList&      Breakpoints() { return m_breakpoints; }
125    const DNBBreakpointList& Breakpoints() const { return m_breakpoints; }
126
127    //----------------------------------------------------------------------
128    // Watchpoint functions
129    //----------------------------------------------------------------------
130    nub_watch_t             CreateWatchpoint (nub_addr_t addr, nub_size_t length, uint32_t watch_type, bool hardware, thread_t thread);
131    bool                    DisableWatchpoint (nub_watch_t watchID, bool remove);
132    nub_size_t              DisableAllWatchpoints (bool remove);
133    bool                    EnableWatchpoint (nub_watch_t watchID);
134    void                    DumpWatchpoint(nub_watch_t watchID) const;
135    DNBBreakpointList&      Watchpoints() { return m_watchpoints; }
136    const DNBBreakpointList& Watchpoints() const { return m_watchpoints; }
137
138    //----------------------------------------------------------------------
139    // Exception thread functions
140    //----------------------------------------------------------------------
141    bool                    StartSTDIOThread ();
142    static void *           STDIOThread (void *arg);
143    void                    ExceptionMessageReceived (const MachException::Message& exceptionMessage);
144    void                    ExceptionMessageBundleComplete ();
145    void                    SharedLibrariesUpdated ();
146    nub_size_t              CopyImageInfos (struct DNBExecutableImageInfo **image_infos, bool only_changed);
147
148    //----------------------------------------------------------------------
149    // Accessors
150    //----------------------------------------------------------------------
151    pid_t                   ProcessID () const { return m_pid; }
152    bool                    ProcessIDIsValid () const { return m_pid > 0; }
153    pid_t                   SetProcessID (pid_t pid);
154    MachTask&               Task() { return m_task; }
155    const MachTask&         Task() const { return m_task; }
156
157    PThreadEvent&           Events() { return m_events; }
158    const DNBRegisterSetInfo *
159                            GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const;
160    bool                    GetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *reg_value) const;
161    bool                    SetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value) const;
162    const char *            ThreadGetName (nub_thread_t tid);
163    nub_state_t             ThreadGetState (nub_thread_t tid);
164    nub_size_t              GetNumThreads () const;
165    nub_thread_t            GetThreadAtIndex (nub_size_t thread_idx) const;
166    nub_thread_t            GetCurrentThread ();
167    nub_thread_t            SetCurrentThread (nub_thread_t tid);
168    MachThreadList &        GetThreadList() { return m_thread_list; }
169    bool                    GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const;
170    void                    DumpThreadStoppedReason(nub_thread_t tid) const;
171    const char *            GetThreadInfo (nub_thread_t tid) const;
172
173    uint32_t                GetCPUType ();
174    nub_state_t             GetState ();
175    void                    SetState (nub_state_t state);
176    bool                    IsRunning (nub_state_t state)
177                            {
178                                return    state == eStateRunning || IsStepping(state);
179                            }
180    bool                    IsStepping (nub_state_t state)
181                            {
182                                return    state == eStateStepping;
183                            }
184    bool                    CanResume (nub_state_t state)
185                            {
186                                return state == eStateStopped;
187                            }
188
189    bool                    GetExitStatus(int* status)
190                            {
191                                if (GetState() == eStateExited)
192                                {
193                                    if (status)
194                                        *status = m_exit_status;
195                                    return true;
196                                }
197                                return false;
198                            }
199    void                    SetExitStatus(int status)
200                            {
201                                m_exit_status = status;
202                                SetState(eStateExited);
203                            }
204
205    uint32_t                StopCount() const { return m_stop_count; }
206    void                    SetChildFileDescriptors (int stdin_fileno, int stdout_fileno, int stderr_fileno)
207                            {
208                                m_child_stdin   = stdin_fileno;
209                                m_child_stdout  = stdout_fileno;
210                                m_child_stderr  = stderr_fileno;
211                            }
212
213    int                     GetStdinFileDescriptor () const { return m_child_stdin; }
214    int                     GetStdoutFileDescriptor () const { return m_child_stdout; }
215    int                     GetStderrFileDescriptor () const { return m_child_stderr; }
216    void                    AppendSTDOUT (char* s, size_t len);
217    size_t                  GetAvailableSTDOUT (char *buf, size_t buf_size);
218    size_t                  GetAvailableSTDERR (char *buf, size_t buf_size);
219    void                    CloseChildFileDescriptors ()
220                            {
221                                if (m_child_stdin >= 0)
222                                {
223                                    ::close (m_child_stdin);
224                                    m_child_stdin = -1;
225                                }
226                                if (m_child_stdout >= 0)
227                                {
228                                    ::close (m_child_stdout);
229                                    m_child_stdout = -1;
230                                }
231                                if (m_child_stderr >= 0)
232                                {
233                                    ::close (m_child_stderr);
234                                    m_child_stderr = -1;
235                                }
236                            }
237
238    bool                    ProcessUsingSpringBoard() const { return (m_flags & eMachProcessFlagsUsingSBS) != 0; }
239private:
240    enum
241    {
242        eMachProcessFlagsNone = 0,
243        eMachProcessFlagsAttached = (1 << 0),
244        eMachProcessFlagsUsingSBS = (1 << 1)
245    };
246    void                    Clear ();
247    void                    ReplyToAllExceptions ();
248    void                    PrivateResume ();
249    nub_size_t              RemoveTrapsFromBuffer (nub_addr_t addr, nub_size_t size, uint8_t *buf) const;
250
251    uint32_t                Flags () const { return m_flags; }
252    nub_state_t             DoSIGSTOP (bool clear_bps_and_wps, uint32_t *thread_idx_ptr = NULL);
253
254    pid_t                       m_pid;                      // Process ID of child process
255    cpu_type_t                  m_cpu_type;                 // The CPU type of this process
256    int                         m_child_stdin;
257    int                         m_child_stdout;
258    int                         m_child_stderr;
259    std::string                 m_path;                     // A path to the executable if we have one
260    std::vector<std::string>    m_args;                     // The arguments with which the process was lauched
261    int                         m_exit_status;              // The exit status for the process
262    MachTask                    m_task;                     // The mach task for this process
263    uint32_t                    m_flags;                    // Process specific flags (see eMachProcessFlags enums)
264    uint32_t                    m_stop_count;               // A count of many times have we stopped
265    pthread_t                   m_stdio_thread;             // Thread ID for the thread that watches for child process stdio
266    PThreadMutex                m_stdio_mutex;              // Multithreaded protection for stdio
267    std::string                 m_stdout_data;
268    DNBThreadResumeActions      m_thread_actions;           // The thread actions for the current MachProcess::Resume() call
269    MachException::Message::collection
270                                m_exception_messages;       // A collection of exception messages caught when listening to the exception port
271    PThreadMutex                m_exception_messages_mutex; // Multithreaded protection for m_exception_messages
272
273    MachThreadList              m_thread_list;               // A list of threads that is maintained/updated after each stop
274    nub_state_t                 m_state;                    // The state of our process
275    PThreadMutex                m_state_mutex;              // Multithreaded protection for m_state
276    PThreadEvent                m_events;                   // Process related events in the child processes lifetime can be waited upon
277    DNBBreakpointList           m_breakpoints;              // Breakpoint list for this process
278    DNBBreakpointList           m_watchpoints;              // Watchpoint list for this process
279    DNBCallbackNameToAddress    m_name_to_addr_callback;
280    void *                      m_name_to_addr_baton;
281    DNBCallbackCopyExecutableImageInfos
282                                m_image_infos_callback;
283    void *                      m_image_infos_baton;
284};
285
286
287#endif // __MachProcess_h__
288