1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

x86_64バイナリをRISC-Vに自動変換するCLIツール作ってみた【RetDec + Clang】

Last updated at Posted at 2025-04-22

x86_64バイナリをRISC-Vに自動変換するCLIツール作ってみた【RetDec + Clang】

はじめに

「x86_64でしか動かないLinuxバイナリを、RISC-V上でも動かせたら便利なのに…」
そう思ったことはありませんか?

最近はRISC-Vが急速に注目される中で、既存のx86_64資産をどう活かすかという課題に直面することも増えてきました。
しかし、静的なバイナリ変換(transpilation)は困難で、ほとんどの人はエミュレーション(QEMUなど)に頼っているのが現状です。

そこで、RetDecとClangを組み合わせて、「なるべく自動でx86_64 ELFバイナリをRISC-V ELFバイナリに変換できるCLIツール」を作ってみました。

まだ作り始めたばかりのプロジェクトですが、最低限「動く」段階に到達したので紹介させてください。


プロジェクト概要

  • GitHub: https://github.com/takahashi-akari/bin2riscv
  • 名前: bin2riscv
  • ライセンス: MIT
  • 現状できること:
    • x86_64 ELFバイナリをRetDecで逆コンパイル(C出力)
    • Intel SIMD IntrinsicsをRISC-V上で動くshim関数に置き換え
    • ClangでRISC-V ELFを生成
    • QEMUで動作確認まで自動化

インストール方法

A. 通常の環境で

git clone https://github.com/takahashi-akari/bin2riscv.git
cd bin2riscv
./bin2riscv.sh your_binary.out

B. Dockerで

docker build -t bin2riscv .
docker run --rm -it -v $(pwd):/workspace bin2riscv ./bin2riscv.sh your_binary.out

実際の変換プロセス

1. RetDecで逆コンパイル

retdec-decompiler.py -o your_binary.c --cleanup your_binary.out

2. ポータブル化の自動変換

  • __int64int64_t
  • long longint64_t
  • _mm_add_pd(a, b)shim_mm_add_pd(a, b) など

3. Intrinsicsのshim生成(例)

static inline __m128d shim_mm_add_pd(__m128d a, __m128d b) {
    return (__m128d){ a[0] + b[0], a[1] + b[1] };
}

4. ClangでRISC-Vに変換

clang --target=riscv64-unknown-elf -march=rv64gc -O2 -nostdlib -ffreestanding \
  your_binary.c -include intrin_shim.h -o your_binary_riscv.elf

5. QEMUで実行(任意)

qemu-riscv64 ./your_binary_riscv.elf

現在の制限

  • 対応しているIntrinsicsはまだ少ない(現在6種:add/sub/mul/div/set1/cmpeq)
  • 動的リンク、syscall、構造体ABIは未対応
  • RVV命令を直接使っているわけではない(今後の課題)
  • RetDec出力の精度に依存する(意味不明な関数名など)

今後の展望(Roadmap)

  • Intrinsics定義をJSONで自動生成できるようにする
  • 動的ライブラリやlibc対応、実行環境を再現する仕組みの構築
  • LLVM IRベースの完全トランスレータ
  • GUI/WebUIによる「バイナリを投げるだけ」体験

まとめ

まだ始まったばかりのプロジェクトですが、「x86_64バイナリをRISC-Vで動かす」という夢に一歩近づけた気がしています。

特にRetDecとClangがあれば、想像以上に変換パイプラインが組めることがわかり、LLVMの柔軟性に感動しました。

興味がある方、協力してくださる方、GitHubでスター or Issue or PRお待ちしています!


おまけ:動作画面(CLIログ)

$ ./bin2riscv.sh your_binary.out
[+] Decompiling with RetDec...
[+] Patching C source...
[+] Writing intrinsic shim...
[+] Compiling with Clang...
[+] Running with QEMU...
Hello from RISC-V!

ありがとうございました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?