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 "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 #include "Genealogy.h"
29 #include "ThreadInfo.h"
30 #include "JSONGenerator.h"
31 
32 #include <mach/mach.h>
33 #include <sys/signal.h>
34 #include <pthread.h>
35 #include <vector>
36 
37 class DNBThreadResumeActions;
38 
39 class MachProcess
40 {
41 public:
42     //----------------------------------------------------------------------
43     // Constructors and Destructors
44     //----------------------------------------------------------------------
45     MachProcess ();
46     ~MachProcess ();
47 
48     //----------------------------------------------------------------------
49     // Child process control
50     //----------------------------------------------------------------------
51     pid_t                   AttachForDebug (pid_t pid, char *err_str, size_t err_len);
52     pid_t                   LaunchForDebug (const char *path,
53                                             char const *argv[],
54                                             char const *envp[],
55                                             const char *working_directory,
56                                             const char *stdin_path,
57                                             const char *stdout_path,
58                                             const char *stderr_path,
59                                             bool no_stdio,
60                                             nub_launch_flavor_t launch_flavor,
61                                             int disable_aslr,
62                                             const char *event_data,
63                                             DNBError &err);
64 
65     static uint32_t         GetCPUTypeForLocalProcess (pid_t pid);
66     static pid_t            ForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], MachProcess* process, DNBError &err);
67     static pid_t            PosixSpawnChildForPTraceDebugging (const char *path,
68                                                                cpu_type_t cpu_type,
69                                                                char const *argv[],
70                                                                char const *envp[],
71                                                                const char *working_directory,
72                                                                const char *stdin_path,
73                                                                const char *stdout_path,
74                                                                const char *stderr_path,
75                                                                bool no_stdio,
76                                                                MachProcess* process,
77                                                                int disable_aslr,
78                                                                DNBError& err);
79     nub_addr_t              GetDYLDAllImageInfosAddress ();
80     static const void *     PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str);
81     static void             CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str);
82     static nub_process_t    CheckForProcess (const void *attach_token);
83 #ifdef WITH_BKS
84     pid_t                   BKSLaunchForDebug (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const char *event_data, DNBError &launch_err);
85     pid_t                   BKSForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const char *event_data, DNBError &launch_err);
86     bool                    BKSSendEvent (const char *event, DNBError &error);
87     static void             BKSCleanupAfterAttach (const void *attach_token, DNBError &err_str);
88 #endif
89 #ifdef WITH_SPRINGBOARD
90     pid_t                   SBLaunchForDebug (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, DNBError &launch_err);
91     static pid_t            SBForkChildForPTraceDebugging (const char *path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err);
92 #endif
93     nub_addr_t              LookupSymbol (const char *name, const char *shlib);
94     void                    SetNameToAddressCallback (DNBCallbackNameToAddress callback, void *baton)
95                             {
96                                 m_name_to_addr_callback = callback;
97                                 m_name_to_addr_baton    = baton;
98                             }
99     void                    SetSharedLibraryInfoCallback (DNBCallbackCopyExecutableImageInfos callback, void *baton)
100                             {
101                                 m_image_infos_callback    = callback;
102                                 m_image_infos_baton        = baton;
103                             }
104 
105     bool                    Resume (const DNBThreadResumeActions& thread_actions);
106     bool                    Signal  (int signal, const struct timespec *timeout_abstime = NULL);
107     bool                    Interrupt();
108     bool                    SendEvent (const char *event, DNBError &send_err);
109     bool                    Kill (const struct timespec *timeout_abstime = NULL);
110     bool                    Detach ();
111     nub_size_t              ReadMemory (nub_addr_t addr, nub_size_t size, void *buf);
112     nub_size_t              WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf);
113 
114     //----------------------------------------------------------------------
115     // Path and arg accessors
116     //----------------------------------------------------------------------
117     const char *            Path () const { return m_path.c_str(); }
118     size_t                  ArgumentCount () const { return m_args.size(); }
119     const char *            ArgumentAtIndex (size_t arg_idx) const
120                             {
121                                 if (arg_idx < m_args.size())
122                                     return m_args[arg_idx].c_str();
123                                 return NULL;
124                             }
125 
126     //----------------------------------------------------------------------
127     // Breakpoint functions
128     //----------------------------------------------------------------------
129     DNBBreakpoint *         CreateBreakpoint (nub_addr_t addr, nub_size_t length, bool hardware);
130     bool                    DisableBreakpoint (nub_addr_t addr, bool remove);
131     void                    DisableAllBreakpoints (bool remove);
132     bool                    EnableBreakpoint (nub_addr_t addr);
133     DNBBreakpointList&      Breakpoints() { return m_breakpoints; }
134     const DNBBreakpointList& Breakpoints() const { return m_breakpoints; }
135 
136     //----------------------------------------------------------------------
137     // Watchpoint functions
138     //----------------------------------------------------------------------
139     DNBBreakpoint *         CreateWatchpoint (nub_addr_t addr, nub_size_t length, uint32_t watch_type, bool hardware);
140     bool                    DisableWatchpoint (nub_addr_t addr, bool remove);
141     void                    DisableAllWatchpoints (bool remove);
142     bool                    EnableWatchpoint (nub_addr_t addr);
143     uint32_t                GetNumSupportedHardwareWatchpoints () const;
144     DNBBreakpointList&      Watchpoints() { return m_watchpoints; }
145     const DNBBreakpointList& Watchpoints() const { return m_watchpoints; }
146 
147     //----------------------------------------------------------------------
148     // Exception thread functions
149     //----------------------------------------------------------------------
150     bool                    StartSTDIOThread ();
151     static void *           STDIOThread (void *arg);
152     void                    ExceptionMessageReceived (const MachException::Message& exceptionMessage);
153     task_t                  ExceptionMessageBundleComplete ();
154     void                    SharedLibrariesUpdated ();
155     nub_size_t              CopyImageInfos (struct DNBExecutableImageInfo **image_infos, bool only_changed);
156 
157     //----------------------------------------------------------------------
158     // Profile functions
159     //----------------------------------------------------------------------
160     void                    SetEnableAsyncProfiling (bool enable, uint64_t internal_usec, DNBProfileDataScanType scan_type);
161     bool                    IsProfilingEnabled () { return m_profile_enabled; }
162     useconds_t                ProfileInterval () { return m_profile_interval_usec; }
163     bool                    StartProfileThread ();
164     static void *           ProfileThread (void *arg);
165     void                    SignalAsyncProfileData (const char *info);
166     size_t                  GetAsyncProfileData (char *buf, size_t buf_size);
167 
168     //----------------------------------------------------------------------
169     // Accessors
170     //----------------------------------------------------------------------
171     pid_t                   ProcessID () const { return m_pid; }
172     bool                    ProcessIDIsValid () const { return m_pid > 0; }
173     pid_t                   SetProcessID (pid_t pid);
174     MachTask&               Task() { return m_task; }
175     const MachTask&         Task() const { return m_task; }
176 
177     PThreadEvent&           Events() { return m_events; }
178     const DNBRegisterSetInfo *
179                             GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const;
180     bool                    GetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *reg_value) const;
181     bool                    SetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value) const;
182     nub_bool_t              SyncThreadState (nub_thread_t tid);
183     const char *            ThreadGetName (nub_thread_t tid);
184     nub_state_t             ThreadGetState (nub_thread_t tid);
185     ThreadInfo::QoS         GetRequestedQoS (nub_thread_t tid, nub_addr_t tsd, uint64_t dti_qos_class_index);
186     nub_addr_t              GetPThreadT (nub_thread_t tid);
187     nub_addr_t              GetDispatchQueueT (nub_thread_t tid);
188     nub_addr_t              GetTSDAddressForThread (nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset, uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size);
189     JSONGenerator::ObjectSP GetLoadedDynamicLibrariesInfos (nub_process_t pid, nub_addr_t image_list_address, nub_addr_t image_count);
190 
191     nub_size_t              GetNumThreads () const;
192     nub_thread_t            GetThreadAtIndex (nub_size_t thread_idx) const;
193     nub_thread_t            GetCurrentThread ();
194     nub_thread_t            GetCurrentThreadMachPort ();
195     nub_thread_t            SetCurrentThread (nub_thread_t tid);
196     MachThreadList &        GetThreadList() { return m_thread_list; }
197     bool                    GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info);
198     void                    DumpThreadStoppedReason(nub_thread_t tid) const;
199     const char *            GetThreadInfo (nub_thread_t tid) const;
200 
201     nub_thread_t            GetThreadIDForMachPortNumber (thread_t mach_port_number) const;
202 
203     uint32_t                GetCPUType ();
204     nub_state_t             GetState ();
205     void                    SetState (nub_state_t state);
206     bool                    IsRunning (nub_state_t state)
207                             {
208                                 return    state == eStateRunning || IsStepping(state);
209                             }
210     bool                    IsStepping (nub_state_t state)
211                             {
212                                 return    state == eStateStepping;
213                             }
214     bool                    CanResume (nub_state_t state)
215                             {
216                                 return state == eStateStopped;
217                             }
218 
219     bool                    GetExitStatus(int* status)
220                             {
221                                 if (GetState() == eStateExited)
222                                 {
223                                     if (status)
224                                         *status = m_exit_status;
225                                     return true;
226                                 }
227                                 return false;
228                             }
229     void                    SetExitStatus(int status)
230                             {
231                                 m_exit_status = status;
232                                 SetState(eStateExited);
233                             }
234     const char *            GetExitInfo ()
235                             {
236                                 return m_exit_info.c_str();
237                             }
238 
239     void                    SetExitInfo (const char *info);
240 
241     uint32_t                StopCount() const { return m_stop_count; }
242     void                    SetChildFileDescriptors (int stdin_fileno, int stdout_fileno, int stderr_fileno)
243                             {
244                                 m_child_stdin   = stdin_fileno;
245                                 m_child_stdout  = stdout_fileno;
246                                 m_child_stderr  = stderr_fileno;
247                             }
248 
249     int                     GetStdinFileDescriptor () const { return m_child_stdin; }
250     int                     GetStdoutFileDescriptor () const { return m_child_stdout; }
251     int                     GetStderrFileDescriptor () const { return m_child_stderr; }
252     void                    AppendSTDOUT (char* s, size_t len);
253     size_t                  GetAvailableSTDOUT (char *buf, size_t buf_size);
254     size_t                  GetAvailableSTDERR (char *buf, size_t buf_size);
255     void                    CloseChildFileDescriptors ()
256                             {
257                                 if (m_child_stdin >= 0)
258                                 {
259                                     ::close (m_child_stdin);
260                                     m_child_stdin = -1;
261                                 }
262                                 if (m_child_stdout >= 0)
263                                 {
264                                     ::close (m_child_stdout);
265                                     m_child_stdout = -1;
266                                 }
267                                 if (m_child_stderr >= 0)
268                                 {
269                                     ::close (m_child_stderr);
270                                     m_child_stderr = -1;
271                                 }
272                             }
273 
274     bool                    ProcessUsingSpringBoard() const { return (m_flags & eMachProcessFlagsUsingSBS) != 0; }
275     bool                    ProcessUsingBackBoard() const { return (m_flags & eMachProcessFlagsUsingBKS) != 0; }
276 
277     Genealogy::ThreadActivitySP GetGenealogyInfoForThread (nub_thread_t tid, bool &timed_out);
278 
279     Genealogy::ProcessExecutableInfoSP GetGenealogyImageInfo (size_t idx);
280 
281     DNBProfileDataScanType  GetProfileScanType () { return m_profile_scan_type; }
282 
283 private:
284     enum
285     {
286         eMachProcessFlagsNone = 0,
287         eMachProcessFlagsAttached = (1 << 0),
288         eMachProcessFlagsUsingSBS = (1 << 1),
289         eMachProcessFlagsUsingBKS = (1 << 2)
290     };
291     void                    Clear (bool detaching = false);
292     void                    ReplyToAllExceptions ();
293     void                    PrivateResume ();
294 
295     uint32_t                Flags () const { return m_flags; }
296     nub_state_t             DoSIGSTOP (bool clear_bps_and_wps, bool allow_running, uint32_t *thread_idx_ptr);
297 
298     pid_t                       m_pid;                      // Process ID of child process
299     cpu_type_t                  m_cpu_type;                 // The CPU type of this process
300     int                         m_child_stdin;
301     int                         m_child_stdout;
302     int                         m_child_stderr;
303     std::string                 m_path;                     // A path to the executable if we have one
304     std::vector<std::string>    m_args;                     // The arguments with which the process was lauched
305     int                         m_exit_status;              // The exit status for the process
306     std::string                 m_exit_info;                // Any extra info that we may have about the exit
307     MachTask                    m_task;                     // The mach task for this process
308     uint32_t                    m_flags;                    // Process specific flags (see eMachProcessFlags enums)
309     uint32_t                    m_stop_count;               // A count of many times have we stopped
310     pthread_t                   m_stdio_thread;             // Thread ID for the thread that watches for child process stdio
311     PThreadMutex                m_stdio_mutex;              // Multithreaded protection for stdio
312     std::string                 m_stdout_data;
313 
314     bool                        m_profile_enabled;          // A flag to indicate if profiling is enabled
315     useconds_t                  m_profile_interval_usec;    // If enable, the profiling interval in microseconds
316     DNBProfileDataScanType      m_profile_scan_type;        // Indicates what needs to be profiled
317     pthread_t                   m_profile_thread;           // Thread ID for the thread that profiles the inferior
318     PThreadMutex                m_profile_data_mutex;       // Multithreaded protection for profile info data
319     std::vector<std::string>    m_profile_data;             // Profile data, must be protected by m_profile_data_mutex
320 
321     DNBThreadResumeActions      m_thread_actions;           // The thread actions for the current MachProcess::Resume() call
322     MachException::Message::collection
323                                 m_exception_messages;       // A collection of exception messages caught when listening to the exception port
324     PThreadMutex                m_exception_messages_mutex; // Multithreaded protection for m_exception_messages
325 
326     MachThreadList              m_thread_list;               // A list of threads that is maintained/updated after each stop
327     Genealogy                   m_activities;               // A list of activities that is updated after every stop lazily
328     nub_state_t                 m_state;                    // The state of our process
329     PThreadMutex                m_state_mutex;              // Multithreaded protection for m_state
330     PThreadEvent                m_events;                   // Process related events in the child processes lifetime can be waited upon
331     PThreadEvent                m_private_events;           // Used to coordinate running and stopping the process without affecting m_events
332     DNBBreakpointList           m_breakpoints;              // Breakpoint list for this process
333     DNBBreakpointList           m_watchpoints;              // Watchpoint list for this process
334     DNBCallbackNameToAddress    m_name_to_addr_callback;
335     void *                      m_name_to_addr_baton;
336     DNBCallbackCopyExecutableImageInfos
337                                 m_image_infos_callback;
338     void *                      m_image_infos_baton;
339     std::string                 m_bundle_id;                 // If we are a SB or BKS process, this will be our bundle ID.
340     int                         m_sent_interrupt_signo;      // When we call MachProcess::Interrupt(), we want to send a single signal
341                                                              // to the inferior and only send the signal if we aren't already stopped.
342                                                              // If we end up sending a signal to stop the process we store it until we
343                                                              // receive an exception with this signal. This helps us to verify we got
344                                                              // the signal that interrupted the process. We might stop due to another
345                                                              // reason after an interrupt signal is sent, so this helps us ensure that
346                                                              // we don't report a spurious stop on the next resume.
347     int                         m_auto_resume_signo;         // If we resume the process and still haven't received our interrupt signal
348                                                              // acknownledgement, we will shortly after the next resume. We store the
349                                                              // interrupt signal in this variable so when we get the interrupt signal
350                                                              // as the sole reason for the process being stopped, we can auto resume
351                                                              // the process.
352     bool                        m_did_exec;
353 };
354 
355 
356 #endif // __MachProcess_h__
357