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