Question

In How do I recover from EXC_BAD_ACCESS?, I figured out how to recover from an EXC_BAD_ACCESS, but I had the badly accessed pointer stored in a global. Obviously, this won't scale. When I run the code in the iOS Simulator (i386), I can see faultvaddr register in the Exception State Registers section of the debugger when inside my catch_exception_raise function. However, its value isn't the same or close to pointer returned from vm_allocate. Is there a way to get this value dynamically?

Given the catch_exception_raise function below, how would I discover the address that caused the EXC_BAD_ACCESS?

kern_return_t
catch_exception_raise(mach_port_t exception_port,
                      mach_port_t thread,
                      mach_port_t task,
                      exception_type_t exception,
                      exception_data_t code_vector,
                      mach_msg_type_number_t code_count)
{
    fprintf(stderr, "catch_exception_raise %d\n", exception);
    return KERN_SUCCESS;
}
Was it helpful?

Solution

There is a great amount of detail on that in the OS X and iOS Internals book (http://www.newosxbook.com). Listing 11-21 (ibid) in the book actually shows sample code to do so. In a nutshell, you've two options:

A) look at the exception itself from the exception data - convert the state to an arm_thread_state, something like so:

struct arm_thread_state *atsh = &exc.old_state;
printf ("CPSR is %p, PC is %p, etc.\n", atsh->cpsr, atsh->pc);

Or

B) call thread_get_state to the thread port (since you have that right there as argument #2), and get pc (the instruction pointer) or any of the other registers

EDIT

I'm not sure how to make A) work, but the following works (found here) for B) on the 32-bit iOS Simulator. I'm not sure what the arm register equivalent is for __faultvaddr, so you'd have to figure that out before trying arm.

// types from thread_status.h
x86_exception_state32_t x86_exception_state32; 
mach_msg_type_number_t sc = x86_EXCEPTION_STATE32_COUNT;

thread_get_state(thread,
                 x86_EXCEPTION_STATE32,
                 (thread_state_t)&x86_exception_state32,
                 &sc);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top