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