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
|
//===-- SpecialFunctionHandler.cpp ----------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SpecialFunctionHandler.h"
#include "ExecutionState.h"
#include "Executor.h"
#include "Memory.h"
#include "MemoryManager.h"
#include "MergeHandler.h"
#include "Searcher.h"
#include "StatsTracker.h"
#include "TimingSolver.h"
#include "klee/Config/config.h"
#include "klee/Module/KInstruction.h"
#include "klee/Module/KModule.h"
#include "klee/Solver/SolverCmdLine.h"
#include "klee/Support/Casting.h"
#include "klee/Support/Debug.h"
#include "klee/Support/ErrorHandling.h"
#include "klee/Support/OptionCategories.h"
#include "klee/Support/CompilerWarning.h"
DISABLE_WARNING_PUSH
DISABLE_WARNING_DEPRECATED_DECLARATIONS
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
DISABLE_WARNING_POP
#include <array>
#include <cerrno>
#include <sstream>
using namespace llvm;
using namespace klee;
namespace {
cl::opt<bool>
ReadablePosix("readable-posix-inputs", cl::init(false),
cl::desc("Prefer creation of POSIX inputs (command-line "
"arguments, files, etc.) with human readable bytes. "
"Note: option is expensive when creating lots of "
"tests (default=false)"),
cl::cat(TestGenCat));
cl::opt<bool>
SilentKleeAssume("silent-klee-assume", cl::init(false),
cl::desc("Silently terminate paths with an infeasible "
"condition given to klee_assume rather than "
"emitting an error (default=false)"),
cl::cat(TerminationCat));
} // namespace
/// \todo Almost all of the demands in this file should be replaced
/// with terminateState calls.
///
// FIXME: We are more or less committed to requiring an intrinsic
// library these days. We can move some of this stuff there,
// especially things like realloc which have complicated semantics
// w.r.t. forking. Among other things this makes delayed query
// dispatch easier to implement.
static constexpr std::array handlerInfo = {
#define add(name, handler, ret) SpecialFunctionHandler::HandlerInfo{ name, \
&SpecialFunctionHandler::handler, \
false, ret, false }
#define addDNR(name, handler) SpecialFunctionHandler::HandlerInfo{ name, \
&SpecialFunctionHandler::handler, \
true, false, false }
addDNR("__assert_rtn", handleAssertFail),
addDNR("__assert_fail", handleAssertFail),
addDNR("__assert", handleAssertFail),
addDNR("_assert", handleAssert),
addDNR("abort", handleAbort),
addDNR("_exit", handleExit),
SpecialFunctionHandler::HandlerInfo{ "exit", &SpecialFunctionHandler::handleExit, true, false, true },
addDNR("klee_abort", handleAbort),
addDNR("klee_silent_exit", handleSilentExit),
addDNR("klee_report_error", handleReportError),
add("calloc", handleCalloc, true),
add("free", handleFree, false),
add("klee_assume", handleAssume, false),
add("klee_check_memory_access", handleCheckMemoryAccess, false),
add("klee_get_valuef", handleGetValue, true),
add("klee_get_valued", handleGetValue, true),
add("klee_get_valuel", handleGetValue, true),
add("klee_get_valuell", handleGetValue, true),
add("klee_get_value_i32", handleGetValue, true),
add("klee_get_value_i64", handleGetValue, true),
add("klee_define_fixed_object", handleDefineFixedObject, false),
add("klee_get_obj_size", handleGetObjSize, true),
add("klee_get_errno", handleGetErrno, true),
#ifndef __APPLE__
add("__errno_location", handleErrnoLocation, true),
#else
add("__error", handleErrnoLocation, true),
#endif
add("klee_is_symbolic", handleIsSymbolic, true),
add("klee_make_symbolic", handleMakeSymbolic, false),
add("klee_mark_global", handleMarkGlobal, false),
add("klee_open_merge", handleOpenMerge, false),
add("klee_close_merge", handleCloseMerge, false),
add("klee_prefer_cex", handlePreferCex, false),
add("klee_posix_prefer_cex", handlePosixPreferCex, false),
add("klee_print_expr", handlePrintExpr, false),
add("klee_print_range", handlePrintRange, false),
add("klee_set_forking", handleSetForking, false),
add("klee_stack_trace", handleStackTrace, false),
add("klee_warning", handleWarning, false),
add("klee_warning_once", handleWarningOnce, false),
add("malloc", handleMalloc, true),
add("memalign", handleMemalign, true),
add("realloc", handleRealloc, true),
#ifdef SUPPORT_KLEE_EH_CXX
add("_klee_eh_Unwind_RaiseException_impl", handleEhUnwindRaiseExceptionImpl, false),
add("klee_eh_typeid_for", handleEhTypeid, true),
#endif
// operator delete[](void*)
add("_ZdaPv", handleDeleteArray, false),
// operator delete(void*)
add("_ZdlPv", handleDelete, false),
// operator new[](unsigned int)
add("_Znaj", handleNewArray, true),
// operator new(unsigned int)
add("_Znwj", handleNew, true),
// FIXME-64: This is wrong for 64-bit long...
// operator new[](unsigned long)
add("_Znam", handleNewArray, true),
// operator new(unsigned long)
add("_Znwm", handleNew, true),
#undef addDNR
#undef add
};
SpecialFunctionHandler::SpecialFunctionHandler(Executor &_executor)
: executor(_executor) {}
void SpecialFunctionHandler::prepare(
std::vector<const char *> &preservedFunctions) {
for (auto &hi : handlerInfo) {
Function *f = executor.kmodule->module->getFunction(hi.name);
// No need to create if the function doesn't exist, since it cannot
// be called in that case.
if (f && (!hi.doNotOverride || f->isDeclaration())) {
preservedFunctions.push_back(hi.name);
// Make sure NoReturn attribute is set, for optimization and
// coverage counting.
if (hi.doesNotReturn)
f->addFnAttr(Attribute::NoReturn);
// Change to a declaration since we handle internally (simplifies
// module and allows deleting dead code).
if (!f->isDeclaration())
f->deleteBody();
}
}
}
void SpecialFunctionHandler::bind() {
for (auto &hi : handlerInfo) {
Function *f = executor.kmodule->module->getFunction(hi.name);
if (f && (!hi.doNotOverride || f->isDeclaration()))
handlers[f] = std::make_pair(hi.handler, hi.hasReturnValue);
}
}
bool SpecialFunctionHandler::handle(ExecutionState &state,
Function *f,
KInstruction *target,
std::vector< ref<Expr> > &arguments) {
handlers_ty::iterator it = handlers.find(f);
if (it != handlers.end()) {
Handler h = it->second.first;
bool hasReturnValue = it->second.second;
// FIXME: Check this... add test?
if (!hasReturnValue && !target->inst->use_empty()) {
executor.terminateStateOnExecError(state,
"expected return value from void special function");
} else {
(this->*h)(state, target, arguments);
}
return true;
} else {
return false;
}
}
/****/
// reads a concrete string from memory
std::string
SpecialFunctionHandler::readStringAtAddress(ExecutionState &state,
ref<Expr> addressExpr) {
ObjectPair op;
addressExpr = executor.toUnique(state, addressExpr);
if (!isa<ConstantExpr>(addressExpr)) {
executor.terminateStateOnUserError(
state, "Symbolic string pointer passed to one of the klee_ functions");
return "";
}
ref<ConstantExpr> address = cast<ConstantExpr>(addressExpr);
if (!state.addressSpace.resolveOne(address, op)) {
executor.terminateStateOnUserError(
state, "Invalid string pointer passed to one of the klee_ functions");
return "";
}
const MemoryObject *mo = op.first;
const ObjectState *os = op.second;
auto relativeOffset = mo->getOffsetExpr(address);
// the relativeOffset must be concrete as the address is concrete
size_t offset = cast<ConstantExpr>(relativeOffset)->getZExtValue();
std::ostringstream buf;
char c = 0;
for (size_t i = offset; i < mo->size; ++i) {
ref<Expr> cur = os->read8(i);
cur = executor.toUnique(state, cur);
assert(isa<ConstantExpr>(cur) &&
"hit symbolic char while reading concrete string");
c = cast<ConstantExpr>(cur)->getZExtValue(8);
if (c == '\0') {
// we read the whole string
break;
}
buf << c;
}
if (c != '\0') {
klee_warning_once(0, "String not terminated by \\0 passed to "
"one of the klee_ functions");
}
return buf.str();
}
/****/
void SpecialFunctionHandler::handleAbort(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 0 && "invalid number of arguments to abort");
executor.terminateStateOnProgramError(state, "abort failure",
StateTerminationType::Abort);
}
void SpecialFunctionHandler::handleExit(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 1 && "invalid number of arguments to exit");
executor.terminateStateOnExit(state);
}
void SpecialFunctionHandler::handleSilentExit(
ExecutionState &state, KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 1 && "invalid number of arguments to exit");
executor.terminateStateEarlyUser(state, "");
}
void SpecialFunctionHandler::handleAssert(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 3 && "invalid number of arguments to _assert");
executor.terminateStateOnProgramError(
state, "ASSERTION FAIL: " + readStringAtAddress(state, arguments[0]),
StateTerminationType::Assert);
}
void SpecialFunctionHandler::handleAssertFail(
ExecutionState &state, KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 4 &&
"invalid number of arguments to __assert_fail");
executor.terminateStateOnProgramError(
state, "ASSERTION FAIL: " + readStringAtAddress(state, arguments[0]),
StateTerminationType::Assert);
}
void SpecialFunctionHandler::handleReportError(
ExecutionState &state, KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 4 &&
"invalid number of arguments to klee_report_error");
// arguments[0,1,2,3] are file, line, message, suffix
executor.terminateStateOnProgramError(
state, readStringAtAddress(state, arguments[2]),
StateTerminationType::ReportError, "",
readStringAtAddress(state, arguments[3]).c_str());
}
void SpecialFunctionHandler::handleOpenMerge(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
if (!UseMerge) {
klee_warning_once(0, "klee_open_merge ignored, use '-use-merge'");
return;
}
state.openMergeStack.push_back(
ref<MergeHandler>(new MergeHandler(&executor, &state)));
if (DebugLogMerge)
llvm::errs() << "open merge: " << &state << "\n";
}
void SpecialFunctionHandler::handleCloseMerge(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
if (!UseMerge) {
klee_warning_once(0, "klee_close_merge ignored, use '-use-merge'");
return;
}
Instruction *i = target->inst;
if (DebugLogMerge)
llvm::errs() << "close merge: " << &state << " at [" << *i << "]\n";
if (state.openMergeStack.empty()) {
std::ostringstream warning;
warning << &state << " ran into a close at " << i << " without a preceding open";
klee_warning("%s", warning.str().c_str());
} else {
assert(executor.mergingSearcher->inCloseMerge.find(&state) ==
executor.mergingSearcher->inCloseMerge.end() &&
"State cannot run into close_merge while being closed");
executor.mergingSearcher->inCloseMerge.insert(&state);
state.openMergeStack.back()->addClosedState(&state, i);
state.openMergeStack.pop_back();
}
}
void SpecialFunctionHandler::handleNew(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 && "invalid number of arguments to new");
executor.executeAlloc(state, arguments[0], false, target);
}
void SpecialFunctionHandler::handleDelete(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// FIXME: Should check proper pairing with allocation type (malloc/free,
// new/delete, new[]/delete[]).
// XXX should type check args
assert(arguments.size()==1 && "invalid number of arguments to delete");
executor.executeFree(state, arguments[0]);
}
void SpecialFunctionHandler::handleNewArray(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 && "invalid number of arguments to new[]");
executor.executeAlloc(state, arguments[0], false, target);
}
void SpecialFunctionHandler::handleDeleteArray(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 && "invalid number of arguments to delete[]");
executor.executeFree(state, arguments[0]);
}
void SpecialFunctionHandler::handleMalloc(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 && "invalid number of arguments to malloc");
executor.executeAlloc(state, arguments[0], false, target);
}
void SpecialFunctionHandler::handleMemalign(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr>> &arguments) {
if (arguments.size() != 2) {
executor.terminateStateOnUserError(state,
"Incorrect number of arguments to memalign(size_t alignment, size_t size)");
return;
}
std::pair<ref<Expr>, ref<Expr>> alignmentRangeExpr =
executor.solver->getRange(state.constraints, arguments[0],
state.queryMetaData);
ref<Expr> alignmentExpr = alignmentRangeExpr.first;
auto alignmentConstExpr = dyn_cast<ConstantExpr>(alignmentExpr);
if (!alignmentConstExpr) {
executor.terminateStateOnUserError(state, "Could not determine size of symbolic alignment");
return;
}
uint64_t alignment = alignmentConstExpr->getZExtValue();
// Warn, if the expression has more than one solution
if (alignmentRangeExpr.first != alignmentRangeExpr.second) {
klee_warning_once(
0, "Symbolic alignment for memalign. Choosing smallest alignment");
}
executor.executeAlloc(state, arguments[1], false, target, false, 0,
alignment);
}
#ifdef SUPPORT_KLEE_EH_CXX
void SpecialFunctionHandler::handleEhUnwindRaiseExceptionImpl(
ExecutionState &state, KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 1 &&
"invalid number of arguments to _klee_eh_Unwind_RaiseException_impl");
ref<ConstantExpr> exceptionObject = dyn_cast<ConstantExpr>(arguments[0]);
if (!exceptionObject.get()) {
executor.terminateStateOnExecError(state, "Internal error: Symbolic exception pointer");
return;
}
if (isa_and_nonnull<SearchPhaseUnwindingInformation>(
state.unwindingInformation.get())) {
executor.terminateStateOnExecError(
state,
"Internal error: Unwinding restarted during an ongoing search phase");
return;
}
state.unwindingInformation =
std::make_unique<SearchPhaseUnwindingInformation>(exceptionObject,
state.stack.size() - 1);
executor.unwindToNextLandingpad(state);
}
void SpecialFunctionHandler::handleEhTypeid(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr>> &arguments) {
assert(arguments.size() == 1 &&
"invalid number of arguments to klee_eh_typeid_for");
executor.bindLocal(target, state, executor.getEhTypeidFor(arguments[0]));
}
#endif // SUPPORT_KLEE_EH_CXX
void SpecialFunctionHandler::handleAssume(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 && "invalid number of arguments to klee_assume");
ref<Expr> e = arguments[0];
if (e->getWidth() != Expr::Bool)
e = NeExpr::create(e, ConstantExpr::create(0, e->getWidth()));
bool res;
bool success __attribute__((unused)) = executor.solver->mustBeFalse(
state.constraints, e, res, state.queryMetaData);
assert(success && "FIXME: Unhandled solver failure");
if (res) {
if (SilentKleeAssume) {
executor.terminateState(state);
} else {
executor.terminateStateOnUserError(
state, "invalid klee_assume call (provably false)");
}
} else {
executor.addConstraint(state, e);
}
}
void SpecialFunctionHandler::handleIsSymbolic(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 && "invalid number of arguments to klee_is_symbolic");
executor.bindLocal(target, state,
ConstantExpr::create(!isa<ConstantExpr>(arguments[0]),
Expr::Int32));
}
void SpecialFunctionHandler::handlePreferCex(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==2 &&
"invalid number of arguments to klee_prefex_cex");
ref<Expr> cond = arguments[1];
if (cond->getWidth() != Expr::Bool)
cond = NeExpr::create(cond, ConstantExpr::alloc(0, cond->getWidth()));
state.addCexPreference(cond);
}
void SpecialFunctionHandler::handlePosixPreferCex(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
if (ReadablePosix)
return handlePreferCex(state, target, arguments);
}
void SpecialFunctionHandler::handlePrintExpr(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==2 &&
"invalid number of arguments to klee_print_expr");
std::string msg_str = readStringAtAddress(state, arguments[0]);
llvm::errs() << msg_str << ":" << arguments[1] << "\n";
}
void SpecialFunctionHandler::handleSetForking(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 &&
"invalid number of arguments to klee_set_forking");
ref<Expr> value = executor.toUnique(state, arguments[0]);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(value)) {
state.forkDisabled = CE->isZero();
} else {
executor.terminateStateOnUserError(state, "klee_set_forking requires a constant arg");
}
}
void SpecialFunctionHandler::handleStackTrace(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
state.dumpStack(outs());
}
void SpecialFunctionHandler::handleWarning(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 && "invalid number of arguments to klee_warning");
std::string msg_str = readStringAtAddress(state, arguments[0]);
klee_warning("%s: %s", state.stack.back().kf->function->getName().data(),
msg_str.c_str());
}
void SpecialFunctionHandler::handleWarningOnce(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 &&
"invalid number of arguments to klee_warning_once");
std::string msg_str = readStringAtAddress(state, arguments[0]);
klee_warning_once(0, "%s: %s", state.stack.back().kf->function->getName().data(),
msg_str.c_str());
}
void SpecialFunctionHandler::handlePrintRange(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==2 &&
"invalid number of arguments to klee_print_range");
std::string msg_str = readStringAtAddress(state, arguments[0]);
llvm::errs() << msg_str << ":" << arguments[1];
if (!isa<ConstantExpr>(arguments[1])) {
// FIXME: Pull into a unique value method?
ref<ConstantExpr> value;
bool success __attribute__((unused)) = executor.solver->getValue(
state.constraints, arguments[1], value, state.queryMetaData);
assert(success && "FIXME: Unhandled solver failure");
bool res;
success = executor.solver->mustBeTrue(state.constraints,
EqExpr::create(arguments[1], value),
res, state.queryMetaData);
assert(success && "FIXME: Unhandled solver failure");
if (res) {
llvm::errs() << " == " << value;
} else {
llvm::errs() << " ~= " << value;
std::pair<ref<Expr>, ref<Expr>> res = executor.solver->getRange(
state.constraints, arguments[1], state.queryMetaData);
llvm::errs() << " (in [" << res.first << ", " << res.second <<"])";
}
}
llvm::errs() << "\n";
}
void SpecialFunctionHandler::handleGetObjSize(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 &&
"invalid number of arguments to klee_get_obj_size");
Executor::ExactResolutionList rl;
executor.resolveExact(state, arguments[0], rl, "klee_get_obj_size");
for (Executor::ExactResolutionList::iterator it = rl.begin(),
ie = rl.end(); it != ie; ++it) {
executor.bindLocal(
target, *it->second,
ConstantExpr::create(it->first.first->size,
executor.kmodule->targetData->getTypeSizeInBits(
target->inst->getType())));
}
}
void SpecialFunctionHandler::handleGetErrno(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==0 &&
"invalid number of arguments to klee_get_errno");
#ifndef WINDOWS
int *errno_addr = executor.getErrnoLocation(state);
#else
int *errno_addr = nullptr;
#endif
// Retrieve the memory object of the errno variable
ObjectPair result;
bool resolved = state.addressSpace.resolveOne(
ConstantExpr::create((uint64_t)errno_addr, Expr::Int64), result);
if (!resolved)
executor.terminateStateOnUserError(state, "Could not resolve address for errno");
executor.bindLocal(target, state, result.second->read(0, Expr::Int32));
}
void SpecialFunctionHandler::handleErrnoLocation(
ExecutionState &state, KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// Returns the address of the errno variable
assert(arguments.size() == 0 &&
"invalid number of arguments to __errno_location/__error");
#ifndef WINDOWS
int *errno_addr = executor.getErrnoLocation(state);
#else
int *errno_addr = nullptr;
#endif
executor.bindLocal(
target, state,
ConstantExpr::create((uint64_t)errno_addr,
executor.kmodule->targetData->getTypeSizeInBits(
target->inst->getType())));
}
void SpecialFunctionHandler::handleCalloc(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==2 &&
"invalid number of arguments to calloc");
ref<Expr> size = MulExpr::create(arguments[0],
arguments[1]);
executor.executeAlloc(state, size, false, target, true);
}
void SpecialFunctionHandler::handleRealloc(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==2 &&
"invalid number of arguments to realloc");
ref<Expr> address = arguments[0];
ref<Expr> size = arguments[1];
Executor::StatePair zeroSize =
executor.fork(state, Expr::createIsZero(size), true, BranchType::Realloc);
if (zeroSize.first) { // size == 0
executor.executeFree(*zeroSize.first, address, target);
}
if (zeroSize.second) { // size != 0
Executor::StatePair zeroPointer =
executor.fork(*zeroSize.second, Expr::createIsZero(address), true,
BranchType::Realloc);
if (zeroPointer.first) { // address == 0
executor.executeAlloc(*zeroPointer.first, size, false, target);
}
if (zeroPointer.second) { // address != 0
Executor::ExactResolutionList rl;
executor.resolveExact(*zeroPointer.second, address, rl, "realloc");
for (Executor::ExactResolutionList::iterator it = rl.begin(),
ie = rl.end(); it != ie; ++it) {
executor.executeAlloc(*it->second, size, false, target, false,
it->first.second);
}
}
}
}
void SpecialFunctionHandler::handleFree(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
// XXX should type check args
assert(arguments.size()==1 &&
"invalid number of arguments to free");
executor.executeFree(state, arguments[0]);
}
void SpecialFunctionHandler::handleCheckMemoryAccess(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> >
&arguments) {
assert(arguments.size()==2 &&
"invalid number of arguments to klee_check_memory_access");
ref<Expr> address = executor.toUnique(state, arguments[0]);
ref<Expr> size = executor.toUnique(state, arguments[1]);
if (!isa<ConstantExpr>(address) || !isa<ConstantExpr>(size)) {
executor.terminateStateOnUserError(state, "check_memory_access requires constant args");
} else {
ObjectPair op;
if (!state.addressSpace.resolveOne(cast<ConstantExpr>(address), op)) {
executor.terminateStateOnProgramError(
state, "check_memory_access: memory error", StateTerminationType::Ptr,
executor.getAddressInfo(state, address));
} else {
ref<Expr> chk =
op.first->getBoundsCheckPointer(address,
cast<ConstantExpr>(size)->getZExtValue());
if (!chk->isTrue()) {
executor.terminateStateOnProgramError(
state, "check_memory_access: memory error",
StateTerminationType::Ptr, executor.getAddressInfo(state, address));
}
}
}
}
void SpecialFunctionHandler::handleGetValue(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 &&
"invalid number of arguments to klee_get_value");
executor.executeGetValue(state, arguments[0], target);
}
void SpecialFunctionHandler::handleDefineFixedObject(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==2 &&
"invalid number of arguments to klee_define_fixed_object");
assert(isa<ConstantExpr>(arguments[0]) &&
"expect constant address argument to klee_define_fixed_object");
assert(isa<ConstantExpr>(arguments[1]) &&
"expect constant size argument to klee_define_fixed_object");
uint64_t address = cast<ConstantExpr>(arguments[0])->getZExtValue();
uint64_t size = cast<ConstantExpr>(arguments[1])->getZExtValue();
MemoryObject *mo = executor.memory->allocateFixed(address, size, state.prevPC->inst);
executor.bindObjectInState(state, mo, false);
mo->isUserSpecified = true; // XXX hack;
}
void SpecialFunctionHandler::handleMakeSymbolic(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
std::string name;
if (arguments.size() != 3) {
executor.terminateStateOnUserError(state,
"Incorrect number of arguments to klee_make_symbolic(void*, size_t, char*)");
return;
}
name = arguments[2]->isZero() ? "" : readStringAtAddress(state, arguments[2]);
if (name.length() == 0) {
name = "unnamed";
klee_warning("klee_make_symbolic: renamed empty name to \"unnamed\"");
}
Executor::ExactResolutionList rl;
executor.resolveExact(state, arguments[0], rl, "make_symbolic");
for (Executor::ExactResolutionList::iterator it = rl.begin(),
ie = rl.end(); it != ie; ++it) {
const MemoryObject *mo = it->first.first;
mo->setName(name);
const ObjectState *old = it->first.second;
ExecutionState *s = it->second;
if (old->readOnly) {
executor.terminateStateOnUserError(*s, "cannot make readonly object symbolic");
return;
}
// FIXME: Type coercion should be done consistently somewhere.
bool res;
bool success __attribute__((unused)) = executor.solver->mustBeTrue(
s->constraints,
EqExpr::create(
ZExtExpr::create(arguments[1], Context::get().getPointerWidth()),
mo->getSizeExpr()),
res, s->queryMetaData);
assert(success && "FIXME: Unhandled solver failure");
if (res) {
executor.executeMakeSymbolic(*s, mo, name);
} else {
executor.terminateStateOnUserError(*s, "Wrong size given to klee_make_symbolic");
}
}
}
void SpecialFunctionHandler::handleMarkGlobal(ExecutionState &state,
KInstruction *target,
std::vector<ref<Expr> > &arguments) {
assert(arguments.size()==1 &&
"invalid number of arguments to klee_mark_global");
Executor::ExactResolutionList rl;
executor.resolveExact(state, arguments[0], rl, "mark_global");
for (Executor::ExactResolutionList::iterator it = rl.begin(),
ie = rl.end(); it != ie; ++it) {
const MemoryObject *mo = it->first.first;
assert(!mo->isLocal);
mo->isGlobal = true;
}
}
|