esaulenka / ghidra_STM8

Ghidra STM8 processor module
Apache License 2.0
23 stars 8 forks source link

Error when tracing and emulating the instruction [90 fd] = > CALL (Y) #9

Open konvikkor opened 3 months ago

konvikkor commented 3 months ago

Error when tracing and emulating the instruction [90 fd] = > CALL (Y) debugging at the chip level and in the Ghidra program showed that the instruction in the STM8S controller works differently than in the documentation. How it works CALL (Y) is equivalent to CALL Y without a request to address a jump by the value of register Y and the same with register X

GaryOderNichts commented 2 months ago

Something seems to be wrong with the emitted PCode for CALL (X)/CALL (Y) and JP (X)/ JP (Y). All of those instructions always attempt to branch to address 0xeb80 resulting in issues with the decompile view: image image image image

esaulenka commented 2 months ago

Looks like 'my' binary had only CALL <fixed address> instructions, but all others seems to be broken. Could you share some binary samples for debugging?

konvikkor commented 2 months ago

image All compilers know this problem and make such stubs using a register, but even here 3 bytes are written to the stack instead of 2

And also the transition must be not by the pointer but by the value of the register, the value of the register is the address of the beginning of the function

GaryOderNichts commented 2 months ago

Here's an example compiled with sdcc -mstm8 main.c --out-fmt-elf which emits both a CALL (X) and JP (X) instruction:

int test_function(void) {
    return 123;
}

int main(void) {
    volatile int(*function)(void) = test_function;
    function();
    return function();
}

main.elf.zip

What @konvikkor mentioned seems to be correct: image The function address gets loaded into X and CALL (X) then jumps directly to that function address.

esaulenka commented 2 months ago

Could you check that this fix haven't break anything? https://github.com/esaulenka/ghidra_STM8/tree/fix_CALL_Y

And, maybe, you also have another CALL/JP cases with variable destination like JP [addr] or CALL offset, X ? All these thing seems also was broken.

GaryOderNichts commented 2 months ago

I'm getting the following error when using that branch with the test binary I uploaded: image