Skip to content

Instantly share code, notes, and snippets.

@Frank-Buss
Created July 30, 2023 02:58
Show Gist options
  • Save Frank-Buss/aa6aa7d4907335e4a529e8cf3e82f47e to your computer and use it in GitHub Desktop.
Save Frank-Buss/aa6aa7d4907335e4a529e8cf3e82f47e to your computer and use it in GitHub Desktop.
run RISC-V assembler on x86_64 Debian Linux

Run RISC-V assembler programs on Debian Linux

This tutorial shows how to compile and run RISC-V assembler code on Debian Linux systems, which are not running on a RISC-V system (e.g. x86_64).

Install the toolchain and emulator

sudo apt-get install qemu qemu-system-misc qemu-user gcc-riscv64-unknown-elf

Create a hello world program

Save this as hello.s:

.section .data
msg:    .asciz "Hello, World!\n"

.section .text
.globl _start
_start:
    # set up the arguments for write syscall
    li a7, 64         # system call number for write
    li a0, 1          # file descriptor 1 is stdout
    la a1, msg        # pointer to message
    li a2, 14         # length of message string

    # make the system call
    ecall

    # set up the arguments for exit syscall
    li a7, 93         # system call number for exit
    li a0, 0          # exit status code

    # make the system call
    ecall

Compile the program

riscv64-unknown-elf-gcc -nostdlib -o hello hello.s

Alternatively you can do it in 2 steps, first creating an obj file, then linking it to the elf file:

riscv64-unknown-elf-as -o hello.o hello.s
riscv64-unknown-elf-ld -o hello hello.o

Run the program

./hello

You might wonder why you can run the RISC-V program on a x86 system. The reason is that the qemu program registered itself for this type of programs with the binfmt_misc feature of Linux. If there are problems with it, you can also start qemu manually to run the program:

qemu-riscv64 hello

Also note that qemu calls the syscalls of the host operating system. Here is a list of all Linux syscalls:

https://man7.org/linux/man-pages/man2/syscalls.2.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment