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