RiscV.RARS.webp

RARS,即 RISC-V 汇编程序、模拟器和运行时,将汇编和模拟 RISC-V 汇编语言程序的执行。 它的主要目标是为开始使用 RISC-V 的人们提供一个有效的开发环境。

B站视频 RARS RISC-V 汇编器和运行时模拟器, 编写Hello World源码

创建 Hello World

我们不用访问 C 标准库,所以jiu调用 write(fd,buffer,len) 直接映射到 Linux 系统调用。 并且让我们将字符串的定义提升到一个全局变量中,因为汇编语言不允许字符串作为参数。

这给我们留下了一些可直接翻译的 C 代码:

char* str = "Hello World!
";
int main(){
    write(1,str,13);
}

第一行可以翻译成 RISC-V 汇编:

.data
str:  .string "Hello World!
" 

C语言 main 函数 和 系统调用 write 函数,可以翻译成 RISC-V 汇编语句

.text
main:
li a0, 1
la a1, str
li a2, 13
li a7, 64
ecall

加上注释和 exit 系统调用,完成完整的 RISC-V 汇编源码

.data # Tell the assembler we are defining data not code
         # 告诉汇编器我们定义的是数据而不是代码

str:   # Label this position in memory so it can be referred to in our code
         # 在内存中标记这个位置,以便我们的代码中引用它
  .string "Hello World!
" # Copy the string "Hello World!
" into memory
                                        # 将字符串 "Hello World!
" 复制到内存中

.text # Tell the assembler that we are writing code (text) now
         # 告诉汇编程序我们现在正在编写代码(文本)

main: # Make a label to say where our program should start from
          # 做一个标签来说明我们的程序应该从哪里开始

  li a0, 1   # li means to Load Immediate and we want to load the value 1 into register a0
                  # li 表示立即加载,我们要将值 1 加载到寄存器 a0
  la a1, str # la is similar to li, but works for loading addresses
                    # la 类似于 li,但用于加载地址
  li a2, 13  # like the first line, but with 13. This is the final argument to the system call
                   # 与第一行相似,但带有 13。这是系统调用的最后一个参数
  li a7, 64  # a7 is what determines which system call we are calling and we what to call write (64)
                   # a7 决定了我们正在调用哪个系统调用以及我们调用什么 write (64)
  ecall      # actually issue the call
                # 实际发出syscall

  li a0, 0   # The exit code we will be returning is 0
                  # 我们将返回的退出代码是 0
  li a7, 93  # Again we need to indicate what system call we are making and this time we are calling exit(93)
                  # 我们需要再次指出我们正在进行的系统调用,这次我们调用 exit(93)
  ecall 

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注

© 2024 兰雅VBA代码分享
浙ICP备2021017795号-2 浙公网安备33078102100266号