-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathCSiMBA.cpp
More file actions
445 lines (366 loc) · 14.3 KB
/
Copy pathCSiMBA.cpp
File metadata and controls
445 lines (366 loc) · 14.3 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#include "CSiMBA.h"
#include <chrono>
#include <filesystem>
#include <fstream>
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/InitLLVM.h"
#include "CSiMBA.h"
#include "LLVMParser.h"
#include "ShuttingYard.h"
#include "Simplifier.h"
#include "SimplifierRouter.h"
using namespace std;
using namespace llvm;
using namespace std::chrono;
/*
Options
*/
extern cl::OptionCategory SiMBAOpt;
cl::opt<std::string> StrMBA("mba", cl::Optional,
cl::desc("MBA that will be verified/simplified"),
cl::value_desc("mba"), cl::init(""),
cl::cat(SiMBAOpt));
cl::opt<std::string> StrMBADB(
"mbadb", cl::Optional,
cl::desc("MBA database that will be verified/simplified"),
cl::value_desc("mbadb"), cl::init(""), cl::cat(SiMBAOpt));
cl::opt<std::string> StrIR("ir", cl::Optional,
cl::desc("LLVM Module that contains MBA functions "
"that will be verified/simplified"),
cl::value_desc("ir"), cl::init(""),
cl::cat(SiMBAOpt));
cl::opt<std::string> ConvertToLLVM(
"convert-to-llvm", cl::Optional,
cl::desc("Converts the MBA database to LLVM"),
cl::value_desc("Database output name"), cl::init(""), cl::cat(SiMBAOpt));
cl::opt<std::string> Output("out", cl::Optional,
cl::desc("Stores the output into this file"),
cl::value_desc("out"), cl::init(""),
cl::cat(SiMBAOpt));
cl::opt<int> StopN("stop", cl::Optional,
cl::desc("Stop after N MBAs are solved (Default 0)"),
cl::value_desc("stop"), cl::init(0), cl::cat(SiMBAOpt));
cl::opt<int> BitCount("bitcount", cl::Optional,
cl::desc("Bitcount of the variables (Default 64)"),
cl::value_desc("BitCount"), cl::init(64),
cl::cat(SiMBAOpt));
cl::opt<bool> DetectAndSimplify(
"detect-simplify", cl::Optional,
cl::desc(
"Search for MBAs in LLVM Module and try to simplify (Default false)"),
cl::value_desc("detect-simplify"), cl::init(false), cl::cat(SiMBAOpt));
cl::opt<bool> UseFastCheck(
"fastcheck", cl::Optional,
cl::desc("Verify MBA with random values (Default true)"),
cl::value_desc("fastcheck"), cl::init(true), cl::cat(SiMBAOpt));
cl::opt<bool> IgnoreExpected(
"ignore-expected", cl::Optional,
cl::desc("Ignores the expected string (Default false)"),
cl::value_desc("ignore-expected"), cl::init(false), cl::cat(SiMBAOpt));
cl::opt<bool> CheckLinear(
"checklinear", cl::Optional,
cl::desc("Check if MBA is a linear expresssion (Default true)"),
cl::value_desc("checklinear"), cl::init(true), cl::cat(SiMBAOpt));
cl::opt<bool> SimplifyExpected(
"simplify-expected", cl::Optional,
cl::desc("Simplify the expected value to match it (Default false)"),
cl::value_desc("simplify-expected"), cl::init(false), cl::cat(SiMBAOpt));
cl::opt<bool> RunParallel(
"parallel", cl::Optional,
cl::desc("Evaluate/Check MBA expressions in parallel, give a "
"nice boost on MBA with > 3 vars (Default true)"),
cl::value_desc("parallel"), cl::init(true), cl::cat(SiMBAOpt));
cl::opt<bool> ProveZ3(
"prove", cl::Optional,
cl::desc("Prove with Z3 that the MBA is correct (Default false)"),
cl::value_desc("prove"), cl::init(false), cl::cat(SiMBAOpt));
cl::opt<bool> RunOptimizer(
"optimize", cl::Optional,
cl::desc("Optimize LLVM IR before simplification (Default true)"),
cl::value_desc("optimize"), cl::init(true), cl::cat(SiMBAOpt));
cl::opt<bool> Debug("simba-debug", cl::Optional,
cl::desc("Print debug information (Default false)"),
cl::value_desc("simba-debug"), cl::init(false),
cl::cat(SiMBAOpt));
/**
* @brief Simplify a single MBA
*/
void SimplifySingleMBA();
/**
* @brief Simplify a MBA database
*/
void SimplifyMBADatabase();
/**
* @brief Simplify a LLVM module
*/
void SimplifyLLVMModule();
/**
* @brief Simplify a LLVM module with MBA functions
*/
void SimplifyLLVMDataBase();
/**
* @brief Run Simplifier
*
* @param MBA The MBA to simplify
* @param SimpMBA The simplified MBA
* @param ExpMBA The expected MBA
* @param Counter The current counter
* @param Valid The valid counter
*/
void RunSimplifier(std::string &MBA, std::string &SimpMBA, std::string &ExpMBA,
int &Counter, int &Valid);
int main(int argc, char **argv) {
InitLLVM X(argc, argv);
llvm::cl::HideUnrelatedOptions(SiMBAOpt);
llvm::cl::ParseCommandLineOptions(argc, argv);
// Print a SiMBA logo
printf(" _____ __ ______ ___ __ __ \n");
printf(" / __(_) |/ / _ )/ _ |__/ /___/ /_\n");
printf(" _\\ \\/ / /|_/ / _ / __ /_ __/_ __/\n");
printf("/___/_/_/ /_/____/_/ |_|/_/ /_/%d.%d\n", VERSION_MAJOR,
VERSION_MINOR);
printf("°°SiMBA ported to C/C++/LLVM ~pgarba~\n\n");
if (StrMBA == "" && StrMBADB == "" && StrIR == "") {
llvm::cl::PrintHelpMessage();
return 0;
}
if (StrIR != "" && !DetectAndSimplify) {
SimplifyLLVMDataBase();
} else if (StrIR != "" && DetectAndSimplify) {
SimplifyLLVMModule();
} else if (StrMBADB != "") {
SimplifyMBADatabase();
} else {
SimplifySingleMBA();
}
return 0;
}
void SimplifySingleMBA() {
std::string SimpMBA = "";
auto start = high_resolution_clock::now();
// Phase 9: route to the selected simplifier (--simplifier, default auto).
// The native route keeps the original code path below untouched.
auto R = LSiMBA::RouteSimplify(StrMBA, SimpMBA, BitCount, ProveZ3,
UseFastCheck, RunParallel, CheckLinear,
LSiMBA::autoFallbackEnabled());
if (R == LSiMBA::RouteResult::SUCCESS) {
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
printf("[+] [Simplified MBA] '%s' time: %dms\n", SimpMBA.c_str(),
(int)duration.count());
return;
}
if (R == LSiMBA::RouteResult::SKIPPED) {
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
printf("[!] [Simplified MBA] Skipped. time: %dms\n", (int)duration.count());
return;
}
if (R == LSiMBA::RouteResult::FAILED) {
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
printf(
"[!] [Simplified MBA] No result from the selected simplifier. time: "
"%dms\n",
(int)duration.count());
return;
}
if (R == LSiMBA::RouteResult::INVALID) {
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
printf(
"[!] [Simplified MBA] Not valid replacement! (verification failed) "
"'%s' time: %dms\n",
SimpMBA.c_str(), (int)duration.count());
return;
}
// NATIVE: original path (baseline behavior unchanged)
auto Result = LSiMBA::Simplifier::simplify_linear_mba(
StrMBA, SimpMBA, BitCount, ProveZ3, CheckLinear);
// Auto-fallback: native produced nothing (e.g. checkLinear classified the
// expression as linear but the native simplifier cannot reduce it, while
// msimba/general could). Try the other routes before reporting a failure.
if (SimpMBA.empty() && LSiMBA::autoFallbackActive()) {
std::string fb;
if (LSiMBA::TryAutoFallback(StrMBA, fb, BitCount, ProveZ3, UseFastCheck,
"")) {
SimpMBA = fb;
Result = true;
}
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
if (Result == true) {
printf("[+] [Simplified MBA] '%s' time: %dms\n", SimpMBA.c_str(),
(int)duration.count());
} else {
printf("[!] [Simplified MBA] Not valid replacement! '%s' time: %dms\n",
SimpMBA.c_str(), (int)duration.count());
}
}
void ConvertToLLVMFunction(llvm::Module *M, std::string &StrMBA) {
auto IntTy =
llvm::Type::getIntNTy(LSiMBA::LLVMParser::getLLVMContext(), BitCount);
auto Vars = LSiMBA::Simplifier::getVariables(StrMBA);
SmallVector<Value *, 2> VarTypes;
for (auto &V : Vars) {
VarTypes.push_back(ConstantInt::get(IntTy, 0));
}
// Create LLVM Function
auto F = createLLVMFunction(M, VarTypes, StrMBA, Vars, IntTy);
// Set name
F->setName("MBA");
}
void SimplifyMBADatabase() {
// read lines from file
std::ifstream infile(StrMBADB);
if (infile.is_open() == false) {
outs() << "[!] Could not open database: '" << StrMBADB << "'\n";
return;
}
std::string line;
int All = 0;
int Counter = 0;
int Valid = 0;
unique_ptr<llvm::Module> LLVMModule;
if (ConvertToLLVM != "") {
LLVMModule = make_unique<llvm::Module>(
StrMBADB, LSiMBA::LLVMParser::getLLVMContext());
}
auto start = high_resolution_clock::now();
while (std::getline(infile, line)) {
// Skip comments
if (line[0] == '#') continue;
// split line at '#' and strip whitespaces
auto MBA = line.substr(0, line.find(','));
MBA = LSiMBA::Simplifier::strip(MBA);
// get line after ','
auto ExpMBA = line.substr(line.find(',') + 1, line.size());
ExpMBA = LSiMBA::Simplifier::strip(ExpMBA);
// Remove whitespaces
ExpMBA.erase(std::remove_if(ExpMBA.begin(), ExpMBA.end(), ::isspace),
ExpMBA.end());
All++;
Counter++;
if (ConvertToLLVM != "") {
// Just convert to LLVM dont simplify
ConvertToLLVMFunction(LLVMModule.get(), MBA);
Valid++;
} else {
// Run Simplifier
std::string SimpMBA = "";
// Simplify MBA
RunSimplifier(MBA, SimpMBA, ExpMBA, Counter, Valid);
}
}
// print stats
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
printf("[+] MBAs: %d -> Counter: %d Valid: %d time: %dms avg: %lfms\n", All,
Counter, Valid, (int)duration.count(),
(double)duration.count() / (double)All);
// Write LLVM Module
if (ConvertToLLVM != "") {
std::error_code EC;
llvm::raw_fd_ostream OS(ConvertToLLVM, EC, llvm::sys::fs::OF_None);
if (EC) {
outs() << "[!] Could not open file: '" << ConvertToLLVM << "'\n";
return;
}
OS << *LLVMModule;
OS.close();
outs() << "[+] Wrote LLVM Module to: '" << ConvertToLLVM << "'\n";
}
}
void SimplifyLLVMDataBase() {
outs() << "[+] Loading LLVM MBA Module: '" << StrIR << "'\n";
LSiMBA::LLVMParser Parser(StrIR, Output, RunParallel, UseFastCheck,
RunOptimizer, RunOptimizer, Debug, ProveZ3);
auto start = high_resolution_clock::now();
int MBACount = Parser.simplifyMBAFunctionsOnly();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
outs() << "[+] MBAs: '" << MBACount << "' time: " << (int)duration.count()
<< "ms\n";
}
void SimplifyLLVMModule() {
outs() << "[+] Loading LLVM Module: '" << StrIR << "'\n";
LSiMBA::LLVMParser Parser(StrIR, Output, RunParallel, UseFastCheck, false,
RunOptimizer, Debug, ProveZ3);
auto start = high_resolution_clock::now();
int MBACount = Parser.simplify();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
outs() << "[+] MBAs found and replaced: '" << MBACount
<< "' time: " << (int)duration.count() << "ms\n";
outs() << "[+] : '" << Parser.getInstructionCountBefore()
<< "' after: " << Parser.getInstructionCountAfter() << " (-"
<< int(Parser.getInstructionCountAfter() * 100. /
Parser.getInstructionCountBefore())
<< "%)\n";
}
void RunSimplifier(std::string &MBA, std::string &SimpMBA, std::string &ExpMBA,
int &Counter, int &Valid) {
// Phase 9: route to the selected simplifier (--simplifier, default auto).
// The native route keeps the original path below untouched.
auto R = LSiMBA::RouteSimplify(MBA, SimpMBA, BitCount, ProveZ3, UseFastCheck,
RunParallel, CheckLinear,
LSiMBA::autoFallbackEnabled());
if (R == LSiMBA::RouteResult::SKIPPED) {
printf("[%d] Skipped (see gate message above)\n", Counter);
return;
}
bool Result;
if (R == LSiMBA::RouteResult::SUCCESS) {
// The selected simplifier's result passed verification (fast-check and,
// with --prove, the Z3 proof).
Result = true;
} else if (R == LSiMBA::RouteResult::INVALID) {
// A result was produced but failed verification (counterexample printed
// above) - report it as an invalid transformation, never as valid.
Result = false;
} else if (R == LSiMBA::RouteResult::FAILED) {
Result = false;
SimpMBA = "";
} else {
// NATIVE: original path (baseline behavior unchanged)
Result = LSiMBA::Simplifier::simplify_linear_mba(
MBA, SimpMBA, BitCount, ProveZ3, CheckLinear, UseFastCheck,
RunParallel);
// Simplify Groundtruth (native path only, as before)
if (IgnoreExpected == false && SimplifyExpected == true) {
LSiMBA::Simplifier::simplify_linear_mba(MBA, ExpMBA, BitCount, false,
false, false, RunParallel);
}
// Auto-fallback: native produced nothing (e.g. checkLinear classified the
// expression as linear but the native simplifier cannot reduce it, while
// msimba/general could). Try the other routes before reporting a failure.
if (SimpMBA.empty() && LSiMBA::autoFallbackActive()) {
std::string fb;
if (LSiMBA::TryAutoFallback(MBA, fb, BitCount, ProveZ3, UseFastCheck,
"")) {
SimpMBA = fb;
Result = true;
}
}
}
// Check if valid replacement
if (Result == true) {
Valid++;
// printf("[%d] Valid Transformation!\n", Counter);
if (!IgnoreExpected && (ExpMBA != SimpMBA)) {
printf(
"[%d] Replacement is valid but does not meet expected string: "
"(%s != %s)\n",
Counter, ExpMBA.c_str(), SimpMBA.c_str());
}
} else {
printf("[%d] Not Valid Transformation! (%s != %s) <=> %s\n", Counter,
ExpMBA.c_str(), SimpMBA.c_str(), MBA.c_str());
}
}