我們現在芯片被美國卡脖子,所以RISC-V是大勢所趨。華爲鴻蒙提供的編譯器(https://repo.huaweicloud.com/harmonyos/compiler/)裏也有RISC-V。雖然現在硬件資源比較少,但是通過軟件模擬環境,可以提早做好準備。
RISC-V GNU Toolchain
源碼獲取
要體驗RISC-V,首先需要安裝交叉編譯器。然而國內的網絡很差,想要在GitHub上拿到源碼(https://github.com/riscv/riscv-gnu-toolchain)編譯非常困難。比較慶幸的是Gitee上有鏡像(https://gitee.com/mirrors/riscv-gnu-toolchain),每天同步一次。
獲取源碼:
git clone https://gitee.com/mirrors/riscv-gnu-toolchain.git
cd riscv-gnu-toolchain
git submodule update --init --recursive
然而在我通過Gitee拿代碼的時候,子模塊下載速度依然非常慢,特別是QEMU裏的一個子模塊。於是我把QEMU從同步中刪除了,因爲不影響編譯:
git rm --cached QEMU
git submodule update --init --recursive
考慮到下載速度,我把拿到的所有代碼放到Gitee上(https://gitee.com/yushulx/riscv-gnu-toolchain)。這個代碼庫不做更新,只提供給網絡差,又需要體驗RISC-V的人。需要拿最新代碼就去GitHub或者Gitee鏡像。
編譯安裝
接下來就按照官方教程編譯。
依賴工具
Ubuntu
$ sudo apt-get install autoconf automake autotools-dev curl python3 libmpc-dev libmpfr-dev libgmp-dev gawk build-essential bison flex texinfo gperf libtool patchutils bc zlib1g-dev libexpat-dev
Fedora/CentOS/RHEL OS
$ sudo yum install autoconf automake python3 libmpc-devel mpfr-devel gmp-devel gawk bison flex texinfo patchutils gcc gcc-c++ zlib-devel expat-devel
Arch Linux
$ pacman -Syyu autoconf automake curl python3 mpc mpfr gmp gawk build-essential bison flex texinfo gperf libtool patchutils bc zlib expat
OS X
$ brew install python3 gawk gnu-sed gmp mpfr libmpc isl zlib expat
編譯GCC
編譯riscv64-unknown-elf-gcc
:
./configure --prefix=/opt/riscv
sudo make
編譯64-bitriscv64-unknown-linux-gnu-gcc
:
./configure --prefix=/opt/riscv
sudo make linux
編譯32-bit:
./configure --prefix=/opt/riscv --with-arch=rv32gc --with-abi=ilp32d
sudo make linux
編譯32-bit和64-bit:
./configure --prefix=/opt/riscv --enable-multilib
sudo make linux
這兩個gcc的區別在於,elf-gcc是靜態鏈接,linux-gnu-gcc是動態鏈接。
RISC-V運行環境
Simulator和Emulator的不同之處在於Emulator提供的是一個完整的模擬環境。
Simulator
首先編譯安裝pk: https://github.com/riscv/riscv-pk。
然後編譯安裝spike:https://github.com/riscv/riscv-isa-sim
編譯程序
riscv64-unknown-elf-gcc -o hello hello.c
運行
spike $(which pk) hello
注意,如果用riscv64-unknown-linux-gnu-gcc
編譯,運行會報錯:
bbl loader
not a statically linked ELF program
Emulator
下載安裝QEMU https://www.qemu.org/download/#source
參考教程運行模擬環境:https://wiki.qemu.org/Documentation/Platforms/RISCV
另外也可以使用tinyemu: https://bellard.org/tinyemu/
Fedora鏡像獲取:https://dl.fedoraproject.org/pub/alt/risc-v/repo/virt-builder-images/images/
解壓鏡像:
unxz Fedora-Minimal-Rawhide-*-sda.raw.xz
啓動模擬器:
qemu-system-riscv64 \
-nographic \
-machine virt \
-smp 4 \
-m 2G \
-kernel Fedora-Minimal-Rawhide-*-fw_payload-uboot-qemu-virt-smode.elf \
-bios none \
-object rng-random,filename=/dev/urandom,id=rng0 \
-device virtio-rng-device,rng=rng0 \
-device virtio-blk-device,drive=hd0 \
-drive file=Fedora-Minimal-Rawhide-20200108.n.0-sda.raw,format=raw,id=hd0 \
-device virtio-net-device,netdev=usernet \
-netdev user,id=usernet,hostfwd=tcp::10000-:22
登錄用戶名riscv
,密碼fedora_rocks!
拷貝程序到模擬器中:
scp <user-name>@<ip address>:/<file path> ./
在模擬器環境中可以正常運行riscv64-unknown-elf-gcc
和riscv64-unknown-linux-gnu-gcc
編譯出來的程序。