1 //===-- MachTask.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 //----------------------------------------------------------------------
14 // Created by Greg Clayton on 12/5/08.
16 //===----------------------------------------------------------------------===//
22 #include <mach-o/dyld_images.h>
23 #include <mach/mach_vm.h>
24 #import <sys/sysctl.h>
26 #if defined(__APPLE__)
35 // Other libraries and framework includes
39 #include "DNBDataRef.h"
42 #include "MachProcess.h"
44 #ifdef WITH_SPRINGBOARD
46 #include <CoreFoundation/CoreFoundation.h>
47 #include <SpringBoardServices/SBSWatchdogAssertion.h>
48 #include <SpringBoardServices/SpringBoardServer.h>
54 #import <BackBoardServices/BKSWatchdogAssertion.h>
55 #import <BackBoardServices/BackBoardServices.h>
56 #import <Foundation/Foundation.h>
60 #include <AvailabilityMacros.h>
63 #include <mach/mach_time.h>
68 //----------------------------------------------------------------------
69 // MachTask constructor
70 //----------------------------------------------------------------------
71 MachTask::MachTask(MachProcess *process)
72 : m_process(process), m_task(TASK_NULL), m_vm_memory(),
73 m_exception_thread(0), m_exception_port(MACH_PORT_NULL) {
74 memset(&m_exc_port_info, 0, sizeof(m_exc_port_info));
77 //----------------------------------------------------------------------
79 //----------------------------------------------------------------------
80 MachTask::~MachTask() { Clear(); }
82 //----------------------------------------------------------------------
84 //----------------------------------------------------------------------
85 kern_return_t MachTask::Suspend() {
87 task_t task = TaskPort();
88 err = ::task_suspend(task);
89 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
90 err.LogThreaded("::task_suspend ( target_task = 0x%4.4x )", task);
94 //----------------------------------------------------------------------
96 //----------------------------------------------------------------------
97 kern_return_t MachTask::Resume() {
98 struct task_basic_info task_info;
99 task_t task = TaskPort();
100 if (task == TASK_NULL)
101 return KERN_INVALID_ARGUMENT;
104 err = BasicInfo(task, &task_info);
107 // task_resume isn't counted like task_suspend calls are, are, so if the
108 // task is not suspended, don't try and resume it since it is already
110 if (task_info.suspend_count > 0) {
111 err = ::task_resume(task);
112 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
113 err.LogThreaded("::task_resume ( target_task = 0x%4.4x )", task);
119 //----------------------------------------------------------------------
120 // MachTask::ExceptionPort
121 //----------------------------------------------------------------------
122 mach_port_t MachTask::ExceptionPort() const { return m_exception_port; }
124 //----------------------------------------------------------------------
125 // MachTask::ExceptionPortIsValid
126 //----------------------------------------------------------------------
127 bool MachTask::ExceptionPortIsValid() const {
128 return MACH_PORT_VALID(m_exception_port);
131 //----------------------------------------------------------------------
133 //----------------------------------------------------------------------
134 void MachTask::Clear() {
135 // Do any cleanup needed for this task
137 m_exception_thread = 0;
138 m_exception_port = MACH_PORT_NULL;
141 //----------------------------------------------------------------------
142 // MachTask::SaveExceptionPortInfo
143 //----------------------------------------------------------------------
144 kern_return_t MachTask::SaveExceptionPortInfo() {
145 return m_exc_port_info.Save(TaskPort());
148 //----------------------------------------------------------------------
149 // MachTask::RestoreExceptionPortInfo
150 //----------------------------------------------------------------------
151 kern_return_t MachTask::RestoreExceptionPortInfo() {
152 return m_exc_port_info.Restore(TaskPort());
155 //----------------------------------------------------------------------
156 // MachTask::ReadMemory
157 //----------------------------------------------------------------------
158 nub_size_t MachTask::ReadMemory(nub_addr_t addr, nub_size_t size, void *buf) {
160 task_t task = TaskPort();
161 if (task != TASK_NULL) {
162 n = m_vm_memory.Read(task, addr, buf, size);
164 DNBLogThreadedIf(LOG_MEMORY, "MachTask::ReadMemory ( addr = 0x%8.8llx, "
165 "size = %llu, buf = %p) => %llu bytes read",
166 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
167 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) ||
168 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) {
169 DNBDataRef data((uint8_t *)buf, n, false);
170 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr,
171 DNBDataRef::TypeUInt8, 16);
177 //----------------------------------------------------------------------
178 // MachTask::WriteMemory
179 //----------------------------------------------------------------------
180 nub_size_t MachTask::WriteMemory(nub_addr_t addr, nub_size_t size,
183 task_t task = TaskPort();
184 if (task != TASK_NULL) {
185 n = m_vm_memory.Write(task, addr, buf, size);
186 DNBLogThreadedIf(LOG_MEMORY, "MachTask::WriteMemory ( addr = 0x%8.8llx, "
187 "size = %llu, buf = %p) => %llu bytes written",
188 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
189 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) ||
190 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) {
191 DNBDataRef data((const uint8_t *)buf, n, false);
192 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr,
193 DNBDataRef::TypeUInt8, 16);
199 //----------------------------------------------------------------------
200 // MachTask::MemoryRegionInfo
201 //----------------------------------------------------------------------
202 int MachTask::GetMemoryRegionInfo(nub_addr_t addr, DNBRegionInfo *region_info) {
203 task_t task = TaskPort();
204 if (task == TASK_NULL)
207 int ret = m_vm_memory.GetMemoryRegionInfo(task, addr, region_info);
208 DNBLogThreadedIf(LOG_MEMORY, "MachTask::MemoryRegionInfo ( addr = 0x%8.8llx "
209 ") => %i (start = 0x%8.8llx, size = 0x%8.8llx, "
211 (uint64_t)addr, ret, (uint64_t)region_info->addr,
212 (uint64_t)region_info->size, region_info->permissions);
216 #define TIME_VALUE_TO_TIMEVAL(a, r) \
218 (r)->tv_sec = (a)->seconds; \
219 (r)->tv_usec = (a)->microseconds; \
222 // We should consider moving this into each MacThread.
223 static void get_threads_profile_data(DNBProfileDataScanType scanType,
224 task_t task, nub_process_t pid,
225 std::vector<uint64_t> &threads_id,
226 std::vector<std::string> &threads_name,
227 std::vector<uint64_t> &threads_used_usec) {
229 thread_act_array_t threads;
230 mach_msg_type_number_t tcnt;
232 kr = task_threads(task, &threads, &tcnt);
233 if (kr != KERN_SUCCESS)
236 for (mach_msg_type_number_t i = 0; i < tcnt; i++) {
237 thread_identifier_info_data_t identifier_info;
238 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
239 kr = ::thread_info(threads[i], THREAD_IDENTIFIER_INFO,
240 (thread_info_t)&identifier_info, &count);
241 if (kr != KERN_SUCCESS)
244 thread_basic_info_data_t basic_info;
245 count = THREAD_BASIC_INFO_COUNT;
246 kr = ::thread_info(threads[i], THREAD_BASIC_INFO,
247 (thread_info_t)&basic_info, &count);
248 if (kr != KERN_SUCCESS)
251 if ((basic_info.flags & TH_FLAGS_IDLE) == 0) {
253 MachThread::GetGloballyUniqueThreadIDForMachPortID(threads[i]);
254 threads_id.push_back(tid);
256 if ((scanType & eProfileThreadName) &&
257 (identifier_info.thread_handle != 0)) {
258 struct proc_threadinfo proc_threadinfo;
259 int len = ::proc_pidinfo(pid, PROC_PIDTHREADINFO,
260 identifier_info.thread_handle,
261 &proc_threadinfo, PROC_PIDTHREADINFO_SIZE);
262 if (len && proc_threadinfo.pth_name[0]) {
263 threads_name.push_back(proc_threadinfo.pth_name);
265 threads_name.push_back("");
268 threads_name.push_back("");
271 struct timeval thread_tv;
272 TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &thread_tv);
273 TIME_VALUE_TO_TIMEVAL(&basic_info.system_time, &tv);
274 timeradd(&thread_tv, &tv, &thread_tv);
275 uint64_t used_usec = thread_tv.tv_sec * 1000000ULL + thread_tv.tv_usec;
276 threads_used_usec.push_back(used_usec);
279 mach_port_deallocate(mach_task_self(), threads[i]);
281 mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads,
282 tcnt * sizeof(*threads));
285 #define RAW_HEXBASE std::setfill('0') << std::hex << std::right
286 #define DECIMAL std::dec << std::setfill(' ')
287 std::string MachTask::GetProfileData(DNBProfileDataScanType scanType) {
290 static int32_t numCPU = -1;
291 struct host_cpu_load_info host_info;
292 if (scanType & eProfileHostCPU) {
293 int32_t mib[] = {CTL_HW, HW_AVAILCPU};
294 size_t len = sizeof(numCPU);
296 if (sysctl(mib, sizeof(mib) / sizeof(int32_t), &numCPU, &len, NULL, 0) !=
301 mach_port_t localHost = mach_host_self();
302 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
303 kern_return_t kr = host_statistics(localHost, HOST_CPU_LOAD_INFO,
304 (host_info_t)&host_info, &count);
305 if (kr != KERN_SUCCESS)
309 task_t task = TaskPort();
310 if (task == TASK_NULL)
313 pid_t pid = m_process->ProcessID();
315 struct task_basic_info task_info;
317 err = BasicInfo(task, &task_info);
322 uint64_t elapsed_usec = 0;
323 uint64_t task_used_usec = 0;
324 if (scanType & eProfileCPU) {
325 // Get current used time.
326 struct timeval current_used_time;
328 TIME_VALUE_TO_TIMEVAL(&task_info.user_time, ¤t_used_time);
329 TIME_VALUE_TO_TIMEVAL(&task_info.system_time, &tv);
330 timeradd(¤t_used_time, &tv, ¤t_used_time);
332 current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec;
334 struct timeval current_elapsed_time;
335 int res = gettimeofday(¤t_elapsed_time, NULL);
337 elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL +
338 current_elapsed_time.tv_usec;
342 std::vector<uint64_t> threads_id;
343 std::vector<std::string> threads_name;
344 std::vector<uint64_t> threads_used_usec;
346 if (scanType & eProfileThreadsCPU) {
347 get_threads_profile_data(scanType, task, pid, threads_id, threads_name,
351 vm_statistics64_data_t vminfo;
352 uint64_t physical_memory = 0;
353 uint64_t anonymous = 0;
354 uint64_t phys_footprint = 0;
355 uint64_t memory_cap = 0;
356 if (m_vm_memory.GetMemoryProfile(scanType, task, task_info,
357 m_process->GetCPUType(), pid, vminfo,
358 physical_memory, anonymous,
359 phys_footprint, memory_cap)) {
360 std::ostringstream profile_data_stream;
362 if (scanType & eProfileHostCPU) {
363 profile_data_stream << "num_cpu:" << numCPU << ';';
364 profile_data_stream << "host_user_ticks:"
365 << host_info.cpu_ticks[CPU_STATE_USER] << ';';
366 profile_data_stream << "host_sys_ticks:"
367 << host_info.cpu_ticks[CPU_STATE_SYSTEM] << ';';
368 profile_data_stream << "host_idle_ticks:"
369 << host_info.cpu_ticks[CPU_STATE_IDLE] << ';';
372 if (scanType & eProfileCPU) {
373 profile_data_stream << "elapsed_usec:" << elapsed_usec << ';';
374 profile_data_stream << "task_used_usec:" << task_used_usec << ';';
377 if (scanType & eProfileThreadsCPU) {
378 const size_t num_threads = threads_id.size();
379 for (size_t i = 0; i < num_threads; i++) {
380 profile_data_stream << "thread_used_id:" << std::hex << threads_id[i]
382 profile_data_stream << "thread_used_usec:" << threads_used_usec[i]
385 if (scanType & eProfileThreadName) {
386 profile_data_stream << "thread_used_name:";
387 const size_t len = threads_name[i].size();
389 const char *thread_name = threads_name[i].c_str();
390 // Make sure that thread name doesn't interfere with our delimiter.
391 profile_data_stream << RAW_HEXBASE << std::setw(2);
392 const uint8_t *ubuf8 = (const uint8_t *)(thread_name);
393 for (size_t j = 0; j < len; j++) {
394 profile_data_stream << (uint32_t)(ubuf8[j]);
396 // Reset back to DECIMAL.
397 profile_data_stream << DECIMAL;
399 profile_data_stream << ';';
404 if (scanType & eProfileHostMemory)
405 profile_data_stream << "total:" << physical_memory << ';';
407 if (scanType & eProfileMemory) {
408 static vm_size_t pagesize = vm_kernel_page_size;
410 // This mimicks Activity Monitor.
411 uint64_t total_used_count =
412 (physical_memory / pagesize) -
413 (vminfo.free_count - vminfo.speculative_count) -
414 vminfo.external_page_count - vminfo.purgeable_count;
415 profile_data_stream << "used:" << total_used_count * pagesize << ';';
417 if (scanType & eProfileMemoryAnonymous) {
418 profile_data_stream << "anonymous:" << anonymous << ';';
421 profile_data_stream << "phys_footprint:" << phys_footprint << ';';
424 if (scanType & eProfileMemoryCap) {
425 profile_data_stream << "mem_cap:" << memory_cap << ';';
429 if (scanType & eProfileEnergy) {
430 struct rusage_info_v2 info;
431 int rc = proc_pid_rusage(pid, RUSAGE_INFO_V2, (rusage_info_t *)&info);
433 uint64_t now = mach_absolute_time();
434 pm_task_energy_data_t pm_energy;
435 memset(&pm_energy, 0, sizeof(pm_energy));
437 * Disable most features of pm_sample_pid. It will gather
438 * network/GPU/WindowServer information; fill in the rest.
440 pm_sample_task_and_pid(task, pid, &pm_energy, now,
441 PM_SAMPLE_ALL & ~PM_SAMPLE_NAME &
442 ~PM_SAMPLE_INTERVAL & ~PM_SAMPLE_CPU &
444 pm_energy.sti.total_user = info.ri_user_time;
445 pm_energy.sti.total_system = info.ri_system_time;
446 pm_energy.sti.task_interrupt_wakeups = info.ri_interrupt_wkups;
447 pm_energy.sti.task_platform_idle_wakeups = info.ri_pkg_idle_wkups;
448 pm_energy.diskio_bytesread = info.ri_diskio_bytesread;
449 pm_energy.diskio_byteswritten = info.ri_diskio_byteswritten;
450 pm_energy.pageins = info.ri_pageins;
452 uint64_t total_energy =
453 (uint64_t)(pm_energy_impact(&pm_energy) * NSEC_PER_SEC);
454 // uint64_t process_age = now - info.ri_proc_start_abstime;
455 // uint64_t avg_energy = 100.0 * (double)total_energy /
456 // (double)process_age;
458 profile_data_stream << "energy:" << total_energy << ';';
463 profile_data_stream << "--end--;";
465 result = profile_data_stream.str();
471 //----------------------------------------------------------------------
472 // MachTask::TaskPortForProcessID
473 //----------------------------------------------------------------------
474 task_t MachTask::TaskPortForProcessID(DNBError &err, bool force) {
475 if (((m_task == TASK_NULL) || force) && m_process != NULL)
476 m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err);
480 //----------------------------------------------------------------------
481 // MachTask::TaskPortForProcessID
482 //----------------------------------------------------------------------
483 task_t MachTask::TaskPortForProcessID(pid_t pid, DNBError &err,
484 uint32_t num_retries,
485 uint32_t usec_interval) {
486 if (pid != INVALID_NUB_PROCESS) {
488 mach_port_t task_self = mach_task_self();
489 task_t task = TASK_NULL;
490 for (uint32_t i = 0; i < num_retries; i++) {
491 err = ::task_for_pid(task_self, pid, &task);
493 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) {
495 ::snprintf(str, sizeof(str), "::task_for_pid ( target_tport = 0x%4.4x, "
496 "pid = %d, &task ) => err = 0x%8.8x (%s)",
497 task_self, pid, err.Status(),
498 err.AsString() ? err.AsString() : "success");
500 err.SetErrorString(str);
501 err.LogThreaded(str);
507 // Sleep a bit and try again
508 ::usleep(usec_interval);
514 //----------------------------------------------------------------------
515 // MachTask::BasicInfo
516 //----------------------------------------------------------------------
517 kern_return_t MachTask::BasicInfo(struct task_basic_info *info) {
518 return BasicInfo(TaskPort(), info);
521 //----------------------------------------------------------------------
522 // MachTask::BasicInfo
523 //----------------------------------------------------------------------
524 kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) {
526 return KERN_INVALID_ARGUMENT;
529 mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
530 err = ::task_info(task, TASK_BASIC_INFO, (task_info_t)info, &count);
531 const bool log_process = DNBLogCheckLogBit(LOG_TASK);
532 if (log_process || err.Fail())
533 err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = "
534 "TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => "
537 if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) &&
539 float user = (float)info->user_time.seconds +
540 (float)info->user_time.microseconds / 1000000.0f;
541 float system = (float)info->user_time.seconds +
542 (float)info->user_time.microseconds / 1000000.0f;
543 DNBLogThreaded("task_basic_info = { suspend_count = %i, virtual_size = "
544 "0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, "
545 "system_time = %f }",
546 info->suspend_count, (uint64_t)info->virtual_size,
547 (uint64_t)info->resident_size, user, system);
552 //----------------------------------------------------------------------
555 // Returns true if a task is a valid task port for a current process.
556 //----------------------------------------------------------------------
557 bool MachTask::IsValid() const { return MachTask::IsValid(TaskPort()); }
559 //----------------------------------------------------------------------
562 // Returns true if a task is a valid task port for a current process.
563 //----------------------------------------------------------------------
564 bool MachTask::IsValid(task_t task) {
565 if (task != TASK_NULL) {
566 struct task_basic_info task_info;
567 return BasicInfo(task, &task_info) == KERN_SUCCESS;
572 bool MachTask::StartExceptionThread(DNBError &err) {
573 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
575 task_t task = TaskPortForProcessID(err);
576 if (MachTask::IsValid(task)) {
577 // Got the mach port for the current process
578 mach_port_t task_self = mach_task_self();
580 // Allocate an exception port that we will use to track our child process
581 err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
586 // Add the ability to send messages on the new exception port
587 err = ::mach_port_insert_right(task_self, m_exception_port,
588 m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
592 // Save the original state of the exception ports for our child process
593 SaveExceptionPortInfo();
595 // We weren't able to save the info for our exception ports, we must stop...
596 if (m_exc_port_info.mask == 0) {
597 err.SetErrorString("failed to get exception port info");
601 // Set the ability to get all exceptions on this port
602 err = ::task_set_exception_ports(
603 task, m_exc_port_info.mask, m_exception_port,
604 EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
605 if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
606 err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
607 "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior "
608 "= 0x%8.8x, new_flavor = 0x%8.8x )",
609 task, m_exc_port_info.mask, m_exception_port,
610 (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
617 // Create the exception thread
618 err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread,
620 return err.Success();
622 DNBLogError("MachTask::%s (): task invalid, exception thread start failed.",
628 kern_return_t MachTask::ShutDownExcecptionThread() {
631 err = RestoreExceptionPortInfo();
633 // NULL our our exception port and let our exception thread exit
634 mach_port_t exception_port = m_exception_port;
635 m_exception_port = 0;
637 err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
638 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
639 err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
641 err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
642 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
643 err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)",
646 // Deallocate our exception port that we used to track our child process
647 mach_port_t task_self = mach_task_self();
648 err = ::mach_port_deallocate(task_self, exception_port);
649 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
650 err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )",
651 task_self, exception_port);
656 void *MachTask::ExceptionThread(void *arg) {
660 MachTask *mach_task = (MachTask *)arg;
661 MachProcess *mach_proc = mach_task->Process();
662 DNBLogThreadedIf(LOG_EXCEPTIONS,
663 "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__,
666 #if defined(__APPLE__)
667 pthread_setname_np("exception monitoring thread");
668 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
669 struct sched_param thread_param;
670 int thread_sched_policy;
671 if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
672 &thread_param) == 0) {
673 thread_param.sched_priority = 47;
674 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
679 // We keep a count of the number of consecutive exceptions received so
680 // we know to grab all exceptions without a timeout. We do this to get a
681 // bunch of related exceptions on our exception port so we can process
682 // then together. When we have multiple threads, we can get an exception
683 // per thread and they will come in consecutively. The main loop in this
684 // thread can stop periodically if needed to service things related to this
686 // flag set in the options, so we will wait forever for an exception on
687 // our exception port. After we get one exception, we then will use the
688 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
689 // exceptions for our process. After we have received the last pending
690 // exception, we will get a timeout which enables us to then notify
691 // our main thread that we have an exception bundle available. We then wait
692 // for the main thread to tell this exception thread to start trying to get
693 // exceptions messages again and we start again with a mach_msg read with
695 uint32_t num_exceptions_received = 0;
697 task_t task = mach_task->TaskPort();
698 mach_msg_timeout_t periodic_timeout = 0;
700 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
701 mach_msg_timeout_t watchdog_elapsed = 0;
702 mach_msg_timeout_t watchdog_timeout = 60 * 1000;
703 pid_t pid = mach_proc->ProcessID();
704 CFReleaser<SBSWatchdogAssertionRef> watchdog;
706 if (mach_proc->ProcessUsingSpringBoard()) {
707 // Request a renewal for every 60 seconds if we attached using SpringBoard
708 watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
710 LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p",
711 pid, watchdog.get());
713 if (watchdog.get()) {
714 ::SBSWatchdogAssertionRenew(watchdog.get());
716 CFTimeInterval watchdogRenewalInterval =
717 ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
720 "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds",
721 watchdog.get(), watchdogRenewalInterval);
722 if (watchdogRenewalInterval > 0.0) {
723 watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
724 if (watchdog_timeout > 3000)
725 watchdog_timeout -= 1000; // Give us a second to renew our timeout
726 else if (watchdog_timeout > 1000)
728 250; // Give us a quarter of a second to renew our timeout
731 if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
732 periodic_timeout = watchdog_timeout;
734 #endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
737 CFReleaser<BKSWatchdogAssertionRef> watchdog;
738 if (mach_proc->ProcessUsingBackBoard()) {
739 pid_t pid = mach_proc->ProcessID();
740 CFAllocatorRef alloc = kCFAllocatorDefault;
741 watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
743 #endif // #ifdef WITH_BKS
745 while (mach_task->ExceptionPortIsValid()) {
746 ::pthread_testcancel();
748 MachException::Message exception_message;
750 if (num_exceptions_received > 0) {
751 // No timeout, just receive as many exceptions as we can since we already
752 // have one and we want
753 // to get all currently available exceptions for this task
754 err = exception_message.Receive(
755 mach_task->ExceptionPort(),
756 MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
757 } else if (periodic_timeout > 0) {
758 // We need to stop periodically in this loop, so try and get a mach
759 // message with a valid timeout (ms)
760 err = exception_message.Receive(mach_task->ExceptionPort(),
761 MACH_RCV_MSG | MACH_RCV_INTERRUPT |
765 // We don't need to parse all current exceptions or stop periodically,
766 // just wait for an exception forever.
767 err = exception_message.Receive(mach_task->ExceptionPort(),
768 MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
771 if (err.Status() == MACH_RCV_INTERRUPTED) {
772 // If we have no task port we should exit this thread
773 if (!mach_task->ExceptionPortIsValid()) {
774 DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
778 // Make sure our task is still valid
779 if (MachTask::IsValid(task)) {
781 DNBLogThreadedIf(LOG_EXCEPTIONS,
782 "interrupted, but task still valid, continuing...");
785 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
786 mach_proc->SetState(eStateExited);
787 // Our task has died, exit the thread.
790 } else if (err.Status() == MACH_RCV_TIMED_OUT) {
791 if (num_exceptions_received > 0) {
792 // We were receiving all current exceptions with a timeout of zero
793 // it is time to go back to our normal looping mode
794 num_exceptions_received = 0;
796 // Notify our main thread we have a complete exception message
797 // bundle available and get the possibly updated task port back
798 // from the process in case we exec'ed and our task port changed
799 task = mach_proc->ExceptionMessageBundleComplete();
801 // in case we use a timeout value when getting exceptions...
802 // Make sure our task is still valid
803 if (MachTask::IsValid(task)) {
805 DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
808 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
809 mach_proc->SetState(eStateExited);
810 // Our task has died, exit the thread.
815 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
816 if (watchdog.get()) {
817 watchdog_elapsed += periodic_timeout;
818 if (watchdog_elapsed >= watchdog_timeout) {
819 DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )",
821 ::SBSWatchdogAssertionRenew(watchdog.get());
822 watchdog_elapsed = 0;
826 } else if (err.Status() != KERN_SUCCESS) {
827 DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something "
828 "about it??? nah, continuing for "
830 // TODO: notify of error?
832 if (exception_message.CatchExceptionRaise(task)) {
833 if (exception_message.state.task_port != task) {
834 if (exception_message.state.IsValid()) {
835 // We exec'ed and our task port changed on us.
836 DNBLogThreadedIf(LOG_EXCEPTIONS,
837 "task port changed from 0x%4.4x to 0x%4.4x",
838 task, exception_message.state.task_port);
839 task = exception_message.state.task_port;
840 mach_task->TaskPortChanged(exception_message.state.task_port);
843 ++num_exceptions_received;
844 mach_proc->ExceptionMessageReceived(exception_message);
849 #if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
850 if (watchdog.get()) {
851 // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
853 // all are up and running on systems that support it. The SBS framework has
855 // that will forward SBSWatchdogAssertionRelease to
856 // SBSWatchdogAssertionCancel for now
857 // so it should still build either way.
858 DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
860 ::SBSWatchdogAssertionRelease(watchdog.get());
862 #endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
864 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...",
869 // So the TASK_DYLD_INFO used to just return the address of the all image infos
870 // as a single member called "all_image_info". Then someone decided it would be
871 // a good idea to rename this first member to "all_image_info_addr" and add a
872 // size member called "all_image_info_size". This of course can not be detected
873 // using code or #defines. So to hack around this problem, we define our own
874 // version of the TASK_DYLD_INFO structure so we can guarantee what is inside
877 struct hack_task_dyld_info {
878 mach_vm_address_t all_image_info_addr;
879 mach_vm_size_t all_image_info_size;
882 nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) {
883 struct hack_task_dyld_info dyld_info;
884 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
885 // Make sure that COUNT isn't bigger than our hacked up struct
886 // hack_task_dyld_info.
887 // If it is, then make COUNT smaller to match.
888 if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
889 count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
891 task_t task = TaskPortForProcessID(err);
893 err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
895 // We now have the address of the all image infos structure
896 return dyld_info.all_image_info_addr;
899 return INVALID_NUB_ADDRESS;
902 //----------------------------------------------------------------------
903 // MachTask::AllocateMemory
904 //----------------------------------------------------------------------
905 nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) {
906 mach_vm_address_t addr;
907 task_t task = TaskPort();
908 if (task == TASK_NULL)
909 return INVALID_NUB_ADDRESS;
912 err = ::mach_vm_allocate(task, &addr, size, TRUE);
913 if (err.Status() == KERN_SUCCESS) {
914 // Set the protections:
915 vm_prot_t mach_prot = VM_PROT_NONE;
916 if (permissions & eMemoryPermissionsReadable)
917 mach_prot |= VM_PROT_READ;
918 if (permissions & eMemoryPermissionsWritable)
919 mach_prot |= VM_PROT_WRITE;
920 if (permissions & eMemoryPermissionsExecutable)
921 mach_prot |= VM_PROT_EXECUTE;
923 err = ::mach_vm_protect(task, addr, size, 0, mach_prot);
924 if (err.Status() == KERN_SUCCESS) {
925 m_allocations.insert(std::make_pair(addr, size));
928 ::mach_vm_deallocate(task, addr, size);
930 return INVALID_NUB_ADDRESS;
933 //----------------------------------------------------------------------
934 // MachTask::DeallocateMemory
935 //----------------------------------------------------------------------
936 nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) {
937 task_t task = TaskPort();
938 if (task == TASK_NULL)
941 // We have to stash away sizes for the allocations...
942 allocation_collection::iterator pos, end = m_allocations.end();
943 for (pos = m_allocations.begin(); pos != end; pos++) {
944 if ((*pos).first == addr) {
945 m_allocations.erase(pos);
946 #define ALWAYS_ZOMBIE_ALLOCATIONS 0
947 if (ALWAYS_ZOMBIE_ALLOCATIONS ||
948 getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) {
949 ::mach_vm_protect(task, (*pos).first, (*pos).second, 0, VM_PROT_NONE);
952 return ::mach_vm_deallocate(task, (*pos).first, (*pos).second) ==
959 void MachTask::TaskPortChanged(task_t task)