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