
リバースエンジニアリング: 大規模言語モデルによるバイナリコードの逆コンパイル
📊 結果 | 🤗 モデル | 🚀 クイックスタート | 📚 HumanEval-Decompile | 📎 引用 | 📝 論文 | 🖥️ Colab | ▶️ YouTube
リバースエンジニアリング: 大規模言語モデルによるバイナリコードの逆コンパイル
コンパイル時、プリプロセッサはソースコード(SRC)を処理してコメントを除去し、マクロやインクルードを展開します。クリーニングされたコードは次にコンパイラに渡され、アセンブリコード(ASM)に変換されます。このASMはアセンブラによってバイナリコード(0と1)に変換されます。リンカは関数呼び出しをリンクして実行可能ファイルを作成し、プロセスを完了させます。一方、逆コンパイルはバイナリコードをソースファイルに戻す変換を含みます。LLMはテキストでトレーニングされているため、バイナリデータを直接処理する能力がありません。そのため、バイナリはまず Objdump によってアセンブリ言語(ASM)に逆アセンブルされる必要があります。バイナリと逆アセンブルされたASMは等価であり、相互変換できることに注意してください。したがって、私たちはこれらを同じ意味で扱います。最後に、逆コンパイルされたコードとソースコードの間で損失が計算され、トレーニングを導きます。逆コンパイルされたコード(SRC')の品質を評価するために、テストアサーション(再実行可能性)を通じてその機能がテストされます。
LLM4Decompileには、13億から330億パラメータのサイズのモデルが含まれており、これらのモデルをHugging Faceで公開しています。
注記3: V1.5シリーズは、より大規模なデータセット(15Bトークン)と最大トークンサイズ4,096でトレーニングされており、以前のモデルと比較して顕著な性能(100%以上の改善)を達成しています。
注記4: V2シリーズはGhidraを基盤としており、Ghidraによって逆コンパイルされた疑似コードを改良するために20億トークンでトレーニングされています。詳細はghidraフォルダを確認してください。
セットアップ: 必要な環境をインストールするには、以下のスクリプトを使用してください。
git clone https://github.com/albertan017/LLM4Decompile.git
cd LLM4Decompile
conda create -n 'llm4decompile' python=3.9 -y
conda activate llm4decompile
pip install -r requirements.txt
以下は、私たちのモデルの使用例です(V1.5用に改訂。以前のモデルについては、HFの対応するモデルページを確認してください)。 注: 逆コンパイルしたい関数名で "func0" を置き換えてください。
前処理: Cコードをバイナリにコンパイルし、バイナリをアセンブリ命令に逆アセンブルします。
import subprocess
import os
func_name = 'func0'
OPT = ["O0", "O1", "O2", "O3"]
fileName = 'samples/sample' #'path/to/file'
for opt_state in OPT:
output_file = fileName +'_' + opt_state
input_file = fileName+'.c'
compile_command = f'gcc -o {output_file}.o {input_file} -{opt_state} -lm'#compile the code with GCC on Linux
subprocess.run(compile_command, shell=True, check=True)
compile_command = f'objdump -d {output_file}.o > {output_file}.s'#disassemble the binary file into assembly instructions
subprocess.run(compile_command, shell=True, check=True)
input_asm = ''
with open(output_file+'.s') as f:#asm file
asm= f.read()
if '<'+func_name+'>:' not in asm: #IMPORTANT replace func0 with the function name
raise ValueError("compile fails")
asm = '<'+func_name+'>:' + asm.split('<'+func_name+'>:')[-1].split('\n\n')[0] #IMPORTANT replace func0 with the function name
asm_clean = ""
asm_sp = asm.split("\n")
for tmp in asm_sp:
if len(tmp.split("\t"))<3 and '00' in tmp:
continue
idx = min(
len(tmp.split("\t")) - 1, 2
)
tmp_asm = "\t".join(tmp.split("\t")[idx:]) # remove the binary code
tmp_asm = tmp_asm.split("#")[0].strip() # remove the comments
asm_clean += tmp_asm + "\n"
input_asm = asm_clean.strip()
before = f"# This is the assembly code:\n"#prompt
after = "\n# What is the source code?\n"#prompt
input_asm_prompt = before+input_asm.strip()+after
with open(fileName +'_' + opt_state +'.asm','w',encoding='utf-8') as f:
f.write(input_asm_prompt)
アセンブリ命令は次の形式である必要があります:
<FUNCTION_NAME>:\nOPERATIONS\nOPERATIONS\n
典型的なアセンブリ命令は次のようになります:
<func0>:
endbr64
lea (%rdi,%rsi,1),%eax
retq
逆コンパイル: LLM4Decompileを使用して、アセンブリ命令をCに変換します:
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_path = 'LLM4Binary/llm4decompile-6.7b-v1.5' # V1.5 Model
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path,torch_dtype=torch.bfloat16).cuda()
with open(fileName +'_' + OPT[0] +'.asm','r') as f:#optimization level O0
asm_func = f.read()
inputs = tokenizer(asm_func, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=2048)### max length to 4096, max new tokens should be below the range
c_func_decompile = tokenizer.decode(outputs[0][len(inputs[0]):-1])
with open(fileName +'.c','r') as f:#original file
func = f.read()
print(f'original function:\n{func}')# Note we only decompile one function, where the original file may contain multiple functions
print(f'decompiled function:\n{c_func_decompile}')
# build docker
docker build -t llm4decompile .
# run docker with GPU
docker run --gpus all -it --name llm4decompile llm4decompile /bin/bash
# run demo.py (choose a model suitable for your resources before running)
cd ghidra
python demo.py
データは llm4decompile/decompile-eval/decompile-eval-executable-gcc-obj.json にJSONリスト形式で保存されています。164*4(O0、O1、O2、O3)個のサンプルがあり、それぞれに5つのキーがあります:
task_id: 問題のIDを示します。type: 最適化ステージで、[O0、O1、O2、O3]のいずれかです。c_func: HumanEval問題のCソリューション。c_test: Cテストアサーション。input_asm_prompt: プロンプト付きのアセンブリ命令。前処理の例のようにして導出できます。評価スクリプトを確認してください。
このコードリポジトリはMITおよびDeepSeekライセンスの下でライセンスされています。
@misc{tan2024llm4decompile,
title={LLM4Decompile: Decompiling Binary Code with Large Language Models},
author={Hanzhuo Tan and Qi Luo and Jing Li and Yuqun Zhang},
year={2024},
eprint={2403.05286},
archivePrefix={arXiv},
primaryClass={cs.PL}
}
| モデル | チェックポイント | サイズ | 再実行可能性 | 注記 |
|---|
| llm4decompile-1.3b-v1.5 | 🤗 HF Link | 1.3B | 27.3% | 注記3 |
| llm4decompile-6.7b-v1.5 | 🤗 HF Link | 6.7B | 45.4% | 注記3 |
| llm4decompile-1.3b-v2 | 🤗 HF Link | 1.3B | 46.0% | 注記4 |
| llm4decompile-6.7b-v2 | 🤗 HF Link | 6.7B | 52.7% | 注記4 |
| llm4decompile-9b-v2 | 🤗 HF Link | 9B | 64.9% | 注記4 |
| llm4decompile-22b-v2 | 🤗 HF Link | 22B | 63.6% | 注記4 |