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 
250   bool GetMachOInformationFromMemory(nub_addr_t mach_o_header_addr,
251                                      int wordsize,
252                                      struct mach_o_information &inf);
253   JSONGenerator::ObjectSP FormatDynamicLibrariesIntoJSON(
254       const std::vector<struct binary_image_information> &image_infos);
255   void GetAllLoadedBinariesViaDYLDSPI(
256       std::vector<struct binary_image_information> &image_infos);
257   JSONGenerator::ObjectSP GetLoadedDynamicLibrariesInfos(
258       nub_process_t pid, nub_addr_t image_list_address, nub_addr_t image_count);
259   JSONGenerator::ObjectSP
260   GetLibrariesInfoForAddresses(nub_process_t pid,
261                                std::vector<uint64_t> &macho_addresses);
262   JSONGenerator::ObjectSP GetAllLoadedLibrariesInfos(nub_process_t pid);
263   JSONGenerator::ObjectSP GetSharedCacheInfo(nub_process_t pid);
264 
265   nub_size_t GetNumThreads() const;
266   nub_thread_t GetThreadAtIndex(nub_size_t thread_idx) const;
267   nub_thread_t GetCurrentThread();
268   nub_thread_t GetCurrentThreadMachPort();
269   nub_thread_t SetCurrentThread(nub_thread_t tid);
270   MachThreadList &GetThreadList() { return m_thread_list; }
271   bool GetThreadStoppedReason(nub_thread_t tid,
272                               struct DNBThreadStopInfo *stop_info);
273   void DumpThreadStoppedReason(nub_thread_t tid) const;
274   const char *GetThreadInfo(nub_thread_t tid) const;
275 
276   nub_thread_t GetThreadIDForMachPortNumber(thread_t mach_port_number) const;
277 
278   uint32_t GetCPUType();
279   nub_state_t GetState();
280   void SetState(nub_state_t state);
281   bool IsRunning(nub_state_t state) {
282     return state == eStateRunning || IsStepping(state);
283   }
284   bool IsStepping(nub_state_t state) { return state == eStateStepping; }
285   bool CanResume(nub_state_t state) { return state == eStateStopped; }
286 
287   bool GetExitStatus(int *status) {
288     if (GetState() == eStateExited) {
289       if (status)
290         *status = m_exit_status;
291       return true;
292     }
293     return false;
294   }
295   void SetExitStatus(int status) {
296     m_exit_status = status;
297     SetState(eStateExited);
298   }
299   const char *GetExitInfo() { return m_exit_info.c_str(); }
300 
301   void SetExitInfo(const char *info);
302 
303   uint32_t StopCount() const { return m_stop_count; }
304   void SetChildFileDescriptors(int stdin_fileno, int stdout_fileno,
305                                int stderr_fileno) {
306     m_child_stdin = stdin_fileno;
307     m_child_stdout = stdout_fileno;
308     m_child_stderr = stderr_fileno;
309   }
310 
311   int GetStdinFileDescriptor() const { return m_child_stdin; }
312   int GetStdoutFileDescriptor() const { return m_child_stdout; }
313   int GetStderrFileDescriptor() const { return m_child_stderr; }
314   void AppendSTDOUT(char *s, size_t len);
315   size_t GetAvailableSTDOUT(char *buf, size_t buf_size);
316   size_t GetAvailableSTDERR(char *buf, size_t buf_size);
317   void CloseChildFileDescriptors() {
318     if (m_child_stdin >= 0) {
319       ::close(m_child_stdin);
320       m_child_stdin = -1;
321     }
322     if (m_child_stdout >= 0) {
323       ::close(m_child_stdout);
324       m_child_stdout = -1;
325     }
326     if (m_child_stderr >= 0) {
327       ::close(m_child_stderr);
328       m_child_stderr = -1;
329     }
330   }
331 
332   bool ProcessUsingSpringBoard() const {
333     return (m_flags & eMachProcessFlagsUsingSBS) != 0;
334   }
335   bool ProcessUsingBackBoard() const {
336     return (m_flags & eMachProcessFlagsUsingBKS) != 0;
337   }
338 
339   Genealogy::ThreadActivitySP GetGenealogyInfoForThread(nub_thread_t tid,
340                                                         bool &timed_out);
341 
342   Genealogy::ProcessExecutableInfoSP GetGenealogyImageInfo(size_t idx);
343 
344   DNBProfileDataScanType GetProfileScanType() { return m_profile_scan_type; }
345 
346 private:
347   enum {
348     eMachProcessFlagsNone = 0,
349     eMachProcessFlagsAttached = (1 << 0),
350     eMachProcessFlagsUsingSBS = (1 << 1),
351     eMachProcessFlagsUsingBKS = (1 << 2),
352     eMachProcessFlagsUsingFBS = (1 << 3)
353   };
354   void Clear(bool detaching = false);
355   void ReplyToAllExceptions();
356   void PrivateResume();
357 
358   uint32_t Flags() const { return m_flags; }
359   nub_state_t DoSIGSTOP(bool clear_bps_and_wps, bool allow_running,
360                         uint32_t *thread_idx_ptr);
361 
362   pid_t m_pid;           // Process ID of child process
363   cpu_type_t m_cpu_type; // The CPU type of this process
364   int m_child_stdin;
365   int m_child_stdout;
366   int m_child_stderr;
367   std::string m_path; // A path to the executable if we have one
368   std::vector<std::string>
369       m_args;              // The arguments with which the process was lauched
370   int m_exit_status;       // The exit status for the process
371   std::string m_exit_info; // Any extra info that we may have about the exit
372   MachTask m_task;         // The mach task for this process
373   uint32_t m_flags;      // Process specific flags (see eMachProcessFlags enums)
374   uint32_t m_stop_count; // A count of many times have we stopped
375   pthread_t m_stdio_thread;   // Thread ID for the thread that watches for child
376                               // process stdio
377   PThreadMutex m_stdio_mutex; // Multithreaded protection for stdio
378   std::string m_stdout_data;
379 
380   bool m_profile_enabled; // A flag to indicate if profiling is enabled
381   useconds_t m_profile_interval_usec; // If enable, the profiling interval in
382                                       // microseconds
383   DNBProfileDataScanType
384       m_profile_scan_type; // Indicates what needs to be profiled
385   pthread_t
386       m_profile_thread; // Thread ID for the thread that profiles the inferior
387   PThreadMutex
388       m_profile_data_mutex; // Multithreaded protection for profile info data
389   std::vector<std::string>
390       m_profile_data; // Profile data, must be protected by m_profile_data_mutex
391 
392   DNBThreadResumeActions m_thread_actions; // The thread actions for the current
393                                            // MachProcess::Resume() call
394   MachException::Message::collection m_exception_messages; // A collection of
395                                                            // exception messages
396                                                            // caught when
397                                                            // listening to the
398                                                            // exception port
399   PThreadMutex m_exception_messages_mutex; // Multithreaded protection for
400                                            // m_exception_messages
401 
402   MachThreadList m_thread_list; // A list of threads that is maintained/updated
403                                 // after each stop
404   Genealogy m_activities; // A list of activities that is updated after every
405                           // stop lazily
406   nub_state_t m_state;    // The state of our process
407   PThreadMutex m_state_mutex; // Multithreaded protection for m_state
408   PThreadEvent m_events;      // Process related events in the child processes
409                               // lifetime can be waited upon
410   PThreadEvent m_private_events; // Used to coordinate running and stopping the
411                                  // process without affecting m_events
412   DNBBreakpointList m_breakpoints; // Breakpoint list for this process
413   DNBBreakpointList m_watchpoints; // Watchpoint list for this process
414   DNBCallbackNameToAddress m_name_to_addr_callback;
415   void *m_name_to_addr_baton;
416   DNBCallbackCopyExecutableImageInfos m_image_infos_callback;
417   void *m_image_infos_baton;
418   std::string
419       m_bundle_id; // If we are a SB or BKS process, this will be our bundle ID.
420   int m_sent_interrupt_signo; // When we call MachProcess::Interrupt(), we want
421                               // to send a single signal
422   // to the inferior and only send the signal if we aren't already stopped.
423   // If we end up sending a signal to stop the process we store it until we
424   // receive an exception with this signal. This helps us to verify we got
425   // the signal that interrupted the process. We might stop due to another
426   // reason after an interrupt signal is sent, so this helps us ensure that
427   // we don't report a spurious stop on the next resume.
428   int m_auto_resume_signo; // If we resume the process and still haven't
429                            // received our interrupt signal
430   // acknownledgement, we will shortly after the next resume. We store the
431   // interrupt signal in this variable so when we get the interrupt signal
432   // as the sole reason for the process being stopped, we can auto resume
433   // the process.
434   bool m_did_exec;
435 
436   void *(*m_dyld_process_info_create)(task_t task, uint64_t timestamp,
437                                       kern_return_t *kernelError);
438   void (*m_dyld_process_info_for_each_image)(
439       void *info, void (^callback)(uint64_t machHeaderAddress,
440                                    const uuid_t uuid, const char *path));
441   void (*m_dyld_process_info_release)(void *info);
442   void (*m_dyld_process_info_get_cache)(void *info, void *cacheInfo);
443 };
444 
445 #endif // __MachProcess_h__
446