55#include "llvm/ADT/SmallPtrSet.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/IR/Attributes.h"
58#include "llvm/IR/BasicBlock.h"
59#if LLVM_VERSION_CODE < LLVM_VERSION(8, 0)
60#include "llvm/IR/CallSite.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DataLayout.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/Instructions.h"
66#include "llvm/IR/IntrinsicInst.h"
67#include "llvm/IR/LLVMContext.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/Operator.h"
70#include "llvm/Support/CommandLine.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/FileSystem.h"
73#include "llvm/Support/Path.h"
74#include "llvm/Support/Process.h"
75#if LLVM_VERSION_CODE >= LLVM_VERSION(10, 0)
76#include "llvm/Support/TypeSize.h"
78typedef unsigned TypeSize;
80#include "llvm/Support/raw_ostream.h"
101 "These are debugging options.");
104 "These options impact external calls.");
108 "These options are related to the use of seeds to start exploration.");
112 "These options control termination of the overall KLEE "
113 "execution and of individual states.");
116 "These options impact test generation.");
120 cl::desc(
"Halt execution after the specified duration. "
121 "Set to 0s to disable (default=0s)"),
130cl::opt<bool> DumpStatesOnHalt(
131 "dump-states-on-halt",
133 cl::desc(
"Dump test cases for all active states on exit (default=true)"),
136cl::opt<bool> OnlyOutputStatesCoveringNew(
137 "only-output-states-covering-new",
139 cl::desc(
"Only output test cases covering new code (default=false)"),
142cl::opt<bool> EmitAllErrors(
143 "emit-all-errors", cl::init(
false),
144 cl::desc(
"Generate tests cases for all errors "
145 "(default=false, i.e. one per (error,instruction) pair)"),
151cl::opt<unsigned> MaxSymArraySize(
152 "max-sym-array-size",
154 "If a symbolic array exceeds this size (in bytes), symbolic addresses "
155 "into this array are concretized. Set to 0 to disable (default=0)"),
160 SimplifySymIndices(
"simplify-sym-indices",
162 cl::desc(
"Simplify symbolic accesses using equalities "
163 "from other constraints (default=false)"),
167 EqualitySubstitution(
"equality-substitution", cl::init(
true),
168 cl::desc(
"Simplify equality expressions before "
169 "querying the solver (default=true)"),
175enum class ExternalCallPolicy {
181cl::opt<ExternalCallPolicy> ExternalCalls(
183 cl::desc(
"Specify the external call policy"),
186 ExternalCallPolicy::None,
"none",
187 "No external function calls are allowed. Note that KLEE always "
188 "allows some external calls with concrete arguments to go through "
189 "(in particular printf and puts), regardless of this option."),
190 clEnumValN(ExternalCallPolicy::Concrete,
"concrete",
191 "Only external function calls with concrete arguments are "
192 "allowed (default)"),
193 clEnumValN(ExternalCallPolicy::All,
"all",
194 "All external function calls are allowed. This concretizes "
195 "any symbolic arguments in calls to external functions.")),
196 cl::init(ExternalCallPolicy::Concrete),
199cl::opt<bool> SuppressExternalWarnings(
200 "suppress-external-warnings",
202 cl::desc(
"Supress warnings about calling external functions."),
205cl::opt<bool> AllExternalWarnings(
206 "all-external-warnings",
208 cl::desc(
"Issue a warning everytime an external call is made, "
209 "as opposed to once per function (default=false)"),
215cl::opt<bool> AlwaysOutputSeeds(
216 "always-output-seeds",
219 "Dump test cases even if they are driven by seeds only (default=true)"),
222cl::opt<bool> OnlyReplaySeeds(
225 cl::desc(
"Discard states that do not have a seed (default=false)."),
228cl::opt<bool> OnlySeed(
"only-seed",
230 cl::desc(
"Stop execution after seeding is done without "
231 "doing regular search (default=false)."),
235 AllowSeedExtension(
"allow-seed-extension",
237 cl::desc(
"Allow extra (unbound) values to become "
238 "symbolic during seeding (default=false)."),
241cl::opt<bool> ZeroSeedExtension(
242 "zero-seed-extension",
245 "Use zero-filled objects if matching seed not found (default=false)"),
248cl::opt<bool> AllowSeedTruncation(
249 "allow-seed-truncation",
251 cl::desc(
"Allow smaller buffers than in seeds (default=false)."),
254cl::opt<bool> NamedSeedMatching(
255 "named-seed-matching",
257 cl::desc(
"Use names to match symbolic objects to inputs (default=false)."),
261 SeedTime(
"seed-time",
262 cl::desc(
"Amount of time to dedicate to seeds, before normal "
263 "search (default=0s (off))"),
269cl::list<StateTerminationType> ExitOnErrorType(
270 "exit-on-error-type",
271 cl::desc(
"Stop execution after reaching a specified condition (default=false)"),
273 clEnumValN(StateTerminationType::Abort,
"Abort",
274 "The program crashed (reached abort()/klee_abort())"),
275 clEnumValN(StateTerminationType::Assert,
"Assert",
276 "An assertion was hit"),
277 clEnumValN(StateTerminationType::BadVectorAccess,
"BadVectorAccess",
278 "Vector accessed out of bounds"),
279 clEnumValN(StateTerminationType::Execution,
"Execution",
280 "Trying to execute an unexpected instruction"),
281 clEnumValN(StateTerminationType::External,
"External",
282 "External objects referenced"),
283 clEnumValN(StateTerminationType::Free,
"Free",
284 "Freeing invalid memory"),
285 clEnumValN(StateTerminationType::Model,
"Model",
286 "Memory model limit hit"),
287 clEnumValN(StateTerminationType::Overflow,
"Overflow",
288 "An overflow occurred"),
289 clEnumValN(StateTerminationType::Ptr,
"Ptr",
"Pointer error"),
290 clEnumValN(StateTerminationType::ReadOnly,
"ReadOnly",
291 "Write to read-only memory"),
292 clEnumValN(StateTerminationType::ReportError,
"ReportError",
293 "klee_report_error called"),
294 clEnumValN(StateTerminationType::User,
"User",
295 "Wrong klee_* functions invocation")),
299cl::opt<unsigned long long> MaxInstructions(
301 cl::desc(
"Stop execution after this many instructions. Set to 0 to disable (default=0)"),
306 MaxForks(
"max-forks",
307 cl::desc(
"Only fork this many times. Set to -1 to disable (default=-1)"),
311cl::opt<unsigned> MaxDepth(
313 cl::desc(
"Only allow this many symbolic branches. Set to 0 to disable (default=0)"),
317cl::opt<unsigned> MaxMemory(
"max-memory",
318 cl::desc(
"Refuse to fork when above this amount of "
319 "memory (in MB) (see -max-memory-inhibit) and terminate "
320 "states when additional 100MB allocated (default=2000)"),
324cl::opt<bool> MaxMemoryInhibit(
325 "max-memory-inhibit",
327 "Inhibit forking when above memory cap (see -max-memory) (default=true)"),
331cl::opt<unsigned> RuntimeMaxStackFrames(
333 cl::desc(
"Terminate a state after this many stack frames. Set to 0 to "
334 "disable (default=8192)"),
338cl::opt<double> MaxStaticForkPct(
339 "max-static-fork-pct", cl::init(1.),
340 cl::desc(
"Maximum percentage spent by an instruction forking out of the "
341 "forking of all instructions (default=1.0 (always))"),
344cl::opt<double> MaxStaticSolvePct(
345 "max-static-solve-pct", cl::init(1.),
346 cl::desc(
"Maximum percentage of solving time that can be spent by a single "
347 "instruction over total solving time for all instructions "
348 "(default=1.0 (always))"),
351cl::opt<double> MaxStaticCPForkPct(
352 "max-static-cpfork-pct", cl::init(1.),
353 cl::desc(
"Maximum percentage spent by an instruction of a call path "
354 "forking out of the forking of all instructions in the call path "
355 "(default=1.0 (always))"),
358cl::opt<double> MaxStaticCPSolvePct(
359 "max-static-cpsolve-pct", cl::init(1.),
360 cl::desc(
"Maximum percentage of solving time that can be spent by a single "
361 "instruction of a call path over total solving time for all "
362 "instructions (default=1.0 (always))"),
365cl::opt<unsigned> MaxStaticPctCheckDelay(
366 "max-static-pct-check-delay",
367 cl::desc(
"Number of forks after which the --max-static-*-pct checks are enforced (default=1000)"),
371cl::opt<std::string> TimerInterval(
373 cl::desc(
"Minimum interval to check timers. "
374 "Affects -max-time, -istats-write-interval, -stats-write-interval, and -uncovered-update-interval (default=1s)"),
382enum PrintDebugInstructionsType {
391llvm::cl::bits<PrintDebugInstructionsType> DebugPrintInstructions(
392 "debug-print-instructions",
393 llvm::cl::desc(
"Log instructions during execution."),
395 clEnumValN(STDERR_ALL,
"all:stderr",
396 "Log all instructions to stderr "
397 "in format [src, inst_id, "
399 clEnumValN(STDERR_SRC,
"src:stderr",
400 "Log all instructions to stderr in format [src, inst_id]"),
401 clEnumValN(STDERR_COMPACT,
"compact:stderr",
402 "Log all instructions to stderr in format [inst_id]"),
403 clEnumValN(FILE_ALL,
"all:file",
404 "Log all instructions to file "
405 "instructions.txt in format [src, "
406 "inst_id, llvm_inst]"),
407 clEnumValN(FILE_SRC,
"src:file",
408 "Log all instructions to file "
409 "instructions.txt in format [src, "
411 clEnumValN(FILE_COMPACT,
"compact:file",
412 "Log all instructions to file instructions.txt in format "
414 llvm::cl::CommaSeparated,
418cl::opt<bool> DebugCompressInstructions(
419 "debug-compress-instructions", cl::init(
false),
421 "Compress the logged instructions in gzip format (default=false)."),
425cl::opt<bool> DebugCheckForImpliedValues(
426 "debug-check-for-implied-values", cl::init(
false),
427 cl::desc(
"Debug the implied value optimization"),
438 :
Interpreter(opts), interpreterHandler(ih), searcher(0),
440 pathWriter(0), symPathWriter(0), specialFunctionHandler(0), timers{time::Span(TimerInterval)},
441 replayKTest(0), replayPath(0), usingSeeds(0),
442 atMemoryLimit(false), inhibitForking(false), haltExecution(false),
443 ivcEnabled(false), debugLogBuffer(debugBufferString) {
448 std::make_unique<Timer>(maxTime, [&]{
473 klee_error(
"To use --only-output-states-covering-new, you need to enable --output-istats.");
475 if (DebugPrintInstructions.isSet(FILE_ALL) ||
476 DebugPrintInstructions.isSet(FILE_COMPACT) ||
477 DebugPrintInstructions.isSet(FILE_SRC)) {
478 std::string debug_file_name =
482 if (!DebugCompressInstructions) {
487 debug_file_name.append(
".gz");
488 debugInstFile = klee_open_compressed_output_file(debug_file_name, error);
492 klee_error(
"Could not open file %s : %s", debug_file_name.c_str(),
501 assert(!
kmodule && !modules.empty() &&
502 "can only register one module");
510 llvm::sys::path::append(LibPath,
511 "libkleeRuntimeIntrinsic" + opts.
OptSuffix +
".bca");
513 if (!
klee::loadFile(LibPath.c_str(), modules[0]->getContext(), modules,
515 klee_error(
"Could not load KLEE intrinsic file %s", LibPath.c_str());
527 std::vector<const char *> preservedFunctions;
531 preservedFunctions.push_back(opts.
EntryPoint.c_str());
534 preservedFunctions.push_back(
"memset");
535 preservedFunctions.push_back(
"memcpy");
536 preservedFunctions.push_back(
"memcmp");
537 preservedFunctions.push_back(
"memmove");
539 kmodule->optimiseAndPrepare(opts, preservedFunctions);
555 DataLayout *TD =
kmodule->targetData.get();
575 const auto targetData =
kmodule->targetData.get();
576 if (
const ConstantVector *cp = dyn_cast<ConstantVector>(c)) {
577 unsigned elementSize =
578 targetData->getTypeStoreSize(cp->getType()->getElementType());
579 for (
unsigned i=0, e=cp->getNumOperands(); i != e; ++i)
581 offset + i*elementSize);
582 }
else if (isa<ConstantAggregateZero>(c)) {
583 unsigned i, size = targetData->getTypeStoreSize(c->getType());
584 for (i=0; i<size; i++)
585 os->
write8(offset+i, (uint8_t) 0);
586 }
else if (
const ConstantArray *ca = dyn_cast<ConstantArray>(c)) {
587 unsigned elementSize =
588 targetData->getTypeStoreSize(ca->getType()->getElementType());
589 for (
unsigned i=0, e=ca->getNumOperands(); i != e; ++i)
591 offset + i*elementSize);
592 }
else if (
const ConstantStruct *cs = dyn_cast<ConstantStruct>(c)) {
593 const StructLayout *sl =
594 targetData->getStructLayout(cast<StructType>(cs->getType()));
595 for (
unsigned i=0, e=cs->getNumOperands(); i != e; ++i)
597 offset + sl->getElementOffset(i));
598 }
else if (
const ConstantDataSequential *cds =
599 dyn_cast<ConstantDataSequential>(c)) {
600 unsigned elementSize =
601 targetData->getTypeStoreSize(cds->getElementType());
602 for (
unsigned i=0, e=cds->getNumElements(); i != e; ++i)
604 offset + i*elementSize);
605 }
else if (!isa<UndefValue>(c) && !isa<MetadataAsValue>(c)) {
606 unsigned StoreBits = targetData->getTypeStoreSizeInBits(c->getType());
610 assert(StoreBits >= C->getWidth() &&
"Invalid store size!");
611 if (StoreBits > C->getWidth())
612 C = C->ZExt(StoreBits);
614 os->
write(offset, C);
619 void *addr,
unsigned size,
624 for(
unsigned i = 0; i < size; i++)
625 os->
write8(i, ((uint8_t*)addr)[i]);
649 Module *m =
kmodule->module.get();
651 if (m->getModuleInlineAsm() !=
"")
652 klee_warning(
"executable has module level assembly (ignoring)");
657 for (Function &f : *m) {
663 if (f.hasExternalWeakLinkage() &&
687#ifdef HAVE_CTYPE_EXTERNALS
694 const uint16_t **addr = __ctype_b_loc();
696 384 *
sizeof **addr,
true);
699 const int32_t **lower_addr = __ctype_tolower_loc();
701 384 *
sizeof **lower_addr,
true);
704 const int32_t **upper_addr = __ctype_toupper_loc();
706 384 *
sizeof **upper_addr,
true);
712 for (
const GlobalVariable &v : m->globals()) {
714 Type *ty = v.getType()->getElementType();
715 std::uint64_t size = 0;
717 size =
kmodule->targetData->getTypeStoreSize(ty);
719 if (v.isDeclaration()) {
725 if (!ty->isSized()) {
727 static_cast<int>(v.getName().size()), v.getName().data());
732 if (v.getName() ==
"_ZTVN10__cxxabiv117__class_type_infoE") {
734 }
else if (v.getName() ==
"_ZTVN10__cxxabiv120__si_class_type_infoE") {
736 }
else if (v.getName() ==
"_ZTVN10__cxxabiv121__vmi_class_type_infoE") {
742 klee_warning(
"Unable to find size for global variable: %.*s (use will "
743 "result in out of bounds access)",
744 static_cast<int>(v.getName().size()), v.getName().data());
750 globalObjectAlignment);
760 const auto *ga = dyn_cast<GlobalAlias>(c);
766 const llvm::Constant *aliasee = ga->getAliasee();
767 if (
const auto *gv = dyn_cast<GlobalValue>(aliasee)) {
779 for (
const auto *op : c->operand_values()) {
790 const Module *m =
kmodule->module.get();
791 for (
const GlobalAlias &a : m->aliases()) {
797 const Module *m =
kmodule->module.get();
801 std::vector<ObjectState *> constantObjects;
802 for (
const GlobalVariable &v : m->globals()) {
806 if (v.isDeclaration() && mo->
size) {
810 if (v.getName() ==
"__dso_handle") {
811 addr = &__dso_handle;
816 klee_error(
"Unable to load symbol(%.*s) while initializing globals",
817 static_cast<int>(v.getName().size()), v.getName().data());
819 for (
unsigned offset = 0; offset < mo->
size; offset++) {
820 os->
write8(offset,
static_cast<unsigned char *
>(addr)[offset]);
822 }
else if (v.hasInitializer()) {
825 constantObjects.emplace_back(os);
832 if (!constantObjects.empty()) {
837 for (
auto obj : constantObjects)
838 obj->setReadOnly(
true);
865 const std::vector<
ref<Expr>> &conditions,
866 std::vector<ExecutionState *> &result,
869 unsigned N = conditions.size();
874 for (
unsigned i=0; i<N; ++i) {
876 result.push_back(&state);
878 result.push_back(
nullptr);
885 result.push_back(&state);
886 for (
unsigned i=1; i<N; ++i) {
890 result.push_back(ns);
899 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
902 std::vector<SeedInfo> seeds = it->second;
908 for (std::vector<SeedInfo>::iterator siit = seeds.begin(),
909 siie = seeds.end(); siit != siie; ++siit) {
911 for (i=0; i<N; ++i) {
914 state.
constraints, siit->assignment.evaluate(conditions[i]), res,
916 assert(success &&
"FIXME: Unhandled solver failure");
929 seedMap[result[i]].push_back(*siit);
932 if (OnlyReplaySeeds) {
933 for (
unsigned i=0; i<N; ++i) {
934 if (result[i] && !
seedMap.count(result[i])) {
935 terminateStateEarly(*result[i],
"Unseeded path during replay", StateTerminationType::Replay);
942 for (
unsigned i=0; i<N; ++i)
949 if (isa<klee::ConstantExpr>(condition))
952 if (MaxStaticForkPct == 1. && MaxStaticSolvePct == 1. &&
953 MaxStaticCPForkPct == 1. && MaxStaticCPSolvePct == 1.)
964 bool reached_max_fork_limit =
965 (MaxStaticForkPct < 1. &&
969 bool reached_max_cp_fork_limit = (MaxStaticCPForkPct < 1. && cpn &&
973 bool reached_max_solver_limit =
974 (MaxStaticSolvePct < 1 &&
978 bool reached_max_cp_solver_limit =
979 (MaxStaticCPForkPct < 1. && cpn &&
983 if (reached_max_fork_limit || reached_max_cp_fork_limit ||
984 reached_max_solver_limit || reached_max_cp_solver_limit) {
988 assert(success &&
"FIXME: Unhandled solver failure");
991 std::string msg(
"skipping fork and concretizing condition (MaxStatic*Pct "
992 "limit reached) at ");
993 llvm::raw_string_ostream os(msg);
1006 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1008 bool isSeeding = it !=
seedMap.end();
1015 timeout *=
static_cast<unsigned>(it->second.size());
1028 assert(replayPosition<replayPath->size() &&
1029 "ran out of branches in replay path mode");
1033 assert(
branch &&
"hit invalid branch in replay path mode");
1035 assert(!
branch &&
"hit invalid branch in replay path mode");
1047 assert(!
replayKTest &&
"in replay mode, only one branch can be true.");
1067 bool trueSeed=
false, falseSeed=
false;
1069 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
1070 siie = it->second.end(); siit != siie; ++siit) {
1073 siit->assignment.evaluate(condition), res,
1075 assert(success &&
"FIXME: Unhandled solver failure");
1077 if (res->isTrue()) {
1082 if (trueSeed && falseSeed)
1085 if (!(trueSeed && falseSeed)) {
1086 assert(trueSeed || falseSeed);
1123 falseState = trueState->
branch();
1127 std::vector<SeedInfo> seeds = it->second;
1129 std::vector<SeedInfo> &trueSeeds =
seedMap[trueState];
1130 std::vector<SeedInfo> &falseSeeds =
seedMap[falseState];
1131 for (std::vector<SeedInfo>::iterator siit = seeds.begin(),
1132 siie = seeds.end(); siit != siie; ++siit) {
1135 siit->assignment.evaluate(condition),
1137 assert(success &&
"FIXME: Unhandled solver failure");
1139 if (res->isTrue()) {
1140 trueSeeds.push_back(*siit);
1142 falseSeeds.push_back(*siit);
1146 bool swapInfo =
false;
1147 if (trueSeeds.empty()) {
1148 if (¤t == trueState) swapInfo =
true;
1151 if (falseSeeds.empty()) {
1152 if (¤t == falseState) swapInfo =
true;
1168 trueState->
pathOS <<
"1";
1169 falseState->
pathOS <<
"0";
1184 if (MaxDepth && MaxDepth<=trueState->depth) {
1190 return StatePair(trueState, falseState);
1195 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(condition)) {
1197 llvm::report_fatal_error(
"attempt to add invalid constraint");
1202 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1206 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
1207 siie = it->second.end(); siit != siie; ++siit) {
1210 siit->assignment.evaluate(condition),
1212 assert(success &&
"FIXME: Unhandled solver failure");
1215 siit->patchSeed(state, condition,
solver);
1220 klee_warning(
"seeds patched for violating constraint");
1231 assert(index < ki->inst->getNumOperands());
1234 assert(vnumber != -1 &&
1235 "Invalid operand to eval(), not a value or constant!");
1239 unsigned index = -vnumber - 2;
1240 return kmodule->constantTable[index];
1242 unsigned index = vnumber;
1262 if (!isa<ConstantExpr>(e)) {
1264 bool isTrue =
false;
1268 ref<Expr> cond = EqExpr::create(e, value);
1287 const char *reason) {
1295 assert(success &&
"FIXME: Unhandled solver failure");
1299 llvm::raw_string_ostream os(str);
1300 os <<
"silently concretizing (reason: " << reason <<
") expression " << e
1301 <<
" to value " << value <<
" (" << (*(state.
pc)).info->file <<
":"
1302 << (*(state.
pc)).info->line <<
")";
1304 if (AllExternalWarnings)
1318 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1320 if (it==
seedMap.end() || isa<ConstantExpr>(e)) {
1325 assert(success &&
"FIXME: Unhandled solver failure");
1329 std::set< ref<Expr> > values;
1330 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
1331 siie = it->second.end(); siit != siie; ++siit) {
1332 ref<Expr> cond = siit->assignment.evaluate(e);
1337 assert(success &&
"FIXME: Unhandled solver failure");
1339 values.insert(value);
1342 std::vector< ref<Expr> > conditions;
1343 for (std::set<
ref<Expr> >::iterator vit = values.begin(),
1344 vie = values.end(); vit != vie; ++vit)
1345 conditions.push_back(EqExpr::create(e, *vit));
1347 std::vector<ExecutionState*> branches;
1348 branch(state, conditions, branches, BranchType::GetVal);
1350 std::vector<ExecutionState*>::iterator bit = branches.begin();
1351 for (std::set<
ref<Expr> >::iterator vit = values.begin(),
1352 vie = values.end(); vit != vie; ++vit) {
1363 if (DebugPrintInstructions.getBits() == 0)
1367 llvm::raw_ostream *stream =
nullptr;
1368 if (DebugPrintInstructions.isSet(STDERR_ALL) ||
1369 DebugPrintInstructions.isSet(STDERR_SRC) ||
1370 DebugPrintInstructions.isSet(STDERR_COMPACT))
1371 stream = &llvm::errs();
1379 if (!DebugPrintInstructions.isSet(STDERR_COMPACT) &&
1380 !DebugPrintInstructions.isSet(FILE_COMPACT)) {
1386 if (DebugPrintInstructions.isSet(STDERR_ALL) ||
1387 DebugPrintInstructions.isSet(FILE_ALL))
1388 (*stream) <<
':' << *(state.
pc->
inst);
1393 if (DebugPrintInstructions.isSet(FILE_ALL) ||
1394 DebugPrintInstructions.isSet(FILE_COMPACT) ||
1395 DebugPrintInstructions.isSet(FILE_SRC)) {
1419 return &llvm::APFloat::IEEEsingle();
1421 return &llvm::APFloat::IEEEdouble();
1423 return &llvm::APFloat::x87DoubleExtended();
1430 const llvm::LandingPadInst &lpi,
1431 bool &stateTerminated) {
1432 stateTerminated =
false;
1434 std::vector<unsigned char> serialized;
1436 for (
unsigned current_clause_id = 0; current_clause_id < lpi.getNumClauses();
1437 ++current_clause_id) {
1438 llvm::Constant *current_clause = lpi.getClause(current_clause_id);
1439 if (lpi.isCatch(current_clause_id)) {
1441 serialized.push_back(0);
1443 std::uint64_t ti_addr = 0;
1445 llvm::BitCastOperator *clause_bitcast =
1446 dyn_cast<llvm::BitCastOperator>(current_clause);
1447 if (clause_bitcast) {
1448 llvm::GlobalValue *clause_type =
1449 dyn_cast<GlobalValue>(clause_bitcast->getOperand(0));
1452 }
else if (current_clause->isNullValue()) {
1456 state,
"Internal: Clause is not a bitcast or null (catch-all)");
1457 stateTerminated =
true;
1460 const std::size_t old_size = serialized.size();
1461 serialized.resize(old_size + 8);
1462 memcpy(serialized.data() + old_size, &ti_addr,
sizeof(ti_addr));
1463 }
else if (lpi.isFilter(current_clause_id)) {
1464 if (current_clause->isNullValue()) {
1467 serialized.push_back(1);
1469 serialized.resize(serialized.size() + 8, 0);
1471 llvm::ConstantArray
const *ca =
1472 cast<llvm::ConstantArray>(current_clause);
1475 unsigned const num_elements = ca->getNumOperands();
1476 unsigned char serialized_num_elements = 0;
1479 std::numeric_limits<
decltype(serialized_num_elements)>::max()) {
1481 state,
"Internal: too many elements in landingpad filter");
1482 stateTerminated =
true;
1486 serialized_num_elements = num_elements;
1487 serialized.push_back(serialized_num_elements + 1);
1490 for (llvm::Value
const *v : ca->operands()) {
1491 llvm::BitCastOperator
const *bitcast =
1492 dyn_cast<llvm::BitCastOperator>(v);
1495 "Internal: expected value inside a "
1496 "filter-clause to be a bitcast");
1497 stateTerminated =
true;
1501 llvm::GlobalValue
const *clause_value =
1502 dyn_cast<GlobalValue>(bitcast->getOperand(0));
1503 if (!clause_value) {
1505 "Internal: expected value inside a "
1506 "filter-clause bitcast to be a GlobalValue");
1507 stateTerminated =
true;
1511 std::uint64_t
const ti_addr =
1514 const std::size_t old_size = serialized.size();
1515 serialized.resize(old_size + 8);
1516 memcpy(serialized.data() + old_size, &ti_addr,
sizeof(ti_addr));
1525 for (
unsigned i = 0; i < serialized.size(); i++) {
1526 os->
write8(i, serialized[i]);
1534 assert(ui &&
"unwinding without unwinding information");
1536 std::size_t startIndex;
1537 std::size_t lowestStackIndex;
1540 if (
auto *sui = dyn_cast<SearchPhaseUnwindingInformation>(ui)) {
1541 startIndex = sui->unwindingProgress;
1542 lowestStackIndex = 0;
1544 }
else if (
auto *cui = dyn_cast<CleanupPhaseUnwindingInformation>(ui)) {
1545 startIndex = state.
stack.size() - 1;
1546 lowestStackIndex = cui->catchingStackIndex;
1549 assert(
false &&
"invalid UnwindingInformation subclass");
1552 for (std::size_t i = startIndex; i > lowestStackIndex; i--) {
1553 auto const &sf = state.
stack.at(i);
1555 Instruction *inst = sf.caller ? sf.caller->inst :
nullptr;
1564 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1567 if (
auto *sui = dyn_cast<SearchPhaseUnwindingInformation>(ui)) {
1571 LandingPadInst *lpi = invoke->getUnwindDest()->getLandingPadInst();
1572 assert(lpi &&
"unwind target of an invoke instruction did not lead to "
1576 if (lpi->isCleanup() && lpi->getNumClauses() == 0) {
1581 bool stateTerminated =
false;
1584 assert((stateTerminated !=
bool(clauses_mo)) &&
1585 "illegal serializeLandingpad result");
1587 if (stateTerminated) {
1591 assert(sui->serializedLandingpad ==
nullptr &&
1592 "serializedLandingpad should be reset");
1593 sui->serializedLandingpad = clauses_mo;
1595 llvm::Function *personality_fn =
1596 kmodule->module->getFunction(
"_klee_eh_cxx_personality");
1611 sui->unwindingProgress = i - 1;
1624 if (isa<SearchPhaseUnwindingInformation>(ui)) {
1637 "Missing landingpad in phase 2 of unwinding");
1644 auto eh_type_iterator =
1646 if (eh_type_iterator == std::end(
eh_typeids)) {
1648 eh_type_iterator = std::prev(std::end(
eh_typeids));
1659 Instruction *i = ki->
inst;
1660 if (isa_and_nonnull<DbgInfoIntrinsic>(i))
1662 if (f && f->isDeclaration()) {
1663 switch (f->getIntrinsicID()) {
1664 case Intrinsic::not_intrinsic:
1668 case Intrinsic::fabs: {
1670 toConstant(state, arguments[0],
"floating point");
1673 state,
"Unsupported intrinsic llvm.fabs call");
1677 Res = llvm::abs(Res);
1683#if LLVM_VERSION_CODE >= LLVM_VERSION(12, 0)
1684 case Intrinsic::abs: {
1685 if (isa<VectorType>(i->getOperand(0)->getType()))
1687 state,
"llvm.abs with vectors is not supported");
1692 assert(poison->
getWidth() == 1 &&
"Second argument is not an i1");
1695 uint64_t moneVal = APInt(bw, -1,
true).getZExtValue();
1696 uint64_t sminVal = APInt::getSignedMinValue(bw).getZExtValue();
1703 ref<Expr> issmin = EqExpr::create(op, smin);
1706 state,
"llvm.abs called with poison and INT_MIN");
1710 ref<Expr> negative = SltExpr::create(op, zero);
1711 ref<Expr> notsmin = NeExpr::create(op, smin);
1712 ref<Expr> cond = AndExpr::create(negative, notsmin);
1715 ref<Expr> flip = MulExpr::create(op, mone);
1722 case Intrinsic::smax:
1723 case Intrinsic::smin:
1724 case Intrinsic::umax:
1725 case Intrinsic::umin: {
1726 if (isa<VectorType>(i->getOperand(0)->getType()) ||
1727 isa<VectorType>(i->getOperand(1)->getType()))
1729 state,
"llvm.{s,u}{max,min} with vectors is not supported");
1735 if (f->getIntrinsicID() == Intrinsic::smax)
1736 cond = SgtExpr::create(op1, op2);
1737 else if (f->getIntrinsicID() == Intrinsic::smin)
1738 cond = SltExpr::create(op1, op2);
1739 else if (f->getIntrinsicID() == Intrinsic::umax)
1740 cond = UgtExpr::create(op1, op2);
1742 cond = UltExpr::create(op1, op2);
1750#if LLVM_VERSION_CODE >= LLVM_VERSION(7, 0)
1751 case Intrinsic::fshr:
1752 case Intrinsic::fshl: {
1757 assert(w == op2->
getWidth() &&
"type mismatch");
1758 assert(w == op3->
getWidth() &&
"type mismatch");
1762 op3 = ZExtExpr::create(op3, w+w);
1763 if (f->getIntrinsicID() == Intrinsic::fshl) {
1779 case Intrinsic::vastart: {
1793 assert(WordSize ==
Expr::Int64 &&
"Unknown word size!");
1818#ifdef SUPPORT_KLEE_EH_CXX
1819 case Intrinsic::eh_typeid_for: {
1825 case Intrinsic::vaend:
1832 case Intrinsic::vacopy:
1838 klee_warning(
"unimplemented intrinsic: %s", f->getName().data());
1843 if (InvokeInst *ii = dyn_cast<InvokeInst>(i)) {
1849 if (RuntimeMaxStackFrames && state.
stack.size() > RuntimeMaxStackFrames) {
1850 terminateStateEarly(state,
"Maximum stack size reached.", StateTerminationType::OutOfStackMemory);
1869 unsigned callingArgs = arguments.size();
1870 unsigned funcArgs = f->arg_size();
1871 if (!f->isVarArg()) {
1872 if (callingArgs > funcArgs) {
1874 f->getName().data());
1875 }
else if (callingArgs < funcArgs) {
1880 if (callingArgs < funcArgs) {
1888 "Unknown word size!");
1891 bool requires16ByteAlignment =
false;
1893 uint64_t offsets[callingArgs];
1896#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
1897 const CallBase &cs = cast<CallBase>(*i);
1899 const CallSite cs(i);
1901 for (
unsigned k = funcArgs; k < callingArgs; k++) {
1902 if (cs.isByValArgument(k)) {
1903#if LLVM_VERSION_CODE >= LLVM_VERSION(9, 0)
1904 Type *t = cs.getParamByValType(k);
1906 auto arg = cs.getArgOperand(k);
1907 Type *t = arg->getType();
1908 assert(t->isPointerTy());
1909 t = t->getPointerElementType();
1911 argWidth =
kmodule->targetData->getTypeSizeInBits(t);
1913 argWidth = arguments[k]->getWidth();
1920#if LLVM_VERSION_CODE >= LLVM_VERSION(11, 0)
1921 MaybeAlign ma = cs.getParamAlign(k);
1922 unsigned alignment = ma ? ma->value() : 0;
1924 unsigned alignment = cs.getParamAlignment(k);
1932 requires16ByteAlignment =
true;
1938 size = llvm::alignTo(size, alignment);
1944 size += llvm::alignTo(argWidth, WordSize) / 8;
1951 (requires16ByteAlignment ? 16 : 8));
1959 requires16ByteAlignment) {
1962 0,
"While allocating varargs: malloc did not align to 16 bytes.");
1967 for (
unsigned k = funcArgs; k < callingArgs; k++) {
1968 if (!cs.isByValArgument(k)) {
1969 os->
write(offsets[k], arguments[k]);
1971 ConstantExpr *CE = dyn_cast<ConstantExpr>(arguments[k]);
1978 for (
unsigned i = 0; i < osarg->
size; i++)
1985 unsigned numFormals = f->arg_size();
1986 for (
unsigned k = 0; k < numFormals; k++)
2009 if (state.
pc->
inst->getOpcode() == Instruction::PHI) {
2010 PHINode *first =
static_cast<PHINode*
>(state.
pc->
inst);
2018 SmallPtrSet<const GlobalValue*, 3> Visited;
2020 Constant *c = dyn_cast<Constant>(calledVal);
2025 if (GlobalValue *gv = dyn_cast<GlobalValue>(c)) {
2026 if (!Visited.insert(gv).second)
2029 if (Function *f = dyn_cast<Function>(gv))
2031 else if (GlobalAlias *ga = dyn_cast<GlobalAlias>(gv))
2032 c = ga->getAliasee();
2035 }
else if (llvm::ConstantExpr *ce = dyn_cast<llvm::ConstantExpr>(c)) {
2036 if (ce->getOpcode()==Instruction::BitCast)
2037 c = ce->getOperand(0);
2046 Instruction *i = ki->
inst;
2047 switch (i->getOpcode()) {
2049 case Instruction::Ret: {
2050 ReturnInst *ri = cast<ReturnInst>(i);
2052 Instruction *caller = kcaller ? kcaller->
inst :
nullptr;
2053 bool isVoidReturn = (ri->getNumOperands() == 0);
2056 if (!isVoidReturn) {
2060 if (state.
stack.size() <= 1) {
2061 assert(!caller &&
"caller set on initial stack frame");
2069 if (InvokeInst *ii = dyn_cast<InvokeInst>(caller)) {
2076#ifdef SUPPORT_KLEE_EH_CXX
2077 if (ri->getFunction()->getName() ==
"_klee_eh_cxx_personality") {
2078 assert(dyn_cast<ConstantExpr>(result) &&
2079 "result from personality fn must be a concrete value");
2081 auto *sui = dyn_cast_or_null<SearchPhaseUnwindingInformation>(
2083 assert(sui &&
"return from personality function outside of "
2084 "search phase unwinding");
2088 sui->serializedLandingpad =
nullptr;
2097 std::make_unique<CleanupPhaseUnwindingInformation>(
2098 sui->exceptionObject, cast<ConstantExpr>(result),
2099 sui->unwindingProgress);
2112 if (!isVoidReturn) {
2113 Type *t = caller->getType();
2114 if (t != Type::getVoidTy(i->getContext())) {
2120#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2121 const CallBase &cs = cast<CallBase>(*caller);
2123 const CallSite cs(isa<InvokeInst>(caller)
2124 ? CallSite(cast<InvokeInst>(caller))
2125 : CallSite(cast<CallInst>(caller)));
2129 bool isSExt = cs.hasRetAttr(llvm::Attribute::SExt);
2131 result = SExtExpr::create(result, to);
2133 result = ZExtExpr::create(result, to);
2143 if (!caller->use_empty()) {
2150 case Instruction::Br: {
2151 BranchInst *bi = cast<BranchInst>(i);
2152 if (bi->isUnconditional()) {
2156 assert(bi->getCondition() == bi->getOperand(0) &&
2157 "Wrong operand index!");
2172 if (branches.second)
2177 case Instruction::IndirectBr: {
2179 const auto bi = cast<IndirectBrInst>(i);
2180 auto address =
eval(ki, 0, state).
value;
2181 address =
toUnique(state, address);
2184 if (
const auto CE = dyn_cast<ConstantExpr>(address.get())) {
2191 const auto numDestinations = bi->getNumDestinations();
2192 std::vector<BasicBlock *> targets;
2193 targets.reserve(numDestinations);
2194 std::vector<ref<Expr>> expressions;
2195 expressions.reserve(numDestinations);
2198 SmallPtrSet<BasicBlock *, 5> destinations;
2200 for (
unsigned k = 0; k < numDestinations; ++k) {
2202 const auto d = bi->getDestination(k);
2203 if (destinations.count(d))
continue;
2204 destinations.insert(d);
2208 ref<Expr> e = EqExpr::create(address, PE);
2217 assert(success &&
"FIXME: Unhandled solver failure");
2219 targets.push_back(d);
2220 expressions.push_back(e);
2227 assert(success &&
"FIXME: Unhandled solver failure");
2229 expressions.push_back(errorCase);
2233 std::vector<ExecutionState *> branches;
2234 branch(state, expressions, branches, BranchType::IndirectBranch);
2239 branches.pop_back();
2243 assert(targets.size() == branches.size());
2244 for (std::vector<ExecutionState *>::size_type k = 0; k < branches.size(); ++k) {
2252 case Instruction::Switch: {
2253 SwitchInst *si = cast<SwitchInst>(i);
2255 BasicBlock *bb = si->getParent();
2261 llvm::IntegerType *Ty = cast<IntegerType>(si->getCondition()->getType());
2262 ConstantInt *ci = ConstantInt::get(Ty, CE->getZExtValue());
2263 unsigned index = si->findCaseValue(ci)->getSuccessorIndex();
2272 std::vector<BasicBlock *> bbOrder;
2273 std::map<BasicBlock *, ref<Expr> > branchTargets;
2275 std::map<ref<Expr>, BasicBlock *> expressionOrder;
2278 for (
auto i : si->cases()) {
2281 BasicBlock *caseSuccessor = i.getCaseSuccessor();
2282 expressionOrder.insert(std::make_pair(value, caseSuccessor));
2289 for (std::map<
ref<Expr>, BasicBlock *>::iterator
2290 it = expressionOrder.begin(),
2291 itE = expressionOrder.end();
2293 ref<Expr> match = EqExpr::create(cond, it->first);
2297 if (it->second == si->getDefaultDest())
continue;
2307 assert(success &&
"FIXME: Unhandled solver failure");
2310 BasicBlock *caseSuccessor = it->second;
2318 std::pair<std::map<BasicBlock *, ref<Expr> >::iterator,
bool> res =
2319 branchTargets.insert(std::make_pair(
2322 res.first->second = OrExpr::create(match, res.first->second);
2326 bbOrder.push_back(caseSuccessor);
2336 assert(success &&
"FIXME: Unhandled solver failure");
2339 std::pair<std::map<BasicBlock *, ref<Expr> >::iterator,
bool> ret =
2340 branchTargets.insert(
2341 std::make_pair(si->getDefaultDest(), defaultValue));
2343 bbOrder.push_back(si->getDefaultDest());
2349 std::vector< ref<Expr> > conditions;
2350 for (std::vector<BasicBlock *>::iterator it = bbOrder.begin(),
2353 conditions.push_back(branchTargets[*it]);
2355 std::vector<ExecutionState*> branches;
2356 branch(state, conditions, branches, BranchType::Switch);
2358 std::vector<ExecutionState*>::iterator bit = branches.begin();
2359 for (std::vector<BasicBlock *>::iterator it = bbOrder.begin(),
2370 case Instruction::Unreachable:
2378 case Instruction::Invoke:
2379 case Instruction::Call: {
2381 if (isa<DbgInfoIntrinsic>(i))
2384#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2385 const CallBase &cs = cast<CallBase>(*i);
2386 Value *fp = cs.getCalledOperand();
2388 const CallSite cs(i);
2389 Value *fp = cs.getCalledValue();
2392 unsigned numArgs = cs.arg_size();
2395 if (isa<InlineAsm>(fp)) {
2400 std::vector< ref<Expr> > arguments;
2401 arguments.reserve(numArgs);
2403 for (
unsigned j=0; j<numArgs; ++j)
2404 arguments.push_back(
eval(ki, j+1, state).value);
2407 const FunctionType *fType =
2408 dyn_cast<FunctionType>(cast<PointerType>(f->getType())->getElementType());
2409 const FunctionType *fpType =
2410 dyn_cast<FunctionType>(cast<PointerType>(fp->getType())->getElementType());
2413 if (fType != fpType) {
2414 assert(fType && fpType &&
"unable to get function type");
2421 ai = arguments.begin(), ie = arguments.end();
2425 if (i<fType->getNumParams()) {
2430 bool isSExt = cs.paramHasAttr(i, llvm::Attribute::SExt);
2432 arguments[i] = SExtExpr::create(arguments[i], to);
2434 arguments[i] = ZExtExpr::create(arguments[i], to);
2448 bool hasInvalid =
false, first =
true;
2458 assert(success &&
"FIXME: Unhandled solver failure");
2460 StatePair res =
fork(*free, EqExpr::create(v, value),
true, BranchType::Call);
2462 uint64_t addr = value->getZExtValue();
2468 if (res.second || !first)
2470 "resolved symbolic function pointer to: %s",
2471 f->getName().data());
2488 case Instruction::PHI: {
2495 case Instruction::Select: {
2505 case Instruction::VAArg:
2511 case Instruction::Add: {
2514 bindLocal(ki, state, AddExpr::create(left, right));
2518 case Instruction::Sub: {
2521 bindLocal(ki, state, SubExpr::create(left, right));
2525 case Instruction::Mul: {
2528 bindLocal(ki, state, MulExpr::create(left, right));
2532 case Instruction::UDiv: {
2535 ref<Expr> result = UDivExpr::create(left, right);
2540 case Instruction::SDiv: {
2543 ref<Expr> result = SDivExpr::create(left, right);
2548 case Instruction::URem: {
2551 ref<Expr> result = URemExpr::create(left, right);
2556 case Instruction::SRem: {
2559 ref<Expr> result = SRemExpr::create(left, right);
2564 case Instruction::And: {
2567 ref<Expr> result = AndExpr::create(left, right);
2572 case Instruction::Or: {
2575 ref<Expr> result = OrExpr::create(left, right);
2580 case Instruction::Xor: {
2583 ref<Expr> result = XorExpr::create(left, right);
2588 case Instruction::Shl: {
2591 ref<Expr> result = ShlExpr::create(left, right);
2596 case Instruction::LShr: {
2599 ref<Expr> result = LShrExpr::create(left, right);
2604 case Instruction::AShr: {
2607 ref<Expr> result = AShrExpr::create(left, right);
2614 case Instruction::ICmp: {
2615 CmpInst *ci = cast<CmpInst>(i);
2616 ICmpInst *ii = cast<ICmpInst>(ci);
2618 switch(ii->getPredicate()) {
2619 case ICmpInst::ICMP_EQ: {
2622 ref<Expr> result = EqExpr::create(left, right);
2627 case ICmpInst::ICMP_NE: {
2630 ref<Expr> result = NeExpr::create(left, right);
2635 case ICmpInst::ICMP_UGT: {
2638 ref<Expr> result = UgtExpr::create(left, right);
2643 case ICmpInst::ICMP_UGE: {
2646 ref<Expr> result = UgeExpr::create(left, right);
2651 case ICmpInst::ICMP_ULT: {
2654 ref<Expr> result = UltExpr::create(left, right);
2659 case ICmpInst::ICMP_ULE: {
2662 ref<Expr> result = UleExpr::create(left, right);
2667 case ICmpInst::ICMP_SGT: {
2670 ref<Expr> result = SgtExpr::create(left, right);
2675 case ICmpInst::ICMP_SGE: {
2678 ref<Expr> result = SgeExpr::create(left, right);
2683 case ICmpInst::ICMP_SLT: {
2686 ref<Expr> result = SltExpr::create(left, right);
2691 case ICmpInst::ICMP_SLE: {
2694 ref<Expr> result = SleExpr::create(left, right);
2706 case Instruction::Alloca: {
2707 AllocaInst *ai = cast<AllocaInst>(i);
2708 unsigned elementSize =
2709 kmodule->targetData->getTypeStoreSize(ai->getAllocatedType());
2711 if (ai->isArrayAllocation()) {
2714 size = MulExpr::create(size, count);
2720 case Instruction::Load: {
2725 case Instruction::Store: {
2732 case Instruction::GetElementPtr: {
2736 for (std::vector< std::pair<unsigned, uint64_t> >::iterator
2739 uint64_t elementSize = it->second;
2741 base = AddExpr::create(base,
2746 base = AddExpr::create(base,
2753 case Instruction::Trunc: {
2754 CastInst *ci = cast<CastInst>(i);
2761 case Instruction::ZExt: {
2762 CastInst *ci = cast<CastInst>(i);
2763 ref<Expr> result = ZExtExpr::create(
eval(ki, 0, state).value,
2768 case Instruction::SExt: {
2769 CastInst *ci = cast<CastInst>(i);
2770 ref<Expr> result = SExtExpr::create(
eval(ki, 0, state).value,
2776 case Instruction::IntToPtr: {
2777 CastInst *ci = cast<CastInst>(i);
2780 bindLocal(ki, state, ZExtExpr::create(arg, pType));
2783 case Instruction::PtrToInt: {
2784 CastInst *ci = cast<CastInst>(i);
2787 bindLocal(ki, state, ZExtExpr::create(arg, iType));
2791 case Instruction::BitCast: {
2799#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2800 case Instruction::FNeg: {
2807 Res = llvm::neg(Res);
2813 case Instruction::FAdd: {
2823 Res.add(APFloat(*
fpWidthToSemantics(right->getWidth()),right->getAPValue()), APFloat::rmNearestTiesToEven);
2828 case Instruction::FSub: {
2837 Res.subtract(APFloat(*
fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2842 case Instruction::FMul: {
2852 Res.multiply(APFloat(*
fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2857 case Instruction::FDiv: {
2867 Res.divide(APFloat(*
fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2872 case Instruction::FRem: {
2887 case Instruction::FPTrunc: {
2888 FPTruncInst *fi = cast<FPTruncInst>(i);
2896 bool losesInfo =
false;
2898 llvm::APFloat::rmNearestTiesToEven,
2904 case Instruction::FPExt: {
2905 FPExtInst *fi = cast<FPExtInst>(i);
2912 bool losesInfo =
false;
2914 llvm::APFloat::rmNearestTiesToEven,
2920 case Instruction::FPToUI: {
2921 FPToUIInst *fi = cast<FPToUIInst>(i);
2930 bool isExact =
true;
2931 auto valueRef = makeMutableArrayRef(value);
2932 Arg.convertToInteger(valueRef, resultType,
false,
2933 llvm::APFloat::rmTowardZero, &isExact);
2938 case Instruction::FPToSI: {
2939 FPToSIInst *fi = cast<FPToSIInst>(i);
2948 bool isExact =
true;
2949 auto valueRef = makeMutableArrayRef(value);
2950 Arg.convertToInteger(valueRef, resultType,
true,
2951 llvm::APFloat::rmTowardZero, &isExact);
2956 case Instruction::UIToFP: {
2957 UIToFPInst *fi = cast<UIToFPInst>(i);
2964 llvm::APFloat f(*semantics, 0);
2965 f.convertFromAPInt(arg->getAPValue(),
false,
2966 llvm::APFloat::rmNearestTiesToEven);
2972 case Instruction::SIToFP: {
2973 SIToFPInst *fi = cast<SIToFPInst>(i);
2980 llvm::APFloat f(*semantics, 0);
2981 f.convertFromAPInt(arg->getAPValue(),
true,
2982 llvm::APFloat::rmNearestTiesToEven);
2988 case Instruction::FCmp: {
2989 FCmpInst *fi = cast<FCmpInst>(i);
3000 APFloat::cmpResult CmpRes = LHS.compare(RHS);
3002 bool Result =
false;
3003 switch( fi->getPredicate() ) {
3005 case FCmpInst::FCMP_ORD:
3006 Result = (CmpRes != APFloat::cmpUnordered);
3009 case FCmpInst::FCMP_UNO:
3010 Result = (CmpRes == APFloat::cmpUnordered);
3015 case FCmpInst::FCMP_UEQ:
3016 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpEqual);
3018 case FCmpInst::FCMP_OEQ:
3019 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpEqual);
3022 case FCmpInst::FCMP_UGT:
3023 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpGreaterThan);
3025 case FCmpInst::FCMP_OGT:
3026 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpGreaterThan);
3029 case FCmpInst::FCMP_UGE:
3030 Result = (CmpRes == APFloat::cmpUnordered || (CmpRes == APFloat::cmpGreaterThan || CmpRes == APFloat::cmpEqual));
3032 case FCmpInst::FCMP_OGE:
3033 Result = (CmpRes != APFloat::cmpUnordered && (CmpRes == APFloat::cmpGreaterThan || CmpRes == APFloat::cmpEqual));
3036 case FCmpInst::FCMP_ULT:
3037 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpLessThan);
3039 case FCmpInst::FCMP_OLT:
3040 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpLessThan);
3043 case FCmpInst::FCMP_ULE:
3044 Result = (CmpRes == APFloat::cmpUnordered || (CmpRes == APFloat::cmpLessThan || CmpRes == APFloat::cmpEqual));
3046 case FCmpInst::FCMP_OLE:
3047 Result = (CmpRes != APFloat::cmpUnordered && (CmpRes == APFloat::cmpLessThan || CmpRes == APFloat::cmpEqual));
3050 case FCmpInst::FCMP_UNE:
3051 Result = (CmpRes == APFloat::cmpUnordered || CmpRes != APFloat::cmpEqual);
3053 case FCmpInst::FCMP_ONE:
3054 Result = (CmpRes != APFloat::cmpUnordered && CmpRes != APFloat::cmpEqual);
3058 assert(0 &&
"Invalid FCMP predicate!");
3060 case FCmpInst::FCMP_FALSE:
3063 case FCmpInst::FCMP_TRUE:
3071 case Instruction::InsertValue: {
3082 if (rOffset < agg->getWidth())
3098 case Instruction::ExtractValue: {
3108 case Instruction::Fence: {
3112 case Instruction::InsertElement: {
3113 InsertElementInst *iei = cast<InsertElementInst>(i);
3121 state,
"InsertElement, support for symbolic index not implemented");
3125#if LLVM_VERSION_MAJOR >= 11
3126 const auto *vt = cast<llvm::FixedVectorType>(iei->getType());
3128 const llvm::VectorType *vt = iei->getType();
3132 if (iIdx >= vt->getNumElements()) {
3135 StateTerminationType::BadVectorAccess);
3139 const unsigned elementCount = vt->getNumElements();
3140 llvm::SmallVector<ref<Expr>, 8> elems;
3141 elems.reserve(elementCount);
3142 for (
unsigned i = elementCount; i != 0; --i) {
3144 unsigned bitOffset = EltBits * of;
3149 assert(
Context::get().isLittleEndian() &&
"FIXME:Broken for big endian");
3154 case Instruction::ExtractElement: {
3155 ExtractElementInst *eei = cast<ExtractElementInst>(i);
3162 state,
"ExtractElement, support for symbolic index not implemented");
3166#if LLVM_VERSION_MAJOR >= 11
3167 const auto *vt = cast<llvm::FixedVectorType>(eei->getVectorOperandType());
3169 const llvm::VectorType *vt = eei->getVectorOperandType();
3173 if (iIdx >= vt->getNumElements()) {
3176 StateTerminationType::BadVectorAccess);
3180 unsigned bitOffset = EltBits * iIdx;
3185 case Instruction::ShuffleVector:
3191#ifdef SUPPORT_KLEE_EH_CXX
3192 case Instruction::Resume: {
3193 auto *cui = dyn_cast_or_null<CleanupPhaseUnwindingInformation>(
3199 "resume-instruction executed outside of cleanup phase unwinding");
3208 if (!dyn_cast<ConstantExpr>(exceptionPointer) ||
3209 !dyn_cast<ConstantExpr>(selectorValue)) {
3211 state,
"resume-instruction called with non constant expression");
3216 klee_warning(
"resume-instruction called with non-0 selector value");
3219 if (!EqExpr::create(exceptionPointer, cui->exceptionObject)->isTrue()) {
3221 state,
"resume-instruction called with unexpected exception pointer");
3229 case Instruction::LandingPad: {
3230 auto *cui = dyn_cast_or_null<CleanupPhaseUnwindingInformation>(
3235 state,
"Executing landing pad but not in unwinding phase 2");
3243 if (state.
stack.size() - 1 == cui->catchingStackIndex) {
3246 selectorValue = cui->selectorValue;
3264 ZExtExpr::create(selectorValue,
Expr::Int32), exceptionPointer);
3272 case Instruction::AtomicRMW:
3274 "lowered by LowerAtomicInstructionPass");
3276 case Instruction::AtomicCmpXchg:
3278 "Unexpected AtomicCmpXchg instruction, should be "
3279 "lowered by LowerAtomicInstructionPass");
3297 for (std::vector<ExecutionState *>::iterator it =
removedStates.begin(),
3301 std::set<ExecutionState*>::iterator it2 =
states.find(es);
3302 assert(it2!=
states.end());
3304 std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it3 =
3314template <
typename SqType,
typename TypeIt>
3317 uint64_t index,
const TypeIt it) {
3318 const auto *sq = cast<SqType>(*it);
3319 uint64_t elementSize =
3320 kmodule->targetData->getTypeStoreSize(sq->getElementType());
3321 const Value *operand = it.getOperand();
3322 if (
const Constant *c = dyn_cast<Constant>(operand)) {
3327 constantOffset = constantOffset->Add(addend);
3329 kgepi->
indices.emplace_back(index, elementSize);
3333template <
typename TypeIt>
3338 for (TypeIt ii = ib; ii != ie; ++ii) {
3339 if (StructType *st = dyn_cast<StructType>(*ii)) {
3340 const StructLayout *sl =
kmodule->targetData->getStructLayout(st);
3341 const ConstantInt *ci = cast<ConstantInt>(ii.getOperand());
3342 uint64_t addend = sl->getElementOffset((
unsigned) ci->getZExtValue());
3345 }
else if (isa<ArrayType>(*ii)) {
3346 computeOffsetsSeqTy<ArrayType>(kgepi, constantOffset, index, ii);
3347 }
else if (isa<VectorType>(*ii)) {
3348 computeOffsetsSeqTy<VectorType>(kgepi, constantOffset, index, ii);
3349 }
else if (isa<PointerType>(*ii)) {
3350 computeOffsetsSeqTy<PointerType>(kgepi, constantOffset, index, ii);
3352 assert(
"invalid type" && 0);
3355 kgepi->
offset = constantOffset->getZExtValue();
3359 if (GetElementPtrInst *gepi = dyn_cast<GetElementPtrInst>(KI->
inst)) {
3362 }
else if (InsertValueInst *ivi = dyn_cast<InsertValueInst>(KI->
inst)) {
3365 assert(kgepi->
indices.empty() &&
"InsertValue constant offset expected");
3366 }
else if (ExtractValueInst *evi = dyn_cast<ExtractValueInst>(KI->
inst)) {
3369 assert(kgepi->
indices.empty() &&
"ExtractValue constant offset expected");
3374 for (
auto &kfp :
kmodule->functions) {
3381 std::unique_ptr<Cell[]>(
new Cell[
kmodule->constants.size()]);
3382 for (
unsigned i=0; i<
kmodule->constants.size(); ++i) {
3389 if (!MaxMemory)
return true;
3400 const auto totalUsage = mallocUsage + mmapUsage;
3406 if (totalUsage <= MaxMemory + 100)
3410 const auto numStates =
states.size();
3411 auto toKill = std::max(1UL, numStates - numStates * MaxMemory / totalUsage);
3412 klee_warning(
"killing %lu states (over memory cap: %luMB)", toKill, totalUsage);
3415 std::vector<ExecutionState *> arr(
states.begin(),
states.end());
3416 for (
unsigned i = 0, N = arr.size(); N && i < toKill; ++i, --N) {
3420 if (arr[idx]->coveredNew)
3423 std::swap(arr[idx], arr[N - 1]);
3424 terminateStateEarly(*arr[N - 1],
"Memory limit exceeded.", StateTerminationType::OutOfMemory);
3431 if (!DumpStatesOnHalt ||
states.empty()) {
3436 klee_message(
"halting execution, dumping remaining states");
3437 for (
const auto &state :
states)
3448 states.insert(&initialState);
3451 std::vector<SeedInfo> &v =
seedMap[&initialState];
3453 for (std::vector<KTest*>::const_iterator it =
usingSeeds->begin(),
3466 std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it =
3467 seedMap.upper_bound(lastState);
3470 lastState = it->first;
3482 int numSeeds = 0, numStates = 0;
3486 numSeeds += it->second.size();
3491 if (seedTime && time > startTime + seedTime) {
3492 klee_warning(
"seed time expired, %d seeds remain over %d states",
3493 numSeeds, numStates);
3495 }
else if (numSeeds<=lastNumSeeds-10 ||
3498 lastNumSeeds = numSeeds;
3500 numSeeds, numStates);
3515 std::vector<ExecutionState *> newStates(
states.begin(),
states.end());
3546 llvm::raw_string_ostream info(Str);
3547 info <<
"\taddress: " << address <<
"\n";
3549 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(address)) {
3550 example = CE->getZExtValue();
3555 assert(success &&
"FIXME: Unhandled solver failure");
3557 example = value->getZExtValue();
3558 info <<
"\texample: " << example <<
"\n";
3561 info <<
"\trange: [" << res.first <<
", " << res.second <<
"]\n";
3571 std::string alloc_info;
3573 info <<
"object at " << mo->
address
3574 <<
" of size " << mo->
size <<
"\n"
3575 <<
"\t\t" << alloc_info <<
"\n";
3584 std::string alloc_info;
3586 info <<
"object at " << mo->
address
3587 <<
" of size " << mo->
size <<
"\n"
3588 <<
"\t\t" << alloc_info <<
"\n";
3599 "replay did not consume all objects in test input.");
3604 std::vector<ExecutionState *>::iterator it =
3612 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it3 =
3623 return !OnlyOutputStatesCoveringNew || state.
coveredNew;
3628#define TTYPE(N,I,S) case StateTerminationType::N: ret = (S); break;
3650 if ((terminationType <= StateTerminationType::EXECERR &&
3652 (AlwaysOutputSeeds &&
seedMap.count(&state))) {
3654 state, (
message +
"\n").str().c_str(),
3666 Instruction ** lastInstruction) {
3669 ExecutionState::stack_ty::const_reverse_iterator it = state.
stack.rbegin(),
3670 itE = state.
stack.rend();
3676 if (
kmodule->internalFunctions.count(it->kf->function) == 0){
3687 for (;it != itE; ++it) {
3689 const Function * f = (*it->caller).inst->getParent()->getParent();
3690 if (
kmodule->internalFunctions.count(f)){
3695 ii = (*it->caller).info;
3696 *lastInstruction = (*it->caller).inst;
3709 auto it = std::find(ExitOnErrorType.begin(), ExitOnErrorType.end(), reason);
3710 return it != ExitOnErrorType.end();
3714 const llvm::Twine &messaget,
3716 const llvm::Twine &info,
3718 std::string
message = messaget.str();
3719 static std::set< std::pair<Instruction*, std::string> > emittedErrors;
3720 Instruction * lastInst;
3723 if (EmitAllErrors ||
3724 emittedErrors.insert(std::make_pair(lastInst,
message)).second) {
3725 if (!ii.
file.empty()) {
3731 klee_message(
"NOTE: now ignoring this error at this location");
3733 std::string MsgString;
3734 llvm::raw_string_ostream msg(MsgString);
3735 msg <<
"Error: " <<
message <<
'\n';
3736 if (!ii.
file.empty()) {
3737 msg <<
"File: " << ii.
file <<
'\n'
3738 <<
"Line: " << ii.
line <<
'\n'
3740 <<
"State: " << state.
getID() <<
'\n';
3745 std::string info_str = info.str();
3746 if (!info_str.empty())
3747 msg <<
"Info: \n" << info_str;
3763 const llvm::Twine &info) {
3789 if (ExternalCalls == ExternalCallPolicy::None &&
3791 klee_warning(
"Disallowed call to external function: %s\n",
3792 function->getName().str().c_str());
3801 uint64_t *args = (uint64_t*) alloca(2*
sizeof(*args) * (arguments.size() + 1));
3802 memset(args, 0, 2 *
sizeof(*args) * (arguments.size() + 1));
3803 unsigned wordIndex = 2;
3804 for (std::vector<
ref<Expr> >::iterator ai = arguments.begin(),
3805 ae = arguments.end(); ai!=ae; ++ai) {
3806 if (ExternalCalls == ExternalCallPolicy::All) {
3811 assert(success &&
"FIXME: Unhandled solver failure");
3813 ce->toMemory(&args[wordIndex]);
3818 op.second->flushToConcreteStore(
solver, state);
3820 wordIndex += (ce->getWidth()+63)/64;
3825 if (ce->getWidth() ==
Expr::Fl80 && wordIndex & 0x01)
3829 ce->toMemory(&args[wordIndex]);
3830 wordIndex += (ce->getWidth()+63)/64;
3833 "external call with symbolic argument: " +
3834 function->getName());
3849 klee_error(
"Could not resolve memory object for errno");
3850 ref<Expr> errValueExpr = result.second->read(0,
sizeof(*errno_addr) * 8);
3851 ConstantExpr *errnoValue = dyn_cast<ConstantExpr>(errValueExpr);
3854 "external call with errno value symbolic: " +
3855 function->getName());
3863 if (!SuppressExternalWarnings) {
3866 llvm::raw_string_ostream os(TmpStr);
3867 os <<
"calling external: " << function->getName().str() <<
"(";
3868 for (
unsigned i=0; i<arguments.size(); i++) {
3870 if (i != arguments.size()-1)
3875 if (AllExternalWarnings)
3884 StateTerminationType::External);
3890 StateTerminationType::External);
3901 Type *resultType = target->
inst->getType();
3902 if (resultType != Type::getVoidTy(function->getContext())) {
3918 if (!isa<ConstantExpr>(e))
3921 if (n != 1 && random() % n)
3928 const Array *array =
3933 llvm::errs() <<
"Making symbolic: " <<
eq <<
"\n";
3941 const Array *array) {
3950 state.
stack.back().allocas.push_back(mo);
3961 size_t allocationAlignment) {
3964 const llvm::Value *allocSite = state.
prevPC->
inst;
3965 if (allocationAlignment == 0) {
3970 allocSite, allocationAlignment);
3984 unsigned count = std::min(reallocFrom->
size, os->
size);
3985 for (
unsigned i=0; i<count; i++)
4007 assert(success &&
"FIXME: Unhandled solver failure");
4018 assert(success &&
"FIXME: Unhandled solver failure");
4026 fork(state, EqExpr::create(example, size),
true, BranchType::Alloc);
4028 if (fixedSize.second) {
4031 bool success =
solver->
getValue(fixedSize.second->constraints, size, tmp,
4032 fixedSize.second->queryMetaData);
4033 assert(success &&
"FIXME: Unhandled solver failure");
4037 EqExpr::create(tmp, size), res,
4038 fixedSize.second->queryMetaData);
4039 assert(success &&
"FIXME: Unhandled solver failure");
4043 target, zeroMemory, reallocFrom);
4048 fork(*fixedSize.second,
4051 if (hugeSize.first) {
4057 if (hugeSize.second) {
4060 llvm::raw_string_ostream info(Str);
4062 info <<
" concretization : " << example <<
"\n";
4063 info <<
" unbound example: " << tmp <<
"\n";
4065 StateTerminationType::Model, info.str());
4070 if (fixedSize.first)
4072 target, zeroMemory, reallocFrom);
4082 if (zeroPointer.first) {
4086 if (zeroPointer.second) {
4088 resolveExact(*zeroPointer.second, address, rl,
"free");
4090 for (Executor::ExactResolutionList::iterator it = rl.begin(),
4091 ie = rl.end(); it != ie; ++it) {
4095 StateTerminationType::Free,
4099 StateTerminationType::Free,
4102 it->second->addressSpace.unbindObject(mo);
4113 const std::string &name) {
4120 for (ResolutionList::iterator it = rl.begin(), ie = rl.end();
4122 ref<Expr> inBounds = EqExpr::create(p, it->first->getBaseExpr());
4125 fork(*unbound, inBounds,
true, BranchType::ResolvePointer);
4128 results.push_back(std::make_pair(*it, branches.first));
4130 unbound = branches.second;
4150 if (SimplifySymIndices) {
4151 if (!isa<ConstantExpr>(address))
4153 if (isWrite && !isa<ConstantExpr>(value))
4164 address =
toConstant(state, address,
"resolveOne failure");
4172 if (MaxSymArraySize && mo->
size >= MaxSymArraySize) {
4173 address =
toConstant(state, address,
"max-sym-array-size");
4196 StateTerminationType::ReadOnly);
4199 wos->
write(offset, value);
4227 for (ResolutionList::iterator i = rl.begin(), ie = rl.end(); i != ie; ++i) {
4232 StatePair branches =
fork(*unbound, inBounds,
true, BranchType::MemOp);
4240 StateTerminationType::ReadOnly);
4251 unbound = branches.second;
4262 StateTerminationType::Ptr,
4270 const std::string &name) {
4276 std::string uniqueName = name;
4277 while (!state.
arrayNames.insert(uniqueName).second) {
4278 uniqueName = name +
"_" + llvm::utostr(++
id);
4284 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
4288 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
4289 siie = it->second.end(); siit != siie; ++siit) {
4294 if (ZeroSeedExtension) {
4296 values = std::vector<unsigned char>(mo->
size,
'\0');
4297 }
else if (!AllowSeedExtension) {
4303 ((!(AllowSeedExtension || ZeroSeedExtension)
4306 std::stringstream msg;
4307 msg <<
"replace size mismatch: "
4308 << mo->
name <<
"[" << mo->
size <<
"]"
4316 values.insert(values.begin(), obj->
bytes,
4318 if (ZeroSeedExtension) {
4319 for (
unsigned i=obj->
numBytes; i<mo->size; ++i)
4320 values.push_back(
'\0');
4335 for (
unsigned i=0; i<mo->
size; i++)
4348 std::vector<ref<Expr> > arguments;
4362 for (envc=0; envp[envc]; ++envc) ;
4367 Function::arg_iterator ai = f->arg_begin(), ae = f->arg_end();
4371 Instruction *first = &*(f->begin()->begin());
4378 klee_error(
"Could not allocate memory for function arguments");
4383 uint64_t envp_start = argvMO->
address + (argc+1)*NumPtrBytes;
4387 klee_error(
"invalid main function (expect 0-3 arguments)");
4403 assert(arguments.size() == f->arg_size() &&
"wrong number of arguments");
4404 for (
unsigned i = 0, e = f->arg_size(); i != e; ++i)
4410 for (
int i=0; i<argc+1+envc+1+1; i++) {
4411 if (i==argc || i>=argc+1+envc) {
4415 char *s = i<argc ? argv[i] : envp[i-(argc+1)];
4416 int j, len = strlen(s);
4422 klee_error(
"Could not allocate memory for function arguments");
4424 for (j=0; j<len+1; j++)
4463 switch (logFormat) {
4467 res = std::string(log);
4473 llvm::raw_string_ostream info(Str);
4480 llvm::raw_string_ostream info(Str);
4490 klee_warning(
"Executor::getConstraintLog() : Log format not supported!");
4496 std::pair<std::string,
4497 std::vector<unsigned char> > >
4519 if (!success)
break;
4526 std::vector< std::vector<unsigned char> > values;
4527 std::vector<const Array*> objects;
4528 for (
unsigned i = 0; i != state.
symbolics.size(); ++i)
4529 objects.push_back(state.
symbolics[i].second);
4534 klee_warning(
"unable to compute initial values (invalid constraints?)!");
4540 for (
unsigned i = 0; i != state.
symbolics.size(); ++i)
4541 res.push_back(std::make_pair(state.
symbolics[i].first->name, values[i]));
4546 std::map<
const std::string*, std::set<unsigned> > &res) {
4555 if (DebugCheckForImpliedValues)
4560 for (ImpliedValueList::iterator it = results.begin(), ie = results.end();
4576 "not possible? read only object with static read?");
4578 wos->
write(CE, it->second);
4585 return kmodule->targetData->getTypeSizeInBits(type);
4591 const size_t forcedAlignment = 8;
4592 size_t alignment = 0;
4593 llvm::Type *type = NULL;
4594 std::string allocationSiteName(allocSite->getName().str());
4595 if (
const GlobalObject *GO = dyn_cast<GlobalObject>(allocSite)) {
4596 alignment = GO->getAlignment();
4597 if (
const GlobalVariable *globalVar = dyn_cast<GlobalVariable>(GO)) {
4599 llvm::PointerType *ptrType =
4600 dyn_cast<llvm::PointerType>(globalVar->getType());
4601 assert(ptrType &&
"globalVar's type is not a pointer");
4602 type = ptrType->getElementType();
4604 type = GO->getType();
4606 }
else if (
const AllocaInst *AI = dyn_cast<AllocaInst>(allocSite)) {
4607 alignment = AI->getAlignment();
4608 type = AI->getAllocatedType();
4609 }
else if (isa<InvokeInst>(allocSite) || isa<CallInst>(allocSite)) {
4611#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
4612 const CallBase &cs = cast<CallBase>(*allocSite);
4614 llvm::Value *allocSiteNonConst =
const_cast<llvm::Value *
>(allocSite);
4615 const CallSite cs(isa<InvokeInst>(allocSiteNonConst)
4616 ? CallSite(cast<InvokeInst>(allocSiteNonConst))
4617 : CallSite(cast<CallInst>(allocSiteNonConst)));
4619 llvm::Function *fn =
4622 allocationSiteName = fn->getName().str();
4625 "Alignment of memory from call \"%s\" is not "
4626 "modelled. Using alignment of %zu.",
4627 allocationSiteName.c_str(), forcedAlignment);
4628 alignment = forcedAlignment;
4630 llvm_unreachable(
"Unhandled allocation site");
4633 if (alignment == 0) {
4634 assert(type != NULL);
4636 if (type->isSized()) {
4637 alignment =
kmodule->targetData->getPrefTypeAlignment(type);
4640 "\"%s\". Using alignment of %zu.",
4641 allocationSiteName.c_str(), forcedAlignment);
4642 alignment = forcedAlignment;
4649 "not supported. Using alignment of %zu",
4650 alignment, allocSite->getName().str().c_str(),
4652 alignment = forcedAlignment;
4655 "Returned alignment must be a power of two");
4668#if !defined(__APPLE__) && !defined(__FreeBSD__)
4670 return __errno_location();
4697 *os <<
"(" << es <<
",";
4699 auto next = es->stack.begin();
4701 for (
auto sfIt = es->stack.begin(), sf_ie = es->stack.end();
4702 sfIt != sf_ie; ++sfIt) {
4703 *os <<
"('" << sfIt->kf->function->getName().str() <<
"',";
4704 if (next == es->stack.end()) {
4705 *os << es->prevPC->info->line <<
"), ";
4707 *os << next->caller->info->line <<
"), ";
4721 *os <<
"'depth' : " << es->depth <<
", ";
4722 *os <<
"'queryCost' : " << es->queryMetaData.queryCost <<
", ";
4723 *os <<
"'coveredNew' : " << es->coveredNew <<
", ";
4724 *os <<
"'instsSinceCovNew' : " << es->instsSinceCovNew <<
", ";
4725 *os <<
"'md2u' : " << md2u <<
", ";
4726 *os <<
"'icnt' : " << icnt <<
", ";
4727 *os <<
"'CPicnt' : " << cpicnt <<
", ";
4740 return new Executor(ctx, opts, ih);
BranchType
Reason an ExecutionState forked.
static const char * okExternalsList[]
static bool shouldWriteTest(const ExecutionState &state)
static std::string terminationTypeFileExtension(StateTerminationType type)
bool shouldExitOn(StateTerminationType reason)
static std::set< std::string > okExternals(okExternalsList, okExternalsList+(sizeof(okExternalsList)/sizeof(okExternalsList[0])))
static const llvm::fltSemantics * fpWidthToSemantics(unsigned width)
void *__dso_handle __attribute__((__weak__))
#define TERMINATION_TYPES
StateTerminationType
Reason an ExecutionState got terminated.
void unbindObject(const MemoryObject *mo)
Remove a binding from the address space.
bool resolveOne(const ref< ConstantExpr > &address, ObjectPair &result) const
bool copyInConcrete(const MemoryObject *mo, const ObjectState *os, uint64_t src_address)
bool resolve(ExecutionState &state, TimingSolver *solver, ref< Expr > p, ResolutionList &rl, unsigned maxResolutions=0, time::Span timeout=time::Span()) const
void bindObject(const MemoryObject *mo, ObjectState *os)
Add a binding to the address space.
const ObjectState * findObject(const MemoryObject *mo) const
Lookup a binding from a MemoryObject.
ObjectState * getWriteable(const MemoryObject *mo, const ObjectState *os)
Obtain an ObjectState suitable for writing.
const Array * CreateArray(const std::string &_name, uint64_t _size, const ref< ConstantExpr > *constantValuesBegin=0, const ref< ConstantExpr > *constantValuesEnd=0, Expr::Width _domain=Expr::Int32, Expr::Width _range=Expr::Int8)
Create an Array object.
StatisticRecord statistics
static ref< Expr > createN(unsigned nKids, const ref< Expr > kids[])
Shortcuts to create larger concats. The chain returned is unbalanced to the right.
static ref< Expr > create(const ref< Expr > &l, const ref< Expr > &r)
static ref< ConstantExpr > create(uint64_t v, Width w)
static ref< ConstantExpr > alloc(const llvm::APInt &v)
uint64_t getZExtValue(unsigned bits=64) const
ref< ConstantExpr > SExt(Width W)
static ref< Expr > fromMemory(void *address, Width w)
Manages constraints, e.g. optimisation.
void addConstraint(const ref< Expr > &constraint)
static ref< Expr > simplifyExpr(const ConstraintSet &constraints, const ref< Expr > &expr)
static void initialize(bool IsLittleEndian, Expr::Width PointerWidth)
initialize - Construct the global Context instance.
Expr::Width getPointerWidth() const
Returns width of the pointer in bits.
static const Context & get()
get - Return the global singleton instance of the Context.
ExecutionState representing a path under exploration.
stack_ty stack
Stack representing the current instruction stream.
void addConstraint(ref< Expr > e)
void pushFrame(KInstIterator caller, KFunction *kf)
std::map< const std::string *, std::set< std::uint32_t > > coveredLines
Set containing which lines in which files are covered by this state.
void addSymbolic(const MemoryObject *mo, const Array *array)
PTreeNode * ptreeNode
Pointer to the process tree of the current state Copies of ExecutionState should not copy ptreeNode.
std::set< std::string > arrayNames
Set of used array names for this state. Used to avoid collisions.
std::uint32_t incomingBBIndex
Remember from which Basic Block control flow arrived (i.e. to select the right phi values)
std::uint32_t getID() const
std::unique_ptr< UnwindingInformation > unwindingInformation
Keep track of unwinding state while unwinding, otherwise empty.
bool forkDisabled
Disables forking for this state. Set by user code.
SolverQueryMetaData queryMetaData
Statistics and information.
ConstraintSet constraints
Constraints collected so far.
TreeOStream pathOS
History of complete path: represents branches taken to reach/create this state (both concrete and sym...
AddressSpace addressSpace
Address space used by this state (e.g. Global and Heap)
std::vector< std::pair< ref< const MemoryObject >, const Array * > > symbolics
Ordered list of symbolics: used to generate test cases.
void dumpStack(llvm::raw_ostream &out) const
TreeOStream symPathOS
History of symbolic path: represents symbolic branches taken to reach/create this state.
KInstIterator prevPC
Pointer to instruction which is currently executed.
bool coveredNew
Whether a new instruction was covered in this state.
std::uint64_t steppedInstructions
The numbers of times this state has run through Executor::stepInstruction.
ExecutionState * branch()
ImmutableSet< ref< Expr > > cexPreferences
A set of boolean expressions the user has requested be true of a counterexample.
KInstIterator pc
Pointer to instruction to be executed after the current instruction.
std::unique_ptr< llvm::raw_ostream > debugInstFile
File to print executed instructions to.
void callExternalFunction(ExecutionState &state, KInstruction *target, llvm::Function *function, std::vector< ref< Expr > > &arguments)
void terminateStateOnExit(ExecutionState &state)
void addConstraint(ExecutionState &state, ref< Expr > condition)
ArrayCache arrayCache
Assumes ownership of the created array objects.
Cell & getArgumentCell(ExecutionState &state, KFunction *kf, unsigned index)
const InstructionInfo & getLastNonKleeInternalInstruction(const ExecutionState &state, llvm::Instruction **lastInstruction)
friend class StatsTracker
TreeStreamWriter * symPathWriter
std::string getAddressInfo(ExecutionState &state, ref< Expr > address) const
Get textual information regarding a memory address.
ObjectState * bindObjectInState(ExecutionState &state, const MemoryObject *mo, bool isLocal, const Array *array=0)
void initializeGlobalAlias(const llvm::Constant *c)
std::map< ExecutionState *, std::vector< SeedInfo > > seedMap
std::map< const llvm::GlobalValue *, ref< ConstantExpr > > globalAddresses
ref< klee::ConstantExpr > toConstant(ExecutionState &state, ref< Expr > e, const char *purpose)
ref< ConstantExpr > getEhTypeidFor(ref< Expr > type_info)
Return the typeid corresponding to a certain type_info
void printDebugInstructions(ExecutionState &state)
void branch(ExecutionState &state, const std::vector< ref< Expr > > &conditions, std::vector< ExecutionState * > &result, BranchType reason)
void bindArgument(KFunction *kf, unsigned index, ExecutionState &state, ref< Expr > value)
llvm::Function * getTargetFunction(llvm::Value *calledVal, ExecutionState &state)
std::vector< std::pair< std::pair< const MemoryObject *, const ObjectState * >, ExecutionState * > > ExactResolutionList
StatePair fork(ExecutionState ¤t, ref< Expr > condition, bool isInternal, BranchType reason)
friend class SpecialFunctionHandler
size_t getAllocationAlignment(const llvm::Value *allocSite) const
std::unique_ptr< PTree > processTree
void initializeGlobalAliases()
RNG theRNG
The random number generator.
const struct KTest * replayKTest
TreeStreamWriter * pathWriter
ref< Expr > toUnique(const ExecutionState &state, ref< Expr > &e)
std::vector< ExecutionState * > addedStates
void terminateState(ExecutionState &state)
Remove state from queue and delete state.
void computeOffsets(KGEPInstruction *kgepi, TypeIt ib, TypeIt ie)
std::unordered_map< std::uint64_t, llvm::Function * > legalFunctions
void computeOffsetsSeqTy(KGEPInstruction *kgepi, ref< ConstantExpr > &constantOffset, uint64_t index, const TypeIt it)
bool inhibitForking
Disables forking, set by client.
void runFunctionAsMain(llvm::Function *f, int argc, char **argv, char **envp) override
llvm::raw_string_ostream debugLogBuffer
std::vector< ref< Expr > > eh_typeids
Typeids used during exception handling.
void executeAlloc(ExecutionState &state, ref< Expr > size, bool isLocal, KInstruction *target, bool zeroMemory=false, const ObjectState *reallocFrom=0, size_t allocationAlignment=0)
void executeInstruction(ExecutionState &state, KInstruction *ki)
void executeMemoryOperation(ExecutionState &state, bool isWrite, ref< Expr > address, ref< Expr > value, KInstruction *target)
void initializeGlobals(ExecutionState &state)
std::set< ExecutionState *, ExecutionStateIDCompare > states
ref< Expr > maxStaticPctChecks(ExecutionState ¤t, ref< Expr > condition)
Expr::Width getWidthForLLVMType(llvm::Type *type) const
Cell & getDestCell(ExecutionState &state, KInstruction *target)
void bindLocal(KInstruction *target, ExecutionState &state, ref< Expr > value)
void doImpliedValueConcretization(ExecutionState &state, ref< Expr > e, ref< ConstantExpr > value)
void getConstraintLog(const ExecutionState &state, std::string &res, Interpreter::LogType logFormat=Interpreter::STP) override
void terminateStateEarly(ExecutionState &state, const llvm::Twine &message, StateTerminationType terminationType)
time::Span coreSolverTimeout
void bindInstructionConstants(KInstruction *KI)
MemoryObject * serializeLandingpad(ExecutionState &state, const llvm::LandingPadInst &lpi, bool &stateTerminated)
std::map< const llvm::GlobalValue *, MemoryObject * > globalObjects
Map of globals to their representative memory object.
void getCoveredLines(const ExecutionState &state, std::map< const std::string *, std::set< unsigned > > &res) override
void bindModuleConstants()
bindModuleConstants - Initialize the module constant table.
std::pair< ExecutionState *, ExecutionState * > StatePair
ref< Expr > replaceReadWithSymbolic(ExecutionState &state, ref< Expr > e)
const Cell & eval(KInstruction *ki, unsigned index, ExecutionState &state) const
void terminateStateOnExecError(ExecutionState &state, const llvm::Twine &message, const llvm::Twine &info="")
void allocateGlobalObjects(ExecutionState &state)
void stepInstruction(ExecutionState &state)
std::string debugBufferString
SpecialFunctionHandler * specialFunctionHandler
llvm::Module * setModule(std::vector< std::unique_ptr< llvm::Module > > &modules, const ModuleOptions &opts) override
bool getSymbolicSolution(const ExecutionState &state, std::vector< std::pair< std::string, std::vector< unsigned char > > > &res) override
void prepareForEarlyExit() override
void executeMakeSymbolic(ExecutionState &state, const MemoryObject *mo, const std::string &name)
void run(ExecutionState &initialState)
InterpreterHandler * interpreterHandler
const std::vector< bool > * replayPath
When non-null a list of branch decisions to be used for replay.
bool branchingPermitted(const ExecutionState &state) const
check if branching/forking is allowed
void terminateStateOnSolverError(ExecutionState &state, const llvm::Twine &message)
void transferToBasicBlock(llvm::BasicBlock *dst, llvm::BasicBlock *src, ExecutionState &state)
std::unique_ptr< KModule > kmodule
unsigned getSymbolicPathStreamID(const ExecutionState &state) override
void terminateStateOnUserError(ExecutionState &state, const llvm::Twine &message)
void resolveExact(ExecutionState &state, ref< Expr > p, ExactResolutionList &results, const std::string &name)
void setHaltExecution(bool value) override
ExternalDispatcher * externalDispatcher
ExprOptimizer optimizer
Optimizes expressions.
void executeGetValue(ExecutionState &state, ref< Expr > e, KInstruction *target)
void unwindToNextLandingpad(ExecutionState &state)
void executeCall(ExecutionState &state, KInstruction *ki, llvm::Function *f, std::vector< ref< Expr > > &arguments)
void executeFree(ExecutionState &state, ref< Expr > address, KInstruction *target=0)
MemoryObject * addExternalObject(ExecutionState &state, void *addr, unsigned size, bool isReadOnly)
StatsTracker * statsTracker
void initializeGlobalObjects(ExecutionState &state)
void initializeGlobalObject(ExecutionState &state, ObjectState *os, const llvm::Constant *c, unsigned offset)
unsigned getPathStreamID(const ExecutionState &state) override
void terminateStateOnError(ExecutionState &state, const llvm::Twine &message, StateTerminationType terminationType, const llvm::Twine &longMessage="", const char *suffix=nullptr)
void updateStates(ExecutionState *current)
std::vector< ExecutionState * > removedStates
ref< klee::ConstantExpr > evalConstant(const llvm::Constant *c, const KInstruction *ki=NULL)
const std::vector< struct KTest * > * usingSeeds
void dumpStates()
Only for debug purposes; enable via debugger or klee-control.
int * getErrnoLocation(const ExecutionState &state) const
Returns the errno location in memory of the state.
ref< Expr > optimizeExpr(const ref< Expr > &e, bool valueOnly)
static void printQuery(llvm::raw_ostream &os, const ConstraintSet &constraints, const ref< Expr > &q, const ref< Expr > *evalExprsBegin=0, const ref< Expr > *evalExprsEnd=0, const Array *const *evalArraysBegin=0, const Array *const *evalArraysEnd=0, bool printArrayDecls=true)
static void printOne(llvm::raw_ostream &os, const char *message, const ref< Expr > &e)
static void printConstraints(llvm::raw_ostream &os, const ConstraintSet &constraints)
void setQuery(const Query &q)
void setOutput(llvm::raw_ostream &output)
static ref< Expr > createZExtToPointerWidth(ref< Expr > e)
static ref< Expr > createIsZero(ref< Expr > e)
static ref< Expr > createSExtToPointerWidth(ref< Expr > e)
virtual Width getWidth() const =0
static ref< ConstantExpr > createPointer(uint64_t v)
unsigned Width
The type of an expression is simply its width, in bits.
bool isZero() const
isZero - Is this a constant zero.
static ref< Expr > createTempRead(const Array *array, Expr::Width w)
static unsigned getMinBytesForWidth(Width w)
returns the smallest number of bytes in which the given width fits
bool isTrue() const
isTrue - Is this the true expression.
void * resolveSymbol(const std::string &name)
bool executeCall(llvm::Function *function, llvm::Instruction *i, uint64_t *args)
void setLastErrno(int newErrno)
iterator upper_bound(const key_type &key) const
virtual std::string getOutputFilename(const std::string &filename)=0
virtual void incPathsExplored(std::uint32_t num=1)=0
virtual std::unique_ptr< llvm::raw_fd_ostream > openOutputFile(const std::string &filename)=0
virtual void processTestCase(const ExecutionState &state, const char *err, const char *suffix)=0
virtual void incPathsCompleted()=0
const InterpreterOptions interpreterOpts
static Interpreter * create(llvm::LLVMContext &ctx, const InterpreterOptions &_interpreterOpts, InterpreterHandler *ih)
MemoryObject * allocateFixed(uint64_t address, uint64_t size, const llvm::Value *allocSite)
size_t getUsedDeterministicSize()
MemoryObject * allocate(uint64_t size, bool isLocal, bool isGlobal, const llvm::Value *allocSite, size_t alignment)
ref< Expr > getBoundsCheckOffset(ref< Expr > offset) const
unsigned size
size in bytes
void getAllocInfo(std::string &result) const
Get an identifying string for this allocation.
ref< ConstantExpr > getSizeExpr() const
ref< Expr > getBoundsCheckPointer(ref< Expr > pointer) const
ref< Expr > getOffsetExpr(ref< Expr > pointer) const
ref< ConstantExpr > getBaseExpr() const
static ref< Expr > create(ref< Expr > src)
ref< Expr > read8(unsigned offset) const
void initializeToZero()
Make contents all concrete and zero.
ref< Expr > read(ref< Expr > offset, Expr::Width width) const
void write8(unsigned offset, uint8_t value)
void initializeToRandom()
Make contents all concrete and random.
void write(unsigned offset, ref< Expr > value)
void setReadOnly(bool ro)
const MemoryObject * getObject() const
Class representing a one byte read from an array.
virtual void update(ExecutionState *current, const std::vector< ExecutionState * > &addedStates, const std::vector< ExecutionState * > &removedStates)=0
virtual ExecutionState & selectState()=0
KTestObject * getNextInput(const MemoryObject *mo, bool byName)
static ref< Expr > create(ref< Expr > c, ref< Expr > t, ref< Expr > f)
bool handle(ExecutionState &state, llvm::Function *f, KInstruction *target, std::vector< ref< Expr > > &arguments)
void prepare(std::vector< const char * > &preservedFunctions)
uint64_t getIndexedValue(const Statistic &s, unsigned index) const
uint64_t getValue(const Statistic &s) const
static bool useStatistics()
void markBranchVisited(ExecutionState *visitedTrue, ExecutionState *visitedFalse)
void stepInstruction(ExecutionState &es)
void framePopped(ExecutionState &es)
void framePushed(ExecutionState &es, StackFrame *parentFrame)
void reset()
Reset all timers.
void add(std::unique_ptr< Timer > timer)
void invoke()
Invoke registered timers with current time only if minimum interval exceeded.
bool evaluate(const ConstraintSet &, ref< Expr >, Solver::Validity &result, SolverQueryMetaData &metaData)
bool getInitialValues(const ConstraintSet &, const std::vector< const Array * > &objects, std::vector< std::vector< unsigned char > > &result, SolverQueryMetaData &metaData)
bool getValue(const ConstraintSet &, ref< Expr > expr, ref< ConstantExpr > &result, SolverQueryMetaData &metaData)
bool mustBeFalse(const ConstraintSet &, ref< Expr >, bool &result, SolverQueryMetaData &metaData)
bool mayBeTrue(const ConstraintSet &, ref< Expr >, bool &result, SolverQueryMetaData &metaData)
void setTimeout(time::Span t)
bool mustBeTrue(const ConstraintSet &, ref< Expr >, bool &result, SolverQueryMetaData &metaData)
std::pair< ref< Expr >, ref< Expr > > getRange(const ConstraintSet &, ref< Expr > query, SolverQueryMetaData &metaData)
std::unique_ptr< Solver > solver
char * getConstraintLog(const Query &query)
int const char const char * suffix
void getImpliedValues(ref< Expr > e, ref< ConstantExpr > cvalue, ImpliedValueList &result)
void checkForImpliedValues(Solver *S, ref< Expr > e, ref< ConstantExpr > cvalue)
uint64_t isPowerOfTwo(uint64_t x)
uint64_t eq(uint64_t l, uint64_t r, unsigned inWidth)
uint64_t ext(uint64_t l, unsigned outWidth, unsigned inWidth)
Statistic forks
The number of process forks.
Point getWallTime()
Returns point in time using a monotonic steady clock.
Span seconds(std::uint64_t)
size_t GetTotalMallocUsage()
Get total malloc usage in bytes.
gep_type_iterator gep_type_begin(const llvm::User *GEP)
llvm::cl::opt< CoreSolverType > CoreSolverToUse
uint64_t computeMinDistToUncovered(const KInstruction *ki, uint64_t minDistAtRA)
llvm::cl::OptionCategory TestGenCat
Solver * constructSolverChain(Solver *coreSolver, std::string querySMT2LogPath, std::string baseSolverQuerySMT2LogPath, std::string queryKQueryLogPath, std::string baseSolverQueryKQueryLogPath)
iv_type_iterator iv_type_end(const llvm::InsertValueInst *IV)
std::vector< ObjectPair > ResolutionList
llvm::cl::opt< std::string > MaxCoreSolverTime
const char ALL_QUERIES_KQUERY_FILE_NAME[]
std::unique_ptr< llvm::raw_fd_ostream > klee_open_output_file(const std::string &path, std::string &error)
cl::OptionCategory TestGenCat("Test generation options", "These options impact test generation.")
void klee_message(const char *msg,...) __attribute__((format(printf
bool loadFile(const std::string &libraryName, llvm::LLVMContext &context, std::vector< std::unique_ptr< llvm::Module > > &modules, std::string &errorMsg)
const char SOLVER_QUERIES_SMT2_FILE_NAME[]
cl::OptionCategory SeedingCat("Seeding options", "These options are related to the use of seeds to start exploration.")
const char ALL_QUERIES_SMT2_FILE_NAME[]
cl::opt< std::string > MaxTime
llvm::Function * getDirectCallTarget(const llvm::CallBase &cb, bool moduleIsFullyLinked)
bool userSearcherRequiresMD2U()
cl::OptionCategory TerminationCat("State and overall termination options", "These options control termination of the overall KLEE " "execution and of individual states.")
cl::OptionCategory DebugCat("Debugging options", "These are debugging options.")
Solver * createCoreSolver(CoreSolverType cst)
void klee_error(const char *msg,...) __attribute__((format(printf
llvm::cl::OptionCategory SeedingCat
llvm::cl::OptionCategory SolvingCat
ev_type_iterator ev_type_begin(const llvm::ExtractValueInst *EV)
ev_type_iterator ev_type_end(const llvm::ExtractValueInst *EV)
void void void void klee_warning_once(const void *id, const char *msg,...) __attribute__((format(printf
llvm::cl::OptionCategory TerminationCat
std::vector< std::pair< ref< ReadExpr >, ref< ConstantExpr > > > ImpliedValueList
void void void klee_warning(const char *msg,...) __attribute__((format(printf
std::pair< const MemoryObject *, const ObjectState * > ObjectPair
gep_type_iterator gep_type_end(const llvm::User *GEP)
llvm::cl::opt< bool > UseForkedCoreSolver
iv_type_iterator iv_type_begin(const llvm::InsertValueInst *IV)
Searcher * constructUserSearcher(Executor &executor)
llvm::cl::OptionCategory DebugCat
const char SOLVER_QUERIES_KQUERY_FILE_NAME[]
void initializeSearchOptions()
StatisticManager * theStatisticManager
cl::OptionCategory ExtCallsCat("External call policy options", "These options impact external calls.")
InstructionInfo stores debug information for a KInstruction.
const std::string & file
Source file name.
unsigned assemblyLine
Line number in generated assembly.ll.
unsigned line
Line number in source file.
unsigned MakeConcreteSymbolic
std::map< llvm::BasicBlock *, unsigned > basicBlockEntry
KInstruction ** instructions
std::vector< std::pair< unsigned, uint64_t > > indices
const InstructionInfo * info
std::string getSourceLocation() const
unsigned minDistToUncoveredOnReturn
CallPathNode * callPathNode