forked from S2E/s2e-old
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathExecutor.cpp
3841 lines (3303 loc) · 128 KB
/
Executor.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- Executor.cpp ------------------------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "klee/Common.h"
#include "klee/Executor.h"
#include "klee/Context.h"
#include "klee/CoreStats.h"
#include "klee/ExternalDispatcher.h"
#include "ImpliedValue.h"
#include "klee/Memory.h"
#include "MemoryManager.h"
#include "klee/PTree.h"
#include "klee/Searcher.h"
#include "SeedInfo.h"
#include "SpecialFunctionHandler.h"
#include "klee/StatsTracker.h"
#include "TimingSolver.h"
#include "klee/UserSearcher.h"
#include "klee/SolverStats.h"
#include "klee/BitfieldSimplifier.h"
#include "klee/ExecutionState.h"
#include "klee/Expr.h"
#include "klee/Interpreter.h"
#include "klee/TimerStatIncrementer.h"
#include "klee/util/Assignment.h"
#include "klee/util/ExprPPrinter.h"
#include "klee/util/ExprUtil.h"
#include "klee/Config/config.h"
#include "klee/Internal/ADT/KTest.h"
#include "klee/Internal/ADT/RNG.h"
#include "klee/Internal/Module/Cell.h"
#include "klee/Internal/Module/InstructionInfoTable.h"
#include "klee/Internal/Module/KInstruction.h"
#include "klee/Internal/Module/KModule.h"
#include "klee/Internal/Support/FloatEvaluation.h"
#include "klee/Internal/System/Time.h"
#include "llvm/Attributes.h"
#include "llvm/BasicBlock.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#if !(LLVM_VERSION_MAJOR == 2 && LLVM_VERSION_MINOR < 7)
#include "llvm/LLVMContext.h"
#endif
#include "llvm/Module.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Process.h"
#include "llvm/DataLayout.h"
#include <cassert>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <stdlib.h>
#ifndef __MINGW32__
#include <sys/mman.h>
#endif
#include <errno.h>
#include <cxxabi.h>
#include <inttypes.h>
using namespace llvm;
using namespace klee;
namespace {
cl::opt<bool>
DumpStatesOnHalt("dump-states-on-halt",
cl::init(true));
cl::opt<bool>
NoPreferCex("no-prefer-cex",
cl::init(false));
cl::opt<bool>
UseAsmAddresses("use-asm-addresses",
cl::init(false));
cl::opt<bool>
RandomizeFork("randomize-fork",
cl::init(false));
cl::opt<bool>
AllowExternalSymCalls("allow-external-sym-calls",
cl::init(false));
cl::opt<bool>
DebugPrintInstructions("debug-print-instructions",
cl::desc("Print instructions during execution."),
cl::init(false));
cl::opt<bool>
DebugCheckForImpliedValues("debug-check-for-implied-values");
cl::opt<bool>
SimplifySymIndices("simplify-sym-indices",
cl::init(true));
cl::opt<unsigned>
MaxSymArraySize("max-sym-array-size",
cl::init(0));
cl::opt<bool>
DebugValidateSolver("debug-validate-solver",
cl::init(false));
cl::opt<bool>
SuppressExternalWarnings("suppress-external-warnings", cl::init(true));
cl::opt<bool>
OnlyOutputStatesCoveringNew("only-output-states-covering-new",
cl::init(false));
cl::opt<bool>
AlwaysOutputSeeds("always-output-seeds",
cl::init(false));
cl::opt<bool>
UseFastCexSolver("use-fast-cex-solver",
cl::init(false));
cl::opt<bool>
UseIndependentSolver("use-independent-solver",
cl::init(true),
cl::desc("Use constraint independence"));
cl::opt<bool>
EmitAllErrors("emit-all-errors",
cl::init(false),
cl::desc("Generate tests cases for all errors "
"(default=one per (error,instruction) pair)"));
//The counter example cache may have bad interactions with
//concolic mode. Disabled by default.
cl::opt<bool>
UseCexCache("use-cex-cache",
cl::init(false),
cl::desc("Use counterexample caching"));
cl::opt<bool>
UseQueryLog("use-query-log",
cl::init(false));
cl::opt<bool>
UseQueryPCLog("use-query-pc-log",
cl::init(false));
cl::opt<bool>
UseSTPQueryPCLog("use-stp-query-pc-log",
cl::init(false));
cl::opt<bool>
NoExternals("no-externals",
cl::desc("Do not allow external functin calls"));
cl::opt<bool>
UseCache("use-cache",
cl::init(true),
cl::desc("Use validity caching"));
cl::opt<bool>
OnlyReplaySeeds("only-replay-seeds",
cl::desc("Discard states that do not have a seed."));
cl::opt<bool>
OnlySeed("only-seed",
cl::desc("Stop execution after seeding is done without doing regular search."));
cl::opt<bool>
AllowSeedExtension("allow-seed-extension",
cl::desc("Allow extra (unbound) values to become symbolic during seeding."));
cl::opt<bool>
ZeroSeedExtension("zero-seed-extension");
cl::opt<bool>
AllowSeedTruncation("allow-seed-truncation",
cl::desc("Allow smaller buffers than in seeds."));
cl::opt<bool>
NamedSeedMatching("named-seed-matching",
cl::desc("Use names to match symbolic objects to inputs."));
cl::opt<double>
MaxStaticForkPct("max-static-fork-pct", cl::init(1.));
cl::opt<double>
MaxStaticSolvePct("max-static-solve-pct", cl::init(1.));
cl::opt<double>
MaxStaticCPForkPct("max-static-cpfork-pct", cl::init(1.));
cl::opt<double>
MaxStaticCPSolvePct("max-static-cpsolve-pct", cl::init(1.));
cl::opt<double>
MaxInstructionTime("max-instruction-time",
cl::desc("Only allow a single instruction to take this much time (default=0 (off))"),
cl::init(0));
cl::opt<double>
SeedTime("seed-time",
cl::desc("Amount of time to dedicate to seeds, before normal search (default=0 (off))"),
cl::init(0));
cl::opt<double>
MaxSTPTime("max-stp-time",
cl::desc("Maximum amount of time for a single query (default=120s)"),
cl::init(120.0));
cl::opt<unsigned int>
StopAfterNInstructions("stop-after-n-instructions",
cl::desc("Stop execution after specified number of instructions (0=off)"),
cl::init(0));
cl::opt<unsigned>
MaxForks("max-forks",
cl::desc("Only fork this many times (-1=off)"),
cl::init(~0u));
cl::opt<unsigned>
MaxDepth("max-depth",
cl::desc("Only allow this many symbolic branches (0=off)"),
cl::init(0));
cl::opt<unsigned>
MaxMemory("max-memory",
cl::desc("Refuse to fork when more above this about of memory (in MB, 0=off)"),
cl::init(0));
cl::opt<bool>
MaxMemoryInhibit("max-memory-inhibit",
cl::desc("Inhibit forking at memory cap (vs. random terminate)"),
cl::init(true));
cl::opt<bool>
UseForkedSTP("use-forked-stp",
cl::desc("Run STP in forked process"), cl::init(false));
/*
cl::opt<bool>
IgnoreAlwaysConcrete("ignore-always-concrete",
cl::desc("Do not add constraints when writing to always concrete memory"),
cl::init(false));
*/
cl::opt<bool>
ValidateSimplifier("validate-expr-simplifier",
cl::desc("Checks that the simplification algorithm produced correct expressions"),
cl::init(false));
cl::opt<bool>
EnableSpeculativeForking("enable-speculative-forking",
cl::desc("Enable speculative forking for concolic execution"),
cl::init(true));
}
//S2E: we want these to be accessible in S2E executor
cl::opt<bool>
UseExprSimplifier("use-expr-simplifier",
cl::desc("Apply expression simplifier for new expressions"),
cl::init(true));
unsigned Executor::getMaxMemory() { return MaxMemory; }
bool Executor::getMaxMemoryInhibit() { return MaxMemoryInhibit; }
static void *theMMap = 0;
static unsigned theMMapSize = 0;
namespace klee {
RNG theRNG;
}
Solver *constructSolverChain(STPSolver *stpSolver,
std::string queryLogPath,
std::string stpQueryLogPath,
std::string queryPCLogPath,
std::string stpQueryPCLogPath) {
Solver *solver = stpSolver;
if (UseSTPQueryPCLog)
solver = createPCLoggingSolver(solver,
stpQueryLogPath);
if (UseFastCexSolver)
solver = createFastCexSolver(solver);
if (UseCexCache)
solver = createCexCachingSolver(solver);
if (UseCache)
solver = createCachingSolver(solver);
if (UseIndependentSolver)
solver = createIndependentSolver(solver);
if (DebugValidateSolver)
solver = createValidatingSolver(solver, stpSolver);
if (UseQueryPCLog)
solver = createPCLoggingSolver(solver,
queryPCLogPath);
return solver;
}
void Executor::initializeSolver()
{
if (this->solver) {
delete this->solver;
}
STPSolver *stpSolver = new STPSolver(UseForkedSTP);
Solver *solver =
constructSolverChain(stpSolver,
interpreterHandler->getOutputFilename("queries.qlog"),
interpreterHandler->getOutputFilename("stp-queries.qlog"),
interpreterHandler->getOutputFilename("queries.pc"),
interpreterHandler->getOutputFilename("stp-queries.pc"));
this->solver = new TimingSolver(solver, stpSolver);
}
Executor::Executor(const InterpreterOptions &opts,
InterpreterHandler *ih, ExecutionEngine *engine)
: Interpreter(opts),
kmodule(0),
interpreterHandler(ih),
searcher(0),
externalDispatcher(new ExternalDispatcher(engine)),
statsTracker(0),
pathWriter(0),
symPathWriter(0),
specialFunctionHandler(0),
processTree(0),
concolicMode(false),
concolicTaint(false),
replayOut(0),
replayPath(0),
usingSeeds(0),
atMemoryLimit(false),
inhibitForking(false),
haltExecution(false),
ivcEnabled(false) {
if(MaxSTPTime == 0) {
stpTimeout = MaxInstructionTime;
} else if(MaxInstructionTime == 0) {
stpTimeout = MaxSTPTime;
} else {
stpTimeout = std::min(MaxSTPTime,MaxInstructionTime);
}
this->solver = NULL;
initializeSolver();
memory = new MemoryManager();
//Mandatory for AddressSpace
exprSimplifier = new BitfieldSimplifier;
}
const Module *Executor::setModule(llvm::Module *module,
const ModuleOptions &opts,
bool createStatsTracker) {
assert(!kmodule && module && "can only register one module"); // XXX gross
kmodule = new KModule(module);
// Initialize the context.
DataLayout *TD = kmodule->targetData;
Context::initialize(TD->isLittleEndian(),
(Expr::Width) TD->getPointerSizeInBits());
specialFunctionHandler = new SpecialFunctionHandler(*this);
specialFunctionHandler->prepare();
kmodule->prepare(opts, interpreterHandler);
specialFunctionHandler->bind();
if (createStatsTracker && StatsTracker::useStatistics()) {
statsTracker =
new StatsTracker(*this,
interpreterHandler->getOutputFilename("assembly.ll"),
userSearcherRequiresMD2U());
statsTracker->writeHeaders();
}
return module;
}
Executor::~Executor() {
delete memory;
delete externalDispatcher;
if (processTree)
delete processTree;
if (specialFunctionHandler)
delete specialFunctionHandler;
if (statsTracker)
delete statsTracker;
delete solver;
delete kmodule;
}
/***/
ref<Expr> Executor::simplifyExpr(const ExecutionState &s, ref<Expr> e)
{
if(UseExprSimplifier) {
//*klee_message_stream << "Simpl hits:" << exprSimplifier->m_cacheHits
// << " misses:" << exprSimplifier->m_cacheMisses << "\n";
ref<Expr> simplified = exprSimplifier->simplify(e);
if (ValidateSimplifier) {
bool isEqual;
if (concolicMode) {
ref<Expr> originalConcrete = s.concolics.evaluate(e);
ref<Expr> simplifiedConcrete = s.concolics.evaluate(simplified);
isEqual = originalConcrete == simplifiedConcrete;
} else {
ref<Expr> eq = EqExpr::create(simplified, e);
bool result = solver->mustBeTrue(s, eq, isEqual);
assert(result);
}
if(!isEqual) {
llvm::errs() << "Error in expression simplifier:" << '\n';
e->dump();
llvm::errs() << "!=" << '\n';
simplified->dump();
assert(false);
}
}
return simplified;
}else {
return e;
}
}
void Executor::initializeGlobalObject(ExecutionState &state, ObjectState *os,
Constant *c,
unsigned offset) {
DataLayout *targetData = kmodule->targetData;
if (ConstantVector *cp = dyn_cast<ConstantVector>(c)) {
unsigned elementSize =
targetData->getTypeStoreSize(cp->getType()->getElementType());
for (unsigned i=0, e=cp->getNumOperands(); i != e; ++i)
initializeGlobalObject(state, os, cp->getOperand(i),
offset + i*elementSize);
} else if (isa<ConstantAggregateZero>(c)) {
unsigned i, size = targetData->getTypeStoreSize(c->getType());
for (i=0; i<size; i++)
os->write8(offset+i, (uint8_t) 0);
} else if (ConstantArray *ca = dyn_cast<ConstantArray>(c)) {
unsigned elementSize =
targetData->getTypeStoreSize(ca->getType()->getElementType());
for (unsigned i=0, e=ca->getNumOperands(); i != e; ++i)
initializeGlobalObject(state, os, ca->getOperand(i),
offset + i*elementSize);
} else if (ConstantStruct *cs = dyn_cast<ConstantStruct>(c)) {
const StructLayout *sl =
targetData->getStructLayout(cast<StructType>(cs->getType()));
for (unsigned i=0, e=cs->getNumOperands(); i != e; ++i)
initializeGlobalObject(state, os, cs->getOperand(i),
offset + sl->getElementOffset(i));
} else if (const ConstantDataSequential *cds =
dyn_cast<ConstantDataSequential>(c)) {
unsigned elementSize =
targetData->getTypeStoreSize(cds->getElementType());
for (unsigned i=0, e=cds->getNumElements(); i != e; ++i)
initializeGlobalObject(state, os, cds->getElementAsConstant(i),
offset + i*elementSize);
} else {
unsigned StoreBits = targetData->getTypeStoreSizeInBits(c->getType());
ref<ConstantExpr> C = evalConstant(c);
// Extend the constant if necessary;
assert(StoreBits >= C->getWidth() && "Invalid store size!");
if (StoreBits > C->getWidth())
C = C->ZExt(StoreBits);
os->write(offset, C);
}
}
MemoryObject * Executor::addExternalObject(ExecutionState &state,
void *addr, unsigned size,
bool isReadOnly,
bool isUserSpecified,
bool isSharedConcrete,
bool isValueIgnored) {
MemoryObject *mo = memory->allocateFixed((uint64_t) addr,
size, 0);
mo->isUserSpecified = isUserSpecified;
mo->isSharedConcrete = isSharedConcrete;
mo->isValueIgnored = isValueIgnored;
ObjectState *os = bindObjectInState(state, mo, false);
if(!isSharedConcrete) {
memcpy(os->getConcreteStore(), addr, size);
/*
for(unsigned i = 0; i < size; i++)
os->write8(i, ((uint8_t*)addr)[i]);
*/
}
if(isReadOnly)
os->setReadOnly(true);
return mo;
}
void Executor::initializeGlobals(ExecutionState &state) {
Module *m = kmodule->module;
if (m->getModuleInlineAsm() != "")
klee_warning("executable has module level assembly (ignoring)");
assert(m->lib_begin() == m->lib_end() &&
"XXX do not support dependent libraries");
// represent function globals using the address of the actual llvm function
// object. given that we use malloc to allocate memory in states this also
// ensures that we won't conflict. we don't need to allocate a memory object
// since reading/writing via a function pointer is unsupported anyway.
for (Module::iterator i = m->begin(), ie = m->end(); i != ie; ++i) {
Function *f = i;
ref<ConstantExpr> addr(0);
// If the symbol has external weak linkage then it is implicitly
// not defined in this module; if it isn't resolvable then it
// should be null.
if (f->hasExternalWeakLinkage() &&
!externalDispatcher->resolveSymbol(f->getName())) {
addr = Expr::createPointer(0);
} else {
addr = Expr::createPointer((uintptr_t) (void*) f);
legalFunctions.insert((uint64_t) (uintptr_t) (void*) f);
}
globalAddresses.insert(std::make_pair(f, addr));
}
// Disabled, we don't want to promote use of live externals.
#ifdef HAVE_CTYPE_EXTERNALS
#ifndef WINDOWS
#ifndef DARWIN
/* From /usr/include/errno.h: it [errno] is a per-thread variable. */
int *errno_addr = __errno_location();
addExternalObject(state, (void *)errno_addr, sizeof *errno_addr, false);
/* from /usr/include/ctype.h:
These point into arrays of 384, so they can be indexed by any `unsigned
char' value [0,255]; by EOF (-1); or by any `signed char' value
[-128,-1). ISO C requires that the ctype functions work for `unsigned */
const uint16_t **addr = __ctype_b_loc();
addExternalObject(state, (void *)(*addr-128),
384 * sizeof **addr, true);
addExternalObject(state, addr, sizeof(*addr), true);
const int32_t **lower_addr = __ctype_tolower_loc();
addExternalObject(state, (void *)(*lower_addr-128),
384 * sizeof **lower_addr, true);
addExternalObject(state, lower_addr, sizeof(*lower_addr), true);
const int32_t **upper_addr = __ctype_toupper_loc();
addExternalObject(state, (void *)(*upper_addr-128),
384 * sizeof **upper_addr, true);
addExternalObject(state, upper_addr, sizeof(*upper_addr), true);
#endif
#endif
#endif
// allocate and initialize globals, done in two passes since we may
// need address of a global in order to initialize some other one.
// allocate memory objects for all globals
for (Module::const_global_iterator i = m->global_begin(),
e = m->global_end();
i != e; ++i) {
std::map<std::string, void*>::iterator po =
predefinedSymbols.find(i->getName());
if(po != predefinedSymbols.end()) {
// This object was externally defined
globalAddresses.insert(std::make_pair(i,
ConstantExpr::create((uint64_t) po->second, sizeof(void*)*8)));
} else if(i->isDeclaration()) {
// FIXME: We have no general way of handling unknown external
// symbols. If we really cared about making external stuff work
// better we could support user definition, or use the EXE style
// hack where we check the object file information.
Type *ty = i->getType()->getElementType();
uint64_t size = kmodule->targetData->getTypeStoreSize(ty);
// XXX - DWD - hardcode some things until we decide how to fix.
#ifndef WINDOWS
if (i->getName() == "_ZTVN10__cxxabiv117__class_type_infoE") {
size = 0x2C;
} else if (i->getName() == "_ZTVN10__cxxabiv120__si_class_type_infoE") {
size = 0x2C;
} else if (i->getName() == "_ZTVN10__cxxabiv121__vmi_class_type_infoE") {
size = 0x2C;
}
#endif
if (size == 0) {
llvm::errs() << "Unable to find size for global variable: "
<< i->getName()
<< " (use will result in out of bounds access)\n";
}
MemoryObject *mo = memory->allocate(size, false, true, i);
ObjectState *os = bindObjectInState(state, mo, false);
globalObjects.insert(std::make_pair(i, mo));
globalAddresses.insert(std::make_pair(i, mo->getBaseExpr()));
// Program already running = object already initialized. Read
// concrete value and write it to our copy.
if (size) {
void *addr;
addr = externalDispatcher->resolveSymbol(i->getName());
if (!addr)
klee_error("unable to load symbol(%s) while initializing globals.",
i->getName().data());
for (unsigned offset=0; offset<mo->size; offset++)
os->write8(offset, ((unsigned char*)addr)[offset]);
}
} else {
Type *ty = i->getType()->getElementType();
uint64_t size = kmodule->targetData->getTypeStoreSize(ty);
MemoryObject *mo = 0;
if (UseAsmAddresses && i->getName()[0]=='\01') {
char *end;
uint64_t address = ::strtoll(i->getName().str().c_str()+1, &end, 0);
if (end && *end == '\0') {
klee_message("NOTE: allocated global at asm specified address: %#08"
PRIx64 " (%" PRIu64 " bytes)",
address, size);
mo = memory->allocateFixed(address, size, &*i);
mo->isUserSpecified = true; // XXX hack;
}
}
if (!mo)
mo = memory->allocate(size, false, true, &*i);
assert(mo && "out of memory");
ObjectState *os = bindObjectInState(state, mo, false);
globalObjects.insert(std::make_pair(i, mo));
globalAddresses.insert(std::make_pair(i, mo->getBaseExpr()));
if (!i->hasInitializer())
os->initializeToRandom();
}
}
// link aliases to their definitions (if bound)
for (Module::alias_iterator i = m->alias_begin(), ie = m->alias_end();
i != ie; ++i) {
// Map the alias to its aliasee's address. This works because we have
// addresses for everything, even undefined functions.
globalAddresses.insert(std::make_pair(i, evalConstant(i->getAliasee())));
}
// once all objects are allocated, do the actual initialization
for (Module::global_iterator i = m->global_begin(), e = m->global_end(); i != e; ++i) {
if (predefinedSymbols.find(i->getName()) != predefinedSymbols.end()) {
continue;
}
if (i->hasInitializer()) {
assert(globalObjects.find(i) != globalObjects.end());
const MemoryObject *mo = globalObjects.find(i)->second;
const ObjectState *os = state.addressSpace.findObject(mo);
assert(os);
ObjectState *wos = state.addressSpace.getWriteable(mo, os);
initializeGlobalObject(state, wos, i->getInitializer(), 0);
// if(i->isConstant()) os->setReadOnly(true);
}
}
}
void Executor::notifyBranch(ExecutionState &state)
{
//Should not get here
assert(false && "Must go through S2E");
}
void Executor::branch(ExecutionState &state,
const std::vector< ref<Expr> > &conditions,
std::vector<ExecutionState*> &result) {
TimerStatIncrementer timer(stats::forkTime);
unsigned N = conditions.size();
assert(N);
notifyBranch(state);
stats::forks += N-1;
// XXX do proper balance or keep random?
result.push_back(&state);
for (unsigned i=1; i<N; ++i) {
ExecutionState *es = result[theRNG.getInt32() % i];
ExecutionState *ns = es->branch();
addedStates.insert(ns);
result.push_back(ns);
es->ptreeNode->data = 0;
std::pair<PTree::Node*,PTree::Node*> res =
processTree->split(es->ptreeNode, ns, es);
ns->ptreeNode = res.first;
es->ptreeNode = res.second;
}
// If necessary redistribute seeds to match conditions, killing
// states if necessary due to OnlyReplaySeeds (inefficient but
// simple).
std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
seedMap.find(&state);
if (it != seedMap.end()) {
std::vector<SeedInfo> seeds = it->second;
seedMap.erase(it);
// Assume each seed only satisfies one condition (necessarily true
// when conditions are mutually exclusive and their conjunction is
// a tautology).
for (std::vector<SeedInfo>::iterator siit = seeds.begin(),
siie = seeds.end(); siit != siie; ++siit) {
unsigned i;
for (i=0; i<N; ++i) {
ref<ConstantExpr> res;
bool success =
solver->getValue(state, siit->assignment.evaluate(
simplifyExpr(state, conditions[i])),
res);
assert(success && "FIXME: Unhandled solver failure");
(void) success;
if (res->isTrue())
break;
}
// If we didn't find a satisfying condition randomly pick one
// (the seed will be patched).
if (i==N)
i = theRNG.getInt32() % N;
seedMap[result[i]].push_back(*siit);
}
if (OnlyReplaySeeds) {
for (unsigned i=0; i<N; ++i) {
if (!seedMap.count(result[i])) {
terminateState(*result[i]);
result[i] = NULL;
}
}
}
}
for (unsigned i=0; i<N; ++i)
if (result[i])
addConstraint(*result[i], conditions[i]);
}
Executor::StatePair
Executor::concolicFork(ExecutionState ¤t, ref<Expr> condition, bool isInternal) {
condition = simplifyExpr(current, condition);
//If we are passed a constant, no need to do anything,
//revert to normal fork (which won't branch).
if (dyn_cast<ConstantExpr>(condition)) {
return Executor::fork(current, condition, isInternal);
}
//*klee_message_stream << "Concolic fork for expression " << condition << "\n";
//The current state is guaranteed to be consistent with whatever
//assignment is stored in the concolics variable.
assert(!current.speculative);
//Evaluate the expression using the current variable assignment.
ref<Expr> evalResult = current.concolics.evaluate(condition);
ConstantExpr *ce = dyn_cast<ConstantExpr>(evalResult);
assert(ce && "Could not evaluate the expression to a constant.");
if (current.forkDisabled) {
if (ce->isTrue()) {
if(!concolicTaint)
//Condition is true in the current state
addConstraint(current, condition);
return StatePair(¤t, 0);
} else {
if(!concolicTaint)
//Condition is false in the current state
addConstraint(current, Expr::createIsZero(condition));
return StatePair(0, ¤t);
}
}
if (!EnableSpeculativeForking) {
if (ce->isTrue()) {
//Condition is true in the current state
current.speculativeCondition = Expr::createIsZero(condition);
bool valid = checkSpeculativeState(current);
current.speculativeCondition = NULL;
if (!valid) {
//Speculative state is infeasible
return StatePair(¤t, 0);
}
} else {
//Condition is false in the current state
current.speculativeCondition = condition;
bool valid = checkSpeculativeState(current);
current.speculativeCondition = NULL;
if (!valid) {
//Speculative state is infeasible
return StatePair(0, ¤t);
}
}
}
notifyBranch(current);
ExecutionState *trueState, *falseState, *branchedState;
branchedState = current.branch();
addedStates.insert(branchedState);
branchedState->speculative = true;
branchedState->concolics.clear();
//We don't know if the branched state could be valid
//or not, so we mark it speculative and defer the
//actual determination of the speculative status to later.
if (ce->isTrue()) {
//Condition is true in the current state
branchedState->speculativeCondition = Expr::createIsZero(condition);
addConstraint(current, condition);
trueState = ¤t;
falseState = branchedState;
} else {
//Condition is false in the current state
branchedState->speculativeCondition = condition;
addConstraint(current, Expr::createIsZero(condition));
falseState = ¤t;
trueState = branchedState;
}
current.ptreeNode->data = 0;
std::pair<PTree::Node*, PTree::Node*> res =
processTree->split(current.ptreeNode, falseState, trueState);
falseState->ptreeNode = res.first;
trueState->ptreeNode = res.second;
return StatePair(trueState, falseState);
}
bool Executor::checkSpeculativeState(ExecutionState &state)
{
//Check if the speculative condition satisfies the current path constraints
Query query(state.constraints,state.speculativeCondition);
bool truth;
bool res = solver->solver->mustBeTrue(query.negateExpr(), truth);
if (!res || truth) {
return false;
}
return true;
}
bool Executor::resolveSpeculativeState(ExecutionState &state)
{
assert(state.isSpeculative());
//The speculative condition must satisfy the current path constraints
if (!checkSpeculativeState(state)) {
return false;
}
state.addConstraint(state.speculativeCondition);
//Compute the values that satisfy the new set of path constraints.
std::vector<const Array*> symbObjects;
std::vector<std::vector<unsigned char> > concreteObjects;
for (unsigned i=0; i<state.symbolics.size(); ++i) {
symbObjects.push_back(state.symbolics[i].second);
}
if (!solver->getInitialValues(state, symbObjects, concreteObjects)) {
return false;
}
//Add the concrete values to the current state
for (unsigned i=0; i<symbObjects.size(); ++i) {
state.concolics.add(symbObjects[i], concreteObjects[i]);
}
state.speculative = false;
return true;
}
Executor::StatePair
Executor::fork(ExecutionState ¤t, ref<Expr> condition, bool isInternal) {
condition = simplifyExpr(current, condition);
Solver::Validity res;
std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
seedMap.find(¤t);
bool isSeeding = it != seedMap.end();
if (!isSeeding && !isa<ConstantExpr>(condition) &&
(MaxStaticForkPct!=1. || MaxStaticSolvePct != 1. ||
MaxStaticCPForkPct!=1. || MaxStaticCPSolvePct != 1.) &&
statsTracker->elapsed() > 60.) {
StatisticManager &sm = *theStatisticManager;
CallPathNode *cpn = current.stack.back().callPathNode;
if ((MaxStaticForkPct<1. &&
sm.getIndexedValue(stats::forks, sm.getIndex()) >
stats::forks*MaxStaticForkPct) ||
(MaxStaticCPForkPct<1. &&
cpn && (cpn->statistics.getValue(stats::forks) >
stats::forks*MaxStaticCPForkPct)) ||
(MaxStaticSolvePct<1 &&
sm.getIndexedValue(stats::solverTime, sm.getIndex()) >
stats::solverTime*MaxStaticSolvePct) ||
(MaxStaticCPForkPct<1. &&
cpn && (cpn->statistics.getValue(stats::solverTime) >
stats::solverTime*MaxStaticCPSolvePct))) {
ref<ConstantExpr> value;
bool success = solver->getValue(current, condition, value);
assert(success && "FIXME: Unhandled solver failure");
(void) success;
addConstraint(current, EqExpr::create(value, condition));
condition = value;
}
}
double timeout = stpTimeout;
if (isSeeding)
timeout *= it->second.size();
solver->setTimeout(timeout);
bool success = solver->evaluate(current, condition, res);
solver->setTimeout(0);
if (!success) {
current.pc = current.prevPC;
std::stringstream ss;
ss << "Query timed out on condition " << condition;
terminateStateEarly(current, ss.str());
return StatePair(0, 0);
}
if (!isSeeding) {
if (replayPath && !isInternal) {
assert(replayPosition<replayPath->size() &&
"ran out of branches in replay path mode");
bool branch = (*replayPath)[replayPosition++];
if (res==Solver::True) {
assert(branch && "hit invalid branch in replay path mode");
} else if (res==Solver::False) {
assert(!branch && "hit invalid branch in replay path mode");
} else {
// add constraints
if(branch) {
res = Solver::True;
addConstraint(current, condition);
} else {
res = Solver::False;