PromleeBlog
만든 앱

posting thumbnail
REA 실습 2편 Ghidra로 네이티브 바이너리 분석
REA Hands-on 2 - Native Binary Analysis with Ghidra

📅

들어가기 전에 🔗

장애 원인을 찾다 보면 소스가 없는 라이브러리나 오래된 실행 파일이 어떤 계산을 하는지 확인해야 할 때가 있습니다.
4편에서 다룬 JavaScript 앱과 달리 네이티브 바이너리는 기계어로 되어 있어서 의사코드로 읽으려면 Ghidra, Hopper, IDA 같은 외부 디컴파일러가 필요합니다.
디컴파일러는 기계어를 C와 비슷한
의사코드
(pseudocode)로 되돌려 보여 주는 도구이고 의사코드는 원본 소스가 아니라 사람이 읽기 쉽게 만든 근사 코드입니다.

이번 글에서는 직접 만든 C 프로그램으로 REA의 네이티브 분석 흐름을 따라가 봅니다.
원본을 알고 있는 프로그램이라 디컴파일 결과가 얼마나 맞는지 정확히 비교할 수 있습니다.
4편에서 rea-agents를 설치했다는 전제로 진행하고 명령은 위에서부터 순서대로 붙여 넣으면 됩니다.
jq가 필요하니 없다면 brew install jq로 먼저 설치해 둡니다.
👨‍💻
실습 환경은 2026년 11월 23일 기준 macOS 26.3.1(arm64), Apple clang, rea-agents 6.10.1, Ghidra 12.2, Temurin JDK 25.0.5.1입니다.
본문의 출력과 화면은 모두 이 환경에서 직접 실행한 결과입니다.
버전이 바뀌면 필드 이름과 결과가 달라질 수 있습니다.

실습용 C 바이너리 만들기 🔗

분석 대상은 문자열의 바이트 값을 더하는 짧은 프로그램입니다.
작업 폴더를 만들고 히어독(heredoc, 여러 줄을 그대로 파일에 쓰는 셸 문법)으로 sample.c를 씁니다.
작업 폴더와 sample.c 만들기
mkdir -p ~/rea-lab/native && cd ~/rea-lab/native
cat > sample.c <<'EOF'
 #include <stdio.h>
 #include <string.h>
 
static int checksum(const char *s) {
    int sum = 0;
    for (size_t i = 0; i < strlen(s); i++) sum += (unsigned char)s[i];
    return sum;
}
 
int main(int argc, char **argv) {
    const char *msg = argc > 1 ? argv[1] : "hello rea";
    printf("%s: %d\n", msg, checksum(msg));
    return 0;
}
EOF
최적화 수준에 따른 차이를 보려고 두 가지로 컴파일했습니다.
-O0은 최적화를 끈 상태, -O2는 일반적인 배포 수준의 최적화이고 -O0에는 디버그 정보(-g)를 넣었습니다.
컴파일
clang -O0 -g -o sample_O0 sample.c
clang -O2 -o sample_O2 sample.c
ls -l sample_O0 sample_O2 | awk '{print $5, $9}'; ls -d *.dSYM
Terminal에서 히어독으로 sample.c를 쓰고 clang -O0 -g와 -O2로 컴파일한 뒤 크기 33832 sample_O0, 33480 sample_O2와 sample_O0.dSYM 폴더가 출력된 화면
Terminal에서 히어독으로 sample.c를 쓰고 clang -O0 -g와 -O2로 컴파일한 뒤 크기 33832 sample_O0, 33480 sample_O2와 sample_O0.dSYM 폴더가 출력된 화면
크기는 sample_O0가 33,832바이트, sample_O2가 33,480바이트였습니다.
-g를 넣은 sample_O0에는 sample_O0.dSYM 디버그 폴더가 함께 생깁니다.
sample_O0 크기는 컴파일한 폴더 경로에 따라 몇 바이트 달라질 수 있는데 디버그 맵에 경로가 들어가기 때문으로 보입니다.
👍
Linux에서는 같은 명령으로 Mach-O가 아닌 ELF 바이너리가 만들어지고 .dSYM 폴더 없이 디버그 정보가 실행 파일 안에 들어갑니다.
그래서 뒤에 나오는 보안 설정 항목, 심볼 이름의 밑줄, 주소 값은 이 글과 다르게 나옵니다.
Windows에서는 PE 형식이 되며 REA의 Windows용 Ghidra 연동은 설치 가이드↗ 기준 실험 단계입니다.
실행해 보기
./sample_O0; ./sample_O2; ./sample_O0 abc; ./sample_O2 abc
file sample_O0 sample_O2
sample_O0와 sample_O2 실행 결과 hello rea: 876 두 번, abc: 294 두 번, file 명령 결과 두 파일 모두 Mach-O 64-bit executable arm64
sample_O0와 sample_O2 실행 결과 hello rea: 876 두 번, abc: 294 두 번, file 명령 결과 두 파일 모두 Mach-O 64-bit executable arm64
두 바이너리 모두 hello rea: 876, abc: 294로 같은 값을 냈고 둘 다 arm64 Mach-O 실행 파일입니다.
원본을 알고 있으니, 나중에 디컴파일 결과가 checksum 함수를 얼마나 비슷하게 복원하는지 비교할 수 있습니다.

엔진 없이 하는 보안 설정 점검 🔗

디컴파일러가 없어도 REA는 바이너리 헤더를 읽어 보안 설정을 점검할 수 있습니다.
내가 배포하는 바이너리에 기본 보호 옵션이 켜져 있는지 확인할 때 바로 쓸 수 있는 기능입니다.
보안 설정 점검
rea inspect-binary-hardening "$PWD/sample_O0" --json > hardening_O0.json
rea inspect-binary-hardening "$PWD/sample_O2" --json > hardening_O2.json; echo exit=$?
jq -r '.normalized_result.images[0].rows[] | [.property, .state, .basis] | @tsv' hardening_O0.json | column -t -s $'\t'
diff <(jq '.normalized_result.images[0].rows' hardening_O0.json) <(jq '.normalized_result.images[0].rows' hardening_O2.json) && echo 'O0 == O2'
inspect-binary-hardening 결과 9행. pie enabled, allow_stack_execution disabled, no_heap_execution disabled, restrict_segment disabled, code_signature_present enabled(This is presence, not validity), encrypted disabled, arm64e disabled, stack_protector unknown, hardened_runtime unknown, 마지막 줄 O0 == O2
inspect-binary-hardening 결과 9행. pie enabled, allow_stack_execution disabled, no_heap_execution disabled, restrict_segment disabled, code_signature_present enabled(This is presence, not validity), encrypted disabled, arm64e disabled, stack_protector unknown, hardened_runtime unknown, 마지막 줄 O0 == O2
arm64 Mach-O 바이너리에서 나온 결과는 다음과 같고 -O0과 -O2 결과는 같았습니다.
항목상태근거
pieenabledMH_PIE 플래그 설정
allow_stack_executiondisabled플래그 해제
no_heap_executiondisabled플래그 해제
restrict_segmentdisabled__RESTRICT 세그먼트 없음
code_signature_presentenabledLC_CODE_SIGNATURE 존재
encrypteddisabled암호화 명령 없음
arm64edisabledCPU 하위 타입이 arm64
stack_protectorunknown__stack_chk_fail 심볼 없음
hardened_runtimeunknown이 검사에서는 읽지 않음
결과를 읽을 때 주의할 점이 두 가지 있습니다.
REA는 심볼을 찾지 못했다고만 말하고 결론은 내리지 않습니다.
hardened_runtime은 다른 검사(inspect_signature)에서 확인하라고 다음 단계를 안내합니다.
모르는 부분을 모른다고 적는 방식
이 REA 결과의 특징입니다.

디컴파일 엔진 연결하기 🔗

이제 본격적인 분석 흐름입니다.
REA의 기본 순서는 rea analyze → rea search → rea decompile → rea xrefs → rea instructions이고 엔진은 --provider로 고릅니다.

Hopper 연결 실패 기록 🔗

처음에는 이미 설치되어 있던 Hopper로 시도했습니다.
rea doctor는 Hopper를 정상으로 인식했지만 analyze부터 실패했습니다.
Hopper로 analyze 시도
time rea analyze sample_O0 --provider hopper --json > hopper_O0.json 2> hopper_O0.err; echo exit=$?
jq '{error, code, message, stage: .details.stage, primary_error: .details.diagnostics.primary_error.code, launcher: (.details.launcher | {exit_code, stderr})}' hopper_O0.json
Hopper 제공자로 rea analyze를 실행해 36.562초 뒤 exit=1. error Analysis failed, code cleanup_incomplete, stage launch, primary_error provider_unavailable, launcher exit_code 2, stderr Cannot launch Hopper! The handler some object is not defined.
Hopper 제공자로 rea analyze를 실행해 36.562초 뒤 exit=1. error Analysis failed, code cleanup_incomplete, stage launch, primary_error provider_unavailable, launcher exit_code 2, stderr Cannot launch Hopper! The handler some object is not defined.
약 37초(36.562초)를 기다린 뒤 종료 코드 1로 끝났습니다.
오류 코드는 cleanup_incomplete, 단계는 launch, 근본 오류는 provider_unavailable입니다.
런처의 표준 오류에는 Cannot launch Hopper!와 The handler some object is not defined.가 남았습니다.
실패 직후 떠 있던 Hopper의 Untitled 창과 라이선스 안내 시트. Thank you for your interest in Hopper Disassembler 문구와 Try the Demo, Purchase a License, Offline Activation, Validate License 버튼
실패 직후 떠 있던 Hopper의 Untitled 창과 라이선스 안내 시트. Thank you for your interest in Hopper Disassembler 문구와 Try the Demo, Purchase a License, Offline Activation, Validate License 버튼
실패 직후 화면에는 Hopper 창과 라이선스 안내 시트가 떠 있었습니다.
데모·라이선스 창을 닫고 다시 시도해도 결과는 같았습니다.
doctor가 정상이라고 해서 실제 분석까지 된다는 보장은 없다
는 점을 확인한 셈이고 원인은 끝내 찾지 못해 엔진을 Ghidra로 바꿨습니다.

Ghidra 12.2와 JDK 25 준비 🔗

Ghidra를 쓰려면 준비할 것이 세 가지 있었습니다.
먼저 Ghidra 공식 GitHub 릴리스↗에서 Ghidra를 받고 SHA-256을 대조합니다.
받은 파일의 해시를 릴리스에 적힌 값과 비교한 뒤에 압축을 풉니다.
Ghidra 12.2 받기와 SHA-256 확인
mkdir -p ~/Downloads/rea-ghidra-dl && cd ~/Downloads/rea-ghidra-dl
curl -fL -O https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.2_build/ghidra_12.2_PUBLIC_20261016.zip
shasum -a 256 ghidra_12.2_PUBLIC_20261016.zip
curl -s https://api.github.com/repos/NationalSecurityAgency/ghidra/releases/tags/Ghidra_12.2_build | jq -r '.assets[] | "\(.name)  \(.digest)"'
curl로 ghidra_12.2_PUBLIC_20261016.zip 543MB를 15초에 받고 shasum -a 256 결과 2c2cd776...a7be67이 GitHub 릴리스 API의 sha256 digest와 일치하는 화면
curl로 ghidra_12.2_PUBLIC_20261016.zip 543MB를 15초에 받고 shasum -a 256 결과 2c2cd776...a7be67이 GitHub 릴리스 API의 sha256 digest와 일치하는 화면
zip은 543MB였고 SHA-256은 2c2cd776db3c1f6a097ba418922378ac3649cadd5e844a6f5f088ae628a7be67로 릴리스에 적힌 값과 같았습니다.
Linux에서는 shasum -a 256 대신 sha256sum을, Windows PowerShell에서는 Get-FileHash를 쓰면 됩니다.
값이 같으면 ~/Applications에 압축을 풉니다.
압축 해제
mkdir -p ~/Applications && cd ~/Applications
unzip -q ~/Downloads/rea-ghidra-dl/ghidra_12.2_PUBLIC_20261016.zip
ls ~/Applications/ghidra_12.2_PUBLIC
다음은 JDK 25입니다.
저는 Eclipse Temurin 25(macOS aarch64 JDK)를 받아 ~/Applications/jdk-25에 두었습니다.
시스템 Java를 바꾸지 않으려고
설치 프로그램(.pkg) 대신 압축 파일을 썼습니다.
아래는 Adoptium API로 최신 Temurin 25를 받는 예이고 받은 파일의 체크섬은 Adoptium Temurin 다운로드 페이지↗의 값과 대조합니다.
Linux와 Windows에서는 주소의 mac/aarch64 부분을 linux/x64, windows/x64처럼 바꿉니다.
Windows용은 zip 파일로 받아지고 두 운영체제 모두 압축을 푼 폴더에 Contents/Home 없이 바로 bin이 있다는 점이 다릅니다.
JDK 25(Temurin) 받기
mkdir -p ~/Downloads/rea-jdk-dl && cd ~/Downloads/rea-jdk-dl
curl -fL -o temurin25.tar.gz "https://api.adoptium.net/v3/binary/latest/25/ga/mac/aarch64/jdk/hotspot/normal/eclipse"
shasum -a 256 temurin25.tar.gz
tar -xzf temurin25.tar.gz
mv jdk-25*/ ~/Applications/jdk-25
버전 요구 사항과 설치 상태를 확인합니다.
JDK 요구 버전 확인
cd ~/Applications
grep -E 'application.(version|java.min)' ghidra_12.2_PUBLIC/Ghidra/application.properties
java -version 2>&1 | head -n 1
jdk-25/Contents/Home/bin/java -version
ls ghidra_12.2_PUBLIC/Ghidra/Features/Decompiler/os/
application.properties의 application.java.min=25와 application.version=12.2, 기본 java는 openjdk 17.0.16, jdk-25의 java는 Temurin 25.0.5.1+2, Decompiler/os 폴더에는 linux_x86_64와 win_x86_64만 있는 화면
application.properties의 application.java.min=25와 application.version=12.2, 기본 java는 openjdk 17.0.16, jdk-25의 java는 Temurin 25.0.5.1+2, Decompiler/os 폴더에는 linux_x86_64와 win_x86_64만 있는 화면
Ghidra 설정 파일에 application.java.min=25가 적혀 있습니다.
기본 java는 17.0.16이고 새로 받은 JDK는 Temurin 25.0.5.1+2입니다.
디컴파일러 폴더에는 linux_x86_64와 win_x86_64만 있고 mac_arm_64가 없습니다.

macOS ARM64 디컴파일러 빌드 🔗

그래서 ARM64용 디컴파일러를 직접 빌드합니다.
Xcode 명령줄 도구(xcode-select --install)가 필요합니다.
REA 설치 가이드↗에 따르면 공식 릴리스 압축 파일에는 Windows와 Linux x64용 네이티브 바이너리만 들어 있어서 Linux ARM64도 같은 방식으로 빌드해야 합니다.
ARM64 네이티브 디컴파일러 빌드
cd ~/Applications/ghidra_12.2_PUBLIC/support/gradle
JAVA_HOME=~/Applications/jdk-25/Contents/Home ./gradlew buildNatives
ls ../../Ghidra/Features/Decompiler/build/os/mac_arm_64/
gradlew buildNatives 재실행 결과 BUILD SUCCESSFUL in 1s, 14 actionable tasks: 3 executed, 11 up-to-date, mac_arm_64 폴더의 decompile과 sleigh, 처음 빌드 로그의 BUILD SUCCESSFUL in 1m 6s와 14 executed
gradlew buildNatives 재실행 결과 BUILD SUCCESSFUL in 1s, 14 actionable tasks: 3 executed, 11 up-to-date, mac_arm_64 폴더의 decompile과 sleigh, 처음 빌드 로그의 BUILD SUCCESSFUL in 1m 6s와 14 executed
처음 빌드는 1분 6초가 걸렸고 14개 작업이 모두 실행됐습니다.
화면은 이미 빌드한 뒤 다시 실행한 것이라 1초 만에 끝났고 아래쪽에 처음 빌드 로그를 함께 띄웠습니다.
결과 폴더 mac_arm_64에 decompile과 sleigh가 생기면 됩니다.
REA도 결과의 한계 항목에 "macOS 세션에는 맞는 네이티브 디컴파일러가 필요하며 REA는 이를 빌드하지 않는다"고 적습니다.

환경변수 넘기고 상태 확인하기 🔗

REA는 GHIDRA_INSTALL_DIR과 JAVA_HOME으로 Ghidra와 JDK를 찾습니다.
셸 설정 파일(.zshrc)은 건드리지 않고
실습하는 터미널 창에서만
export했습니다.
창을 닫으면 사라집니다.
이 터미널 창에서만 환경변수 설정
cd ~/rea-lab/native
export GHIDRA_INSTALL_DIR=$HOME/Applications/ghidra_12.2_PUBLIC
export JAVA_HOME=$HOME/Applications/jdk-25/Contents/Home
명령마다 앞에 붙여도 효과는 같습니다.
Windows PowerShell에서는 이 문법 대신 $env:GHIDRA_INSTALL_DIR = "..."처럼 설정합니다.
명령마다 넘기는 방법
GHIDRA_INSTALL_DIR=$HOME/Applications/ghidra_12.2_PUBLIC \
JAVA_HOME=$HOME/Applications/jdk-25/Contents/Home \
rea analyze sample_O0 --provider ghidra --json
이 상태에서 rea doctor의 엔진 관련 항목만 뽑아 봤습니다.
Ghidra 설정 후 rea doctor
rea doctor --json | jq -r '"healthy: \(.healthy)", (.scope_checks[] | select(.name | test("^(node|host|hopper|ghidra|ida|jadx|kuna)")) | [.name, .classification, (.detail // "" | tostring | .[0:60])] | @tsv)' | sed "s#$HOME#~#g" | column -t -s $'\t'
환경변수 설정 후 rea doctor 결과. ghidra, ghidra-platform darwin, ghidra-architecture arm64, ghidra-installation, ghidra-version 12.2, ghidra-headless, ghidra-native_decompiler, ghidra-java 25.0.5.1 64-bit JDK가 모두 healthy
환경변수 설정 후 rea doctor 결과. ghidra, ghidra-platform darwin, ghidra-architecture arm64, ghidra-installation, ghidra-version 12.2, ghidra-headless, ghidra-native_decompiler, ghidra-java 25.0.5.1 64-bit JDK가 모두 healthy
Ghidra 관련 항목(플랫폼, 아키텍처, 설치, 버전 12.2, headless, 네이티브 디컴파일러, Java 25.0.5.1)이 모두 healthy로 바뀌었습니다.
전체 healthy는 여전히 false인데, IDA·JADX·Kuna가 없고 클라이언트 등록이 drift 상태라서입니다.

함수 검색과 디컴파일 🔗

먼저 두 바이너리를 analyze로 분석합니다.
이후 명령은 모두 같은 터미널 창(환경변수가 설정된 창)에서 실행합니다.
rea analyze (O0, O2)
time rea analyze sample_O0 --provider ghidra --json > analyze_O0.json
time rea analyze sample_O2 --provider ghidra --json > analyze_O2.json
for f in analyze_O0.json analyze_O2.json; do echo -n "$f  "; jq -c '.normalized_result | {procedure_count, string_count, segment_count, image_base}' $f; done
rea analyze 실행 시간 10.382초와 10.048초, analyze_O0.json은 procedure_count 6, string_count 22, segment_count 9, image_base 0x100000000, analyze_O2.json은 procedure_count 5, string_count 16, segment_count 9
rea analyze 실행 시간 10.382초와 10.048초, analyze_O0.json은 procedure_count 6, string_count 22, segment_count 9, image_base 0x100000000, analyze_O2.json은 procedure_count 5, string_count 16, segment_count 9
명령 하나에 10초 정도(10.382초, 10.048초) 걸렸습니다.
찾은 함수는 -O0 바이너리에서 6개, -O2 바이너리에서 5개였고 문자열은 22개와 16개입니다.

search로 checksum을 찾으면 차이가 바로 드러납니다.
search와 이름 오류 확인
rea search sample_O0 checksum --kind procedures --provider ghidra --json | jq -c '.normalized_result[] | {address, value}'
rea search sample_O2 checksum --kind procedures --provider ghidra --json | jq -c '.normalized_result'
rea decompile sample_O0 --procedure checksum --provider ghidra --json | jq -c '{code, message}'
rea decompile sample_O2 --procedure _checksum --provider ghidra --json | jq -c '{code, message}'
search 결과 sample_O0은 address 0x1000004f0, value _checksum, sample_O2는 빈 배열. 밑줄 없는 checksum과 O2의 _checksum으로 decompile하면 invalid_request, Unknown Ghidra procedure name or address 오류
search 결과 sample_O0은 address 0x1000004f0, value _checksum, sample_O2는 빈 배열. 밑줄 없는 checksum과 O2의 _checksum으로 decompile하면 invalid_request, Unknown Ghidra procedure name or address 오류
명령sample_O0sample_O2
search checksum --kind procedures_checksum @ 0x1000004f0결과 없음
decompile --procedure _checksum성공Unknown Ghidra procedure name or address
함수 개수65
👍
--procedure checksum처럼 밑줄 없이 넘기면 -O0에서도 invalid_request로 실패합니다(위 화면 세 번째 줄).
Mach-O에서는 C 함수 이름 앞에 밑줄이 붙어 심볼이 _checksum이기 때문이고 main도 _main으로 넘겨야 했습니다.
Ghidra GUI의 Symbol Tree에서는 같은 함수가 밑줄 없이 checksum으로 보입니다.
-O0 바이너리의 _checksum을 디컴파일합니다.
rea decompile _checksum (O0)
rea decompile sample_O0 --procedure _checksum --provider ghidra --json > decompile_O0_checksum.json
jq -r '.normalized_result' decompile_O0_checksum.json
jq -r '.limitations[]' decompile_O0_checksum.json | grep -i -E 'pseudocode|source' | head -n 3
rea decompile로 얻은 sample_O0 _checksum의 Ghidra 의사코드(int _checksum(char *param_1), local_1c, local_28, while(true), _strlen)와 한계 문구 Pseudocode is Ghidra decompiler output, not original source
rea decompile로 얻은 sample_O0 _checksum의 Ghidra 의사코드(int _checksum(char *param_1), local_1c, local_28, while(true), _strlen)와 한계 문구 Pseudocode is Ghidra decompiler output, not original source
Ghidra 의사코드: sample_O0 _checksum
int _checksum(char *param_1)
{
  size_t sVar1;
  ulong local_28;   // 원본의 i
  int local_1c;     // 원본의 sum
 
  local_1c = 0;
  local_28 = 0;
  while( true ) {
    sVar1 = _strlen(param_1);          // 반복마다 strlen 호출
    if (sVar1 <= local_28) break;
    local_1c = local_1c + (uint)(byte)param_1[local_28];
    local_28 = local_28 + 1;
  }
  return local_1c;
}
원본과 비교하면 컴파일 과정에서 사라지는 정보(변수 이름, 주석, 원래 구조)가 그대로 드러납니다.
변수 이름 sum, i, s는 local_1c, local_28, param_1이 됐고 for 문은 while(true)와 break로 바뀌었습니다.
그래도
동작은 원본과 같습니다.
매 반복마다 strlen을 부르고 바이트를 부호 없는 값으로 더합니다.
REA도 결과에 "의사코드는 Ghidra 디컴파일러의 출력이며 원본 소스가 아니다"라고 적어 둡니다.

최적화가 바꾼 것 -O0과 -O2 비교 🔗

-O2 바이너리에는 _checksum이 없습니다.
함수가 main 안으로
인라인
됐기 때문입니다.
인라인은 컴파일러가 함수 호출 대신 함수 본문을 호출한 자리에 직접 펼쳐 넣는 최적화입니다.

먼저 xrefs로 strlen을 부르는 곳을 찾아봤습니다.
xref(교차 참조)는 어떤 함수나 데이터를 누가 참조하는지 나타내는 정보입니다.
rea xrefs
rea xrefs sample_O0 _strlen --provider ghidra --json | jq -c '.normalized_result'
rea xrefs sample_O2 _strlen --provider ghidra --json | jq -c '.normalized_result'
rea xrefs sample_O0 _checksum --provider ghidra --json | jq -c '.normalized_result'
xrefs _strlen 결과. O0은 0x100000518, 0x10000057c, 0x100004008, O2는 0x10000048c, 0x10000066c, 0x100004008, O0 _checksum 참조는 0x1000004bc와 0x1000080a2
xrefs _strlen 결과. O0은 0x100000518, 0x10000057c, 0x100004008, O2는 0x10000048c, 0x10000066c, 0x100004008, O0 _checksum 참조는 0x1000004bc와 0x1000080a2
결과는 바이너리마다 주소 세 개인데,
실제 코드에서 부르는 곳은 첫 번째 하나뿐
입니다.
두 번째 주소(O0 0x10000057c, O2 0x10000066c)는 __stubs 구역 안의 _strlen 스텁이고 0x100004008은 __got 항목입니다.
analyze 결과의 세그먼트 범위와 맞춰 보면 구분할 수 있습니다.
-O0의 0x100000518은 _checksum(0x1000004f0~0x100000567) 안이고 -O2의 0x10000048c는 main 안입니다.

다음은 main의 크기와 명령어 수, 그리고 bl(호출) 명령입니다.
main 크기·명령어 수와 호출 명령
for b in sample_O0 sample_O2; do rea instructions $b --procedure _main --provider ghidra --json > instr_${b}_main.json; jq -c --arg b $b '.normalized_result | {binary: $b, name: .procedure.name, bytes: .procedure.body.total_bytes, instructions: (.instructions|length)}' instr_${b}_main.json; done
jq -r '.normalized_result.instructions[]' instr_sample_O0_main.json | grep -E '\bbl\b'
jq -r '.normalized_result.instructions[]' instr_sample_O2_main.json | grep -E '\bbl\b'
rea instructions 결과. sample_O0 main은 이름 entry, 144바이트, 명령어 36개, sample_O2 main은 entry, 504바이트, 126개. O0의 bl 0x1000004f0과 bl 0x100000568, O2의 bl 0x100000664와 bl 0x100000658
rea instructions 결과. sample_O0 main은 이름 entry, 144바이트, 명령어 36개, sample_O2 main은 entry, 504바이트, 126개. O0의 bl 0x1000004f0과 bl 0x100000568, O2의 bl 0x100000664와 bl 0x100000658
sample_O0sample_O2
main 크기144바이트504바이트
main 명령어 수36개126개
checksum 호출bl 0x1000004f0없음 (인라인)
strlen 호출 위치_checksum 루프 안 (0x100000518)main의 루프 앞 (0x10000048c)
-O0의 main은 _checksum(0x1000004f0)과 printf 스텁을 부릅니다.
-O2의 main은 strlen 스텁과 printf 스텁만 부르고 checksum 호출이 없습니다.
-O0에서는 루프 조건 안에서 반복할 때마다 strlen을 불러서 문자열 길이가 n이면 O(n²)의 비용이 듭니다.
-O2에서는 루프 앞에서 한 번만 부르고 그 값을 길이로 재사용하므로 O(n)이 됩니다.
루프 안에서 문자열이 바뀌지 않으므로 컴파일러가 호출을 루프 밖으로 끌어낸 것
입니다.

-O2 main의 벡터화된 의사코드 🔗

-O2의 main을 디컴파일하면 상황이 더 복잡해집니다.
rea decompile _main (O2)
rea decompile sample_O2 --procedure _main --provider ghidra --json > decompile_O2_main.json
jq -r '.normalized_result' decompile_O2_main.json | wc -l
jq -r '.normalized_result' decompile_O2_main.json | grep -n -E '^undefined8 entry|_strlen|& 0xffffffffffffff(c0|f8)'
jq -r '.normalized_result' decompile_O2_main.json | sed -n '/sVar1 = _strlen/,+24p'
sample_O2 main 의사코드가 326줄이고, 2행 undefined8 entry(int param_1,long param_2), 103행 sVar1 = _strlen(param1), 122행 sVar1 & 0xffffffffffffffc0, 285행 sVar1 & 0xfffffffffffffff8이 검색된 화면과 _strlen 호출 뒤 분기 발췌
sample_O2 main 의사코드가 326줄이고, 2행 undefined8 entry(int param_1,long param_2), 103행 sVar1 = _strlen(param1), 122행 sVar1 & 0xffffffffffffffc0, 285행 sVar1 & 0xfffffffffffffff8이 검색된 화면과 _strlen 호출 뒤 분기 발췌
의사코드는 326줄입니다.
합계 루프가
벡터화
되어 길이에 따라 세 갈래로 나뉩니다.
벡터화는 여러 바이트를 한 번의 명령으로 묶어 처리하도록 루프를 바꾸는 최적화입니다.
Ghidra 의사코드: sample_O2 main (앞부분 발췌)
  sVar1 = _strlen(param1);           // 길이는 루프 앞에서 한 번만 구한다
  if (sVar1 == 0) {
    iVar23 = 0;
    goto LAB_100000634;
  }
  if (sVar1 < 8) {                   // 8바이트 미만은 꼬리 루프로
    uVar2 = 0;
    iVar23 = 0;
  }
  else {
    if (sVar1 < 0x40) {              // 64바이트 미만은 8바이트 루프로
      ...
    }
    else {
      ...
      uVar2 = sVar1 & 0xffffffffffffffc0;   // 64의 배수만큼 먼저 처리
Ghidra는 이 부분을 바이트 추출 연산과 수십 개의 int 누산기(iVar19~iVar83)로 풀어서 보여 줍니다.
원래는 for 문 하나였다는 사실은 의사코드에 나타나지 않습니다.
구조를 보고 사람이 다시 읽어 내야 합니다.
또 Ghidra는 두 바이너리 모두에서 main을 entry라는 이름으로 보여 줬고 search main은 별칭 _main으로 찾아 줍니다.
👨‍💻
최적화 수준이 높은 바이너리는 의사코드가 정확하더라도 읽기 어려워집니다.
이럴 때는 rea instructions로 어셈블리를 함께 보면서 마스크 상수와 분기 조건으로 루프 단위를 먼저 파악하면 구조를 빨리 복원할 수 있습니다.

Ghidra GUI에서 같은 결과 보기 🔗

REA는 Ghidra를 headless(화면 없이 명령줄로 실행)로 돌립니다.
같은 결과를 Ghidra 화면에서 직접 보고 싶다면 프로젝트를 만들어 열면 됩니다.
임포트와 자동 분석은 Ghidra에 들어 있는 headless 분석기로 한 번에 할 수 있습니다.
Ghidra 프로젝트로 임포트·자동 분석
cd ~/rea-lab/native
mkdir -p ~/rea-lab/ghidra-proj
~/Applications/ghidra_12.2_PUBLIC/support/analyzeHeadless ~/rea-lab/ghidra-proj rea-lab -import sample_O0 sample_O2 2>&1 | grep -E 'IMPORTING|ANALYZING|Import succeeded|REPORT|ERROR'
analyzeHeadless로 sample_O0와 sample_O2를 rea-lab 프로젝트에 임포트해 Analysis succeeded, Save succeeded, Import succeeded가 나오고 sample_O0에서 DWARF 표현식 경고가 ERROR 레벨로 찍힌 화면
analyzeHeadless로 sample_O0와 sample_O2를 rea-lab 프로젝트에 임포트해 Analysis succeeded, Save succeeded, Import succeeded가 나오고 sample_O0에서 DWARF 표현식 경고가 ERROR 레벨로 찍힌 화면
두 파일 모두 Import succeeded로 끝났습니다.
sample_O0에서는 DWARF 표현식(DW_OP_reg29 등)을 처리하지 못했다는 줄이 ERROR 레벨로 찍히지만 분석 자체는 성공합니다.

Ghidra 화면은 ghidraRun으로 엽니다.
JAVA_HOME이 JDK 25를 가리키는 창에서 실행해야 하고 Windows에서는 같은 폴더의 ghidraRun.bat을 씁니다.
Ghidra GUI 열기
~/Applications/ghidra_12.2_PUBLIC/ghidraRun
ghidraRun으로 띄운 Ghidra 프로젝트 창. 제목 Ghidra: NO ACTIVE PROJECT, 상태줄 Ghidra startup complete (3502 ms)
ghidraRun으로 띄운 Ghidra 프로젝트 창. 제목 Ghidra: NO ACTIVE PROJECT, 상태줄 Ghidra startup complete (3502 ms)
처음 창은 열린 프로젝트가 없는 상태입니다.
메뉴에서
File > Open Project
를 누르고 ~/rea-lab/ghidra-proj/rea-lab.gpr을 고르면 됩니다.
프로젝트 파일을 인자로 넘겨 바로 열 수도 있습니다.
실습 프로젝트를 지정해 열기
~/Applications/ghidra_12.2_PUBLIC/ghidraRun ~/rea-lab/ghidra-proj/rea-lab.gpr
rea-lab 프로젝트를 연 Ghidra 창. 제목 Ghidra: rea-lab, Active Project 목록에 sample_O0와 sample_O2, 상태줄 Ghidra startup complete (3819 ms)
rea-lab 프로젝트를 연 Ghidra 창. 제목 Ghidra: rea-lab, Active Project 목록에 sample_O0와 sample_O2, 상태줄 Ghidra startup complete (3819 ms)
프로젝트 목록에서 sample_O0를 더블클릭하면 CodeBrowser가 열립니다.
왼쪽
Symbol Tree > Functions > checksum
을 누르면 오른쪽 Decompile 창에 의사코드가 나옵니다.
Ghidra CodeBrowser에서 sample_O0의 checksum 함수를 선택한 화면. 왼쪽 Symbol Tree의 Functions에 _printf, _strlen, checksum, main, 가운데 Listing에 int __cdecl checksum(char * s) 함수 머리와 지역 변수 local_1c, local_28의 XREF, 오른쪽 Decompile: checksum 창에 int checksum(char *s), while( true ), sVar1 = _strlen(s) 의사코드
Ghidra CodeBrowser에서 sample_O0의 checksum 함수를 선택한 화면. 왼쪽 Symbol Tree의 Functions에 _printf, _strlen, checksum, main, 가운데 Listing에 int __cdecl checksum(char * s) 함수 머리와 지역 변수 local_1c, local_28의 XREF, 오른쪽 Decompile: checksum 창에 int checksum(char *s), while( true ), sVar1 = _strlen(s) 의사코드
루프 구조와 local_1c, local_28은 rea decompile 결과와 같습니다.
다른 점은 두 가지로, 함수 이름이 밑줄 없는 checksum으로 보이고 매개변수 이름이 param_1이 아니라 원래 이름인 s로 나옵니다.
GUI 프로젝트는 -g로 넣은 디버그 정보(DWARF)를 읽어 매개변수 이름을 살렸기 때문
으로 보입니다.
Listing의 sample.c:13 같은 소스 줄 표시도 같은 디버그 정보에서 나왔습니다.

같은 CodeBrowser에서 sample_O2를 열고 entry(= _main)로 가면 벡터화된 main을 볼 수 있습니다.
Ghidra CodeBrowser에서 sample_O2를 연 화면. 가운데 Listing에 entry 함수의 arm64 어셈블리(sub sp,sp,#0x30, bl _strlen 등), 오른쪽 Decompile: entry 창에 iVar68~iVar83 선언과 param1 = hello rea, sVar1 = _strlen(param1), if (sVar1 < 8) 분기
Ghidra CodeBrowser에서 sample_O2를 연 화면. 가운데 Listing에 entry 함수의 arm64 어셈블리(sub sp,sp,#0x30, bl _strlen 등), 오른쪽 Decompile: entry 창에 iVar68~iVar83 선언과 param1 = hello rea, sVar1 = _strlen(param1), if (sVar1 < 8) 분기
가운데 Listing 창에는 entry 함수의 어셈블리가, 오른쪽 Decompile 창에는 rea decompile로 본 것과 같은 의사코드가 나옵니다.
누산기 변수 선언(iVar68부터 iVar83, uVar84부터 uVar90까지) 뒤에 sVar1 = _strlen(param1);과 길이 분기가 이어집니다.

재구현과 차분 테스트 🔗

마지막으로 디컴파일 결과가 정말 맞는지 확인했습니다.
-O0 의사코드를 거의 그대로 옮겨 C 함수로 다시 쓰고 원본 바이너리 두 개와 같은 입력을 넣어 출력을 비교했습니다.
이렇게 원본과 재구현에 같은 입력을 넣고 출력을 비교하는 검증을
차분 테스트
라고 합니다.
재구현 하네스 작성
mkdir -p ~/rea-lab/native/harness && cd ~/rea-lab/native
cat > harness/checksum_recovered.c <<'EOF'
/* Ghidra 12.2 디컴파일 결과를 바탕으로 다시 쓴 checksum. main은 sample_O0 main의 구조를 따른다. */
 #include <stdio.h>
 #include <string.h>
 
static int checksum_recovered(const char *param_1) {
    int local_1c = 0;
    unsigned long local_28 = 0;
    while (1) {
        size_t sVar1 = strlen(param_1);
        if (sVar1 <= local_28) break;
        local_1c = local_1c + (unsigned int)(unsigned char)param_1[local_28];
        local_28 = local_28 + 1;
    }
    return local_1c;
}
 
int main(int param_1, char **param_2) {
    const char *local_30 = param_1 < 2 ? "hello rea" : param_2[1];
    printf("%s: %d\n", local_30, checksum_recovered(local_30));
    return 0;
}
EOF
입력은 14가지를 골랐습니다.
인자 없음, 빈 문자열, 한글과 이모지 같은 UTF-8 문자열, 0x80 이상의 바이트를 넣었습니다.
벡터화 루프의 경계를 지나도록
길이 7, 8, 63, 64, 65와 1,000자짜리 입력도 넣었습니다.
비교 스크립트는 zsh 기준이며 첫 줄의 실행 셸 지정(shebang)은 printf로 따로 써 넣습니다.
차분 테스트 스크립트 작성
printf '#!/bin/zsh\n' > harness/difftest.sh
cat >> harness/difftest.sh <<'EOF'
 # 원본 sample_O0, sample_O2와 재작성 하네스의 출력을 같은 입력으로 비교한다.
cd "${0:A:h}/.."
H=harness/checksum_recovered
pass=0; fail=0
long1000=$(printf 'a%.0s' {1..1000})
mixed1000=$(python3 -c "import sys;sys.stdout.write(''.join(chr(33+(i*7)%94) for i in range(1000)))")
kor1000=$(python3 -c "import sys;sys.stdout.write('가나다라'*250)")
typeset -a names inputs
names=(no-arg empty hello-rea korean-utf8 emoji-utf8 len7 len8 len63 len64 len65 long1000-a long1000-mixed korean-1000chars high-bytes)
inputs=(__NOARG__ "" "hello rea" "안녕하세요 리버싱" "🙂✓é" "abcdefg" "abcdefgh" "$(printf 'x%.0s' {1..63})" "$(printf 'y%.0s' {1..64})" "$(printf 'z%.0s' {1..65})" "$long1000" "$mixed1000" "$kor1000" "$(printf '\xff\xfe\x80\x81')")
for i in {1..${#names}}; do
  n=${names[$i]}; in=${inputs[$i]}
  if [[ $in == __NOARG__ ]]; then
    o0=$(./sample_O0); o2=$(./sample_O2); h=$($H)
  else
    o0=$(./sample_O0 "$in"); o2=$(./sample_O2 "$in"); h=$($H "$in")
  fi
  s0=${o0##*: }; s2=${o2##*: }; sh=${h##*: }
  if [[ "$o0" == "$h" && "$o2" == "$h" ]]; then r=PASS; ((pass++)); else r=FAIL; ((fail++)); fi
  printf '%-18s bytes=%-5s O0=%-8s O2=%-8s harness=%-8s %s\n' "$n" "$(printf '%s' "$in" | wc -c | tr -d ' ')" "$s0" "$s2" "$sh" "$r"
done
echo "PASS=$pass FAIL=$fail (비교 기준: 출력 한 줄 전체가 바이트 단위로 같은지)"
EOF
chmod +x harness/difftest.sh
컴파일하고 실행합니다.
Linux에서는 zsh를 먼저 설치하거나, 스크립트를 bash 문법으로 바꿔서 실행해야 합니다.
하네스 컴파일과 차분 테스트 실행
sed -n '6,16p' harness/checksum_recovered.c
clang -O0 -o harness/checksum_recovered harness/checksum_recovered.c && ./harness/difftest.sh
checksum_recovered 함수 본문과 difftest.sh 실행 결과. no-arg부터 high-bytes까지 14개 입력에서 O0, O2, harness 값이 모두 같아 PASS, 마지막 줄 PASS=14 FAIL=0
checksum_recovered 함수 본문과 difftest.sh 실행 결과. no-arg부터 high-bytes까지 14개 입력에서 O0, O2, harness 값이 모두 같아 PASS, 마지막 줄 PASS=14 FAIL=0
입력바이트O0O2재구현
빈 문자열0000
hello rea9876876876
한글 UTF-825436843684368
이모지 UTF-89157515751575
길이 6363756075607560
길이 6464774477447744
길이 6565793079307930
한글 1,000자3000543250543250543250
0x80 이상 바이트4766766766
표에는 일부만 옮겼고
14개 입력 모두에서 출력 한 줄 전체가 바이트 단위로 일치했습니다
(PASS=14 FAIL=0).

이 결과의 의미는 정확히 짚어야 합니다.
작은 함수 하나를 원본과 같은 동작으로 복원했고 고른 입력에서 차이가 없다는 것까지 확인했습니다.
모든 입력에서 같다는 증명은 아니며
, 원본 소스를 알고 있었기 때문에 입력을 고르기도 쉬웠습니다.
REA 프로젝트가 공개한 DX-Ball 쇼케이스↗가 3,205건의 동작 비교와 컴파일된 63바이트 일치 확인을 함께 쓰는 이유가 여기에 있습니다.

결론 🔗

엔진 없이도 바이너리의 보안 설정은 바로 점검할 수 있었습니다.
반면 디컴파일은 외부 엔진의 설치 상태에 크게 좌우됐고 Hopper는 끝내 실행되지 않았으며 Ghidra는 JDK 25와 네이티브 빌드까지 마쳐야 동작했습니다.
일단 연결되자 REA는 함수 검색, 디컴파일, 참조 추적을 일정한 형식으로 돌려주고 결과마다 한계까지 함께 적어 줬습니다.
REA는 엔진을 대신하는 도구가 아니라, 이미 설치된 엔진을 에이전트가 쓸 수 있게 이어 주는 도구
라는 점을 이번 실습에서 확인했습니다.
9편에서는 이런 도구와 분석 대상을 다룰 때 생기는 보안 문제를 정리합니다.

참고 🔗