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