unicorn-engine / unicorn

Unicorn CPU emulator framework (ARM, AArch64, M68K, Mips, Sparc, PowerPC, RiscV, S390x, TriCore, X86)
http://www.unicorn-engine.org
GNU General Public License v2.0
7.33k stars 1.31k forks source link

UC_HOOK_INTR not observed #1940

Closed keroblabs closed 2 months ago

keroblabs commented 2 months ago

I'm emulating ARM Cortex M4 on Mac M1 (ARM64 library build) and UC_HOOK_INTR was not observed.

The emulator is initialised with the following:

uc_open( UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS, &uc ); uc_ctl_set_cpu_model( uc, UC_CPU_ARM_CORTEX_M4 ); uc_hook_add( uc, &intr_hook, UC_HOOK_INTR, interrupt_hook, NULL, 1, 0 );

The UC_HOOK_INTR is set to interrupt_hook

The exception is entered manually according to armV7 reference manual; 8 byte alignment is ignored - I suppose this is irrelevant for Unicorn Engine. Please note this code is not complete and assume the execution is branched to the interrupt vector as expected:

uc_reg_read( uc, UC_ARM_REG_SP, &stack_pointer ); save_aapcs_context_registers( context_frame ); // Save R0-R3, R12, LR, PC and CPSR to stack frame stack_pointer -= CONTEXT_FRAME_SIZE; uc_mem_write( uc, stack_pointer, stack_frame, CONTEXT_FRAME_SIZE ); uc_reg_write( uc, UC_ARM_REG_SP, &stack_pointer ); uc_reg_write( uc, UC_ARM_REG_IPSR, &vector ); // set the interrupt vector in IPSR uc_reg_write( uc, UC_ARM_REG_LR, &current_pc ); // set the return of interrupt address. This is "PC+1" for Thumb uc_reg_write( uc, UC_ARM_REG_PC, &intr_vector_pc); // set the PC to start in the ISR. This is "PC+1" for Thumb uc_emu_start( uc_arm, intr_vector_pc, 0, 0, 32 );

The guest executes the following instruction at the end of the ISR. LR contains the correct return address.

8002902: 4770 bx lr

The execution returns to the correct address but the function interrupt_hook is never called at any point. Is there anything missing in the emulator initialisation?

Cheers.

keroblabs commented 2 months ago

Sorry, I found it.

uc_reg_write( uc, UC_ARM_REG_LR, &current_pc ); // set the return of interrupt address. This is "PC+1" for Thumb

On exception entry, LR should be set to 0xFFFFFFFD, the hook is called and the the context should be restored.