在主機上搭建WAMR的核心是構建iwasm執行器,另一種方式是以運行時庫libiwasm.a的形式調用,本文不介紹這個方式。
1. 主機環境準備(以 Ubuntu 20.04 為例)
1.1 構建 wamrc AOT 編譯器
wasm 二進制文件和 AOT 文件都受 iwasm 支持。wamrc AOT 編譯器是將 wasm 二進制文件編譯成 AOT 文件,也可以由 iwasm 運行。執行以下命令構建 wamrc 編譯器:
sudo apt-get install git build-essential cmake g++-multilib libgcc-9-dev lib32gcc-9-dev ccache #首先確保安裝了必要的依賴項
cd wamr-compiler
./build_llvm.sh (or "./build_llvm_xtensa.sh" to support xtensa target)
mkdir build
cd build
cmake .. (or "cmake .. -DWAMR_BUILD_PLATFORM=darwin" for MacOS)
make
注:cmake要求版本在3.19及以上(構建asmjit庫的要求),否則會報錯,cmake版本升級方法為附後
1.2 安裝 WASI SDK
下載官網 wasi-sdk 版本(wasi-sdk 版本要求在 7 及以上)並提取到默認路徑:/opt/wasi-sdk
1.3 構建iwasm
構建iwasm的命令如下:
cd ${WAMR-dir}/product-mini/platforms/${your platform}
mkdir build && cd build
cmake ..
make
2. 主機上跑hello-world程序(c語言)
構建好iwasm後,把生成的iwasm可執行文件複製到wasm應用所在的目錄,執行./iwasm即可執行對應的程序文件。
以官方的hello-world示例程序所在目錄為例:
cp iwasm ../../../app-samples/hello-world
cd ${WAMR-dir}/product-mini/app-samples/hello-world
./build.sh #為程序寫了makefile的編譯方法
官方示例我跑的時候報錯了
有可能是因為沒有配置wamr-sdk,這是教程wamr-app-framework/wamr-sdk at main · bytecodealliance/wamr-app-framework · GitHub
用下面的示例可以跑通
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char *buf;
printf("Hello world!\n");
buf = malloc(1024);
if (!buf) {
printf("malloc buf failed\n");
return -1;
}
printf("buf ptr: %p\n", buf);
sprintf(buf, "%s", "1234\n");
printf("buf: %s", buf);
free(buf);
return 0;
}
將.c程序編譯成.wasm
/opt/wasi-sdk/bin/clang -O3 -o test.wasm test.c #直接調用官方wasi-sdk中的clang編譯
運行.wasm
./iwasm test.wasm
在配置過程中遇到的問題:
缺乏asmjit 庫,
問題:從github上無法直接拉取
解決:手動下載庫的源碼,找到配置文件,修改指定路徑
修改配置文件
FetchContent_Declare(
asmjit
SOURCE_DIR /home/f/asmjit //指定本地路徑
# GIT_REPOSITORY https://github.com/asmjit/asmjit.git
# GIT_TAG c1019f1642a588107148f64ba54584b0ae3ec8d1
)
SDK 是 "Software Development Kit" 的縮寫,中文翻譯為“軟件開發工具包”。