Esempio n. 1
0
//----------------------------------------------------------------------
// MachTask::AllocateMemory
//----------------------------------------------------------------------
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)
    {
        // Set the protections:
        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;
}
Esempio n. 2
0
kern_return_t
MachException::PortInfo::Save (task_t task)
{
    DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE, "MachException::PortInfo::Save ( task = 0x%4.4x )", task);
    // Be careful to be able to have debugserver built on a newer OS than what
    // it is currently running on by being able to start with all exceptions
    // and back off to just what is supported on the current system
    DNBError err;

    mask = EXC_MASK_ALL;

    count = (sizeof (ports) / sizeof (ports[0]));
    err = ::task_get_exception_ports (task, mask, masks, &count, ports, behaviors, flavors);
    if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
        err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, maskCnt => %u, ports, behaviors, flavors )", task, mask, count);

    if (err.Error() == KERN_INVALID_ARGUMENT && mask != PREV_EXC_MASK_ALL)
    {
        mask = PREV_EXC_MASK_ALL;
        count = (sizeof (ports) / sizeof (ports[0]));
        err = ::task_get_exception_ports (task, mask, masks, &count, ports, behaviors, flavors);
        if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
            err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, maskCnt => %u, ports, behaviors, flavors )", task, mask, count);
    }
    if (err.Fail())
    {
        mask = 0;
        count = 0;
    }
    return err.Error();
}
Esempio n. 3
0
//----------------------------------------------------------------------
// MachTask::Resume
//----------------------------------------------------------------------
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())
    {
		// task_resume isn't counted like task_suspend calls are, are, so if the 
		// task is not suspended, don't try and resume it since it is already 
		// running
		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();
}
Esempio n. 4
0
kern_return_t
MachTask::ShutDownExcecptionThread()
{
    DNBError err;

    err = RestoreExceptionPortInfo();

    // NULL our our exception port and let our exception thread exit
    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);

    // Deallocate our exception port that we used to track our child process
    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);
    exception_port = NULL;

    return err.Error();
}
Esempio n. 5
0
//----------------------------------------------------------------------
// MachTask::BasicInfo
//----------------------------------------------------------------------
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();
}
Esempio n. 6
0
//----------------------------------------------------------------------
// MachTask::Suspend
//----------------------------------------------------------------------
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();
}
Esempio n. 7
0
kern_return_t
MachException::PortInfo::Save (task_t task)
{
    count = (sizeof (ports) / sizeof (ports[0]));
    DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE, "MachException::PortInfo::Save ( task = 0x%4.4x )", task);
    DNBError err;
    err = ::task_get_exception_ports (task, EXC_MASK_ALL, masks, &count, ports, behaviors, flavors);
    if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
        err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, maskCnt => %u, ports, behaviors, flavors )", task, EXC_MASK_ALL, count);
    if (err.Fail())
        count = 0;
    return err.Error();
}
Esempio n. 8
0
kern_return_t
MachException::Message::Receive(mach_port_t port, mach_msg_option_t options, mach_msg_timeout_t timeout, mach_port_t notify_port)
{
    DNBError err;
    const bool log_exceptions = DNBLogCheckLogBit(LOG_EXCEPTIONS);
    mach_msg_timeout_t mach_msg_timeout = options & MACH_RCV_TIMEOUT ? timeout : 0;
    if (log_exceptions && ((options & MACH_RCV_TIMEOUT) == 0))
    {
        // Dump this log message if we have no timeout in case it never returns
        DNBLogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = %#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, option = %#x, send_size = %u, rcv_size = %u, rcv_name = %#x, timeout = %u, notify = %#x)",
                exc_msg.hdr.msgh_bits,
                exc_msg.hdr.msgh_size,
                exc_msg.hdr.msgh_remote_port,
                exc_msg.hdr.msgh_local_port,
                exc_msg.hdr.msgh_reserved,
                exc_msg.hdr.msgh_id,
                options,
                0,
                sizeof (exc_msg.data),
                port,
                mach_msg_timeout,
                notify_port);
    }

    err = ::mach_msg (&exc_msg.hdr,
                      options,                  // options
                      0,                        // Send size
                      sizeof (exc_msg.data),    // Receive size
                      port,                     // exception port to watch for exception on
                      mach_msg_timeout,         // timeout in msec (obeyed only if MACH_RCV_TIMEOUT is ORed into the options parameter)
                      notify_port);

    // Dump any errors we get
    if (log_exceptions)
    {
        err.LogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = %#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, option = %#x, send_size = %u, rcv_size = %u, rcv_name = %#x, timeout = %u, notify = %#x)",
            exc_msg.hdr.msgh_bits,
            exc_msg.hdr.msgh_size,
            exc_msg.hdr.msgh_remote_port,
            exc_msg.hdr.msgh_local_port,
            exc_msg.hdr.msgh_reserved,
            exc_msg.hdr.msgh_id,
            options,
            0,
            sizeof (exc_msg.data),
            port,
            mach_msg_timeout,
            notify_port);
    }
    return err.Error();
}
Esempio n. 9
0
//----------------------------------------------------------------------
// MachTask::TaskPortForProcessID
//----------------------------------------------------------------------
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;

			// Sleep a bit and try again
			::usleep (usec_interval);
		}
	}
	return TASK_NULL;
}
Esempio n. 10
0
kern_return_t
MachException::PortInfo::Restore (task_t task)
{
    DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE, "MachException::PortInfo::Restore( task = 0x%4.4x )", task);
    uint32_t i = 0;
    DNBError err;
    if (count > 0)
    {
        for (i = 0; i < count; i++)
        {
            err = ::task_set_exception_ports (task, masks[i], ports[i], behaviors[i], flavors[i]);
            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, masks[i], ports[i], behaviors[i], flavors[i]);
                // Bail if we encounter any errors
            }

            if (err.Fail())
                break;
        }
    }
    count = 0;
    return err.Error();
}
Esempio n. 11
0
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);

    // We keep a count of the number of consecutive exceptions received so
    // we know to grab all exceptions without a timeout. We do this to get a
    // bunch of related exceptions on our exception port so we can process
    // then together. When we have multiple threads, we can get an exception
    // per thread and they will come in consecutively. The main loop in this
    // thread can stop periodically if needed to service things related to this
    // process.
    // flag set in the options, so we will wait forever for an exception on
    // our exception port. After we get one exception, we then will use the
    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
    // exceptions for our process. After we have received the last pending
    // exception, we will get a timeout which enables us to then notify
    // our main thread that we have an exception bundle avaiable. We then wait
    // for the main thread to tell this exception thread to start trying to get
    // exceptions messages again and we start again with a mach_msg read with
    // infinite timeout.
    uint32_t num_exceptions_received = 0;
    DNBError err;
    task_t task = mach_task->TaskPort();
    mach_msg_timeout_t periodic_timeout = 0;

#if defined (__arm__)
    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())
    {
        // Request a renewal for every 60 seconds if we attached using SpringBoard
        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;   // Give us a second to renew our timeout
                else if (watchdog_timeout > 1000)
                    watchdog_timeout -= 250;    // Give us a quarter of a second to renew our timeout
            }
        }
        if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
            periodic_timeout = watchdog_timeout;
    }
#endif  // #if defined (__arm__)

    while (mach_task->ExceptionPortIsValid())
    {
        ::pthread_testcancel ();

        MachException::Message exception_message;


        if (num_exceptions_received > 0)
        {
            // No timeout, just receive as many exceptions as we can since we already have one and we want
            // to get all currently available exceptions for this task
            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
        }
        else if (periodic_timeout > 0)
        {
            // We need to stop periodically in this loop, so try and get a mach message with a valid timeout (ms)
            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, periodic_timeout);
        }
        else
        {
            // We don't need to parse all current exceptions or stop periodically,
            // just wait for an exception forever.
            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
        }

        if (err.Error() == MACH_RCV_INTERRUPTED)
        {
            // If we have no task port we should exit this thread
            if (!mach_task->ExceptionPortIsValid())
            {
                DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
                break;
            }

            // Make sure our task is still valid
            if (MachTask::IsValid(task))
            {
                // Task is still ok
                DNBLogThreadedIf(LOG_EXCEPTIONS, "interrupted, but task still valid, continuing...");
                continue;
            }
            else
            {
                DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
                mach_proc->SetState(eStateExited);
                // Our task has died, exit the thread.
                break;
            }
        }
        else if (err.Error() == MACH_RCV_TIMED_OUT)
        {
            if (num_exceptions_received > 0)
            {
                // We were receiving all current exceptions with a timeout of zero
                // it is time to go back to our normal looping mode
                num_exceptions_received = 0;

                // Notify our main thread we have a complete exception message
                // bundle available.
                mach_proc->ExceptionMessageBundleComplete();

                // in case we use a timeout value when getting exceptions...
                // Make sure our task is still valid
                if (MachTask::IsValid(task))
                {
                    // Task is still ok
                    DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
                    continue;
                }
                else
                {
                    DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
                    mach_proc->SetState(eStateExited);
                    // Our task has died, exit the thread.
                    break;
                }
                continue;
            }

#if defined (__arm__)
            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...");
            // TODO: notify of error?
        }
        else
        {
            if (exception_message.CatchExceptionRaise())
            {
                ++num_exceptions_received;
                mach_proc->ExceptionMessageReceived(exception_message);
            }
        }
    }

#if defined (__arm__)
    if (watchdog.get())
    {
        // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel when we
        // all are up and running on systems that support it. The SBS framework has a #define
        // that will forward SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel for now
        // so it should still build either way.
        DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)", watchdog.get());
        ::SBSWatchdogAssertionRelease (watchdog.get());
    }
#endif  // #if defined (__arm__)

    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...", __FUNCTION__, arg);
    return NULL;
}
Esempio n. 12
0
kern_return_t
MachException::Message::Reply(MachProcess *process, int signal)
{
    // Reply to the exception...
    DNBError err;

    // If we had a soft signal, we need to update the thread first so it can
    // continue without signaling
    int soft_signal = state.SoftSignal();
    if (soft_signal)
    {
        int state_pid = -1;
        if (process->Task().TaskPort() == state.task_port)
        {
            // This is our task, so we can update the signal to send to it
            state_pid = process->ProcessID();
            soft_signal = signal;
        }
        else
        {
            err = ::pid_for_task(state.task_port, &state_pid);
        }

        assert (state_pid != -1);
        if (state_pid != -1)
        {
            errno = 0;
            if (::ptrace (PT_THUPDATE, state_pid, (caddr_t)state.thread_port, soft_signal) != 0)
                err.SetError(errno, DNBError::POSIX);
            else
                err.Clear();

            if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
                err.LogThreaded("::ptrace (request = PT_THUPDATE, pid = 0x%4.4x, tid = 0x%4.4x, signal = %i)", state_pid, state.thread_port, soft_signal);
        }
    }

    DNBLogThreadedIf(LOG_EXCEPTIONS, "::mach_msg ( msg->{bits = %#x, size = %u, remote_port = %#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, option = %#x, send_size = %u, rcv_size = %u, rcv_name = %#x, timeout = %u, notify = %#x)",
        reply_msg.hdr.msgh_bits,
        reply_msg.hdr.msgh_size,
        reply_msg.hdr.msgh_remote_port,
        reply_msg.hdr.msgh_local_port,
        reply_msg.hdr.msgh_reserved,
        reply_msg.hdr.msgh_id,
        MACH_SEND_MSG | MACH_SEND_INTERRUPT,
        reply_msg.hdr.msgh_size,
        0,
        MACH_PORT_NULL,
        MACH_MSG_TIMEOUT_NONE,
        MACH_PORT_NULL);

    err = ::mach_msg (  &reply_msg.hdr,
                        MACH_SEND_MSG | MACH_SEND_INTERRUPT,
                        reply_msg.hdr.msgh_size,
                        0,
                        MACH_PORT_NULL,
                        MACH_MSG_TIMEOUT_NONE,
                        MACH_PORT_NULL);

    if (err.Fail())
    {
        if (err.Error() == MACH_SEND_INTERRUPTED)
        {
            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
                err.LogThreaded("::mach_msg() - send interrupted");
            // TODO: keep retrying to reply???
        }
        else
        {
            if (state.task_port == process->Task().TaskPort())
            {
                if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
                    err.LogThreaded("::mach_msg() - failed (task)");
                abort ();
            }
            else
            {
                if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
                    err.LogThreaded("::mach_msg() - failed (child of task)");
            }
        }
    }

    return err.Error();
}