forked from 61bcdefg/Hikari-LLVM15-Core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cpp
325 lines (299 loc) · 10.2 KB
/
Utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// For open-source license, please refer to
// [License](https://github.com/HikariObfuscator/Hikari/wiki/License).
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Obfuscation/Utils.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NoFolder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <set>
#include <sstream>
using namespace llvm;
namespace llvm {
// Shamefully borrowed from ../Scalar/RegToMem.cpp :(
bool valueEscapes(Instruction *Inst) {
BasicBlock *BB = Inst->getParent();
for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end(); UI != E;
++UI) {
Instruction *I = cast<Instruction>(*UI);
if (I->getParent() != BB || isa<PHINode>(I)) {
return true;
}
}
return false;
}
void fixStack(Function *f) {
// Try to remove phi node and demote reg to stack
SmallVector<PHINode *, 8> tmpPhi;
SmallVector<Instruction *, 32> tmpReg;
BasicBlock *bbEntry = &*f->begin();
// Find first non-alloca instruction and create insertion point. This is
// safe if block is well-formed: it always have terminator, otherwise
// we'll get and assertion.
BasicBlock::iterator I = bbEntry->begin();
while (isa<AllocaInst>(I))
++I;
Instruction *AllocaInsertionPoint = &*I;
do {
tmpPhi.clear();
tmpReg.clear();
for (BasicBlock &i : *f) {
for (Instruction &j : i) {
if (isa<PHINode>(&j)) {
PHINode *phi = cast<PHINode>(&j);
tmpPhi.emplace_back(phi);
continue;
}
if (!(isa<AllocaInst>(&j) && j.getParent() == bbEntry) &&
(valueEscapes(&j) || j.isUsedOutsideOfBlock(&i))) {
tmpReg.emplace_back(&j);
continue;
}
}
}
for (Instruction *I : tmpReg)
DemoteRegToStack(*I, false, AllocaInsertionPoint);
for (PHINode *P : tmpPhi)
DemotePHIToStack(P, AllocaInsertionPoint);
} while (tmpReg.size() != 0 || tmpPhi.size() != 0);
}
// Unlike O-LLVM which uses __attribute__ that is not supported by the ObjC
// CFE. We use a dummy call here and remove the call later Very dumb and
// definitely slower than the function attribute method Merely a hack
bool readFlag(Function *f, std::string attribute) {
for (Instruction &I : instructions(f)) {
Instruction *Inst = &I;
if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
if (CI->getCalledFunction() != nullptr &&
CI->getCalledFunction()->getName().contains("hikari_" + attribute)) {
CI->eraseFromParent();
return true;
}
}
}
return false;
}
bool toObfuscate(bool flag, Function *f, std::string attribute) {
// Check if declaration and external linkage
if (f->isDeclaration() || f->hasAvailableExternallyLinkage()) {
return false;
}
std::string attr = attribute;
std::string attrNo = "no" + attr;
if (readAnnotationMetadata(f, attrNo) || readFlag(f, attrNo)) {
return false;
}
if (readAnnotationMetadata(f, attr) || readFlag(f, attr)) {
return true;
}
return flag;
}
bool toObfuscateBoolOption(Function *f, std::string option, bool *val) {
std::string opt = option;
std::string optDisable = "no" + option;
if (readAnnotationMetadata(f, optDisable) || readFlag(f, optDisable)) {
*val = false;
return true;
}
if (readAnnotationMetadata(f, opt) || readFlag(f, opt)) {
*val = true;
return true;
}
return false;
}
static const char obfkindid[] = "MD_obf";
bool readAnnotationMetadataUint32OptVal(Function *f, std::string opt,
uint32_t *val) {
MDNode *Existing = f->getMetadata(obfkindid);
if (Existing) {
MDTuple *Tuple = cast<MDTuple>(Existing);
for (auto &N : Tuple->operands()) {
StringRef mdstr = cast<MDString>(N.get())->getString();
std::string estr = opt + "=";
if (mdstr.startswith(estr)) {
*val = atoi(mdstr.substr(strlen(estr.c_str())).str().c_str());
return true;
}
}
}
return false;
}
bool readFlagUint32OptVal(Function *f, std::string opt, uint32_t *val) {
for (Instruction &I : instructions(f)) {
Instruction *Inst = &I;
if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
if (CI->getCalledFunction() != nullptr &&
CI->getCalledFunction()->getName().contains("hikari_" + opt)) {
if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getArgOperand(0))) {
*val = (uint32_t)C->getValue().getZExtValue();
CI->eraseFromParent();
return true;
}
}
}
}
return false;
}
bool toObfuscateUint32Option(Function *f, std::string option, uint32_t *val) {
if (readAnnotationMetadataUint32OptVal(f, option, val) ||
readFlagUint32OptVal(f, option, val))
return true;
return false;
}
bool hasApplePtrauth(Module *M) {
for (GlobalVariable &GV : M->globals())
if (GV.getSection() == "llvm.ptrauth")
return true;
return false;
}
void FixBasicBlockConstantExpr(BasicBlock *BB) {
// Replace ConstantExpr with equal instructions
// Otherwise replacing on Constant will crash the compiler
// Things to note:
// - Phis must be placed at BB start so CEs must be placed prior to current BB
assert(!BB->empty() && "BasicBlock is empty!");
assert(BB->getParent() && "BasicBlock must be in a Function!");
Instruction *FunctionInsertPt =
&*(BB->getParent()->getEntryBlock().getFirstInsertionPt());
for (Instruction &I : *BB) {
if (isa<LandingPadInst>(I) || isa<FuncletPadInst>(I) ||
isa<IntrinsicInst>(I))
continue;
for (unsigned int i = 0; i < I.getNumOperands(); i++)
if (ConstantExpr *C = dyn_cast<ConstantExpr>(I.getOperand(i))) {
IRBuilder<NoFolder> IRB(&I);
if (isa<PHINode>(I))
IRB.SetInsertPoint(FunctionInsertPt);
Instruction *Inst = IRB.Insert(C->getAsInstruction());
I.setOperand(i, Inst);
}
}
}
void FixFunctionConstantExpr(Function *Func) {
// Replace ConstantExpr with equal instructions
// Otherwise replacing on Constant will crash the compiler
for (BasicBlock &BB : *Func)
FixBasicBlockConstantExpr(&BB);
}
void turnOffOptimization(Function *f) {
f->removeFnAttr(Attribute::AttrKind::MinSize);
f->removeFnAttr(Attribute::AttrKind::OptimizeForSize);
if (!f->hasFnAttribute(Attribute::AttrKind::OptimizeNone) &&
!f->hasFnAttribute(Attribute::AttrKind::AlwaysInline)) {
f->addFnAttr(Attribute::AttrKind::OptimizeNone);
f->addFnAttr(Attribute::AttrKind::NoInline);
}
}
static inline std::vector<std::string> splitString(std::string str) {
std::stringstream ss(str);
std::string word;
std::vector<std::string> words;
while (ss >> word)
words.emplace_back(word);
return words;
}
void annotation2Metadata(Module &M) {
GlobalVariable *Annotations = M.getGlobalVariable("llvm.global.annotations");
if (!Annotations)
return;
auto *C = dyn_cast<ConstantArray>(Annotations->getInitializer());
if (!C)
return;
for (unsigned int i = 0; i < C->getNumOperands(); i++)
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C->getOperand(i))) {
GlobalValue *StrC =
dyn_cast<GlobalValue>(CS->getOperand(1)->stripPointerCasts());
if (!StrC)
continue;
ConstantDataSequential *StrData =
dyn_cast<ConstantDataSequential>(StrC->getOperand(0));
if (!StrData)
continue;
Function *Fn = dyn_cast<Function>(CS->getOperand(0)->stripPointerCasts());
if (!Fn)
continue;
// Add annotation to the function.
std::vector<std::string> strs =
splitString(StrData->getAsCString().str());
for (std::string str : strs)
writeAnnotationMetadata(Fn, str);
}
}
bool readAnnotationMetadata(Function *f, std::string annotation) {
MDNode *Existing = f->getMetadata(obfkindid);
if (Existing) {
MDTuple *Tuple = cast<MDTuple>(Existing);
for (auto &N : Tuple->operands())
if (cast<MDString>(N.get())->getString() == annotation)
return true;
}
return false;
}
void writeAnnotationMetadata(Function *f, std::string annotation) {
LLVMContext &Context = f->getContext();
MDBuilder MDB(Context);
MDNode *Existing = f->getMetadata(obfkindid);
SmallVector<Metadata *, 4> Names;
bool AppendName = true;
if (Existing) {
MDTuple *Tuple = cast<MDTuple>(Existing);
for (auto &N : Tuple->operands()) {
if (cast<MDString>(N.get())->getString() == annotation)
AppendName = false;
Names.emplace_back(N.get());
}
}
if (AppendName)
Names.emplace_back(MDB.createString(annotation));
MDNode *MD = MDTuple::get(Context, Names);
f->setMetadata(obfkindid, MD);
}
bool AreUsersInOneFunction(GlobalVariable *GV) {
SmallPtrSet<Function *, 6> userFunctions;
for (User *U : GV->users()) {
if (Instruction *I = dyn_cast<Instruction>(U)) {
userFunctions.insert(I->getFunction());
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
for (User *U2 : CE->users()) {
if (Instruction *I = dyn_cast<Instruction>(U2)) {
userFunctions.insert(I->getFunction());
}
}
} else {
return false;
}
}
return userFunctions.size() <= 1;
}
#if 0
std::map<GlobalValue *, StringRef> BuildAnnotateMap(Module &M) {
std::map<GlobalValue *, StringRef> VAMap;
GlobalVariable *glob = M.getGlobalVariable("llvm.global.annotations");
if (glob != nullptr && glob->hasInitializer()) {
ConstantArray *CDA = cast<ConstantArray>(glob->getInitializer());
for (Value *op : CDA->operands()) {
ConstantStruct *anStruct = cast<ConstantStruct>(op);
/*
Structure: [Value,Annotation,SourceFilePath,LineNumber]
Usually wrapped inside GEP/BitCast
We only care about Value and Annotation Here
*/
GlobalValue *Value =
cast<GlobalValue>(anStruct->getOperand(0)->getOperand(0));
GlobalVariable *Annotation =
cast<GlobalVariable>(anStruct->getOperand(1)->getOperand(0));
if (Annotation->hasInitializer()) {
VAMap[Value] =
cast<ConstantDataSequential>(Annotation->getInitializer())
->getAsCString();
}
}
}
return VAMap;
}
#endif
} // namespace llvm