Using assembly code, embedded in C code


I would like to get your help please,

I’m trying to convert c function to assembly and use the assembly code instead c-code function.
I convert the c function to asm by using -S, and use the generated ASM code as assembly function

The problem that i’m getting compilation error while the asm code trying to access array, that defines in the C-code

error message : relocation truncated to fit: R_RISCV_HI20 against symbol `sbox’ defined in .rodata.sbox section in

The final code looks like this
int main {
const unsigned char sbox[256] = {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76}

myasm();    //call asm code 


myasm.S looks like this

.globl myasm
lui a4,%hi(sbox)
addi a4,a4,%lo(sbox)

any idea how can i fix this, in a way that the ASM code will recognize the array defined in c-code?

thank you !

Your code sample doesn’t compile, and is defining sbox inside main, which means it will end up on the stack, so there is no symbol for the assembly code to refer to. Move that definition outside main to get a symbol. But the error mentions .rodata.sbox which suggests the real code is substantially different than your example code.

In general, I need an example that can be used to reproduce the error to see what is really going on. Otherwise I have to make an educated guess.

The R_RISCV_HI20 error means that the symbol in too far away from the code for the %hi relocation to reach. %hi requires that both the symbol and the code referencing it are in the low 2GB of the address space. Perhaps you are putting the symbol or code somewhere else in the address space?

If the code and symbol are within 2GB of each other, but not in the lowest 2GB of address space, then you can use auipc and %pcrel_hi along with %pcrel_lo. However, it would be easier to just use the lla macro. This assumes you are compiling using -mcmodel=medany which allows code outside the low 2GB of address space.

I would suggest looking at
though you may want to read the entire blog series.