1 //===-- MachTask.cpp --------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
8 //----------------------------------------------------------------------
13 // Created by Greg Clayton on 12/5/08.
15 //===----------------------------------------------------------------------===//
21 #include <mach-o/dyld_images.h>
22 #include <mach/mach_vm.h>
23 #import <sys/sysctl.h>
25 #if defined(__APPLE__)
34 // Other libraries and framework includes
38 #include "DNBDataRef.h"
41 #include "MachProcess.h"
43 #ifdef WITH_SPRINGBOARD
45 #include <CoreFoundation/CoreFoundation.h>
46 #include <SpringBoardServices/SBSWatchdogAssertion.h>
47 #include <SpringBoardServices/SpringBoardServer.h>
53 #import <BackBoardServices/BKSWatchdogAssertion.h>
54 #import <BackBoardServices/BackBoardServices.h>
55 #import <Foundation/Foundation.h>
59 #include <AvailabilityMacros.h>
62 #include <mach/mach_time.h>
68 proc_get_cpumon_params(pid_t pid, int *percentage,
69 int *interval); // <libproc_internal.h> SPI
71 //----------------------------------------------------------------------
72 // MachTask constructor
73 //----------------------------------------------------------------------
74 MachTask::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));
81 //----------------------------------------------------------------------
83 //----------------------------------------------------------------------
84 MachTask::~MachTask() { Clear(); }
86 //----------------------------------------------------------------------
88 //----------------------------------------------------------------------
89 kern_return_t MachTask::Suspend() {
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);
98 //----------------------------------------------------------------------
100 //----------------------------------------------------------------------
101 kern_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;
108 err = BasicInfo(task, &task_info);
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);
117 m_do_double_resume = false;
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
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);
131 //----------------------------------------------------------------------
132 // MachTask::ExceptionPort
133 //----------------------------------------------------------------------
134 mach_port_t MachTask::ExceptionPort() const { return m_exception_port; }
136 //----------------------------------------------------------------------
137 // MachTask::ExceptionPortIsValid
138 //----------------------------------------------------------------------
139 bool MachTask::ExceptionPortIsValid() const {
140 return MACH_PORT_VALID(m_exception_port);
143 //----------------------------------------------------------------------
145 //----------------------------------------------------------------------
146 void MachTask::Clear() {
147 // Do any cleanup needed for this task
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;
155 //----------------------------------------------------------------------
156 // MachTask::SaveExceptionPortInfo
157 //----------------------------------------------------------------------
158 kern_return_t MachTask::SaveExceptionPortInfo() {
159 return m_exc_port_info.Save(TaskPort());
162 //----------------------------------------------------------------------
163 // MachTask::RestoreExceptionPortInfo
164 //----------------------------------------------------------------------
165 kern_return_t MachTask::RestoreExceptionPortInfo() {
166 return m_exc_port_info.Restore(TaskPort());
169 //----------------------------------------------------------------------
170 // MachTask::ReadMemory
171 //----------------------------------------------------------------------
172 nub_size_t MachTask::ReadMemory(nub_addr_t addr, nub_size_t size, void *buf) {
174 task_t task = TaskPort();
175 if (task != TASK_NULL) {
176 n = m_vm_memory.Read(task, addr, buf, size);
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);
191 //----------------------------------------------------------------------
192 // MachTask::WriteMemory
193 //----------------------------------------------------------------------
194 nub_size_t MachTask::WriteMemory(nub_addr_t addr, nub_size_t size,
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);
213 //----------------------------------------------------------------------
214 // MachTask::MemoryRegionInfo
215 //----------------------------------------------------------------------
216 int MachTask::GetMemoryRegionInfo(nub_addr_t addr, DNBRegionInfo *region_info) {
217 task_t task = TaskPort();
218 if (task == TASK_NULL)
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, "
225 (uint64_t)addr, ret, (uint64_t)region_info->addr,
226 (uint64_t)region_info->size, region_info->permissions);
230 #define TIME_VALUE_TO_TIMEVAL(a, r) \
232 (r)->tv_sec = (a)->seconds; \
233 (r)->tv_usec = (a)->microseconds; \
236 // We should consider moving this into each MacThread.
237 static 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) {
243 thread_act_array_t threads;
244 mach_msg_type_number_t tcnt;
246 kr = task_threads(task, &threads, &tcnt);
247 if (kr != KERN_SUCCESS)
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)
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)
265 if ((basic_info.flags & TH_FLAGS_IDLE) == 0) {
267 MachThread::GetGloballyUniqueThreadIDForMachPortID(threads[i]);
268 threads_id.push_back(tid);
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);
279 threads_name.push_back("");
282 threads_name.push_back("");
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);
293 mach_port_deallocate(mach_task_self(), threads[i]);
295 mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads,
296 tcnt * sizeof(*threads));
299 #define RAW_HEXBASE std::setfill('0') << std::hex << std::right
300 #define DECIMAL std::dec << std::setfill(' ')
301 std::string MachTask::GetProfileData(DNBProfileDataScanType scanType) {
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);
310 if (sysctl(mib, sizeof(mib) / sizeof(int32_t), &numCPU, &len, NULL, 0) !=
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)
323 task_t task = TaskPort();
324 if (task == TASK_NULL)
327 pid_t pid = m_process->ProcessID();
329 struct task_basic_info task_info;
331 err = BasicInfo(task, &task_info);
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;
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);
346 current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec;
348 struct timeval current_elapsed_time;
349 int res = gettimeofday(¤t_elapsed_time, NULL);
351 elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL +
352 current_elapsed_time.tv_usec;
356 std::vector<uint64_t> threads_id;
357 std::vector<std::string> threads_name;
358 std::vector<uint64_t> threads_used_usec;
360 if (scanType & eProfileThreadsCPU) {
361 get_threads_profile_data(scanType, task, pid, threads_id, threads_name,
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;
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] << ';';
386 if (scanType & eProfileCPU) {
387 profile_data_stream << "elapsed_usec:" << elapsed_usec << ';';
388 profile_data_stream << "task_used_usec:" << task_used_usec << ';';
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]
396 profile_data_stream << "thread_used_usec:" << threads_used_usec[i]
399 if (scanType & eProfileThreadName) {
400 profile_data_stream << "thread_used_name:";
401 const size_t len = threads_name[i].size();
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]);
410 // Reset back to DECIMAL.
411 profile_data_stream << DECIMAL;
413 profile_data_stream << ';';
418 if (scanType & eProfileHostMemory)
419 profile_data_stream << "total:" << physical_memory << ';';
421 if (scanType & eProfileMemory) {
422 static vm_size_t pagesize = vm_kernel_page_size;
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 << ';';
431 if (scanType & eProfileMemoryAnonymous) {
432 profile_data_stream << "anonymous:" << anonymous << ';';
435 profile_data_stream << "phys_footprint:" << phys_footprint << ';';
438 if (scanType & eProfileMemoryCap) {
439 profile_data_stream << "mem_cap:" << memory_cap << ';';
443 if (scanType & eProfileEnergy) {
444 struct rusage_info_v2 info;
445 int rc = proc_pid_rusage(pid, RUSAGE_INFO_V2, (rusage_info_t *)&info);
447 uint64_t now = mach_absolute_time();
448 pm_task_energy_data_t pm_energy;
449 memset(&pm_energy, 0, sizeof(pm_energy));
451 * Disable most features of pm_sample_pid. It will gather
452 * network/GPU/WindowServer information; fill in the rest.
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 &
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;
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;
472 profile_data_stream << "energy:" << total_energy << ';';
477 if (scanType & eProfileEnergyCPUCap) {
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 << ';';
487 profile_data_stream << "--end--;";
489 result = profile_data_stream.str();
495 //----------------------------------------------------------------------
496 // MachTask::TaskPortForProcessID
497 //----------------------------------------------------------------------
498 task_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);
504 //----------------------------------------------------------------------
505 // MachTask::TaskPortForProcessID
506 //----------------------------------------------------------------------
507 task_t MachTask::TaskPortForProcessID(pid_t pid, DNBError &err,
508 uint32_t num_retries,
509 uint32_t usec_interval) {
510 if (pid != INVALID_NUB_PROCESS) {
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);
518 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) {
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");
525 err.SetErrorString(str);
527 "[LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(%d) "
531 err.LogThreaded(str);
535 DNBLog("[LaunchAttach] (%d) successfully task_for_pid(%d)'ed", getpid(),
540 // Sleep a bit and try again
541 ::usleep(usec_interval);
547 //----------------------------------------------------------------------
548 // MachTask::BasicInfo
549 //----------------------------------------------------------------------
550 kern_return_t MachTask::BasicInfo(struct task_basic_info *info) {
551 return BasicInfo(TaskPort(), info);
554 //----------------------------------------------------------------------
555 // MachTask::BasicInfo
556 //----------------------------------------------------------------------
557 kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) {
559 return KERN_INVALID_ARGUMENT;
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 => "
570 if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) &&
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);
585 //----------------------------------------------------------------------
588 // Returns true if a task is a valid task port for a current process.
589 //----------------------------------------------------------------------
590 bool MachTask::IsValid() const { return MachTask::IsValid(TaskPort()); }
592 //----------------------------------------------------------------------
595 // Returns true if a task is a valid task port for a current process.
596 //----------------------------------------------------------------------
597 bool 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;
605 bool MachTask::StartExceptionThread(bool unmask_signals, DNBError &err) {
606 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
608 task_t task = TaskPortForProcessID(err);
609 if (MachTask::IsValid(task)) {
610 // Got the mach port for the current process
611 mach_port_t task_self = mach_task_self();
613 // Allocate an exception port that we will use to track our child process
614 err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
619 // Add the ability to send messages on the new exception port
620 err = ::mach_port_insert_right(task_self, m_exception_port,
621 m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
625 // Save the original state of the exception ports for our child process
626 SaveExceptionPortInfo();
628 // We weren't able to save the info for our exception ports, we must stop...
629 if (m_exc_port_info.mask == 0) {
630 err.SetErrorString("failed to get exception port info");
634 if (unmask_signals) {
635 m_exc_port_info.mask = m_exc_port_info.mask &
636 ~(EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION |
637 EXC_MASK_ARITHMETIC);
640 // Set the ability to get all exceptions on this port
641 err = ::task_set_exception_ports(
642 task, m_exc_port_info.mask, m_exception_port,
643 EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
644 if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
645 err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
646 "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior "
647 "= 0x%8.8x, new_flavor = 0x%8.8x )",
648 task, m_exc_port_info.mask, m_exception_port,
649 (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
656 // Create the exception thread
657 err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread,
659 return err.Success();
661 DNBLogError("MachTask::%s (): task invalid, exception thread start failed.",
667 kern_return_t MachTask::ShutDownExcecptionThread() {
670 err = RestoreExceptionPortInfo();
672 // NULL our our exception port and let our exception thread exit
673 mach_port_t exception_port = m_exception_port;
674 m_exception_port = 0;
676 err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
677 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
678 err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
680 err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
681 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
682 err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)",
685 // Deallocate our exception port that we used to track our child process
686 mach_port_t task_self = mach_task_self();
687 err = ::mach_port_deallocate(task_self, exception_port);
688 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
689 err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )",
690 task_self, exception_port);
692 m_exec_will_be_suspended = false;
693 m_do_double_resume = false;
698 void *MachTask::ExceptionThread(void *arg) {
702 MachTask *mach_task = (MachTask *)arg;
703 MachProcess *mach_proc = mach_task->Process();
704 DNBLogThreadedIf(LOG_EXCEPTIONS,
705 "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__,
708 #if defined(__APPLE__)
709 pthread_setname_np("exception monitoring thread");
710 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
711 struct sched_param thread_param;
712 int thread_sched_policy;
713 if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
714 &thread_param) == 0) {
715 thread_param.sched_priority = 47;
716 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
721 // We keep a count of the number of consecutive exceptions received so
722 // we know to grab all exceptions without a timeout. We do this to get a
723 // bunch of related exceptions on our exception port so we can process
724 // then together. When we have multiple threads, we can get an exception
725 // per thread and they will come in consecutively. The main loop in this
726 // thread can stop periodically if needed to service things related to this
728 // flag set in the options, so we will wait forever for an exception on
729 // our exception port. After we get one exception, we then will use the
730 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
731 // exceptions for our process. After we have received the last pending
732 // exception, we will get a timeout which enables us to then notify
733 // our main thread that we have an exception bundle available. We then wait
734 // for the main thread to tell this exception thread to start trying to get
735 // exceptions messages again and we start again with a mach_msg read with
737 uint32_t num_exceptions_received = 0;
739 task_t task = mach_task->TaskPort();
740 mach_msg_timeout_t periodic_timeout = 0;
742 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
743 mach_msg_timeout_t watchdog_elapsed = 0;
744 mach_msg_timeout_t watchdog_timeout = 60 * 1000;
745 pid_t pid = mach_proc->ProcessID();
746 CFReleaser<SBSWatchdogAssertionRef> watchdog;
748 if (mach_proc->ProcessUsingSpringBoard()) {
749 // Request a renewal for every 60 seconds if we attached using SpringBoard
750 watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
752 LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p",
753 pid, watchdog.get());
755 if (watchdog.get()) {
756 ::SBSWatchdogAssertionRenew(watchdog.get());
758 CFTimeInterval watchdogRenewalInterval =
759 ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
762 "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds",
763 watchdog.get(), watchdogRenewalInterval);
764 if (watchdogRenewalInterval > 0.0) {
765 watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
766 if (watchdog_timeout > 3000)
767 watchdog_timeout -= 1000; // Give us a second to renew our timeout
768 else if (watchdog_timeout > 1000)
770 250; // Give us a quarter of a second to renew our timeout
773 if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
774 periodic_timeout = watchdog_timeout;
776 #endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
779 CFReleaser<BKSWatchdogAssertionRef> watchdog;
780 if (mach_proc->ProcessUsingBackBoard()) {
781 pid_t pid = mach_proc->ProcessID();
782 CFAllocatorRef alloc = kCFAllocatorDefault;
783 watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
785 #endif // #ifdef WITH_BKS
787 while (mach_task->ExceptionPortIsValid()) {
788 ::pthread_testcancel();
790 MachException::Message exception_message;
792 if (num_exceptions_received > 0) {
793 // No timeout, just receive as many exceptions as we can since we already
794 // have one and we want
795 // to get all currently available exceptions for this task
796 err = exception_message.Receive(
797 mach_task->ExceptionPort(),
798 MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 1);
799 } else if (periodic_timeout > 0) {
800 // We need to stop periodically in this loop, so try and get a mach
801 // message with a valid timeout (ms)
802 err = exception_message.Receive(mach_task->ExceptionPort(),
803 MACH_RCV_MSG | MACH_RCV_INTERRUPT |
807 // We don't need to parse all current exceptions or stop periodically,
808 // just wait for an exception forever.
809 err = exception_message.Receive(mach_task->ExceptionPort(),
810 MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
813 if (err.Status() == MACH_RCV_INTERRUPTED) {
814 // If we have no task port we should exit this thread
815 if (!mach_task->ExceptionPortIsValid()) {
816 DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
820 // Make sure our task is still valid
821 if (MachTask::IsValid(task)) {
823 DNBLogThreadedIf(LOG_EXCEPTIONS,
824 "interrupted, but task still valid, continuing...");
827 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
828 mach_proc->SetState(eStateExited);
829 // Our task has died, exit the thread.
832 } else if (err.Status() == MACH_RCV_TIMED_OUT) {
833 if (num_exceptions_received > 0) {
834 // We were receiving all current exceptions with a timeout of zero
835 // it is time to go back to our normal looping mode
836 num_exceptions_received = 0;
838 // Notify our main thread we have a complete exception message
839 // bundle available and get the possibly updated task port back
840 // from the process in case we exec'ed and our task port changed
841 task = mach_proc->ExceptionMessageBundleComplete();
843 // in case we use a timeout value when getting exceptions...
844 // Make sure our task is still valid
845 if (MachTask::IsValid(task)) {
847 DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
850 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
851 mach_proc->SetState(eStateExited);
852 // Our task has died, exit the thread.
857 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
858 if (watchdog.get()) {
859 watchdog_elapsed += periodic_timeout;
860 if (watchdog_elapsed >= watchdog_timeout) {
861 DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )",
863 ::SBSWatchdogAssertionRenew(watchdog.get());
864 watchdog_elapsed = 0;
868 } else if (err.Status() != KERN_SUCCESS) {
869 DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something "
870 "about it??? nah, continuing for "
872 // TODO: notify of error?
874 if (exception_message.CatchExceptionRaise(task)) {
875 if (exception_message.state.task_port != task) {
876 if (exception_message.state.IsValid()) {
877 // We exec'ed and our task port changed on us.
878 DNBLogThreadedIf(LOG_EXCEPTIONS,
879 "task port changed from 0x%4.4x to 0x%4.4x",
880 task, exception_message.state.task_port);
881 task = exception_message.state.task_port;
882 mach_task->TaskPortChanged(exception_message.state.task_port);
885 ++num_exceptions_received;
886 mach_proc->ExceptionMessageReceived(exception_message);
891 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
892 if (watchdog.get()) {
893 // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
895 // all are up and running on systems that support it. The SBS framework has
897 // that will forward SBSWatchdogAssertionRelease to
898 // SBSWatchdogAssertionCancel for now
899 // so it should still build either way.
900 DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
902 ::SBSWatchdogAssertionRelease(watchdog.get());
904 #endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
906 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...",
911 // So the TASK_DYLD_INFO used to just return the address of the all image infos
912 // as a single member called "all_image_info". Then someone decided it would be
913 // a good idea to rename this first member to "all_image_info_addr" and add a
914 // size member called "all_image_info_size". This of course can not be detected
915 // using code or #defines. So to hack around this problem, we define our own
916 // version of the TASK_DYLD_INFO structure so we can guarantee what is inside
919 struct hack_task_dyld_info {
920 mach_vm_address_t all_image_info_addr;
921 mach_vm_size_t all_image_info_size;
924 nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) {
925 struct hack_task_dyld_info dyld_info;
926 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
927 // Make sure that COUNT isn't bigger than our hacked up struct
928 // hack_task_dyld_info.
929 // If it is, then make COUNT smaller to match.
930 if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
931 count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
933 task_t task = TaskPortForProcessID(err);
935 err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
937 // We now have the address of the all image infos structure
938 return dyld_info.all_image_info_addr;
941 return INVALID_NUB_ADDRESS;
944 //----------------------------------------------------------------------
945 // MachTask::AllocateMemory
946 //----------------------------------------------------------------------
947 nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) {
948 mach_vm_address_t addr;
949 task_t task = TaskPort();
950 if (task == TASK_NULL)
951 return INVALID_NUB_ADDRESS;
954 err = ::mach_vm_allocate(task, &addr, size, TRUE);
955 if (err.Status() == KERN_SUCCESS) {
956 // Set the protections:
957 vm_prot_t mach_prot = VM_PROT_NONE;
958 if (permissions & eMemoryPermissionsReadable)
959 mach_prot |= VM_PROT_READ;
960 if (permissions & eMemoryPermissionsWritable)
961 mach_prot |= VM_PROT_WRITE;
962 if (permissions & eMemoryPermissionsExecutable)
963 mach_prot |= VM_PROT_EXECUTE;
965 err = ::mach_vm_protect(task, addr, size, 0, mach_prot);
966 if (err.Status() == KERN_SUCCESS) {
967 m_allocations.insert(std::make_pair(addr, size));
970 ::mach_vm_deallocate(task, addr, size);
972 return INVALID_NUB_ADDRESS;
975 //----------------------------------------------------------------------
976 // MachTask::DeallocateMemory
977 //----------------------------------------------------------------------
978 nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) {
979 task_t task = TaskPort();
980 if (task == TASK_NULL)
983 // We have to stash away sizes for the allocations...
984 allocation_collection::iterator pos, end = m_allocations.end();
985 for (pos = m_allocations.begin(); pos != end; pos++) {
986 if ((*pos).first == addr) {
987 size_t size = (*pos).second;
988 m_allocations.erase(pos);
989 #define ALWAYS_ZOMBIE_ALLOCATIONS 0
990 if (ALWAYS_ZOMBIE_ALLOCATIONS ||
991 getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) {
992 ::mach_vm_protect(task, addr, size, 0, VM_PROT_NONE);
995 return ::mach_vm_deallocate(task, addr, size) == KERN_SUCCESS;
1001 void MachTask::TaskPortChanged(task_t task)
1005 // If we've just exec'd to a new process, and it
1006 // is started suspended, we'll need to do two
1007 // task_resume's to get the inferior process to
1009 if (m_exec_will_be_suspended)
1010 m_do_double_resume = true;
1012 m_do_double_resume = false;
1013 m_exec_will_be_suspended = false;