I’m writing code targeting ARM Cortex-A on Android devices (using GNU assembler and compiler), and I’m trying to interface between Assembly and C. In particular, I’m interested in calling functions written in C from Assembly. I tried many things, including the .extern directive, declaring C functions with asm and __asm__ and so on, but none of them worked, so I’m looking for a minimal example of doing so. A reference to such example would be just as welcome.
I’m writing code targeting ARM Cortex-A on Android devices (using GNU assembler and compiler),
Share
You need to read the ARM ARM and/or know the instruction set is all, normally you would want to do something like this
You can try this yourself. for gnu as and gcc this works just fine it should also work just fine if you use clang to get the c code to an object and gnu as for assembler. Not sure what you are using.
The problem with the above is bl has a limited reach,
knowing that the bl instruction sets the link register to the instruction after the bl instruction, then if you read about the program counter register:
so if you make your asm look like this:
you get
The assembler will reserve a memory location, within reach of the ldr pc, instruction (if possible, otherwise generate an error) where it will place the full 32 bit address for the instruction. the linker will later fill in this address with the external address. that way you can reach any address in the address space.
if you dont want to play assembler games like that and want to be in control then you create the location to keep the address of the function and load it into the pc yourself:
compiled:
Lastly if you want to move into the modern ARM world where ARM and thumb is mixed or can be (for example use bx lr instead of mov pc,lr) then you will want to use bx
of course you need another register to do that and remember to push and pop your link register and the other register before and after your call to C if you want to preserve them.