1//===-- MachTask.cpp --------------------------------------------*- 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// 10// MachTask.cpp 11// debugserver 12// 13// Created by Greg Clayton on 12/5/08. 14// 15//===----------------------------------------------------------------------===// 16 17#include "MachTask.h" 18 19// C Includes 20 21#include <mach-o/dyld_images.h> 22#include <mach/mach_vm.h> 23#import <sys/sysctl.h> 24 25#if defined(__APPLE__) 26#include <pthread.h> 27#include <sched.h> 28#endif 29 30// C++ Includes 31#include <iomanip> 32#include <sstream> 33 34// Other libraries and framework includes 35// Project includes 36#include "CFUtils.h" 37#include "DNB.h" 38#include "DNBDataRef.h" 39#include "DNBError.h" 40#include "DNBLog.h" 41#include "MachProcess.h" 42 43#ifdef WITH_SPRINGBOARD 44 45#include <CoreFoundation/CoreFoundation.h> 46#include <SpringBoardServices/SBSWatchdogAssertion.h> 47#include <SpringBoardServices/SpringBoardServer.h> 48 49#endif 50 51#ifdef WITH_BKS 52extern "C" { 53#import <BackBoardServices/BKSWatchdogAssertion.h> 54#import <BackBoardServices/BackBoardServices.h> 55#import <Foundation/Foundation.h> 56} 57#endif 58 59#include <AvailabilityMacros.h> 60 61#ifdef LLDB_ENERGY 62#include <mach/mach_time.h> 63#include <pmenergy.h> 64#include <pmsample.h> 65#endif 66 67extern "C" int 68proc_get_cpumon_params(pid_t pid, int *percentage, 69 int *interval); // <libproc_internal.h> SPI 70 71//---------------------------------------------------------------------- 72// MachTask constructor 73//---------------------------------------------------------------------- 74MachTask::MachTask(MachProcess *process) 75 : m_process(process), m_task(TASK_NULL), m_vm_memory(), 76 m_exception_thread(0), m_exception_port(MACH_PORT_NULL), 77 m_exec_will_be_suspended(false), m_do_double_resume(false) { 78 memset(&m_exc_port_info, 0, sizeof(m_exc_port_info)); 79} 80 81//---------------------------------------------------------------------- 82// Destructor 83//---------------------------------------------------------------------- 84MachTask::~MachTask() { Clear(); } 85 86//---------------------------------------------------------------------- 87// MachTask::Suspend 88//---------------------------------------------------------------------- 89kern_return_t MachTask::Suspend() { 90 DNBError err; 91 task_t task = TaskPort(); 92 err = ::task_suspend(task); 93 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 94 err.LogThreaded("::task_suspend ( target_task = 0x%4.4x )", task); 95 return err.Status(); 96} 97 98//---------------------------------------------------------------------- 99// MachTask::Resume 100//---------------------------------------------------------------------- 101kern_return_t MachTask::Resume() { 102 struct task_basic_info task_info; 103 task_t task = TaskPort(); 104 if (task == TASK_NULL) 105 return KERN_INVALID_ARGUMENT; 106 107 DNBError err; 108 err = BasicInfo(task, &task_info); 109 110 if (err.Success()) { 111 if (m_do_double_resume && task_info.suspend_count == 2) { 112 err = ::task_resume(task); 113 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 114 err.LogThreaded("::task_resume double-resume after exec-start-stopped " 115 "( target_task = 0x%4.4x )", task); 116 } 117 m_do_double_resume = false; 118 119 // task_resume isn't counted like task_suspend calls are, are, so if the 120 // task is not suspended, don't try and resume it since it is already 121 // running 122 if (task_info.suspend_count > 0) { 123 err = ::task_resume(task); 124 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 125 err.LogThreaded("::task_resume ( target_task = 0x%4.4x )", task); 126 } 127 } 128 return err.Status(); 129} 130 131//---------------------------------------------------------------------- 132// MachTask::ExceptionPort 133//---------------------------------------------------------------------- 134mach_port_t MachTask::ExceptionPort() const { return m_exception_port; } 135 136//---------------------------------------------------------------------- 137// MachTask::ExceptionPortIsValid 138//---------------------------------------------------------------------- 139bool MachTask::ExceptionPortIsValid() const { 140 return MACH_PORT_VALID(m_exception_port); 141} 142 143//---------------------------------------------------------------------- 144// MachTask::Clear 145//---------------------------------------------------------------------- 146void MachTask::Clear() { 147 // Do any cleanup needed for this task 148 m_task = TASK_NULL; 149 m_exception_thread = 0; 150 m_exception_port = MACH_PORT_NULL; 151 m_exec_will_be_suspended = false; 152 m_do_double_resume = false; 153} 154 155//---------------------------------------------------------------------- 156// MachTask::SaveExceptionPortInfo 157//---------------------------------------------------------------------- 158kern_return_t MachTask::SaveExceptionPortInfo() { 159 return m_exc_port_info.Save(TaskPort()); 160} 161 162//---------------------------------------------------------------------- 163// MachTask::RestoreExceptionPortInfo 164//---------------------------------------------------------------------- 165kern_return_t MachTask::RestoreExceptionPortInfo() { 166 return m_exc_port_info.Restore(TaskPort()); 167} 168 169//---------------------------------------------------------------------- 170// MachTask::ReadMemory 171//---------------------------------------------------------------------- 172nub_size_t MachTask::ReadMemory(nub_addr_t addr, nub_size_t size, void *buf) { 173 nub_size_t n = 0; 174 task_t task = TaskPort(); 175 if (task != TASK_NULL) { 176 n = m_vm_memory.Read(task, addr, buf, size); 177 178 DNBLogThreadedIf(LOG_MEMORY, "MachTask::ReadMemory ( addr = 0x%8.8llx, " 179 "size = %llu, buf = %p) => %llu bytes read", 180 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n); 181 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || 182 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) { 183 DNBDataRef data((uint8_t *)buf, n, false); 184 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr, 185 DNBDataRef::TypeUInt8, 16); 186 } 187 } 188 return n; 189} 190 191//---------------------------------------------------------------------- 192// MachTask::WriteMemory 193//---------------------------------------------------------------------- 194nub_size_t MachTask::WriteMemory(nub_addr_t addr, nub_size_t size, 195 const void *buf) { 196 nub_size_t n = 0; 197 task_t task = TaskPort(); 198 if (task != TASK_NULL) { 199 n = m_vm_memory.Write(task, addr, buf, size); 200 DNBLogThreadedIf(LOG_MEMORY, "MachTask::WriteMemory ( addr = 0x%8.8llx, " 201 "size = %llu, buf = %p) => %llu bytes written", 202 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n); 203 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || 204 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) { 205 DNBDataRef data((const uint8_t *)buf, n, false); 206 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr, 207 DNBDataRef::TypeUInt8, 16); 208 } 209 } 210 return n; 211} 212 213//---------------------------------------------------------------------- 214// MachTask::MemoryRegionInfo 215//---------------------------------------------------------------------- 216int MachTask::GetMemoryRegionInfo(nub_addr_t addr, DNBRegionInfo *region_info) { 217 task_t task = TaskPort(); 218 if (task == TASK_NULL) 219 return -1; 220 221 int ret = m_vm_memory.GetMemoryRegionInfo(task, addr, region_info); 222 DNBLogThreadedIf(LOG_MEMORY, "MachTask::MemoryRegionInfo ( addr = 0x%8.8llx " 223 ") => %i (start = 0x%8.8llx, size = 0x%8.8llx, " 224 "permissions = %u)", 225 (uint64_t)addr, ret, (uint64_t)region_info->addr, 226 (uint64_t)region_info->size, region_info->permissions); 227 return ret; 228} 229 230#define TIME_VALUE_TO_TIMEVAL(a, r) \ 231 do { \ 232 (r)->tv_sec = (a)->seconds; \ 233 (r)->tv_usec = (a)->microseconds; \ 234 } while (0) 235 236// We should consider moving this into each MacThread. 237static void get_threads_profile_data(DNBProfileDataScanType scanType, 238 task_t task, nub_process_t pid, 239 std::vector<uint64_t> &threads_id, 240 std::vector<std::string> &threads_name, 241 std::vector<uint64_t> &threads_used_usec) { 242 kern_return_t kr; 243 thread_act_array_t threads; 244 mach_msg_type_number_t tcnt; 245 246 kr = task_threads(task, &threads, &tcnt); 247 if (kr != KERN_SUCCESS) 248 return; 249 250 for (mach_msg_type_number_t i = 0; i < tcnt; i++) { 251 thread_identifier_info_data_t identifier_info; 252 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT; 253 kr = ::thread_info(threads[i], THREAD_IDENTIFIER_INFO, 254 (thread_info_t)&identifier_info, &count); 255 if (kr != KERN_SUCCESS) 256 continue; 257 258 thread_basic_info_data_t basic_info; 259 count = THREAD_BASIC_INFO_COUNT; 260 kr = ::thread_info(threads[i], THREAD_BASIC_INFO, 261 (thread_info_t)&basic_info, &count); 262 if (kr != KERN_SUCCESS) 263 continue; 264 265 if ((basic_info.flags & TH_FLAGS_IDLE) == 0) { 266 nub_thread_t tid = 267 MachThread::GetGloballyUniqueThreadIDForMachPortID(threads[i]); 268 threads_id.push_back(tid); 269 270 if ((scanType & eProfileThreadName) && 271 (identifier_info.thread_handle != 0)) { 272 struct proc_threadinfo proc_threadinfo; 273 int len = ::proc_pidinfo(pid, PROC_PIDTHREADINFO, 274 identifier_info.thread_handle, 275 &proc_threadinfo, PROC_PIDTHREADINFO_SIZE); 276 if (len && proc_threadinfo.pth_name[0]) { 277 threads_name.push_back(proc_threadinfo.pth_name); 278 } else { 279 threads_name.push_back(""); 280 } 281 } else { 282 threads_name.push_back(""); 283 } 284 struct timeval tv; 285 struct timeval thread_tv; 286 TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &thread_tv); 287 TIME_VALUE_TO_TIMEVAL(&basic_info.system_time, &tv); 288 timeradd(&thread_tv, &tv, &thread_tv); 289 uint64_t used_usec = thread_tv.tv_sec * 1000000ULL + thread_tv.tv_usec; 290 threads_used_usec.push_back(used_usec); 291 } 292 293 mach_port_deallocate(mach_task_self(), threads[i]); 294 } 295 mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads, 296 tcnt * sizeof(*threads)); 297} 298 299#define RAW_HEXBASE std::setfill('0') << std::hex << std::right 300#define DECIMAL std::dec << std::setfill(' ') 301std::string MachTask::GetProfileData(DNBProfileDataScanType scanType) { 302 std::string result; 303 304 static int32_t numCPU = -1; 305 struct host_cpu_load_info host_info; 306 if (scanType & eProfileHostCPU) { 307 int32_t mib[] = {CTL_HW, HW_AVAILCPU}; 308 size_t len = sizeof(numCPU); 309 if (numCPU == -1) { 310 if (sysctl(mib, sizeof(mib) / sizeof(int32_t), &numCPU, &len, NULL, 0) != 311 0) 312 return result; 313 } 314 315 mach_port_t localHost = mach_host_self(); 316 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; 317 kern_return_t kr = host_statistics(localHost, HOST_CPU_LOAD_INFO, 318 (host_info_t)&host_info, &count); 319 if (kr != KERN_SUCCESS) 320 return result; 321 } 322 323 task_t task = TaskPort(); 324 if (task == TASK_NULL) 325 return result; 326 327 pid_t pid = m_process->ProcessID(); 328 329 struct task_basic_info task_info; 330 DNBError err; 331 err = BasicInfo(task, &task_info); 332 333 if (!err.Success()) 334 return result; 335 336 uint64_t elapsed_usec = 0; 337 uint64_t task_used_usec = 0; 338 if (scanType & eProfileCPU) { 339 // Get current used time. 340 struct timeval current_used_time; 341 struct timeval tv; 342 TIME_VALUE_TO_TIMEVAL(&task_info.user_time, ¤t_used_time); 343 TIME_VALUE_TO_TIMEVAL(&task_info.system_time, &tv); 344 timeradd(¤t_used_time, &tv, ¤t_used_time); 345 task_used_usec = 346 current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec; 347 348 struct timeval current_elapsed_time; 349 int res = gettimeofday(¤t_elapsed_time, NULL); 350 if (res == 0) { 351 elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL + 352 current_elapsed_time.tv_usec; 353 } 354 } 355 356 std::vector<uint64_t> threads_id; 357 std::vector<std::string> threads_name; 358 std::vector<uint64_t> threads_used_usec; 359 360 if (scanType & eProfileThreadsCPU) { 361 get_threads_profile_data(scanType, task, pid, threads_id, threads_name, 362 threads_used_usec); 363 } 364 365 vm_statistics64_data_t vminfo; 366 uint64_t physical_memory = 0; 367 uint64_t anonymous = 0; 368 uint64_t phys_footprint = 0; 369 uint64_t memory_cap = 0; 370 if (m_vm_memory.GetMemoryProfile(scanType, task, task_info, 371 m_process->GetCPUType(), pid, vminfo, 372 physical_memory, anonymous, 373 phys_footprint, memory_cap)) { 374 std::ostringstream profile_data_stream; 375 376 if (scanType & eProfileHostCPU) { 377 profile_data_stream << "num_cpu:" << numCPU << ';'; 378 profile_data_stream << "host_user_ticks:" 379 << host_info.cpu_ticks[CPU_STATE_USER] << ';'; 380 profile_data_stream << "host_sys_ticks:" 381 << host_info.cpu_ticks[CPU_STATE_SYSTEM] << ';'; 382 profile_data_stream << "host_idle_ticks:" 383 << host_info.cpu_ticks[CPU_STATE_IDLE] << ';'; 384 } 385 386 if (scanType & eProfileCPU) { 387 profile_data_stream << "elapsed_usec:" << elapsed_usec << ';'; 388 profile_data_stream << "task_used_usec:" << task_used_usec << ';'; 389 } 390 391 if (scanType & eProfileThreadsCPU) { 392 const size_t num_threads = threads_id.size(); 393 for (size_t i = 0; i < num_threads; i++) { 394 profile_data_stream << "thread_used_id:" << std::hex << threads_id[i] 395 << std::dec << ';'; 396 profile_data_stream << "thread_used_usec:" << threads_used_usec[i] 397 << ';'; 398 399 if (scanType & eProfileThreadName) { 400 profile_data_stream << "thread_used_name:"; 401 const size_t len = threads_name[i].size(); 402 if (len) { 403 const char *thread_name = threads_name[i].c_str(); 404 // Make sure that thread name doesn't interfere with our delimiter. 405 profile_data_stream << RAW_HEXBASE << std::setw(2); 406 const uint8_t *ubuf8 = (const uint8_t *)(thread_name); 407 for (size_t j = 0; j < len; j++) { 408 profile_data_stream << (uint32_t)(ubuf8[j]); 409 } 410 // Reset back to DECIMAL. 411 profile_data_stream << DECIMAL; 412 } 413 profile_data_stream << ';'; 414 } 415 } 416 } 417 418 if (scanType & eProfileHostMemory) 419 profile_data_stream << "total:" << physical_memory << ';'; 420 421 if (scanType & eProfileMemory) { 422 static vm_size_t pagesize = vm_kernel_page_size; 423 424 // This mimicks Activity Monitor. 425 uint64_t total_used_count = 426 (physical_memory / pagesize) - 427 (vminfo.free_count - vminfo.speculative_count) - 428 vminfo.external_page_count - vminfo.purgeable_count; 429 profile_data_stream << "used:" << total_used_count * pagesize << ';'; 430 431 if (scanType & eProfileMemoryAnonymous) { 432 profile_data_stream << "anonymous:" << anonymous << ';'; 433 } 434 435 profile_data_stream << "phys_footprint:" << phys_footprint << ';'; 436 } 437 438 if (scanType & eProfileMemoryCap) { 439 profile_data_stream << "mem_cap:" << memory_cap << ';'; 440 } 441 442#ifdef LLDB_ENERGY 443 if (scanType & eProfileEnergy) { 444 struct rusage_info_v2 info; 445 int rc = proc_pid_rusage(pid, RUSAGE_INFO_V2, (rusage_info_t *)&info); 446 if (rc == 0) { 447 uint64_t now = mach_absolute_time(); 448 pm_task_energy_data_t pm_energy; 449 memset(&pm_energy, 0, sizeof(pm_energy)); 450 /* 451 * Disable most features of pm_sample_pid. It will gather 452 * network/GPU/WindowServer information; fill in the rest. 453 */ 454 pm_sample_task_and_pid(task, pid, &pm_energy, now, 455 PM_SAMPLE_ALL & ~PM_SAMPLE_NAME & 456 ~PM_SAMPLE_INTERVAL & ~PM_SAMPLE_CPU & 457 ~PM_SAMPLE_DISK); 458 pm_energy.sti.total_user = info.ri_user_time; 459 pm_energy.sti.total_system = info.ri_system_time; 460 pm_energy.sti.task_interrupt_wakeups = info.ri_interrupt_wkups; 461 pm_energy.sti.task_platform_idle_wakeups = info.ri_pkg_idle_wkups; 462 pm_energy.diskio_bytesread = info.ri_diskio_bytesread; 463 pm_energy.diskio_byteswritten = info.ri_diskio_byteswritten; 464 pm_energy.pageins = info.ri_pageins; 465 466 uint64_t total_energy = 467 (uint64_t)(pm_energy_impact(&pm_energy) * NSEC_PER_SEC); 468 // uint64_t process_age = now - info.ri_proc_start_abstime; 469 // uint64_t avg_energy = 100.0 * (double)total_energy / 470 // (double)process_age; 471 472 profile_data_stream << "energy:" << total_energy << ';'; 473 } 474 } 475#endif 476 477 if (scanType & eProfileEnergyCPUCap) { 478 int percentage = -1; 479 int interval = -1; 480 int result = proc_get_cpumon_params(pid, &percentage, &interval); 481 if ((result == 0) && (percentage >= 0) && (interval >= 0)) { 482 profile_data_stream << "cpu_cap_p:" << percentage << ';'; 483 profile_data_stream << "cpu_cap_t:" << interval << ';'; 484 } 485 } 486 487 profile_data_stream << "--end--;"; 488 489 result = profile_data_stream.str(); 490 } 491 492 return result; 493} 494 495//---------------------------------------------------------------------- 496// MachTask::TaskPortForProcessID 497//---------------------------------------------------------------------- 498task_t MachTask::TaskPortForProcessID(DNBError &err, bool force) { 499 if (((m_task == TASK_NULL) || force) && m_process != NULL) 500 m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err); 501 return m_task; 502} 503 504//---------------------------------------------------------------------- 505// MachTask::TaskPortForProcessID 506//---------------------------------------------------------------------- 507task_t MachTask::TaskPortForProcessID(pid_t pid, DNBError &err, 508 uint32_t num_retries, 509 uint32_t usec_interval) { 510 if (pid != INVALID_NUB_PROCESS) { 511 DNBError err; 512 mach_port_t task_self = mach_task_self(); 513 task_t task = TASK_NULL; 514 for (uint32_t i = 0; i < num_retries; i++) { 515 DNBLog("[LaunchAttach] (%d) about to task_for_pid(%d)", getpid(), pid); 516 err = ::task_for_pid(task_self, pid, &task); 517 518 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) { 519 char str[1024]; 520 ::snprintf(str, sizeof(str), "::task_for_pid ( target_tport = 0x%4.4x, " 521 "pid = %d, &task ) => err = 0x%8.8x (%s)", 522 task_self, pid, err.Status(), 523 err.AsString() ? err.AsString() : "success"); 524 if (err.Fail()) { 525 err.SetErrorString(str); 526 DNBLogError( 527 "[LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(%d) " 528 "failed: %s", 529 pid, str); 530 } 531 err.LogThreaded(str); 532 } 533 534 if (err.Success()) { 535 DNBLog("[LaunchAttach] (%d) successfully task_for_pid(%d)'ed", getpid(), 536 pid); 537 return task; 538 } 539 540 // Sleep a bit and try again 541 ::usleep(usec_interval); 542 } 543 } 544 return TASK_NULL; 545} 546 547//---------------------------------------------------------------------- 548// MachTask::BasicInfo 549//---------------------------------------------------------------------- 550kern_return_t MachTask::BasicInfo(struct task_basic_info *info) { 551 return BasicInfo(TaskPort(), info); 552} 553 554//---------------------------------------------------------------------- 555// MachTask::BasicInfo 556//---------------------------------------------------------------------- 557kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) { 558 if (info == NULL) 559 return KERN_INVALID_ARGUMENT; 560 561 DNBError err; 562 mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT; 563 err = ::task_info(task, TASK_BASIC_INFO, (task_info_t)info, &count); 564 const bool log_process = DNBLogCheckLogBit(LOG_TASK); 565 if (log_process || err.Fail()) 566 err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = " 567 "TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => " 568 "%u )", 569 task, info, count); 570 if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) && 571 err.Success()) { 572 float user = (float)info->user_time.seconds + 573 (float)info->user_time.microseconds / 1000000.0f; 574 float system = (float)info->user_time.seconds + 575 (float)info->user_time.microseconds / 1000000.0f; 576 DNBLogThreaded("task_basic_info = { suspend_count = %i, virtual_size = " 577 "0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, " 578 "system_time = %f }", 579 info->suspend_count, (uint64_t)info->virtual_size, 580 (uint64_t)info->resident_size, user, system); 581 } 582 return err.Status(); 583} 584 585//---------------------------------------------------------------------- 586// MachTask::IsValid 587// 588// Returns true if a task is a valid task port for a current process. 589//---------------------------------------------------------------------- 590bool MachTask::IsValid() const { return MachTask::IsValid(TaskPort()); } 591 592//---------------------------------------------------------------------- 593// MachTask::IsValid 594// 595// Returns true if a task is a valid task port for a current process. 596//---------------------------------------------------------------------- 597bool MachTask::IsValid(task_t task) { 598 if (task != TASK_NULL) { 599 struct task_basic_info task_info; 600 return BasicInfo(task, &task_info) == KERN_SUCCESS; 601 } 602 return false; 603} 604 605bool MachTask::StartExceptionThread( 606 const RNBContext::IgnoredExceptions &ignored_exceptions, 607 DNBError &err) { 608 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__); 609 610 task_t task = TaskPortForProcessID(err); 611 if (MachTask::IsValid(task)) { 612 // Got the mach port for the current process 613 mach_port_t task_self = mach_task_self(); 614 615 // Allocate an exception port that we will use to track our child process 616 err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE, 617 &m_exception_port); 618 if (err.Fail()) 619 return false; 620 621 // Add the ability to send messages on the new exception port 622 err = ::mach_port_insert_right(task_self, m_exception_port, 623 m_exception_port, MACH_MSG_TYPE_MAKE_SEND); 624 if (err.Fail()) 625 return false; 626 627 // Save the original state of the exception ports for our child process 628 SaveExceptionPortInfo(); 629 630 // We weren't able to save the info for our exception ports, we must stop... 631 if (m_exc_port_info.mask == 0) { 632 err.SetErrorString("failed to get exception port info"); 633 return false; 634 } 635 636 if (!ignored_exceptions.empty()) { 637 for (exception_mask_t mask : ignored_exceptions) 638 m_exc_port_info.mask = m_exc_port_info.mask & ~mask; 639 } 640 641 // Set the ability to get all exceptions on this port 642 err = ::task_set_exception_ports( 643 task, m_exc_port_info.mask, m_exception_port, 644 EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE); 645 if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) { 646 err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, " 647 "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior " 648 "= 0x%8.8x, new_flavor = 0x%8.8x )", 649 task, m_exc_port_info.mask, m_exception_port, 650 (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), 651 THREAD_STATE_NONE); 652 } 653 654 if (err.Fail()) 655 return false; 656 657 // Create the exception thread 658 err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread, 659 this); 660 return err.Success(); 661 } else { 662 DNBLogError("MachTask::%s (): task invalid, exception thread start failed.", 663 __FUNCTION__); 664 } 665 return false; 666} 667 668kern_return_t MachTask::ShutDownExcecptionThread() { 669 DNBError err; 670 671 err = RestoreExceptionPortInfo(); 672 673 // NULL our our exception port and let our exception thread exit 674 mach_port_t exception_port = m_exception_port; 675 m_exception_port = 0; 676 677 err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX); 678 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 679 err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread); 680 681 err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX); 682 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 683 err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)", 684 m_exception_thread); 685 686 // Deallocate our exception port that we used to track our child process 687 mach_port_t task_self = mach_task_self(); 688 err = ::mach_port_deallocate(task_self, exception_port); 689 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) 690 err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )", 691 task_self, exception_port); 692 693 m_exec_will_be_suspended = false; 694 m_do_double_resume = false; 695 696 return err.Status(); 697} 698 699void *MachTask::ExceptionThread(void *arg) { 700 if (arg == NULL) 701 return NULL; 702 703 MachTask *mach_task = (MachTask *)arg; 704 MachProcess *mach_proc = mach_task->Process(); 705 DNBLogThreadedIf(LOG_EXCEPTIONS, 706 "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__, 707 arg); 708 709#if defined(__APPLE__) 710 pthread_setname_np("exception monitoring thread"); 711#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 712 struct sched_param thread_param; 713 int thread_sched_policy; 714 if (pthread_getschedparam(pthread_self(), &thread_sched_policy, 715 &thread_param) == 0) { 716 thread_param.sched_priority = 47; 717 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param); 718 } 719#endif 720#endif 721 722 // We keep a count of the number of consecutive exceptions received so 723 // we know to grab all exceptions without a timeout. We do this to get a 724 // bunch of related exceptions on our exception port so we can process 725 // then together. When we have multiple threads, we can get an exception 726 // per thread and they will come in consecutively. The main loop in this 727 // thread can stop periodically if needed to service things related to this 728 // process. 729 // flag set in the options, so we will wait forever for an exception on 730 // our exception port. After we get one exception, we then will use the 731 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current 732 // exceptions for our process. After we have received the last pending 733 // exception, we will get a timeout which enables us to then notify 734 // our main thread that we have an exception bundle available. We then wait 735 // for the main thread to tell this exception thread to start trying to get 736 // exceptions messages again and we start again with a mach_msg read with 737 // infinite timeout. 738 uint32_t num_exceptions_received = 0; 739 DNBError err; 740 task_t task = mach_task->TaskPort(); 741 mach_msg_timeout_t periodic_timeout = 0; 742 743#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS) 744 mach_msg_timeout_t watchdog_elapsed = 0; 745 mach_msg_timeout_t watchdog_timeout = 60 * 1000; 746 pid_t pid = mach_proc->ProcessID(); 747 CFReleaser<SBSWatchdogAssertionRef> watchdog; 748 749 if (mach_proc->ProcessUsingSpringBoard()) { 750 // Request a renewal for every 60 seconds if we attached using SpringBoard 751 watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60)); 752 DNBLogThreadedIf( 753 LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p", 754 pid, watchdog.get()); 755 756 if (watchdog.get()) { 757 ::SBSWatchdogAssertionRenew(watchdog.get()); 758 759 CFTimeInterval watchdogRenewalInterval = 760 ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get()); 761 DNBLogThreadedIf( 762 LOG_TASK, 763 "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds", 764 watchdog.get(), watchdogRenewalInterval); 765 if (watchdogRenewalInterval > 0.0) { 766 watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000; 767 if (watchdog_timeout > 3000) 768 watchdog_timeout -= 1000; // Give us a second to renew our timeout 769 else if (watchdog_timeout > 1000) 770 watchdog_timeout -= 771 250; // Give us a quarter of a second to renew our timeout 772 } 773 } 774 if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout) 775 periodic_timeout = watchdog_timeout; 776 } 777#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS) 778 779#ifdef WITH_BKS 780 CFReleaser<BKSWatchdogAssertionRef> watchdog; 781 if (mach_proc->ProcessUsingBackBoard()) { 782 pid_t pid = mach_proc->ProcessID(); 783 CFAllocatorRef alloc = kCFAllocatorDefault; 784 watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid)); 785 } 786#endif // #ifdef WITH_BKS 787 788 while (mach_task->ExceptionPortIsValid()) { 789 ::pthread_testcancel(); 790 791 MachException::Message exception_message; 792 793 if (num_exceptions_received > 0) { 794 // No timeout, just receive as many exceptions as we can since we already 795 // have one and we want 796 // to get all currently available exceptions for this task 797 err = exception_message.Receive( 798 mach_task->ExceptionPort(), 799 MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 1); 800 } else if (periodic_timeout > 0) { 801 // We need to stop periodically in this loop, so try and get a mach 802 // message with a valid timeout (ms) 803 err = exception_message.Receive(mach_task->ExceptionPort(), 804 MACH_RCV_MSG | MACH_RCV_INTERRUPT | 805 MACH_RCV_TIMEOUT, 806 periodic_timeout); 807 } else { 808 // We don't need to parse all current exceptions or stop periodically, 809 // just wait for an exception forever. 810 err = exception_message.Receive(mach_task->ExceptionPort(), 811 MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0); 812 } 813 814 if (err.Status() == MACH_RCV_INTERRUPTED) { 815 // If we have no task port we should exit this thread 816 if (!mach_task->ExceptionPortIsValid()) { 817 DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled..."); 818 break; 819 } 820 821 // Make sure our task is still valid 822 if (MachTask::IsValid(task)) { 823 // Task is still ok 824 DNBLogThreadedIf(LOG_EXCEPTIONS, 825 "interrupted, but task still valid, continuing..."); 826 continue; 827 } else { 828 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited..."); 829 mach_proc->SetState(eStateExited); 830 // Our task has died, exit the thread. 831 break; 832 } 833 } else if (err.Status() == MACH_RCV_TIMED_OUT) { 834 if (num_exceptions_received > 0) { 835 // We were receiving all current exceptions with a timeout of zero 836 // it is time to go back to our normal looping mode 837 num_exceptions_received = 0; 838 839 // Notify our main thread we have a complete exception message 840 // bundle available and get the possibly updated task port back 841 // from the process in case we exec'ed and our task port changed 842 task = mach_proc->ExceptionMessageBundleComplete(); 843 844 // in case we use a timeout value when getting exceptions... 845 // Make sure our task is still valid 846 if (MachTask::IsValid(task)) { 847 // Task is still ok 848 DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing..."); 849 continue; 850 } else { 851 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited..."); 852 mach_proc->SetState(eStateExited); 853 // Our task has died, exit the thread. 854 break; 855 } 856 } 857 858#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS) 859 if (watchdog.get()) { 860 watchdog_elapsed += periodic_timeout; 861 if (watchdog_elapsed >= watchdog_timeout) { 862 DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )", 863 watchdog.get()); 864 ::SBSWatchdogAssertionRenew(watchdog.get()); 865 watchdog_elapsed = 0; 866 } 867 } 868#endif 869 } else if (err.Status() != KERN_SUCCESS) { 870 DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something " 871 "about it??? nah, continuing for " 872 "now..."); 873 // TODO: notify of error? 874 } else { 875 if (exception_message.CatchExceptionRaise(task)) { 876 if (exception_message.state.task_port != task) { 877 if (exception_message.state.IsValid()) { 878 // We exec'ed and our task port changed on us. 879 DNBLogThreadedIf(LOG_EXCEPTIONS, 880 "task port changed from 0x%4.4x to 0x%4.4x", 881 task, exception_message.state.task_port); 882 task = exception_message.state.task_port; 883 mach_task->TaskPortChanged(exception_message.state.task_port); 884 } 885 } 886 ++num_exceptions_received; 887 mach_proc->ExceptionMessageReceived(exception_message); 888 } 889 } 890 } 891 892#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS) 893 if (watchdog.get()) { 894 // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel 895 // when we 896 // all are up and running on systems that support it. The SBS framework has 897 // a #define 898 // that will forward SBSWatchdogAssertionRelease to 899 // SBSWatchdogAssertionCancel for now 900 // so it should still build either way. 901 DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)", 902 watchdog.get()); 903 ::SBSWatchdogAssertionRelease(watchdog.get()); 904 } 905#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS) 906 907 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...", 908 __FUNCTION__, arg); 909 return NULL; 910} 911 912// So the TASK_DYLD_INFO used to just return the address of the all image infos 913// as a single member called "all_image_info". Then someone decided it would be 914// a good idea to rename this first member to "all_image_info_addr" and add a 915// size member called "all_image_info_size". This of course can not be detected 916// using code or #defines. So to hack around this problem, we define our own 917// version of the TASK_DYLD_INFO structure so we can guarantee what is inside 918// it. 919 920struct hack_task_dyld_info { 921 mach_vm_address_t all_image_info_addr; 922 mach_vm_size_t all_image_info_size; 923}; 924 925nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) { 926 struct hack_task_dyld_info dyld_info; 927 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT; 928 // Make sure that COUNT isn't bigger than our hacked up struct 929 // hack_task_dyld_info. 930 // If it is, then make COUNT smaller to match. 931 if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t))) 932 count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)); 933 934 task_t task = TaskPortForProcessID(err); 935 if (err.Success()) { 936 err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count); 937 if (err.Success()) { 938 // We now have the address of the all image infos structure 939 return dyld_info.all_image_info_addr; 940 } 941 } 942 return INVALID_NUB_ADDRESS; 943} 944 945//---------------------------------------------------------------------- 946// MachTask::AllocateMemory 947//---------------------------------------------------------------------- 948nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) { 949 mach_vm_address_t addr; 950 task_t task = TaskPort(); 951 if (task == TASK_NULL) 952 return INVALID_NUB_ADDRESS; 953 954 DNBError err; 955 err = ::mach_vm_allocate(task, &addr, size, TRUE); 956 if (err.Status() == KERN_SUCCESS) { 957 // Set the protections: 958 vm_prot_t mach_prot = VM_PROT_NONE; 959 if (permissions & eMemoryPermissionsReadable) 960 mach_prot |= VM_PROT_READ; 961 if (permissions & eMemoryPermissionsWritable) 962 mach_prot |= VM_PROT_WRITE; 963 if (permissions & eMemoryPermissionsExecutable) 964 mach_prot |= VM_PROT_EXECUTE; 965 966 err = ::mach_vm_protect(task, addr, size, 0, mach_prot); 967 if (err.Status() == KERN_SUCCESS) { 968 m_allocations.insert(std::make_pair(addr, size)); 969 return addr; 970 } 971 ::mach_vm_deallocate(task, addr, size); 972 } 973 return INVALID_NUB_ADDRESS; 974} 975 976//---------------------------------------------------------------------- 977// MachTask::DeallocateMemory 978//---------------------------------------------------------------------- 979nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) { 980 task_t task = TaskPort(); 981 if (task == TASK_NULL) 982 return false; 983 984 // We have to stash away sizes for the allocations... 985 allocation_collection::iterator pos, end = m_allocations.end(); 986 for (pos = m_allocations.begin(); pos != end; pos++) { 987 if ((*pos).first == addr) { 988 size_t size = (*pos).second; 989 m_allocations.erase(pos); 990#define ALWAYS_ZOMBIE_ALLOCATIONS 0 991 if (ALWAYS_ZOMBIE_ALLOCATIONS || 992 getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) { 993 ::mach_vm_protect(task, addr, size, 0, VM_PROT_NONE); 994 return true; 995 } else 996 return ::mach_vm_deallocate(task, addr, size) == KERN_SUCCESS; 997 } 998 } 999 return false; 1000} 1001 1002//---------------------------------------------------------------------- 1003// MachTask::ClearAllocations 1004//---------------------------------------------------------------------- 1005void MachTask::ClearAllocations() { 1006 m_allocations.clear(); 1007} 1008 1009void MachTask::TaskPortChanged(task_t task) 1010{ 1011 m_task = task; 1012 1013 // If we've just exec'd to a new process, and it 1014 // is started suspended, we'll need to do two 1015 // task_resume's to get the inferior process to 1016 // continue. 1017 if (m_exec_will_be_suspended) 1018 m_do_double_resume = true; 1019 else 1020 m_do_double_resume = false; 1021 m_exec_will_be_suspended = false; 1022} 1023