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