I am writing a RISC-V assembly program that need to store a word (saved into a register) into a .data segment:
.section .rodata
msg:
.string "Hello World\n"
.section .data
num:
.word 97
.section .text
.global _start
_start:
li a1, 100
sw a1, num
loop:
j loop
But when the program reaches sw a1, num
I get the error "illegal operands `sw a1,num'".
How can I store datas into a memory location inside .data segment? could you give me some hints?
As a general rule of thumb, the assembly that you write into the assembler is its own programming language that just happens to look quite a bit like what's in the RISC-V ISA manual. RISC-V is a pretty simple ISA, so for most instructions there's actually no difference between the syntax of the ISA manual and the syntax accepted by the assembler. The place this starts to break down is when referencing symbols, because while you can fill out the immediate directly in your assembly code you probably want to rely on the linker to do so because you won't know the actual symbol address until link time (and it's likely to change as you modify your program).
In order to enable the linker to fill out symbol addresses in your code, you need to emit relocations from the assembler so the linker can later fill these out. I have a whole blog post on how this works at SiFive's blog, but we just refreshed the website and I can't figure out how to find it :).
In this case you're essentially trying to write assembly that implements the following C code
You've got all the data stuff correct in your original answer, so the only thing to worry about here is how to emit the correct instructions. You have a few options as to how to emit these. One option is to explicitly write each instruction and relocation into your source code, which would look like this
You can generate this assembly from my C code above by compiling with
-mcmodel=medlow -mexplicit-relocs -O3
. The GCC manual defines the other RISC-V backend specific options that control code generation.If you're interested in more details, we have an assembly programmer's manual availiable on GitHub: https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md . It's far from complete, but we'd love to have help either pointing out issues or providing more content.