rcore-os / rCore-Tutorial

Tutorial for rCore OS step by step (3rd edition)
https://rcore-os.github.io/rCore-Tutorial-deploy/
GNU General Public License v3.0
462 stars 68 forks source link

如何用 RISC-V 汇编打印字符 #50

Closed shiweiwww closed 4 years ago

shiweiwww commented 4 years ago

RISC-V汇编如何在屏幕输出字符串

大致描述问题

如下汇编代码如何正确输出字符串hello world?

代码

.section .text
.global _start
_start:
    lui     a1, %hi(msg)
    addi    a1,a1,%lo(msg)
    #jalr   ra,puts
    call puts
2:  j       2b

.section .rodata
msg:
    .string "hello world\n"
yukiiiteru commented 4 years ago

我用C写了个输出HelloWorld的代码,然后用RISC-V的gcc编译成汇编代码了,结果如下:

    .file   "tmp.c"
    .option nopic
    .text
    .section    .rodata
    .align  3
.LC0:
    .string "Hello, World!"
    .text
    .align  1
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    addi    sp,sp,-16
    .cfi_def_cfa_offset 16
    sd  ra,8(sp)
    sd  s0,0(sp)
    .cfi_offset 1, -8
    .cfi_offset 8, -16
    addi    s0,sp,16
    .cfi_def_cfa 8, 0
    lui a5,%hi(.LC0)
    addi    a0,a5,%lo(.LC0)
    call    puts
    li  a5,0
    mv  a0,a5
    ld  ra,8(sp)
    .cfi_restore 1
    ld  s0,0(sp)
    .cfi_restore 8
    .cfi_def_cfa 2, 16
    addi    sp,sp,16
    .cfi_def_cfa_offset 0
    jr  ra
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (GNU) 10.1.0"
    .section    .note.GNU-stack,"",@progbits

我觉得核心就是

.LC0:
    .string "Hello, World!"

    lui a5,%hi(.LC0)
    addi    a0,a5,%lo(.LC0)
    call    puts

这两部分了

我查了一下RISC-V的手册,a0-a7是传递参数用的,第一个参数应该放在a0吧,你的代码问题可能出现在这。

不过我也没法运行这段代码,不知道结果正确与否,只能帮你到这了

luojia65 commented 4 years ago

如果调用别的函数,a0是第一个参数,由被调用者保存

    .section .text
    .globl main
main:
    la a0, aHelloWorld # 展开为auipc和addi
    call puts

    .section .data
aHelloWorld: 
    .string "Hello World!" # 后面有个\0
shiweiwww commented 4 years ago

感谢两位回答,我试试

shiweiwww commented 4 years ago

https://smist08.wordpress.com/2019/09/07/risc-v-assembly-language-hello-world/ google了下,解决了,用系统调用就行,可以关闭了@ Tuyixiang

sunshaoce commented 4 years ago
    .section    .rodata
.LC0:
    .string "hello world!"
    .text
    .globl  main
main:
    lui a5,%hi(.LC0)
    addi    a0,a5,%lo(.LC0)
    call    puts