feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固

- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测
- llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言)
- tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化)
- tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+19
View File
@@ -0,0 +1,19 @@
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/include")
add_llvm_pass_plugin(IGObfuscator
src/IGPluginMain.cpp
src/IGPolicyConfig.cpp
src/IGStringEncryption.cpp
src/IGFunctionOutline.cpp
src/IGOpaqueFieldAccess.cpp
src/IGOpaqueConstants.cpp
src/IGArithmetic.cpp
src/IGIndirectCall.cpp
src/IGBasicBlockSplit.cpp
src/IGFlattening.cpp
src/IGIndirectBranch.cpp
src/IGAntiHooking.cpp
DEPENDS
intrinsics_gen
BUILDTREE_ONLY
)
+142
View File
@@ -0,0 +1,142 @@
#ifndef IG_OBFUSCATOR_PASS_UTILS_H
#define IG_OBFUSCATOR_PASS_UTILS_H
#include "IGPolicyConfig.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/SHA256.h"
#include "llvm/TargetParser/Triple.h"
#include <algorithm>
#include <string>
#include <vector>
namespace igobf {
inline llvm::StringRef stripObjCMarker(llvm::StringRef Name) {
if (!Name.empty() && Name.front() == '\x01')
return Name.drop_front(1);
return Name;
}
inline bool isMachOAArch64NonArm64e(const llvm::Module &M) {
if (M.getTargetTriple().empty())
return true;
llvm::Triple TT(M.getTargetTriple());
return TT.isOSBinFormatMachO() && TT.isAArch64() &&
TT.getArchName() != "arm64e";
}
inline std::string computeShortModuleTag(llvm::StringRef Seed,
llvm::StringRef ModId,
llvm::StringRef SourcePath) {
llvm::SHA256 Hasher;
Hasher.update(Seed);
Hasher.update("|");
Hasher.update(ModId);
Hasher.update("|");
Hasher.update(SourcePath);
auto Digest = Hasher.final();
return llvm::toHex(llvm::ArrayRef<uint8_t>(Digest.data(), 4),
/*LowerCase=*/true);
}
inline bool isCompilerSynthesizedFunction(const llvm::Function &F,
const IGPolicyConfig &Policy) {
if (Policy.hasAnnotation(F, "ig_flatten"))
return false;
llvm::StringRef Name = stripObjCMarker(F.getName());
if (Name.starts_with("block_copy_helper") ||
Name.starts_with("block_destroy_helper") ||
Name.starts_with("__copy_helper_block_") ||
Name.starts_with("___copy_helper_block_") ||
Name.starts_with("__destroy_helper_block_") ||
Name.starts_with("___destroy_helper_block_") ||
Name.starts_with("objectdestroy") ||
Name.ends_with(" .cxx_destruct]") ||
Name.contains(".resume.")) {
return true;
}
if (Name.starts_with("$s") || Name.starts_with("_$s")) {
if (Name.ends_with("Tm") || Name.ends_with("Wl") ||
Name.ends_with("WL") || Name.ends_with("CMa") ||
Name.ends_with("VMa") || Name.ends_with("OMa") ||
Name.ends_with("WOh") || Name.ends_with("WOy") ||
Name.ends_with("WOe") || Name.ends_with("WOc") ||
Name.ends_with("WOb") || Name.ends_with("WOd") ||
Name.ends_with("TR") || Name.ends_with("TA")) {
return true;
}
}
if (const llvm::Module *M = F.getParent()) {
if (M->getNamedMetadata("llvm.dbg.cu") != nullptr) {
const llvm::DISubprogram *SP = F.getSubprogram();
if (!SP || SP->isArtificial() ||
SP->getFilename().contains("<compiler-generated>")) {
return true;
}
}
}
return false;
}
inline bool matchesAnySubstring(const llvm::Function &F,
const std::vector<std::string> &Patterns) {
llvm::StringRef CleanName = stripObjCMarker(F.getName());
for (const std::string &Pat : Patterns) {
if (!Pat.empty() &&
(CleanName.contains(Pat) || F.getName().contains(Pat))) {
return true;
}
}
return false;
}
inline bool isFunctionSafeForTransform(
const llvm::Function &F, const IGPolicyConfig &Policy,
const std::vector<std::string> *ExtraExemptSubstrings = nullptr) {
if (F.isDeclaration() || Policy.isFunctionExempt(F))
return false;
if (llvm::GlobalValue::isWeakForLinker(F.getLinkage()) ||
F.hasAvailableExternallyLinkage()) {
return false;
}
if (F.isPresplitCoroutine() || F.hasFnAttribute(llvm::Attribute::Naked))
return false;
if (F.getCallingConv() == llvm::CallingConv::SwiftTail)
return false;
if (F.hasSection()) {
llvm::StringRef Sec = F.getSection();
if (Sec.contains("__mod_init_func") || Sec.contains("__objc_init_func") ||
Sec.contains("__mod_term_func")) {
return false;
}
}
if (isCompilerSynthesizedFunction(F, Policy))
return false;
if (ExtraExemptSubstrings &&
matchesAnySubstring(F, *ExtraExemptSubstrings)) {
return false;
}
return true;
}
inline llvm::DebugLoc resolveInstDebugLoc(const llvm::Instruction *I,
const llvm::Function &F) {
if (I && I->getDebugLoc())
return I->getDebugLoc();
if (llvm::DISubprogram *SP = F.getSubprogram()) {
unsigned Line = SP->getScopeLine() ? SP->getScopeLine() : SP->getLine();
return llvm::DILocation::get(F.getContext(), Line, 0, SP);
}
return llvm::DebugLoc();
}
} // namespace igobf
#endif
+314
View File
@@ -0,0 +1,314 @@
#ifndef IG_OBFUSCATOR_POLICY_CONFIG_H
#define IG_OBFUSCATOR_POLICY_CONFIG_H
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
namespace llvm {
class Function;
class Module;
} // namespace llvm
namespace igobf {
enum class ObfMode {
Off,
Noop,
StrOnly,
Full,
};
enum class PassFilter {
All,
StrOnly,
FlaOnly,
IcallOnly,
OpaqueConstOnly,
ArithOnly,
IbrOnly,
AntiHookOnly,
OutlineOnly,
FieldOnly,
BBSplitOnly,
};
enum class FlattenTopology {
Polymorphic,
StarSwitch,
};
struct TargetRule {
std::string Id;
std::string PathContains;
std::string FunctionContains;
bool WholeModuleIfNoDebug = false;
std::optional<unsigned> Rounds;
std::optional<unsigned> MaxPerFn;
std::optional<unsigned> Probability;
std::optional<bool> NonlinearMBA;
std::optional<bool> OpaqueZero;
};
struct StringReplaceRule {
std::string Exact;
std::string Replace;
};
struct SkippedFunctionRecord {
std::string Name;
std::string Reason;
};
struct FlattenedFunctionDetail {
std::string Name;
std::string Topology;
std::string Encoding;
unsigned Blocks = 0;
};
struct IGAuditRecord {
std::string Mode;
std::string PassFilter;
std::string Seed;
std::string SourcePath;
std::string ModuleId;
std::vector<std::string> FunctionsFlattened;
std::vector<FlattenedFunctionDetail> FunctionsFlattenedDetails;
std::vector<SkippedFunctionRecord> FunctionsSkipped;
unsigned StringsEncryptedCount = 0;
std::vector<std::string> StringsEncryptedFunctions;
unsigned StringsStackEncryptedCount = 0;
unsigned ObjCStringsEncryptedCount = 0;
unsigned SwiftStringsEncryptedCount = 0;
unsigned StringsReplacedCount = 0;
unsigned StringsSkippedCount = 0;
unsigned PathsScrubbedCount = 0;
unsigned IndirectCallsCount = 0;
std::vector<std::string> IndirectCallsFunctions;
bool IndirectCallDualTable = false;
unsigned OpaqueConstantsCount = 0;
std::vector<std::string> OpaqueConstantsFunctions;
unsigned ArithmeticRewritesCount = 0;
std::vector<std::string> ArithmeticFunctions;
unsigned IndirectBranchesCount = 0;
std::vector<std::string> IndirectBranchesFunctions;
unsigned AntiHookFunctionsCount = 0;
std::vector<std::string> AntiHookFunctions;
unsigned FunctionsOutlinedCount = 0;
std::vector<std::string> OutlinedFunctions;
unsigned OpaqueFieldAccessCount = 0;
std::vector<std::string> OpaqueFieldFunctions;
unsigned BBSplitCount = 0;
std::vector<std::string> BBSplitFunctions;
unsigned NonlinearMBACount = 0;
unsigned OpaqueZeroCount = 0;
std::vector<std::string> AnnotatedTargets;
bool writeToFile(llvm::StringRef OutPath) const;
};
class IGDeterministicRNG {
public:
IGDeterministicRNG(llvm::StringRef Seed, llvm::StringRef ModuleId,
llvm::StringRef ItemId);
std::array<uint8_t, 32> nextBlock();
uint32_t nextU32();
uint32_t nextNonZeroU32();
uint64_t nextU64();
uint64_t nextNonZeroU64();
uint8_t nextNonZeroByte();
template <typename VecT> void shuffle(VecT &Items) {
if (Items.size() < 2)
return;
for (size_t i = Items.size() - 1; i > 0; --i) {
size_t j = static_cast<size_t>(nextU32() % static_cast<uint32_t>(i + 1));
if (i != j)
std::swap(Items[i], Items[j]);
}
}
private:
std::string Prefix_;
uint64_t Counter_ = 0;
std::array<uint8_t, 32> Buffer_{};
size_t Offset_ = 32;
};
class IGPolicyConfig {
public:
static IGPolicyConfig loadFromCLI(const llvm::Module &M,
IGAuditRecord &AuditOut);
ObfMode mode() const { return Mode_; }
PassFilter passFilter() const { return Filter_; }
llvm::StringRef seed() const { return Seed_; }
llvm::StringRef sourcePath() const { return SourcePath_; }
llvm::StringRef swiftModuleName() const { return SwiftModuleName_; }
llvm::StringRef auditOutPath() const { return AuditOutPath_; }
bool isStringEncryptionEnabled() const;
bool isIndirectCallEnabled() const;
bool isFlatteningEnabled() const;
bool isOpaqueConstantsEnabled() const;
bool isArithmeticEnabled() const;
bool isIndirectBranchEnabled() const;
bool isAntiHookingEnabled() const;
bool isFunctionOutlineEnabled() const;
bool isOpaqueFieldEnabled() const;
bool isBBSplitEnabled() const;
FlattenTopology flattenTopology() const { return FlattenTopology_; }
unsigned bogusBlockCount() const { return BogusBlockCount_; }
bool splitLinearBlocks() const { return SplitLinearBlocks_; }
unsigned opaqueConstMaxPerFn() const { return OpaqueConstMaxPerFn_; }
bool opaqueConstOpaqueZero() const { return OpaqueConstOpaqueZero_; }
unsigned arithmeticRounds() const { return ArithmeticRounds_; }
unsigned arithmeticMaxPerFn() const { return ArithmeticMaxPerFn_; }
bool arithmeticNonlinearMBA() const { return ArithmeticNonlinearMBA_; }
unsigned stringEncryptStackMaxLen() const { return StringEncryptStackMaxLen_; }
bool isIndirectCallDualTableEnabled() const { return IndirectCallDualTable_; }
unsigned functionOutlineMaxPerFn() const { return FunctionOutlineMaxPerFn_; }
unsigned functionOutlineMinInsts() const { return FunctionOutlineMinInsts_; }
unsigned opaqueFieldMaxPerFn() const { return OpaqueFieldMaxPerFn_; }
unsigned bbSplitMaxPerFn() const { return BBSplitMaxPerFn_; }
unsigned bbSplitMinInsts() const { return BBSplitMinInsts_; }
bool isModuleExempt(const llvm::Module &M) const;
bool isFunctionExempt(const llvm::Function &F) const;
bool shouldEncryptStringsInFunction(const llvm::Function &F) const;
bool shouldEncryptObjCStringsInFunction(const llvm::Function &F) const;
bool shouldEncryptSwiftStringsInFunction(const llvm::Function &F) const;
bool shouldStackEncryptStringsInFunction(const llvm::Function &F) const;
const std::vector<StringReplaceRule> &stringReplaceRules() const {
return StringReplaceRules_;
}
bool shouldIndirectCallInFunction(const llvm::Function &F) const;
bool shouldFlattenFunction(const llvm::Function &F) const;
bool shouldObfuscateConstantsInFunction(const llvm::Function &F) const;
bool shouldObfuscateArithmeticInFunction(const llvm::Function &F) const;
bool shouldIndirectBranchInFunction(const llvm::Function &F) const;
bool shouldAntiHookFunction(const llvm::Function &F) const;
bool shouldOutlineFunction(const llvm::Function &F) const;
bool shouldObfuscateFieldAccessInFunction(const llvm::Function &F) const;
bool shouldSplitBasicBlocksInFunction(const llvm::Function &F) const;
const TargetRule *findArithmeticRule(const llvm::Function &F) const;
const TargetRule *findOpaqueConstRule(const llvm::Function &F) const;
const TargetRule *findBBSplitRule(const llvm::Function &F) const;
const std::vector<std::string> &indirectCallSameImagePrefixes() const {
return IndirectCallSameImagePrefixes_;
}
const std::vector<std::string> &exemptFunctionPrefixes() const {
return ExemptFunctionPrefixes_;
}
const std::vector<std::string> &scrubPathSubstrings() const {
return ScrubPathSubstrings_;
}
const std::vector<std::string> &opaqueConstExemptFunctions() const {
return OpaqueConstExemptFunctions_;
}
const std::vector<std::string> &arithmeticExemptFunctions() const {
return ArithmeticExemptFunctions_;
}
const std::vector<std::string> &indirectBranchExemptFunctions() const {
return IndirectBranchExemptFunctions_;
}
const std::vector<std::string> &antiHookingExemptFunctions() const {
return AntiHookingExemptFunctions_;
}
const std::vector<std::string> &functionOutlineExemptFunctions() const {
return FunctionOutlineExemptFunctions_;
}
const std::vector<std::string> &opaqueFieldExemptFunctions() const {
return OpaqueFieldExemptFunctions_;
}
const std::vector<std::string> &bbSplitExemptFunctions() const {
return BBSplitExemptFunctions_;
}
void collectAnnotations(const llvm::Module &M);
bool hasAnnotation(const llvm::Function &F, llvm::StringRef Tag) const;
static std::string resolveFunctionSourcePath(const llvm::Function &F,
llvm::StringRef FallbackPath);
private:
const TargetRule *findMatchingRule(const std::vector<TargetRule> &Rules,
const llvm::Function &F) const;
bool matchesAnyRule(const std::vector<TargetRule> &Rules,
const llvm::Function &F) const;
ObfMode Mode_ = ObfMode::Full;
PassFilter Filter_ = PassFilter::All;
FlattenTopology FlattenTopology_ = FlattenTopology::Polymorphic;
unsigned BogusBlockCount_ = 0;
bool SplitLinearBlocks_ = false;
unsigned OpaqueConstMaxPerFn_ = 64;
bool OpaqueConstOpaqueZero_ = false;
unsigned ArithmeticRounds_ = 1;
unsigned ArithmeticMaxPerFn_ = 128;
bool ArithmeticNonlinearMBA_ = false;
unsigned StringEncryptStackMaxLen_ = 128;
bool IndirectCallDualTable_ = false;
unsigned FunctionOutlineMaxPerFn_ = 2;
unsigned FunctionOutlineMinInsts_ = 6;
unsigned OpaqueFieldMaxPerFn_ = 32;
unsigned BBSplitMaxPerFn_ = 4;
unsigned BBSplitMinInsts_ = 8;
std::string Seed_ = "m0_seed_20261119_v1";
std::string SourcePath_;
std::string SwiftModuleName_;
std::string AuditOutPath_;
std::vector<std::string> ExemptPathSubstrings_;
std::vector<std::string> ExemptFunctionPrefixes_;
std::vector<std::string> ScrubPathSubstrings_;
std::vector<TargetRule> StringEncryptTargets_;
std::vector<TargetRule> StringEncryptObjCTargets_;
std::vector<TargetRule> StringEncryptSwiftTargets_;
std::vector<TargetRule> StringEncryptStackTargets_;
std::vector<StringReplaceRule> StringReplaceRules_;
std::vector<TargetRule> IndirectCallTargets_;
std::vector<std::string> IndirectCallSameImagePrefixes_;
std::vector<TargetRule> FlattenTargets_;
std::vector<TargetRule> OpaqueConstTargets_;
std::vector<std::string> OpaqueConstExemptFunctions_;
std::vector<TargetRule> ArithmeticTargets_;
std::vector<std::string> ArithmeticExemptFunctions_;
std::vector<TargetRule> IndirectBranchTargets_;
std::vector<std::string> IndirectBranchExemptFunctions_;
std::vector<TargetRule> AntiHookingTargets_;
std::vector<std::string> AntiHookingExemptFunctions_;
std::vector<TargetRule> FunctionOutlineTargets_;
std::vector<std::string> FunctionOutlineExemptFunctions_;
std::vector<TargetRule> OpaqueFieldTargets_;
std::vector<std::string> OpaqueFieldExemptFunctions_;
std::vector<TargetRule> BBSplitTargets_;
std::vector<std::string> BBSplitExemptFunctions_;
llvm::StringSet<> AnnotatedFlatten_;
llvm::StringSet<> AnnotatedStr_;
llvm::StringSet<> AnnotatedIcall_;
llvm::StringSet<> AnnotatedConst_;
llvm::StringSet<> AnnotatedArith_;
llvm::StringSet<> AnnotatedIbr_;
llvm::StringSet<> AnnotatedAntiHook_;
llvm::StringSet<> AnnotatedOutline_;
llvm::StringSet<> AnnotatedField_;
llvm::StringSet<> AnnotatedBBSplit_;
llvm::StringSet<> AnnotatedExempt_;
};
} // namespace igobf
#endif
+76
View File
@@ -0,0 +1,76 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/ErrorHandling.h"
#include <cstdint>
using namespace llvm;
namespace igobf {
bool runAntiHooking(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isAntiHookingEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
LLVMContext &Ctx = M.getContext();
bool Changed = false;
// AArch64 AAPCS64 IP0/IP1 (x16/x17) harmless 8-byte prologue:
// mov x17, x17 -> orr x17, xzr, x17 -> 0xAA1103F1
// mov x16, x16 -> orr x16, xzr, x16 -> 0xAA1003F0
// Breaks naive inline-hook trampolines (Substrate/Dobby/Frida 16-byte patch
// assumptions or instruction-decoding prologues) without clobbering state.
static constexpr uint8_t kPrologueX17X16[8] = {
0xf1, 0x03, 0x11, 0xaa, 0xf0, 0x03, 0x10, 0xaa,
};
static constexpr uint8_t kPrologueX16X17[8] = {
0xf0, 0x03, 0x10, 0xaa, 0xf1, 0x03, 0x11, 0xaa,
};
for (Function &F : M) {
if (!Policy.shouldAntiHookFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.antiHookingExemptFunctions())) {
continue;
}
if (F.empty() || F.hasPrologueData() || !F.doesNotThrow() ||
F.hasPersonalityFn()) {
continue;
}
if (F.hasFnAttribute(Attribute::Naked) ||
F.hasFnAttribute("branch-target-enforcement") ||
F.getCallingConv() == CallingConv::SwiftTail) {
continue;
}
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(), F.getName());
const uint8_t *Seq =
((RNG.nextU32() & 1U) == 0) ? kPrologueX17X16 : kPrologueX16X17;
Constant *Prologue =
ConstantDataVector::get(Ctx, ArrayRef<uint8_t>(Seq, 8));
F.setPrologueData(Prologue);
if (verifyFunction(F, &errs())) {
report_fatal_error(Twine("[IGAntiHooking] IR verification failed on ") +
F.getName());
}
++Audit.AntiHookFunctionsCount;
Audit.AntiHookFunctions.push_back(F.getName().str());
Changed = true;
}
return Changed;
}
} // namespace igobf
+299
View File
@@ -0,0 +1,299 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
using namespace llvm;
namespace igobf {
namespace {
uint64_t bitMaskForWidth(unsigned BW) {
return (BW == 32) ? 0xFFFFFFFFULL : 0xFFFFFFFFFFFFFFFFULL;
}
// Compute modular inverse A^{-1} mod 2^W (W in {32, 64}) via Newton-Raphson.
uint64_t modInverseU64(uint64_t A, unsigned BW) {
uint64_t Mask = bitMaskForWidth(BW);
uint64_t Inv = 1;
for (int i = 0; i < 6; ++i) {
Inv = (Inv * (2ULL - A * Inv)) & Mask;
}
assert(((A * Inv) & Mask) == 1ULL && "A must be odd");
return Inv;
}
bool isEligibleBinaryOp(const BinaryOperator *BO) {
if (!BO || BO->getParent()->isEHPad())
return false;
auto *IntTy = dyn_cast<IntegerType>(BO->getType());
if (!IntTy)
return false;
unsigned BW = IntTy->getBitWidth();
if (BW != 32 && BW != 64)
return false;
switch (BO->getOpcode()) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Xor:
case Instruction::And:
case Instruction::Or:
break;
default:
return false;
}
// Skip trivial two-constant folding leftovers (should not exist after -O2).
if (isa<ConstantInt>(BO->getOperand(0)) &&
isa<ConstantInt>(BO->getOperand(1))) {
return false;
}
return true;
}
// Rewrites integer ops with bit-exact mod-2^W Mixed Boolean-Arithmetic formulas.
// Note: NSW/NUW flags are intentionally omitted on generated ops so intermediate
// modulo-2^W wraps never introduce LLVM poison.
Value *emitLinearMBAForPair(IRBuilder<> &B, unsigned Opcode, Value *X,
Value *Y, unsigned Variant) {
Type *Ty = X->getType();
Value *One = ConstantInt::get(Ty, 1);
switch (Opcode) {
case Instruction::Add:
switch (Variant % 3) {
case 0:
// x + y == (x ^ y) + 2 * (x & y)
return B.CreateAdd(B.CreateXor(X, Y),
B.CreateShl(B.CreateAnd(X, Y), One));
case 1:
// x + y == (x | y) + (x & y)
return B.CreateAdd(B.CreateOr(X, Y), B.CreateAnd(X, Y));
default:
// x + y == 2 * (x | y) - (x ^ y)
return B.CreateSub(B.CreateShl(B.CreateOr(X, Y), One),
B.CreateXor(X, Y));
}
case Instruction::Sub:
switch (Variant % 3) {
case 0:
// x - y == (x ^ y) - 2 * (~x & y)
return B.CreateSub(B.CreateXor(X, Y),
B.CreateShl(B.CreateAnd(B.CreateNot(X), Y), One));
case 1:
// x - y == (x & ~y) - (~x & y)
return B.CreateSub(B.CreateAnd(X, B.CreateNot(Y)),
B.CreateAnd(B.CreateNot(X), Y));
default: {
// x - y == ((x ^ ~y) + 2 * (x & ~y)) + 1
Value *NotY = B.CreateNot(Y);
Value *AddNotY = B.CreateAdd(B.CreateXor(X, NotY),
B.CreateShl(B.CreateAnd(X, NotY), One));
return B.CreateAdd(AddNotY, One);
}
}
case Instruction::Xor:
switch (Variant % 3) {
case 0:
// x ^ y == (x | y) - (x & y)
return B.CreateSub(B.CreateOr(X, Y), B.CreateAnd(X, Y));
case 1:
// x ^ y == (x + y) - 2 * (x & y)
return B.CreateSub(B.CreateAdd(X, Y),
B.CreateShl(B.CreateAnd(X, Y), One));
default:
// x ^ y == (x & ~y) | (~x & y)
return B.CreateOr(B.CreateAnd(X, B.CreateNot(Y)),
B.CreateAnd(B.CreateNot(X), Y));
}
case Instruction::And:
switch (Variant % 3) {
case 0:
// x & y == (x + y) - (x | y)
return B.CreateSub(B.CreateAdd(X, Y), B.CreateOr(X, Y));
case 1:
// x & y == ~(~x | ~y)
return B.CreateNot(B.CreateOr(B.CreateNot(X), B.CreateNot(Y)));
default:
// x & y == (x | y) - (x ^ y)
return B.CreateSub(B.CreateOr(X, Y), B.CreateXor(X, Y));
}
case Instruction::Or:
switch (Variant % 3) {
case 0:
// x | y == (x ^ y) + (x & y)
return B.CreateAdd(B.CreateXor(X, Y), B.CreateAnd(X, Y));
case 1:
// x | y == ~(~x & ~y)
return B.CreateNot(B.CreateAnd(B.CreateNot(X), B.CreateNot(Y)));
default:
// x | y == (x + y) - (x & y)
return B.CreateSub(B.CreateAdd(X, Y), B.CreateAnd(X, Y));
}
default:
return nullptr;
}
}
Value *emitLinearMBA(IRBuilder<> &B, BinaryOperator *BO, unsigned Variant) {
return emitLinearMBAForPair(B, BO->getOpcode(), BO->getOperand(0),
BO->getOperand(1), Variant);
}
// Self-inverse mod-2^W quadratic half-Feistel codec:
// T(v) = v ^ (((v * v) + Key) << (W/2)). Since the low W/2 bits are unchanged,
// T(T(v)) == v identically across all bit patterns without NSW/NUW flags.
Value *emitQuadraticHalfFeistel(IRBuilder<> &B, Value *V, uint64_t Key,
unsigned BW) {
Type *Ty = V->getType();
Value *One = ConstantInt::get(Ty, 1);
Value *HalfC = ConstantInt::get(Ty, BW / 2);
Value *KeyC = ConstantInt::get(Ty, Key);
Value *Sq1 = B.CreateMul(V, V);
Value *T1 = B.CreateShl(B.CreateAdd(Sq1, KeyC), HalfC);
// U = V ^ T1 written via non-xor MBA identity (V | T1) - (V & T1)
Value *U = B.CreateSub(B.CreateOr(V, T1), B.CreateAnd(V, T1));
Value *Sq2 = B.CreateMul(U, U);
Value *T2 = B.CreateShl(B.CreateAdd(Sq2, KeyC), HalfC);
// Out = U ^ T2 written via (U + T2) - 2*(U & T2)
return B.CreateSub(B.CreateAdd(U, T2), B.CreateShl(B.CreateAnd(U, T2), One));
}
Value *emitNonlinearMBA(IRBuilder<> &B, BinaryOperator *BO,
IGDeterministicRNG &RNG) {
unsigned Opcode = BO->getOpcode();
Type *Ty = BO->getType();
unsigned BW = Ty->getIntegerBitWidth();
uint64_t Mask = bitMaskForWidth(BW);
Value *X = BO->getOperand(0);
Value *Y = BO->getOperand(1);
if (Opcode == Instruction::Add || Opcode == Instruction::Sub) {
uint64_t A = (RNG.nextNonZeroU64() | 1ULL) & Mask;
uint64_t AInv = modInverseU64(A, BW);
uint64_t B1 = RNG.nextNonZeroU64() & Mask;
uint64_t B2 = RNG.nextNonZeroU64() & Mask;
Value *AC = ConstantInt::get(Ty, A);
Value *AInvC = ConstantInt::get(Ty, AInv);
Value *U = B.CreateAdd(B.CreateMul(X, AC), ConstantInt::get(Ty, B1));
Value *V = B.CreateAdd(B.CreateMul(Y, AC), ConstantInt::get(Ty, B2));
Value *Comb = emitLinearMBAForPair(B, Opcode, U, V, RNG.nextU32());
uint64_t BDelta = (Opcode == Instruction::Add) ? ((B1 + B2) & Mask)
: ((B1 - B2) & Mask);
Value *Res =
B.CreateMul(B.CreateSub(Comb, ConstantInt::get(Ty, BDelta)), AInvC);
if ((RNG.nextU32() & 1U) == 0) {
Res = emitQuadraticHalfFeistel(B, Res, RNG.nextNonZeroU64() & Mask, BW);
}
return Res;
}
Value *Lin = emitLinearMBA(B, BO, RNG.nextU32());
if (!Lin)
return nullptr;
return emitQuadraticHalfFeistel(B, Lin, RNG.nextNonZeroU64() & Mask, BW);
}
} // namespace
bool runArithmeticObfuscation(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isArithmeticEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
bool Changed = false;
const unsigned DefaultRounds = Policy.arithmeticRounds();
const unsigned DefaultMaxPerFn = Policy.arithmeticMaxPerFn();
const bool DefaultNonlinear = Policy.arithmeticNonlinearMBA();
for (Function &F : M) {
if (!Policy.shouldObfuscateArithmeticInFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.arithmeticExemptFunctions())) {
continue;
}
const TargetRule *Rule = Policy.findArithmeticRule(F);
unsigned Rounds = (Rule && Rule->Rounds) ? *Rule->Rounds : DefaultRounds;
unsigned MaxPerFn =
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
unsigned Prob =
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
bool UseNonlinear =
(Rule && Rule->NonlinearMBA) ? *Rule->NonlinearMBA : DefaultNonlinear;
if (MaxPerFn == 0 || Prob == 0)
continue;
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
(F.getName() + "|arith").str());
unsigned FnRewrites = 0;
for (unsigned Round = 0; Round < Rounds && FnRewrites < MaxPerFn; ++Round) {
SmallVector<BinaryOperator *, 32> Candidates;
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
if (isEligibleBinaryOp(BO))
Candidates.push_back(BO);
}
}
}
if (Candidates.empty())
break;
for (BinaryOperator *BO : Candidates) {
if (FnRewrites >= MaxPerFn)
break;
if (Prob < 100U && (RNG.nextU32() % 100U) >= Prob)
continue;
IRBuilder<> B(BO);
B.SetCurrentDebugLocation(resolveInstDebugLoc(BO, F));
Value *Replacement = nullptr;
if (UseNonlinear && Round == 0) {
Replacement = emitNonlinearMBA(B, BO, RNG);
if (Replacement)
++Audit.NonlinearMBACount;
} else {
Replacement = emitLinearMBA(B, BO, RNG.nextU32());
}
if (!Replacement)
continue;
BO->replaceAllUsesWith(Replacement);
BO->eraseFromParent();
++FnRewrites;
++Audit.ArithmeticRewritesCount;
Changed = true;
}
}
if (FnRewrites > 0) {
if (verifyFunction(F, &errs())) {
report_fatal_error(Twine("[IGArithmetic] IR verification failed on ") +
F.getName());
}
Audit.ArithmeticFunctions.push_back(F.getName().str());
}
}
return Changed;
}
} // namespace igobf
+175
View File
@@ -0,0 +1,175 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace igobf {
namespace {
bool isBlockSafeToSplit(const BasicBlock &BB) {
if (BB.isEHPad() || isa<CatchSwitchInst>(BB.getTerminator()))
return false;
for (const Instruction &I : BB) {
if (I.getType()->isTokenTy())
return false;
if (const auto *AI = dyn_cast<AllocaInst>(&I)) {
if (AI->isSwiftError())
return false;
}
if (const auto *CB = dyn_cast<CallBase>(&I)) {
if (CB->isInlineAsm() || CB->isMustTailCall() ||
CB->getCallingConv() == CallingConv::SwiftTail) {
return false;
}
if (const Function *Callee = CB->getCalledFunction()) {
StringRef Name = Callee->getName();
if (Name.starts_with("llvm.coro."))
return false;
}
}
}
return true;
}
bool isDangerousSplitPoint(const Instruction &I) {
if (I.isTerminator() || isa<PHINode>(I) || isa<AllocaInst>(I) ||
isa<LandingPadInst>(I) || isa<DbgInfoIntrinsic>(I)) {
return true;
}
if (const auto *CB = dyn_cast<CallBase>(&I)) {
if (const Function *Callee = CB->getCalledFunction()) {
StringRef Name = Callee->getName();
if (Name.contains("objc_retainAutoreleasedReturnValue") ||
Name.contains("objc_unsafeClaimAutoreleasedReturnValue") ||
Name.starts_with("llvm.objc.clang.arc.use")) {
return true;
}
}
}
return false;
}
} // namespace
bool runBasicBlockSplit(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isBBSplitEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
const unsigned DefaultMaxPerFn = Policy.bbSplitMaxPerFn();
const unsigned MinInsts = Policy.bbSplitMinInsts();
bool Changed = false;
for (Function &F : M) {
if (!Policy.shouldSplitBasicBlocksInFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.bbSplitExemptFunctions())) {
continue;
}
if (F.isVarArg() || F.hasPersonalityFn() || F.empty())
continue;
const TargetRule *Rule = Policy.findBBSplitRule(F);
unsigned MaxPerFn =
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
unsigned Prob =
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
if (MaxPerFn == 0 || Prob == 0)
continue;
SmallVector<BasicBlock *, 16> WorkBlocks;
for (BasicBlock &BB : F)
WorkBlocks.push_back(&BB);
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
(F.getName() + "|bbsplit").str());
unsigned FnSplits = 0;
for (size_t wi = 0; wi < WorkBlocks.size() && FnSplits < MaxPerFn; ++wi) {
BasicBlock *BB = WorkBlocks[wi];
if (!BB || !isBlockSafeToSplit(*BB))
continue;
AllocaInst *LastAlloca = nullptr;
for (Instruction &Inst : *BB) {
if (auto *AI = dyn_cast<AllocaInst>(&Inst))
LastAlloca = AI;
}
BasicBlock::iterator FirstSplittable =
LastAlloca ? std::next(LastAlloca->getIterator())
: BB->getFirstInsertionPt();
while (FirstSplittable != BB->end() &&
(isa<AllocaInst>(*FirstSplittable) ||
isa<DbgInfoIntrinsic>(*FirstSplittable))) {
++FirstSplittable;
}
SmallVector<Instruction *, 32> SplittableInsts;
for (auto It = FirstSplittable; It != BB->end(); ++It) {
Instruction &I = *It;
if (!I.isTerminator() && !isa<DbgInfoIntrinsic>(I))
SplittableInsts.push_back(&I);
}
if (SplittableInsts.size() < MinInsts)
continue;
SmallVector<Instruction *, 16> CandidateTargets;
// Start at index 1 so the upper block retains at least 1 real instruction.
for (size_t idx = 1; idx < SplittableInsts.size(); ++idx) {
if (!isDangerousSplitPoint(*SplittableInsts[idx]))
CandidateTargets.push_back(SplittableInsts[idx]);
}
if (CandidateTargets.empty())
continue;
if (Prob < 100U && (RNG.nextU32() % 100U) >= Prob)
continue;
size_t Mid = CandidateTargets.size() / 2;
int Jitter = static_cast<int>(RNG.nextU32() % 3U) - 1;
ptrdiff_t Chosen = static_cast<ptrdiff_t>(Mid) + Jitter;
if (Chosen < 0)
Chosen = 0;
if (Chosen >= static_cast<ptrdiff_t>(CandidateTargets.size()))
Chosen = static_cast<ptrdiff_t>(CandidateTargets.size()) - 1;
Instruction *SplitBefore = CandidateTargets[static_cast<size_t>(Chosen)];
BasicBlock *NewBB = BB->splitBasicBlock(SplitBefore->getIterator(),
BB->getName() + ".ig.spl");
if (F.getSubprogram() && BB->getTerminator() &&
!BB->getTerminator()->getDebugLoc()) {
BB->getTerminator()->setDebugLoc(
resolveInstDebugLoc(&*NewBB->begin(), F));
}
++FnSplits;
++Audit.BBSplitCount;
Changed = true;
if (FnSplits < MaxPerFn) {
WorkBlocks.push_back(BB);
WorkBlocks.push_back(NewBB);
}
}
if (FnSplits > 0) {
if (verifyFunction(F, &errs())) {
report_fatal_error(Twine("[IGBasicBlockSplit] IR verification failed on ") +
F.getName());
}
Audit.BBSplitFunctions.push_back(F.getName().str());
}
}
return Changed;
}
} // namespace igobf
+832
View File
@@ -0,0 +1,832 @@
#include "IGPolicyConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <utility>
using namespace llvm;
namespace igobf {
namespace {
DebugLoc pickBlockDebugLoc(const BasicBlock &BB, const Function &F) {
for (const Instruction &I : BB) {
if (I.getDebugLoc())
return I.getDebugLoc();
}
if (DISubprogram *SP = F.getSubprogram()) {
unsigned Line = SP->getScopeLine() ? SP->getScopeLine() : SP->getLine();
return DILocation::get(F.getContext(), Line, 0, SP);
}
return DebugLoc();
}
bool isCompilerSynthesizedGlue(const Function &F,
const IGPolicyConfig &Policy) {
if (Policy.hasAnnotation(F, "ig_flatten"))
return false;
StringRef Name = F.getName();
if (!Name.empty() && Name.front() == '\x01')
Name = Name.drop_front();
if (Name.starts_with("block_copy_helper") ||
Name.starts_with("block_destroy_helper") ||
Name.starts_with("__copy_helper_block_") ||
Name.starts_with("___copy_helper_block_") ||
Name.starts_with("__destroy_helper_block_") ||
Name.starts_with("___destroy_helper_block_") ||
Name.starts_with("objectdestroy") ||
Name.ends_with(" .cxx_destruct]") ||
Name.contains(".resume.")) {
return true;
}
if (Name.starts_with("$s") || Name.starts_with("_$s")) {
if (Name.ends_with("Tm") || Name.ends_with("Wl") ||
Name.ends_with("WL") || Name.ends_with("CMa") ||
Name.ends_with("VMa") || Name.ends_with("OMa") ||
Name.ends_with("WOh") || Name.ends_with("WOy") ||
Name.ends_with("WOe") || Name.ends_with("WOc") ||
Name.ends_with("WOb") || Name.ends_with("WOd") ||
Name.ends_with("TR") || Name.ends_with("TA")) {
return true;
}
}
if (const Module *M = F.getParent()) {
if (M->getNamedMetadata("llvm.dbg.cu") != nullptr) {
const DISubprogram *SP = F.getSubprogram();
if (!SP || SP->isArtificial() ||
SP->getFilename().contains("<compiler-generated>")) {
return true;
}
}
}
return false;
}
bool checkFlatteningSafety(Function &F, const IGPolicyConfig &Policy,
std::string &SkipReason, bool &HasMustTailOut) {
HasMustTailOut = false;
if (GlobalValue::isWeakForLinker(F.getLinkage()) ||
F.hasAvailableExternallyLinkage()) {
SkipReason = "weak_or_linkonce_odr";
return false;
}
if (isCompilerSynthesizedGlue(F, Policy)) {
SkipReason = "compiler_synthesized_thunk";
return false;
}
if (!Policy.splitLinearBlocks() && F.size() < 3) {
SkipReason = "too_few_blocks";
return false;
}
const BasicBlock *EntryBB = &F.getEntryBlock();
const DataLayout &DL = F.getDataLayout();
uint64_t NonEntryAllocaBytes = 0;
for (BasicBlock &BB : F) {
if (BB.isEHPad()) {
SkipReason = "eh_pad";
return false;
}
Instruction *Term = BB.getTerminator();
if (!Term || isa<InvokeInst>(Term) || isa<ResumeInst>(Term) ||
isa<CatchSwitchInst>(Term) || isa<CatchReturnInst>(Term) ||
isa<CleanupReturnInst>(Term) || isa<IndirectBrInst>(Term) ||
isa<CallBrInst>(Term)) {
SkipReason = "eh_or_indirect_terminator";
return false;
}
for (Instruction &I : BB) {
if (I.getType()->isTokenTy()) {
SkipReason = "token_type";
return false;
}
if (auto *AI = dyn_cast<AllocaInst>(&I)) {
if (!AI->isStaticAlloca() || AI->isUsedWithInAlloca()) {
SkipReason = "dynamic_alloca";
return false;
}
if (AI->isSwiftError()) {
if (&BB != EntryBB) {
SkipReason = "non_entry_swifterror";
return false;
}
for (const User *U : AI->users()) {
const auto *UI = dyn_cast<Instruction>(U);
if (!UI || UI->getType()->isTokenTy()) {
SkipReason = "swifterror_complex_use";
return false;
}
}
}
if (&BB != EntryBB) {
TypeSize AllocSz = DL.getTypeAllocSize(AI->getAllocatedType());
if (AllocSz.isScalable()) {
SkipReason = "dynamic_alloca";
return false;
}
NonEntryAllocaBytes += AllocSz.getFixedValue();
if (NonEntryAllocaBytes > 4096u) {
SkipReason = "large_non_entry_alloca";
return false;
}
}
}
if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
if (II->getIntrinsicID() == Intrinsic::stacksave) {
for (const User *U : II->users()) {
const auto *Restore = dyn_cast<IntrinsicInst>(U);
if (!Restore ||
Restore->getIntrinsicID() != Intrinsic::stackrestore) {
SkipReason = "complex_stacksave";
return false;
}
}
}
}
if (auto *CB = dyn_cast<CallBase>(&I)) {
if (CB->isInlineAsm()) {
SkipReason = "inline_asm";
return false;
}
if (Function *Callee = CB->getCalledFunction()) {
if (Callee->getName().starts_with("llvm.coro.")) {
SkipReason = "unsplit_coroutine";
return false;
}
}
if (auto *CI = dyn_cast<CallInst>(&I)) {
if (CI->isMustTailCall()) {
HasMustTailOut = true;
Instruction *Next = CI->getNextNonDebugInstruction();
if (Next != Term || !isa<ReturnInst>(Term)) {
SkipReason = "non_terminal_musttail";
return false;
}
}
}
}
}
}
return true;
}
bool splitLinearBlocksIfNeeded(Function &F, Instruction *FirstNonAlloca,
std::string &SkipReason) {
if (F.size() >= 3)
return true;
SmallVector<Instruction *, 32> SplitCandidates;
for (BasicBlock &BB : F) {
bool SeenBodyInst = false;
for (Instruction &I : BB) {
if (isa<AllocaInst>(I) || isa<PHINode>(I) || I.isDebugOrPseudoInst() ||
I.isLifetimeStartOrEnd()) {
continue;
}
if (&I == FirstNonAlloca) {
SeenBodyInst = true;
continue;
}
if (!SeenBodyInst) {
SeenBodyInst = true;
continue;
}
if (I.isTerminator())
continue;
if (auto *CI = dyn_cast<CallInst>(&I)) {
if (CI->isMustTailCall())
continue;
}
SplitCandidates.push_back(&I);
}
}
if (SplitCandidates.size() < 2) {
if (F.size() == 2 && FirstNonAlloca != F.getEntryBlock().getTerminator())
return true;
SkipReason = "too_few_blocks";
return false;
}
SmallVector<Instruction *, 4> Chosen;
size_t N = SplitCandidates.size();
size_t Desired = (F.size() == 1) ? std::min<size_t>(3, N) : 1;
if (Desired >= N) {
for (size_t i = 0; i < N; ++i)
Chosen.push_back(SplitCandidates[i]);
} else {
for (size_t k = 1; k <= Desired; ++k) {
size_t Idx = ((k * N) / (Desired + 1));
if (Idx >= N)
Idx = N - 1;
Instruction *Inst = SplitCandidates[Idx];
if (std::find(Chosen.begin(), Chosen.end(), Inst) == Chosen.end())
Chosen.push_back(Inst);
}
}
// Split from back to front so earlier candidate pointers stay in valid blocks
for (auto It = Chosen.rbegin(); It != Chosen.rend(); ++It) {
Instruction *SplitAt = *It;
SplitAt->getParent()->splitBasicBlock(SplitAt->getIterator(),
"ig.lin.split");
}
return F.size() >= 2;
}
struct StateCipherParams {
unsigned Kind = 0; // 0=xor_rot, 1=odd_affine_mul, 2=add_xor
uint32_t MaskKey = 0;
uint32_t AddKey = 0;
uint32_t MulKey = 1;
uint32_t InvMulKey = 1;
uint32_t Rot = 7;
const char *encodingName() const {
switch (Kind) {
case 0:
return "xor_rot";
case 1:
return "odd_affine_mul";
default:
return "add_xor";
}
}
};
StateCipherParams makeCipherParams(IGDeterministicRNG &RNG) {
StateCipherParams P;
P.Kind = RNG.nextU32() % 3u;
P.MaskKey = RNG.nextNonZeroU32();
P.AddKey = RNG.nextNonZeroU32();
P.Rot = 1u + (RNG.nextU32() % 31u);
// Guarantee odd multiplier != 1 (low 2 bits = 0b11) and invert mod 2^32
P.MulKey = RNG.nextU32() | 3u;
uint32_t Inv = 1u;
for (int i = 0; i < 5; ++i)
Inv *= static_cast<uint32_t>(2u - P.MulKey * Inv);
P.InvMulKey = Inv;
return P;
}
uint32_t encodeState(uint32_t RawState, const StateCipherParams &P) {
if (P.Kind == 0) {
uint32_t X = RawState ^ P.MaskKey;
return (X << P.Rot) | (X >> (32u - P.Rot));
}
if (P.Kind == 1)
return static_cast<uint32_t>(RawState * P.MulKey + P.AddKey);
return static_cast<uint32_t>(RawState + P.AddKey) ^ P.MaskKey;
}
Value *emitDecodeState(IRBuilder<> &B, Value *Encoded, Type *I32Ty,
const StateCipherParams &P) {
if (P.Kind == 0) {
Value *R1 =
B.CreateLShr(Encoded, ConstantInt::get(I32Ty, P.Rot), "ig.dec.r1");
Value *R2 = B.CreateShl(Encoded, ConstantInt::get(I32Ty, 32u - P.Rot),
"ig.dec.r2");
Value *Unrot = B.CreateOr(R1, R2, "ig.dec.unrot");
return B.CreateXor(Unrot, ConstantInt::get(I32Ty, P.MaskKey), "ig.dec.xor");
}
if (P.Kind == 1) {
Value *Sub =
B.CreateSub(Encoded, ConstantInt::get(I32Ty, P.AddKey), "ig.dec.sub");
return B.CreateMul(Sub, ConstantInt::get(I32Ty, P.InvMulKey),
"ig.dec.mul");
}
Value *X =
B.CreateXor(Encoded, ConstantInt::get(I32Ty, P.MaskKey), "ig.dec.xor");
return B.CreateSub(X, ConstantInt::get(I32Ty, P.AddKey), "ig.dec.sub");
}
bool flattenSingleFunction(Function &F, const IGPolicyConfig &Policy,
FlattenedFunctionDetail &DetailOut,
std::string &SkipReason) {
bool HasMustTail = false;
if (!checkFlatteningSafety(F, Policy, SkipReason, HasMustTail))
return false;
LLVMContext &Ctx = F.getContext();
IntegerType *I32Ty = Type::getInt32Ty(Ctx);
BasicBlock &EntryBB = F.getEntryBlock();
// 1. Drop redundant stacksave/stackrestore (verified static-alloca-only) and
// hoist all static allocas across F before the first non-alloca in EntryBB.
SmallVector<IntrinsicInst *, 8> StackRestores;
SmallVector<IntrinsicInst *, 8> StackSaves;
SmallVector<AllocaInst *, 16> Allocas;
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
if (II->getIntrinsicID() == Intrinsic::stackrestore)
StackRestores.push_back(II);
else if (II->getIntrinsicID() == Intrinsic::stacksave)
StackSaves.push_back(II);
} else if (auto *AI = dyn_cast<AllocaInst>(&I)) {
Allocas.push_back(AI);
}
}
}
for (IntrinsicInst *SR : StackRestores)
SR->eraseFromParent();
for (IntrinsicInst *SS : StackSaves) {
if (SS->use_empty())
SS->eraseFromParent();
}
Instruction *FirstNonAlloca = nullptr;
for (Instruction &I : EntryBB) {
if (!isa<AllocaInst>(I)) {
FirstNonAlloca = &I;
break;
}
}
if (!FirstNonAlloca) {
SkipReason = "malformed_entry";
return false;
}
for (AllocaInst *AI : Allocas) {
if (AI->getParent() == &EntryBB && AI->comesBefore(FirstNonAlloca))
continue;
AI->moveBefore(FirstNonAlloca->getIterator());
}
// Recompute split point cleanly after hoisting allocas.
Instruction *SplitInst = nullptr;
for (Instruction &I : EntryBB) {
if (!isa<AllocaInst>(I)) {
SplitInst = &I;
break;
}
}
if (!SplitInst) {
SkipReason = "no_split_point";
return false;
}
if (Policy.splitLinearBlocks() && F.size() < 3) {
if (!splitLinearBlocksIfNeeded(F, SplitInst, SkipReason))
return false;
}
// If SplitInst is already the terminator and EntryBB has an unconditional br,
// avoid creating a degenerate empty body block unless there are already >= 2
// blocks outside EntryBB.
if (SplitInst == EntryBB.getTerminator() && F.size() < 3) {
SkipReason = "too_few_body_blocks";
return false;
}
BasicBlock *FirstBodyBB =
EntryBB.splitBasicBlock(SplitInst->getIterator(), "ig.entry.body");
SmallVector<BasicBlock *, 32> OrigBBs;
for (BasicBlock &BB : F) {
if (&BB != &EntryBB)
OrigBBs.push_back(&BB);
}
if (OrigBBs.size() < 2) {
SkipReason = "too_few_body_blocks";
return false;
}
// 2. Demote all PHINodes and cross-block SSA instructions to EntryBB allocas
SmallVector<PHINode *, 16> Phis;
for (BasicBlock &BB : F) {
for (PHINode &PN : BB.phis())
Phis.push_back(&PN);
}
for (PHINode *PN : Phis) {
DemotePHIToStack(PN, EntryBB.getTerminator()->getIterator());
}
SmallVector<Instruction *, 32> CrossBlockRegs;
for (BasicBlock *BB : OrigBBs) {
for (Instruction &I : *BB) {
if (I.isTerminator() || I.getType()->isVoidTy() || isa<AllocaInst>(I))
continue;
if (auto *CI = dyn_cast<CallInst>(&I)) {
if (CI->isMustTailCall())
continue;
}
bool UsedOutside = false;
for (const User *U : I.users()) {
const auto *UI = dyn_cast<Instruction>(U);
if (!UI || UI->getParent() != BB || isa<PHINode>(UI)) {
UsedOutside = true;
break;
}
}
if (UsedOutside)
CrossBlockRegs.push_back(&I);
}
}
for (Instruction *I : CrossBlockRegs) {
DemoteRegToStack(*I, /*VolatileLoads=*/false,
EntryBB.getTerminator()->getIterator());
}
// 3. Deterministic per-function RNG for layout, states, encoding, topology
IGDeterministicRNG RNG(Policy.seed(), F.getParent()->getModuleIdentifier(),
F.getName());
SmallVector<BasicBlock *, 32> ShuffledBBs(OrigBBs.begin(), OrigBBs.end());
RNG.shuffle(ShuffledBBs);
DenseMap<BasicBlock *, uint32_t> StateMap;
DenseMap<uint32_t, bool> UsedIds;
for (BasicBlock *BB : ShuffledBBs) {
uint32_t Id = 0;
do {
Id = RNG.nextNonZeroU32();
} while (UsedIds.contains(Id));
UsedIds[Id] = true;
StateMap[BB] = Id;
}
StateCipherParams Cipher = makeCipherParams(RNG);
unsigned TopologyKind = 0;
if (Policy.flattenTopology() == FlattenTopology::StarSwitch) {
TopologyKind = 0;
} else if (ShuffledBBs.size() >= 4) {
TopologyKind = RNG.nextU32() % 3u;
} else if (ShuffledBBs.size() >= 2) {
TopologyKind = (RNG.nextU32() % 2u == 0) ? 0u : 2u;
}
const char *TopologyName = "sparse_switch";
if (TopologyKind == 1)
TopologyName = "cascaded_subdisp";
else if (TopologyKind == 2)
TopologyName = "asymmetric_cmp_tree";
DebugLoc EntryLoc = pickBlockDebugLoc(*FirstBodyBB, F);
// Physically reorder ShuffledBBs in the Function to vary binary block layout
BasicBlock *Anchor = &EntryBB;
for (BasicBlock *BB : ShuffledBBs) {
BB->moveAfter(Anchor);
Anchor = BB;
}
// 4. Create state slot in EntryBB and replace EntryBB terminator
auto *StateSlot = new AllocaInst(I32Ty, 0, "ig.state",
EntryBB.getTerminator()->getIterator());
StateSlot->setAlignment(Align(4));
bool HasReturnInst = false;
for (BasicBlock *BB : ShuffledBBs) {
if (isa<ReturnInst>(BB->getTerminator())) {
HasReturnInst = true;
break;
}
}
bool UseUnifiedRet =
(TopologyKind == 0) && HasReturnInst && !HasMustTail &&
(F.getReturnType()->isVoidTy() || F.getReturnType()->isSized());
AllocaInst *RetSlot = nullptr;
Align RetAlign(1);
BasicBlock *UnifiedRetBB = nullptr;
uint32_t ExitStateId = 0;
if (UseUnifiedRet) {
if (!F.getReturnType()->isVoidTy()) {
RetAlign =
F.getParent()->getDataLayout().getABITypeAlign(F.getReturnType());
RetSlot = new AllocaInst(F.getReturnType(), 0, "ig.ret.slot",
EntryBB.getTerminator()->getIterator());
RetSlot->setAlignment(RetAlign);
}
do {
ExitStateId = RNG.nextNonZeroU32();
} while (UsedIds.contains(ExitStateId));
UsedIds[ExitStateId] = true;
UnifiedRetBB = BasicBlock::Create(Ctx, "ig.unified.ret", &F);
IRBuilder<> UB(UnifiedRetBB);
UB.SetCurrentDebugLocation(EntryLoc);
if (RetSlot) {
LoadInst *RetVal =
UB.CreateLoad(F.getReturnType(), RetSlot, false, "ig.ret.val");
RetVal->setAlignment(RetAlign);
UB.CreateRet(RetVal);
} else {
UB.CreateRetVoid();
}
}
BasicBlock *LoopEntryBB = BasicBlock::Create(Ctx, "ig.loop.entry", &F);
BasicBlock *LoopEndBB = BasicBlock::Create(Ctx, "ig.loop.end", &F);
BasicBlock *SwitchDefaultBB =
BasicBlock::Create(Ctx, "ig.switch.default", &F);
LoopEntryBB->moveAfter(&EntryBB);
if (UnifiedRetBB) {
UnifiedRetBB->moveAfter(LoopEndBB);
}
SmallVector<std::pair<uint32_t, BasicBlock *>, 8> BogusCases;
unsigned BogusCount = (TopologyKind == 0) ? Policy.bogusBlockCount() : 0u;
for (unsigned b = 0; b < BogusCount; ++b) {
uint32_t BogusId = 0;
do {
BogusId = RNG.nextNonZeroU32();
} while (UsedIds.contains(BogusId));
UsedIds[BogusId] = true;
BasicBlock *BogusBB =
BasicBlock::Create(Ctx, "ig.bogus." + Twine(b), &F, SwitchDefaultBB);
IRBuilder<> BBBuilder(BogusBB);
BBBuilder.SetCurrentDebugLocation(EntryLoc);
LoadInst *BLoad = BBBuilder.CreateLoad(I32Ty, StateSlot, /*isVolatile=*/true,
"ig.bogus.st");
BLoad->setAlignment(Align(4));
BasicBlock *T1 = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
BasicBlock *T2 = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
uint32_t C1 = encodeState(StateMap[T1], Cipher);
uint32_t C2 = encodeState(StateMap[T2], Cipher);
Value *M = BBBuilder.CreateMul(BLoad, ConstantInt::get(I32Ty, RNG.nextU32() | 1u),
"ig.bm");
Value *X = BBBuilder.CreateXor(
M, ConstantInt::get(I32Ty, RNG.nextNonZeroU32()), "ig.bx");
Value *Cond = BBBuilder.CreateICmpUGT(
X, ConstantInt::get(I32Ty, RNG.nextU32()), "ig.bc");
Value *Sel = BBBuilder.CreateSelect(
Cond, ConstantInt::get(I32Ty, C1), ConstantInt::get(I32Ty, C2),
"ig.bsel");
StoreInst *BStore =
BBBuilder.CreateStore(Sel, StateSlot, /*isVolatile=*/true);
BStore->setAlignment(Align(4));
BBBuilder.CreateBr(LoopEndBB);
BasicBlock *InsertAfter = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
BogusBB->moveAfter(InsertAfter);
BogusCases.emplace_back(BogusId, BogusBB);
}
DetailOut.Name = F.getName().str();
DetailOut.Topology = TopologyName;
DetailOut.Encoding = Cipher.encodingName();
DetailOut.Blocks = static_cast<unsigned>(
ShuffledBBs.size() + BogusCases.size() + (UnifiedRetBB ? 1u : 0u));
EntryBB.getTerminator()->eraseFromParent();
{
IRBuilder<> EB(&EntryBB);
EB.SetCurrentDebugLocation(EntryLoc);
uint32_t InitEnc = encodeState(StateMap[FirstBodyBB], Cipher);
StoreInst *InitStore =
EB.CreateStore(ConstantInt::get(I32Ty, InitEnc), StateSlot, true);
InitStore->setAlignment(Align(4));
EB.CreateBr(LoopEntryBB);
}
{
IRBuilder<> DB(SwitchDefaultBB);
DB.SetCurrentDebugLocation(EntryLoc);
DB.CreateBr(LoopEndBB);
}
{
IRBuilder<> LB(LoopEndBB);
LB.SetCurrentDebugLocation(EntryLoc);
LB.CreateBr(LoopEntryBB);
}
// 5. Build polymorphic dispatcher (sparse switch / cascaded sub-dispatchers /
// asymmetric comparison tree)
{
IRBuilder<> DB(LoopEntryBB);
DB.SetCurrentDebugLocation(EntryLoc);
LoadInst *EncState = DB.CreateLoad(I32Ty, StateSlot, /*isVolatile=*/true,
"ig.state.enc");
EncState->setAlignment(Align(4));
Value *CurState = emitDecodeState(DB, EncState, I32Ty, Cipher);
if (TopologyKind == 1) {
size_t N = ShuffledBBs.size();
if (N >= 9) {
size_t S1 = std::max<size_t>(2, (N / 3) + (RNG.nextU32() % 2u));
size_t S2 = S1 + std::max<size_t>(2, ((N - S1) / 2));
BasicBlock *SubDisp1BB =
BasicBlock::Create(Ctx, "ig.loop.subdisp1", &F, SwitchDefaultBB);
BasicBlock *SubDisp2BB =
BasicBlock::Create(Ctx, "ig.loop.subdisp2", &F, SwitchDefaultBB);
SwitchInst *SW1 =
DB.CreateSwitch(CurState, SubDisp1BB, static_cast<unsigned>(S1));
for (size_t i = 0; i < S1; ++i) {
SW1->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
ShuffledBBs[i]);
}
IRBuilder<> SB1(SubDisp1BB);
SB1.SetCurrentDebugLocation(EntryLoc);
SwitchInst *SW2 = SB1.CreateSwitch(CurState, SubDisp2BB,
static_cast<unsigned>(S2 - S1));
for (size_t i = S1; i < S2; ++i) {
SW2->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
ShuffledBBs[i]);
}
IRBuilder<> SB2(SubDisp2BB);
SB2.SetCurrentDebugLocation(EntryLoc);
SwitchInst *SW3 = SB2.CreateSwitch(CurState, SwitchDefaultBB,
static_cast<unsigned>(N - S2));
for (size_t i = S2; i < N; ++i) {
SW3->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
ShuffledBBs[i]);
}
} else {
size_t SplitIdx = 1 + (RNG.nextU32() % static_cast<uint32_t>(N - 1));
BasicBlock *SubDispBB =
BasicBlock::Create(Ctx, "ig.loop.subdisp", &F, SwitchDefaultBB);
SwitchInst *SW1 = DB.CreateSwitch(CurState, SubDispBB,
static_cast<unsigned>(SplitIdx));
for (size_t i = 0; i < SplitIdx; ++i) {
SW1->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
ShuffledBBs[i]);
}
IRBuilder<> SB(SubDispBB);
SB.SetCurrentDebugLocation(EntryLoc);
SwitchInst *SW2 = SB.CreateSwitch(CurState, SwitchDefaultBB,
static_cast<unsigned>(N - SplitIdx));
for (size_t i = SplitIdx; i < N; ++i) {
SW2->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
ShuffledBBs[i]);
}
}
} else if (TopologyKind == 2) {
SmallVector<std::pair<uint32_t, BasicBlock *>, 32> Sorted;
Sorted.reserve(ShuffledBBs.size());
for (BasicBlock *BB : ShuffledBBs)
Sorted.emplace_back(StateMap[BB], BB);
std::sort(Sorted.begin(), Sorted.end(),
[](const auto &A, const auto &B) { return A.first < B.first; });
auto emitCmpTree = [&](auto &Self, BasicBlock *NodeBB, size_t Lo,
size_t Hi) -> void {
IRBuilder<> CB(NodeBB);
CB.SetCurrentDebugLocation(EntryLoc);
if (Hi - Lo == 1) {
Value *Eq = CB.CreateICmpEQ(
CurState, ConstantInt::get(I32Ty, Sorted[Lo].first), "ig.eq");
CB.CreateCondBr(Eq, Sorted[Lo].second, SwitchDefaultBB);
return;
}
size_t Mid =
(Hi - Lo == 2)
? (Lo + 1)
: (Lo + 1 +
static_cast<size_t>(RNG.nextU32() %
static_cast<uint32_t>(Hi - Lo - 1)));
uint32_t PivotState = Sorted[Mid].first;
BasicBlock *LeftBB =
BasicBlock::Create(Ctx, "ig.cmp.l", &F, SwitchDefaultBB);
BasicBlock *RightBB =
BasicBlock::Create(Ctx, "ig.cmp.r", &F, SwitchDefaultBB);
Value *Ult = CB.CreateICmpULT(
CurState, ConstantInt::get(I32Ty, PivotState), "ig.ult");
CB.CreateCondBr(Ult, LeftBB, RightBB);
Self(Self, LeftBB, Lo, Mid);
Self(Self, RightBB, Mid, Hi);
};
emitCmpTree(emitCmpTree, LoopEntryBB, 0, Sorted.size());
} else {
SmallVector<std::pair<uint32_t, BasicBlock *>, 40> DispatchCases;
DispatchCases.reserve(ShuffledBBs.size() + BogusCases.size() +
(UnifiedRetBB ? 1 : 0));
for (BasicBlock *Target : ShuffledBBs)
DispatchCases.emplace_back(StateMap[Target], Target);
for (const auto &BC : BogusCases)
DispatchCases.push_back(BC);
if (UnifiedRetBB)
DispatchCases.emplace_back(ExitStateId, UnifiedRetBB);
RNG.shuffle(DispatchCases);
SwitchInst *SW = DB.CreateSwitch(
CurState, SwitchDefaultBB, static_cast<unsigned>(DispatchCases.size()));
for (const auto &DC : DispatchCases) {
SW->addCase(ConstantInt::get(I32Ty, DC.first), DC.second);
}
}
}
// 6. Rewrite non-exit terminators (and ReturnInst when unified return block is active)
for (BasicBlock *BB : ShuffledBBs) {
Instruction *Term = BB->getTerminator();
if (isa<UnreachableInst>(Term))
continue;
if (auto *RI = dyn_cast<ReturnInst>(Term)) {
if (!UnifiedRetBB)
continue;
DebugLoc Loc = RI->getDebugLoc() ? RI->getDebugLoc() : EntryLoc;
IRBuilder<> RB(BB);
RB.SetCurrentDebugLocation(Loc);
if (RetSlot && RI->getReturnValue()) {
StoreInst *RSt = RB.CreateStore(RI->getReturnValue(), RetSlot, false);
RSt->setAlignment(RetAlign);
}
RI->eraseFromParent();
StoreInst *SSt = RB.CreateStore(
ConstantInt::get(I32Ty, encodeState(ExitStateId, Cipher)),
StateSlot, true);
SSt->setAlignment(Align(4));
RB.CreateBr(LoopEndBB);
continue;
}
DebugLoc Loc = Term->getDebugLoc() ? Term->getDebugLoc() : EntryLoc;
if (auto *Br = dyn_cast<BranchInst>(Term)) {
IRBuilder<> TB(BB);
TB.SetCurrentDebugLocation(Loc);
if (Br->isUnconditional()) {
BasicBlock *Succ = Br->getSuccessor(0);
uint32_t NextEnc = encodeState(StateMap[Succ], Cipher);
Term->eraseFromParent();
StoreInst *St =
TB.CreateStore(ConstantInt::get(I32Ty, NextEnc), StateSlot, true);
St->setAlignment(Align(4));
TB.CreateBr(LoopEndBB);
} else {
Value *Cond = Br->getCondition();
BasicBlock *TrueBB = Br->getSuccessor(0);
BasicBlock *FalseBB = Br->getSuccessor(1);
uint32_t TrueEnc = encodeState(StateMap[TrueBB], Cipher);
uint32_t FalseEnc = encodeState(StateMap[FalseBB], Cipher);
Term->eraseFromParent();
Value *Sel = TB.CreateSelect(Cond, ConstantInt::get(I32Ty, TrueEnc),
ConstantInt::get(I32Ty, FalseEnc),
"ig.next");
StoreInst *St = TB.CreateStore(Sel, StateSlot, true);
St->setAlignment(Align(4));
TB.CreateBr(LoopEndBB);
}
} else if (auto *SW = dyn_cast<SwitchInst>(Term)) {
auto makeEdgeBlock = [&](BasicBlock *Dest) -> BasicBlock * {
BasicBlock *EdgeBB =
BasicBlock::Create(Ctx, "ig.sw.edge", &F, SwitchDefaultBB);
IRBuilder<> EB(EdgeBB);
EB.SetCurrentDebugLocation(Loc);
uint32_t NextEnc = encodeState(StateMap[Dest], Cipher);
StoreInst *St =
EB.CreateStore(ConstantInt::get(I32Ty, NextEnc), StateSlot, true);
St->setAlignment(Align(4));
EB.CreateBr(LoopEndBB);
return EdgeBB;
};
BasicBlock *OrigDef = SW->getDefaultDest();
SW->setDefaultDest(makeEdgeBlock(OrigDef));
for (unsigned idx = 1, e = SW->getNumSuccessors(); idx < e; ++idx) {
SW->setSuccessor(idx, makeEdgeBlock(SW->getSuccessor(idx)));
}
}
}
if (verifyFunction(F, &errs())) {
report_fatal_error(Twine("[IGFlattening] IR verification failed on ") +
F.getName());
}
return true;
}
} // namespace
bool runControlFlowFlattening(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isFlatteningEnabled() || Policy.isModuleExempt(M))
return false;
SmallVector<Function *, 16> Targets;
for (Function &F : M) {
if (F.isDeclaration())
continue;
if (Policy.shouldFlattenFunction(F))
Targets.push_back(&F);
}
bool Changed = false;
for (Function *F : Targets) {
FlattenedFunctionDetail Detail;
std::string SkipReason;
if (flattenSingleFunction(*F, Policy, Detail, SkipReason)) {
Audit.FunctionsFlattened.push_back(F->getName().str());
Audit.FunctionsFlattenedDetails.push_back(std::move(Detail));
Changed = true;
} else {
Audit.FunctionsSkipped.push_back({F->getName().str(), SkipReason});
}
}
return Changed;
}
} // namespace igobf
+232
View File
@@ -0,0 +1,232 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Transforms/Utils/CodeExtractor.h"
using namespace llvm;
namespace igobf {
namespace {
bool isSwiftABIHazardValue(const Value *V) {
if (!V)
return false;
if (V->getType()->isTokenTy() || V->getType()->isLabelTy() ||
V->getType()->isMetadataTy()) {
return true;
}
if (const auto *AI = dyn_cast<AllocaInst>(V)) {
if (AI->isSwiftError())
return true;
}
if (const auto *Arg = dyn_cast<Argument>(V)) {
if (Arg->hasAttribute(Attribute::SwiftError) ||
Arg->hasAttribute(Attribute::SwiftAsync) ||
Arg->hasAttribute(Attribute::SwiftSelf)) {
return true;
}
}
return false;
}
bool isBlockEligibleForOutline(BasicBlock &BB, const Function &F,
unsigned MinInsts) {
if (&BB == &F.getEntryBlock() || BB.isEHPad() || BB.hasAddressTaken() ||
pred_empty(&BB)) {
return false;
}
if (isa<PHINode>(BB.front()))
return false;
if (!isa<BranchInst>(BB.getTerminator()))
return false;
unsigned WorkInsts = 0;
for (const Instruction &I : BB) {
if (isa<DbgInfoIntrinsic>(I))
continue;
if (isa<AllocaInst>(I) || isa<InvokeInst>(I) || isa<CallBrInst>(I) ||
isa<LandingPadInst>(I) || isa<CatchSwitchInst>(I) ||
isa<CatchReturnInst>(I) || isa<CleanupReturnInst>(I) ||
isa<IndirectBrInst>(I) || isa<VAArgInst>(I) || I.isAtomic()) {
return false;
}
if (I.getType()->isTokenTy())
return false;
for (const Use &U : I.operands()) {
if (isa<BlockAddress>(U.get()))
return false;
if (isa<BasicBlock>(U.get()))
continue;
if (isSwiftABIHazardValue(U.get()))
return false;
}
if (const auto *CB = dyn_cast<CallBase>(&I)) {
if (CB->isInlineAsm() || CB->isMustTailCall() ||
CB->getCallingConv() == CallingConv::SwiftTail) {
return false;
}
for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) {
if (CB->paramHasAttr(i, Attribute::SwiftError) ||
CB->paramHasAttr(i, Attribute::SwiftAsync) ||
CB->paramHasAttr(i, Attribute::SwiftSelf) ||
CB->paramHasAttr(i, Attribute::InAlloca) ||
CB->paramHasAttr(i, Attribute::Preallocated) ||
CB->paramHasAttr(i, Attribute::ImmArg)) {
return false;
}
}
if (const Function *Callee = CB->getCalledFunction()) {
StringRef CName = Callee->getName();
if (CName.starts_with("llvm.coro.") ||
CName.starts_with("llvm.objc.clang.arc.use") ||
CName.starts_with("llvm.va_")) {
return false;
}
}
}
if (!isa<DbgInfoIntrinsic>(I) && !I.isTerminator())
++WorkInsts;
}
return WorkInsts >= MinInsts;
}
} // namespace
bool runFunctionOutline(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isFunctionOutlineEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
const unsigned MaxPerFn = Policy.functionOutlineMaxPerFn();
const unsigned MinInsts = Policy.functionOutlineMinInsts();
if (MaxPerFn == 0)
return false;
SmallVector<Function *, 32> OrigFuncs;
for (Function &F : M)
OrigFuncs.push_back(&F);
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
Policy.sourcePath());
unsigned GlobalOutlineIdx = 0;
bool Changed = false;
for (Function *F : OrigFuncs) {
if (!F || !Policy.shouldOutlineFunction(*F))
continue;
if (!isFunctionSafeForTransform(*F, Policy,
&Policy.functionOutlineExemptFunctions())) {
continue;
}
if (F->isVarArg() || F->hasPersonalityFn() || F->size() < 2)
continue;
SmallVector<BasicBlock *, 16> OrigBlocks;
for (BasicBlock &BB : *F)
OrigBlocks.push_back(&BB);
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
(F->getName() + "|outline").str());
RNG.shuffle(OrigBlocks);
unsigned FnOutlined = 0;
for (BasicBlock *BB : OrigBlocks) {
if (FnOutlined >= MaxPerFn)
break;
if (!BB || BB->getParent() != F)
continue;
if (!isBlockEligibleForOutline(*BB, *F, MinInsts))
continue;
DominatorTree DT(*F);
CodeExtractorAnalysisCache CEAC(*F);
SmallVector<BasicBlock *, 1> Region{BB};
CodeExtractor CE(Region, &DT, /*AggregateArgs=*/false);
if (!CE.isEligible())
continue;
SetVector<Value *> Inputs, Outputs, Allocas;
CE.findInputsOutputs(Inputs, Outputs, Allocas);
if (Inputs.size() > 5 || Outputs.size() > 2)
continue;
bool Hazard = false;
for (const Value *V : Inputs) {
if (isSwiftABIHazardValue(V)) {
Hazard = true;
break;
}
}
if (!Hazard) {
for (const Value *V : Outputs) {
if (isSwiftABIHazardValue(V)) {
Hazard = true;
break;
}
}
}
if (Hazard)
continue;
Function *OutF = CE.extractCodeRegion(CEAC);
if (!OutF)
continue;
OutF->setName("ig_sub_" + Tag + "_" + Twine(GlobalOutlineIdx++));
OutF->setLinkage(GlobalValue::InternalLinkage);
OutF->setVisibility(GlobalValue::DefaultVisibility);
OutF->addFnAttr(Attribute::NoInline);
OutF->removeFnAttr(Attribute::AlwaysInline);
OutF->removeFnAttr(Attribute::InlineHint);
llvm::stripDebugInfo(*OutF);
for (BasicBlock &OBB : *OutF) {
for (Instruction &OI : make_early_inc_range(OBB)) {
if (isa<DbgInfoIntrinsic>(OI))
OI.eraseFromParent();
}
}
if (F->getSubprogram()) {
for (BasicBlock &FBB : *F) {
for (Instruction &FI : FBB) {
if (!FI.getDebugLoc())
FI.setDebugLoc(resolveInstDebugLoc(&FI, *F));
}
}
}
if (verifyFunction(*OutF, &errs())) {
report_fatal_error(Twine("[IGFunctionOutline] IR verification failed on ") +
OutF->getName());
}
if (verifyFunction(*F, &errs())) {
report_fatal_error(Twine("[IGFunctionOutline] IR verification failed on ") +
F->getName());
}
++FnOutlined;
++Audit.FunctionsOutlinedCount;
Changed = true;
}
if (FnOutlined > 0)
Audit.OutlinedFunctions.push_back(F->getName().str());
}
return Changed;
}
} // namespace igobf
+280
View File
@@ -0,0 +1,280 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace igobf {
namespace {
bool isFunctionCFGSafeForIBR(Function &F) {
if (F.size() < 3)
return false;
for (BasicBlock &BB : F) {
if (BB.isEHPad())
return false;
Instruction *Term = BB.getTerminator();
if (!Term || isa<InvokeInst>(Term) || isa<ResumeInst>(Term) ||
isa<CatchSwitchInst>(Term) || isa<CatchReturnInst>(Term) ||
isa<CleanupReturnInst>(Term) || isa<IndirectBrInst>(Term) ||
isa<CallBrInst>(Term)) {
return false;
}
for (Instruction &I : BB) {
if (I.getType()->isTokenTy())
return false;
if (auto *CI = dyn_cast<CallInst>(&I)) {
if (CI->isMustTailCall())
return false;
}
}
}
return true;
}
bool obfuscateSingleFunctionIBR(Function &F, const IGPolicyConfig &Policy,
StringRef Tag, unsigned FnIndex,
unsigned &OutRewritten) {
if (!isFunctionCFGSafeForIBR(F))
return false;
SmallVector<BranchInst *, 24> Branches;
SmallVector<BasicBlock *, 24> Targets;
SmallPtrSet<BasicBlock *, 24> SeenTargets;
BasicBlock *EntryBB = &F.getEntryBlock();
SmallPtrSet<BasicBlock *, 32> Reachable;
SmallVector<BasicBlock *, 32> Worklist;
Reachable.insert(EntryBB);
Worklist.push_back(EntryBB);
while (!Worklist.empty()) {
BasicBlock *Cur = Worklist.pop_back_val();
Instruction *Term = Cur->getTerminator();
if (!Term)
continue;
if (auto *CBr = dyn_cast<BranchInst>(Term); CBr && CBr->isConditional()) {
if (auto *CondCI = dyn_cast<ConstantInt>(CBr->getCondition())) {
BasicBlock *LiveSucc =
CondCI->isZero() ? CBr->getSuccessor(1) : CBr->getSuccessor(0);
if (Reachable.insert(LiveSucc).second)
Worklist.push_back(LiveSucc);
continue;
}
}
for (unsigned i = 0, e = Term->getNumSuccessors(); i < e; ++i) {
BasicBlock *Succ = Term->getSuccessor(i);
if (Reachable.insert(Succ).second)
Worklist.push_back(Succ);
}
}
bool NeedDecoy = false;
for (BasicBlock &BB : F) {
if (!Reachable.contains(&BB))
continue;
auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
if (!Br)
continue;
if (Br->isUnconditional()) {
BasicBlock *Dest = Br->getSuccessor(0);
if (Dest == EntryBB)
continue;
NeedDecoy = true;
Branches.push_back(Br);
if (SeenTargets.insert(Dest).second)
Targets.push_back(Dest);
} else {
if (isa<ConstantInt>(Br->getCondition()))
continue;
BasicBlock *T = Br->getSuccessor(0);
BasicBlock *FBB = Br->getSuccessor(1);
if (T == EntryBB || FBB == EntryBB)
continue;
if (T == FBB && !T->phis().empty())
continue;
if (T == FBB)
NeedDecoy = true;
Branches.push_back(Br);
if (SeenTargets.insert(T).second)
Targets.push_back(T);
if (SeenTargets.insert(FBB).second)
Targets.push_back(FBB);
}
}
if (Branches.empty() || (Targets.size() + (NeedDecoy ? 1 : 0)) < 2)
return false;
if (F.hasPrivateLinkage())
F.setLinkage(GlobalValue::InternalLinkage);
LLVMContext &Ctx = F.getContext();
Module &M = *F.getParent();
Type *I64Ty = Type::getInt64Ty(Ctx);
PointerType *PtrTy = PointerType::getUnqual(Ctx);
// Only emit ig.ibr.decoy when at least one unconditional/degenerate indirectbr
// lists it; otherwise UnreachableBlockElim deletes it and leaves a dangling blockaddress.
BasicBlock *DecoyBB = nullptr;
if (NeedDecoy) {
DecoyBB = BasicBlock::Create(Ctx, "ig.ibr.decoy", &F);
IRBuilder<> DB(DecoyBB);
DB.SetCurrentDebugLocation(resolveInstDebugLoc(nullptr, F));
Function *TrapFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::trap);
DB.CreateCall(TrapFn);
DB.CreateUnreachable();
Targets.push_back(DecoyBB);
}
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
(F.getName() + "|ibr").str());
RNG.shuffle(Targets);
DenseMap<BasicBlock *, unsigned> SlotMap;
SmallVector<Constant *, 24> Share1Entries;
SmallVector<Constant *, 24> Share2Entries;
Share1Entries.reserve(Targets.size());
Share2Entries.reserve(Targets.size());
Constant *FnInt = ConstantExpr::getPtrToInt(&F, I64Ty);
for (unsigned Idx = 0; Idx < Targets.size(); ++Idx) {
BasicBlock *BB = Targets[Idx];
SlotMap[BB] = Idx;
uint64_t Salt = RNG.nextNonZeroU64();
Constant *BBAddrInt = ConstantExpr::getPtrToInt(BlockAddress::get(&F, BB), I64Ty);
Constant *RelOffset = ConstantExpr::getSub(BBAddrInt, FnInt);
Constant *Share1 = ConstantExpr::getAdd(RelOffset, ConstantInt::get(I64Ty, Salt));
Share1Entries.push_back(Share1);
Share2Entries.push_back(ConstantInt::get(I64Ty, Salt));
}
ArrayType *TableTy = ArrayType::get(I64Ty, Targets.size());
std::string Suffix = Tag.str() + "_" + std::to_string(FnIndex);
auto *Share1GV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Share1Entries), "__ig_ibt1_" + Suffix);
Share1GV->setAlignment(Align(8));
Share1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
auto *Share2GV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Share2Entries), "__ig_ibt2_" + Suffix);
Share2GV->setAlignment(Align(8));
Share2GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
unsigned RewrittenHere = 0;
for (BranchInst *Br : Branches) {
BasicBlock *ParentBB = Br->getParent();
DebugLoc Loc = resolveInstDebugLoc(Br, F);
IRBuilder<> B(Br);
B.SetCurrentDebugLocation(Loc);
if (Br->isUnconditional() || Br->getSuccessor(0) == Br->getSuccessor(1)) {
BasicBlock *Dest = Br->getSuccessor(0);
unsigned SlotIdx = SlotMap[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();
IRBuilder<> EndB(ParentBB);
EndB.SetCurrentDebugLocation(Loc);
IndirectBrInst *IBr = EndB.CreateIndirectBr(DstPtr, 2);
IBr->addDestination(Dest);
IBr->addDestination(DecoyBB);
++RewrittenHere;
} else {
BasicBlock *TrueBB = Br->getSuccessor(0);
BasicBlock *FalseBB = Br->getSuccessor(1);
Value *Cond = Br->getCondition();
Value *IdxVal = B.CreateSelect(
Cond, ConstantInt::get(I64Ty, SlotMap[TrueBB]),
ConstantInt::get(I64Ty, SlotMap[FalseBB]), "ig.ibr.idx");
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();
IRBuilder<> EndB(ParentBB);
EndB.SetCurrentDebugLocation(Loc);
IndirectBrInst *IBr = EndB.CreateIndirectBr(DstPtr, 2);
IBr->addDestination(TrueBB);
IBr->addDestination(FalseBB);
++RewrittenHere;
}
}
if (verifyFunction(F, &errs())) {
report_fatal_error(Twine("[IGIndirectBranch] IR verification failed on ") +
F.getName());
}
OutRewritten += RewrittenHere;
return RewrittenHere > 0;
}
} // namespace
bool runIndirectBranchObfuscation(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isIndirectBranchEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
SmallVector<Function *, 16> Targets;
for (Function &F : M) {
if (!Policy.shouldIndirectBranchInFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.indirectBranchExemptFunctions())) {
continue;
}
Targets.push_back(&F);
}
if (Targets.empty())
return false;
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
Policy.sourcePath());
bool Changed = false;
unsigned FnIndex = 0;
for (Function *F : Targets) {
unsigned Rewritten = 0;
if (obfuscateSingleFunctionIBR(*F, Policy, Tag, FnIndex++, Rewritten)) {
Audit.IndirectBranchesCount += Rewritten;
Audit.IndirectBranchesFunctions.push_back(F->getName().str());
Changed = true;
}
}
return Changed;
}
} // namespace igobf
+501
View File
@@ -0,0 +1,501 @@
#include "IGPolicyConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/SHA256.h"
#include "llvm/TargetParser/Triple.h"
using namespace llvm;
namespace igobf {
namespace {
StringRef stripObjCMarkerRef(StringRef Name) {
if (!Name.empty() && Name.front() == '\x01')
return Name.drop_front(1);
return Name;
}
bool isValidSwiftIdentChars(StringRef S) {
if (S.empty())
return false;
for (char C : S) {
unsigned char UC = static_cast<unsigned char>(C);
if (!isAlnum(UC) && C != '_')
return false;
}
return true;
}
bool isBuiltinSwiftModuleName(StringRef ModName) {
return ModName == "So" || ModName == "SC" || ModName == "s" ||
ModName == "Swift" || ModName == "Foundation" ||
ModName == "UIKit" || ModName == "SwiftUI" ||
ModName == "Combine" || ModName == "Dispatch" ||
ModName == "ObjectiveC" || ModName == "CoreFoundation" ||
ModName == "CoreGraphics" || ModName == "CryptoKit" ||
ModName == "StoreKit" || ModName == "Security" ||
ModName == "WebKit" || ModName == "Darwin";
}
// Parse `<Len><ModChars>` starting at `S[Start]` if valid.
// Sets `AfterIdx` to index immediately following `<ModChars>`.
StringRef parseLengthPrefixedSwiftIdent(StringRef S, size_t Start,
size_t &AfterIdx) {
if (Start >= S.size() || !isDigit(static_cast<unsigned char>(S[Start])) ||
S[Start] == '0') {
return StringRef();
}
size_t Pos = Start;
uint64_t Len = 0;
while (Pos < S.size() && isDigit(static_cast<unsigned char>(S[Pos]))) {
Len = Len * 10 + static_cast<uint64_t>(S[Pos] - '0');
if (Len > 128)
return StringRef();
++Pos;
}
if (Len == 0 || Pos + Len > S.size())
return StringRef();
StringRef Ident = S.substr(Pos, static_cast<size_t>(Len));
if (!isValidSwiftIdentChars(Ident) || isBuiltinSwiftModuleName(Ident))
return StringRef();
AfterIdx = Pos + static_cast<size_t>(Len);
return S.substr(Start, AfterIdx - Start);
}
std::string detectSwiftModuleToken(const Module &M) {
StringMap<unsigned> Counts;
auto InspectFn = [&](const Function &F, unsigned BaseWeight) {
StringRef Clean = stripObjCMarkerRef(F.getName());
if (!Clean.starts_with("$s"))
return;
size_t AfterIdx = 0;
StringRef DirectTok = parseLengthPrefixedSwiftIdent(Clean, 2, AfterIdx);
if (!DirectTok.empty()) {
Counts[DirectTok] += BaseWeight * 2;
return;
}
// Fallback for pure extension files (e.g. `$sSo6UIViewC17AppModE...`).
for (size_t i = 3; i + 2 < Clean.size(); ++i) {
if (isDigit(static_cast<unsigned char>(Clean[i - 1])) ||
!isDigit(static_cast<unsigned char>(Clean[i])) || Clean[i] == '0') {
continue;
}
size_t ExtAfter = 0;
StringRef ExtTok = parseLengthPrefixedSwiftIdent(Clean, i, ExtAfter);
if (!ExtTok.empty() && ExtAfter < Clean.size() && Clean[ExtAfter] == 'E') {
Counts[ExtTok] += BaseWeight;
break;
}
}
};
for (const Function &F : M) {
if (!F.isDeclaration() && !F.hasLocalLinkage() &&
!F.hasAvailableExternallyLinkage() && !F.isWeakForLinker()) {
InspectFn(F, 2);
} else if (F.isDeclaration() && F.hasHiddenVisibility() &&
!F.isWeakForLinker() && !F.hasExternalWeakLinkage()) {
InspectFn(F, 1);
}
}
std::string Best;
unsigned BestScore = 0;
for (const auto &KV : Counts) {
StringRef Key = KV.getKey();
unsigned Score = KV.getValue();
if (Score > BestScore || (Score == BestScore && Key < Best)) {
Best = Key.str();
BestScore = Score;
}
}
return Best;
}
bool hasSwiftMetadataOrWitnessSuffix(StringRef CleanName) {
static constexpr StringRef Suffixes[] = {
"CMa", "VMa", "OMa", "CMn", "VMn", "OMn", "CN", "VN", "ON", "Wl",
"WL", "Tm", "Mr", "Mi", "Ma", "Mc", "Wp", "WG", "WI", "Wr",
"Ws", "WT", "WOh", "WOy", "WOe", "WOc", "WOb", "WOd", "WOi", "wCP",
"wxx", "wcp", "wca", "wtk", "wta", "wet", "wst", "wug", "wup", "wui",
"TQ0_", "TY0_",
};
for (StringRef Suf : Suffixes) {
if (CleanName.ends_with(Suf) ||
CleanName.ends_with((Suf + "_").str())) {
return true;
}
}
return false;
}
bool isPlumbingOrRuntimeSymbol(StringRef RawName, StringRef CleanName,
const IGPolicyConfig &Policy) {
if (RawName.empty() || RawName.starts_with("\x01L") ||
RawName.starts_with("\x01l")) {
return true;
}
static constexpr StringRef BuiltinSkipPrefixes[] = {
"llvm.", "__ig_", "ig_defender_", "ig_call_",
"ig_poison_", "ig_sys_", "ig_a", "ig_archive_",
"_IG_dispatch_", "IG_dispatch_", "objc_", "_objc_",
"swift_", "_swift_", "__swift_", "___",
"__stack_chk", "__clang_", "__cxa_", "__gxx_",
"_Unwind_",
};
for (StringRef P : BuiltinSkipPrefixes) {
if (CleanName.starts_with(P))
return true;
}
for (const std::string &P : Policy.exemptFunctionPrefixes()) {
if (!P.empty() && CleanName.starts_with(P))
return true;
}
if (CleanName.contains(".resume.") || CleanName.contains(".coro"))
return true;
if (CleanName.starts_with("$s") && hasSwiftMetadataOrWitnessSuffix(CleanName))
return true;
return false;
}
bool isSameModuleSwiftDeclaration(StringRef CleanName,
StringRef SwiftModToken) {
if (SwiftModToken.empty() || !CleanName.starts_with("$s"))
return false;
if (CleanName.drop_front(2).starts_with(SwiftModToken))
return true;
StringRef Base = CleanName;
size_t TgPos = Base.find("Tg");
if (TgPos != StringRef::npos)
Base = Base.substr(0, TgPos);
size_t TfPos = Base.find("Tf");
if (TfPos != StringRef::npos)
Base = Base.substr(0, TfPos);
size_t SearchFrom = 3;
while (SearchFrom < Base.size()) {
size_t Pos = Base.find(SwiftModToken, SearchFrom);
if (Pos == StringRef::npos)
break;
size_t EndPos = Pos + SwiftModToken.size();
if (Pos >= 3 && !isDigit(static_cast<unsigned char>(Base[Pos - 1])) &&
EndPos < Base.size() && Base[EndPos] == 'E') {
return true;
}
SearchFrom = Pos + 1;
}
return false;
}
bool isSameImageSafeCallee(const Function &Callee, StringRef SwiftModToken,
const IGPolicyConfig &Policy) {
if (Callee.isIntrinsic() || Callee.isPresplitCoroutine())
return false;
if (Callee.getCallingConv() == CallingConv::SwiftTail)
return false;
if (Callee.hasAvailableExternallyLinkage() ||
Callee.hasExternalWeakLinkage() || Callee.hasDLLImportStorageClass()) {
return false;
}
for (const Argument &Arg : Callee.args()) {
if (Arg.hasAttribute(Attribute::SwiftAsync) ||
Arg.hasAttribute(Attribute::InAlloca) ||
Arg.hasAttribute(Attribute::Preallocated)) {
return false;
}
}
StringRef RawName = Callee.getName();
StringRef CleanName = stripObjCMarkerRef(RawName);
if (isPlumbingOrRuntimeSymbol(RawName, CleanName, Policy))
return false;
if (!Callee.isDeclaration()) {
if (GlobalValue::isInterposableLinkage(Callee.getLinkage()))
return false;
if (Callee.isWeakForLinker()) {
return (Callee.hasLinkOnceODRLinkage() || Callee.hasWeakODRLinkage()) &&
Callee.hasHiddenVisibility();
}
return true;
}
if (Callee.isWeakForLinker())
return false;
if (isSameModuleSwiftDeclaration(CleanName, SwiftModToken))
return true;
for (const std::string &Prefix : Policy.indirectCallSameImagePrefixes()) {
if (!Prefix.empty() && CleanName.starts_with(Prefix))
return true;
}
return false;
}
bool isCallerEligible(const Function &Caller, const IGPolicyConfig &Policy) {
if (!Policy.shouldIndirectCallInFunction(Caller))
return false;
if (Caller.isPresplitCoroutine() ||
Caller.hasFnAttribute(Attribute::Naked) ||
Caller.getCallingConv() == CallingConv::SwiftTail) {
return false;
}
if (Caller.hasSection()) {
StringRef Sec = Caller.getSection();
if (Sec.contains("__mod_init_func") || Sec.contains("__objc_init_func") ||
Sec.contains("__mod_term_func")) {
return false;
}
}
return true;
}
bool isCallSiteEligible(CallInst *CI, Function *&OutCallee) {
OutCallee = nullptr;
if (!CI || CI->isInlineAsm() || CI->isMustTailCall() || CI->isNoTailCall())
return false;
if (CI->getFunctionType()->isVarArg() || CI->getType()->isTokenTy())
return false;
if (CI->getCallingConv() == CallingConv::SwiftTail)
return false;
for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
if (CI->getArgOperand(i)->getType()->isTokenTy())
return false;
if (CI->paramHasAttr(i, Attribute::SwiftAsync) ||
CI->paramHasAttr(i, Attribute::InAlloca) ||
CI->paramHasAttr(i, Attribute::Preallocated) ||
CI->paramHasAttr(i, Attribute::ImmArg)) {
return false;
}
}
if (CI->hasOperandBundles()) {
for (unsigned i = 0, e = CI->getNumOperandBundles(); i != e; ++i) {
if (CI->getOperandBundleAt(i).getTagName() != "clang.arc.attachedcall")
return false;
}
}
auto *Callee = dyn_cast<Function>(CI->getCalledOperand());
if (!Callee || Callee->getFunctionType() != CI->getFunctionType())
return false;
OutCallee = Callee;
return true;
}
std::string computeModuleTag(StringRef Seed, StringRef ModId,
StringRef SourcePath) {
SHA256 Hasher;
Hasher.update(Seed);
Hasher.update("|");
Hasher.update(ModId);
Hasher.update("|");
Hasher.update(SourcePath);
auto Digest = Hasher.final();
return toHex(ArrayRef<uint8_t>(Digest.data(), 4), /*LowerCase=*/true);
}
struct PendingIndirectSite {
CallInst *CI = nullptr;
Function *Callee = nullptr;
};
} // namespace
bool runIndirectCallObfuscation(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isIndirectCallEnabled() || Policy.isModuleExempt(M))
return false;
if (!M.getTargetTriple().empty()) {
Triple TT(M.getTargetTriple());
if (!TT.isOSBinFormatMachO() || !TT.isAArch64() ||
TT.getArchName() == "arm64e") {
return false;
}
}
std::string SwiftModToken;
if (!Policy.swiftModuleName().empty()) {
StringRef ExplicitMod = Policy.swiftModuleName();
SwiftModToken =
std::to_string(ExplicitMod.size()) + ExplicitMod.str();
} else {
SwiftModToken = detectSwiftModuleToken(M);
}
SmallVector<PendingIndirectSite, 32> Sites;
SmallVector<Function *, 16> UniqueCallees;
DenseMap<Function *, unsigned> SeenCallees;
std::vector<std::string> TouchedCallers;
for (Function &Caller : M) {
if (!isCallerEligible(Caller, Policy))
continue;
bool CallerTouched = false;
for (BasicBlock &BB : Caller) {
for (Instruction &I : BB) {
auto *CI = dyn_cast<CallInst>(&I);
if (!CI)
continue;
Function *Callee = nullptr;
if (!isCallSiteEligible(CI, Callee))
continue;
if (!isSameImageSafeCallee(*Callee, SwiftModToken, Policy))
continue;
Sites.push_back({CI, Callee});
if (SeenCallees.try_emplace(Callee, UniqueCallees.size()).second)
UniqueCallees.push_back(Callee);
CallerTouched = true;
}
}
if (CallerTouched)
TouchedCallers.push_back(Caller.getName().str());
}
if (Sites.empty())
return false;
for (Function *Callee : UniqueCallees) {
if (!Callee->isDeclaration() && Callee->hasPrivateLinkage())
Callee->setLinkage(GlobalValue::InternalLinkage);
}
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
"__ig_icall_table");
RNG.shuffle(UniqueCallees);
LLVMContext &Ctx = M.getContext();
Type *I8Ty = Type::getInt8Ty(Ctx);
Type *I64Ty = Type::getInt64Ty(Ctx);
PointerType *PtrTy = PointerType::getUnqual(Ctx);
std::string Tag =
computeModuleTag(Policy.seed(), M.getModuleIdentifier(), Policy.sourcePath());
auto *AnchorGV = new GlobalVariable(
M, I8Ty, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantInt::get(I8Ty, RNG.nextNonZeroByte()), "__ig_ca_" + Tag);
AnchorGV->setAlignment(Align(1));
AnchorGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Constant *AnchorInt = ConstantExpr::getPtrToInt(AnchorGV, I64Ty);
bool UseDualTable = Policy.isIndirectCallDualTableEnabled();
Audit.IndirectCallDualTable = UseDualTable;
DenseMap<Function *, std::pair<unsigned, uint64_t>> SlotMap;
SmallVector<Constant *, 16> Table1Entries;
SmallVector<Constant *, 16> Table2Entries;
Table1Entries.reserve(UniqueCallees.size());
if (UseDualTable)
Table2Entries.reserve(UniqueCallees.size());
for (unsigned Idx = 0; Idx < UniqueCallees.size(); ++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 *Diff = ConstantExpr::getSub(CalleeInt, AnchorInt);
if (UseDualTable) {
uint64_t Share2 = RNG.nextNonZeroU64();
uint64_t CombinedSalt = Share2 + SlotSalt;
Constant *Encoded1 =
ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, CombinedSalt));
Table1Entries.push_back(Encoded1);
Table2Entries.push_back(ConstantInt::get(I64Ty, Share2));
} else {
Constant *Encoded =
ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, SlotSalt));
Table1Entries.push_back(Encoded);
}
SlotMap[TargetFn] = {Idx, SlotSalt};
}
ArrayType *TableTy = ArrayType::get(I64Ty, Table1Entries.size());
GlobalVariable *Table1GV = nullptr;
GlobalVariable *Table2GV = nullptr;
if (UseDualTable) {
Table1GV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Table1Entries), "__ig_cs1_" + Tag);
Table1GV->setAlignment(Align(8));
Table1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Table2GV = new GlobalVariable(
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(TableTy, Table2Entries), "__ig_cs2_" + Tag);
Table2GV->setAlignment(Align(8));
Table2GV->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);
for (const PendingIndirectSite &Site : Sites) {
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);
B.SetCurrentDebugLocation(CI->getDebugLoc());
Constant *IdxConst = ConstantInt::get(I64Ty, SlotIdx);
Value *SlotPtr1 = B.CreateInBoundsGEP(TableTy, Table1GV, {Zero64, IdxConst});
LoadInst *Load1 =
B.CreateAlignedLoad(I64Ty, SlotPtr1, Align(8), /*isVolatile=*/true);
Value *RawDelta = Load1;
if (UseDualTable) {
Value *SlotPtr2 = B.CreateInBoundsGEP(TableTy, Table2GV, {Zero64, IdxConst});
LoadInst *Load2 =
B.CreateAlignedLoad(I64Ty, SlotPtr2, Align(8), /*isVolatile=*/true);
RawDelta = B.CreateSub(Load1, Load2);
}
Value *AnchorVal = B.CreatePtrToInt(AnchorGV, I64Ty);
Value *Step1 = B.CreateSub(RawDelta, ConstantInt::get(I64Ty, SiteA));
Value *Step2 = B.CreateAdd(AnchorVal, Step1);
Value *TargetInt = B.CreateSub(Step2, ConstantInt::get(I64Ty, SiteB));
Value *FnPtr = B.CreateIntToPtr(TargetInt, PtrTy);
CI->setTailCallKind(CallInst::TCK_None);
CI->setCalledOperand(FnPtr);
++Audit.IndirectCallsCount;
}
Audit.IndirectCallsFunctions.insert(Audit.IndirectCallsFunctions.end(),
TouchedCallers.begin(),
TouchedCallers.end());
return true;
}
} // namespace igobf
+348
View File
@@ -0,0 +1,348 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/ErrorHandling.h"
#include <array>
using namespace llvm;
namespace igobf {
namespace {
constexpr unsigned kConstPoolSize = 32;
struct ConstSite {
Instruction *Inst = nullptr;
unsigned OpIdx = 0;
uint64_t Value = 0;
unsigned BitWidth = 0;
};
void considerOperand(Instruction *I, unsigned OpIdx,
SmallVectorImpl<ConstSite> &Sites, unsigned MaxBudget) {
if (Sites.size() >= MaxBudget)
return;
auto *CI = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
if (!CI)
return;
unsigned BW = CI->getBitWidth();
if (BW != 32 && BW != 64)
return;
Sites.push_back({I, OpIdx, CI->getZExtValue(), BW});
}
void collectConstantSites(Function &F, unsigned MaxBudget,
SmallVectorImpl<ConstSite> &Sites) {
for (BasicBlock &BB : F) {
if (BB.isEHPad())
continue;
for (Instruction &I : BB) {
if (Sites.size() >= MaxBudget)
return;
if (isa<SwitchInst>(&I) || isa<GetElementPtrInst>(&I) ||
isa<CallBase>(&I) || isa<AllocaInst>(&I) || isa<PHINode>(&I) ||
isa<LandingPadInst>(&I)) {
continue;
}
if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
if (!BO->getType()->isIntegerTy())
continue;
considerOperand(BO, 0, Sites, MaxBudget);
// Preserve constant shift counts to avoid UB / dynamic shift penalties.
if (!BO->isShift())
considerOperand(BO, 1, Sites, MaxBudget);
} else if (auto *Cmp = dyn_cast<ICmpInst>(&I)) {
if (!Cmp->getOperand(0)->getType()->isIntegerTy())
continue;
considerOperand(Cmp, 0, Sites, MaxBudget);
considerOperand(Cmp, 1, Sites, MaxBudget);
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (!SI->isAtomic() && !SI->isVolatile() &&
SI->getValueOperand()->getType()->isIntegerTy()) {
considerOperand(SI, 0, Sites, MaxBudget);
}
} else if (auto *Sel = dyn_cast<SelectInst>(&I)) {
if (Sel->getType()->isIntegerTy()) {
considerOperand(Sel, 1, Sites, MaxBudget);
considerOperand(Sel, 2, Sites, MaxBudget);
}
} else if (auto *IV = dyn_cast<InsertValueInst>(&I)) {
if (auto *CI = dyn_cast<ConstantInt>(IV->getInsertedValueOperand())) {
if (CI->getBitWidth() == 64 && CI->getZExtValue() > 0xFFFFULL) {
considerOperand(IV, 1, Sites, MaxBudget);
}
}
} else if (auto *RI = dyn_cast<ReturnInst>(&I)) {
if (Value *RV = RI->getReturnValue()) {
if (auto *CI = dyn_cast<ConstantInt>(RV)) {
if ((CI->getBitWidth() == 32 || CI->getBitWidth() == 64) &&
CI->getZExtValue() > 0xFFFFULL) {
considerOperand(RI, 0, Sites, MaxBudget);
}
}
}
}
}
}
}
struct FnRuntimeSeeds {
bool Initialized = false;
Value *Seed32 = nullptr;
Value *Seed64 = nullptr;
void init(Function &F, Type *I32Ty, Type *I64Ty) {
if (Initialized)
return;
Initialized = true;
BasicBlock &Entry = F.getEntryBlock();
Value *IntSeed64 = nullptr;
for (Argument &Arg : F.args()) {
if (auto *IntTy = dyn_cast<IntegerType>(Arg.getType())) {
if (IntTy->getBitWidth() >= 16) {
IntSeed64 = &Arg;
break;
}
}
}
Value *PtrSeed = nullptr;
if (!IntSeed64) {
for (Argument &Arg : F.args()) {
if (Arg.getType()->isPointerTy()) {
PtrSeed = &Arg;
break;
}
}
}
AllocaInst *Slot = nullptr;
if (!IntSeed64 && !PtrSeed) {
Instruction *AllocaPt = &*Entry.getFirstInsertionPt();
IRBuilder<> AllocaB(AllocaPt);
AllocaB.SetCurrentDebugLocation(resolveInstDebugLoc(AllocaPt, F));
Slot = AllocaB.CreateAlloca(Type::getInt8Ty(F.getContext()), nullptr,
"ig.oz.seed");
}
// Keep all static allocas strictly grouped before non-alloca seed ops.
AllocaInst *LastAlloca = nullptr;
for (Instruction &Inst : Entry) {
if (auto *AI = dyn_cast<AllocaInst>(&Inst))
LastAlloca = AI;
}
Instruction *SeedPt =
LastAlloca ? LastAlloca->getNextNode() : &*Entry.getFirstInsertionPt();
IRBuilder<> EB(SeedPt);
EB.SetCurrentDebugLocation(resolveInstDebugLoc(SeedPt, F));
Value *Chosen64 = nullptr;
if (IntSeed64) {
unsigned BW = IntSeed64->getType()->getIntegerBitWidth();
Chosen64 = (BW == 64) ? IntSeed64 : EB.CreateZExt(IntSeed64, I64Ty);
} else if (PtrSeed) {
Value *P2I = EB.CreatePtrToInt(PtrSeed, I64Ty);
Chosen64 = EB.CreateLShr(P2I, ConstantInt::get(I64Ty, 4));
} else {
Value *P2I = EB.CreatePtrToInt(Slot, I64Ty);
Chosen64 = EB.CreateLShr(P2I, ConstantInt::get(I64Ty, 4));
}
Seed64 = Chosen64;
Seed32 = EB.CreateTrunc(Chosen64, I32Ty);
}
Value *get(Function &F, bool Is32, Type *I32Ty, Type *I64Ty) {
init(F, I32Ty, I64Ty);
return Is32 ? Seed32 : Seed64;
}
};
Value *emitOpaqueZero(IRBuilder<> &B, Value *SeedVal, unsigned Variant,
uint64_t MixK) {
Type *Ty = SeedVal->getType();
Value *RawZero = nullptr;
if ((Variant & 1U) == 0) {
// ((s | 1)^2 - 1) & 7 == 0 for every integer (odd^2 - 1 is divisible by 8).
Value *Odd = B.CreateOr(SeedVal, ConstantInt::get(Ty, 1));
Value *Sq = B.CreateMul(Odd, Odd);
Value *Diff = B.CreateSub(Sq, ConstantInt::get(Ty, 1));
RawZero = B.CreateAnd(Diff, ConstantInt::get(Ty, 7));
} else {
// (s * (s + 1)) & 1 == 0 for every integer (product of consecutive ints is even).
Value *Plus1 = B.CreateAdd(SeedVal, ConstantInt::get(Ty, 1));
Value *Prod = B.CreateMul(SeedVal, Plus1);
RawZero = B.CreateAnd(Prod, ConstantInt::get(Ty, 1));
}
return B.CreateMul(RawZero, ConstantInt::get(Ty, MixK));
}
} // namespace
bool runOpaqueConstants(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isOpaqueConstantsEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
struct FunctionSites {
Function *Fn = nullptr;
SmallVector<ConstSite, 16> Sites;
unsigned Prob = 100;
bool UseOpaqueZero = false;
};
SmallVector<FunctionSites, 8> Worklist;
const unsigned DefaultMaxPerFn = Policy.opaqueConstMaxPerFn();
const bool DefaultOpaqueZero = Policy.opaqueConstOpaqueZero();
bool NeedsPool = false;
for (Function &F : M) {
if (!Policy.shouldObfuscateConstantsInFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.opaqueConstExemptFunctions())) {
continue;
}
const TargetRule *Rule = Policy.findOpaqueConstRule(F);
unsigned MaxPerFn =
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
unsigned Prob =
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
bool UseOpaqueZero =
(Rule && Rule->OpaqueZero) ? *Rule->OpaqueZero : DefaultOpaqueZero;
if (MaxPerFn == 0 || Prob == 0)
continue;
SmallVector<ConstSite, 16> Sites;
collectConstantSites(F, MaxPerFn, Sites);
if (!Sites.empty()) {
if (!UseOpaqueZero)
NeedsPool = true;
Worklist.push_back({&F, std::move(Sites), Prob, UseOpaqueZero});
}
}
if (Worklist.empty())
return false;
LLVMContext &Ctx = M.getContext();
Type *I32Ty = Type::getInt32Ty(Ctx);
Type *I64Ty = Type::getInt64Ty(Ctx);
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
Policy.sourcePath());
std::array<uint64_t, kConstPoolSize> PoolMasks{};
ArrayType *PoolTy = ArrayType::get(I64Ty, kConstPoolSize);
GlobalVariable *PoolGV = nullptr;
if (NeedsPool) {
IGDeterministicRNG PoolRNG(Policy.seed(), M.getModuleIdentifier(),
"__ig_oc_pool");
SmallVector<Constant *, kConstPoolSize> PoolConsts;
PoolConsts.reserve(kConstPoolSize);
for (unsigned i = 0; i < kConstPoolSize; ++i) {
uint64_t MaskVal = PoolRNG.nextNonZeroU64();
PoolMasks[i] = MaskVal;
PoolConsts.push_back(ConstantInt::get(I64Ty, MaskVal));
}
PoolGV = new GlobalVariable(
M, PoolTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(PoolTy, PoolConsts), "__ig_ocp_" + Tag);
PoolGV->setAlignment(Align(8));
PoolGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
}
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
bool Changed = false;
for (FunctionSites &Item : Worklist) {
Function *F = Item.Fn;
IGDeterministicRNG FnRNG(Policy.seed(), M.getModuleIdentifier(),
F->getName());
FnRuntimeSeeds Seeds;
unsigned FnHits = 0;
for (const ConstSite &Site : Item.Sites) {
if (Item.Prob < 100U && (FnRNG.nextU32() % 100U) >= Item.Prob)
continue;
bool Is32 = (Site.BitWidth == 32);
Type *ValTy = Is32 ? I32Ty : I64Ty;
uint64_t BitMask = Is32 ? 0xFFFFFFFFULL : 0xFFFFFFFFFFFFFFFFULL;
uint64_t TargetVal = Site.Value & BitMask;
uint64_t RemA = (Is32 ? static_cast<uint64_t>(FnRNG.nextNonZeroU32())
: FnRNG.nextNonZeroU64()) &
BitMask;
bool UseXorAdd = (FnRNG.nextU32() & 1U) == 0;
Value *SeedVal = nullptr;
if (Item.UseOpaqueZero) {
SeedVal = Seeds.get(*F, Is32, I32Ty, I64Ty);
}
IRBuilder<> B(Site.Inst);
B.SetCurrentDebugLocation(resolveInstDebugLoc(Site.Inst, *F));
Value *Encoded = nullptr;
if (Item.UseOpaqueZero) {
uint64_t MixK = (FnRNG.nextNonZeroU64() | 1ULL) & BitMask;
Value *OZero = emitOpaqueZero(B, SeedVal, FnRNG.nextU32(), MixK);
if (UseXorAdd) {
uint64_t PartB = (TargetVal ^ RemA) & BitMask;
Value *T1 = B.CreateAdd(OZero, ConstantInt::get(ValTy, RemA));
Encoded = B.CreateXor(T1, ConstantInt::get(ValTy, PartB));
} else {
uint64_t PartB = (TargetVal - RemA) & BitMask;
Value *T1 = B.CreateXor(OZero, ConstantInt::get(ValTy, RemA));
Encoded = B.CreateAdd(T1, ConstantInt::get(ValTy, PartB));
}
++Audit.OpaqueZeroCount;
} else {
unsigned Slot = FnRNG.nextU32() % kConstPoolSize;
uint64_t Mask64 = PoolMasks[Slot];
uint64_t MaskedM = Mask64 & BitMask;
Value *SlotPtr = B.CreateInBoundsGEP(
PoolTy, PoolGV, {Zero64, ConstantInt::get(I64Ty, Slot)});
LoadInst *Loaded64 =
B.CreateAlignedLoad(I64Ty, SlotPtr, Align(8), /*isVolatile=*/true);
Value *Base = Is32 ? B.CreateTrunc(Loaded64, I32Ty)
: static_cast<Value *>(Loaded64);
if (UseXorAdd) {
// Mod-2^W inverse of ((M ^ RemA) + RemB) prevents Add/Xor folding.
uint64_t RemB = (TargetVal - (MaskedM ^ RemA)) & BitMask;
Value *T1 = B.CreateXor(Base, ConstantInt::get(ValTy, RemA));
Encoded = B.CreateAdd(T1, ConstantInt::get(ValTy, RemB));
} else {
uint64_t RemB = ((MaskedM + RemA) ^ TargetVal) & BitMask;
Value *T1 = B.CreateAdd(Base, ConstantInt::get(ValTy, RemA));
Encoded = B.CreateXor(T1, ConstantInt::get(ValTy, RemB));
}
}
Site.Inst->setOperand(Site.OpIdx, Encoded);
++Audit.OpaqueConstantsCount;
++FnHits;
Changed = true;
}
if (FnHits > 0) {
if (verifyFunction(*F, &errs())) {
report_fatal_error(Twine("[IGOpaqueConstants] IR verification failed on ") +
F->getName());
}
Audit.OpaqueConstantsFunctions.push_back(F->getName().str());
}
}
return Changed;
}
} // namespace igobf
+297
View File
@@ -0,0 +1,297 @@
#include "IGPassUtils.h"
#include "IGPolicyConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/ErrorHandling.h"
#include <array>
using namespace llvm;
namespace igobf {
namespace {
constexpr unsigned kFieldPoolSize = 32;
bool isSensitiveGlobalSymbol(const GlobalVariable *GV) {
if (!GV)
return true;
if (GV->isThreadLocal() || GV->isExternallyInitialized() ||
GV->hasAppendingLinkage() || GV->hasExternalWeakLinkage() ||
GV->getAddressSpace() != 0) {
return true;
}
if (GV->hasSection()) {
StringRef Sec = GV->getSection();
if (Sec.contains("__objc") || Sec.contains("__swift") ||
Sec.contains("__cfstring") || Sec.contains("__LLVM") ||
Sec.contains("__mod_init") || Sec.contains("__mod_term")) {
return true;
}
}
StringRef Clean = stripObjCMarker(GV->getName());
if (Clean.starts_with("llvm.") || Clean.starts_with("__ig_") ||
Clean.starts_with(".ig.") || Clean.starts_with("L_OBJC_") ||
Clean.starts_with("l_OBJC_") || Clean.starts_with("OBJC_") ||
Clean.starts_with("_OBJC_") || Clean.starts_with("L_.str")) {
return true;
}
return false;
}
bool isSensitiveBasePtr(const Value *Ptr) {
if (!Ptr)
return true;
const Value *Stripped = Ptr->stripPointerCasts();
if (const auto *GV = dyn_cast<GlobalVariable>(Stripped)) {
if (GV->isConstant() || isSensitiveGlobalSymbol(GV))
return true;
}
return false;
}
struct GEPSite {
GetElementPtrInst *GEP = nullptr;
int64_t ConstOffset = 0;
};
struct GlobalAccessSite {
Instruction *Inst = nullptr;
unsigned PtrOpIdx = 0;
GlobalVariable *GV = nullptr;
};
struct FieldFnWork {
Function *Fn = nullptr;
SmallVector<GEPSite, 16> GEPs;
SmallVector<GlobalAccessSite, 16> Globals;
};
void collectFieldSites(Function &F, const DataLayout &DL, unsigned MaxPerFn,
SmallVectorImpl<GEPSite> &GEPs,
SmallVectorImpl<GlobalAccessSite> &Globals) {
unsigned Total = 0;
for (BasicBlock &BB : F) {
if (BB.isEHPad())
continue;
for (Instruction &I : BB) {
if (Total >= MaxPerFn)
return;
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
if (GEP->getType()->isVectorTy() || GEP->getPointerAddressSpace() != 0)
continue;
if (!GEP->hasAllConstantIndices())
continue;
if (isSensitiveBasePtr(GEP->getPointerOperand()))
continue;
if (any_of(GEP->users(), [](const User *U) {
return isa<LifetimeIntrinsic>(U) || isa<DbgInfoIntrinsic>(U) ||
isa<AssumeInst>(U);
})) {
continue;
}
unsigned IdxBits = DL.getIndexTypeSizeInBits(GEP->getType());
if (IdxBits == 0 || IdxBits > 64)
continue;
APInt ConstOff(IdxBits, 0);
if (!GEP->accumulateConstantOffset(DL, ConstOff))
continue;
int64_t SignedOff = ConstOff.getSExtValue();
if (SignedOff == 0)
continue;
GEPs.push_back({GEP, SignedOff});
++Total;
continue;
}
if (auto *LI = dyn_cast<LoadInst>(&I)) {
if (LI->isVolatile() || LI->isAtomic())
continue;
if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) {
if (!GV->isConstant() && !isSensitiveGlobalSymbol(GV)) {
Globals.push_back({LI, 0, GV});
++Total;
}
}
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (SI->isVolatile() || SI->isAtomic())
continue;
if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
if (!GV->isConstant() && !isSensitiveGlobalSymbol(GV)) {
Globals.push_back({SI, 1, GV});
++Total;
}
}
}
}
}
}
Value *emitMaskedOffset64(IRBuilder<> &B, GlobalVariable *PoolGV,
ArrayType *PoolTy, uint64_t TargetSigned64,
const std::array<uint64_t, kFieldPoolSize> &PoolMasks,
IGDeterministicRNG &RNG) {
Type *I64Ty = B.getInt64Ty();
Value *Zero64 = ConstantInt::get(I64Ty, 0);
unsigned Slot = RNG.nextU32() % kFieldPoolSize;
uint64_t Mask = PoolMasks[Slot];
uint64_t RemA = RNG.nextNonZeroU64();
bool UseXorAdd = (RNG.nextU32() & 1U) == 0;
Value *SlotPtr =
B.CreateInBoundsGEP(PoolTy, PoolGV, {Zero64, ConstantInt::get(I64Ty, Slot)});
Value *LoadedMask =
B.CreateAlignedLoad(I64Ty, SlotPtr, Align(8), /*isVolatile=*/true);
if (UseXorAdd) {
uint64_t RemB = TargetSigned64 - (Mask ^ RemA);
Value *T1 = B.CreateXor(LoadedMask, ConstantInt::get(I64Ty, RemA));
return B.CreateAdd(T1, ConstantInt::get(I64Ty, RemB));
}
uint64_t RemB = (Mask + RemA) ^ TargetSigned64;
Value *T1 = B.CreateAdd(LoadedMask, ConstantInt::get(I64Ty, RemA));
return B.CreateXor(T1, ConstantInt::get(I64Ty, RemB));
}
} // namespace
bool runOpaqueFieldAccess(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isOpaqueFieldEnabled() || Policy.isModuleExempt(M))
return false;
if (!isMachOAArch64NonArm64e(M))
return false;
const DataLayout &DL = M.getDataLayout();
const unsigned MaxPerFn = Policy.opaqueFieldMaxPerFn();
if (MaxPerFn == 0)
return false;
SmallVector<FieldFnWork, 8> Worklist;
DenseMap<GlobalVariable *, unsigned> AnchorSlotMap;
SmallVector<Constant *, 32> AnchorPtrs;
for (Function &F : M) {
if (!Policy.shouldObfuscateFieldAccessInFunction(F))
continue;
if (!isFunctionSafeForTransform(F, Policy,
&Policy.opaqueFieldExemptFunctions())) {
continue;
}
SmallVector<GEPSite, 16> GEPs;
SmallVector<GlobalAccessSite, 16> Globals;
collectFieldSites(F, DL, MaxPerFn, GEPs, Globals);
if (GEPs.empty() && Globals.empty())
continue;
for (const GlobalAccessSite &GS : Globals) {
if (AnchorSlotMap.try_emplace(GS.GV, static_cast<unsigned>(AnchorPtrs.size()))
.second) {
AnchorPtrs.push_back(GS.GV);
}
}
Worklist.push_back({&F, std::move(GEPs), std::move(Globals)});
}
if (Worklist.empty())
return false;
LLVMContext &Ctx = M.getContext();
Type *I8Ty = Type::getInt8Ty(Ctx);
Type *I64Ty = Type::getInt64Ty(Ctx);
PointerType *PtrTy = PointerType::getUnqual(Ctx);
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
Policy.sourcePath());
IGDeterministicRNG PoolRNG(Policy.seed(), M.getModuleIdentifier(),
"__ig_fop_pool");
std::array<uint64_t, kFieldPoolSize> PoolMasks{};
SmallVector<Constant *, kFieldPoolSize> PoolConsts;
PoolConsts.reserve(kFieldPoolSize);
for (unsigned i = 0; i < kFieldPoolSize; ++i) {
uint64_t V = PoolRNG.nextNonZeroU64();
PoolMasks[i] = V;
PoolConsts.push_back(ConstantInt::get(I64Ty, V));
}
ArrayType *PoolTy = ArrayType::get(I64Ty, kFieldPoolSize);
auto *PoolGV = new GlobalVariable(
M, PoolTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
ConstantArray::get(PoolTy, PoolConsts), "__ig_fop_" + Tag);
PoolGV->setAlignment(Align(8));
PoolGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
ArrayType *AnchorArrTy = nullptr;
GlobalVariable *AnchorGV = nullptr;
if (!AnchorPtrs.empty()) {
AnchorArrTy = ArrayType::get(PtrTy, AnchorPtrs.size());
AnchorGV = new GlobalVariable(
M, AnchorArrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
ConstantArray::get(AnchorArrTy, AnchorPtrs), "__ig_gba_" + Tag);
AnchorGV->setAlignment(Align(8));
AnchorGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
}
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
bool Changed = false;
for (FieldFnWork &Item : Worklist) {
Function *F = Item.Fn;
IGDeterministicRNG FnRNG(Policy.seed(), M.getModuleIdentifier(),
(F->getName() + "|field").str());
unsigned FnHits = 0;
for (const GEPSite &Site : Item.GEPs) {
GetElementPtrInst *GEP = Site.GEP;
IRBuilder<> B(GEP);
B.SetCurrentDebugLocation(resolveInstDebugLoc(GEP, *F));
Value *DynOff = emitMaskedOffset64(
B, PoolGV, PoolTy, static_cast<uint64_t>(Site.ConstOffset), PoolMasks,
FnRNG);
Value *NewPtr = B.CreateGEP(I8Ty, GEP->getPointerOperand(), DynOff);
GEP->replaceAllUsesWith(NewPtr);
GEP->eraseFromParent();
++FnHits;
}
for (const GlobalAccessSite &Site : Item.Globals) {
unsigned AnchorIdx = AnchorSlotMap[Site.GV];
IRBuilder<> B(Site.Inst);
B.SetCurrentDebugLocation(resolveInstDebugLoc(Site.Inst, *F));
Value *SlotPtr = B.CreateInBoundsGEP(
AnchorArrTy, AnchorGV, {Zero64, ConstantInt::get(I64Ty, AnchorIdx)});
Value *LoadedBase =
B.CreateAlignedLoad(PtrTy, SlotPtr, Align(8), /*isVolatile=*/true);
Value *OpaqueZero =
emitMaskedOffset64(B, PoolGV, PoolTy, 0ULL, PoolMasks, FnRNG);
Value *NewPtr = B.CreateGEP(I8Ty, LoadedBase, OpaqueZero);
Site.Inst->setOperand(Site.PtrOpIdx, NewPtr);
++FnHits;
}
if (FnHits > 0) {
if (verifyFunction(*F, &errs())) {
report_fatal_error(
Twine("[IGOpaqueFieldAccess] IR verification failed on ") +
F->getName());
}
Audit.OpaqueFieldAccessCount += FnHits;
Audit.OpaqueFieldFunctions.push_back(F->getName().str());
Changed = true;
}
}
return Changed;
}
} // namespace igobf
+94
View File
@@ -0,0 +1,94 @@
#include "IGPolicyConfig.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/PassPlugin.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
namespace igobf {
bool runSourcePathScrubbing(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runStringEncryption(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runFunctionOutline(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runOpaqueFieldAccess(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runOpaqueConstants(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runArithmeticObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runIndirectCallObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runBasicBlockSplit(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runControlFlowFlattening(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runIndirectBranchObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
bool runAntiHooking(llvm::Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit);
} // namespace igobf
using namespace llvm;
namespace {
struct IGObfuscateModulePass : public PassInfoMixin<IGObfuscateModulePass> {
PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
igobf::IGAuditRecord Audit;
igobf::IGPolicyConfig Policy = igobf::IGPolicyConfig::loadFromCLI(M, Audit);
bool Changed = false;
if (Policy.mode() != igobf::ObfMode::Off &&
Policy.mode() != igobf::ObfMode::Noop) {
Changed |= igobf::runSourcePathScrubbing(M, Policy, Audit);
Changed |= igobf::runStringEncryption(M, Policy, Audit);
Changed |= igobf::runOpaqueFieldAccess(M, Policy, Audit);
Changed |= igobf::runFunctionOutline(M, Policy, Audit);
Changed |= igobf::runOpaqueConstants(M, Policy, Audit);
Changed |= igobf::runArithmeticObfuscation(M, Policy, Audit);
Changed |= igobf::runIndirectCallObfuscation(M, Policy, Audit);
Changed |= igobf::runBasicBlockSplit(M, Policy, Audit);
Changed |= igobf::runControlFlowFlattening(M, Policy, Audit);
Changed |= igobf::runIndirectBranchObfuscation(M, Policy, Audit);
Changed |= igobf::runAntiHooking(M, Policy, Audit);
if (Changed && verifyModule(M, &errs())) {
report_fatal_error("[IGPass] Module verification failed after passes");
}
}
if (!Audit.writeToFile(Policy.auditOutPath())) {
report_fatal_error("[IGPass] Failed to persist module audit JSON");
}
return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
}
};
} // namespace
llvm::PassPluginLibraryInfo getIGObfuscatorPluginInfo() {
return {LLVM_PLUGIN_API_VERSION, "IGObfuscator", LLVM_VERSION_STRING,
[](PassBuilder &PB) {
PB.registerPipelineParsingCallback(
[](StringRef Name, ModulePassManager &MPM,
ArrayRef<PassBuilder::PipelineElement>) {
if (Name == "ig-obfuscate") {
MPM.addPass(IGObfuscateModulePass());
return true;
}
return false;
});
}};
}
#ifndef LLVM_IGOBFUSCATOR_LINK_INTO_TOOLS
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
llvmGetPassPluginInfo() {
return getIGObfuscatorPluginInfo();
}
#endif
+805
View File
@@ -0,0 +1,805 @@
#include "IGPolicyConfig.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SHA256.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
cl::opt<std::string>
IGPolicyPath("ig-policy", cl::init(""),
cl::desc("Path to iOSGuard LLVM obfuscation policy JSON"));
cl::opt<std::string>
IGModeOpt("ig-mode", cl::init("full"),
cl::desc("iOSGuard obfuscation mode: full|str|noop|off"));
cl::opt<std::string> IGPassFilterOpt(
"ig-pass-filter", cl::init("all"),
cl::desc("iOSGuard pass filter: all|str|fla|icall|const|arith|ibr|antihook|outline|field|bbsplit"));
cl::opt<std::string>
IGSeedOpt("ig-seed", cl::init("m0_seed_20261119_v1"),
cl::desc("iOSGuard deterministic obfuscation seed"));
cl::opt<std::string>
IGSourcePathOpt("ig-source-path", cl::init(""),
cl::desc("Original source path hint for policy matching"));
cl::opt<std::string>
IGSwiftModuleOpt("ig-swift-module", cl::init(""),
cl::desc("Authoritative Swift module name of current target"));
cl::opt<std::string>
IGAuditOutOpt("ig-audit-out", cl::init(""),
cl::desc("Output path for module obfuscation audit JSON"));
std::string stripLeadingObjCMarker(StringRef Name) {
if (!Name.empty() && Name.front() == '\x01')
return Name.drop_front(1).str();
return Name.str();
}
igobf::ObfMode parseMode(StringRef S) {
if (S == "off")
return igobf::ObfMode::Off;
if (S == "noop")
return igobf::ObfMode::Noop;
if (S == "str")
return igobf::ObfMode::StrOnly;
return igobf::ObfMode::Full;
}
igobf::PassFilter parseFilter(StringRef S) {
if (S == "str")
return igobf::PassFilter::StrOnly;
if (S == "fla")
return igobf::PassFilter::FlaOnly;
if (S == "icall")
return igobf::PassFilter::IcallOnly;
if (S == "const")
return igobf::PassFilter::OpaqueConstOnly;
if (S == "arith")
return igobf::PassFilter::ArithOnly;
if (S == "ibr")
return igobf::PassFilter::IbrOnly;
if (S == "antihook")
return igobf::PassFilter::AntiHookOnly;
if (S == "outline")
return igobf::PassFilter::OutlineOnly;
if (S == "field")
return igobf::PassFilter::FieldOnly;
if (S == "bbsplit")
return igobf::PassFilter::BBSplitOnly;
return igobf::PassFilter::All;
}
unsigned parseClampedUInt(const json::Object &Obj, StringRef Key,
unsigned DefaultVal, int64_t MinVal,
int64_t MaxVal) {
if (auto V = Obj.getInteger(Key)) {
int64_t Raw = *V;
if (Raw < MinVal)
Raw = MinVal;
if (Raw > MaxVal)
Raw = MaxVal;
return static_cast<unsigned>(Raw);
}
return DefaultVal;
}
void appendStringArray(const json::Object &Obj, StringRef Key,
std::vector<std::string> &Out) {
if (const json::Array *Arr = Obj.getArray(Key)) {
for (const json::Value &V : *Arr) {
if (auto S = V.getAsString()) {
if (!S->empty())
Out.push_back(S->str());
}
}
}
}
void appendRuleArray(const json::Object &Obj, StringRef Key,
std::vector<igobf::TargetRule> &Out) {
if (const json::Array *Arr = Obj.getArray(Key)) {
for (const json::Value &V : *Arr) {
const json::Object *RuleObj = V.getAsObject();
if (!RuleObj)
continue;
igobf::TargetRule Rule;
if (auto S = RuleObj->getString("id"))
Rule.Id = S->str();
if (auto S = RuleObj->getString("path_contains"))
Rule.PathContains = S->str();
if (auto S = RuleObj->getString("function_contains"))
Rule.FunctionContains = S->str();
if (auto B = RuleObj->getBoolean("whole_module_if_no_debug"))
Rule.WholeModuleIfNoDebug = *B;
if (RuleObj->getInteger("rounds"))
Rule.Rounds = parseClampedUInt(*RuleObj, "rounds", 1, 1, 4);
if (RuleObj->getInteger("max_per_fn"))
Rule.MaxPerFn = parseClampedUInt(*RuleObj, "max_per_fn", 64, 0, 1024);
if (RuleObj->getInteger("probability"))
Rule.Probability = parseClampedUInt(*RuleObj, "probability", 100, 0, 100);
if (auto B = RuleObj->getBoolean("nonlinear_mba"))
Rule.NonlinearMBA = *B;
if (auto B = RuleObj->getBoolean("opaque_zero"))
Rule.OpaqueZero = *B;
if (!Rule.PathContains.empty() || !Rule.FunctionContains.empty())
Out.push_back(std::move(Rule));
}
}
}
void appendStringReplaceRules(const json::Object &Obj, StringRef Key,
std::vector<igobf::StringReplaceRule> &Out) {
if (const json::Array *Arr = Obj.getArray(Key)) {
for (const json::Value &V : *Arr) {
const json::Object *RuleObj = V.getAsObject();
if (!RuleObj)
continue;
igobf::StringReplaceRule Rule;
if (auto S = RuleObj->getString("exact"))
Rule.Exact = S->str();
if (auto S = RuleObj->getString("replace"))
Rule.Replace = S->str();
if (!Rule.Exact.empty())
Out.push_back(std::move(Rule));
}
}
}
void writeStringArrayAttr(json::OStream &J, StringRef Key,
const std::vector<std::string> &Items) {
J.attributeArray(Key, [&] {
for (const auto &Item : Items)
J.value(Item);
});
}
} // namespace
namespace igobf {
IGDeterministicRNG::IGDeterministicRNG(StringRef Seed, StringRef ModuleId,
StringRef ItemId) {
Prefix_.reserve(Seed.size() + ModuleId.size() + ItemId.size() + 4);
Prefix_.append(Seed.begin(), Seed.end());
Prefix_.push_back('|');
Prefix_.append(ModuleId.begin(), ModuleId.end());
Prefix_.push_back('|');
Prefix_.append(ItemId.begin(), ItemId.end());
Prefix_.push_back('|');
}
std::array<uint8_t, 32> IGDeterministicRNG::nextBlock() {
SHA256 Hasher;
Hasher.update(StringRef(Prefix_));
std::string CntStr = std::to_string(Counter_++);
Hasher.update(StringRef(CntStr));
return Hasher.final();
}
uint32_t IGDeterministicRNG::nextU32() {
if (Offset_ + 4 > Buffer_.size()) {
Buffer_ = nextBlock();
Offset_ = 0;
}
uint32_t V = (static_cast<uint32_t>(Buffer_[Offset_]) << 24) |
(static_cast<uint32_t>(Buffer_[Offset_ + 1]) << 16) |
(static_cast<uint32_t>(Buffer_[Offset_ + 2]) << 8) |
static_cast<uint32_t>(Buffer_[Offset_ + 3]);
Offset_ += 4;
return V;
}
uint32_t IGDeterministicRNG::nextNonZeroU32() {
uint32_t V = 0;
do {
V = nextU32();
} while (V == 0);
return V;
}
uint64_t IGDeterministicRNG::nextU64() {
uint64_t Hi = static_cast<uint64_t>(nextU32());
uint64_t Lo = static_cast<uint64_t>(nextU32());
return (Hi << 32) | Lo;
}
uint64_t IGDeterministicRNG::nextNonZeroU64() {
uint64_t V = 0;
do {
V = nextU64();
} while (V == 0);
return V;
}
uint8_t IGDeterministicRNG::nextNonZeroByte() {
uint8_t B = 0;
do {
if (Offset_ >= Buffer_.size()) {
Buffer_ = nextBlock();
Offset_ = 0;
}
B = Buffer_[Offset_++];
} while (B == 0);
return B;
}
bool IGAuditRecord::writeToFile(StringRef OutPath) const {
if (OutPath.empty())
return true;
SmallString<256> Parent = sys::path::parent_path(OutPath);
if (!Parent.empty()) {
std::error_code EC = sys::fs::create_directories(Parent);
if (EC) {
errs() << "[IGPass] Failed to create audit directory " << Parent << ": "
<< EC.message() << "\n";
return false;
}
}
std::error_code EC;
raw_fd_ostream OS(OutPath, EC, sys::fs::OF_Text);
if (EC) {
errs() << "[IGPass] Failed to open audit output " << OutPath << ": "
<< EC.message() << "\n";
return false;
}
json::OStream J(OS, 2);
J.object([&] {
J.attribute("mode", Mode);
J.attribute("pass_filter", PassFilter);
J.attribute("seed", Seed);
J.attribute("source_path", SourcePath);
J.attribute("module_id", ModuleId);
J.attribute("strings_encrypted_count",
static_cast<int64_t>(StringsEncryptedCount));
J.attribute("strings_stack_encrypted_count",
static_cast<int64_t>(StringsStackEncryptedCount));
J.attribute("objc_strings_encrypted_count",
static_cast<int64_t>(ObjCStringsEncryptedCount));
J.attribute("swift_strings_encrypted_count",
static_cast<int64_t>(SwiftStringsEncryptedCount));
J.attribute("strings_replaced_count",
static_cast<int64_t>(StringsReplacedCount));
J.attribute("strings_skipped_count",
static_cast<int64_t>(StringsSkippedCount));
J.attribute("paths_scrubbed_count",
static_cast<int64_t>(PathsScrubbedCount));
J.attribute("indirect_calls_count",
static_cast<int64_t>(IndirectCallsCount));
J.attribute("indirect_call_dual_table", IndirectCallDualTable);
J.attribute("opaque_constants_count",
static_cast<int64_t>(OpaqueConstantsCount));
J.attribute("arithmetic_rewrites_count",
static_cast<int64_t>(ArithmeticRewritesCount));
J.attribute("indirect_branches_count",
static_cast<int64_t>(IndirectBranchesCount));
J.attribute("anti_hook_functions_count",
static_cast<int64_t>(AntiHookFunctionsCount));
J.attribute("functions_outlined_count",
static_cast<int64_t>(FunctionsOutlinedCount));
J.attribute("opaque_field_access_count",
static_cast<int64_t>(OpaqueFieldAccessCount));
J.attribute("bb_split_count", static_cast<int64_t>(BBSplitCount));
J.attribute("nonlinear_mba_count",
static_cast<int64_t>(NonlinearMBACount));
J.attribute("opaque_zero_count", static_cast<int64_t>(OpaqueZeroCount));
writeStringArrayAttr(J, "functions_flattened", FunctionsFlattened);
J.attributeArray("functions_flattened_details", [&] {
for (const auto &D : FunctionsFlattenedDetails) {
J.object([&] {
J.attribute("name", D.Name);
J.attribute("topology", D.Topology);
J.attribute("encoding", D.Encoding);
J.attribute("blocks", static_cast<int64_t>(D.Blocks));
});
}
});
writeStringArrayAttr(J, "strings_encrypted_functions",
StringsEncryptedFunctions);
writeStringArrayAttr(J, "indirect_calls_functions", IndirectCallsFunctions);
writeStringArrayAttr(J, "opaque_constants_functions",
OpaqueConstantsFunctions);
writeStringArrayAttr(J, "arithmetic_functions", ArithmeticFunctions);
writeStringArrayAttr(J, "indirect_branches_functions",
IndirectBranchesFunctions);
writeStringArrayAttr(J, "anti_hook_functions", AntiHookFunctions);
writeStringArrayAttr(J, "outlined_functions", OutlinedFunctions);
writeStringArrayAttr(J, "opaque_field_functions", OpaqueFieldFunctions);
writeStringArrayAttr(J, "bb_split_functions", BBSplitFunctions);
J.attributeArray("functions_skipped", [&] {
for (const auto &S : FunctionsSkipped) {
J.object([&] {
J.attribute("name", S.Name);
J.attribute("reason", S.Reason);
});
}
});
writeStringArrayAttr(J, "annotated_targets", AnnotatedTargets);
});
OS << "\n";
return true;
}
IGPolicyConfig IGPolicyConfig::loadFromCLI(const Module &M,
IGAuditRecord &AuditOut) {
IGPolicyConfig Cfg;
Cfg.Mode_ = parseMode(IGModeOpt);
Cfg.Filter_ = parseFilter(IGPassFilterOpt);
Cfg.Seed_ = IGSeedOpt;
Cfg.SourcePath_ = !IGSourcePathOpt.empty() ? std::string(IGSourcePathOpt)
: M.getSourceFileName();
Cfg.SwiftModuleName_ = IGSwiftModuleOpt;
Cfg.AuditOutPath_ = IGAuditOutOpt;
// Baseline function exemptions protecting runtime/linker/defender hooks
Cfg.ExemptFunctionPrefixes_ = {
"__ig_", "ig_defender_", "ig_call_", "ig_poison_",
"ig_sys_", "ig_a", "ig_archive_", "_IG_dispatch_",
"IG_dispatch_", "llvm.", "__swift_",
};
if (!IGPolicyPath.empty()) {
auto BufOrErr = MemoryBuffer::getFile(IGPolicyPath);
if (!BufOrErr) {
report_fatal_error(Twine("[IGPass] Cannot read policy JSON: ") +
IGPolicyPath + ": " +
BufOrErr.getError().message());
}
Expected<json::Value> Parsed = json::parse(BufOrErr.get()->getBuffer());
if (!Parsed) {
report_fatal_error(Twine("[IGPass] Invalid policy JSON: ") +
IGPolicyPath + ": " + toString(Parsed.takeError()));
}
if (const json::Object *Root = Parsed->getAsObject()) {
if (auto Topo = Root->getString("flatten_topology")) {
if (*Topo == "sparse_switch" || *Topo == "star_switch")
Cfg.FlattenTopology_ = igobf::FlattenTopology::StarSwitch;
}
Cfg.BogusBlockCount_ =
parseClampedUInt(*Root, "flatten_bogus_blocks", 0, 0, 8);
if (auto SplitLin = Root->getBoolean("flatten_split_linear_blocks")) {
Cfg.SplitLinearBlocks_ = *SplitLin;
}
Cfg.OpaqueConstMaxPerFn_ =
parseClampedUInt(*Root, "opaque_const_max_per_fn", 64, 1, 512);
Cfg.ArithmeticRounds_ =
parseClampedUInt(*Root, "arithmetic_rounds", 1, 1, 3);
Cfg.ArithmeticMaxPerFn_ =
parseClampedUInt(*Root, "arithmetic_max_per_fn", 128, 1, 1024);
Cfg.StringEncryptStackMaxLen_ =
parseClampedUInt(*Root, "string_encrypt_stack_max_len", 128, 16, 512);
if (auto DualTbl = Root->getBoolean("indirect_call_dual_table")) {
Cfg.IndirectCallDualTable_ = *DualTbl;
}
Cfg.FunctionOutlineMaxPerFn_ =
parseClampedUInt(*Root, "function_outline_max_per_fn", 2, 0, 8);
Cfg.FunctionOutlineMinInsts_ =
parseClampedUInt(*Root, "function_outline_min_insts", 6, 3, 64);
Cfg.OpaqueFieldMaxPerFn_ =
parseClampedUInt(*Root, "opaque_field_max_per_fn", 32, 0, 256);
Cfg.BBSplitMaxPerFn_ =
parseClampedUInt(*Root, "bb_split_max_per_fn", 4, 0, 16);
Cfg.BBSplitMinInsts_ =
parseClampedUInt(*Root, "bb_split_min_insts", 8, 4, 64);
if (auto NlMba = Root->getBoolean("arithmetic_nonlinear_mba")) {
Cfg.ArithmeticNonlinearMBA_ = *NlMba;
}
if (auto Oz = Root->getBoolean("opaque_const_opaque_zero")) {
Cfg.OpaqueConstOpaqueZero_ = *Oz;
}
appendStringArray(*Root, "exempt_path_substrings",
Cfg.ExemptPathSubstrings_);
appendStringArray(*Root, "exempt_function_prefixes",
Cfg.ExemptFunctionPrefixes_);
appendStringArray(*Root, "scrub_path_substrings",
Cfg.ScrubPathSubstrings_);
appendRuleArray(*Root, "string_encrypt_targets",
Cfg.StringEncryptTargets_);
appendRuleArray(*Root, "string_encrypt_objc_targets",
Cfg.StringEncryptObjCTargets_);
appendRuleArray(*Root, "string_encrypt_swift_targets",
Cfg.StringEncryptSwiftTargets_);
appendRuleArray(*Root, "string_encrypt_stack_targets",
Cfg.StringEncryptStackTargets_);
appendStringReplaceRules(*Root, "string_replace_rules",
Cfg.StringReplaceRules_);
appendRuleArray(*Root, "indirect_call_targets",
Cfg.IndirectCallTargets_);
appendStringArray(*Root, "indirect_call_same_image_prefixes",
Cfg.IndirectCallSameImagePrefixes_);
appendRuleArray(*Root, "flatten_targets", Cfg.FlattenTargets_);
appendRuleArray(*Root, "opaque_const_targets", Cfg.OpaqueConstTargets_);
appendStringArray(*Root, "opaque_const_exempt_functions",
Cfg.OpaqueConstExemptFunctions_);
appendRuleArray(*Root, "arithmetic_targets", Cfg.ArithmeticTargets_);
appendStringArray(*Root, "arithmetic_exempt_functions",
Cfg.ArithmeticExemptFunctions_);
appendRuleArray(*Root, "indirect_branch_targets",
Cfg.IndirectBranchTargets_);
appendStringArray(*Root, "indirect_branch_exempt_functions",
Cfg.IndirectBranchExemptFunctions_);
appendRuleArray(*Root, "anti_hooking_targets", Cfg.AntiHookingTargets_);
appendStringArray(*Root, "anti_hooking_exempt_functions",
Cfg.AntiHookingExemptFunctions_);
appendRuleArray(*Root, "function_outline_targets",
Cfg.FunctionOutlineTargets_);
appendStringArray(*Root, "function_outline_exempt_functions",
Cfg.FunctionOutlineExemptFunctions_);
appendRuleArray(*Root, "opaque_field_targets", Cfg.OpaqueFieldTargets_);
appendStringArray(*Root, "opaque_field_exempt_functions",
Cfg.OpaqueFieldExemptFunctions_);
appendRuleArray(*Root, "bb_split_targets", Cfg.BBSplitTargets_);
appendStringArray(*Root, "bb_split_exempt_functions",
Cfg.BBSplitExemptFunctions_);
}
}
Cfg.collectAnnotations(M);
AuditOut.Mode = IGModeOpt;
AuditOut.PassFilter = IGPassFilterOpt;
AuditOut.Seed = Cfg.Seed_;
AuditOut.SourcePath = Cfg.SourcePath_;
AuditOut.ModuleId = M.getModuleIdentifier();
AuditOut.IndirectCallDualTable = Cfg.IndirectCallDualTable_;
for (const auto *SetPtr :
{&Cfg.AnnotatedFlatten_, &Cfg.AnnotatedStr_, &Cfg.AnnotatedIcall_,
&Cfg.AnnotatedConst_, &Cfg.AnnotatedArith_, &Cfg.AnnotatedIbr_,
&Cfg.AnnotatedAntiHook_, &Cfg.AnnotatedOutline_,
&Cfg.AnnotatedField_, &Cfg.AnnotatedBBSplit_}) {
for (const auto &Item : *SetPtr)
AuditOut.AnnotatedTargets.push_back(Item.getKey().str());
}
return Cfg;
}
bool IGPolicyConfig::isStringEncryptionEnabled() const {
if (Mode_ == ObfMode::Off || Mode_ == ObfMode::Noop)
return false;
if (Mode_ == ObfMode::StrOnly)
return true;
return Filter_ == PassFilter::All || Filter_ == PassFilter::StrOnly;
}
bool IGPolicyConfig::isIndirectCallEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::IcallOnly;
}
bool IGPolicyConfig::isFlatteningEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::FlaOnly;
}
bool IGPolicyConfig::isOpaqueConstantsEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::OpaqueConstOnly;
}
bool IGPolicyConfig::isArithmeticEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::ArithOnly;
}
bool IGPolicyConfig::isIndirectBranchEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::IbrOnly;
}
bool IGPolicyConfig::isAntiHookingEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::AntiHookOnly;
}
bool IGPolicyConfig::isFunctionOutlineEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::OutlineOnly;
}
bool IGPolicyConfig::isOpaqueFieldEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::FieldOnly;
}
bool IGPolicyConfig::isBBSplitEnabled() const {
if (Mode_ != ObfMode::Full)
return false;
return Filter_ == PassFilter::All || Filter_ == PassFilter::BBSplitOnly;
}
std::string IGPolicyConfig::resolveFunctionSourcePath(const Function &F,
StringRef FallbackPath) {
if (const DISubprogram *SP = F.getSubprogram()) {
StringRef File = SP->getFilename();
StringRef Dir = SP->getDirectory();
if (!File.empty()) {
if (sys::path::is_absolute(File) || Dir.empty())
return File.str();
SmallString<256> Joined(Dir);
sys::path::append(Joined, File);
return Joined.str().str();
}
}
if (!FallbackPath.empty())
return FallbackPath.str();
if (const Module *M = F.getParent())
return M->getSourceFileName();
return "";
}
void IGPolicyConfig::collectAnnotations(const Module &M) {
const GlobalVariable *GA = M.getNamedGlobal("llvm.global.annotations");
if (!GA || !GA->hasInitializer())
return;
const auto *CA = dyn_cast<ConstantArray>(GA->getInitializer());
if (!CA)
return;
for (const Use &Op : CA->operands()) {
const auto *CS = dyn_cast<ConstantStruct>(Op.get());
if (!CS || CS->getNumOperands() < 2)
continue;
const Value *FnVal = CS->getOperand(0)->stripPointerCasts();
const Value *AnnVal = CS->getOperand(1)->stripPointerCasts();
const auto *Fn = dyn_cast<Function>(FnVal);
const auto *AnnGV = dyn_cast<GlobalVariable>(AnnVal);
if (!Fn || !AnnGV || !AnnGV->hasInitializer())
continue;
const auto *CDS = dyn_cast<ConstantDataSequential>(AnnGV->getInitializer());
if (!CDS || !CDS->isString())
continue;
StringRef Tag = CDS->getAsCString();
StringRef Name = Fn->getName();
if (Tag == "ig_exempt")
AnnotatedExempt_.insert(Name);
else if (Tag == "ig_flatten")
AnnotatedFlatten_.insert(Name);
else if (Tag == "ig_str")
AnnotatedStr_.insert(Name);
else if (Tag == "ig_icall")
AnnotatedIcall_.insert(Name);
else if (Tag == "ig_const")
AnnotatedConst_.insert(Name);
else if (Tag == "ig_arith")
AnnotatedArith_.insert(Name);
else if (Tag == "ig_ibr")
AnnotatedIbr_.insert(Name);
else if (Tag == "ig_antihook")
AnnotatedAntiHook_.insert(Name);
else if (Tag == "ig_outline")
AnnotatedOutline_.insert(Name);
else if (Tag == "ig_field")
AnnotatedField_.insert(Name);
else if (Tag == "ig_bbsplit")
AnnotatedBBSplit_.insert(Name);
}
}
bool IGPolicyConfig::hasAnnotation(const Function &F, StringRef Tag) const {
if (Tag == "ig_exempt")
return AnnotatedExempt_.contains(F.getName());
if (Tag == "ig_flatten")
return AnnotatedFlatten_.contains(F.getName());
if (Tag == "ig_str")
return AnnotatedStr_.contains(F.getName());
if (Tag == "ig_icall")
return AnnotatedIcall_.contains(F.getName());
if (Tag == "ig_const")
return AnnotatedConst_.contains(F.getName());
if (Tag == "ig_arith")
return AnnotatedArith_.contains(F.getName());
if (Tag == "ig_ibr")
return AnnotatedIbr_.contains(F.getName());
if (Tag == "ig_antihook")
return AnnotatedAntiHook_.contains(F.getName());
if (Tag == "ig_outline")
return AnnotatedOutline_.contains(F.getName());
if (Tag == "ig_field")
return AnnotatedField_.contains(F.getName());
if (Tag == "ig_bbsplit")
return AnnotatedBBSplit_.contains(F.getName());
return false;
}
bool IGPolicyConfig::isModuleExempt(const Module &M) const {
StringRef Candidate =
!SourcePath_.empty() ? StringRef(SourcePath_) : M.getSourceFileName();
for (const std::string &Ex : ExemptPathSubstrings_) {
if (!Candidate.empty() && Candidate.contains(Ex))
return true;
}
return false;
}
bool IGPolicyConfig::isFunctionExempt(const Function &F) const {
if (F.isDeclaration())
return true;
if (hasAnnotation(F, "ig_exempt"))
return true;
std::string CleanName = stripLeadingObjCMarker(F.getName());
for (const std::string &Prefix : ExemptFunctionPrefixes_) {
if (StringRef(CleanName).starts_with(Prefix))
return true;
}
std::string FuncPath = resolveFunctionSourcePath(F, SourcePath_);
for (const std::string &Ex : ExemptPathSubstrings_) {
if ((!FuncPath.empty() && StringRef(FuncPath).contains(Ex)) ||
(!SourcePath_.empty() && StringRef(SourcePath_).contains(Ex))) {
return true;
}
}
return false;
}
const TargetRule *
IGPolicyConfig::findMatchingRule(const std::vector<TargetRule> &Rules,
const Function &F) const {
std::string FuncPath = resolveFunctionSourcePath(F, SourcePath_);
std::string CleanName = stripLeadingObjCMarker(F.getName());
StringRef ModuleSrc =
F.getParent() ? StringRef(F.getParent()->getSourceFileName())
: StringRef();
for (const TargetRule &R : Rules) {
bool PathOk = R.PathContains.empty() ||
StringRef(FuncPath).contains(R.PathContains) ||
StringRef(SourcePath_).contains(R.PathContains) ||
StringRef(ModuleSrc).contains(R.PathContains);
if (!PathOk)
continue;
bool FnOk = R.FunctionContains.empty() ||
StringRef(CleanName).contains(R.FunctionContains) ||
F.getName().contains(R.FunctionContains);
if (FnOk)
return &R;
}
return nullptr;
}
bool IGPolicyConfig::matchesAnyRule(const std::vector<TargetRule> &Rules,
const Function &F) const {
return findMatchingRule(Rules, F) != nullptr;
}
bool IGPolicyConfig::shouldEncryptStringsInFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_str") || hasAnnotation(F, "ig_flatten"))
return true;
return matchesAnyRule(StringEncryptTargets_, F);
}
bool IGPolicyConfig::shouldEncryptObjCStringsInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
return matchesAnyRule(StringEncryptObjCTargets_, F);
}
bool IGPolicyConfig::shouldEncryptSwiftStringsInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
return matchesAnyRule(StringEncryptSwiftTargets_, F);
}
bool IGPolicyConfig::shouldStackEncryptStringsInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
return matchesAnyRule(StringEncryptStackTargets_, F);
}
bool IGPolicyConfig::shouldIndirectCallInFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_icall"))
return true;
return matchesAnyRule(IndirectCallTargets_, F);
}
bool IGPolicyConfig::shouldFlattenFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_flatten"))
return true;
return matchesAnyRule(FlattenTargets_, F);
}
bool IGPolicyConfig::shouldObfuscateConstantsInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_const"))
return true;
return matchesAnyRule(OpaqueConstTargets_, F);
}
bool IGPolicyConfig::shouldObfuscateArithmeticInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_arith"))
return true;
return matchesAnyRule(ArithmeticTargets_, F);
}
bool IGPolicyConfig::shouldIndirectBranchInFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_ibr"))
return true;
return matchesAnyRule(IndirectBranchTargets_, F);
}
bool IGPolicyConfig::shouldAntiHookFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_antihook"))
return true;
return matchesAnyRule(AntiHookingTargets_, F);
}
bool IGPolicyConfig::shouldOutlineFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_outline"))
return true;
return matchesAnyRule(FunctionOutlineTargets_, F);
}
bool IGPolicyConfig::shouldObfuscateFieldAccessInFunction(
const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_field"))
return true;
return matchesAnyRule(OpaqueFieldTargets_, F);
}
bool IGPolicyConfig::shouldSplitBasicBlocksInFunction(const Function &F) const {
if (isFunctionExempt(F))
return false;
if (hasAnnotation(F, "ig_bbsplit"))
return true;
return matchesAnyRule(BBSplitTargets_, F);
}
const TargetRule *
IGPolicyConfig::findArithmeticRule(const Function &F) const {
return findMatchingRule(ArithmeticTargets_, F);
}
const TargetRule *
IGPolicyConfig::findOpaqueConstRule(const Function &F) const {
return findMatchingRule(OpaqueConstTargets_, F);
}
const TargetRule *
IGPolicyConfig::findBBSplitRule(const Function &F) const {
return findMatchingRule(BBSplitTargets_, F);
}
} // namespace igobf
+983
View File
@@ -0,0 +1,983 @@
#include "IGPolicyConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicsAArch64.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/SHA256.h"
#include "llvm/TargetParser/Triple.h"
#include <algorithm>
#include <cstring>
using namespace llvm;
namespace igobf {
namespace {
void collectCompilerUsed(const Module &M, StringRef Name,
SmallPtrSetImpl<const GlobalValue *> &Out) {
const GlobalVariable *GV = M.getNamedGlobal(Name);
if (!GV || !GV->hasInitializer())
return;
const auto *CA = dyn_cast<ConstantArray>(GV->getInitializer());
if (!CA)
return;
for (const Use &U : CA->operands()) {
if (const auto *Target = dyn_cast<GlobalValue>(U.get()->stripPointerCasts()))
Out.insert(Target);
}
}
bool isPassThroughConstantExpr(const ConstantExpr *CE) {
unsigned Op = CE->getOpcode();
if (Op == Instruction::BitCast || Op == Instruction::AddrSpaceCast)
return true;
if (Op == Instruction::GetElementPtr) {
if (const auto *GEP = dyn_cast<GEPOperator>(CE))
return GEP->hasAllZeroIndices();
}
return false;
}
bool containsRootValue(const Value *V, const GlobalVariable *Root,
bool AllowSwiftBias) {
if (V == Root)
return true;
const auto *CE = dyn_cast<ConstantExpr>(V);
if (!CE)
return false;
if (isPassThroughConstantExpr(CE))
return containsRootValue(CE->getOperand(0), Root, AllowSwiftBias);
if (!AllowSwiftBias)
return false;
switch (CE->getOpcode()) {
case Instruction::PtrToInt:
case Instruction::IntToPtr:
return containsRootValue(CE->getOperand(0), Root, true);
case Instruction::Sub:
return isa<ConstantInt>(CE->getOperand(1)) &&
containsRootValue(CE->getOperand(0), Root, true);
case Instruction::Add:
case Instruction::Or: {
bool LeftRoot = isa<ConstantInt>(CE->getOperand(1)) &&
containsRootValue(CE->getOperand(0), Root, true);
bool RightRoot = isa<ConstantInt>(CE->getOperand(0)) &&
containsRootValue(CE->getOperand(1), Root, true);
return LeftRoot || RightRoot;
}
default:
return false;
}
}
const Value *unwrapBaseValue(const Value *V) {
while (const auto *CE = dyn_cast<ConstantExpr>(V)) {
if (!isPassThroughConstantExpr(CE))
break;
V = CE->getOperand(0);
}
return V;
}
bool isSafePhiPredBlock(const BasicBlock *PredBB) {
if (!PredBB || PredBB->isEHPad())
return false;
const Instruction *Term = PredBB->getTerminator();
if (!Term || isa<CatchSwitchInst>(Term) || isa<IndirectBrInst>(Term))
return false;
return true;
}
// Verify that EVERY transitive user of Root is a controlled instruction inside
// a function matching FnPred (or safe predecessor edges of PHINodes).
bool collectControlledUsersEx(const GlobalVariable *Root, bool AllowSwiftBias,
function_ref<bool(const Function &)> FnPred,
SmallVectorImpl<Instruction *> &OutInsts) {
SmallVector<const Value *, 8> Worklist{Root};
SmallPtrSet<const Value *, 8> Visited{Root};
SmallPtrSet<Instruction *, 8> SeenInsts;
while (!Worklist.empty()) {
const Value *Cur = Worklist.pop_back_val();
for (const Use &U : Cur->uses()) {
const User *Usr = U.getUser();
if (const auto *CE = dyn_cast<ConstantExpr>(Usr)) {
if (!containsRootValue(CE, Root, AllowSwiftBias))
return false;
if (Visited.insert(CE).second)
Worklist.push_back(CE);
continue;
}
if (isa<Constant>(Usr))
return false;
const auto *Inst = dyn_cast<Instruction>(Usr);
if (!Inst || !Inst->getParent() || Inst->getParent()->isEHPad())
return false;
if (isa<LandingPadInst>(Inst) || Inst->isEHPad())
return false;
if (const auto *CB = dyn_cast<CallBase>(Inst)) {
if (&U == &CB->getCalledOperandUse())
return false;
}
if (const auto *PN = dyn_cast<PHINode>(Inst)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
if (PN->getIncomingValue(i) == Cur &&
!isSafePhiPredBlock(PN->getIncomingBlock(i))) {
return false;
}
}
}
const Function *ParentF = Inst->getFunction();
if (!ParentF || !FnPred(*ParentF))
return false;
Instruction *MutableInst = const_cast<Instruction *>(Inst);
if (SeenInsts.insert(MutableInst).second)
OutInsts.push_back(MutableInst);
}
}
return !OutInsts.empty();
}
Value *materializeValueForRoot(IRBuilder<> &B, Value *Orig,
const GlobalVariable *Root, Value *Replacement) {
if (Orig == Root)
return Replacement;
auto *CE = dyn_cast<ConstantExpr>(Orig);
if (!CE)
return Orig;
switch (CE->getOpcode()) {
case Instruction::BitCast: {
Value *Inner =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return (Inner->getType() == CE->getType())
? Inner
: B.CreateBitCast(Inner, CE->getType());
}
case Instruction::AddrSpaceCast: {
Value *Inner =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return (Inner->getType() == CE->getType())
? Inner
: B.CreateAddrSpaceCast(Inner, CE->getType());
}
case Instruction::GetElementPtr: {
Value *Inner =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return (Inner->getType() == CE->getType())
? Inner
: B.CreateBitCast(Inner, CE->getType());
}
case Instruction::PtrToInt: {
Value *Inner =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return B.CreatePtrToInt(Inner, CE->getType());
}
case Instruction::IntToPtr: {
Value *Inner =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return B.CreateIntToPtr(Inner, CE->getType());
}
case Instruction::Sub: {
Value *LHS =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return B.CreateSub(LHS, CE->getOperand(1));
}
case Instruction::Add: {
if (containsRootValue(CE->getOperand(0), Root, true)) {
Value *LHS =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return B.CreateAdd(LHS, CE->getOperand(1));
}
Value *RHS =
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
return B.CreateAdd(CE->getOperand(0), RHS);
}
case Instruction::Or: {
if (containsRootValue(CE->getOperand(0), Root, true)) {
Value *LHS =
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
return B.CreateOr(LHS, CE->getOperand(1));
}
Value *RHS =
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
return B.CreateOr(CE->getOperand(0), RHS);
}
default:
return Orig;
}
}
void rewriteUsersWithDecryptFn(
GlobalVariable *RootGV, Function *DecFn, bool AllowSwiftBias,
ArrayRef<Instruction *> LeafInsts, StringSet<> &SeenFunctions,
std::vector<std::string> &TouchedFunctions) {
for (Instruction *UI : LeafInsts) {
if (auto *PN = dyn_cast<PHINode>(UI)) {
DenseMap<std::pair<BasicBlock *, Value *>, Value *> EdgeCache;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
Value *InVal = PN->getIncomingValue(i);
if (!containsRootValue(InVal, RootGV, AllowSwiftBias))
continue;
BasicBlock *PredBB = PN->getIncomingBlock(i);
auto CacheKey = std::make_pair(PredBB, InVal);
Value *ReplVal = nullptr;
auto It = EdgeCache.find(CacheKey);
if (It != EdgeCache.end()) {
ReplVal = It->second;
} else {
Instruction *Term = PredBB->getTerminator();
IRBuilder<> EdgeB(Term);
CallInst *DecCall = EdgeB.CreateCall(DecFn, {}, "ig.str");
DecCall->setDebugLoc(Term->getDebugLoc());
ReplVal = AllowSwiftBias
? materializeValueForRoot(EdgeB, InVal, RootGV, DecCall)
: static_cast<Value *>(DecCall);
EdgeCache[CacheKey] = ReplVal;
}
PN->setIncomingValue(i, ReplVal);
}
} else {
IRBuilder<> B(UI);
CallInst *DecCall = B.CreateCall(DecFn, {}, "ig.str");
DecCall->setDebugLoc(UI->getDebugLoc());
for (unsigned i = 0, e = UI->getNumOperands(); i < e; ++i) {
Value *Op = UI->getOperand(i);
if (containsRootValue(Op, RootGV, AllowSwiftBias)) {
Value *ReplVal = AllowSwiftBias
? materializeValueForRoot(B, Op, RootGV, DecCall)
: static_cast<Value *>(DecCall);
UI->setOperand(i, ReplVal);
}
}
}
if (const Function *ParentF = UI->getFunction()) {
if (SeenFunctions.insert(ParentF->getName()).second)
TouchedFunctions.push_back(ParentF->getName().str());
}
}
}
Function *createDecryptFunction(Module &M, uint64_t Id, StringRef FnPrefix,
GlobalVariable *EncGV, GlobalVariable *KeyGV,
GlobalVariable *BufGV, GlobalVariable *StateGV,
GlobalVariable *RetGV, uint64_t Len,
Align BufAlign) {
LLVMContext &Ctx = M.getContext();
Type *PtrTy = PointerType::getUnqual(Ctx);
Type *I32Ty = Type::getInt32Ty(Ctx);
Type *I64Ty = Type::getInt64Ty(Ctx);
Type *I8Ty = Type::getInt8Ty(Ctx);
ArrayType *ArrTy = ArrayType::get(I8Ty, Len);
FunctionType *FnTy = FunctionType::get(PtrTy, false);
std::string FnName = (FnPrefix + Twine(Id)).str();
Function *Fn =
Function::Create(FnTy, GlobalValue::InternalLinkage, FnName, &M);
Fn->addFnAttr(Attribute::NoInline);
Fn->addFnAttr(Attribute::NoBuiltin);
Fn->addFnAttr(Attribute::NoUnwind);
Fn->setDSOLocal(true);
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
BasicBlock *CasBB = BasicBlock::Create(Ctx, "cas", Fn);
BasicBlock *WaitBB = BasicBlock::Create(Ctx, "wait", Fn);
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
BasicBlock *DoneBB = BasicBlock::Create(Ctx, "done", Fn);
BasicBlock *RetBB = BasicBlock::Create(Ctx, "ret", Fn);
// Entry: fast path acquire load == 2
IRBuilder<> B(EntryBB);
LoadInst *FastState = B.CreateLoad(I32Ty, StateGV, false, "st.fast");
FastState->setAlignment(Align(4));
FastState->setAtomic(AtomicOrdering::Acquire);
Value *Ready =
B.CreateICmpEQ(FastState, ConstantInt::get(I32Ty, 2), "is.ready");
B.CreateCondBr(Ready, RetBB, CasBB);
// CAS: try claiming 0 -> 1
B.SetInsertPoint(CasBB);
AtomicCmpXchgInst *CX = B.CreateAtomicCmpXchg(
StateGV, ConstantInt::get(I32Ty, 0), ConstantInt::get(I32Ty, 1),
Align(4), AtomicOrdering::AcquireRelease, AtomicOrdering::Acquire);
Value *Won = B.CreateExtractValue(CX, 1, "won");
B.CreateCondBr(Won, LoopBB, WaitBB);
// Wait: spin with optional AArch64 yield hint until winner releases 2
B.SetInsertPoint(WaitBB);
if (Triple(M.getTargetTriple()).isAArch64()) {
Function *HintFn =
Intrinsic::getOrInsertDeclaration(&M, Intrinsic::aarch64_hint);
B.CreateCall(HintFn, {ConstantInt::get(I32Ty, 1)});
}
LoadInst *WaitState = B.CreateLoad(I32Ty, StateGV, false, "st.wait");
WaitState->setAlignment(Align(4));
WaitState->setAtomic(AtomicOrdering::Acquire);
Value *NowReady =
B.CreateICmpEQ(WaitState, ConstantInt::get(I32Ty, 2), "wait.ready");
B.CreateCondBr(NowReady, RetBB, WaitBB);
// Loop: volatile decrypt bytes from enc ^ key into internal global buffer
B.SetInsertPoint(LoopBB);
PHINode *Idx = B.CreatePHI(I64Ty, 2, "idx");
Idx->addIncoming(ConstantInt::get(I64Ty, 0), CasBB);
Value *Zero64 = ConstantInt::get(I64Ty, 0);
Value *EncPtr = B.CreateInBoundsGEP(ArrTy, EncGV, {Zero64, Idx}, "enc.ptr");
Value *KeyPtr = B.CreateInBoundsGEP(ArrTy, KeyGV, {Zero64, Idx}, "key.ptr");
Value *BufPtr = B.CreateInBoundsGEP(ArrTy, BufGV, {Zero64, Idx}, "buf.ptr");
LoadInst *EncByte = B.CreateLoad(I8Ty, EncPtr, /*isVolatile=*/true, "eb");
LoadInst *KeyByte = B.CreateLoad(I8Ty, KeyPtr, /*isVolatile=*/true, "kb");
Value *PlainByte = B.CreateXor(EncByte, KeyByte, "pb");
StoreInst *St = B.CreateStore(PlainByte, BufPtr, /*isVolatile=*/true);
St->setAlignment(Align(1));
(void)BufAlign;
Value *NextIdx =
B.CreateAdd(Idx, ConstantInt::get(I64Ty, 1), "next", /*HasNUW=*/true);
Idx->addIncoming(NextIdx, LoopBB);
Value *LoopDone =
B.CreateICmpEQ(NextIdx, ConstantInt::get(I64Ty, Len), "loop.done");
B.CreateCondBr(LoopDone, DoneBB, LoopBB);
// Done: release store 2 so waiting and future callers observe decrypted bytes
B.SetInsertPoint(DoneBB);
StoreInst *Publish =
B.CreateStore(ConstantInt::get(I32Ty, 2), StateGV, false);
Publish->setAlignment(Align(4));
Publish->setAtomic(AtomicOrdering::Release);
B.CreateBr(RetBB);
// Ret: return target object base pointer (BufGV or CFConstantString)
B.SetInsertPoint(RetBB);
B.CreateRet(RetGV);
return Fn;
}
bool isStackAllowlistedCallee(StringRef RawName, bool &OutIsStrstr,
bool &OutIsMemcpySrc) {
OutIsStrstr = false;
OutIsMemcpySrc = false;
StringRef Name = RawName;
if (Name.starts_with("\x01_"))
Name = Name.drop_front(2);
else if (Name.starts_with("\x01"))
Name = Name.drop_front(1);
if (Name == "strstr") {
OutIsStrstr = true;
return true;
}
if (Name.starts_with("llvm.memcpy.")) {
OutIsMemcpySrc = true;
return true;
}
static constexpr const char *kAllowed[] = {
"strcmp", "strncmp",
"strcasecmp", "strncasecmp",
"strlen", "memcmp",
"access", "stat",
"lstat", "open",
"fopen", "dlopen",
"dlsym", "getenv",
"sysctlbyname", "IG_dispatch_open",
"IG_dispatch_stat", "IG_dispatch_lstat",
"IG_dispatch_access", "ig_ends_with",
"ig_strncmp", "ig_strcmp",
"ig_strlen",
};
for (const char *Allowed : kAllowed) {
if (Name == Allowed)
return true;
}
return false;
}
bool canUseMultiFnStackDecrypt(const GlobalVariable *GV, uint64_t Len,
const IGPolicyConfig &Policy,
ArrayRef<Instruction *> LeafInsts) {
uint64_t MaxStackLen = Policy.stringEncryptStackMaxLen();
if (MaxStackLen == 0 || Len == 0 || Len > MaxStackLen || LeafInsts.empty())
return false;
for (Instruction *UI : LeafInsts) {
auto *CI = dyn_cast<CallInst>(UI);
if (!CI || CI->isMustTailCall() || CI->isInlineAsm())
return false;
Function *ParentF = CI->getFunction();
if (!ParentF || ParentF->empty() || ParentF->getEntryBlock().isEHPad() ||
!Policy.shouldStackEncryptStringsInFunction(*ParentF)) {
return false;
}
Function *Callee = CI->getCalledFunction();
if (!Callee)
return false;
bool IsStrstr = false;
bool IsMemcpySrc = false;
if (!isStackAllowlistedCallee(Callee->getName(), IsStrstr, IsMemcpySrc))
return false;
bool FoundOp = false;
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
Value *Op = CI->getOperand(i);
if (unwrapBaseValue(Op) == GV) {
if (!CI->isArgOperand(&CI->getOperandUse(i)) ||
!Op->getType()->isPointerTy() ||
Op->stripPointerCasts() != GV) {
return false;
}
if ((IsStrstr || IsMemcpySrc) && i != 1)
return false;
FoundOp = true;
}
}
if (!FoundOp)
return false;
}
return true;
}
Function *getOrCreateStackDecryptFn(Module &M) {
if (Function *Existing = M.getFunction("__ig_str_dec_stack"))
return Existing;
LLVMContext &Ctx = M.getContext();
Type *PtrTy = PointerType::getUnqual(Ctx);
Type *I64Ty = Type::getInt64Ty(Ctx);
Type *I8Ty = Type::getInt8Ty(Ctx);
FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Ctx),
{PtrTy, PtrTy, PtrTy, I64Ty}, false);
Function *Fn = Function::Create(FnTy, GlobalValue::InternalLinkage,
"__ig_str_dec_stack", &M);
Fn->addFnAttr(Attribute::NoInline);
Fn->addFnAttr(Attribute::NoUnwind);
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", Fn);
Value *Dst = Fn->getArg(0);
Value *Enc = Fn->getArg(1);
Value *Key = Fn->getArg(2);
Value *LenArg = Fn->getArg(3);
IRBuilder<> EB(EntryBB);
Value *HasBytes = EB.CreateICmpUGT(LenArg, ConstantInt::get(I64Ty, 0));
EB.CreateCondBr(HasBytes, LoopBB, ExitBB);
IRBuilder<> LB(LoopBB);
PHINode *Idx = LB.CreatePHI(I64Ty, 2, "idx");
Idx->addIncoming(ConstantInt::get(I64Ty, 0), EntryBB);
Value *EncPtr = LB.CreateInBoundsGEP(I8Ty, Enc, Idx);
Value *KeyPtr = LB.CreateInBoundsGEP(I8Ty, Key, Idx);
Value *DstPtr = LB.CreateInBoundsGEP(I8Ty, Dst, Idx);
Value *EncByte = LB.CreateAlignedLoad(I8Ty, EncPtr, Align(1));
Value *KeyByte = LB.CreateAlignedLoad(I8Ty, KeyPtr, Align(1));
Value *DecByte = LB.CreateXor(EncByte, KeyByte);
LB.CreateAlignedStore(DecByte, DstPtr, Align(1));
Value *NextIdx = LB.CreateAdd(Idx, ConstantInt::get(I64Ty, 1));
Idx->addIncoming(NextIdx, LoopBB);
Value *Cont = LB.CreateICmpULT(NextIdx, LenArg);
LB.CreateCondBr(Cont, LoopBB, ExitBB);
IRBuilder<> XB(ExitBB);
XB.CreateRetVoid();
return Fn;
}
void emitEncryptedKeyPair(Module &M, uint64_t CurId, StringRef RawBytes,
StringRef Seed, StringRef ItemId, Align BufAlign,
bool EmitGlobalBuf, GlobalVariable *&OutEncGV,
GlobalVariable *&OutKeyGV,
GlobalVariable *&OutBufGV,
GlobalVariable *&OutStateGV) {
LLVMContext &Ctx = M.getContext();
uint64_t Len = RawBytes.size();
IGDeterministicRNG RNG(Seed, M.getModuleIdentifier(), ItemId);
SmallVector<uint8_t, 64> KeyBytes(Len);
SmallVector<uint8_t, 64> EncBytes(Len);
for (size_t i = 0; i < Len; ++i) {
uint8_t K = RNG.nextNonZeroByte();
KeyBytes[i] = K;
EncBytes[i] = static_cast<uint8_t>(RawBytes[i]) ^ K;
}
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
OutEncGV = new GlobalVariable(
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
ConstantDataArray::get(Ctx, EncBytes), ".ig.enc." + Twine(CurId));
OutEncGV->setAlignment(Align(1));
OutEncGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
OutKeyGV = new GlobalVariable(
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
ConstantDataArray::get(Ctx, KeyBytes), ".ig.key." + Twine(CurId));
OutKeyGV->setAlignment(Align(1));
OutKeyGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
OutBufGV = nullptr;
OutStateGV = nullptr;
if (EmitGlobalBuf) {
OutBufGV = new GlobalVariable(
M, ArrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
ConstantAggregateZero::get(ArrTy), ".ig.buf." + Twine(CurId));
OutBufGV->setAlignment(BufAlign);
Type *I32Ty = Type::getInt32Ty(Ctx);
OutStateGV = new GlobalVariable(
M, I32Ty, /*isConstant=*/false, GlobalValue::InternalLinkage,
ConstantInt::get(I32Ty, 0), ".ig.state." + Twine(CurId));
OutStateGV->setAlignment(Align(4));
}
}
void applyStackDecryptAndWipe(Module &M, GlobalVariable *GV, uint64_t CurId,
GlobalVariable *EncGV, GlobalVariable *KeyGV,
uint64_t Len, ArrayRef<Instruction *> LeafInsts,
StringSet<> &SeenFunctions,
std::vector<std::string> &TouchedFunctions) {
LLVMContext &Ctx = M.getContext();
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
Function *StackDecFn = getOrCreateStackDecryptFn(M);
Type *I64Ty = Type::getInt64Ty(Ctx);
Type *I8Ty = Type::getInt8Ty(Ctx);
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
Constant *Zero8 = ConstantInt::get(I8Ty, 0);
Constant *LenConst = ConstantInt::get(I64Ty, Len);
DenseMap<Function *, AllocaInst *> FuncBufs;
for (Instruction *UI : LeafInsts) {
auto *CI = cast<CallInst>(UI);
Function *ParentF = CI->getFunction();
AllocaInst *&StackBuf = FuncBufs[ParentF];
if (!StackBuf) {
BasicBlock &TargetEntry = ParentF->getEntryBlock();
BasicBlock::iterator AllocaInsPt = TargetEntry.begin();
while (AllocaInsPt != TargetEntry.end() && isa<AllocaInst>(AllocaInsPt))
++AllocaInsPt;
IRBuilder<> AllocaB(&TargetEntry, AllocaInsPt);
StackBuf = AllocaB.CreateAlloca(ArrTy, nullptr, "ig.sbuf." + Twine(CurId));
StackBuf->setAlignment(Align(1));
if (SeenFunctions.insert(ParentF->getName()).second)
TouchedFunctions.push_back(ParentF->getName().str());
}
DebugLoc DbgLoc = CI->getDebugLoc();
IRBuilder<> PreB(CI);
CallInst *DecCall =
PreB.CreateCall(StackDecFn, {StackBuf, EncGV, KeyGV, LenConst});
DecCall->setDebugLoc(DbgLoc);
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
if (unwrapBaseValue(CI->getOperand(i)) == GV)
CI->setOperand(i, StackBuf);
}
if (Len <= 64) {
IRBuilder<> AfterB(CI->getNextNode());
for (uint64_t k = 0; k < Len; ++k) {
Value *BytePtr = AfterB.CreateInBoundsGEP(
ArrTy, StackBuf, {Zero64, ConstantInt::get(I64Ty, k)});
StoreInst *WipeStore = AfterB.CreateAlignedStore(
Zero8, BytePtr, Align(1), /*isVolatile=*/true);
WipeStore->setDebugLoc(DbgLoc);
}
} else {
BasicBlock *CurBB = CI->getParent();
BasicBlock *ContBB = CurBB->splitBasicBlock(
CI->getNextNode(), "ig.wipe.cont." + Twine(CurId));
BasicBlock *WipeBB = BasicBlock::Create(
Ctx, "ig.wipe.loop." + Twine(CurId), ParentF, ContBB);
CurBB->getTerminator()->eraseFromParent();
IRBuilder<> BrB(CurBB);
BrB.SetCurrentDebugLocation(DbgLoc);
BrB.CreateBr(WipeBB);
IRBuilder<> WB(WipeBB);
WB.SetCurrentDebugLocation(DbgLoc);
PHINode *WIdx = WB.CreatePHI(I64Ty, 2, "widx");
WIdx->addIncoming(Zero64, CurBB);
Value *BytePtr = WB.CreateInBoundsGEP(ArrTy, StackBuf, {Zero64, WIdx});
WB.CreateAlignedStore(Zero8, BytePtr, Align(1), /*isVolatile=*/true);
Value *NextWIdx = WB.CreateAdd(WIdx, ConstantInt::get(I64Ty, 1));
WIdx->addIncoming(NextWIdx, WipeBB);
Value *More = WB.CreateICmpULT(NextWIdx, LenConst);
WB.CreateCondBr(More, WipeBB, ContBB);
}
}
}
bool hasAnyNonZeroBytes(StringRef Raw) {
for (unsigned char C : Raw) {
if (C != 0)
return true;
}
return false;
}
bool tryEncryptCFConstantString(
Module &M, GlobalVariable *CFGV, const IGPolicyConfig &Policy,
const SmallPtrSet<const GlobalValue *, 16> &PreservedUsed,
const SmallPtrSet<const GlobalVariable *, 16> &AliasedGlobals,
uint64_t &NextId, StringSet<> &SeenFunctions,
std::vector<std::string> &TouchedFunctions, IGAuditRecord &Audit) {
if (!CFGV->hasInitializer() || !CFGV->hasLocalLinkage() ||
CFGV->isThreadLocal() || CFGV->getSection() != "__DATA,__cfstring") {
return false;
}
if (PreservedUsed.contains(CFGV) || AliasedGlobals.contains(CFGV))
return false;
const auto *CS = dyn_cast<ConstantStruct>(CFGV->getInitializer());
if (!CS || CS->getNumOperands() != 4)
return false;
const auto *ClassGV =
dyn_cast<GlobalValue>(CS->getOperand(0)->stripPointerCasts());
if (!ClassGV || ClassGV->getName() != "__CFConstantStringClassReference")
return false;
const auto *FlagsCI = dyn_cast<ConstantInt>(CS->getOperand(1));
const auto *LenCI = dyn_cast<ConstantInt>(CS->getOperand(3));
if (!FlagsCI || !LenCI)
return false;
uint64_t Flags = FlagsCI->getZExtValue();
uint64_t CharCount = LenCI->getZExtValue();
if ((Flags != 1992 && Flags != 2000) || CharCount < 4)
return false;
auto *StrGV = dyn_cast<GlobalVariable>(CS->getOperand(2)->stripPointerCasts());
if (!StrGV || !StrGV->hasInitializer() || !StrGV->isConstant() ||
!StrGV->hasLocalLinkage() || PreservedUsed.contains(StrGV) ||
AliasedGlobals.contains(StrGV) || !StrGV->hasOneUse()) {
return false;
}
const auto *CDS = dyn_cast<ConstantDataSequential>(StrGV->getInitializer());
if (!CDS || CDS->getNumElements() != CharCount + 1)
return false;
bool IsUTF16 = (Flags == 2000);
if (IsUTF16 && !CDS->getElementType()->isIntegerTy(16))
return false;
if (!IsUTF16 && !CDS->getElementType()->isIntegerTy(8))
return false;
if (CDS->getElementAsInteger(CharCount) != 0)
return false;
StringRef Raw = CDS->getRawDataValues();
if (Raw.empty() || !hasAnyNonZeroBytes(Raw))
return false;
SmallVector<Instruction *, 8> LeafInsts;
auto FnPred = [&](const Function &F) {
return Policy.shouldEncryptObjCStringsInFunction(F) ||
Policy.shouldEncryptSwiftStringsInFunction(F);
};
if (!collectControlledUsersEx(CFGV, /*AllowSwiftBias=*/false, FnPred,
LeafInsts)) {
return false;
}
uint64_t CurId = NextId++;
Align BufAlign(IsUTF16 ? 2 : 1);
GlobalVariable *EncGV = nullptr;
GlobalVariable *KeyGV = nullptr;
GlobalVariable *BufGV = nullptr;
GlobalVariable *StateGV = nullptr;
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), StrGV->getName(), BufAlign,
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
Constant *NewCFInit = ConstantStruct::get(
CS->getType(),
{CS->getOperand(0), CS->getOperand(1), BufGV, CS->getOperand(3)});
CFGV->setInitializer(NewCFInit);
Function *DecFn =
createDecryptFunction(M, CurId, "__ig_dec_cf_", EncGV, KeyGV, BufGV,
StateGV, CFGV, Raw.size(), BufAlign);
rewriteUsersWithDecryptFn(CFGV, DecFn, /*AllowSwiftBias=*/false, LeafInsts,
SeenFunctions, TouchedFunctions);
StrGV->removeDeadConstantUsers();
if (StrGV->use_empty())
StrGV->eraseFromParent();
Audit.StringsEncryptedCount++;
Audit.ObjCStringsEncryptedCount++;
return true;
}
} // namespace
bool runSourcePathScrubbing(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
return false;
const auto &Substrings = Policy.scrubPathSubstrings();
std::string SwiftModPrefix;
if (!Policy.swiftModuleName().empty())
SwiftModPrefix = Policy.swiftModuleName().str() + "/";
if (Substrings.empty() && SwiftModPrefix.empty())
return false;
bool Changed = false;
LLVMContext &Ctx = M.getContext();
for (GlobalVariable &GV : M.globals()) {
if (!GV.hasInitializer() || !GV.isConstant() || !GV.hasLocalLinkage())
continue;
if (GV.hasSection() || GV.isThreadLocal())
continue;
StringRef Name = GV.getName();
if (Name == "llvm.global.annotations" || Name.starts_with(".ig.") ||
Name.starts_with("__ig_"))
continue;
const auto *CDS = dyn_cast<ConstantDataSequential>(GV.getInitializer());
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
continue;
StringRef S = CDS->getAsCString();
if (S.empty())
continue;
bool IsSourceExt = S.ends_with(".swift") || S.ends_with(".m") ||
S.ends_with(".mm") || S.ends_with(".c") ||
S.ends_with(".h");
bool Matched = false;
for (const std::string &Sub : Substrings) {
if (!Sub.empty() && S.contains(Sub)) {
Matched = true;
break;
}
}
if (!Matched && IsSourceExt &&
(S.starts_with("./readoor/") || S.starts_with("readoor/") ||
S.contains("/readoor/"))) {
Matched = true;
}
if (!Matched && !SwiftModPrefix.empty() &&
S.starts_with(SwiftModPrefix) && S.ends_with(".swift")) {
Matched = true;
}
if (!Matched)
continue;
SHA256 Hasher;
Hasher.update(Policy.seed());
Hasher.update("|");
Hasher.update(S);
auto Digest = Hasher.final();
std::string Tag8 = toHex(ArrayRef<uint8_t>(Digest.data(), 4), /*LowerCase=*/true);
std::string Repl = "ig_p_" + Tag8;
if (Repl.size() < S.size())
Repl.append(S.size() - Repl.size(), ' ');
else if (Repl.size() > S.size())
Repl.resize(S.size());
Constant *NewInit = ConstantDataArray::getString(Ctx, Repl, /*AddNull=*/true);
if (NewInit->getType() != GV.getValueType())
continue;
GV.setInitializer(NewInit);
Audit.PathsScrubbedCount++;
Changed = true;
}
return Changed;
}
bool runStringEncryption(Module &M, const IGPolicyConfig &Policy,
IGAuditRecord &Audit) {
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
return false;
SmallPtrSet<const GlobalValue *, 16> PreservedUsed;
collectCompilerUsed(M, "llvm.used", PreservedUsed);
collectCompilerUsed(M, "llvm.compiler.used", PreservedUsed);
SmallPtrSet<const GlobalVariable *, 16> AliasedGlobals;
for (const GlobalAlias &GA : M.aliases()) {
if (const auto *AliaseeGV =
dyn_cast<GlobalVariable>(GA.getAliasee()->stripPointerCasts())) {
AliasedGlobals.insert(AliaseeGV);
}
}
SmallVector<GlobalVariable *, 32> Candidates;
for (GlobalVariable &GV : M.globals()) {
Candidates.push_back(&GV);
}
bool Changed = false;
uint64_t NextId = 0;
StringSet<> SeenFunctions;
std::vector<std::string> TouchedFunctions;
LLVMContext &Ctx = M.getContext();
const auto &ReplaceRules = Policy.stringReplaceRules();
if (!ReplaceRules.empty()) {
for (GlobalVariable *GV : Candidates) {
if (!GV->hasInitializer() || !GV->isConstant() ||
!GV->hasLocalLinkage() || GV->hasSection() || GV->isThreadLocal() ||
GV->getName().starts_with(".ig.") ||
GV->getName().starts_with("__ig_") ||
PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
continue;
}
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
continue;
StringRef CStr = CDS->getAsCString();
for (const StringReplaceRule &Rule : ReplaceRules) {
if (Rule.Exact == CStr) {
uint64_t TotalLen = CDS->getNumElements();
if (TotalLen < 2)
break;
SmallVector<uint8_t, 64> Buf(TotalLen, 0);
size_t CopyLen = std::min<size_t>(Rule.Replace.size(), TotalLen - 1);
if (CopyLen > 0)
std::memcpy(Buf.data(), Rule.Replace.data(), CopyLen);
GV->setInitializer(ConstantDataArray::get(Ctx, Buf));
Audit.StringsReplacedCount++;
Changed = true;
break;
}
}
}
}
for (GlobalVariable *GV : Candidates) {
if (tryEncryptCFConstantString(M, GV, Policy, PreservedUsed, AliasedGlobals,
NextId, SeenFunctions, TouchedFunctions,
Audit)) {
Changed = true;
continue;
}
if (!GV->hasInitializer() || !GV->isConstant())
continue;
if (!GV->hasLocalLinkage())
continue;
if (GV->hasSection() || GV->isThreadLocal())
continue;
if (GV->getName().starts_with(".ig.") ||
GV->getName().starts_with("__ig_"))
continue;
if (PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
Audit.StringsSkippedCount++;
continue;
}
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
if (!CDS || (!CDS->isString() && !CDS->isCString()) ||
!CDS->getElementType()->isIntegerTy(8)) {
continue;
}
StringRef Raw = CDS->getRawDataValues();
if (Raw.size() < 5) // Require >= 4 non-trivial bytes (+ optional NUL)
continue;
if (!hasAnyNonZeroBytes(Raw))
continue;
SmallVector<Instruction *, 8> LeafInsts;
bool MatchedC = collectControlledUsersEx(
GV, /*AllowSwiftBias=*/false,
[&](const Function &F) {
return Policy.shouldEncryptStringsInFunction(F);
},
LeafInsts);
if (MatchedC) {
uint64_t CurId = NextId++;
bool UseStack = canUseMultiFnStackDecrypt(GV, Raw.size(), Policy, LeafInsts);
GlobalVariable *EncGV = nullptr;
GlobalVariable *KeyGV = nullptr;
GlobalVariable *BufGV = nullptr;
GlobalVariable *StateGV = nullptr;
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(1),
/*EmitGlobalBuf=*/!UseStack, EncGV, KeyGV, BufGV,
StateGV);
if (UseStack) {
applyStackDecryptAndWipe(M, GV, CurId, EncGV, KeyGV, Raw.size(),
LeafInsts, SeenFunctions, TouchedFunctions);
Audit.StringsStackEncryptedCount++;
} else {
Function *DecFn =
createDecryptFunction(M, CurId, "__ig_dec_str_", EncGV, KeyGV,
BufGV, StateGV, BufGV, Raw.size(), Align(1));
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/false,
LeafInsts, SeenFunctions, TouchedFunctions);
}
GV->removeDeadConstantUsers();
if (GV->use_empty())
GV->eraseFromParent();
Audit.StringsEncryptedCount++;
Changed = true;
continue;
}
LeafInsts.clear();
bool MatchedSwift =
!GV->use_empty() && Raw.size() >= 16 &&
collectControlledUsersEx(
GV, /*AllowSwiftBias=*/true,
[&](const Function &F) {
return Policy.shouldEncryptSwiftStringsInFunction(F);
},
LeafInsts);
if (MatchedSwift) {
uint64_t CurId = NextId++;
GlobalVariable *EncGV = nullptr;
GlobalVariable *KeyGV = nullptr;
GlobalVariable *BufGV = nullptr;
GlobalVariable *StateGV = nullptr;
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(8),
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
Function *DecFn =
createDecryptFunction(M, CurId, "__ig_dec_sw_", EncGV, KeyGV, BufGV,
StateGV, BufGV, Raw.size(), Align(8));
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/true, LeafInsts,
SeenFunctions, TouchedFunctions);
GV->removeDeadConstantUsers();
if (GV->use_empty())
GV->eraseFromParent();
Audit.StringsEncryptedCount++;
Audit.SwiftStringsEncryptedCount++;
Changed = true;
continue;
}
if (!GV->use_empty())
Audit.StringsSkippedCount++;
}
for (const std::string &FnName : TouchedFunctions)
Audit.StringsEncryptedFunctions.push_back(FnName);
return Changed;
}
} // namespace igobf