forked from klee/klee
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathExecutor.cpp
More file actions
7888 lines (6902 loc) · 282 KB
/
Executor.cpp
File metadata and controls
7888 lines (6902 loc) · 282 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
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 "Executor.h"
#include "AddressSpace.h"
#include "ConstructStorage.h"
#include "CoreStats.h"
#include "DistanceCalculator.h"
#include "ExecutionState.h"
#include "ExternalDispatcher.h"
#if LLVM_VERSION_CODE <= LLVM_VERSION(14, 0)
#include "GetElementPtrTypeIterator.h"
#endif
#include "ImpliedValue.h"
#include "Memory.h"
#include "MemoryManager.h"
#include "PForest.h"
#include "PTree.h"
#include "Searcher.h"
#include "SeedInfo.h"
#include "SpecialFunctionHandler.h"
#include "StatsTracker.h"
#include "TargetCalculator.h"
#include "TargetManager.h"
#include "TargetedExecutionManager.h"
#include "TimingSolver.h"
#include "UserSearcher.h"
#include "klee/ADT/Bits.h"
#include "klee/ADT/SparseStorage.h"
#include "klee/Core/Context.h"
#include "klee/ADT/KTest.h"
#include "klee/Config/Version.h"
#include "klee/Config/config.h"
#include "klee/Core/Interpreter.h"
#include "klee/Core/MockBuilder.h"
#include "klee/Core/TerminationTypes.h"
#include "klee/Expr/ArrayExprOptimizer.h"
#include "klee/Expr/ArrayExprVisitor.h"
#include "klee/Expr/Assignment.h"
#include "klee/Expr/Constraints.h"
#include "klee/Expr/Expr.h"
#include "klee/Expr/ExprHashMap.h"
#include "klee/Expr/ExprPPrinter.h"
#include "klee/Expr/ExprSMTLIBPrinter.h"
#include "klee/Expr/ExprUtil.h"
#include "klee/Expr/SymbolicSource.h"
#include "klee/Expr/Symcrete.h"
#include "klee/Module/Cell.h"
#include "klee/Module/CodeGraphInfo.h"
#include "klee/Module/KCallable.h"
#include "klee/Module/KInstruction.h"
#include "klee/Module/KModule.h"
#include "klee/Module/SarifReport.h"
#include "klee/Solver/Common.h"
#include "klee/Solver/Solver.h"
#include "klee/Solver/SolverCmdLine.h"
#include "klee/Statistics/TimerStatIncrementer.h"
#include "klee/Support/Casting.h"
#include "klee/Support/ErrorHandling.h"
#include "klee/Support/FileHandling.h"
#include "klee/Support/ModuleUtil.h"
#include "klee/Support/OptionCategories.h"
#include "klee/Support/RoundingModeUtil.h"
#include "klee/System/MemoryUsage.h"
#include "klee/System/Time.h"
#include "CodeEvent.h"
#include "CodeLocation.h"
#include "EventRecorder.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#if LLVM_VERSION_CODE >= LLVM_VERSION(15, 0)
#include "llvm/IR/GetElementPtrTypeIterator.h"
#endif
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TypeSize.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cinttypes>
#include <cstdint>
#include <cstring>
#include <cxxabi.h>
#include <iosfwd>
#include <iostream>
#include <sys/mman.h>
#include <sys/resource.h>
#include <type_traits>
#include <utility>
#include <vector>
#ifdef HAVE_CTYPE_EXTERNALS
#include <ctype.h>
#endif
using namespace llvm;
using namespace klee;
namespace klee {
cl::OptionCategory ExecCat("Execution option",
"These options configure execution.");
cl::OptionCategory DebugCat("Debugging options",
"These are debugging options.");
cl::OptionCategory ExtCallsCat("External call policy options",
"These options impact external calls.");
cl::OptionCategory SeedingCat(
"Seeding options",
"These options are related to the use of seeds to start exploration.");
cl::OptionCategory TestGenCat("Test generation options",
"These options impact test generation.");
cl::OptionCategory LazyInitCat("Lazy initialization option",
"These options configure lazy initialization.");
cl::opt<bool> MergedPointerDereference(
"use-merged-pointer-dereference", cl::init(false),
cl::desc("Enable merged pointer dereference (default=false)"),
cl::cat(ExecCat));
cl::opt<bool>
AlignSymbolicPointers("align-symbolic-pointers",
cl::desc("Makes symbolic pointers aligned according"
"to the used type system (default=false)"),
cl::init(false), cl::cat(ExecCat));
cl::opt<bool>
ExternCallsCanReturnNull("extern-calls-can-return-null", cl::init(false),
cl::desc("Enable case when extern call can crash "
"and return null (default=false)"),
cl::cat(ExecCat));
cl::opt<size_t> OSCopySizeMemoryCheckThreshold(
"os-copy-size-mem-check-threshold", cl::init(30000),
cl::desc("Check memory usage when this amount of bytes dense OS is copied"),
cl::cat(ExecCat));
cl::opt<size_t> StackCopySizeMemoryCheckThreshold(
"stack-copy-size-mem-check-threshold", cl::init(30000),
cl::desc("Check memory usage when state with stack this big (in bytes) is "
"copied"),
cl::cat(ExecCat));
namespace {
/*** Lazy initialization options ***/
enum class LazyInitializationPolicy {
None,
Only,
All,
};
cl::opt<LazyInitializationPolicy> LazyInitialization(
"use-lazy-initialization",
cl::values(clEnumValN(LazyInitializationPolicy::None, "none",
"Disable lazy initialization."),
clEnumValN(LazyInitializationPolicy::Only, "only",
"Only lazy initilization without resolving."),
clEnumValN(LazyInitializationPolicy::All, "all",
"Enable lazy initialization (default).")),
cl::init(LazyInitializationPolicy::All), cl::cat(LazyInitCat));
llvm::cl::opt<bool> UseSymbolicSizeLazyInit(
"use-sym-size-li",
llvm::cl::desc(
"Allows lazy initialize symbolic size objects (default false)"),
llvm::cl::init(false), llvm::cl::cat(LazyInitCat));
llvm::cl::opt<unsigned> MinElementSizeLazyInit(
"min-element-size-li",
llvm::cl::desc("Minimum size of an element of array for one lazy "
"initialization (default 4)"),
llvm::cl::init(4), llvm::cl::cat(LazyInitCat));
llvm::cl::opt<unsigned> MinNumberElementsLazyInit(
"min-number-elements-li",
llvm::cl::desc("Minimum number of array elements for one lazy "
"initialization (default 4)"),
llvm::cl::init(4), llvm::cl::cat(LazyInitCat));
} // namespace
cl::opt<std::string> FunctionCallReproduce(
"function-call-reproduce", cl::init(""),
cl::desc("Marks mentioned function as target for error-guided mode."),
cl::cat(ExecCat));
llvm::cl::opt<bool> X86FPAsX87FP80(
"x86FP-as-x87FP80", cl::init(false),
cl::desc("Convert X86 fp values to X87FP80 during computation according to "
"GCC behavior (default=false)"),
cl::cat(ExecCat));
cl::opt<HaltExecution::Reason> DumpStatesOnHalt(
"dump-states-on-halt", cl::init(HaltExecution::Reason::Unspecified),
cl::values(
clEnumValN(HaltExecution::Reason::NotHalt, "none",
"Do not dump test cases for all active states on exit."),
clEnumValN(HaltExecution::Reason::Unspecified, "all",
"Dump test cases for all active states on exit (default)")),
cl::cat(TestGenCat));
} // namespace klee
namespace {
/*** Test generation options ***/
cl::opt<bool> OnlyOutputStatesCoveringNew(
"only-output-states-covering-new", cl::init(false),
cl::desc("Only output test cases covering new code (default=false)"),
cl::cat(TestGenCat));
cl::opt<bool> EmitAllErrors(
"emit-all-errors", cl::init(false),
cl::desc("Generate tests cases for all errors "
"(default=false, i.e. one per (error,instruction) pair)"),
cl::cat(TestGenCat));
cl::opt<bool> CoverOnTheFly(
"cover-on-the-fly", cl::init(false),
cl::desc("Generate tests cases for each new covered block or branch "
"(default=false)"),
cl::cat(TestGenCat));
cl::opt<bool> MemoryTriggerCoverOnTheFly(
"mem-trigger-cof", cl::init(false),
cl::desc("Start on the fly tests generation after approaching memory cup"
"(default=false)"),
cl::cat(TestGenCat));
cl::opt<std::string> DelayCoverOnTheFly(
"delay-cover-on-the-fly", cl::init("0s"),
cl::desc("Start on the fly tests generation after the specified duration. "
"Set to 0s to disable (default=0s)"),
cl::cat(TestGenCat));
cl::opt<unsigned> UninitMemoryTestMultiplier(
"uninit-memory-test-multiplier", cl::init(6),
cl::desc("Generate additional number of duplicate tests due to "
"irreproducibility of uninitialized memory "
"(default=6)"),
cl::cat(TestGenCat));
/* Constraint solving options */
cl::opt<unsigned> MaxSymArraySize(
"max-sym-array-size",
cl::desc(
"If a symbolic array exceeds this size (in bytes), symbolic addresses "
"into this array are concretized. Set to 0 to disable (default=0)"),
cl::init(0), cl::cat(SolvingCat));
cl::opt<bool>
SimplifySymIndices("simplify-sym-indices", cl::init(true),
cl::desc("Simplify symbolic accesses using equalities "
"from other constraints (default=true)"),
cl::cat(SolvingCat));
cl::opt<bool>
EqualitySubstitution("equality-substitution", cl::init(true),
cl::desc("Simplify equality expressions before "
"querying the solver (default=true)"),
cl::cat(SolvingCat));
cl::opt<bool> OnlyOutputMakeSymbolicArrays(
"only-output-make-symbolic-arrays", cl::init(false),
cl::desc(
"Only output test data with klee_make_symbolic source (default=false)"),
cl::cat(TestGenCat));
/*** External call policy options ***/
enum class ExternalCallPolicy {
None, // No external calls allowed
Concrete, // Only external calls with concrete arguments allowed
All, // All external calls allowed, symbolic arguments concretized
OverApprox, // All external calls allowed, symbolic inputs are not constrained
// by the call
};
cl::opt<ExternalCallPolicy> ExternalCalls(
"external-calls", cl::desc("Specify the external call policy"),
cl::values(
clEnumValN(
ExternalCallPolicy::None, "none",
"No external function calls are allowed. Note that KLEE always "
"allows some external calls with concrete arguments to go through "
"(in particular printf and puts), regardless of this option."),
clEnumValN(ExternalCallPolicy::Concrete, "concrete",
"Only external function calls with concrete arguments are "
"allowed (default)"),
clEnumValN(ExternalCallPolicy::All, "all",
"All external function calls are allowed. This concretizes "
"any symbolic arguments in calls to external functions."),
clEnumValN(ExternalCallPolicy::OverApprox, "over-approx",
"All external function calls are allowed. This concretizes "
"any symbolic arguments in calls to external functions but"
"the concretization is ignored after the call (see docs).")),
cl::init(ExternalCallPolicy::Concrete), cl::cat(ExtCallsCat));
/*** External call warnings options ***/
enum class ExtCallWarnings {
None, // Never warn on external calls
OncePerFunction, // Only warn once per function on external calls
All, // Always warn on external calls
};
cl::opt<ExtCallWarnings> ExternalCallWarnings(
"external-call-warnings",
cl::desc("Specify when to warn about external calls"),
cl::values(clEnumValN(ExtCallWarnings::None, "none", "Never warn"),
clEnumValN(ExtCallWarnings::OncePerFunction, "once-per-function",
"Warn once per external function (default)"),
clEnumValN(ExtCallWarnings::All, "all", "Always warn")),
cl::init(ExtCallWarnings::OncePerFunction), cl::cat(ExtCallsCat));
/*** Seeding options ***/
cl::opt<bool> AlwaysOutputSeeds(
"always-output-seeds", cl::init(true),
cl::desc(
"Dump test cases even if they are driven by seeds only (default=true)"),
cl::cat(SeedingCat));
cl::opt<bool> OnlyReplaySeeds(
"only-replay-seeds", cl::init(false),
cl::desc("Discard states that do not have a seed (default=false)."),
cl::cat(SeedingCat));
cl::opt<bool> OnlySeed("only-seed", cl::init(false),
cl::desc("Stop execution after seeding is done without "
"doing regular search (default=false)."),
cl::cat(SeedingCat));
cl::opt<bool>
AllowSeedExtension("allow-seed-extension", cl::init(false),
cl::desc("Allow extra (unbound) values to become "
"symbolic during seeding (default=false)."),
cl::cat(SeedingCat));
cl::opt<bool> ZeroSeedExtension(
"zero-seed-extension", cl::init(false),
cl::desc(
"Use zero-filled objects if matching seed not found (default=false)"),
cl::cat(SeedingCat));
cl::opt<bool> AllowSeedTruncation(
"allow-seed-truncation", cl::init(false),
cl::desc("Allow smaller buffers than in seeds (default=false)."),
cl::cat(SeedingCat));
cl::opt<bool> NamedSeedMatching(
"named-seed-matching", cl::init(false),
cl::desc("Use names to match symbolic objects to inputs (default=false)."),
cl::cat(SeedingCat));
cl::opt<std::string>
SeedTime("seed-time",
cl::desc("Amount of time to dedicate to seeds, before normal "
"search (default=0s (off))"),
cl::cat(SeedingCat));
/*** Debugging options ***/
/// The different query logging solvers that can switched on/off
enum PrintDebugInstructionsType {
STDERR_ALL, ///
STDERR_SRC,
STDERR_COMPACT,
FILE_ALL, ///
FILE_SRC, ///
FILE_COMPACT ///
};
llvm::cl::bits<PrintDebugInstructionsType> DebugPrintInstructions(
"debug-print-instructions",
llvm::cl::desc("Log instructions during execution."),
llvm::cl::values(
clEnumValN(STDERR_ALL, "all:stderr",
"Log all instructions to stderr "
"in format [src, inst_id, "
"llvm_inst]"),
clEnumValN(STDERR_SRC, "src:stderr",
"Log all instructions to stderr in format [src, inst_id]"),
clEnumValN(STDERR_COMPACT, "compact:stderr",
"Log all instructions to stderr in format [inst_id]"),
clEnumValN(FILE_ALL, "all:file",
"Log all instructions to file "
"instructions.txt in format [src, "
"inst_id, llvm_inst]"),
clEnumValN(FILE_SRC, "src:file",
"Log all instructions to file "
"instructions.txt in format [src, "
"inst_id]"),
clEnumValN(FILE_COMPACT, "compact:file",
"Log all instructions to file instructions.txt in format "
"[inst_id]")),
llvm::cl::CommaSeparated, cl::cat(DebugCat));
#ifdef HAVE_ZLIB_H
cl::opt<bool> DebugCompressInstructions(
"debug-compress-instructions", cl::init(false),
cl::desc(
"Compress the logged instructions in gzip format (default=false)."),
cl::cat(DebugCat));
#endif
cl::opt<bool> DebugCheckForImpliedValues(
"debug-check-for-implied-values", cl::init(false),
cl::desc("Debug the implied value optimization"), cl::cat(DebugCat));
bool allLeafsAreConstant(const ref<Expr> &expr) {
if (isa<klee::ConstantExpr>(expr)) {
return true;
}
if (isa<klee::ConstantPointerExpr>(expr)) {
return true;
}
if (!isa<SelectExpr>(expr)) {
return false;
}
const SelectExpr *sel = cast<SelectExpr>(expr);
std::vector<ref<Expr>> alternatives;
ArrayExprHelper::collectAlternatives(*sel, alternatives);
for (auto leaf : alternatives) {
if (!isa<klee::ConstantExpr>(leaf)) {
return false;
}
}
return true;
}
} // namespace
extern llvm::cl::opt<unsigned long> MaxConstantAllocationSize;
extern llvm::cl::opt<unsigned long> MaxSymbolicAllocationSize;
extern llvm::cl::opt<bool> UseSymbolicSizeAllocation;
extern llvm::cl::opt<TrackCoverageBy> TrackCoverage;
// XXX hack
extern "C" unsigned dumpStates, dumpPForest;
unsigned dumpStates = 0, dumpPForest = 0;
bool Interpreter::hasTargetForest() const { return false; }
const std::unordered_set<Intrinsic::ID> Executor::supportedFPIntrinsics = {
// Intrinsic::fabs and Intrinsic::fma handled individually because of thier
// presence in
// mainline KLEE
Intrinsic::sqrt, Intrinsic::maxnum, Intrinsic::minnum, Intrinsic::trunc,
Intrinsic::rint};
const std::unordered_set<Intrinsic::ID> Executor::modelledFPIntrinsics = {
Intrinsic::ceil, Intrinsic::copysign, Intrinsic::cos, Intrinsic::exp2,
Intrinsic::exp, Intrinsic::floor, Intrinsic::log10, Intrinsic::log2,
Intrinsic::log, Intrinsic::round, Intrinsic::sin};
Executor::Executor(LLVMContext &ctx, const InterpreterOptions &opts,
InterpreterHandler *ih)
: Interpreter(opts), interpreterHandler(ih), searcher(nullptr),
externalDispatcher(new ExternalDispatcher(ctx)), statsTracker(0),
pathWriter(0), symPathWriter(0),
specialFunctionHandler(0), timers{time::Span(TimerInterval)},
guidanceKind(opts.Guidance), codeGraphInfo(new CodeGraphInfo()),
distanceCalculator(new DistanceCalculator(*codeGraphInfo)),
targetCalculator(new TargetCalculator(*codeGraphInfo)),
targetManager(new TargetManager(guidanceKind, *distanceCalculator,
*targetCalculator)),
targetedExecutionManager(
new TargetedExecutionManager(*codeGraphInfo, *targetManager)),
replayKTest(0), replayPath(0), usingSeeds(0), atMemoryLimit(false),
inhibitForking(false), coverOnTheFly(false),
haltExecution(HaltExecution::NotHalt), ivcEnabled(false),
debugLogBuffer(debugBufferString), sarifReport({}) {
objectManager = std::make_unique<ObjectManager>();
seedMap = std::make_unique<SeedMap>();
objectManager->addSubscriber(seedMap.get());
// Add first entry for single run
sarifReport.version = "2.1.0";
sarifReport.runs.push_back(RunJson{{}, ih->info()});
if (interpreterOpts.MockStrategy == MockStrategyKind::Deterministic &&
CoreSolverToUse != Z3_SOLVER) {
klee_error("Deterministic mocks can be generated with Z3 solver only.\n");
}
if (interpreterOpts.MockStrategy == MockStrategyKind::Deterministic &&
interpreterOpts.Mock != MockPolicy::All) {
klee_error("Deterministic mocks can be generated only with "
"`--mock-policy=all`.\n");
}
const time::Span maxTime{MaxTime};
if (maxTime)
timers.add(std::make_unique<Timer>(maxTime, [&] {
klee_message("HaltTimer invoked");
setHaltExecution(HaltExecution::MaxTime);
}));
if (CoverOnTheFly && guidanceKind != GuidanceKind::ErrorGuidance) {
const time::Span delayTime{DelayCoverOnTheFly};
if (delayTime)
timers.add(
std::make_unique<Timer>(delayTime, [&] { coverOnTheFly = true; }));
}
coreSolverTimeout = time::Span{MaxCoreSolverTime};
if (coreSolverTimeout)
UseForkedCoreSolver = true;
std::unique_ptr<Solver> coreSolver = klee::createCoreSolver(CoreSolverToUse);
if (!coreSolver) {
klee_error("Failed to create core solver\n");
}
memory = std::make_unique<MemoryManager>();
std::unique_ptr<Solver> solver = constructSolverChain(
std::move(coreSolver),
interpreterHandler->getOutputFilename(ALL_QUERIES_SMT2_FILE_NAME),
interpreterHandler->getOutputFilename(SOLVER_QUERIES_SMT2_FILE_NAME),
interpreterHandler->getOutputFilename(ALL_QUERIES_KQUERY_FILE_NAME),
interpreterHandler->getOutputFilename(SOLVER_QUERIES_KQUERY_FILE_NAME));
this->solver = std::make_unique<TimingSolver>(std::move(solver), optimizer,
EqualitySubstitution);
initializeSearchOptions();
if (DebugPrintInstructions.isSet(FILE_ALL) ||
DebugPrintInstructions.isSet(FILE_COMPACT) ||
DebugPrintInstructions.isSet(FILE_SRC)) {
std::string debug_file_name =
interpreterHandler->getOutputFilename("instructions.txt");
std::string error;
#ifdef HAVE_ZLIB_H
if (!DebugCompressInstructions) {
#endif
debugInstFile = klee_open_output_file(debug_file_name, error);
#ifdef HAVE_ZLIB_H
} else {
debug_file_name.append(".gz");
debugInstFile = klee_open_compressed_output_file(debug_file_name, error);
}
#endif
if (!debugInstFile) {
klee_error("Could not open file %s : %s", debug_file_name.c_str(),
error.c_str());
}
}
}
llvm::Module *Executor::setModule(
std::vector<std::unique_ptr<llvm::Module>> &userModules,
std::vector<std::unique_ptr<llvm::Module>> &libsModules,
const ModuleOptions &opts, std::set<std::string> &&mainModuleFunctions,
std::set<std::string> &&mainModuleGlobals, FLCtoOpcode &&origInstructions,
const std::set<std::string> &ignoredExternals,
std::vector<std::pair<std::string, std::string>> redefinitions) {
assert(!kmodule && !userModules.empty() &&
"can only register one module"); // XXX gross
kmodule = std::make_unique<KModule>();
// 1.) Link the modules together && 2.) Apply different instrumentation
kmodule->link(userModules, 1);
kmodule->instrument(opts);
kmodule->link(libsModules, 2);
kmodule->instrument(opts);
{
std::vector<std::unique_ptr<llvm::Module>> modules;
// Link with KLEE intrinsics library before running any optimizations
SmallString<128> LibPath(opts.LibraryDir);
llvm::sys::path::append(LibPath, "libkleeRuntimeIntrinsic" +
opts.OptSuffix + ".bca");
std::string error;
if (!klee::loadFileAsOneModule(
LibPath.c_str(), kmodule->module->getContext(), modules, error)) {
klee_error("Could not load KLEE intrinsic file %s", LibPath.c_str());
}
kmodule->link(modules, 2);
kmodule->instrument(opts);
}
if (interpreterOpts.Mock == MockPolicy::All ||
interpreterOpts.MockMutableGlobals == MockMutableGlobalsPolicy::All ||
!opts.AnnotationsFile.empty()) {
MockBuilder mockBuilder(kmodule->module.get(), opts, interpreterOpts,
ignoredExternals, redefinitions, interpreterHandler,
mainModuleFunctions, mainModuleGlobals);
std::unique_ptr<llvm::Module> mockModule = mockBuilder.build();
std::vector<std::unique_ptr<llvm::Module>> mockModules;
mockModules.push_back(std::move(mockModule));
// std::swap(mockModule, kmodule->module);
kmodule->link(mockModules, 1);
klee_message("Mock linkage: done");
for (auto &global : kmodule->module->globals()) {
if (global.isDeclaration()) {
llvm::Constant *zeroInitializer =
llvm::Constant::getNullValue(global.getValueType());
if (!zeroInitializer) {
klee_error("Unable to get zero initializer for '%s'",
global.getName().str().c_str());
}
global.setInitializer(zeroInitializer);
}
}
}
// 3.) Optimise and prepare for KLEE
// Create a list of functions that should be preserved if used
std::vector<const char *> preservedFunctions;
specialFunctionHandler = new SpecialFunctionHandler(*this);
specialFunctionHandler->prepare(preservedFunctions);
// Preserve the free-standing library calls
preservedFunctions.push_back("memset");
preservedFunctions.push_back("memcpy");
preservedFunctions.push_back("memcmp");
preservedFunctions.push_back("memmove");
if (FunctionCallReproduce != "") {
preservedFunctions.push_back(FunctionCallReproduce.c_str());
}
// prevent elimination of the preservedFunctions functions
for (auto pf : preservedFunctions) {
auto f = kmodule->module->getFunction(pf);
if (f) {
f->addFnAttr(Attribute::OptimizeNone);
f->addFnAttr(Attribute::NoInline);
}
}
// except the entry point
preservedFunctions.push_back(opts.EntryPoint.c_str());
kmodule->optimiseAndPrepare(opts, preservedFunctions);
kmodule->checkModule();
// 4.) Manifest the module
std::swap(kmodule->mainModuleFunctions, mainModuleFunctions);
std::swap(kmodule->mainModuleGlobals, mainModuleGlobals);
kmodule->manifest(interpreterHandler, StatsTracker::useStatistics());
kmodule->origInstructions = origInstructions;
specialFunctionHandler->bind();
if (StatsTracker::useStatistics() || userSearcherRequiresMD2U()) {
statsTracker = new StatsTracker(
*this, interpreterHandler->getOutputFilename("assembly.ll"),
userSearcherRequiresMD2U());
}
// Initialize the context.
DataLayout *TD = kmodule->targetData.get();
Context::initialize(TD->isLittleEndian(),
(Expr::Width)TD->getPointerSizeInBits());
return kmodule->module.get();
}
void Executor::setFunctionsByModule(FunctionsByModule &&fnsByModule) {
functionsByModule = std::forward<FunctionsByModule>(fnsByModule);
}
Executor::~Executor() {
delete externalDispatcher;
delete specialFunctionHandler;
delete statsTracker;
}
/***/
ref<Expr> X87FP80ToFPTrunc(ref<Expr> arg, [[maybe_unused]] Expr::Width type,
[[maybe_unused]] llvm::APFloat::roundingMode rm) {
ref<Expr> result = arg;
#ifdef ENABLE_FP
Expr::Width resultType = type;
if (Context::get().getPointerWidth() == 32 && arg->getWidth() == Expr::Fl80) {
result = FPTruncExpr::create(arg, resultType, rm);
}
#else
klee_message(
"You may enable x86-as-x87FP80 behaviour by passing the following options"
" to cmake:\n"
"\"-DENABLE_FLOATING_POINT=ON\"\n");
#endif
return result;
}
ref<Expr> FPToX87FP80Ext(ref<Expr> arg) {
ref<Expr> result = arg;
#ifdef ENABLE_FP
Expr::Width resultType = Expr::Fl80;
if (Context::get().getPointerWidth() == 32) {
result = FPExtExpr::create(arg, resultType);
}
#else
klee_message(
"You may enable x86-as-x87FP80 behaviour by passing the following options"
" to cmake:\n"
"\"-DENABLE_FLOATING_POINT=ON\"\n");
#endif
return result;
}
void Executor::initializeGlobalObject(ExecutionState &state, ObjectState *os,
const Constant *c, unsigned offset) {
const auto targetData = kmodule->targetData.get();
if (const 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());
if (offset) {
for (i = 0; i < size; i++)
os->write8(offset + i, (uint8_t)0);
} else {
os->initializeToZero();
}
} else if (const 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 (const 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 if (!isa<UndefValue>(c) && !isa<MetadataAsValue>(c)) {
unsigned StoreBits = targetData->getTypeStoreSizeInBits(c->getType());
ref<Expr> C = evalConstant(c, state.roundingMode);
if (c->getType()->isFloatingPointTy() &&
Context::get().getPointerWidth() == 32) {
C = X87FP80ToFPTrunc(C, getWidthForLLVMType(c->getType()),
state.roundingMode);
}
// Extend the constant if necessary;
assert(StoreBits >= C->getWidth() && "Invalid store size!");
if (StoreBits > C->getWidth())
C = ZExtExpr::create(C, StoreBits);
os->write(offset, C);
}
}
ObjectPair Executor::addExternalObjectAsNonStatic(ExecutionState &state,
unsigned size,
bool isReadOnly) {
auto mo = allocate(state, Expr::createPointer(size), false, true, nullptr, 8);
mo->isFixed = true;
auto os = bindObjectInState(state, mo, false);
os->setReadOnly(isReadOnly);
return ObjectPair{mo, os};
}
ObjectPair Executor::addExternalObject(ExecutionState &state, const void *addr,
unsigned size, bool isReadOnly) {
auto mo = memory->allocateFixed(reinterpret_cast<std::uint64_t>(addr), size,
nullptr);
ObjectState *os = bindObjectInState(state, mo, false);
ref<ConstantExpr> seg =
Expr::createPointer(reinterpret_cast<std::uint64_t>(addr));
for (unsigned i = 0; i < size; i++) {
ref<Expr> byte = ConstantExpr::create(((uint8_t *)addr)[i], Expr::Int8);
os->write(i, PointerExpr::create(seg, byte));
}
if (isReadOnly)
os->setReadOnly(true);
return {mo, os};
}
extern void *__dso_handle __attribute__((__weak__));
void Executor::initializeGlobals(ExecutionState &state) {
// 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
allocateGlobalObjects(state);
// initialize aliases first, may be needed for global objects
initializeGlobalAliases(state);
// finally, do the actual initialization
initializeGlobalObjects(state);
}
#ifdef HAVE_CTYPE_EXTERNALS
static const std::size_t kCTypeMemSize = 384;
static const std::size_t kCTypeMemOffset = 128;
template <typename F>
decltype(auto) Executor::addCTypeFixedObject(ExecutionState &state,
F objectProvider) {
using underlying_t = decltype(**objectProvider());
static_assert(std::is_integral_v<std::remove_reference_t<underlying_t>>,
"ctype structure expected to contain integral variables");
auto ctypeObj =
addExternalObject(state,
const_cast<void *>(reinterpret_cast<const void *>(
*objectProvider() - kCTypeMemOffset)),
kCTypeMemSize * sizeof(underlying_t), true);
auto ctypePointerObj = addExternalObject(
state, objectProvider(), Context::get().getPointerWidthInBytes(), true);
state.addressSpace
.getWriteable(ctypePointerObj.first, ctypePointerObj.second)
->write(0,
ConstantPointerExpr::create(
ctypeObj.first->getBaseExpr(),
AddExpr::create(ctypeObj.first->getBaseExpr(),
Expr::createPointer(kCTypeMemOffset *
sizeof(underlying_t)))));
return objectProvider();
}
template <typename F>
decltype(auto) Executor::addCTypeModelledObject(ExecutionState &state,
F objectProvider) {
using underlying_t = decltype(**objectProvider());
static_assert(std::is_integral_v<std::remove_reference_t<underlying_t>>,
"ctype structure expected to contain integral variables");
// Allocate memory
auto ctypeObj = addExternalObjectAsNonStatic(
state, kCTypeMemSize * sizeof(underlying_t), true);
auto ctypePointerObj = addExternalObjectAsNonStatic(
state, Context::get().getPointerWidthInBytes(), true);
// Write address of memory into pointer
state.addressSpace
.getWriteable(ctypePointerObj.first, ctypePointerObj.second)
->write(0, AddExpr::create(ctypeObj.first->getBaseExpr(),
Expr::createPointer(kCTypeMemOffset *
sizeof(underlying_t))));
// Write content from actiual ctype into modelled memory
ref<ConstantExpr> seg = cast<ConstantExpr>(ctypeObj.first->getBaseExpr());
auto addr =
reinterpret_cast<const uint8_t *>(*objectProvider() - kCTypeMemOffset);
for (unsigned i = 0; i < kCTypeMemSize * sizeof(underlying_t); i++) {
ref<Expr> byte = ConstantExpr::create(addr[i], Expr::Int8);
state.addressSpace.getWriteable(ctypeObj.first, ctypeObj.second)
->write(i, PointerExpr::create(seg, byte));
}
// Return address to pointer
return reinterpret_cast<decltype(objectProvider())>(
cast<ConstantExpr>(ctypePointerObj.first->getBaseExpr())->getZExtValue());
};
#endif
void Executor::allocateGlobalObjects(ExecutionState &state) {
Module *m = kmodule->module.get();
if (m->getModuleInlineAsm() != "")
klee_warning("executable has module level assembly (ignoring)");
// 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 (Function &f : *m) {
ref<ConstantPointerExpr> addr;
// 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().str())) {
addr = ConstantPointerExpr::create(Expr::createPointer(0),
Expr::createPointer(0));
} else {
// We allocate an object to represent each function,
// its address can be used for function pointers.
// TODO: Check whether the object is accessed?
const KFunction *kf = kmodule->functionMap.at(&f);
ref<CodeLocation> fCodeLocation = CodeLocation::create(
kf, kf->getSourceFilepath(), kf->getLine(), std::nullopt);
auto mo = allocate(state, Expr::createPointer(8), false, true,
fCodeLocation, 8);
auto baseExpr = cast<ConstantExpr>(mo->getBaseExpr());
addr = ConstantPointerExpr::create(baseExpr, baseExpr);
legalFunctions.emplace(baseExpr->getZExtValue(), &f);
}
globalAddresses.emplace(&f, addr);
}
#ifndef WINDOWS
const MemoryObject *errnoObj = nullptr;
if (Context::get().getPointerWidth() == 32) {
errnoObj =
addExternalObjectAsNonStatic(state, sizeof(*errno_addr), false).first;
errno_addr = reinterpret_cast<int *>(
cast<ConstantExpr>(errnoObj->getBaseExpr())->getZExtValue());
} else {
errno_addr = getErrnoLocation();
errnoObj =
addExternalObject(state, (void *)errno_addr, sizeof *errno_addr, false)
.first;
}
// Copy values from and to program space explicitly
const_cast<MemoryObject *>(errnoObj)->isUserSpecified = true;
#endif
// Disabled, we don't want to promote use of live externals.
#ifdef HAVE_CTYPE_EXTERNALS
#ifndef WINDOWS
#ifndef DARWIN
/* 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 */
// We assume that KLEE is running on 64-bit platform.
// Therefore, for 32-bit binaries we can not just use addresses
// of actual ctype* objects in memory.
// Hence, we need to model then in address space.
if (Context::get().getPointerWidth() == 32) {
c_type_b_loc_addr = addCTypeModelledObject(state, __ctype_b_loc);
c_type_tolower_addr = addCTypeModelledObject(state, __ctype_tolower_loc);
c_type_toupper_addr = addCTypeModelledObject(state, __ctype_toupper_loc);
} else {
c_type_b_loc_addr = addCTypeFixedObject(state, __ctype_b_loc);
c_type_tolower_addr = addCTypeFixedObject(state, __ctype_tolower_loc);
c_type_toupper_addr = addCTypeFixedObject(state, __ctype_toupper_loc);
}
#endif
#endif
#endif