-
Notifications
You must be signed in to change notification settings - Fork 9
/
caller.cpp
579 lines (494 loc) · 20.2 KB
/
caller.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
* Copyright (C) 2014 - 2019 Map2Check tool
* This file is part of the Map2Check tool, and is made available under
* the terms of the GNU General Public License version 2.
*
* Map2Check -> GPL-2.0
* CLANG -> Apache-2.0
* KLEE -> NCSA
* CRAB-LLVM -> Apache-2.0
* STP,Z3 -> MIT
*
* SPDX-License-Identifier: (GPL-2.0 AND Apache-2.0 AND NCSA AND MIT)
**/
#include "caller.hpp"
#include <stdlib.h>
// CPP Libs
#include <algorithm>
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include "utils/gen_crypto_hash.hpp"
#include "utils/log.hpp"
#include "utils/tools.hpp"
// namespace fs = boost::filesystem;
// } // namespace
using std::ifstream;
using std::regex;
using std::smatch;
namespace {
inline std::string getLibSuffix() { return ".so"; }
bool isWitnessFileCreated() {
Map2Check::Log::Debug("Checking file");
std::ifstream infile("map2check_checked_error");
if (infile.is_open()) {
Map2Check::Log::Debug("Found file!");
return true;
}
return false;
}
} // namespace
namespace Map2Check {
Caller::Caller(std::string bc_program_path, Map2CheckMode mode,
NonDetGenerator generator) {
// this->cleanGarbage();
this->pathprogram = bc_program_path;
this->map2checkMode = mode;
this->nonDetGenerator = generator;
GenHash hash;
hash.setFilePath(bc_program_path);
hash.generate_sha1_hash_for_file();
this->programHash = hash.getOutputSha1HashFile() + ".map2check";
std::ostringstream createTempDir;
createTempDir.str("");
createTempDir << "mkdir " << programHash;
system(createTempDir.str().c_str());
std::ostringstream moveProgram;
moveProgram << "cp " << bc_program_path << " " << programHash;
system(moveProgram.str().c_str());
Map2Check::Log::Debug("Changing current dir");
currentPath = boost::filesystem::current_path().string();
boost::filesystem::current_path(currentPath + "/" + programHash);
Map2Check::Log::Debug("Current path: " +
boost::filesystem::current_path().string());
}
std::string Caller::preOptimizationFlags() {
std::ostringstream flags;
flags.str("");
flags << "-O0";
return flags.str();
}
std::string Caller::postOptimizationFlags() {
std::ostringstream flags;
flags.str("");
flags << "-O2 ";
return flags.str();
}
void Caller::cleanGarbage() {
boost::filesystem::current_path(currentPath);
std::ostringstream removeCommand;
removeCommand.str("");
removeCommand << "rm -rf " << programHash;
Map2Check::Log::Debug("Remove " + removeCommand.str());
system(removeCommand.str().c_str());
}
void Caller::applyNonDetGenerator() {
switch (nonDetGenerator) {
case (NonDetGenerator::None): { // TODO(hbgit): Should generate binary
Map2Check::Log::Info(
"Map2Check will not generate non deterministic numbers");
break;
}
case (NonDetGenerator::Klee): {
Map2Check::Log::Info("Applying optimizations for klee");
break;
}
case (NonDetGenerator::LibFuzzer): {
Map2Check::Log::Info("Instrumenting with LLVM LibFuzzer");
std::ostringstream command;
command.str("");
command
<< Map2Check::clangBinary
<< " -g -fsanitize=fuzzer -fsanitize-coverage=inline-8bit-counters "
<< Caller::postOptimizationFlags()
<< " -o " + programHash + "-fuzzed.out"
<< " " + programHash + "-result.bc";
system(command.str().c_str());
std::ostringstream commandWitness;
commandWitness.str("");
commandWitness << Map2Check::clangBinary << " -g -fsanitize=fuzzer "
<< " -o " + programHash + "-witness-fuzzed.out"
<< " " + programHash + "-witness-result.bc";
system(commandWitness.str().c_str());
break;
}
}
}
int Caller::callPass(std::string target_function, bool sv_comp) {
std::ostringstream transformCommand;
transformCommand.str("");
transformCommand << Map2Check::optBinary;
/* TODO([email protected]): Should apply generate_automata_true
* and TrackBasicBlockPass now */
std::string nonDetPass = "${MAP2CHECK_PATH}/lib/libNonDetPass";
/*Map2Check::Log::Info("Adding loop pass");
std::string loopPredAssumePass =
"${MAP2CHECK_PATH}/lib/libLoopPredAssumePass"; transformCommand << " -load "
<< loopPredAssumePass << getLibSuffix()
<< " -loop_predicate_assume";*/
Map2Check::Log::Info("Adding nondet pass");
transformCommand << " -tailcallopt";
transformCommand << " -load " << nonDetPass << getLibSuffix() << " -non_det";
switch (map2checkMode) {
case Map2CheckMode::MEMTRACK_MODE: {
Map2Check::Log::Info("Adding memtrack pass");
std::string memoryTrackPass = "${MAP2CHECK_PATH}/lib/libMemoryTrackPass";
transformCommand << " -load " << memoryTrackPass << getLibSuffix()
<< " -memory_track";
break;
}
case Map2CheckMode::MEMCLEANUP_MODE: {
Map2Check::Log::Info("Adding memcleanup pass");
std::string memoryTrackPass = "${MAP2CHECK_PATH}/lib/libMemoryTrackPass";
transformCommand << " -load " << memoryTrackPass << getLibSuffix()
<< " -memory_track";
break;
}
case Map2CheckMode::OVERFLOW_MODE: {
std::string overflowPass = "${MAP2CHECK_PATH}/lib/libOverflowPass";
transformCommand << " -load " << overflowPass << getLibSuffix()
<< " -check_overflow";
break;
}
case Map2CheckMode::REACHABILITY_MODE: {
Map2Check::Log::Info("Running reachability mode");
std::string targetPass = "${MAP2CHECK_PATH}/lib/libTargetPass";
transformCommand << " -load " << targetPass << getLibSuffix()
<< " -target_function";
break;
}
case Map2CheckMode::ASSERT_MODE: {
Map2Check::Log::Info("Running assert mode");
std::string assertPass = "${MAP2CHECK_PATH}/lib/libAssertPass";
transformCommand << " -load " << assertPass << getLibSuffix()
<< " -validate_asserts";
break;
}
default: { break; }
}
Map2Check::Log::Info("Adding map2check pass");
std::string map2checkPass = "${MAP2CHECK_PATH}/lib/libMap2CheckLibrary";
transformCommand << " -load " << map2checkPass << getLibSuffix()
<< " -map2check ";
std::string input_file = "< " + this->pathprogram;
std::string output_file = "> " + programHash + "-output.bc";
transformCommand << input_file << output_file;
Map2Check::Log::Debug(transformCommand.str());
system(transformCommand.str().c_str());
return 1;
}
void Caller::linkLLVM() {
/* Link functions called after executing the passes */
// TODO([email protected]) Only link against used libraries
Map2Check::Log::Info("Linking with map2check library");
std::ostringstream witnessCommand;
std::ostringstream linkCommand;
linkCommand.str("");
linkCommand << Map2Check::llvmLinkBinary;
linkCommand << " " + programHash + "-output.bc"
<< " ${MAP2CHECK_PATH}/lib/Map2CheckFunctions.bc"
<< " ${MAP2CHECK_PATH}/lib/TrackBBLog.bc"
<< " ${MAP2CHECK_PATH}/lib/NonDetLog.bc"
<< " ${MAP2CHECK_PATH}/lib/PropertyGenerator.bc";
switch (dataStructure) {
case DataStructure::Array: {
linkCommand << " ${MAP2CHECK_PATH}/lib/ContainerRealloc.bc";
break;
}
case DataStructure::BTree: {
linkCommand << " ${MAP2CHECK_PATH}/lib/ContainerBTree.bc"
<< " ${MAP2CHECK_PATH}/lib/BTree.bc";
break;
}
}
switch (map2checkMode) {
case Map2CheckMode::MEMTRACK_MODE: {
linkCommand << " ${MAP2CHECK_PATH}/lib/AnalysisModeMemtrack.bc"
<< " ${MAP2CHECK_PATH}/lib/AllocationLog.bc"
<< " ${MAP2CHECK_PATH}/lib/ListLog.bc"
<< " ${MAP2CHECK_PATH}/lib/HeapLog.bc";
break;
}
case Map2CheckMode::MEMCLEANUP_MODE: {
linkCommand << " ${MAP2CHECK_PATH}/lib/AnalysisModeMemcleanup.bc"
<< " ${MAP2CHECK_PATH}/lib/AllocationLog.bc"
<< " ${MAP2CHECK_PATH}/lib/ListLog.bc"
<< " ${MAP2CHECK_PATH}/lib/HeapLog.bc";
break;
}
case Map2CheckMode::OVERFLOW_MODE: {
linkCommand << " ${MAP2CHECK_PATH}/lib/AnalysisModeOverflow.bc";
break;
}
case Map2CheckMode::ASSERT_MODE: {
linkCommand << " ${MAP2CHECK_PATH}/lib/AnalysisModeAssert.bc";
break;
}
case Map2CheckMode::REACHABILITY_MODE: {
// Since the map2check api provides the function, we do not need to do any
// analysis
linkCommand << " ${MAP2CHECK_PATH}/lib/AnalysisModeNone.bc";
break;
}
}
switch (nonDetGenerator) {
case (NonDetGenerator::None): {
linkCommand << " ${MAP2CHECK_PATH}/lib/NonDetGeneratorNone.bc";
break;
}
case (NonDetGenerator::Klee): { // TODO(hbgit): Add klee non det generator
linkCommand << " ${MAP2CHECK_PATH}/lib/NonDetGeneratorKlee.bc";
break;
}
case (NonDetGenerator::LibFuzzer): {
linkCommand << " ${MAP2CHECK_PATH}/lib/NonDetGeneratorLibFuzzy.bc";
break;
}
}
witnessCommand.str("");
witnessCommand << linkCommand.str();
witnessCommand << " ${MAP2CHECK_PATH}/lib/WitnessGeneration.bc";
witnessCommand << " > " + programHash + "-witness-result.bc";
Map2Check::Log::Debug(witnessCommand.str());
system(witnessCommand.str().c_str());
linkCommand << " ${MAP2CHECK_PATH}/lib/WitnessGenerationNone.bc";
linkCommand << " > " + programHash + "-result.bc";
Map2Check::Log::Debug(linkCommand.str());
system(linkCommand.str().c_str());
}
void Caller::executeAnalysis(std::string solvername) {
switch (nonDetGenerator) {
// TODO(hbgit): implement this method
case (NonDetGenerator::None): { // TODO(hbgit): Activate mode
Map2Check::Log::Info("This mode is not supported");
break;
}
case (NonDetGenerator::Klee): {
Map2Check::Log::Info("Executing Klee with map2check");
std::ostringstream kleeCommand;
kleeCommand.str("");
kleeCommand << "timeout " << (0.8 * this->timeout) << " ";
kleeCommand << Map2Check::kleeBinary;
std::vector<std::string> kleebackendsolver = {"z3", "stp"};
std::vector<std::string> kleemetasolver = {"btor", "yices2"};
if ( std::count(kleebackendsolver.begin(), kleebackendsolver.end(), solvername) ) {
// Checkout solver adopted, if is z3 or stp
// in KLEE add -solver-backend option
Map2Check::Log::Info("Solver backend caller: " + solvername);
// --allow-external-sym-calls
// -use-cache
kleeCommand << " -suppress-external-warnings"
<< " --external-calls=all"
<< " -exit-on-error-type=Abort"
<< " --optimize"
<< " -use-cex-cache"
<< " -solver-backend=" + solvername + " "
<< " -use-construct-hash-metasmt "
<< " -libc=uclibc"
<< " ./" + programHash + "-witness-result.bc"
<< " > ExecutionOutput.log";
} else if ( std::count(kleemetasolver.begin(), kleemetasolver.end(), solvername) ) {
// Checkout solver adopted, if is btor (Boolector) or yices (Yices)
// in KLEE add - option
Map2Check::Log::Info("Solver metaSMT caller: " + solvername);
kleeCommand << " -suppress-external-warnings"
<< " --external-calls=all"
<< " -exit-on-error-type=Abort"
<< " --optimize"
<< " -use-cex-cache"
<< " -solver-backend=metasmt "
<< " -metasmt-backend=" + solvername + " "
<< " -use-construct-hash-metasmt "
<< " -libc=uclibc"
<< " ./" + programHash + "-witness-result.bc"
<< " > ExecutionOutput.log";
}
Map2Check::Log::Debug(kleeCommand.str());
int result = system(kleeCommand.str().c_str());
Map2Check::Log::Warning("Exited klee with " + std::to_string(result));
if (result == 31744) // Timeout
gotTimeout = true;
break;
}
case (NonDetGenerator::LibFuzzer): {
Map2Check::Log::Info("Executing LibFuzzer with map2check");
std::ostringstream command;
command.str("");
command << "timeout " << (0.2 * this->timeout) << " ";
command << "./" + programHash +
"-fuzzed.out -jobs=8 -use_value_profile=1 "
<< " > fuzzer.output";
int result = system(command.str().c_str());
Map2Check::Log::Warning("Exited fuzzer with " + std::to_string(result));
if (result == 31744) // Timeout
gotTimeout = true;
std::ostringstream commandWitness;
commandWitness.str("");
commandWitness << "./" + programHash + "-witness-fuzzed.out crash-*";
system(commandWitness.str().c_str());
Map2Check::Log::Debug("Finished fuzzer");
if (isWitnessFileCreated()) {
witnessVerified = true;
}
break;
}
}
if (isWitnessFileCreated()) {
witnessVerified = true;
}
}
std::vector<int> Caller::processClangOutput() {
const char* path_name = "clang.out";
std::vector<int> result;
ifstream in(path_name);
if (!in.is_open()) {
Map2Check::Log::Debug("Clang did not generate warning or errors");
return result;
}
Map2Check::Log::Debug("Clang generate warning or errors");
// This regex captures accused line number for overflow warnings (from clang)
regex overflowWarning(
".*:([[:digit:]]+):[[:digit:]]+:.*(Winteger-overflow).*");
string line;
smatch match;
while (getline(in, line)) {
if (std::regex_search(line, match, overflowWarning) && match.size() > 1) {
Map2Check::Log::Info("Found warning at line " + match[1].str());
int lineNumber = std::stoi(match[1].str());
result.push_back(lineNumber);
}
}
return result;
}
/** This function should:
* (1) Remove unsupported functions and clean the C code
* (2) Generate .bc file from code
* (3) Check for overflow errors on compilation
*/
void Caller::compileCFile(bool is_llvm_bc) {
if (!is_llvm_bc) {
Map2Check::Log::Info("Compiling " + this->pathprogram);
// (1) Remove unsupported functions and clean the C code
std::ostringstream commandRemoveExternMalloc;
commandRemoveExternMalloc.str("");
commandRemoveExternMalloc << "cat " << this->pathprogram << " | ";
commandRemoveExternMalloc << "sed -e 's/extern void [*].[^_]*lloc.*/ / g' "
<< " > " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMalloc.str().c_str());
system(commandRemoveExternMalloc.str().c_str());
std::ostringstream commandRemoveExternMemset;
commandRemoveExternMemset.str("");
commandRemoveExternMemset << "sed -i 's/extern void [*]memset.*/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveExternMemset.str().c_str());
std::ostringstream commandRemoveVoidMemset;
commandRemoveVoidMemset.str("");
commandRemoveVoidMemset << "sed -i 's/void [*]memset(void[*], int, size_t);/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveVoidMemset.str().c_str());
std::ostringstream commandRemoveVoidMemcpy;
commandRemoveVoidMemcpy.str("");
commandRemoveVoidMemcpy << "sed -i 's/void [*]memcpy(void[*], const void [*], size_t);/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveVoidMemcpy.str().c_str());
// (2) Generate .bc file from code
// TODO(hbgit): -Winteger-overflow should be called only if is on overflow
// mode
std::string compiledFile = programHash + "-compiled.bc";
std::ostringstream command;
command.str("");
command << Map2Check::clangBinary << " -I" << Map2Check::clangIncludeFolder
<< " -Wno-everything "
<< " -Winteger-overflow "
<< " -c -emit-llvm -g"
<< " " << Caller::preOptimizationFlags() << " -o " << compiledFile
<< " " << programHash << "-preprocessed.c "
<< " > " << programHash << "-clang.out 2>&1";
system(command.str().c_str());
this->pathprogram = compiledFile;
} else {
std::string compiledFile = programHash + "-compiled.bc";
std::ostringstream command;
command.str("");
command << " cp " << this->pathprogram << " " << compiledFile;
system(command.str().c_str());
this->pathprogram = compiledFile;
}
// TODO(hbgit): (3) Check for overflow errors on compilation
}
void Caller::compileToCrabLlvm() {
Map2Check::Log::Info("Compiling using crab-llvm in " + this->pathprogram);
// (1) Remove unsupported functions and clean the C code
// TODO(hbgit): improve regex to the next line
std::ostringstream commandRemoveExternMalloc;
commandRemoveExternMalloc.str("");
commandRemoveExternMalloc << "cat " << this->pathprogram << " | ";
commandRemoveExternMalloc << "sed -e 's/extern void [*].[^_]*lloc.*/ / g' "
<< " > " << programHash << "-preprocessed.c ";
system(commandRemoveExternMalloc.str().c_str());
std::ostringstream commandRemoveExternMemset;
commandRemoveExternMemset.str("");
commandRemoveExternMemset << "sed -i 's/extern void [*]memset.*/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveExternMemset.str().c_str());
std::ostringstream commandRemoveVoidMemset;
commandRemoveVoidMemset.str("");
commandRemoveVoidMemset << "sed -i 's/void [*]memset(void[*], int, size_t);/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveVoidMemset.str().c_str());
std::ostringstream commandRemoveVoidMemcpy;
commandRemoveVoidMemcpy.str("");
commandRemoveVoidMemcpy << "sed -i 's/void [*]memcpy(void[*], const void [*], size_t);/ / g' "
<< " " << programHash << "-preprocessed.c ";
// Map2Check::Log::Info(commandRemoveExternMemset.str().c_str());
system(commandRemoveVoidMemcpy.str().c_str());
// (2) Generate .bc file from code
// TODO(hbgit): -Winteger-overflow should be called only if is on overflow
// mode CLANG PATH
std::ostringstream getPathCLCommand;
getPathCLCommand.str("");
std::ostringstream getMapPath;
getMapPath << getenv("MAP2CHECK_PATH");
getPathCLCommand << "CLANG_PATH=" << getMapPath.str().c_str() << "/bin";
std::string tmp_gpcc = getPathCLCommand.str().c_str();
char* c_gpcc = new char[tmp_gpcc.length() + 1];
std::copy(tmp_gpcc.c_str(), tmp_gpcc.c_str() + tmp_gpcc.length() + 1, c_gpcc);
putenv(c_gpcc);
// Export libCrab.so from CrabLLVM
std::ostringstream getPathLibCrabCommand;
getPathLibCrabCommand.str("");
std::ostringstream tmp_ld_p;
tmp_ld_p << getenv("LD_LIBRARY_PATH");
getPathLibCrabCommand << "LD_LIBRARY_PATH="
<< tmp_ld_p.str().c_str()
<< ":"
<< getMapPath.str().c_str()
<< "/bin/crabllvm/lib";
// std::ostringstream tmp_ld;
// tmp_ld << getenv("LD_LIBRARY_PATH");
// std::cout << tmp_ld.str().c_str();
std::string tmp_gplibcc = getPathLibCrabCommand.str().c_str();
char* c_gplibcc = new char[tmp_gplibcc.length() + 1];
std::copy(tmp_gplibcc.c_str(), tmp_gplibcc.c_str() + tmp_gplibcc.length() + 1,
c_gplibcc);
putenv(c_gplibcc);
std::string compiledFile = programHash + "-compiled.bc";
std::ostringstream command;
command.str("");
command << Map2Check::crabBinary << " -o " << compiledFile
<< " -m 64 -g --crab-disable-warnings --disable-lower-gv "
"--llvm-pp-loops --crab-promote-assume --crab-inter "
"--crab-track=num --crab-add-invariants=block-entry "
<< " " << programHash << "-preprocessed.c ";
//<< " -m 64 --crab-dom=oct --crab-track=num --crab-add-invariants=all "
system(command.str().c_str());
this->pathprogram = compiledFile;
}
} // namespace Map2Check