fix(llvm): keep Mach-O relocation addends out of indirect tables

This commit is contained in:
shenlei
2026-11-24 17:33:22 +09:00
parent 47a7acc741
commit d4626203e1
4 changed files with 145 additions and 103 deletions
+33 -39
View File
@@ -140,41 +140,51 @@ bool obfuscateSingleFunctionIBR(Function &F, const IGPolicyConfig &Policy,
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(), IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
(F.getName() + "|ibr").str()); (F.getName() + "|ibr").str());
RNG.shuffle(Targets);
DenseMap<BasicBlock *, unsigned> SlotMap; DenseMap<BasicBlock *, unsigned> SlotMap;
SmallVector<Constant *, 24> Share1Entries; for (unsigned Idx = 0; Idx < Targets.size(); ++Idx)
SmallVector<Constant *, 24> Share2Entries; SlotMap[Targets[Idx]] = Idx;
Share1Entries.reserve(Targets.size()); RNG.shuffle(Targets);
Share2Entries.reserve(Targets.size());
SmallVector<Constant *, 24> DeltaEntries;
SmallVector<Constant *, 24> IndexEntries(Targets.size());
DeltaEntries.reserve(Targets.size());
uint64_t IndexKey = RNG.nextNonZeroU64();
Constant *FnInt = ConstantExpr::getPtrToInt(&F, I64Ty); Constant *FnInt = ConstantExpr::getPtrToInt(&F, I64Ty);
for (unsigned Idx = 0; Idx < Targets.size(); ++Idx) { for (unsigned Idx = 0; Idx < Targets.size(); ++Idx) {
BasicBlock *BB = Targets[Idx]; BasicBlock *BB = Targets[Idx];
SlotMap[BB] = Idx;
uint64_t Salt = RNG.nextNonZeroU64();
Constant *BBAddrInt = ConstantExpr::getPtrToInt(BlockAddress::get(&F, BB), I64Ty); Constant *BBAddrInt = ConstantExpr::getPtrToInt(BlockAddress::get(&F, BB), I64Ty);
Constant *RelOffset = ConstantExpr::getSub(BBAddrInt, FnInt); // Keep the encoded indices out of the Mach-O symbol-difference relocations.
Constant *Share1 = ConstantExpr::getAdd(RelOffset, ConstantInt::get(I64Ty, Salt)); DeltaEntries.push_back(ConstantExpr::getSub(BBAddrInt, FnInt));
Share1Entries.push_back(Share1); IndexEntries[SlotMap.lookup(BB)] = ConstantInt::get(I64Ty, Idx ^ IndexKey);
Share2Entries.push_back(ConstantInt::get(I64Ty, Salt));
} }
ArrayType *TableTy = ArrayType::get(I64Ty, Targets.size()); ArrayType *TableTy = ArrayType::get(I64Ty, Targets.size());
std::string Suffix = Tag.str() + "_" + std::to_string(FnIndex); std::string Suffix = Tag.str() + "_" + std::to_string(FnIndex);
auto *Share1GV = new GlobalVariable( auto *DeltaGV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Share1Entries), "__ig_ibt1_" + Suffix); ConstantArray::get(TableTy, DeltaEntries), "__ig_ibt1_" + Suffix);
Share1GV->setAlignment(Align(8)); DeltaGV->setAlignment(Align(8));
Share1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); DeltaGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
auto *Share2GV = new GlobalVariable( auto *IndexGV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Share2Entries), "__ig_ibt2_" + Suffix); ConstantArray::get(TableTy, IndexEntries), "__ig_ibt2_" + Suffix);
Share2GV->setAlignment(Align(8)); IndexGV->setAlignment(Align(8));
Share2GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); IndexGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Constant *Zero64 = ConstantInt::get(I64Ty, 0); Constant *Zero64 = ConstantInt::get(I64Ty, 0);
auto ResolveTarget = [&](IRBuilder<> &B, Value *Slot) {
Value *IndexPtr = B.CreateInBoundsGEP(TableTy, IndexGV, {Zero64, Slot});
Value *EncodedIndex =
B.CreateAlignedLoad(I64Ty, IndexPtr, Align(8), /*isVolatile=*/true);
Value *Index = B.CreateXor(EncodedIndex, ConstantInt::get(I64Ty, IndexKey));
Value *DeltaPtr = B.CreateInBoundsGEP(TableTy, DeltaGV, {Zero64, Index});
Value *Delta =
B.CreateAlignedLoad(I64Ty, DeltaPtr, Align(8), /*isVolatile=*/true);
Value *Addr = B.CreateAdd(B.CreatePtrToInt(&F, I64Ty), Delta);
return B.CreateIntToPtr(Addr, PtrTy);
};
unsigned RewrittenHere = 0; unsigned RewrittenHere = 0;
for (BranchInst *Br : Branches) { for (BranchInst *Br : Branches) {
@@ -185,16 +195,7 @@ bool obfuscateSingleFunctionIBR(Function &F, const IGPolicyConfig &Policy,
if (Br->isUnconditional() || Br->getSuccessor(0) == Br->getSuccessor(1)) { if (Br->isUnconditional() || Br->getSuccessor(0) == Br->getSuccessor(1)) {
BasicBlock *Dest = Br->getSuccessor(0); BasicBlock *Dest = Br->getSuccessor(0);
unsigned SlotIdx = SlotMap[Dest]; Value *DstPtr = ResolveTarget(B, ConstantInt::get(I64Ty, SlotMap.lookup(Dest)));
Value *IdxVal = ConstantInt::get(I64Ty, SlotIdx);
Value *P1 = B.CreateInBoundsGEP(TableTy, Share1GV, {Zero64, IdxVal});
Value *P2 = B.CreateInBoundsGEP(TableTy, Share2GV, {Zero64, IdxVal});
LoadInst *S1 = B.CreateAlignedLoad(I64Ty, P1, Align(8), /*isVolatile=*/true);
LoadInst *S2 = B.CreateAlignedLoad(I64Ty, P2, Align(8), /*isVolatile=*/true);
Value *BaseInt = B.CreatePtrToInt(&F, I64Ty);
Value *Delta = B.CreateSub(S1, S2);
Value *Addr = B.CreateAdd(BaseInt, Delta);
Value *DstPtr = B.CreateIntToPtr(Addr, PtrTy);
Br->eraseFromParent(); Br->eraseFromParent();
IRBuilder<> EndB(ParentBB); IRBuilder<> EndB(ParentBB);
@@ -208,16 +209,9 @@ bool obfuscateSingleFunctionIBR(Function &F, const IGPolicyConfig &Policy,
BasicBlock *FalseBB = Br->getSuccessor(1); BasicBlock *FalseBB = Br->getSuccessor(1);
Value *Cond = Br->getCondition(); Value *Cond = Br->getCondition();
Value *IdxVal = B.CreateSelect( Value *IdxVal = B.CreateSelect(
Cond, ConstantInt::get(I64Ty, SlotMap[TrueBB]), Cond, ConstantInt::get(I64Ty, SlotMap.lookup(TrueBB)),
ConstantInt::get(I64Ty, SlotMap[FalseBB]), "ig.ibr.idx"); ConstantInt::get(I64Ty, SlotMap.lookup(FalseBB)), "ig.ibr.idx");
Value *P1 = B.CreateInBoundsGEP(TableTy, Share1GV, {Zero64, IdxVal}); Value *DstPtr = ResolveTarget(B, IdxVal);
Value *P2 = B.CreateInBoundsGEP(TableTy, Share2GV, {Zero64, IdxVal});
LoadInst *S1 = B.CreateAlignedLoad(I64Ty, P1, Align(8), /*isVolatile=*/true);
LoadInst *S2 = B.CreateAlignedLoad(I64Ty, P2, Align(8), /*isVolatile=*/true);
Value *BaseInt = B.CreatePtrToInt(&F, I64Ty);
Value *Delta = B.CreateSub(S1, S2);
Value *Addr = B.CreateAdd(BaseInt, Delta);
Value *DstPtr = B.CreateIntToPtr(Addr, PtrTy);
Br->eraseFromParent(); Br->eraseFromParent();
IRBuilder<> EndB(ParentBB); IRBuilder<> EndB(ParentBB);
+32 -62
View File
@@ -402,89 +402,59 @@ bool runIndirectCallObfuscation(Module &M, const IGPolicyConfig &Policy,
bool UseDualTable = Policy.isIndirectCallDualTableEnabled(); bool UseDualTable = Policy.isIndirectCallDualTableEnabled();
Audit.IndirectCallDualTable = UseDualTable; Audit.IndirectCallDualTable = UseDualTable;
DenseMap<Function *, std::pair<unsigned, uint64_t>> SlotMap; SmallVector<Constant *, 16> DeltaEntries;
SmallVector<Constant *, 16> Table1Entries; SmallVector<Constant *, 16> IndexEntries(UseDualTable ? UniqueCallees.size() : 0);
SmallVector<Constant *, 16> Table2Entries; DeltaEntries.reserve(UniqueCallees.size());
Table1Entries.reserve(UniqueCallees.size()); uint64_t IndexKey = UseDualTable ? RNG.nextNonZeroU64() : 0;
if (UseDualTable)
Table2Entries.reserve(UniqueCallees.size());
// Mach-O linkers may truncate addends on symbol differences. Keep the
// relocated table to pure differences and encode only the separate indices.
for (unsigned Idx = 0; Idx < UniqueCallees.size(); ++Idx) { for (unsigned Idx = 0; Idx < UniqueCallees.size(); ++Idx) {
Function *TargetFn = UniqueCallees[Idx]; Function *TargetFn = UniqueCallees[Idx];
// [2 GiB, 4 GiB) salt shifts static delta outside Mach-O VM range while
// allowing per-call-site split immediates SiteA + SiteB == SlotSalt in u32.
uint64_t SlotSalt =
0x80000000ULL | static_cast<uint64_t>(RNG.nextU32() & 0x7FFFFFFFU);
Constant *CalleeInt = ConstantExpr::getPtrToInt(TargetFn, I64Ty); Constant *CalleeInt = ConstantExpr::getPtrToInt(TargetFn, I64Ty);
Constant *Diff = ConstantExpr::getSub(CalleeInt, AnchorInt); DeltaEntries.push_back(ConstantExpr::getSub(CalleeInt, AnchorInt));
if (UseDualTable) { if (UseDualTable) {
uint64_t Share2 = RNG.nextNonZeroU64(); IndexEntries[SeenCallees.lookup(TargetFn)] =
uint64_t CombinedSalt = Share2 + SlotSalt; ConstantInt::get(I64Ty, Idx ^ IndexKey);
Constant *Encoded1 =
ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, CombinedSalt));
Table1Entries.push_back(Encoded1);
Table2Entries.push_back(ConstantInt::get(I64Ty, Share2));
} else { } else {
Constant *Encoded = SeenCallees[TargetFn] = Idx;
ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, SlotSalt));
Table1Entries.push_back(Encoded);
} }
SlotMap[TargetFn] = {Idx, SlotSalt};
} }
ArrayType *TableTy = ArrayType::get(I64Ty, Table1Entries.size()); ArrayType *TableTy = ArrayType::get(I64Ty, DeltaEntries.size());
GlobalVariable *Table1GV = nullptr; auto *DeltaGV = new GlobalVariable(
GlobalVariable *Table2GV = nullptr; M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
if (UseDualTable) { ConstantArray::get(TableTy, DeltaEntries),
Table1GV = new GlobalVariable( (UseDualTable ? "__ig_cs1_" : "__ig_ct_") + Tag);
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, DeltaGV->setAlignment(Align(8));
ConstantArray::get(TableTy, Table1Entries), "__ig_cs1_" + Tag); DeltaGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Table1GV->setAlignment(Align(8));
Table1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Table2GV = new GlobalVariable( GlobalVariable *IndexGV = nullptr;
if (UseDualTable) {
IndexGV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Table2Entries), "__ig_cs2_" + Tag); ConstantArray::get(TableTy, IndexEntries), "__ig_cs2_" + Tag);
Table2GV->setAlignment(Align(8)); IndexGV->setAlignment(Align(8));
Table2GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); IndexGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
} else {
Table1GV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Table1Entries), "__ig_ct_" + Tag);
Table1GV->setAlignment(Align(8));
Table1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
} }
Constant *Zero64 = ConstantInt::get(I64Ty, 0); Constant *Zero64 = ConstantInt::get(I64Ty, 0);
for (const PendingIndirectSite &Site : Sites) { for (const PendingIndirectSite &Site : Sites) {
CallInst *CI = Site.CI; CallInst *CI = Site.CI;
auto It = SlotMap.find(Site.Callee);
if (It == SlotMap.end())
continue;
unsigned SlotIdx = It->second.first;
uint64_t SlotSalt = It->second.second;
uint64_t SiteA =
1ULL + (static_cast<uint64_t>(RNG.nextU32()) % (SlotSalt - 1ULL));
uint64_t SiteB = SlotSalt - SiteA;
IRBuilder<> B(CI); IRBuilder<> B(CI);
B.SetCurrentDebugLocation(CI->getDebugLoc()); B.SetCurrentDebugLocation(CI->getDebugLoc());
Constant *IdxConst = ConstantInt::get(I64Ty, SlotIdx); Value *Index = ConstantInt::get(I64Ty, SeenCallees.lookup(Site.Callee));
Value *SlotPtr1 = B.CreateInBoundsGEP(TableTy, Table1GV, {Zero64, IdxConst});
LoadInst *Load1 =
B.CreateAlignedLoad(I64Ty, SlotPtr1, Align(8), /*isVolatile=*/true);
Value *RawDelta = Load1;
if (UseDualTable) { if (UseDualTable) {
Value *SlotPtr2 = B.CreateInBoundsGEP(TableTy, Table2GV, {Zero64, IdxConst}); Value *IndexPtr = B.CreateInBoundsGEP(TableTy, IndexGV, {Zero64, Index});
LoadInst *Load2 = Value *EncodedIndex =
B.CreateAlignedLoad(I64Ty, SlotPtr2, Align(8), /*isVolatile=*/true); B.CreateAlignedLoad(I64Ty, IndexPtr, Align(8), /*isVolatile=*/true);
RawDelta = B.CreateSub(Load1, Load2); Index = B.CreateXor(EncodedIndex, ConstantInt::get(I64Ty, IndexKey));
} }
Value *DeltaPtr = B.CreateInBoundsGEP(TableTy, DeltaGV, {Zero64, Index});
Value *Delta =
B.CreateAlignedLoad(I64Ty, DeltaPtr, Align(8), /*isVolatile=*/true);
Value *AnchorVal = B.CreatePtrToInt(AnchorGV, I64Ty); Value *AnchorVal = B.CreatePtrToInt(AnchorGV, I64Ty);
Value *Step1 = B.CreateSub(RawDelta, ConstantInt::get(I64Ty, SiteA)); Value *TargetInt = B.CreateAdd(AnchorVal, Delta);
Value *Step2 = B.CreateAdd(AnchorVal, Step1);
Value *TargetInt = B.CreateSub(Step2, ConstantInt::get(I64Ty, SiteB));
Value *FnPtr = B.CreateIntToPtr(TargetInt, PtrTy); Value *FnPtr = B.CreateIntToPtr(TargetInt, PtrTy);
CI->setTailCallKind(CallInst::TCK_None); CI->setTailCallKind(CallInst::TCK_None);
+10 -2
View File
@@ -196,12 +196,12 @@ int main(void) {
# Cross-compile & link for arm64-apple-ios15.0 with -Wl,-dead_strip to validate ld64 PIC relocations # Cross-compile & link for arm64-apple-ios15.0 with -Wl,-dead_strip to validate ld64 PIC relocations
bc_ios = p / 'ibr_ios.bc' bc_ios = p / 'ibr_ios.bc'
obf_ios = p / 'ibr_ios.obf.bc' obf_ios = p / 'ibr_ios.obf.ll'
obj_ios = p / 'ibr_ios.o' obj_ios = p / 'ibr_ios.o'
bin_ios = p / 'ibr_ios.bin' bin_ios = p / 'ibr_ios.bin'
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios)], check=True) subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios)], check=True)
subprocess.run([ subprocess.run([
opt_path, '-passes=ig-obfuscate', opt_path, '-S', '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', f'--ig-policy={policy_path}',
'--ig-mode=full', '--ig-mode=full',
'--ig-pass-filter=all', '--ig-pass-filter=all',
@@ -209,6 +209,14 @@ int main(void) {
f'--ig-source-path={src_c}', f'--ig-source-path={src_c}',
str(bc_ios), '-o', str(obf_ios), str(bc_ios), '-o', str(obf_ios),
], check=True) ], check=True)
delta_tables = [
line for line in obf_ios.read_text(encoding='utf-8').splitlines()
if line.startswith('@__ig_ibt1_')
]
self.assertTrue(delta_tables)
for table in delta_tables:
self.assertIn('i64 sub (', table)
self.assertNotIn('i64 add (', table)
subprocess.run([ subprocess.run([
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
+70
View File
@@ -2,6 +2,7 @@ import hashlib
import json import json
from pathlib import Path from pathlib import Path
import re import re
import struct
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
@@ -12,6 +13,7 @@ TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
sys.path.insert(0, str(TOOLS_LLVM_OBF)) sys.path.insert(0, str(TOOLS_LLVM_OBF))
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402 from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
from verify_macho_indirect_calls import parse_macho_sections # noqa: E402
def require_host_opt() -> str: def require_host_opt() -> str:
@@ -27,6 +29,74 @@ def macos_sdk_path() -> str:
class TestIndirectCallPass(unittest.TestCase): class TestIndirectCallPass(unittest.TestCase):
def test_ios_linker_preserves_indirect_call_destinations(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = subprocess.check_output(
['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True,
).strip()
target = ['-target', 'arm64-apple-ios15.0', '-isysroot', sdk]
with tempfile.TemporaryDirectory(prefix='ig-icall-ios-link-') as td:
p = Path(td)
source = p / 'ios_call.c'
source.write_text(
'__attribute__((noinline)) int ios_add(int x) { return x + 7; }\n'
'__attribute__((noinline)) int ios_sub(int x) { return x - 9; }\n'
'int main(int argc, char **argv) { return ios_add(argc) + ios_sub(argc); }\n',
encoding='utf-8',
)
bc = p / 'ios_call.bc'
subprocess.run([
clang, *target, '-O2', '-emit-llvm', '-c', str(source), '-o', str(bc),
], check=True)
for dual in (False, True):
with self.subTest(dual=dual):
policy = p / 'policy.json'
policy.write_text(json.dumps({
'indirect_call_targets': [{'path_contains': source.name}],
'indirect_call_dual_table': dual,
}), encoding='utf-8')
obf = p / 'obf.bc'
obj = p / 'obf.o'
binary = p / 'app'
subprocess.run([
opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy}',
'--ig-mode=full', '--ig-pass-filter=icall',
'--ig-seed=ios_call_relocation_regression',
f'--ig-source-path={source}', str(bc), '-o', str(obf),
], check=True)
subprocess.run([
clang, *target, '-O2', '-Xclang', '-disable-llvm-passes',
'-x', 'ir', '-c', str(obf), '-o', str(obj),
], check=True)
subprocess.run([
clang, *target, '-Wl,-dead_strip', str(obj), '-o', str(binary),
], check=True)
nm = subprocess.check_output(['xcrun', 'nm', '-n', str(binary)], text=True)
symbols = {}
for line in nm.splitlines():
fields = line.split()
if len(fields) == 3:
address, _, name = fields
symbols[name] = int(address, 16)
anchor, = [addr for name, addr in symbols.items() if name.startswith('___ig_ca_')]
prefix = '___ig_cs1_' if dual else '___ig_ct_'
table, = [addr for name, addr in symbols.items() if name.startswith(prefix)]
section = next(
section for name, section in parse_macho_sections(binary).items()
if not name.endswith(',*')
and section['addr'] <= table
and table + 16 <= section['addr'] + section['size']
)
offset = section['offset'] + table - section['addr']
deltas = struct.unpack_from('<2q', binary.read_bytes(), offset)
self.assertCountEqual(
[anchor + delta for delta in deltas],
[symbols['_ios_add'], symbols['_ios_sub']],
)
def test_c_same_tu_cross_tu_dead_strip_and_dylib_safety(self): def test_c_same_tu_cross_tu_dead_strip_and_dylib_safety(self):
opt_path = require_host_opt() opt_path = require_host_opt()
clang = detect_stock_tool('clang') clang = detect_stock_tool('clang')