#include "MachTask.h"
#include <mach-o/dyld_images.h>
#include <mach/mach_vm.h>
#include "CFUtils.h"
#include "DNB.h"
#include "DNBError.h"
#include "DNBLog.h"
#include "MachProcess.h"
#include "DNBDataRef.h"
#include "stack_logging.h"
#ifdef WITH_SPRINGBOARD
#include <CoreFoundation/CoreFoundation.h>
#include <SpringBoardServices/SpringBoardServer.h>
#include <SpringBoardServices/SBSWatchdogAssertion.h>
#endif
MachTask::MachTask(MachProcess *process) :
m_process (process),
m_task (TASK_NULL),
m_vm_memory (),
m_exception_thread (0),
m_exception_port (MACH_PORT_NULL)
{
memset(&m_exc_port_info, 0, sizeof(m_exc_port_info));
}
MachTask::~MachTask()
{
Clear();
}
kern_return_t
MachTask::Suspend()
{
DNBError err;
task_t task = TaskPort();
err = ::task_suspend (task);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
err.LogThreaded("::task_suspend ( target_task = 0x%4.4x )", task);
return err.Error();
}
kern_return_t
MachTask::Resume()
{
struct task_basic_info task_info;
task_t task = TaskPort();
if (task == TASK_NULL)
return KERN_INVALID_ARGUMENT;
DNBError err;
err = BasicInfo(task, &task_info);
if (err.Success())
{
if (task_info.suspend_count > 0)
{
err = ::task_resume (task);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
err.LogThreaded("::task_resume ( target_task = 0x%4.4x )", task);
}
}
return err.Error();
}
mach_port_t
MachTask::ExceptionPort() const
{
return m_exception_port;
}
bool
MachTask::ExceptionPortIsValid() const
{
return MACH_PORT_VALID(m_exception_port);
}
void
MachTask::Clear()
{
m_task = TASK_NULL;
m_exception_thread = 0;
m_exception_port = MACH_PORT_NULL;
}
kern_return_t
MachTask::SaveExceptionPortInfo()
{
return m_exc_port_info.Save(TaskPort());
}
kern_return_t
MachTask::RestoreExceptionPortInfo()
{
return m_exc_port_info.Restore(TaskPort());
}
nub_size_t
MachTask::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
{
nub_size_t n = 0;
task_t task = TaskPort();
if (task != TASK_NULL)
{
n = m_vm_memory.Read(task, addr, buf, size);
DNBLogThreadedIf(LOG_MEMORY, "MachTask::ReadMemory ( addr = 0x%8.8llx, size = %zu, buf = %p) => %zu bytes read", (uint64_t)addr, size, buf, n);
if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8))
{
DNBDataRef data((uint8_t*)buf, n, false);
data.Dump(0, n, addr, DNBDataRef::TypeUInt8, 16);
}
}
return n;
}
nub_size_t
MachTask::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
{
nub_size_t n = 0;
task_t task = TaskPort();
if (task != TASK_NULL)
{
n = m_vm_memory.Write(task, addr, buf, size);
DNBLogThreadedIf(LOG_MEMORY, "MachTask::WriteMemory ( addr = 0x%8.8llx, size = %zu, buf = %p) => %zu bytes written", (uint64_t)addr, size, buf, n);
if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8))
{
DNBDataRef data((uint8_t*)buf, n, false);
data.Dump(0, n, addr, DNBDataRef::TypeUInt8, 16);
}
}
return n;
}
int
MachTask::GetMemoryRegionInfo (nub_addr_t addr, DNBRegionInfo *region_info)
{
task_t task = TaskPort();
if (task == TASK_NULL)
return -1;
int ret = m_vm_memory.GetMemoryRegionInfo(task, addr, region_info);
DNBLogThreadedIf(LOG_MEMORY, "MachTask::MemoryRegionInfo ( addr = 0x%8.8llx ) => %i (start = 0x%8.8llx, size = 0x%8.8llx, permissions = %u)",
(uint64_t)addr,
ret,
(uint64_t)region_info->addr,
(uint64_t)region_info->size,
region_info->permissions);
return ret;
}
task_t
MachTask::TaskPortForProcessID (DNBError &err)
{
if (m_task == TASK_NULL && m_process != NULL)
m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err);
return m_task;
}
task_t
MachTask::TaskPortForProcessID (pid_t pid, DNBError &err, uint32_t num_retries, uint32_t usec_interval)
{
if (pid != INVALID_NUB_PROCESS)
{
DNBError err;
mach_port_t task_self = mach_task_self ();
task_t task = TASK_NULL;
for (uint32_t i=0; i<num_retries; i++)
{
err = ::task_for_pid ( task_self, pid, &task);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
{
char str[1024];
::snprintf (str,
sizeof(str),
"::task_for_pid ( target_tport = 0x%4.4x, pid = %d, &task ) => err = 0x%8.8x (%s)",
task_self,
pid,
err.Error(),
err.AsString() ? err.AsString() : "success");
if (err.Fail())
err.SetErrorString(str);
err.LogThreaded(str);
}
if (err.Success())
return task;
::usleep (usec_interval);
}
}
return TASK_NULL;
}
kern_return_t
MachTask::BasicInfo(struct task_basic_info *info)
{
return BasicInfo (TaskPort(), info);
}
kern_return_t
MachTask::BasicInfo(task_t task, struct task_basic_info *info)
{
if (info == NULL)
return KERN_INVALID_ARGUMENT;
DNBError err;
mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
err = ::task_info (task, TASK_BASIC_INFO, (task_info_t)info, &count);
const bool log_process = DNBLogCheckLogBit(LOG_TASK);
if (log_process || err.Fail())
err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => %u )", task, info, count);
if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) && err.Success())
{
float user = (float)info->user_time.seconds + (float)info->user_time.microseconds / 1000000.0f;
float system = (float)info->user_time.seconds + (float)info->user_time.microseconds / 1000000.0f;
DNBLogThreaded ("task_basic_info = { suspend_count = %i, virtual_size = 0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, system_time = %f }",
info->suspend_count,
(uint64_t)info->virtual_size,
(uint64_t)info->resident_size,
user,
system);
}
return err.Error();
}
bool
MachTask::IsValid () const
{
return MachTask::IsValid(TaskPort());
}
bool
MachTask::IsValid (task_t task)
{
if (task != TASK_NULL)
{
struct task_basic_info task_info;
return BasicInfo(task, &task_info) == KERN_SUCCESS;
}
return false;
}
bool
MachTask::StartExceptionThread(DNBError &err)
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
task_t task = TaskPortForProcessID(err);
if (MachTask::IsValid(task))
{
mach_port_t task_self = mach_task_self ();
err = ::mach_port_allocate (task_self, MACH_PORT_RIGHT_RECEIVE, &m_exception_port);
if (err.Fail())
return false;
err = ::mach_port_insert_right (task_self, m_exception_port, m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
if (err.Fail())
return false;
SaveExceptionPortInfo();
if (m_exc_port_info.mask == 0)
{
err.SetErrorString("failed to get exception port info");
return false;
}
err = ::task_set_exception_ports (task, m_exc_port_info.mask, m_exception_port, EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
{
err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior = 0x%8.8x, new_flavor = 0x%8.8x )",
task,
m_exc_port_info.mask,
m_exception_port,
(EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
THREAD_STATE_NONE);
}
if (err.Fail())
return false;
err = ::pthread_create (&m_exception_thread, NULL, MachTask::ExceptionThread, this);
return err.Success();
}
else
{
DNBLogError("MachTask::%s (): task invalid, exception thread start failed.", __FUNCTION__);
}
return false;
}
kern_return_t
MachTask::ShutDownExcecptionThread()
{
DNBError err;
err = RestoreExceptionPortInfo();
mach_port_t exception_port = m_exception_port;
m_exception_port = NULL;
err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)", m_exception_thread);
mach_port_t task_self = mach_task_self ();
err = ::mach_port_deallocate (task_self, exception_port);
if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )", task_self, exception_port);
return err.Error();
}
void *
MachTask::ExceptionThread (void *arg)
{
if (arg == NULL)
return NULL;
MachTask *mach_task = (MachTask*) arg;
MachProcess *mach_proc = mach_task->Process();
DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__, arg);
uint32_t num_exceptions_received = 0;
DNBError err;
task_t task = mach_task->TaskPort();
mach_msg_timeout_t periodic_timeout = 0;
#ifdef WITH_SPRINGBOARD
mach_msg_timeout_t watchdog_elapsed = 0;
mach_msg_timeout_t watchdog_timeout = 60 * 1000;
pid_t pid = mach_proc->ProcessID();
CFReleaser<SBSWatchdogAssertionRef> watchdog;
if (mach_proc->ProcessUsingSpringBoard())
{
watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p", pid, watchdog.get());
if (watchdog.get())
{
::SBSWatchdogAssertionRenew (watchdog.get());
CFTimeInterval watchdogRenewalInterval = ::SBSWatchdogAssertionGetRenewalInterval (watchdog.get());
DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds", watchdog.get(), watchdogRenewalInterval);
if (watchdogRenewalInterval > 0.0)
{
watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
if (watchdog_timeout > 3000)
watchdog_timeout -= 1000; else if (watchdog_timeout > 1000)
watchdog_timeout -= 250; }
}
if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
periodic_timeout = watchdog_timeout;
}
#endif // #ifdef WITH_SPRINGBOARD
while (mach_task->ExceptionPortIsValid())
{
::pthread_testcancel ();
MachException::Message exception_message;
if (num_exceptions_received > 0)
{
err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
}
else if (periodic_timeout > 0)
{
err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, periodic_timeout);
}
else
{
err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
}
if (err.Error() == MACH_RCV_INTERRUPTED)
{
if (!mach_task->ExceptionPortIsValid())
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
break;
}
if (MachTask::IsValid(task))
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "interrupted, but task still valid, continuing...");
continue;
}
else
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
mach_proc->SetState(eStateExited);
break;
}
}
else if (err.Error() == MACH_RCV_TIMED_OUT)
{
if (num_exceptions_received > 0)
{
num_exceptions_received = 0;
mach_proc->ExceptionMessageBundleComplete();
if (MachTask::IsValid(task))
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
continue;
}
else
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
mach_proc->SetState(eStateExited);
break;
}
continue;
}
#ifdef WITH_SPRINGBOARD
if (watchdog.get())
{
watchdog_elapsed += periodic_timeout;
if (watchdog_elapsed >= watchdog_timeout)
{
DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )", watchdog.get());
::SBSWatchdogAssertionRenew (watchdog.get());
watchdog_elapsed = 0;
}
}
#endif
}
else if (err.Error() != KERN_SUCCESS)
{
DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something about it??? nah, continuing for now...");
}
else
{
if (exception_message.CatchExceptionRaise(task))
{
++num_exceptions_received;
mach_proc->ExceptionMessageReceived(exception_message);
}
}
}
#ifdef WITH_SPRINGBOARD
if (watchdog.get())
{
DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)", watchdog.get());
::SBSWatchdogAssertionRelease (watchdog.get());
}
#endif // #ifdef WITH_SPRINGBOARD
DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...", __FUNCTION__, arg);
return NULL;
}
struct hack_task_dyld_info {
mach_vm_address_t all_image_info_addr;
mach_vm_size_t all_image_info_size;
};
nub_addr_t
MachTask::GetDYLDAllImageInfosAddress (DNBError& err)
{
struct hack_task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
task_t task = TaskPortForProcessID (err);
if (err.Success())
{
err = ::task_info (task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
if (err.Success())
{
return dyld_info.all_image_info_addr;
}
}
return INVALID_NUB_ADDRESS;
}
nub_addr_t
MachTask::AllocateMemory (size_t size, uint32_t permissions)
{
mach_vm_address_t addr;
task_t task = TaskPort();
if (task == TASK_NULL)
return INVALID_NUB_ADDRESS;
DNBError err;
err = ::mach_vm_allocate (task, &addr, size, TRUE);
if (err.Error() == KERN_SUCCESS)
{
vm_prot_t mach_prot = VM_PROT_NONE;
if (permissions & eMemoryPermissionsReadable)
mach_prot |= VM_PROT_READ;
if (permissions & eMemoryPermissionsWritable)
mach_prot |= VM_PROT_WRITE;
if (permissions & eMemoryPermissionsExecutable)
mach_prot |= VM_PROT_EXECUTE;
err = ::mach_vm_protect (task, addr, size, 0, mach_prot);
if (err.Error() == KERN_SUCCESS)
{
m_allocations.insert (std::make_pair(addr, size));
return addr;
}
::mach_vm_deallocate (task, addr, size);
}
return INVALID_NUB_ADDRESS;
}
nub_bool_t
MachTask::DeallocateMemory (nub_addr_t addr)
{
task_t task = TaskPort();
if (task == TASK_NULL)
return false;
allocation_collection::iterator pos, end = m_allocations.end();
for (pos = m_allocations.begin(); pos != end; pos++)
{
if ((*pos).first == addr)
{
m_allocations.erase(pos);
#define ALWAYS_ZOMBIE_ALLOCATIONS 0
if (ALWAYS_ZOMBIE_ALLOCATIONS || getenv ("DEBUGSERVER_ZOMBIE_ALLOCATIONS"))
{
::mach_vm_protect (task, (*pos).first, (*pos).second, 0, VM_PROT_NONE);
return true;
}
else
return ::mach_vm_deallocate (task, (*pos).first, (*pos).second) == KERN_SUCCESS;
}
}
return false;
}
static void foundStackLog(mach_stack_logging_record_t record, void *context) {
*((bool*)context) = true;
}
bool
MachTask::HasMallocLoggingEnabled ()
{
bool found = false;
__mach_stack_logging_enumerate_records(m_task, 0x0, foundStackLog, &found);
return found;
}
struct history_enumerator_impl_data
{
MachMallocEvent *buffer;
uint32_t *position;
uint32_t count;
};
static void history_enumerator_impl(mach_stack_logging_record_t record, void* enum_obj)
{
history_enumerator_impl_data *data = (history_enumerator_impl_data*)enum_obj;
if (*data->position >= data->count)
return;
data->buffer[*data->position].m_base_address = record.address;
data->buffer[*data->position].m_size = record.argument;
data->buffer[*data->position].m_event_id = record.stack_identifier;
data->buffer[*data->position].m_event_type = record.type_flags == stack_logging_type_alloc ? eMachMallocEventTypeAlloc :
record.type_flags == stack_logging_type_dealloc ? eMachMallocEventTypeDealloc :
eMachMallocEventTypeOther;
*data->position+=1;
}
bool
MachTask::EnumerateMallocRecords (MachMallocEvent *event_buffer,
uint32_t buffer_size,
uint32_t *count)
{
return EnumerateMallocRecords(0,
event_buffer,
buffer_size,
count);
}
bool
MachTask::EnumerateMallocRecords (mach_vm_address_t address,
MachMallocEvent *event_buffer,
uint32_t buffer_size,
uint32_t *count)
{
if (!event_buffer || !count)
return false;
if (buffer_size == 0)
return false;
*count = 0;
history_enumerator_impl_data data = { event_buffer, count, buffer_size };
__mach_stack_logging_enumerate_records(m_task, address, history_enumerator_impl, &data);
return (*count > 0);
}
bool
MachTask::EnumerateMallocFrames (MachMallocEventId event_id,
mach_vm_address_t *function_addresses_buffer,
uint32_t buffer_size,
uint32_t *count)
{
if (!function_addresses_buffer || !count)
return false;
if (buffer_size == 0)
return false;
__mach_stack_logging_frames_for_uniqued_stack(m_task, event_id, &function_addresses_buffer[0], buffer_size, count);
*count -= 1;
if (function_addresses_buffer[*count-1] < vm_page_size)
*count -= 1;
return (*count > 0);
}