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