klee
Executor.cpp
Go to the documentation of this file.
1//===-- Executor.cpp ------------------------------------------------------===//
2//
3// The KLEE Symbolic Virtual Machine
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Executor.h"
11
12#include "Context.h"
13#include "CoreStats.h"
14#include "ExecutionState.h"
15#include "ExternalDispatcher.h"
17#include "ImpliedValue.h"
18#include "Memory.h"
19#include "MemoryManager.h"
20#include "PTree.h"
21#include "Searcher.h"
22#include "SeedInfo.h"
24#include "StatsTracker.h"
25#include "TimingSolver.h"
26#include "UserSearcher.h"
27
28#include "klee/ADT/KTest.h"
29#include "klee/ADT/RNG.h"
30#include "klee/Config/Version.h"
34#include "klee/Expr/Expr.h"
37#include "klee/Expr/ExprUtil.h"
38#include "klee/Module/Cell.h"
41#include "klee/Module/KModule.h"
42#include "klee/Solver/Common.h"
53#include "klee/System/Time.h"
54
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"
61#endif
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"
77#else
78typedef unsigned TypeSize;
79#endif
80#include "llvm/Support/raw_ostream.h"
81
82#include <algorithm>
83#include <cassert>
84#include <cerrno>
85#include <cstring>
86#include <cxxabi.h>
87#include <fstream>
88#include <iomanip>
89#include <iosfwd>
90#include <limits>
91#include <sstream>
92#include <string>
93#include <sys/mman.h>
94#include <vector>
95
96using namespace llvm;
97using namespace klee;
98
99namespace klee {
100cl::OptionCategory DebugCat("Debugging options",
101 "These are debugging options.");
102
103cl::OptionCategory ExtCallsCat("External call policy options",
104 "These options impact external calls.");
105
106cl::OptionCategory SeedingCat(
107 "Seeding options",
108 "These options are related to the use of seeds to start exploration.");
109
110cl::OptionCategory
111 TerminationCat("State and overall termination options",
112 "These options control termination of the overall KLEE "
113 "execution and of individual states.");
114
115cl::OptionCategory TestGenCat("Test generation options",
116 "These options impact test generation.");
117
118cl::opt<std::string> MaxTime(
119 "max-time",
120 cl::desc("Halt execution after the specified duration. "
121 "Set to 0s to disable (default=0s)"),
122 cl::init("0s"),
123 cl::cat(TerminationCat));
124} // namespace klee
125
126namespace {
127
128/*** Test generation options ***/
129
130cl::opt<bool> DumpStatesOnHalt(
131 "dump-states-on-halt",
132 cl::init(true),
133 cl::desc("Dump test cases for all active states on exit (default=true)"),
134 cl::cat(TestGenCat));
135
136cl::opt<bool> OnlyOutputStatesCoveringNew(
137 "only-output-states-covering-new",
138 cl::init(false),
139 cl::desc("Only output test cases covering new code (default=false)"),
140 cl::cat(TestGenCat));
141
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)"),
146 cl::cat(TestGenCat));
147
148
149/* Constraint solving options */
150
151cl::opt<unsigned> MaxSymArraySize(
152 "max-sym-array-size",
153 cl::desc(
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)"),
156 cl::init(0),
157 cl::cat(SolvingCat));
158
159cl::opt<bool>
160 SimplifySymIndices("simplify-sym-indices",
161 cl::init(false),
162 cl::desc("Simplify symbolic accesses using equalities "
163 "from other constraints (default=false)"),
164 cl::cat(SolvingCat));
165
166cl::opt<bool>
167 EqualitySubstitution("equality-substitution", cl::init(true),
168 cl::desc("Simplify equality expressions before "
169 "querying the solver (default=true)"),
170 cl::cat(SolvingCat));
171
172
173/*** External call policy options ***/
174
175enum class ExternalCallPolicy {
176 None, // No external calls allowed
177 Concrete, // Only external calls with concrete arguments allowed
178 All, // All external calls allowed
179};
180
181cl::opt<ExternalCallPolicy> ExternalCalls(
182 "external-calls",
183 cl::desc("Specify the external call policy"),
184 cl::values(
185 clEnumValN(
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),
197 cl::cat(ExtCallsCat));
198
199cl::opt<bool> SuppressExternalWarnings(
200 "suppress-external-warnings",
201 cl::init(false),
202 cl::desc("Supress warnings about calling external functions."),
203 cl::cat(ExtCallsCat));
204
205cl::opt<bool> AllExternalWarnings(
206 "all-external-warnings",
207 cl::init(false),
208 cl::desc("Issue a warning everytime an external call is made, "
209 "as opposed to once per function (default=false)"),
210 cl::cat(ExtCallsCat));
211
212
213/*** Seeding options ***/
214
215cl::opt<bool> AlwaysOutputSeeds(
216 "always-output-seeds",
217 cl::init(true),
218 cl::desc(
219 "Dump test cases even if they are driven by seeds only (default=true)"),
220 cl::cat(SeedingCat));
221
222cl::opt<bool> OnlyReplaySeeds(
223 "only-replay-seeds",
224 cl::init(false),
225 cl::desc("Discard states that do not have a seed (default=false)."),
226 cl::cat(SeedingCat));
227
228cl::opt<bool> OnlySeed("only-seed",
229 cl::init(false),
230 cl::desc("Stop execution after seeding is done without "
231 "doing regular search (default=false)."),
232 cl::cat(SeedingCat));
233
234cl::opt<bool>
235 AllowSeedExtension("allow-seed-extension",
236 cl::init(false),
237 cl::desc("Allow extra (unbound) values to become "
238 "symbolic during seeding (default=false)."),
239 cl::cat(SeedingCat));
240
241cl::opt<bool> ZeroSeedExtension(
242 "zero-seed-extension",
243 cl::init(false),
244 cl::desc(
245 "Use zero-filled objects if matching seed not found (default=false)"),
246 cl::cat(SeedingCat));
247
248cl::opt<bool> AllowSeedTruncation(
249 "allow-seed-truncation",
250 cl::init(false),
251 cl::desc("Allow smaller buffers than in seeds (default=false)."),
252 cl::cat(SeedingCat));
253
254cl::opt<bool> NamedSeedMatching(
255 "named-seed-matching",
256 cl::init(false),
257 cl::desc("Use names to match symbolic objects to inputs (default=false)."),
258 cl::cat(SeedingCat));
259
260cl::opt<std::string>
261 SeedTime("seed-time",
262 cl::desc("Amount of time to dedicate to seeds, before normal "
263 "search (default=0s (off))"),
264 cl::cat(SeedingCat));
265
266
267/*** Termination criteria options ***/
268
269cl::list<StateTerminationType> ExitOnErrorType(
270 "exit-on-error-type",
271 cl::desc("Stop execution after reaching a specified condition (default=false)"),
272 cl::values(
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")),
296 cl::ZeroOrMore,
297 cl::cat(TerminationCat));
298
299cl::opt<unsigned long long> MaxInstructions(
300 "max-instructions",
301 cl::desc("Stop execution after this many instructions. Set to 0 to disable (default=0)"),
302 cl::init(0),
303 cl::cat(TerminationCat));
304
305cl::opt<unsigned>
306 MaxForks("max-forks",
307 cl::desc("Only fork this many times. Set to -1 to disable (default=-1)"),
308 cl::init(~0u),
309 cl::cat(TerminationCat));
310
311cl::opt<unsigned> MaxDepth(
312 "max-depth",
313 cl::desc("Only allow this many symbolic branches. Set to 0 to disable (default=0)"),
314 cl::init(0),
315 cl::cat(TerminationCat));
316
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)"),
321 cl::init(2000),
322 cl::cat(TerminationCat));
323
324cl::opt<bool> MaxMemoryInhibit(
325 "max-memory-inhibit",
326 cl::desc(
327 "Inhibit forking when above memory cap (see -max-memory) (default=true)"),
328 cl::init(true),
329 cl::cat(TerminationCat));
330
331cl::opt<unsigned> RuntimeMaxStackFrames(
332 "max-stack-frames",
333 cl::desc("Terminate a state after this many stack frames. Set to 0 to "
334 "disable (default=8192)"),
335 cl::init(8192),
336 cl::cat(TerminationCat));
337
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))"),
342 cl::cat(TerminationCat));
343
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))"),
349 cl::cat(TerminationCat));
350
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))"),
356 cl::cat(TerminationCat));
357
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))"),
363 cl::cat(TerminationCat));
364
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)"),
368 cl::init(1000),
369 cl::cat(TerminationCat));
370
371cl::opt<std::string> TimerInterval(
372 "timer-interval",
373 cl::desc("Minimum interval to check timers. "
374 "Affects -max-time, -istats-write-interval, -stats-write-interval, and -uncovered-update-interval (default=1s)"),
375 cl::init("1s"),
376 cl::cat(TerminationCat));
377
378
379/*** Debugging options ***/
380
382enum PrintDebugInstructionsType {
383 STDERR_ALL,
384 STDERR_SRC,
385 STDERR_COMPACT,
386 FILE_ALL,
387 FILE_SRC,
388 FILE_COMPACT
389};
390
391llvm::cl::bits<PrintDebugInstructionsType> DebugPrintInstructions(
392 "debug-print-instructions",
393 llvm::cl::desc("Log instructions during execution."),
394 llvm::cl::values(
395 clEnumValN(STDERR_ALL, "all:stderr",
396 "Log all instructions to stderr "
397 "in format [src, inst_id, "
398 "llvm_inst]"),
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, "
410 "inst_id]"),
411 clEnumValN(FILE_COMPACT, "compact:file",
412 "Log all instructions to file instructions.txt in format "
413 "[inst_id]")),
414 llvm::cl::CommaSeparated,
415 cl::cat(DebugCat));
416
417#ifdef HAVE_ZLIB_H
418cl::opt<bool> DebugCompressInstructions(
419 "debug-compress-instructions", cl::init(false),
420 cl::desc(
421 "Compress the logged instructions in gzip format (default=false)."),
422 cl::cat(DebugCat));
423#endif
424
425cl::opt<bool> DebugCheckForImpliedValues(
426 "debug-check-for-implied-values", cl::init(false),
427 cl::desc("Debug the implied value optimization"),
428 cl::cat(DebugCat));
429
430} // namespace
431
432// XXX hack
433extern "C" unsigned dumpStates, dumpPTree;
434unsigned dumpStates = 0, dumpPTree = 0;
435
436Executor::Executor(LLVMContext &ctx, const InterpreterOptions &opts,
438 : Interpreter(opts), interpreterHandler(ih), searcher(0),
439 externalDispatcher(new ExternalDispatcher(ctx)), statsTracker(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) {
444
445
446 const time::Span maxTime{MaxTime};
447 if (maxTime) timers.add(
448 std::make_unique<Timer>(maxTime, [&]{
449 klee_message("HaltTimer invoked");
450 setHaltExecution(true);
451 }));
452
456 if (!coreSolver) {
457 klee_error("Failed to create core solver\n");
458 }
459
461 coreSolver,
466
467 this->solver = new TimingSolver(solver, EqualitySubstitution);
469
471
472 if (OnlyOutputStatesCoveringNew && !StatsTracker::useIStats())
473 klee_error("To use --only-output-states-covering-new, you need to enable --output-istats.");
474
475 if (DebugPrintInstructions.isSet(FILE_ALL) ||
476 DebugPrintInstructions.isSet(FILE_COMPACT) ||
477 DebugPrintInstructions.isSet(FILE_SRC)) {
478 std::string debug_file_name =
479 interpreterHandler->getOutputFilename("instructions.txt");
480 std::string error;
481#ifdef HAVE_ZLIB_H
482 if (!DebugCompressInstructions) {
483#endif
484 debugInstFile = klee_open_output_file(debug_file_name, error);
485#ifdef HAVE_ZLIB_H
486 } else {
487 debug_file_name.append(".gz");
488 debugInstFile = klee_open_compressed_output_file(debug_file_name, error);
489 }
490#endif
491 if (!debugInstFile) {
492 klee_error("Could not open file %s : %s", debug_file_name.c_str(),
493 error.c_str());
494 }
495 }
496}
497
498llvm::Module *
499Executor::setModule(std::vector<std::unique_ptr<llvm::Module>> &modules,
500 const ModuleOptions &opts) {
501 assert(!kmodule && !modules.empty() &&
502 "can only register one module"); // XXX gross
503
504 kmodule = std::unique_ptr<KModule>(new KModule());
505
506 // Preparing the final module happens in multiple stages
507
508 // Link with KLEE intrinsics library before running any optimizations
509 SmallString<128> LibPath(opts.LibraryDir);
510 llvm::sys::path::append(LibPath,
511 "libkleeRuntimeIntrinsic" + opts.OptSuffix + ".bca");
512 std::string error;
513 if (!klee::loadFile(LibPath.c_str(), modules[0]->getContext(), modules,
514 error)) {
515 klee_error("Could not load KLEE intrinsic file %s", LibPath.c_str());
516 }
517
518 // 1.) Link the modules together
519 while (kmodule->link(modules, opts.EntryPoint)) {
520 // 2.) Apply different instrumentation
521 kmodule->instrument(opts);
522 }
523
524 // 3.) Optimise and prepare for KLEE
525
526 // Create a list of functions that should be preserved if used
527 std::vector<const char *> preservedFunctions;
529 specialFunctionHandler->prepare(preservedFunctions);
530
531 preservedFunctions.push_back(opts.EntryPoint.c_str());
532
533 // Preserve the free-standing library calls
534 preservedFunctions.push_back("memset");
535 preservedFunctions.push_back("memcpy");
536 preservedFunctions.push_back("memcmp");
537 preservedFunctions.push_back("memmove");
538
539 kmodule->optimiseAndPrepare(opts, preservedFunctions);
540 kmodule->checkModule();
541
542 // 4.) Manifest the module
544
546
548 statsTracker =
549 new StatsTracker(*this,
552 }
553
554 // Initialize the context.
555 DataLayout *TD = kmodule->targetData.get();
556 Context::initialize(TD->isLittleEndian(),
557 (Expr::Width)TD->getPointerSizeInBits());
558
559 return kmodule->module.get();
560}
561
563 delete memory;
564 delete externalDispatcher;
566 delete statsTracker;
567 delete solver;
568}
569
570/***/
571
573 const Constant *c,
574 unsigned offset) {
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)
580 initializeGlobalObject(state, os, cp->getOperand(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)
590 initializeGlobalObject(state, os, ca->getOperand(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)
596 initializeGlobalObject(state, os, cs->getOperand(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)
603 initializeGlobalObject(state, os, cds->getElementAsConstant(i),
604 offset + i*elementSize);
605 } else if (!isa<UndefValue>(c) && !isa<MetadataAsValue>(c)) {
606 unsigned StoreBits = targetData->getTypeStoreSizeInBits(c->getType());
608
609 // Extend the constant if necessary;
610 assert(StoreBits >= C->getWidth() && "Invalid store size!");
611 if (StoreBits > C->getWidth())
612 C = C->ZExt(StoreBits);
613
614 os->write(offset, C);
615 }
616}
617
619 void *addr, unsigned size,
620 bool isReadOnly) {
621 auto mo = memory->allocateFixed(reinterpret_cast<std::uint64_t>(addr),
622 size, nullptr);
623 ObjectState *os = bindObjectInState(state, mo, false);
624 for(unsigned i = 0; i < size; i++)
625 os->write8(i, ((uint8_t*)addr)[i]);
626 if(isReadOnly)
627 os->setReadOnly(true);
628 return mo;
629}
630
631
632extern void *__dso_handle __attribute__ ((__weak__));
633
635 // allocate and initialize globals, done in two passes since we may
636 // need address of a global in order to initialize some other one.
637
638 // allocate memory objects for all globals
640
641 // initialize aliases first, may be needed for global objects
643
644 // finally, do the actual initialization
646}
647
649 Module *m = kmodule->module.get();
650
651 if (m->getModuleInlineAsm() != "")
652 klee_warning("executable has module level assembly (ignoring)");
653 // represent function globals using the address of the actual llvm function
654 // object. given that we use malloc to allocate memory in states this also
655 // ensures that we won't conflict. we don't need to allocate a memory object
656 // since reading/writing via a function pointer is unsupported anyway.
657 for (Function &f : *m) {
659
660 // If the symbol has external weak linkage then it is implicitly
661 // not defined in this module; if it isn't resolvable then it
662 // should be null.
663 if (f.hasExternalWeakLinkage() &&
664 !externalDispatcher->resolveSymbol(f.getName().str())) {
665 addr = Expr::createPointer(0);
666 } else {
667 // We allocate an object to represent each function,
668 // its address can be used for function pointers.
669 // TODO: Check whether the object is accessed?
670 auto mo = memory->allocate(8, false, true, &f, 8);
671 addr = Expr::createPointer(mo->address);
672 legalFunctions.emplace(mo->address, &f);
673 }
674
675 globalAddresses.emplace(&f, addr);
676 }
677
678#ifndef WINDOWS
679 int *errno_addr = getErrnoLocation(state);
680 MemoryObject *errnoObj =
681 addExternalObject(state, (void *)errno_addr, sizeof *errno_addr, false);
682 // Copy values from and to program space explicitly
683 errnoObj->isUserSpecified = true;
684#endif
685
686 // Disabled, we don't want to promote use of live externals.
687#ifdef HAVE_CTYPE_EXTERNALS
688#ifndef WINDOWS
689#ifndef DARWIN
690 /* from /usr/include/ctype.h:
691 These point into arrays of 384, so they can be indexed by any `unsigned
692 char' value [0,255]; by EOF (-1); or by any `signed char' value
693 [-128,-1). ISO C requires that the ctype functions work for `unsigned */
694 const uint16_t **addr = __ctype_b_loc();
695 addExternalObject(state, const_cast<uint16_t*>(*addr-128),
696 384 * sizeof **addr, true);
697 addExternalObject(state, addr, sizeof(*addr), true);
698
699 const int32_t **lower_addr = __ctype_tolower_loc();
700 addExternalObject(state, const_cast<int32_t*>(*lower_addr-128),
701 384 * sizeof **lower_addr, true);
702 addExternalObject(state, lower_addr, sizeof(*lower_addr), true);
703
704 const int32_t **upper_addr = __ctype_toupper_loc();
705 addExternalObject(state, const_cast<int32_t*>(*upper_addr-128),
706 384 * sizeof **upper_addr, true);
707 addExternalObject(state, upper_addr, sizeof(*upper_addr), true);
708#endif
709#endif
710#endif
711
712 for (const GlobalVariable &v : m->globals()) {
713 std::size_t globalObjectAlignment = getAllocationAlignment(&v);
714 Type *ty = v.getType()->getElementType();
715 std::uint64_t size = 0;
716 if (ty->isSized())
717 size = kmodule->targetData->getTypeStoreSize(ty);
718
719 if (v.isDeclaration()) {
720 // FIXME: We have no general way of handling unknown external
721 // symbols. If we really cared about making external stuff work
722 // better we could support user definition, or use the EXE style
723 // hack where we check the object file information.
724
725 if (!ty->isSized()) {
726 klee_warning("Type for %.*s is not sized",
727 static_cast<int>(v.getName().size()), v.getName().data());
728 }
729
730 // XXX - DWD - hardcode some things until we decide how to fix.
731#ifndef WINDOWS
732 if (v.getName() == "_ZTVN10__cxxabiv117__class_type_infoE") {
733 size = 0x2C;
734 } else if (v.getName() == "_ZTVN10__cxxabiv120__si_class_type_infoE") {
735 size = 0x2C;
736 } else if (v.getName() == "_ZTVN10__cxxabiv121__vmi_class_type_infoE") {
737 size = 0x2C;
738 }
739#endif
740
741 if (size == 0) {
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());
745 }
746 }
747
748 MemoryObject *mo = memory->allocate(size, /*isLocal=*/false,
749 /*isGlobal=*/true, /*allocSite=*/&v,
750 /*alignment=*/globalObjectAlignment);
751 if (!mo)
752 klee_error("out of memory");
753 globalObjects.emplace(&v, mo);
754 globalAddresses.emplace(&v, mo->getBaseExpr());
755 }
756}
757
758void Executor::initializeGlobalAlias(const llvm::Constant *c) {
759 // aliasee may either be a global value or constant expression
760 const auto *ga = dyn_cast<GlobalAlias>(c);
761 if (ga) {
762 if (globalAddresses.count(ga)) {
763 // already resolved by previous invocation
764 return;
765 }
766 const llvm::Constant *aliasee = ga->getAliasee();
767 if (const auto *gv = dyn_cast<GlobalValue>(aliasee)) {
768 // aliasee is global value
769 auto it = globalAddresses.find(gv);
770 // uninitialized only if aliasee is another global alias
771 if (it != globalAddresses.end()) {
772 globalAddresses.emplace(ga, it->second);
773 return;
774 }
775 }
776 }
777
778 // resolve aliases in all sub-expressions
779 for (const auto *op : c->operand_values()) {
780 initializeGlobalAlias(cast<Constant>(op));
781 }
782
783 if (ga) {
784 // aliasee is constant expression (or global alias)
785 globalAddresses.emplace(ga, evalConstant(ga->getAliasee()));
786 }
787}
788
790 const Module *m = kmodule->module.get();
791 for (const GlobalAlias &a : m->aliases()) {
793 }
794}
795
797 const Module *m = kmodule->module.get();
798
799 // remember constant objects to initialise their counter part for external
800 // calls
801 std::vector<ObjectState *> constantObjects;
802 for (const GlobalVariable &v : m->globals()) {
803 MemoryObject *mo = globalObjects.find(&v)->second;
804 ObjectState *os = bindObjectInState(state, mo, false);
805
806 if (v.isDeclaration() && mo->size) {
807 // Program already running -> object already initialized.
808 // Read concrete value and write it to our copy.
809 void *addr;
810 if (v.getName() == "__dso_handle") {
811 addr = &__dso_handle; // wtf ?
812 } else {
813 addr = externalDispatcher->resolveSymbol(v.getName().str());
814 }
815 if (!addr) {
816 klee_error("Unable to load symbol(%.*s) while initializing globals",
817 static_cast<int>(v.getName().size()), v.getName().data());
818 }
819 for (unsigned offset = 0; offset < mo->size; offset++) {
820 os->write8(offset, static_cast<unsigned char *>(addr)[offset]);
821 }
822 } else if (v.hasInitializer()) {
823 initializeGlobalObject(state, os, v.getInitializer(), 0);
824 if (v.isConstant())
825 constantObjects.emplace_back(os);
826 } else {
827 os->initializeToRandom();
828 }
829 }
830
831 // initialise constant memory that is potentially used with external calls
832 if (!constantObjects.empty()) {
833 // initialise the actual memory with constant values
835
836 // mark constant objects as read-only
837 for (auto obj : constantObjects)
838 obj->setReadOnly(true);
839 }
840}
841
842
844 if ((MaxMemoryInhibit && atMemoryLimit) ||
845 state.forkDisabled ||
847 (MaxForks!=~0u && stats::forks >= MaxForks)) {
848
849 if (MaxMemoryInhibit && atMemoryLimit)
850 klee_warning_once(0, "skipping fork (memory cap exceeded)");
851 else if (state.forkDisabled)
852 klee_warning_once(0, "skipping fork (fork disabled on current path)");
853 else if (inhibitForking)
854 klee_warning_once(0, "skipping fork (fork disabled globally)");
855 else
856 klee_warning_once(0, "skipping fork (max-forks reached)");
857
858 return false;
859 }
860
861 return true;
862}
863
865 const std::vector<ref<Expr>> &conditions,
866 std::vector<ExecutionState *> &result,
867 BranchType reason) {
869 unsigned N = conditions.size();
870 assert(N);
871
872 if (!branchingPermitted(state)) {
873 unsigned next = theRNG.getInt32() % N;
874 for (unsigned i=0; i<N; ++i) {
875 if (i == next) {
876 result.push_back(&state);
877 } else {
878 result.push_back(nullptr);
879 }
880 }
881 } else {
882 stats::forks += N-1;
883
884 // XXX do proper balance or keep random?
885 result.push_back(&state);
886 for (unsigned i=1; i<N; ++i) {
887 ExecutionState *es = result[theRNG.getInt32() % i];
888 ExecutionState *ns = es->branch();
889 addedStates.push_back(ns);
890 result.push_back(ns);
891 processTree->attach(es->ptreeNode, ns, es, reason);
892 }
893 }
894
895 // If necessary redistribute seeds to match conditions, killing
896 // states if necessary due to OnlyReplaySeeds (inefficient but
897 // simple).
898
899 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
900 seedMap.find(&state);
901 if (it != seedMap.end()) {
902 std::vector<SeedInfo> seeds = it->second;
903 seedMap.erase(it);
904
905 // Assume each seed only satisfies one condition (necessarily true
906 // when conditions are mutually exclusive and their conjunction is
907 // a tautology).
908 for (std::vector<SeedInfo>::iterator siit = seeds.begin(),
909 siie = seeds.end(); siit != siie; ++siit) {
910 unsigned i;
911 for (i=0; i<N; ++i) {
913 bool success = solver->getValue(
914 state.constraints, siit->assignment.evaluate(conditions[i]), res,
915 state.queryMetaData);
916 assert(success && "FIXME: Unhandled solver failure");
917 (void) success;
918 if (res->isTrue())
919 break;
920 }
921
922 // If we didn't find a satisfying condition randomly pick one
923 // (the seed will be patched).
924 if (i==N)
925 i = theRNG.getInt32() % N;
926
927 // Extra check in case we're replaying seeds with a max-fork
928 if (result[i])
929 seedMap[result[i]].push_back(*siit);
930 }
931
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);
936 result[i] = nullptr;
937 }
938 }
939 }
940 }
941
942 for (unsigned i=0; i<N; ++i)
943 if (result[i])
944 addConstraint(*result[i], conditions[i]);
945}
946
948 ref<Expr> condition) {
949 if (isa<klee::ConstantExpr>(condition))
950 return condition;
951
952 if (MaxStaticForkPct == 1. && MaxStaticSolvePct == 1. &&
953 MaxStaticCPForkPct == 1. && MaxStaticCPSolvePct == 1.)
954 return condition;
955
956 // These checks are performed only after at least MaxStaticPctCheckDelay forks
957 // have been performed since execution started
958 if (stats::forks < MaxStaticPctCheckDelay)
959 return condition;
960
962 CallPathNode *cpn = current.stack.back().callPathNode;
963
964 bool reached_max_fork_limit =
965 (MaxStaticForkPct < 1. &&
967 stats::forks * MaxStaticForkPct));
968
969 bool reached_max_cp_fork_limit = (MaxStaticCPForkPct < 1. && cpn &&
971 stats::forks * MaxStaticCPForkPct));
972
973 bool reached_max_solver_limit =
974 (MaxStaticSolvePct < 1 &&
976 stats::solverTime * MaxStaticSolvePct));
977
978 bool reached_max_cp_solver_limit =
979 (MaxStaticCPForkPct < 1. && cpn &&
981 stats::solverTime * MaxStaticCPSolvePct));
982
983 if (reached_max_fork_limit || reached_max_cp_fork_limit ||
984 reached_max_solver_limit || reached_max_cp_solver_limit) {
986 bool success = solver->getValue(current.constraints, condition, value,
987 current.queryMetaData);
988 assert(success && "FIXME: Unhandled solver failure");
989 (void)success;
990
991 std::string msg("skipping fork and concretizing condition (MaxStatic*Pct "
992 "limit reached) at ");
993 llvm::raw_string_ostream os(msg);
994 os << current.prevPC->getSourceLocation();
995 klee_warning_once(0, "%s", os.str().c_str());
996
997 addConstraint(current, EqExpr::create(value, condition));
998 condition = value;
999 }
1000 return condition;
1001}
1002
1004 bool isInternal, BranchType reason) {
1005 Solver::Validity res;
1006 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1007 seedMap.find(&current);
1008 bool isSeeding = it != seedMap.end();
1009
1010 if (!isSeeding)
1011 condition = maxStaticPctChecks(current, condition);
1012
1013 time::Span timeout = coreSolverTimeout;
1014 if (isSeeding)
1015 timeout *= static_cast<unsigned>(it->second.size());
1016 solver->setTimeout(timeout);
1017 bool success = solver->evaluate(current.constraints, condition, res,
1018 current.queryMetaData);
1020 if (!success) {
1021 current.pc = current.prevPC;
1022 terminateStateOnSolverError(current, "Query timed out (fork).");
1023 return StatePair(nullptr, nullptr);
1024 }
1025
1026 if (!isSeeding) {
1027 if (replayPath && !isInternal) {
1028 assert(replayPosition<replayPath->size() &&
1029 "ran out of branches in replay path mode");
1030 bool branch = (*replayPath)[replayPosition++];
1031
1032 if (res==Solver::True) {
1033 assert(branch && "hit invalid branch in replay path mode");
1034 } else if (res==Solver::False) {
1035 assert(!branch && "hit invalid branch in replay path mode");
1036 } else {
1037 // add constraints
1038 if(branch) {
1039 res = Solver::True;
1040 addConstraint(current, condition);
1041 } else {
1042 res = Solver::False;
1043 addConstraint(current, Expr::createIsZero(condition));
1044 }
1045 }
1046 } else if (res==Solver::Unknown) {
1047 assert(!replayKTest && "in replay mode, only one branch can be true.");
1048
1049 if (!branchingPermitted(current)) {
1051 if (theRNG.getBool()) {
1052 addConstraint(current, condition);
1053 res = Solver::True;
1054 } else {
1055 addConstraint(current, Expr::createIsZero(condition));
1056 res = Solver::False;
1057 }
1058 }
1059 }
1060 }
1061
1062 // Fix branch in only-replay-seed mode, if we don't have both true
1063 // and false seeds.
1064 if (isSeeding &&
1065 (current.forkDisabled || OnlyReplaySeeds) &&
1066 res == Solver::Unknown) {
1067 bool trueSeed=false, falseSeed=false;
1068 // Is seed extension still ok here?
1069 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
1070 siie = it->second.end(); siit != siie; ++siit) {
1072 bool success = solver->getValue(current.constraints,
1073 siit->assignment.evaluate(condition), res,
1074 current.queryMetaData);
1075 assert(success && "FIXME: Unhandled solver failure");
1076 (void) success;
1077 if (res->isTrue()) {
1078 trueSeed = true;
1079 } else {
1080 falseSeed = true;
1081 }
1082 if (trueSeed && falseSeed)
1083 break;
1084 }
1085 if (!(trueSeed && falseSeed)) {
1086 assert(trueSeed || falseSeed);
1087
1088 res = trueSeed ? Solver::True : Solver::False;
1089 addConstraint(current, trueSeed ? condition : Expr::createIsZero(condition));
1090 }
1091 }
1092
1093
1094 // XXX - even if the constraint is provable one way or the other we
1095 // can probably benefit by adding this constraint and allowing it to
1096 // reduce the other constraints. For example, if we do a binary
1097 // search on a particular value, and then see a comparison against
1098 // the value it has been fixed at, we should take this as a nice
1099 // hint to just use the single constraint instead of all the binary
1100 // search ones. If that makes sense.
1101 if (res==Solver::True) {
1102 if (!isInternal) {
1103 if (pathWriter) {
1104 current.pathOS << "1";
1105 }
1106 }
1107
1108 return StatePair(&current, nullptr);
1109 } else if (res==Solver::False) {
1110 if (!isInternal) {
1111 if (pathWriter) {
1112 current.pathOS << "0";
1113 }
1114 }
1115
1116 return StatePair(nullptr, &current);
1117 } else {
1119 ExecutionState *falseState, *trueState = &current;
1120
1121 ++stats::forks;
1122
1123 falseState = trueState->branch();
1124 addedStates.push_back(falseState);
1125
1126 if (it != seedMap.end()) {
1127 std::vector<SeedInfo> seeds = it->second;
1128 it->second.clear();
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) {
1134 bool success = solver->getValue(current.constraints,
1135 siit->assignment.evaluate(condition),
1136 res, current.queryMetaData);
1137 assert(success && "FIXME: Unhandled solver failure");
1138 (void) success;
1139 if (res->isTrue()) {
1140 trueSeeds.push_back(*siit);
1141 } else {
1142 falseSeeds.push_back(*siit);
1143 }
1144 }
1145
1146 bool swapInfo = false;
1147 if (trueSeeds.empty()) {
1148 if (&current == trueState) swapInfo = true;
1149 seedMap.erase(trueState);
1150 }
1151 if (falseSeeds.empty()) {
1152 if (&current == falseState) swapInfo = true;
1153 seedMap.erase(falseState);
1154 }
1155 if (swapInfo) {
1156 std::swap(trueState->coveredNew, falseState->coveredNew);
1157 std::swap(trueState->coveredLines, falseState->coveredLines);
1158 }
1159 }
1160
1161 processTree->attach(current.ptreeNode, falseState, trueState, reason);
1162
1163 if (pathWriter) {
1164 // Need to update the pathOS.id field of falseState, otherwise the same id
1165 // is used for both falseState and trueState.
1166 falseState->pathOS = pathWriter->open(current.pathOS);
1167 if (!isInternal) {
1168 trueState->pathOS << "1";
1169 falseState->pathOS << "0";
1170 }
1171 }
1172 if (symPathWriter) {
1173 falseState->symPathOS = symPathWriter->open(current.symPathOS);
1174 if (!isInternal) {
1175 trueState->symPathOS << "1";
1176 falseState->symPathOS << "0";
1177 }
1178 }
1179
1180 addConstraint(*trueState, condition);
1181 addConstraint(*falseState, Expr::createIsZero(condition));
1182
1183 // Kinda gross, do we even really still want this option?
1184 if (MaxDepth && MaxDepth<=trueState->depth) {
1185 terminateStateEarly(*trueState, "max-depth exceeded.", StateTerminationType::MaxDepth);
1186 terminateStateEarly(*falseState, "max-depth exceeded.", StateTerminationType::MaxDepth);
1187 return StatePair(nullptr, nullptr);
1188 }
1189
1190 return StatePair(trueState, falseState);
1191 }
1192}
1193
1195 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(condition)) {
1196 if (!CE->isTrue())
1197 llvm::report_fatal_error("attempt to add invalid constraint");
1198 return;
1199 }
1200
1201 // Check to see if this constraint violates seeds.
1202 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1203 seedMap.find(&state);
1204 if (it != seedMap.end()) {
1205 bool warn = false;
1206 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
1207 siie = it->second.end(); siit != siie; ++siit) {
1208 bool res;
1209 bool success = solver->mustBeFalse(state.constraints,
1210 siit->assignment.evaluate(condition),
1211 res, state.queryMetaData);
1212 assert(success && "FIXME: Unhandled solver failure");
1213 (void) success;
1214 if (res) {
1215 siit->patchSeed(state, condition, solver);
1216 warn = true;
1217 }
1218 }
1219 if (warn)
1220 klee_warning("seeds patched for violating constraint");
1221 }
1222
1223 state.addConstraint(condition);
1224 if (ivcEnabled)
1225 doImpliedValueConcretization(state, condition,
1227}
1228
1229const Cell& Executor::eval(KInstruction *ki, unsigned index,
1230 ExecutionState &state) const {
1231 assert(index < ki->inst->getNumOperands());
1232 int vnumber = ki->operands[index];
1233
1234 assert(vnumber != -1 &&
1235 "Invalid operand to eval(), not a value or constant!");
1236
1237 // Determine if this is a constant or not.
1238 if (vnumber < 0) {
1239 unsigned index = -vnumber - 2;
1240 return kmodule->constantTable[index];
1241 } else {
1242 unsigned index = vnumber;
1243 StackFrame &sf = state.stack.back();
1244 return sf.locals[index];
1245 }
1246}
1247
1249 ref<Expr> value) {
1250 getDestCell(state, target).value = value;
1251}
1252
1253void Executor::bindArgument(KFunction *kf, unsigned index,
1254 ExecutionState &state, ref<Expr> value) {
1255 getArgumentCell(state, kf, index).value = value;
1256}
1257
1259 ref<Expr> &e) {
1260 ref<Expr> result = e;
1261
1262 if (!isa<ConstantExpr>(e)) {
1263 ref<ConstantExpr> value;
1264 bool isTrue = false;
1265 e = optimizer.optimizeExpr(e, true);
1267 if (solver->getValue(state.constraints, e, value, state.queryMetaData)) {
1268 ref<Expr> cond = EqExpr::create(e, value);
1269 cond = optimizer.optimizeExpr(cond, false);
1270 if (solver->mustBeTrue(state.constraints, cond, isTrue,
1271 state.queryMetaData) &&
1272 isTrue)
1273 result = value;
1274 }
1276 }
1277
1278 return result;
1279}
1280
1281
1282/* Concretize the given expression, and return a possible constant value.
1283 'reason' is just a documentation string stating the reason for concretization. */
1286 ref<Expr> e,
1287 const char *reason) {
1289 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(e))
1290 return CE;
1291
1292 ref<ConstantExpr> value;
1293 bool success =
1294 solver->getValue(state.constraints, e, value, state.queryMetaData);
1295 assert(success && "FIXME: Unhandled solver failure");
1296 (void) success;
1297
1298 std::string str;
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 << ")";
1303
1304 if (AllExternalWarnings)
1305 klee_warning("%s", os.str().c_str());
1306 else
1307 klee_warning_once(reason, "%s", os.str().c_str());
1308
1309 addConstraint(state, EqExpr::create(e, value));
1310
1311 return value;
1312}
1313
1315 ref<Expr> e,
1316 KInstruction *target) {
1318 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
1319 seedMap.find(&state);
1320 if (it==seedMap.end() || isa<ConstantExpr>(e)) {
1321 ref<ConstantExpr> value;
1322 e = optimizer.optimizeExpr(e, true);
1323 bool success =
1324 solver->getValue(state.constraints, e, value, state.queryMetaData);
1325 assert(success && "FIXME: Unhandled solver failure");
1326 (void) success;
1327 bindLocal(target, state, value);
1328 } else {
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);
1333 cond = optimizer.optimizeExpr(cond, true);
1334 ref<ConstantExpr> value;
1335 bool success =
1336 solver->getValue(state.constraints, cond, value, state.queryMetaData);
1337 assert(success && "FIXME: Unhandled solver failure");
1338 (void) success;
1339 values.insert(value);
1340 }
1341
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));
1346
1347 std::vector<ExecutionState*> branches;
1348 branch(state, conditions, branches, BranchType::GetVal);
1349
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) {
1353 ExecutionState *es = *bit;
1354 if (es)
1355 bindLocal(target, *es, *vit);
1356 ++bit;
1357 }
1358 }
1359}
1360
1362 // print nothing if option unset
1363 if (DebugPrintInstructions.getBits() == 0)
1364 return;
1365
1366 // set output stream (stderr/file)
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();
1372 else
1373 stream = &debugLogBuffer;
1374
1375 // print:
1376 // [all] src location:asm line:state ID:instruction
1377 // [compact] asm line:state ID
1378 // [src] src location:asm line:state ID
1379 if (!DebugPrintInstructions.isSet(STDERR_COMPACT) &&
1380 !DebugPrintInstructions.isSet(FILE_COMPACT)) {
1381 (*stream) << " " << state.pc->getSourceLocation() << ':';
1382 }
1383
1384 (*stream) << state.pc->info->assemblyLine << ':' << state.getID();
1385
1386 if (DebugPrintInstructions.isSet(STDERR_ALL) ||
1387 DebugPrintInstructions.isSet(FILE_ALL))
1388 (*stream) << ':' << *(state.pc->inst);
1389
1390 (*stream) << '\n';
1391
1392 // flush to file
1393 if (DebugPrintInstructions.isSet(FILE_ALL) ||
1394 DebugPrintInstructions.isSet(FILE_COMPACT) ||
1395 DebugPrintInstructions.isSet(FILE_SRC)) {
1396 debugLogBuffer.flush();
1397 (*debugInstFile) << debugLogBuffer.str();
1398 debugBufferString = "";
1399 }
1400}
1401
1404 if (statsTracker)
1406
1408 ++state.steppedInstructions;
1409 state.prevPC = state.pc;
1410 ++state.pc;
1411
1412 if (stats::instructions == MaxInstructions)
1413 haltExecution = true;
1414}
1415
1416static inline const llvm::fltSemantics *fpWidthToSemantics(unsigned width) {
1417 switch (width) {
1418 case Expr::Int32:
1419 return &llvm::APFloat::IEEEsingle();
1420 case Expr::Int64:
1421 return &llvm::APFloat::IEEEdouble();
1422 case Expr::Fl80:
1423 return &llvm::APFloat::x87DoubleExtended();
1424 default:
1425 return 0;
1426 }
1427}
1428
1430 const llvm::LandingPadInst &lpi,
1431 bool &stateTerminated) {
1432 stateTerminated = false;
1433
1434 std::vector<unsigned char> serialized;
1435
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)) {
1440 // catch-clause
1441 serialized.push_back(0);
1442
1443 std::uint64_t ti_addr = 0;
1444
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));
1450
1451 ti_addr = globalAddresses[clause_type]->getZExtValue();
1452 } else if (current_clause->isNullValue()) {
1453 ti_addr = 0;
1454 } else {
1456 state, "Internal: Clause is not a bitcast or null (catch-all)");
1457 stateTerminated = true;
1458 return nullptr;
1459 }
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()) {
1465 // special handling for a catch-all filter clause, i.e., "[0 x i8*]"
1466 // for this case we serialize 1 element..
1467 serialized.push_back(1);
1468 // which is a 64bit-wide 0.
1469 serialized.resize(serialized.size() + 8, 0);
1470 } else {
1471 llvm::ConstantArray const *ca =
1472 cast<llvm::ConstantArray>(current_clause);
1473
1474 // serialize `num_elements+1` as unsigned char
1475 unsigned const num_elements = ca->getNumOperands();
1476 unsigned char serialized_num_elements = 0;
1477
1478 if (num_elements >=
1479 std::numeric_limits<decltype(serialized_num_elements)>::max()) {
1481 state, "Internal: too many elements in landingpad filter");
1482 stateTerminated = true;
1483 return nullptr;
1484 }
1485
1486 serialized_num_elements = num_elements;
1487 serialized.push_back(serialized_num_elements + 1);
1488
1489 // serialize the exception-types occurring in this filter-clause
1490 for (llvm::Value const *v : ca->operands()) {
1491 llvm::BitCastOperator const *bitcast =
1492 dyn_cast<llvm::BitCastOperator>(v);
1493 if (!bitcast) {
1495 "Internal: expected value inside a "
1496 "filter-clause to be a bitcast");
1497 stateTerminated = true;
1498 return nullptr;
1499 }
1500
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;
1508 return nullptr;
1509 }
1510
1511 std::uint64_t const ti_addr =
1512 globalAddresses[clause_value]->getZExtValue();
1513
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));
1517 }
1518 }
1519 }
1520 }
1521
1522 MemoryObject *mo =
1523 memory->allocate(serialized.size(), true, false, nullptr, 1);
1524 ObjectState *os = bindObjectInState(state, mo, false);
1525 for (unsigned i = 0; i < serialized.size(); i++) {
1526 os->write8(i, serialized[i]);
1527 }
1528
1529 return mo;
1530}
1531
1534 assert(ui && "unwinding without unwinding information");
1535
1536 std::size_t startIndex;
1537 std::size_t lowestStackIndex;
1538 bool popFrames;
1539
1540 if (auto *sui = dyn_cast<SearchPhaseUnwindingInformation>(ui)) {
1541 startIndex = sui->unwindingProgress;
1542 lowestStackIndex = 0;
1543 popFrames = false;
1544 } else if (auto *cui = dyn_cast<CleanupPhaseUnwindingInformation>(ui)) {
1545 startIndex = state.stack.size() - 1;
1546 lowestStackIndex = cui->catchingStackIndex;
1547 popFrames = true;
1548 } else {
1549 assert(false && "invalid UnwindingInformation subclass");
1550 }
1551
1552 for (std::size_t i = startIndex; i > lowestStackIndex; i--) {
1553 auto const &sf = state.stack.at(i);
1554
1555 Instruction *inst = sf.caller ? sf.caller->inst : nullptr;
1556
1557 if (popFrames) {
1558 state.popFrame();
1559 if (statsTracker != nullptr) {
1560 statsTracker->framePopped(state);
1561 }
1562 }
1563
1564 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1565 // we found the next invoke instruction in the call stack, handle it
1566 // depending on the current phase.
1567 if (auto *sui = dyn_cast<SearchPhaseUnwindingInformation>(ui)) {
1568 // in the search phase, run personality function to check if this
1569 // landingpad catches the exception
1570
1571 LandingPadInst *lpi = invoke->getUnwindDest()->getLandingPadInst();
1572 assert(lpi && "unwind target of an invoke instruction did not lead to "
1573 "a landingpad");
1574
1575 // check if this is a pure cleanup landingpad first
1576 if (lpi->isCleanup() && lpi->getNumClauses() == 0) {
1577 // pure cleanup lpi, this can't be a handler, so skip it
1578 continue;
1579 }
1580
1581 bool stateTerminated = false;
1582 MemoryObject *clauses_mo =
1583 serializeLandingpad(state, *lpi, stateTerminated);
1584 assert((stateTerminated != bool(clauses_mo)) &&
1585 "illegal serializeLandingpad result");
1586
1587 if (stateTerminated) {
1588 return;
1589 }
1590
1591 assert(sui->serializedLandingpad == nullptr &&
1592 "serializedLandingpad should be reset");
1593 sui->serializedLandingpad = clauses_mo;
1594
1595 llvm::Function *personality_fn =
1596 kmodule->module->getFunction("_klee_eh_cxx_personality");
1597 KFunction *kf = kmodule->functionMap[personality_fn];
1598
1599 state.pushFrame(state.prevPC, kf);
1600 state.pc = kf->instructions;
1601 bindArgument(kf, 0, state, sui->exceptionObject);
1602 bindArgument(kf, 1, state, clauses_mo->getSizeExpr());
1603 bindArgument(kf, 2, state, clauses_mo->getBaseExpr());
1604
1605 if (statsTracker) {
1607 &state.stack[state.stack.size() - 2]);
1608 }
1609
1610 // make sure we remember our search progress afterwards
1611 sui->unwindingProgress = i - 1;
1612 } else {
1613 // in the cleanup phase, redirect control flow
1614 transferToBasicBlock(invoke->getUnwindDest(), invoke->getParent(),
1615 state);
1616 }
1617
1618 // we are done, stop search/unwinding here
1619 return;
1620 }
1621 }
1622
1623 // no further invoke instruction/landingpad found
1624 if (isa<SearchPhaseUnwindingInformation>(ui)) {
1625 // in phase 1, simply stop unwinding. this will return
1626 // control flow back to _Unwind_RaiseException, which will
1627 // return the correct error.
1628
1629 // clean up unwinding state
1630 state.unwindingInformation.reset();
1631 } else {
1632 // in phase 2, this represent a situation that should
1633 // not happen, as we only progressed to phase 2 because
1634 // we found a handler in phase 1.
1635 // therefore terminate the state.
1637 "Missing landingpad in phase 2 of unwinding");
1638 }
1639}
1640
1642 // FIXME: Handling getEhTypeidFor is non-deterministic and depends on the
1643 // order states have been processed and executed.
1644 auto eh_type_iterator =
1645 std::find(std::begin(eh_typeids), std::end(eh_typeids), type_info);
1646 if (eh_type_iterator == std::end(eh_typeids)) {
1647 eh_typeids.push_back(type_info);
1648 eh_type_iterator = std::prev(std::end(eh_typeids));
1649 }
1650 // +1 because typeids must always be positive, so they can be distinguished
1651 // from 'no landingpad clause matched' which has value 0
1652 auto res = ConstantExpr::create(eh_type_iterator - std::begin(eh_typeids) + 1,
1653 Expr::Int32);
1654 return res;
1655}
1656
1658 std::vector<ref<Expr>> &arguments) {
1659 Instruction *i = ki->inst;
1660 if (isa_and_nonnull<DbgInfoIntrinsic>(i))
1661 return;
1662 if (f && f->isDeclaration()) {
1663 switch (f->getIntrinsicID()) {
1664 case Intrinsic::not_intrinsic:
1665 // state may be destroyed by this call, cannot touch
1666 callExternalFunction(state, ki, f, arguments);
1667 break;
1668 case Intrinsic::fabs: {
1669 ref<ConstantExpr> arg =
1670 toConstant(state, arguments[0], "floating point");
1671 if (!fpWidthToSemantics(arg->getWidth()))
1673 state, "Unsupported intrinsic llvm.fabs call");
1674
1675 llvm::APFloat Res(*fpWidthToSemantics(arg->getWidth()),
1676 arg->getAPValue());
1677 Res = llvm::abs(Res);
1678
1679 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
1680 break;
1681 }
1682
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");
1688
1689 ref<Expr> op = eval(ki, 1, state).value;
1690 ref<Expr> poison = eval(ki, 2, state).value;
1691
1692 assert(poison->getWidth() == 1 && "Second argument is not an i1");
1693 unsigned bw = op->getWidth();
1694
1695 uint64_t moneVal = APInt(bw, -1, true).getZExtValue();
1696 uint64_t sminVal = APInt::getSignedMinValue(bw).getZExtValue();
1697
1699 ref<ConstantExpr> mone = ConstantExpr::create(moneVal, bw);
1700 ref<ConstantExpr> smin = ConstantExpr::create(sminVal, bw);
1701
1702 if (poison->isTrue()) {
1703 ref<Expr> issmin = EqExpr::create(op, smin);
1704 if (issmin->isTrue())
1706 state, "llvm.abs called with poison and INT_MIN");
1707 }
1708
1709 // conditions to flip the sign: INT_MIN < op < 0
1710 ref<Expr> negative = SltExpr::create(op, zero);
1711 ref<Expr> notsmin = NeExpr::create(op, smin);
1712 ref<Expr> cond = AndExpr::create(negative, notsmin);
1713
1714 // flip and select the result
1715 ref<Expr> flip = MulExpr::create(op, mone);
1716 ref<Expr> result = SelectExpr::create(cond, flip, op);
1717
1718 bindLocal(ki, state, result);
1719 break;
1720 }
1721
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");
1730
1731 ref<Expr> op1 = eval(ki, 1, state).value;
1732 ref<Expr> op2 = eval(ki, 2, state).value;
1733
1734 ref<Expr> cond = nullptr;
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);
1741 else // (f->getIntrinsicID() == Intrinsic::umin)
1742 cond = UltExpr::create(op1, op2);
1743
1744 ref<Expr> result = SelectExpr::create(cond, op1, op2);
1745 bindLocal(ki, state, result);
1746 break;
1747 }
1748#endif
1749
1750#if LLVM_VERSION_CODE >= LLVM_VERSION(7, 0)
1751 case Intrinsic::fshr:
1752 case Intrinsic::fshl: {
1753 ref<Expr> op1 = eval(ki, 1, state).value;
1754 ref<Expr> op2 = eval(ki, 2, state).value;
1755 ref<Expr> op3 = eval(ki, 3, state).value;
1756 unsigned w = op1->getWidth();
1757 assert(w == op2->getWidth() && "type mismatch");
1758 assert(w == op3->getWidth() && "type mismatch");
1759 ref<Expr> c = ConcatExpr::create(op1, op2);
1760 // op3 = zeroExtend(op3 % w)
1761 op3 = URemExpr::create(op3, ConstantExpr::create(w, w));
1762 op3 = ZExtExpr::create(op3, w+w);
1763 if (f->getIntrinsicID() == Intrinsic::fshl) {
1764 // shift left and take top half
1765 ref<Expr> s = ShlExpr::create(c, op3);
1766 bindLocal(ki, state, ExtractExpr::create(s, w, w));
1767 } else {
1768 // shift right and take bottom half
1769 // note that LShr and AShr will have same behaviour
1770 ref<Expr> s = LShrExpr::create(c, op3);
1771 bindLocal(ki, state, ExtractExpr::create(s, 0, w));
1772 }
1773 break;
1774 }
1775#endif
1776
1777 // va_arg is handled by caller and intrinsic lowering, see comment for
1778 // ExecutionState::varargs
1779 case Intrinsic::vastart: {
1780 StackFrame &sf = state.stack.back();
1781
1782 // varargs can be zero if no varargs were provided
1783 if (!sf.varargs)
1784 return;
1785
1786 // FIXME: This is really specific to the architecture, not the pointer
1787 // size. This happens to work for x86-32 and x86-64, however.
1789 if (WordSize == Expr::Int32) {
1790 executeMemoryOperation(state, true, arguments[0],
1791 sf.varargs->getBaseExpr(), 0);
1792 } else {
1793 assert(WordSize == Expr::Int64 && "Unknown word size!");
1794
1795 // x86-64 has quite complicated calling convention. However,
1796 // instead of implementing it, we can do a simple hack: just
1797 // make a function believe that all varargs are on stack.
1799 state, true,
1800 arguments[0],
1801 ConstantExpr::create(48, 32), 0); // gp_offset
1803 state, true,
1804 AddExpr::create(arguments[0], ConstantExpr::create(4, 64)),
1805 ConstantExpr::create(304, 32), 0); // fp_offset
1807 state, true,
1808 AddExpr::create(arguments[0], ConstantExpr::create(8, 64)),
1809 sf.varargs->getBaseExpr(), 0); // overflow_arg_area
1811 state, true,
1812 AddExpr::create(arguments[0], ConstantExpr::create(16, 64)),
1813 ConstantExpr::create(0, 64), 0); // reg_save_area
1814 }
1815 break;
1816 }
1817
1818#ifdef SUPPORT_KLEE_EH_CXX
1819 case Intrinsic::eh_typeid_for: {
1820 bindLocal(ki, state, getEhTypeidFor(arguments.at(0)));
1821 break;
1822 }
1823#endif
1824
1825 case Intrinsic::vaend:
1826 // va_end is a noop for the interpreter.
1827 //
1828 // FIXME: We should validate that the target didn't do something bad
1829 // with va_end, however (like call it twice).
1830 break;
1831
1832 case Intrinsic::vacopy:
1833 // va_copy should have been lowered.
1834 //
1835 // FIXME: It would be nice to check for errors in the usage of this as
1836 // well.
1837 default:
1838 klee_warning("unimplemented intrinsic: %s", f->getName().data());
1839 terminateStateOnExecError(state, "unimplemented intrinsic");
1840 return;
1841 }
1842
1843 if (InvokeInst *ii = dyn_cast<InvokeInst>(i)) {
1844 transferToBasicBlock(ii->getNormalDest(), i->getParent(), state);
1845 }
1846 } else {
1847 // Check if maximum stack size was reached.
1848 // We currently only count the number of stack frames
1849 if (RuntimeMaxStackFrames && state.stack.size() > RuntimeMaxStackFrames) {
1850 terminateStateEarly(state, "Maximum stack size reached.", StateTerminationType::OutOfStackMemory);
1851 klee_warning("Maximum stack size reached.");
1852 return;
1853 }
1854
1855 // FIXME: I'm not really happy about this reliance on prevPC but it is ok, I
1856 // guess. This just done to avoid having to pass KInstIterator everywhere
1857 // instead of the actual instruction, since we can't make a KInstIterator
1858 // from just an instruction (unlike LLVM).
1859 KFunction *kf = kmodule->functionMap[f];
1860
1861 state.pushFrame(state.prevPC, kf);
1862 state.pc = kf->instructions;
1863
1864 if (statsTracker)
1865 statsTracker->framePushed(state, &state.stack[state.stack.size() - 2]);
1866
1867 // TODO: support zeroext, signext, sret attributes
1868
1869 unsigned callingArgs = arguments.size();
1870 unsigned funcArgs = f->arg_size();
1871 if (!f->isVarArg()) {
1872 if (callingArgs > funcArgs) {
1873 klee_warning_once(f, "calling %s with extra arguments.",
1874 f->getName().data());
1875 } else if (callingArgs < funcArgs) {
1876 terminateStateOnUserError(state, "calling function with too few arguments");
1877 return;
1878 }
1879 } else {
1880 if (callingArgs < funcArgs) {
1881 terminateStateOnUserError(state, "calling function with too few arguments");
1882 return;
1883 }
1884
1885 // Only x86-32 and x86-64 are supported
1887 assert(((WordSize == Expr::Int32) || (WordSize == Expr::Int64)) &&
1888 "Unknown word size!");
1889
1890 uint64_t size = 0; // total size of variadic arguments
1891 bool requires16ByteAlignment = false;
1892
1893 uint64_t offsets[callingArgs]; // offsets of variadic arguments
1894 uint64_t argWidth; // width of current variadic argument
1895
1896#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
1897 const CallBase &cs = cast<CallBase>(*i);
1898#else
1899 const CallSite cs(i);
1900#endif
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);
1905#else
1906 auto arg = cs.getArgOperand(k);
1907 Type *t = arg->getType();
1908 assert(t->isPointerTy());
1909 t = t->getPointerElementType();
1910#endif
1911 argWidth = kmodule->targetData->getTypeSizeInBits(t);
1912 } else {
1913 argWidth = arguments[k]->getWidth();
1914 }
1915
1916 if (WordSize == Expr::Int32) {
1917 offsets[k] = size;
1918 size += Expr::getMinBytesForWidth(argWidth);
1919 } else {
1920#if LLVM_VERSION_CODE >= LLVM_VERSION(11, 0)
1921 MaybeAlign ma = cs.getParamAlign(k);
1922 unsigned alignment = ma ? ma->value() : 0;
1923#else
1924 unsigned alignment = cs.getParamAlignment(k);
1925#endif
1926
1927 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a
1928 // 16 byte boundary if alignment needed by type exceeds 8 byte
1929 // boundary.
1930 if (!alignment && argWidth > Expr::Int64) {
1931 alignment = 16;
1932 requires16ByteAlignment = true;
1933 }
1934
1935 if (!alignment)
1936 alignment = 8;
1937
1938 size = llvm::alignTo(size, alignment);
1939 offsets[k] = size;
1940
1941 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1942 // l->overflow_arg_area + sizeof(type)
1943 // Step 10. Align l->overflow_arg_area upwards to an 8 byte boundary.
1944 size += llvm::alignTo(argWidth, WordSize) / 8;
1945 }
1946 }
1947
1948 StackFrame &sf = state.stack.back();
1949 MemoryObject *mo = sf.varargs =
1950 memory->allocate(size, true, false, state.prevPC->inst,
1951 (requires16ByteAlignment ? 16 : 8));
1952 if (!mo && size) {
1953 terminateStateOnExecError(state, "out of memory (varargs)");
1954 return;
1955 }
1956
1957 if (mo) {
1958 if ((WordSize == Expr::Int64) && (mo->address & 15) &&
1959 requires16ByteAlignment) {
1960 // Both 64bit Linux/Glibc and 64bit MacOSX should align to 16 bytes.
1962 0, "While allocating varargs: malloc did not align to 16 bytes.");
1963 }
1964
1965 ObjectState *os = bindObjectInState(state, mo, true);
1966
1967 for (unsigned k = funcArgs; k < callingArgs; k++) {
1968 if (!cs.isByValArgument(k)) {
1969 os->write(offsets[k], arguments[k]);
1970 } else {
1971 ConstantExpr *CE = dyn_cast<ConstantExpr>(arguments[k]);
1972 assert(CE); // byval argument needs to be a concrete pointer
1973
1974 ObjectPair op;
1975 state.addressSpace.resolveOne(CE, op);
1976 const ObjectState *osarg = op.second;
1977 assert(osarg);
1978 for (unsigned i = 0; i < osarg->size; i++)
1979 os->write(offsets[k] + i, osarg->read8(i));
1980 }
1981 }
1982 }
1983 }
1984
1985 unsigned numFormals = f->arg_size();
1986 for (unsigned k = 0; k < numFormals; k++)
1987 bindArgument(kf, k, state, arguments[k]);
1988 }
1989}
1990
1991void Executor::transferToBasicBlock(BasicBlock *dst, BasicBlock *src,
1992 ExecutionState &state) {
1993 // Note that in general phi nodes can reuse phi values from the same
1994 // block but the incoming value is the eval() result *before* the
1995 // execution of any phi nodes. this is pathological and doesn't
1996 // really seem to occur, but just in case we run the PhiCleanerPass
1997 // which makes sure this cannot happen and so it is safe to just
1998 // eval things in order. The PhiCleanerPass also makes sure that all
1999 // incoming blocks have the same order for each PHINode so we only
2000 // have to compute the index once.
2001 //
2002 // With that done we simply set an index in the state so that PHI
2003 // instructions know which argument to eval, set the pc, and continue.
2004
2005 // XXX this lookup has to go ?
2006 KFunction *kf = state.stack.back().kf;
2007 unsigned entry = kf->basicBlockEntry[dst];
2008 state.pc = &kf->instructions[entry];
2009 if (state.pc->inst->getOpcode() == Instruction::PHI) {
2010 PHINode *first = static_cast<PHINode*>(state.pc->inst);
2011 state.incomingBBIndex = first->getBasicBlockIndex(src);
2012 }
2013}
2014
2017Function* Executor::getTargetFunction(Value *calledVal, ExecutionState &state) {
2018 SmallPtrSet<const GlobalValue*, 3> Visited;
2019
2020 Constant *c = dyn_cast<Constant>(calledVal);
2021 if (!c)
2022 return 0;
2023
2024 while (true) {
2025 if (GlobalValue *gv = dyn_cast<GlobalValue>(c)) {
2026 if (!Visited.insert(gv).second)
2027 return 0;
2028
2029 if (Function *f = dyn_cast<Function>(gv))
2030 return f;
2031 else if (GlobalAlias *ga = dyn_cast<GlobalAlias>(gv))
2032 c = ga->getAliasee();
2033 else
2034 return 0;
2035 } else if (llvm::ConstantExpr *ce = dyn_cast<llvm::ConstantExpr>(c)) {
2036 if (ce->getOpcode()==Instruction::BitCast)
2037 c = ce->getOperand(0);
2038 else
2039 return 0;
2040 } else
2041 return 0;
2042 }
2043}
2044
2046 Instruction *i = ki->inst;
2047 switch (i->getOpcode()) {
2048 // Control flow
2049 case Instruction::Ret: {
2050 ReturnInst *ri = cast<ReturnInst>(i);
2051 KInstIterator kcaller = state.stack.back().caller;
2052 Instruction *caller = kcaller ? kcaller->inst : nullptr;
2053 bool isVoidReturn = (ri->getNumOperands() == 0);
2055
2056 if (!isVoidReturn) {
2057 result = eval(ki, 0, state).value;
2058 }
2059
2060 if (state.stack.size() <= 1) {
2061 assert(!caller && "caller set on initial stack frame");
2062 terminateStateOnExit(state);
2063 } else {
2064 state.popFrame();
2065
2066 if (statsTracker)
2067 statsTracker->framePopped(state);
2068
2069 if (InvokeInst *ii = dyn_cast<InvokeInst>(caller)) {
2070 transferToBasicBlock(ii->getNormalDest(), caller->getParent(), state);
2071 } else {
2072 state.pc = kcaller;
2073 ++state.pc;
2074 }
2075
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");
2080
2081 auto *sui = dyn_cast_or_null<SearchPhaseUnwindingInformation>(
2082 state.unwindingInformation.get());
2083 assert(sui && "return from personality function outside of "
2084 "search phase unwinding");
2085
2086 // unbind the MO we used to pass the serialized landingpad
2087 state.addressSpace.unbindObject(sui->serializedLandingpad);
2088 sui->serializedLandingpad = nullptr;
2089
2090 if (result->isZero()) {
2091 // this lpi doesn't handle the exception, continue the search
2093 } else {
2094 // a clause (or a catch-all clause or filter clause) matches:
2095 // remember the stack index and switch to cleanup phase
2096 state.unwindingInformation =
2097 std::make_unique<CleanupPhaseUnwindingInformation>(
2098 sui->exceptionObject, cast<ConstantExpr>(result),
2099 sui->unwindingProgress);
2100 // this pointer is now invalidated
2101 sui = nullptr;
2102 // continue the unwinding process (which will now start with the
2103 // cleanup phase)
2105 }
2106
2107 // never return normally from the personality fn
2108 break;
2109 }
2110#endif // SUPPORT_KLEE_EH_CXX
2111
2112 if (!isVoidReturn) {
2113 Type *t = caller->getType();
2114 if (t != Type::getVoidTy(i->getContext())) {
2115 // may need to do coercion due to bitcasts
2116 Expr::Width from = result->getWidth();
2118
2119 if (from != to) {
2120#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2121 const CallBase &cs = cast<CallBase>(*caller);
2122#else
2123 const CallSite cs(isa<InvokeInst>(caller)
2124 ? CallSite(cast<InvokeInst>(caller))
2125 : CallSite(cast<CallInst>(caller)));
2126#endif
2127
2128 // XXX need to check other param attrs ?
2129 bool isSExt = cs.hasRetAttr(llvm::Attribute::SExt);
2130 if (isSExt) {
2131 result = SExtExpr::create(result, to);
2132 } else {
2133 result = ZExtExpr::create(result, to);
2134 }
2135 }
2136
2137 bindLocal(kcaller, state, result);
2138 }
2139 } else {
2140 // We check that the return value has no users instead of
2141 // checking the type, since C defaults to returning int for
2142 // undeclared functions.
2143 if (!caller->use_empty()) {
2144 terminateStateOnExecError(state, "return void when caller expected a result");
2145 }
2146 }
2147 }
2148 break;
2149 }
2150 case Instruction::Br: {
2151 BranchInst *bi = cast<BranchInst>(i);
2152 if (bi->isUnconditional()) {
2153 transferToBasicBlock(bi->getSuccessor(0), bi->getParent(), state);
2154 } else {
2155 // FIXME: Find a way that we don't have this hidden dependency.
2156 assert(bi->getCondition() == bi->getOperand(0) &&
2157 "Wrong operand index!");
2158 ref<Expr> cond = eval(ki, 0, state).value;
2159
2160 cond = optimizer.optimizeExpr(cond, false);
2161 Executor::StatePair branches = fork(state, cond, false, BranchType::ConditionalBranch);
2162
2163 // NOTE: There is a hidden dependency here, markBranchVisited
2164 // requires that we still be in the context of the branch
2165 // instruction (it reuses its statistic id). Should be cleaned
2166 // up with convenient instruction specific data.
2167 if (statsTracker && state.stack.back().kf->trackCoverage)
2168 statsTracker->markBranchVisited(branches.first, branches.second);
2169
2170 if (branches.first)
2171 transferToBasicBlock(bi->getSuccessor(0), bi->getParent(), *branches.first);
2172 if (branches.second)
2173 transferToBasicBlock(bi->getSuccessor(1), bi->getParent(), *branches.second);
2174 }
2175 break;
2176 }
2177 case Instruction::IndirectBr: {
2178 // implements indirect branch to a label within the current function
2179 const auto bi = cast<IndirectBrInst>(i);
2180 auto address = eval(ki, 0, state).value;
2181 address = toUnique(state, address);
2182
2183 // concrete address
2184 if (const auto CE = dyn_cast<ConstantExpr>(address.get())) {
2185 const auto bb_address = (BasicBlock *) CE->getZExtValue(Context::get().getPointerWidth());
2186 transferToBasicBlock(bb_address, bi->getParent(), state);
2187 break;
2188 }
2189
2190 // symbolic address
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);
2196
2198 SmallPtrSet<BasicBlock *, 5> destinations;
2199 // collect and check destinations from label list
2200 for (unsigned k = 0; k < numDestinations; ++k) {
2201 // filter duplicates
2202 const auto d = bi->getDestination(k);
2203 if (destinations.count(d)) continue;
2204 destinations.insert(d);
2205
2206 // create address expression
2207 const auto PE = Expr::createPointer(reinterpret_cast<std::uint64_t>(d));
2208 ref<Expr> e = EqExpr::create(address, PE);
2209
2210 // exclude address from errorCase
2211 errorCase = AndExpr::create(errorCase, Expr::createIsZero(e));
2212
2213 // check feasibility
2214 bool result;
2215 bool success __attribute__((unused)) =
2216 solver->mayBeTrue(state.constraints, e, result, state.queryMetaData);
2217 assert(success && "FIXME: Unhandled solver failure");
2218 if (result) {
2219 targets.push_back(d);
2220 expressions.push_back(e);
2221 }
2222 }
2223 // check errorCase feasibility
2224 bool result;
2225 bool success __attribute__((unused)) = solver->mayBeTrue(
2226 state.constraints, errorCase, result, state.queryMetaData);
2227 assert(success && "FIXME: Unhandled solver failure");
2228 if (result) {
2229 expressions.push_back(errorCase);
2230 }
2231
2232 // fork states
2233 std::vector<ExecutionState *> branches;
2234 branch(state, expressions, branches, BranchType::IndirectBranch);
2235
2236 // terminate error state
2237 if (result) {
2238 terminateStateOnExecError(*branches.back(), "indirectbr: illegal label address");
2239 branches.pop_back();
2240 }
2241
2242 // branch states to resp. target blocks
2243 assert(targets.size() == branches.size());
2244 for (std::vector<ExecutionState *>::size_type k = 0; k < branches.size(); ++k) {
2245 if (branches[k]) {
2246 transferToBasicBlock(targets[k], bi->getParent(), *branches[k]);
2247 }
2248 }
2249
2250 break;
2251 }
2252 case Instruction::Switch: {
2253 SwitchInst *si = cast<SwitchInst>(i);
2254 ref<Expr> cond = eval(ki, 0, state).value;
2255 BasicBlock *bb = si->getParent();
2256
2257 cond = toUnique(state, cond);
2258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(cond)) {
2259 // Somewhat gross to create these all the time, but fine till we
2260 // switch to an internal rep.
2261 llvm::IntegerType *Ty = cast<IntegerType>(si->getCondition()->getType());
2262 ConstantInt *ci = ConstantInt::get(Ty, CE->getZExtValue());
2263 unsigned index = si->findCaseValue(ci)->getSuccessorIndex();
2264 transferToBasicBlock(si->getSuccessor(index), si->getParent(), state);
2265 } else {
2266 // Handle possible different branch targets
2267
2268 // We have the following assumptions:
2269 // - each case value is mutual exclusive to all other values
2270 // - order of case branches is based on the order of the expressions of
2271 // the case values, still default is handled last
2272 std::vector<BasicBlock *> bbOrder;
2273 std::map<BasicBlock *, ref<Expr> > branchTargets;
2274
2275 std::map<ref<Expr>, BasicBlock *> expressionOrder;
2276
2277 // Iterate through all non-default cases and order them by expressions
2278 for (auto i : si->cases()) {
2279 ref<Expr> value = evalConstant(i.getCaseValue());
2280
2281 BasicBlock *caseSuccessor = i.getCaseSuccessor();
2282 expressionOrder.insert(std::make_pair(value, caseSuccessor));
2283 }
2284
2285 // Track default branch values
2286 ref<Expr> defaultValue = ConstantExpr::alloc(1, Expr::Bool);
2287
2288 // iterate through all non-default cases but in order of the expressions
2289 for (std::map<ref<Expr>, BasicBlock *>::iterator
2290 it = expressionOrder.begin(),
2291 itE = expressionOrder.end();
2292 it != itE; ++it) {
2293 ref<Expr> match = EqExpr::create(cond, it->first);
2294
2295 // skip if case has same successor basic block as default case
2296 // (should work even with phi nodes as a switch is a single terminating instruction)
2297 if (it->second == si->getDefaultDest()) continue;
2298
2299 // Make sure that the default value does not contain this target's value
2300 defaultValue = AndExpr::create(defaultValue, Expr::createIsZero(match));
2301
2302 // Check if control flow could take this case
2303 bool result;
2304 match = optimizer.optimizeExpr(match, false);
2305 bool success = solver->mayBeTrue(state.constraints, match, result,
2306 state.queryMetaData);
2307 assert(success && "FIXME: Unhandled solver failure");
2308 (void) success;
2309 if (result) {
2310 BasicBlock *caseSuccessor = it->second;
2311
2312 // Handle the case that a basic block might be the target of multiple
2313 // switch cases.
2314 // Currently we generate an expression containing all switch-case
2315 // values for the same target basic block. We spare us forking too
2316 // many times but we generate more complex condition expressions
2317 // TODO Add option to allow to choose between those behaviors
2318 std::pair<std::map<BasicBlock *, ref<Expr> >::iterator, bool> res =
2319 branchTargets.insert(std::make_pair(
2320 caseSuccessor, ConstantExpr::alloc(0, Expr::Bool)));
2321
2322 res.first->second = OrExpr::create(match, res.first->second);
2323
2324 // Only add basic blocks which have not been target of a branch yet
2325 if (res.second) {
2326 bbOrder.push_back(caseSuccessor);
2327 }
2328 }
2329 }
2330
2331 // Check if control could take the default case
2332 defaultValue = optimizer.optimizeExpr(defaultValue, false);
2333 bool res;
2334 bool success = solver->mayBeTrue(state.constraints, defaultValue, res,
2335 state.queryMetaData);
2336 assert(success && "FIXME: Unhandled solver failure");
2337 (void) success;
2338 if (res) {
2339 std::pair<std::map<BasicBlock *, ref<Expr> >::iterator, bool> ret =
2340 branchTargets.insert(
2341 std::make_pair(si->getDefaultDest(), defaultValue));
2342 if (ret.second) {
2343 bbOrder.push_back(si->getDefaultDest());
2344 }
2345 }
2346
2347 // Fork the current state with each state having one of the possible
2348 // successors of this switch
2349 std::vector< ref<Expr> > conditions;
2350 for (std::vector<BasicBlock *>::iterator it = bbOrder.begin(),
2351 ie = bbOrder.end();
2352 it != ie; ++it) {
2353 conditions.push_back(branchTargets[*it]);
2354 }
2355 std::vector<ExecutionState*> branches;
2356 branch(state, conditions, branches, BranchType::Switch);
2357
2358 std::vector<ExecutionState*>::iterator bit = branches.begin();
2359 for (std::vector<BasicBlock *>::iterator it = bbOrder.begin(),
2360 ie = bbOrder.end();
2361 it != ie; ++it) {
2362 ExecutionState *es = *bit;
2363 if (es)
2364 transferToBasicBlock(*it, bb, *es);
2365 ++bit;
2366 }
2367 }
2368 break;
2369 }
2370 case Instruction::Unreachable:
2371 // Note that this is not necessarily an internal bug, llvm will
2372 // generate unreachable instructions in cases where it knows the
2373 // program will crash. So it is effectively a SEGV or internal
2374 // error.
2375 terminateStateOnExecError(state, "reached \"unreachable\" instruction");
2376 break;
2377
2378 case Instruction::Invoke:
2379 case Instruction::Call: {
2380 // Ignore debug intrinsic calls
2381 if (isa<DbgInfoIntrinsic>(i))
2382 break;
2383
2384#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2385 const CallBase &cs = cast<CallBase>(*i);
2386 Value *fp = cs.getCalledOperand();
2387#else
2388 const CallSite cs(i);
2389 Value *fp = cs.getCalledValue();
2390#endif
2391
2392 unsigned numArgs = cs.arg_size();
2393 Function *f = getTargetFunction(fp, state);
2394
2395 if (isa<InlineAsm>(fp)) {
2396 terminateStateOnExecError(state, "inline assembly is unsupported");
2397 break;
2398 }
2399 // evaluate arguments
2400 std::vector< ref<Expr> > arguments;
2401 arguments.reserve(numArgs);
2402
2403 for (unsigned j=0; j<numArgs; ++j)
2404 arguments.push_back(eval(ki, j+1, state).value);
2405
2406 if (f) {
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());
2411
2412 // special case the call with a bitcast case
2413 if (fType != fpType) {
2414 assert(fType && fpType && "unable to get function type");
2415
2416 // XXX check result coercion
2417
2418 // XXX this really needs thought and validation
2419 unsigned i=0;
2420 for (std::vector< ref<Expr> >::iterator
2421 ai = arguments.begin(), ie = arguments.end();
2422 ai != ie; ++ai) {
2423 Expr::Width to, from = (*ai)->getWidth();
2424
2425 if (i<fType->getNumParams()) {
2426 to = getWidthForLLVMType(fType->getParamType(i));
2427
2428 if (from != to) {
2429 // XXX need to check other param attrs ?
2430 bool isSExt = cs.paramHasAttr(i, llvm::Attribute::SExt);
2431 if (isSExt) {
2432 arguments[i] = SExtExpr::create(arguments[i], to);
2433 } else {
2434 arguments[i] = ZExtExpr::create(arguments[i], to);
2435 }
2436 }
2437 }
2438
2439 i++;
2440 }
2441 }
2442
2443 executeCall(state, ki, f, arguments);
2444 } else {
2445 ref<Expr> v = eval(ki, 0, state).value;
2446
2447 ExecutionState *free = &state;
2448 bool hasInvalid = false, first = true;
2449
2450 /* XXX This is wasteful, no need to do a full evaluate since we
2451 have already got a value. But in the end the caches should
2452 handle it for us, albeit with some overhead. */
2453 do {
2454 v = optimizer.optimizeExpr(v, true);
2455 ref<ConstantExpr> value;
2456 bool success =
2457 solver->getValue(free->constraints, v, value, free->queryMetaData);
2458 assert(success && "FIXME: Unhandled solver failure");
2459 (void) success;
2460 StatePair res = fork(*free, EqExpr::create(v, value), true, BranchType::Call);
2461 if (res.first) {
2462 uint64_t addr = value->getZExtValue();
2463 auto it = legalFunctions.find(addr);
2464 if (it != legalFunctions.end()) {
2465 f = it->second;
2466
2467 // Don't give warning on unique resolution
2468 if (res.second || !first)
2469 klee_warning_once(reinterpret_cast<void*>(addr),
2470 "resolved symbolic function pointer to: %s",
2471 f->getName().data());
2472
2473 executeCall(*res.first, ki, f, arguments);
2474 } else {
2475 if (!hasInvalid) {
2476 terminateStateOnExecError(state, "invalid function pointer");
2477 hasInvalid = true;
2478 }
2479 }
2480 }
2481
2482 first = false;
2483 free = res.second;
2484 } while (free);
2485 }
2486 break;
2487 }
2488 case Instruction::PHI: {
2489 ref<Expr> result = eval(ki, state.incomingBBIndex, state).value;
2490 bindLocal(ki, state, result);
2491 break;
2492 }
2493
2494 // Special instructions
2495 case Instruction::Select: {
2496 // NOTE: It is not required that operands 1 and 2 be of scalar type.
2497 ref<Expr> cond = eval(ki, 0, state).value;
2498 ref<Expr> tExpr = eval(ki, 1, state).value;
2499 ref<Expr> fExpr = eval(ki, 2, state).value;
2500 ref<Expr> result = SelectExpr::create(cond, tExpr, fExpr);
2501 bindLocal(ki, state, result);
2502 break;
2503 }
2504
2505 case Instruction::VAArg:
2506 terminateStateOnExecError(state, "unexpected VAArg instruction");
2507 break;
2508
2509 // Arithmetic / logical
2510
2511 case Instruction::Add: {
2512 ref<Expr> left = eval(ki, 0, state).value;
2513 ref<Expr> right = eval(ki, 1, state).value;
2514 bindLocal(ki, state, AddExpr::create(left, right));
2515 break;
2516 }
2517
2518 case Instruction::Sub: {
2519 ref<Expr> left = eval(ki, 0, state).value;
2520 ref<Expr> right = eval(ki, 1, state).value;
2521 bindLocal(ki, state, SubExpr::create(left, right));
2522 break;
2523 }
2524
2525 case Instruction::Mul: {
2526 ref<Expr> left = eval(ki, 0, state).value;
2527 ref<Expr> right = eval(ki, 1, state).value;
2528 bindLocal(ki, state, MulExpr::create(left, right));
2529 break;
2530 }
2531
2532 case Instruction::UDiv: {
2533 ref<Expr> left = eval(ki, 0, state).value;
2534 ref<Expr> right = eval(ki, 1, state).value;
2535 ref<Expr> result = UDivExpr::create(left, right);
2536 bindLocal(ki, state, result);
2537 break;
2538 }
2539
2540 case Instruction::SDiv: {
2541 ref<Expr> left = eval(ki, 0, state).value;
2542 ref<Expr> right = eval(ki, 1, state).value;
2543 ref<Expr> result = SDivExpr::create(left, right);
2544 bindLocal(ki, state, result);
2545 break;
2546 }
2547
2548 case Instruction::URem: {
2549 ref<Expr> left = eval(ki, 0, state).value;
2550 ref<Expr> right = eval(ki, 1, state).value;
2551 ref<Expr> result = URemExpr::create(left, right);
2552 bindLocal(ki, state, result);
2553 break;
2554 }
2555
2556 case Instruction::SRem: {
2557 ref<Expr> left = eval(ki, 0, state).value;
2558 ref<Expr> right = eval(ki, 1, state).value;
2559 ref<Expr> result = SRemExpr::create(left, right);
2560 bindLocal(ki, state, result);
2561 break;
2562 }
2563
2564 case Instruction::And: {
2565 ref<Expr> left = eval(ki, 0, state).value;
2566 ref<Expr> right = eval(ki, 1, state).value;
2567 ref<Expr> result = AndExpr::create(left, right);
2568 bindLocal(ki, state, result);
2569 break;
2570 }
2571
2572 case Instruction::Or: {
2573 ref<Expr> left = eval(ki, 0, state).value;
2574 ref<Expr> right = eval(ki, 1, state).value;
2575 ref<Expr> result = OrExpr::create(left, right);
2576 bindLocal(ki, state, result);
2577 break;
2578 }
2579
2580 case Instruction::Xor: {
2581 ref<Expr> left = eval(ki, 0, state).value;
2582 ref<Expr> right = eval(ki, 1, state).value;
2583 ref<Expr> result = XorExpr::create(left, right);
2584 bindLocal(ki, state, result);
2585 break;
2586 }
2587
2588 case Instruction::Shl: {
2589 ref<Expr> left = eval(ki, 0, state).value;
2590 ref<Expr> right = eval(ki, 1, state).value;
2591 ref<Expr> result = ShlExpr::create(left, right);
2592 bindLocal(ki, state, result);
2593 break;
2594 }
2595
2596 case Instruction::LShr: {
2597 ref<Expr> left = eval(ki, 0, state).value;
2598 ref<Expr> right = eval(ki, 1, state).value;
2599 ref<Expr> result = LShrExpr::create(left, right);
2600 bindLocal(ki, state, result);
2601 break;
2602 }
2603
2604 case Instruction::AShr: {
2605 ref<Expr> left = eval(ki, 0, state).value;
2606 ref<Expr> right = eval(ki, 1, state).value;
2607 ref<Expr> result = AShrExpr::create(left, right);
2608 bindLocal(ki, state, result);
2609 break;
2610 }
2611
2612 // Compare
2613
2614 case Instruction::ICmp: {
2615 CmpInst *ci = cast<CmpInst>(i);
2616 ICmpInst *ii = cast<ICmpInst>(ci);
2617
2618 switch(ii->getPredicate()) {
2619 case ICmpInst::ICMP_EQ: {
2620 ref<Expr> left = eval(ki, 0, state).value;
2621 ref<Expr> right = eval(ki, 1, state).value;
2622 ref<Expr> result = EqExpr::create(left, right);
2623 bindLocal(ki, state, result);
2624 break;
2625 }
2626
2627 case ICmpInst::ICMP_NE: {
2628 ref<Expr> left = eval(ki, 0, state).value;
2629 ref<Expr> right = eval(ki, 1, state).value;
2630 ref<Expr> result = NeExpr::create(left, right);
2631 bindLocal(ki, state, result);
2632 break;
2633 }
2634
2635 case ICmpInst::ICMP_UGT: {
2636 ref<Expr> left = eval(ki, 0, state).value;
2637 ref<Expr> right = eval(ki, 1, state).value;
2638 ref<Expr> result = UgtExpr::create(left, right);
2639 bindLocal(ki, state,result);
2640 break;
2641 }
2642
2643 case ICmpInst::ICMP_UGE: {
2644 ref<Expr> left = eval(ki, 0, state).value;
2645 ref<Expr> right = eval(ki, 1, state).value;
2646 ref<Expr> result = UgeExpr::create(left, right);
2647 bindLocal(ki, state, result);
2648 break;
2649 }
2650
2651 case ICmpInst::ICMP_ULT: {
2652 ref<Expr> left = eval(ki, 0, state).value;
2653 ref<Expr> right = eval(ki, 1, state).value;
2654 ref<Expr> result = UltExpr::create(left, right);
2655 bindLocal(ki, state, result);
2656 break;
2657 }
2658
2659 case ICmpInst::ICMP_ULE: {
2660 ref<Expr> left = eval(ki, 0, state).value;
2661 ref<Expr> right = eval(ki, 1, state).value;
2662 ref<Expr> result = UleExpr::create(left, right);
2663 bindLocal(ki, state, result);
2664 break;
2665 }
2666
2667 case ICmpInst::ICMP_SGT: {
2668 ref<Expr> left = eval(ki, 0, state).value;
2669 ref<Expr> right = eval(ki, 1, state).value;
2670 ref<Expr> result = SgtExpr::create(left, right);
2671 bindLocal(ki, state, result);
2672 break;
2673 }
2674
2675 case ICmpInst::ICMP_SGE: {
2676 ref<Expr> left = eval(ki, 0, state).value;
2677 ref<Expr> right = eval(ki, 1, state).value;
2678 ref<Expr> result = SgeExpr::create(left, right);
2679 bindLocal(ki, state, result);
2680 break;
2681 }
2682
2683 case ICmpInst::ICMP_SLT: {
2684 ref<Expr> left = eval(ki, 0, state).value;
2685 ref<Expr> right = eval(ki, 1, state).value;
2686 ref<Expr> result = SltExpr::create(left, right);
2687 bindLocal(ki, state, result);
2688 break;
2689 }
2690
2691 case ICmpInst::ICMP_SLE: {
2692 ref<Expr> left = eval(ki, 0, state).value;
2693 ref<Expr> right = eval(ki, 1, state).value;
2694 ref<Expr> result = SleExpr::create(left, right);
2695 bindLocal(ki, state, result);
2696 break;
2697 }
2698
2699 default:
2700 terminateStateOnExecError(state, "invalid ICmp predicate");
2701 }
2702 break;
2703 }
2704
2705 // Memory instructions...
2706 case Instruction::Alloca: {
2707 AllocaInst *ai = cast<AllocaInst>(i);
2708 unsigned elementSize =
2709 kmodule->targetData->getTypeStoreSize(ai->getAllocatedType());
2710 ref<Expr> size = Expr::createPointer(elementSize);
2711 if (ai->isArrayAllocation()) {
2712 ref<Expr> count = eval(ki, 0, state).value;
2713 count = Expr::createZExtToPointerWidth(count);
2714 size = MulExpr::create(size, count);
2715 }
2716 executeAlloc(state, size, true, ki);
2717 break;
2718 }
2719
2720 case Instruction::Load: {
2721 ref<Expr> base = eval(ki, 0, state).value;
2722 executeMemoryOperation(state, false, base, 0, ki);
2723 break;
2724 }
2725 case Instruction::Store: {
2726 ref<Expr> base = eval(ki, 1, state).value;
2727 ref<Expr> value = eval(ki, 0, state).value;
2728 executeMemoryOperation(state, true, base, value, 0);
2729 break;
2730 }
2731
2732 case Instruction::GetElementPtr: {
2733 KGEPInstruction *kgepi = static_cast<KGEPInstruction*>(ki);
2734 ref<Expr> base = eval(ki, 0, state).value;
2735
2736 for (std::vector< std::pair<unsigned, uint64_t> >::iterator
2737 it = kgepi->indices.begin(), ie = kgepi->indices.end();
2738 it != ie; ++it) {
2739 uint64_t elementSize = it->second;
2740 ref<Expr> index = eval(ki, it->first, state).value;
2741 base = AddExpr::create(base,
2742 MulExpr::create(Expr::createSExtToPointerWidth(index),
2743 Expr::createPointer(elementSize)));
2744 }
2745 if (kgepi->offset)
2746 base = AddExpr::create(base,
2747 Expr::createPointer(kgepi->offset));
2748 bindLocal(ki, state, base);
2749 break;
2750 }
2751
2752 // Conversion
2753 case Instruction::Trunc: {
2754 CastInst *ci = cast<CastInst>(i);
2755 ref<Expr> result = ExtractExpr::create(eval(ki, 0, state).value,
2756 0,
2757 getWidthForLLVMType(ci->getType()));
2758 bindLocal(ki, state, result);
2759 break;
2760 }
2761 case Instruction::ZExt: {
2762 CastInst *ci = cast<CastInst>(i);
2763 ref<Expr> result = ZExtExpr::create(eval(ki, 0, state).value,
2764 getWidthForLLVMType(ci->getType()));
2765 bindLocal(ki, state, result);
2766 break;
2767 }
2768 case Instruction::SExt: {
2769 CastInst *ci = cast<CastInst>(i);
2770 ref<Expr> result = SExtExpr::create(eval(ki, 0, state).value,
2771 getWidthForLLVMType(ci->getType()));
2772 bindLocal(ki, state, result);
2773 break;
2774 }
2775
2776 case Instruction::IntToPtr: {
2777 CastInst *ci = cast<CastInst>(i);
2778 Expr::Width pType = getWidthForLLVMType(ci->getType());
2779 ref<Expr> arg = eval(ki, 0, state).value;
2780 bindLocal(ki, state, ZExtExpr::create(arg, pType));
2781 break;
2782 }
2783 case Instruction::PtrToInt: {
2784 CastInst *ci = cast<CastInst>(i);
2785 Expr::Width iType = getWidthForLLVMType(ci->getType());
2786 ref<Expr> arg = eval(ki, 0, state).value;
2787 bindLocal(ki, state, ZExtExpr::create(arg, iType));
2788 break;
2789 }
2790
2791 case Instruction::BitCast: {
2792 ref<Expr> result = eval(ki, 0, state).value;
2793 bindLocal(ki, state, result);
2794 break;
2795 }
2796
2797 // Floating point instructions
2798
2799#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
2800 case Instruction::FNeg: {
2801 ref<ConstantExpr> arg =
2802 toConstant(state, eval(ki, 0, state).value, "floating point");
2803 if (!fpWidthToSemantics(arg->getWidth()))
2804 return terminateStateOnExecError(state, "Unsupported FNeg operation");
2805
2806 llvm::APFloat Res(*fpWidthToSemantics(arg->getWidth()), arg->getAPValue());
2807 Res = llvm::neg(Res);
2808 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2809 break;
2810 }
2811#endif
2812
2813 case Instruction::FAdd: {
2814 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2815 "floating point");
2816 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2817 "floating point");
2818 if (!fpWidthToSemantics(left->getWidth()) ||
2819 !fpWidthToSemantics(right->getWidth()))
2820 return terminateStateOnExecError(state, "Unsupported FAdd operation");
2821
2822 llvm::APFloat Res(*fpWidthToSemantics(left->getWidth()), left->getAPValue());
2823 Res.add(APFloat(*fpWidthToSemantics(right->getWidth()),right->getAPValue()), APFloat::rmNearestTiesToEven);
2824 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2825 break;
2826 }
2827
2828 case Instruction::FSub: {
2829 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2830 "floating point");
2831 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2832 "floating point");
2833 if (!fpWidthToSemantics(left->getWidth()) ||
2834 !fpWidthToSemantics(right->getWidth()))
2835 return terminateStateOnExecError(state, "Unsupported FSub operation");
2836 llvm::APFloat Res(*fpWidthToSemantics(left->getWidth()), left->getAPValue());
2837 Res.subtract(APFloat(*fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2838 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2839 break;
2840 }
2841
2842 case Instruction::FMul: {
2843 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2844 "floating point");
2845 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2846 "floating point");
2847 if (!fpWidthToSemantics(left->getWidth()) ||
2848 !fpWidthToSemantics(right->getWidth()))
2849 return terminateStateOnExecError(state, "Unsupported FMul operation");
2850
2851 llvm::APFloat Res(*fpWidthToSemantics(left->getWidth()), left->getAPValue());
2852 Res.multiply(APFloat(*fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2853 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2854 break;
2855 }
2856
2857 case Instruction::FDiv: {
2858 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2859 "floating point");
2860 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2861 "floating point");
2862 if (!fpWidthToSemantics(left->getWidth()) ||
2863 !fpWidthToSemantics(right->getWidth()))
2864 return terminateStateOnExecError(state, "Unsupported FDiv operation");
2865
2866 llvm::APFloat Res(*fpWidthToSemantics(left->getWidth()), left->getAPValue());
2867 Res.divide(APFloat(*fpWidthToSemantics(right->getWidth()), right->getAPValue()), APFloat::rmNearestTiesToEven);
2868 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2869 break;
2870 }
2871
2872 case Instruction::FRem: {
2873 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2874 "floating point");
2875 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2876 "floating point");
2877 if (!fpWidthToSemantics(left->getWidth()) ||
2878 !fpWidthToSemantics(right->getWidth()))
2879 return terminateStateOnExecError(state, "Unsupported FRem operation");
2880 llvm::APFloat Res(*fpWidthToSemantics(left->getWidth()), left->getAPValue());
2881 Res.mod(
2882 APFloat(*fpWidthToSemantics(right->getWidth()), right->getAPValue()));
2883 bindLocal(ki, state, ConstantExpr::alloc(Res.bitcastToAPInt()));
2884 break;
2885 }
2886
2887 case Instruction::FPTrunc: {
2888 FPTruncInst *fi = cast<FPTruncInst>(i);
2889 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2890 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2891 "floating point");
2892 if (!fpWidthToSemantics(arg->getWidth()) || resultType > arg->getWidth())
2893 return terminateStateOnExecError(state, "Unsupported FPTrunc operation");
2894
2895 llvm::APFloat Res(*fpWidthToSemantics(arg->getWidth()), arg->getAPValue());
2896 bool losesInfo = false;
2897 Res.convert(*fpWidthToSemantics(resultType),
2898 llvm::APFloat::rmNearestTiesToEven,
2899 &losesInfo);
2900 bindLocal(ki, state, ConstantExpr::alloc(Res));
2901 break;
2902 }
2903
2904 case Instruction::FPExt: {
2905 FPExtInst *fi = cast<FPExtInst>(i);
2906 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2907 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2908 "floating point");
2909 if (!fpWidthToSemantics(arg->getWidth()) || arg->getWidth() > resultType)
2910 return terminateStateOnExecError(state, "Unsupported FPExt operation");
2911 llvm::APFloat Res(*fpWidthToSemantics(arg->getWidth()), arg->getAPValue());
2912 bool losesInfo = false;
2913 Res.convert(*fpWidthToSemantics(resultType),
2914 llvm::APFloat::rmNearestTiesToEven,
2915 &losesInfo);
2916 bindLocal(ki, state, ConstantExpr::alloc(Res));
2917 break;
2918 }
2919
2920 case Instruction::FPToUI: {
2921 FPToUIInst *fi = cast<FPToUIInst>(i);
2922 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2923 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2924 "floating point");
2925 if (!fpWidthToSemantics(arg->getWidth()) || resultType > 64)
2926 return terminateStateOnExecError(state, "Unsupported FPToUI operation");
2927
2928 llvm::APFloat Arg(*fpWidthToSemantics(arg->getWidth()), arg->getAPValue());
2929 uint64_t value = 0;
2930 bool isExact = true;
2931 auto valueRef = makeMutableArrayRef(value);
2932 Arg.convertToInteger(valueRef, resultType, false,
2933 llvm::APFloat::rmTowardZero, &isExact);
2934 bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
2935 break;
2936 }
2937
2938 case Instruction::FPToSI: {
2939 FPToSIInst *fi = cast<FPToSIInst>(i);
2940 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2941 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2942 "floating point");
2943 if (!fpWidthToSemantics(arg->getWidth()) || resultType > 64)
2944 return terminateStateOnExecError(state, "Unsupported FPToSI operation");
2945 llvm::APFloat Arg(*fpWidthToSemantics(arg->getWidth()), arg->getAPValue());
2946
2947 uint64_t value = 0;
2948 bool isExact = true;
2949 auto valueRef = makeMutableArrayRef(value);
2950 Arg.convertToInteger(valueRef, resultType, true,
2951 llvm::APFloat::rmTowardZero, &isExact);
2952 bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
2953 break;
2954 }
2955
2956 case Instruction::UIToFP: {
2957 UIToFPInst *fi = cast<UIToFPInst>(i);
2958 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2959 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2960 "floating point");
2961 const llvm::fltSemantics *semantics = fpWidthToSemantics(resultType);
2962 if (!semantics)
2963 return terminateStateOnExecError(state, "Unsupported UIToFP operation");
2964 llvm::APFloat f(*semantics, 0);
2965 f.convertFromAPInt(arg->getAPValue(), false,
2966 llvm::APFloat::rmNearestTiesToEven);
2967
2968 bindLocal(ki, state, ConstantExpr::alloc(f));
2969 break;
2970 }
2971
2972 case Instruction::SIToFP: {
2973 SIToFPInst *fi = cast<SIToFPInst>(i);
2974 Expr::Width resultType = getWidthForLLVMType(fi->getType());
2975 ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
2976 "floating point");
2977 const llvm::fltSemantics *semantics = fpWidthToSemantics(resultType);
2978 if (!semantics)
2979 return terminateStateOnExecError(state, "Unsupported SIToFP operation");
2980 llvm::APFloat f(*semantics, 0);
2981 f.convertFromAPInt(arg->getAPValue(), true,
2982 llvm::APFloat::rmNearestTiesToEven);
2983
2984 bindLocal(ki, state, ConstantExpr::alloc(f));
2985 break;
2986 }
2987
2988 case Instruction::FCmp: {
2989 FCmpInst *fi = cast<FCmpInst>(i);
2990 ref<ConstantExpr> left = toConstant(state, eval(ki, 0, state).value,
2991 "floating point");
2992 ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
2993 "floating point");
2994 if (!fpWidthToSemantics(left->getWidth()) ||
2995 !fpWidthToSemantics(right->getWidth()))
2996 return terminateStateOnExecError(state, "Unsupported FCmp operation");
2997
2998 APFloat LHS(*fpWidthToSemantics(left->getWidth()),left->getAPValue());
2999 APFloat RHS(*fpWidthToSemantics(right->getWidth()),right->getAPValue());
3000 APFloat::cmpResult CmpRes = LHS.compare(RHS);
3001
3002 bool Result = false;
3003 switch( fi->getPredicate() ) {
3004 // Predicates which only care about whether or not the operands are NaNs.
3005 case FCmpInst::FCMP_ORD:
3006 Result = (CmpRes != APFloat::cmpUnordered);
3007 break;
3008
3009 case FCmpInst::FCMP_UNO:
3010 Result = (CmpRes == APFloat::cmpUnordered);
3011 break;
3012
3013 // Ordered comparisons return false if either operand is NaN. Unordered
3014 // comparisons return true if either operand is NaN.
3015 case FCmpInst::FCMP_UEQ:
3016 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpEqual);
3017 break;
3018 case FCmpInst::FCMP_OEQ:
3019 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpEqual);
3020 break;
3021
3022 case FCmpInst::FCMP_UGT:
3023 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpGreaterThan);
3024 break;
3025 case FCmpInst::FCMP_OGT:
3026 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpGreaterThan);
3027 break;
3028
3029 case FCmpInst::FCMP_UGE:
3030 Result = (CmpRes == APFloat::cmpUnordered || (CmpRes == APFloat::cmpGreaterThan || CmpRes == APFloat::cmpEqual));
3031 break;
3032 case FCmpInst::FCMP_OGE:
3033 Result = (CmpRes != APFloat::cmpUnordered && (CmpRes == APFloat::cmpGreaterThan || CmpRes == APFloat::cmpEqual));
3034 break;
3035
3036 case FCmpInst::FCMP_ULT:
3037 Result = (CmpRes == APFloat::cmpUnordered || CmpRes == APFloat::cmpLessThan);
3038 break;
3039 case FCmpInst::FCMP_OLT:
3040 Result = (CmpRes != APFloat::cmpUnordered && CmpRes == APFloat::cmpLessThan);
3041 break;
3042
3043 case FCmpInst::FCMP_ULE:
3044 Result = (CmpRes == APFloat::cmpUnordered || (CmpRes == APFloat::cmpLessThan || CmpRes == APFloat::cmpEqual));
3045 break;
3046 case FCmpInst::FCMP_OLE:
3047 Result = (CmpRes != APFloat::cmpUnordered && (CmpRes == APFloat::cmpLessThan || CmpRes == APFloat::cmpEqual));
3048 break;
3049
3050 case FCmpInst::FCMP_UNE:
3051 Result = (CmpRes == APFloat::cmpUnordered || CmpRes != APFloat::cmpEqual);
3052 break;
3053 case FCmpInst::FCMP_ONE:
3054 Result = (CmpRes != APFloat::cmpUnordered && CmpRes != APFloat::cmpEqual);
3055 break;
3056
3057 default:
3058 assert(0 && "Invalid FCMP predicate!");
3059 break;
3060 case FCmpInst::FCMP_FALSE:
3061 Result = false;
3062 break;
3063 case FCmpInst::FCMP_TRUE:
3064 Result = true;
3065 break;
3066 }
3067
3068 bindLocal(ki, state, ConstantExpr::alloc(Result, Expr::Bool));
3069 break;
3070 }
3071 case Instruction::InsertValue: {
3072 KGEPInstruction *kgepi = static_cast<KGEPInstruction*>(ki);
3073
3074 ref<Expr> agg = eval(ki, 0, state).value;
3075 ref<Expr> val = eval(ki, 1, state).value;
3076
3077 ref<Expr> l = NULL, r = NULL;
3078 unsigned lOffset = kgepi->offset*8, rOffset = kgepi->offset*8 + val->getWidth();
3079
3080 if (lOffset > 0)
3081 l = ExtractExpr::create(agg, 0, lOffset);
3082 if (rOffset < agg->getWidth())
3083 r = ExtractExpr::create(agg, rOffset, agg->getWidth() - rOffset);
3084
3085 ref<Expr> result;
3086 if (l && r)
3087 result = ConcatExpr::create(r, ConcatExpr::create(val, l));
3088 else if (l)
3089 result = ConcatExpr::create(val, l);
3090 else if (r)
3091 result = ConcatExpr::create(r, val);
3092 else
3093 result = val;
3094
3095 bindLocal(ki, state, result);
3096 break;
3097 }
3098 case Instruction::ExtractValue: {
3099 KGEPInstruction *kgepi = static_cast<KGEPInstruction*>(ki);
3100
3101 ref<Expr> agg = eval(ki, 0, state).value;
3102
3103 ref<Expr> result = ExtractExpr::create(agg, kgepi->offset*8, getWidthForLLVMType(i->getType()));
3104
3105 bindLocal(ki, state, result);
3106 break;
3107 }
3108 case Instruction::Fence: {
3109 // Ignore for now
3110 break;
3111 }
3112 case Instruction::InsertElement: {
3113 InsertElementInst *iei = cast<InsertElementInst>(i);
3114 ref<Expr> vec = eval(ki, 0, state).value;
3115 ref<Expr> newElt = eval(ki, 1, state).value;
3116 ref<Expr> idx = eval(ki, 2, state).value;
3117
3118 ConstantExpr *cIdx = dyn_cast<ConstantExpr>(idx);
3119 if (cIdx == NULL) {
3121 state, "InsertElement, support for symbolic index not implemented");
3122 return;
3123 }
3124 uint64_t iIdx = cIdx->getZExtValue();
3125#if LLVM_VERSION_MAJOR >= 11
3126 const auto *vt = cast<llvm::FixedVectorType>(iei->getType());
3127#else
3128 const llvm::VectorType *vt = iei->getType();
3129#endif
3130 unsigned EltBits = getWidthForLLVMType(vt->getElementType());
3131
3132 if (iIdx >= vt->getNumElements()) {
3133 // Out of bounds write
3134 terminateStateOnError(state, "Out of bounds write when inserting element",
3135 StateTerminationType::BadVectorAccess);
3136 return;
3137 }
3138
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) {
3143 auto of = i - 1;
3144 unsigned bitOffset = EltBits * of;
3145 elems.push_back(
3146 of == iIdx ? newElt : ExtractExpr::create(vec, bitOffset, EltBits));
3147 }
3148
3149 assert(Context::get().isLittleEndian() && "FIXME:Broken for big endian");
3150 ref<Expr> Result = ConcatExpr::createN(elementCount, elems.data());
3151 bindLocal(ki, state, Result);
3152 break;
3153 }
3154 case Instruction::ExtractElement: {
3155 ExtractElementInst *eei = cast<ExtractElementInst>(i);
3156 ref<Expr> vec = eval(ki, 0, state).value;
3157 ref<Expr> idx = eval(ki, 1, state).value;
3158
3159 ConstantExpr *cIdx = dyn_cast<ConstantExpr>(idx);
3160 if (cIdx == NULL) {
3162 state, "ExtractElement, support for symbolic index not implemented");
3163 return;
3164 }
3165 uint64_t iIdx = cIdx->getZExtValue();
3166#if LLVM_VERSION_MAJOR >= 11
3167 const auto *vt = cast<llvm::FixedVectorType>(eei->getVectorOperandType());
3168#else
3169 const llvm::VectorType *vt = eei->getVectorOperandType();
3170#endif
3171 unsigned EltBits = getWidthForLLVMType(vt->getElementType());
3172
3173 if (iIdx >= vt->getNumElements()) {
3174 // Out of bounds read
3175 terminateStateOnError(state, "Out of bounds read when extracting element",
3176 StateTerminationType::BadVectorAccess);
3177 return;
3178 }
3179
3180 unsigned bitOffset = EltBits * iIdx;
3181 ref<Expr> Result = ExtractExpr::create(vec, bitOffset, EltBits);
3182 bindLocal(ki, state, Result);
3183 break;
3184 }
3185 case Instruction::ShuffleVector:
3186 // Should never happen due to Scalarizer pass removing ShuffleVector
3187 // instructions.
3188 terminateStateOnExecError(state, "Unexpected ShuffleVector instruction");
3189 break;
3190
3191#ifdef SUPPORT_KLEE_EH_CXX
3192 case Instruction::Resume: {
3193 auto *cui = dyn_cast_or_null<CleanupPhaseUnwindingInformation>(
3194 state.unwindingInformation.get());
3195
3196 if (!cui) {
3198 state,
3199 "resume-instruction executed outside of cleanup phase unwinding");
3200 break;
3201 }
3202
3203 ref<Expr> arg = eval(ki, 0, state).value;
3204 ref<Expr> exceptionPointer = ExtractExpr::create(arg, 0, Expr::Int64);
3205 ref<Expr> selectorValue =
3207
3208 if (!dyn_cast<ConstantExpr>(exceptionPointer) ||
3209 !dyn_cast<ConstantExpr>(selectorValue)) {
3211 state, "resume-instruction called with non constant expression");
3212 break;
3213 }
3214
3215 if (!Expr::createIsZero(selectorValue)->isTrue()) {
3216 klee_warning("resume-instruction called with non-0 selector value");
3217 }
3218
3219 if (!EqExpr::create(exceptionPointer, cui->exceptionObject)->isTrue()) {
3221 state, "resume-instruction called with unexpected exception pointer");
3222 break;
3223 }
3224
3226 break;
3227 }
3228
3229 case Instruction::LandingPad: {
3230 auto *cui = dyn_cast_or_null<CleanupPhaseUnwindingInformation>(
3231 state.unwindingInformation.get());
3232
3233 if (!cui) {
3235 state, "Executing landing pad but not in unwinding phase 2");
3236 break;
3237 }
3238
3239 ref<ConstantExpr> exceptionPointer = cui->exceptionObject;
3240 ref<ConstantExpr> selectorValue;
3241
3242 // check on which frame we are currently
3243 if (state.stack.size() - 1 == cui->catchingStackIndex) {
3244 // we are in the target stack frame, return the selector value
3245 // that was returned by the personality fn in phase 1 and stop unwinding.
3246 selectorValue = cui->selectorValue;
3247
3248 // stop unwinding by cleaning up our unwinding information.
3249 state.unwindingInformation.reset();
3250
3251 // this would otherwise now be a dangling pointer
3252 cui = nullptr;
3253 } else {
3254 // we are not yet at the target stack frame. the landingpad might have
3255 // a cleanup clause or not, anyway, we give it the selector value "0",
3256 // which represents a cleanup, and expect it to handle it.
3257 // This is explicitly allowed by LLVM, see
3258 // https://llvm.org/docs/ExceptionHandling.html#id18
3259 selectorValue = ConstantExpr::create(0, Expr::Int32);
3260 }
3261
3262 // we have to return a {i8*, i32}
3264 ZExtExpr::create(selectorValue, Expr::Int32), exceptionPointer);
3265
3266 bindLocal(ki, state, result);
3267
3268 break;
3269 }
3270#endif // SUPPORT_KLEE_EH_CXX
3271
3272 case Instruction::AtomicRMW:
3273 terminateStateOnExecError(state, "Unexpected Atomic instruction, should be "
3274 "lowered by LowerAtomicInstructionPass");
3275 break;
3276 case Instruction::AtomicCmpXchg:
3278 "Unexpected AtomicCmpXchg instruction, should be "
3279 "lowered by LowerAtomicInstructionPass");
3280 break;
3281 // Other instructions...
3282 // Unhandled
3283 default:
3284 terminateStateOnExecError(state, "illegal instruction");
3285 break;
3286 }
3287}
3288
3290 if (searcher) {
3292 }
3293
3294 states.insert(addedStates.begin(), addedStates.end());
3295 addedStates.clear();
3296
3297 for (std::vector<ExecutionState *>::iterator it = removedStates.begin(),
3298 ie = removedStates.end();
3299 it != ie; ++it) {
3300 ExecutionState *es = *it;
3301 std::set<ExecutionState*>::iterator it2 = states.find(es);
3302 assert(it2!=states.end());
3303 states.erase(it2);
3304 std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it3 =
3305 seedMap.find(es);
3306 if (it3 != seedMap.end())
3307 seedMap.erase(it3);
3308 processTree->remove(es->ptreeNode);
3309 delete es;
3310 }
3311 removedStates.clear();
3312}
3313
3314template <typename SqType, typename TypeIt>
3316 ref<ConstantExpr> &constantOffset,
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)) {
3323 ref<ConstantExpr> index =
3324 evalConstant(c)->SExt(Context::get().getPointerWidth());
3325 ref<ConstantExpr> addend = index->Mul(
3326 ConstantExpr::alloc(elementSize, Context::get().getPointerWidth()));
3327 constantOffset = constantOffset->Add(addend);
3328 } else {
3329 kgepi->indices.emplace_back(index, elementSize);
3330 }
3331}
3332
3333template <typename TypeIt>
3334void Executor::computeOffsets(KGEPInstruction *kgepi, TypeIt ib, TypeIt ie) {
3335 ref<ConstantExpr> constantOffset =
3336 ConstantExpr::alloc(0, Context::get().getPointerWidth());
3337 uint64_t index = 1;
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());
3343 constantOffset = constantOffset->Add(ConstantExpr::alloc(addend,
3344 Context::get().getPointerWidth()));
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);
3351 } else
3352 assert("invalid type" && 0);
3353 index++;
3354 }
3355 kgepi->offset = constantOffset->getZExtValue();
3356}
3357
3359 if (GetElementPtrInst *gepi = dyn_cast<GetElementPtrInst>(KI->inst)) {
3360 KGEPInstruction *kgepi = static_cast<KGEPInstruction *>(KI);
3361 computeOffsets(kgepi, gep_type_begin(gepi), gep_type_end(gepi));
3362 } else if (InsertValueInst *ivi = dyn_cast<InsertValueInst>(KI->inst)) {
3363 KGEPInstruction *kgepi = static_cast<KGEPInstruction *>(KI);
3364 computeOffsets(kgepi, iv_type_begin(ivi), iv_type_end(ivi));
3365 assert(kgepi->indices.empty() && "InsertValue constant offset expected");
3366 } else if (ExtractValueInst *evi = dyn_cast<ExtractValueInst>(KI->inst)) {
3367 KGEPInstruction *kgepi = static_cast<KGEPInstruction *>(KI);
3368 computeOffsets(kgepi, ev_type_begin(evi), ev_type_end(evi));
3369 assert(kgepi->indices.empty() && "ExtractValue constant offset expected");
3370 }
3371}
3372
3374 for (auto &kfp : kmodule->functions) {
3375 KFunction *kf = kfp.get();
3376 for (unsigned i=0; i<kf->numInstructions; ++i)
3378 }
3379
3380 kmodule->constantTable =
3381 std::unique_ptr<Cell[]>(new Cell[kmodule->constants.size()]);
3382 for (unsigned i=0; i<kmodule->constants.size(); ++i) {
3383 Cell &c = kmodule->constantTable[i];
3384 c.value = evalConstant(kmodule->constants[i]);
3385 }
3386}
3387
3389 if (!MaxMemory) return true;
3390
3391 // We need to avoid calling GetTotalMallocUsage() often because it
3392 // is O(elts on freelist). This is really bad since we start
3393 // to pummel the freelist once we hit the memory cap.
3394 if ((stats::instructions & 0xFFFFU) != 0) // every 65536 instructions
3395 return true;
3396
3397 // check memory limit
3398 const auto mallocUsage = util::GetTotalMallocUsage() >> 20U;
3399 const auto mmapUsage = memory->getUsedDeterministicSize() >> 20U;
3400 const auto totalUsage = mallocUsage + mmapUsage;
3401 atMemoryLimit = totalUsage > MaxMemory; // inhibit forking
3402 if (!atMemoryLimit)
3403 return true;
3404
3405 // only terminate states when threshold (+100MB) exceeded
3406 if (totalUsage <= MaxMemory + 100)
3407 return true;
3408
3409 // just guess at how many to kill
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);
3413
3414 // randomly select states for early termination
3415 std::vector<ExecutionState *> arr(states.begin(), states.end()); // FIXME: expensive
3416 for (unsigned i = 0, N = arr.size(); N && i < toKill; ++i, --N) {
3417 unsigned idx = theRNG.getInt32() % N;
3418 // Make two pulls to try and not hit a state that
3419 // covered new code.
3420 if (arr[idx]->coveredNew)
3421 idx = theRNG.getInt32() % N;
3422
3423 std::swap(arr[idx], arr[N - 1]);
3424 terminateStateEarly(*arr[N - 1], "Memory limit exceeded.", StateTerminationType::OutOfMemory);
3425 }
3426
3427 return false;
3428}
3429
3431 if (!DumpStatesOnHalt || states.empty()) {
3433 return;
3434 }
3435
3436 klee_message("halting execution, dumping remaining states");
3437 for (const auto &state : states)
3438 terminateStateEarly(*state, "Execution halting.", StateTerminationType::Interrupted);
3439 updateStates(nullptr);
3440}
3441
3442void Executor::run(ExecutionState &initialState) {
3444
3445 // Delay init till now so that ticks don't accrue during optimization and such.
3446 timers.reset();
3447
3448 states.insert(&initialState);
3449
3450 if (usingSeeds) {
3451 std::vector<SeedInfo> &v = seedMap[&initialState];
3452
3453 for (std::vector<KTest*>::const_iterator it = usingSeeds->begin(),
3454 ie = usingSeeds->end(); it != ie; ++it)
3455 v.push_back(SeedInfo(*it));
3456
3457 int lastNumSeeds = usingSeeds->size()+10;
3458 time::Point lastTime, startTime = lastTime = time::getWallTime();
3459 ExecutionState *lastState = 0;
3460 while (!seedMap.empty()) {
3461 if (haltExecution) {
3462 doDumpStates();
3463 return;
3464 }
3465
3466 std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it =
3467 seedMap.upper_bound(lastState);
3468 if (it == seedMap.end())
3469 it = seedMap.begin();
3470 lastState = it->first;
3471 ExecutionState &state = *lastState;
3472 KInstruction *ki = state.pc;
3473 stepInstruction(state);
3474
3475 executeInstruction(state, ki);
3476 timers.invoke();
3477 if (::dumpStates) dumpStates();
3478 if (::dumpPTree) dumpPTree();
3479 updateStates(&state);
3480
3481 if ((stats::instructions % 1000) == 0) {
3482 int numSeeds = 0, numStates = 0;
3483 for (std::map<ExecutionState*, std::vector<SeedInfo> >::iterator
3484 it = seedMap.begin(), ie = seedMap.end();
3485 it != ie; ++it) {
3486 numSeeds += it->second.size();
3487 numStates++;
3488 }
3489 const auto time = time::getWallTime();
3490 const time::Span seedTime(SeedTime);
3491 if (seedTime && time > startTime + seedTime) {
3492 klee_warning("seed time expired, %d seeds remain over %d states",
3493 numSeeds, numStates);
3494 break;
3495 } else if (numSeeds<=lastNumSeeds-10 ||
3496 time - lastTime >= time::seconds(10)) {
3497 lastTime = time;
3498 lastNumSeeds = numSeeds;
3499 klee_message("%d seeds remaining over: %d states",
3500 numSeeds, numStates);
3501 }
3502 }
3503 }
3504
3505 klee_message("seeding done (%d states remain)", (int) states.size());
3506
3507 if (OnlySeed) {
3508 doDumpStates();
3509 return;
3510 }
3511 }
3512
3514
3515 std::vector<ExecutionState *> newStates(states.begin(), states.end());
3516 searcher->update(0, newStates, std::vector<ExecutionState *>());
3517
3518 // main interpreter loop
3519 while (!states.empty() && !haltExecution) {
3521 KInstruction *ki = state.pc;
3522 stepInstruction(state);
3523
3524 executeInstruction(state, ki);
3525 timers.invoke();
3526 if (::dumpStates) dumpStates();
3527 if (::dumpPTree) dumpPTree();
3528
3529 updateStates(&state);
3530
3531 if (!checkMemoryUsage()) {
3532 // update searchers when states were terminated early due to memory pressure
3533 updateStates(nullptr);
3534 }
3535 }
3536
3537 delete searcher;
3538 searcher = nullptr;
3539
3540 doDumpStates();
3541}
3542
3544 ref<Expr> address) const{
3545 std::string Str;
3546 llvm::raw_string_ostream info(Str);
3547 info << "\taddress: " << address << "\n";
3548 uint64_t example;
3549 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(address)) {
3550 example = CE->getZExtValue();
3551 } else {
3552 ref<ConstantExpr> value;
3553 bool success = solver->getValue(state.constraints, address, value,
3554 state.queryMetaData);
3555 assert(success && "FIXME: Unhandled solver failure");
3556 (void) success;
3557 example = value->getZExtValue();
3558 info << "\texample: " << example << "\n";
3559 std::pair<ref<Expr>, ref<Expr>> res =
3560 solver->getRange(state.constraints, address, state.queryMetaData);
3561 info << "\trange: [" << res.first << ", " << res.second <<"]\n";
3562 }
3563
3564 MemoryObject hack((unsigned) example);
3566 info << "\tnext: ";
3567 if (lower==state.addressSpace.objects.end()) {
3568 info << "none\n";
3569 } else {
3570 const MemoryObject *mo = lower->first;
3571 std::string alloc_info;
3572 mo->getAllocInfo(alloc_info);
3573 info << "object at " << mo->address
3574 << " of size " << mo->size << "\n"
3575 << "\t\t" << alloc_info << "\n";
3576 }
3577 if (lower!=state.addressSpace.objects.begin()) {
3578 --lower;
3579 info << "\tprev: ";
3580 if (lower==state.addressSpace.objects.end()) {
3581 info << "none\n";
3582 } else {
3583 const MemoryObject *mo = lower->first;
3584 std::string alloc_info;
3585 mo->getAllocInfo(alloc_info);
3586 info << "object at " << mo->address
3587 << " of size " << mo->size << "\n"
3588 << "\t\t" << alloc_info << "\n";
3589 }
3590 }
3591
3592 return info.str();
3593}
3594
3595
3599 "replay did not consume all objects in test input.");
3600 }
3601
3603
3604 std::vector<ExecutionState *>::iterator it =
3605 std::find(addedStates.begin(), addedStates.end(), &state);
3606 if (it==addedStates.end()) {
3607 state.pc = state.prevPC;
3608
3609 removedStates.push_back(&state);
3610 } else {
3611 // never reached searcher, just delete immediately
3612 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it3 =
3613 seedMap.find(&state);
3614 if (it3 != seedMap.end())
3615 seedMap.erase(it3);
3616 addedStates.erase(it);
3617 processTree->remove(state.ptreeNode);
3618 delete &state;
3619 }
3620}
3621
3622static bool shouldWriteTest(const ExecutionState &state) {
3623 return !OnlyOutputStatesCoveringNew || state.coveredNew;
3624}
3625
3627 std::string ret;
3628#define TTYPE(N,I,S) case StateTerminationType::N: ret = (S); break;
3629#define MARK(N,I)
3630 switch (type) {
3632 }
3633#undef TTYPE
3634#undef MARK
3635 return ret;
3636};
3637
3639 if (shouldWriteTest(state) || (AlwaysOutputSeeds && seedMap.count(&state)))
3641 state, nullptr,
3642 terminationTypeFileExtension(StateTerminationType::Exit).c_str());
3643
3645 terminateState(state);
3646}
3647
3649 StateTerminationType terminationType) {
3650 if ((terminationType <= StateTerminationType::EXECERR &&
3651 shouldWriteTest(state)) ||
3652 (AlwaysOutputSeeds && seedMap.count(&state))) {
3654 state, (message + "\n").str().c_str(),
3655 terminationTypeFileExtension(terminationType).c_str());
3656 }
3657
3658 terminateState(state);
3659}
3660
3662 terminateStateOnError(state, message, StateTerminationType::User, "");
3663}
3664
3666 Instruction ** lastInstruction) {
3667 // unroll the stack of the applications state and find
3668 // the last instruction which is not inside a KLEE internal function
3669 ExecutionState::stack_ty::const_reverse_iterator it = state.stack.rbegin(),
3670 itE = state.stack.rend();
3671
3672 // don't check beyond the outermost function (i.e. main())
3673 itE--;
3674
3675 const InstructionInfo * ii = 0;
3676 if (kmodule->internalFunctions.count(it->kf->function) == 0){
3677 ii = state.prevPC->info;
3678 *lastInstruction = state.prevPC->inst;
3679 // Cannot return yet because even though
3680 // it->function is not an internal function it might of
3681 // been called from an internal function.
3682 }
3683
3684 // Wind up the stack and check if we are in a KLEE internal function.
3685 // We visit the entire stack because we want to return a CallInstruction
3686 // that was not reached via any KLEE internal functions.
3687 for (;it != itE; ++it) {
3688 // check calling instruction and if it is contained in a KLEE internal function
3689 const Function * f = (*it->caller).inst->getParent()->getParent();
3690 if (kmodule->internalFunctions.count(f)){
3691 ii = 0;
3692 continue;
3693 }
3694 if (!ii){
3695 ii = (*it->caller).info;
3696 *lastInstruction = (*it->caller).inst;
3697 }
3698 }
3699
3700 if (!ii) {
3701 // something went wrong, play safe and return the current instruction info
3702 *lastInstruction = state.prevPC->inst;
3703 return *state.prevPC->info;
3704 }
3705 return *ii;
3706}
3707
3709 auto it = std::find(ExitOnErrorType.begin(), ExitOnErrorType.end(), reason);
3710 return it != ExitOnErrorType.end();
3711}
3712
3714 const llvm::Twine &messaget,
3715 StateTerminationType terminationType,
3716 const llvm::Twine &info,
3717 const char *suffix) {
3718 std::string message = messaget.str();
3719 static std::set< std::pair<Instruction*, std::string> > emittedErrors;
3720 Instruction * lastInst;
3721 const InstructionInfo &ii = getLastNonKleeInternalInstruction(state, &lastInst);
3722
3723 if (EmitAllErrors ||
3724 emittedErrors.insert(std::make_pair(lastInst, message)).second) {
3725 if (!ii.file.empty()) {
3726 klee_message("ERROR: %s:%d: %s", ii.file.c_str(), ii.line, message.c_str());
3727 } else {
3728 klee_message("ERROR: (location information missing) %s", message.c_str());
3729 }
3730 if (!EmitAllErrors)
3731 klee_message("NOTE: now ignoring this error at this location");
3732
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'
3739 << "assembly.ll line: " << ii.assemblyLine << '\n'
3740 << "State: " << state.getID() << '\n';
3741 }
3742 msg << "Stack: \n";
3743 state.dumpStack(msg);
3744
3745 std::string info_str = info.str();
3746 if (!info_str.empty())
3747 msg << "Info: \n" << info_str;
3748
3749 const std::string ext = terminationTypeFileExtension(terminationType);
3750 // use user provided suffix from klee_report_error()
3751 const char * file_suffix = suffix ? suffix : ext.c_str();
3752 interpreterHandler->processTestCase(state, msg.str().c_str(), file_suffix);
3753 }
3754
3755 terminateState(state);
3756
3757 if (shouldExitOn(terminationType))
3758 haltExecution = true;
3759}
3760
3762 const llvm::Twine &message,
3763 const llvm::Twine &info) {
3764 terminateStateOnError(state, message, StateTerminationType::Execution, info);
3765}
3766
3768 const llvm::Twine &message) {
3769 terminateStateOnError(state, message, StateTerminationType::Solver, "");
3770}
3771
3772// XXX shoot me
3773static const char *okExternalsList[] = { "printf",
3774 "fprintf",
3775 "puts",
3776 "getpid" };
3777static std::set<std::string> okExternals(okExternalsList,
3779 (sizeof(okExternalsList)/sizeof(okExternalsList[0])));
3780
3782 KInstruction *target,
3783 Function *function,
3784 std::vector< ref<Expr> > &arguments) {
3785 // check if specialFunctionHandler wants it
3786 if (specialFunctionHandler->handle(state, function, target, arguments))
3787 return;
3788
3789 if (ExternalCalls == ExternalCallPolicy::None &&
3790 !okExternals.count(function->getName().str())) {
3791 klee_warning("Disallowed call to external function: %s\n",
3792 function->getName().str().c_str());
3793 terminateStateOnUserError(state, "external calls disallowed");
3794 return;
3795 }
3796
3797 // normal external function handling path
3798 // allocate 128 bits for each argument (+return value) to support fp80's;
3799 // we could iterate through all the arguments first and determine the exact
3800 // size we need, but this is faster, and the memory usage isn't significant.
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) { // don't bother checking uniqueness
3807 *ai = optimizer.optimizeExpr(*ai, true);
3809 bool success =
3810 solver->getValue(state.constraints, *ai, ce, state.queryMetaData);
3811 assert(success && "FIXME: Unhandled solver failure");
3812 (void) success;
3813 ce->toMemory(&args[wordIndex]);
3814 ObjectPair op;
3815 // Checking to see if the argument is a pointer to something
3816 if (ce->getWidth() == Context::get().getPointerWidth() &&
3817 state.addressSpace.resolveOne(ce, op)) {
3818 op.second->flushToConcreteStore(solver, state);
3819 }
3820 wordIndex += (ce->getWidth()+63)/64;
3821 } else {
3822 ref<Expr> arg = toUnique(state, *ai);
3823 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(arg)) {
3824 // fp80 must be aligned to 16 according to the System V AMD 64 ABI
3825 if (ce->getWidth() == Expr::Fl80 && wordIndex & 0x01)
3826 wordIndex++;
3827
3828 // XXX kick toMemory functions from here
3829 ce->toMemory(&args[wordIndex]);
3830 wordIndex += (ce->getWidth()+63)/64;
3831 } else {
3833 "external call with symbolic argument: " +
3834 function->getName());
3835 return;
3836 }
3837 }
3838 }
3839
3840 // Prepare external memory for invoking the function
3842#ifndef WINDOWS
3843 // Update external errno state with local state value
3844 int *errno_addr = getErrnoLocation(state);
3845 ObjectPair result;
3846 bool resolved = state.addressSpace.resolveOne(
3847 ConstantExpr::create((uint64_t)errno_addr, Expr::Int64), result);
3848 if (!resolved)
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);
3852 if (!errnoValue) {
3854 "external call with errno value symbolic: " +
3855 function->getName());
3856 return;
3857 }
3858
3860 errnoValue->getZExtValue(sizeof(*errno_addr) * 8));
3861#endif
3862
3863 if (!SuppressExternalWarnings) {
3864
3865 std::string TmpStr;
3866 llvm::raw_string_ostream os(TmpStr);
3867 os << "calling external: " << function->getName().str() << "(";
3868 for (unsigned i=0; i<arguments.size(); i++) {
3869 os << arguments[i];
3870 if (i != arguments.size()-1)
3871 os << ", ";
3872 }
3873 os << ") at " << state.pc->getSourceLocation();
3874
3875 if (AllExternalWarnings)
3876 klee_warning("%s", os.str().c_str());
3877 else
3878 klee_warning_once(function, "%s", os.str().c_str());
3879 }
3880
3881 bool success = externalDispatcher->executeCall(function, target->inst, args);
3882 if (!success) {
3883 terminateStateOnError(state, "failed external call: " + function->getName(),
3884 StateTerminationType::External);
3885 return;
3886 }
3887
3888 if (!state.addressSpace.copyInConcretes()) {
3889 terminateStateOnError(state, "external modified read-only object",
3890 StateTerminationType::External);
3891 return;
3892 }
3893
3894#ifndef WINDOWS
3895 // Update errno memory object with the errno value from the call
3896 int error = externalDispatcher->getLastErrno();
3897 state.addressSpace.copyInConcrete(result.first, result.second,
3898 (uint64_t)&error);
3899#endif
3900
3901 Type *resultType = target->inst->getType();
3902 if (resultType != Type::getVoidTy(function->getContext())) {
3903 ref<Expr> e = ConstantExpr::fromMemory((void*) args,
3904 getWidthForLLVMType(resultType));
3905 bindLocal(target, state, e);
3906 }
3907}
3908
3909/***/
3910
3912 ref<Expr> e) {
3914 if (!n || replayKTest || replayPath)
3915 return e;
3916
3917 // right now, we don't replace symbolics (is there any reason to?)
3918 if (!isa<ConstantExpr>(e))
3919 return e;
3920
3921 if (n != 1 && random() % n)
3922 return e;
3923
3924 // create a new fresh location, assert it is equal to concrete value in e
3925 // and return it.
3926
3927 static unsigned id;
3928 const Array *array =
3929 arrayCache.CreateArray("rrws_arr" + llvm::utostr(++id),
3931 ref<Expr> res = Expr::createTempRead(array, e->getWidth());
3932 ref<Expr> eq = NotOptimizedExpr::create(EqExpr::create(e, res));
3933 llvm::errs() << "Making symbolic: " << eq << "\n";
3934 state.addConstraint(eq);
3935 return res;
3936}
3937
3939 const MemoryObject *mo,
3940 bool isLocal,
3941 const Array *array) {
3942 ObjectState *os = array ? new ObjectState(mo, array) : new ObjectState(mo);
3943 state.addressSpace.bindObject(mo, os);
3944
3945 // Its possible that multiple bindings of the same mo in the state
3946 // will put multiple copies on this list, but it doesn't really
3947 // matter because all we use this list for is to unbind the object
3948 // on function return.
3949 if (isLocal)
3950 state.stack.back().allocas.push_back(mo);
3951
3952 return os;
3953}
3954
3956 ref<Expr> size,
3957 bool isLocal,
3958 KInstruction *target,
3959 bool zeroMemory,
3960 const ObjectState *reallocFrom,
3961 size_t allocationAlignment) {
3962 size = toUnique(state, size);
3963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(size)) {
3964 const llvm::Value *allocSite = state.prevPC->inst;
3965 if (allocationAlignment == 0) {
3966 allocationAlignment = getAllocationAlignment(allocSite);
3967 }
3968 MemoryObject *mo =
3969 memory->allocate(CE->getZExtValue(), isLocal, /*isGlobal=*/false,
3970 allocSite, allocationAlignment);
3971 if (!mo) {
3972 bindLocal(target, state,
3973 ConstantExpr::alloc(0, Context::get().getPointerWidth()));
3974 } else {
3975 ObjectState *os = bindObjectInState(state, mo, isLocal);
3976 if (zeroMemory) {
3977 os->initializeToZero();
3978 } else {
3979 os->initializeToRandom();
3980 }
3981 bindLocal(target, state, mo->getBaseExpr());
3982
3983 if (reallocFrom) {
3984 unsigned count = std::min(reallocFrom->size, os->size);
3985 for (unsigned i=0; i<count; i++)
3986 os->write(i, reallocFrom->read8(i));
3987 state.addressSpace.unbindObject(reallocFrom->getObject());
3988 }
3989 }
3990 } else {
3991 // XXX For now we just pick a size. Ideally we would support
3992 // symbolic sizes fully but even if we don't it would be better to
3993 // "smartly" pick a value, for example we could fork and pick the
3994 // min and max values and perhaps some intermediate (reasonable
3995 // value).
3996 //
3997 // It would also be nice to recognize the case when size has
3998 // exactly two values and just fork (but we need to get rid of
3999 // return argument first). This shows up in pcre when llvm
4000 // collapses the size expression with a select.
4001
4002 size = optimizer.optimizeExpr(size, true);
4003
4004 ref<ConstantExpr> example;
4005 bool success =
4006 solver->getValue(state.constraints, size, example, state.queryMetaData);
4007 assert(success && "FIXME: Unhandled solver failure");
4008 (void) success;
4009
4010 // Try and start with a small example.
4011 Expr::Width W = example->getWidth();
4012 while (example->Ugt(ConstantExpr::alloc(128, W))->isTrue()) {
4013 ref<ConstantExpr> tmp = example->LShr(ConstantExpr::alloc(1, W));
4014 bool res;
4015 bool success =
4016 solver->mayBeTrue(state.constraints, EqExpr::create(tmp, size), res,
4017 state.queryMetaData);
4018 assert(success && "FIXME: Unhandled solver failure");
4019 (void) success;
4020 if (!res)
4021 break;
4022 example = tmp;
4023 }
4024
4025 StatePair fixedSize =
4026 fork(state, EqExpr::create(example, size), true, BranchType::Alloc);
4027
4028 if (fixedSize.second) {
4029 // Check for exactly two values
4031 bool success = solver->getValue(fixedSize.second->constraints, size, tmp,
4032 fixedSize.second->queryMetaData);
4033 assert(success && "FIXME: Unhandled solver failure");
4034 (void) success;
4035 bool res;
4036 success = solver->mustBeTrue(fixedSize.second->constraints,
4037 EqExpr::create(tmp, size), res,
4038 fixedSize.second->queryMetaData);
4039 assert(success && "FIXME: Unhandled solver failure");
4040 (void) success;
4041 if (res) {
4042 executeAlloc(*fixedSize.second, tmp, isLocal,
4043 target, zeroMemory, reallocFrom);
4044 } else {
4045 // See if a *really* big value is possible. If so assume
4046 // malloc will fail for it, so lets fork and return 0.
4047 StatePair hugeSize =
4048 fork(*fixedSize.second,
4049 UltExpr::create(ConstantExpr::alloc(1U << 31, W), size), true,
4050 BranchType::Alloc);
4051 if (hugeSize.first) {
4052 klee_message("NOTE: found huge malloc, returning 0");
4053 bindLocal(target, *hugeSize.first,
4055 }
4056
4057 if (hugeSize.second) {
4058
4059 std::string Str;
4060 llvm::raw_string_ostream info(Str);
4061 ExprPPrinter::printOne(info, " size expr", size);
4062 info << " concretization : " << example << "\n";
4063 info << " unbound example: " << tmp << "\n";
4064 terminateStateOnError(*hugeSize.second, "concretized symbolic size",
4065 StateTerminationType::Model, info.str());
4066 }
4067 }
4068 }
4069
4070 if (fixedSize.first) // can be zero when fork fails
4071 executeAlloc(*fixedSize.first, example, isLocal,
4072 target, zeroMemory, reallocFrom);
4073 }
4074}
4075
4077 ref<Expr> address,
4078 KInstruction *target) {
4079 address = optimizer.optimizeExpr(address, true);
4080 StatePair zeroPointer =
4081 fork(state, Expr::createIsZero(address), true, BranchType::Free);
4082 if (zeroPointer.first) {
4083 if (target)
4084 bindLocal(target, *zeroPointer.first, Expr::createPointer(0));
4085 }
4086 if (zeroPointer.second) { // address != 0
4088 resolveExact(*zeroPointer.second, address, rl, "free");
4089
4090 for (Executor::ExactResolutionList::iterator it = rl.begin(),
4091 ie = rl.end(); it != ie; ++it) {
4092 const MemoryObject *mo = it->first.first;
4093 if (mo->isLocal) {
4094 terminateStateOnError(*it->second, "free of alloca",
4095 StateTerminationType::Free,
4096 getAddressInfo(*it->second, address));
4097 } else if (mo->isGlobal) {
4098 terminateStateOnError(*it->second, "free of global",
4099 StateTerminationType::Free,
4100 getAddressInfo(*it->second, address));
4101 } else {
4102 it->second->addressSpace.unbindObject(mo);
4103 if (target)
4104 bindLocal(target, *it->second, Expr::createPointer(0));
4105 }
4106 }
4107 }
4108}
4109
4111 ref<Expr> p,
4112 ExactResolutionList &results,
4113 const std::string &name) {
4114 p = optimizer.optimizeExpr(p, true);
4115 // XXX we may want to be capping this?
4116 ResolutionList rl;
4117 state.addressSpace.resolve(state, solver, p, rl);
4118
4119 ExecutionState *unbound = &state;
4120 for (ResolutionList::iterator it = rl.begin(), ie = rl.end();
4121 it != ie; ++it) {
4122 ref<Expr> inBounds = EqExpr::create(p, it->first->getBaseExpr());
4123
4124 StatePair branches =
4125 fork(*unbound, inBounds, true, BranchType::ResolvePointer);
4126
4127 if (branches.first)
4128 results.push_back(std::make_pair(*it, branches.first));
4129
4130 unbound = branches.second;
4131 if (!unbound) // Fork failure
4132 break;
4133 }
4134
4135 if (unbound) {
4136 terminateStateOnError(*unbound, "memory error: invalid pointer: " + name,
4137 StateTerminationType::Ptr, getAddressInfo(*unbound, p));
4138 }
4139}
4140
4142 bool isWrite,
4143 ref<Expr> address,
4144 ref<Expr> value /* undef if read */,
4145 KInstruction *target /* undef if write */) {
4146 Expr::Width type = (isWrite ? value->getWidth() :
4147 getWidthForLLVMType(target->inst->getType()));
4148 unsigned bytes = Expr::getMinBytesForWidth(type);
4149
4150 if (SimplifySymIndices) {
4151 if (!isa<ConstantExpr>(address))
4152 address = ConstraintManager::simplifyExpr(state.constraints, address);
4153 if (isWrite && !isa<ConstantExpr>(value))
4154 value = ConstraintManager::simplifyExpr(state.constraints, value);
4155 }
4156
4157 address = optimizer.optimizeExpr(address, true);
4158
4159 // fast path: single in-bounds resolution
4160 ObjectPair op;
4161 bool success;
4163 if (!state.addressSpace.resolveOne(state, solver, address, op, success)) {
4164 address = toConstant(state, address, "resolveOne failure");
4165 success = state.addressSpace.resolveOne(cast<ConstantExpr>(address), op);
4166 }
4168
4169 if (success) {
4170 const MemoryObject *mo = op.first;
4171
4172 if (MaxSymArraySize && mo->size >= MaxSymArraySize) {
4173 address = toConstant(state, address, "max-sym-array-size");
4174 }
4175
4176 ref<Expr> offset = mo->getOffsetExpr(address);
4177 ref<Expr> check = mo->getBoundsCheckOffset(offset, bytes);
4178 check = optimizer.optimizeExpr(check, true);
4179
4180 bool inBounds;
4182 bool success = solver->mustBeTrue(state.constraints, check, inBounds,
4183 state.queryMetaData);
4185 if (!success) {
4186 state.pc = state.prevPC;
4187 terminateStateOnSolverError(state, "Query timed out (bounds check).");
4188 return;
4189 }
4190
4191 if (inBounds) {
4192 const ObjectState *os = op.second;
4193 if (isWrite) {
4194 if (os->readOnly) {
4195 terminateStateOnError(state, "memory error: object read only",
4196 StateTerminationType::ReadOnly);
4197 } else {
4198 ObjectState *wos = state.addressSpace.getWriteable(mo, os);
4199 wos->write(offset, value);
4200 }
4201 } else {
4202 ref<Expr> result = os->read(offset, type);
4203
4205 result = replaceReadWithSymbolic(state, result);
4206
4207 bindLocal(target, state, result);
4208 }
4209
4210 return;
4211 }
4212 }
4213
4214 // we are on an error path (no resolution, multiple resolution, one
4215 // resolution with out of bounds)
4216
4217 address = optimizer.optimizeExpr(address, true);
4218 ResolutionList rl;
4220 bool incomplete = state.addressSpace.resolve(state, solver, address, rl,
4223
4224 // XXX there is some query wasteage here. who cares?
4225 ExecutionState *unbound = &state;
4226
4227 for (ResolutionList::iterator i = rl.begin(), ie = rl.end(); i != ie; ++i) {
4228 const MemoryObject *mo = i->first;
4229 const ObjectState *os = i->second;
4230 ref<Expr> inBounds = mo->getBoundsCheckPointer(address, bytes);
4231
4232 StatePair branches = fork(*unbound, inBounds, true, BranchType::MemOp);
4233 ExecutionState *bound = branches.first;
4234
4235 // bound can be 0 on failure or overlapped
4236 if (bound) {
4237 if (isWrite) {
4238 if (os->readOnly) {
4239 terminateStateOnError(*bound, "memory error: object read only",
4240 StateTerminationType::ReadOnly);
4241 } else {
4242 ObjectState *wos = bound->addressSpace.getWriteable(mo, os);
4243 wos->write(mo->getOffsetExpr(address), value);
4244 }
4245 } else {
4246 ref<Expr> result = os->read(mo->getOffsetExpr(address), type);
4247 bindLocal(target, *bound, result);
4248 }
4249 }
4250
4251 unbound = branches.second;
4252 if (!unbound)
4253 break;
4254 }
4255
4256 // XXX should we distinguish out of bounds and overlapped cases?
4257 if (unbound) {
4258 if (incomplete) {
4259 terminateStateOnSolverError(*unbound, "Query timed out (resolve).");
4260 } else {
4261 terminateStateOnError(*unbound, "memory error: out of bound pointer",
4262 StateTerminationType::Ptr,
4263 getAddressInfo(*unbound, address));
4264 }
4265 }
4266}
4267
4269 const MemoryObject *mo,
4270 const std::string &name) {
4271 // Create a new object state for the memory object (instead of a copy).
4272 if (!replayKTest) {
4273 // Find a unique name for this array. First try the original name,
4274 // or if that fails try adding a unique identifier.
4275 unsigned id = 0;
4276 std::string uniqueName = name;
4277 while (!state.arrayNames.insert(uniqueName).second) {
4278 uniqueName = name + "_" + llvm::utostr(++id);
4279 }
4280 const Array *array = arrayCache.CreateArray(uniqueName, mo->size);
4281 bindObjectInState(state, mo, false, array);
4282 state.addSymbolic(mo, array);
4283
4284 std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it =
4285 seedMap.find(&state);
4286 if (it!=seedMap.end()) { // In seed mode we need to add this as a
4287 // binding.
4288 for (std::vector<SeedInfo>::iterator siit = it->second.begin(),
4289 siie = it->second.end(); siit != siie; ++siit) {
4290 SeedInfo &si = *siit;
4291 KTestObject *obj = si.getNextInput(mo, NamedSeedMatching);
4292
4293 if (!obj) {
4294 if (ZeroSeedExtension) {
4295 std::vector<unsigned char> &values = si.assignment.bindings[array];
4296 values = std::vector<unsigned char>(mo->size, '\0');
4297 } else if (!AllowSeedExtension) {
4298 terminateStateOnUserError(state, "ran out of inputs during seeding");
4299 break;
4300 }
4301 } else {
4302 if (obj->numBytes != mo->size &&
4303 ((!(AllowSeedExtension || ZeroSeedExtension)
4304 && obj->numBytes < mo->size) ||
4305 (!AllowSeedTruncation && obj->numBytes > mo->size))) {
4306 std::stringstream msg;
4307 msg << "replace size mismatch: "
4308 << mo->name << "[" << mo->size << "]"
4309 << " vs " << obj->name << "[" << obj->numBytes << "]"
4310 << " in test\n";
4311
4312 terminateStateOnUserError(state, msg.str());
4313 break;
4314 } else {
4315 std::vector<unsigned char> &values = si.assignment.bindings[array];
4316 values.insert(values.begin(), obj->bytes,
4317 obj->bytes + std::min(obj->numBytes, mo->size));
4318 if (ZeroSeedExtension) {
4319 for (unsigned i=obj->numBytes; i<mo->size; ++i)
4320 values.push_back('\0');
4321 }
4322 }
4323 }
4324 }
4325 }
4326 } else {
4327 ObjectState *os = bindObjectInState(state, mo, false);
4329 terminateStateOnUserError(state, "replay count mismatch");
4330 } else {
4332 if (obj->numBytes != mo->size) {
4333 terminateStateOnUserError(state, "replay size mismatch");
4334 } else {
4335 for (unsigned i=0; i<mo->size; i++)
4336 os->write8(i, obj->bytes[i]);
4337 }
4338 }
4339 }
4340}
4341
4342/***/
4343
4345 int argc,
4346 char **argv,
4347 char **envp) {
4348 std::vector<ref<Expr> > arguments;
4349
4350 // force deterministic initialization of memory objects
4351 srand(1);
4352 srandom(1);
4353
4354 MemoryObject *argvMO = 0;
4355
4356 // In order to make uclibc happy and be closer to what the system is
4357 // doing we lay out the environments at the end of the argv array
4358 // (both are terminated by a null). There is also a final terminating
4359 // null that uclibc seems to expect, possibly the ELF header?
4360
4361 int envc;
4362 for (envc=0; envp[envc]; ++envc) ;
4363
4364 unsigned NumPtrBytes = Context::get().getPointerWidth() / 8;
4365 KFunction *kf = kmodule->functionMap[f];
4366 assert(kf);
4367 Function::arg_iterator ai = f->arg_begin(), ae = f->arg_end();
4368 if (ai!=ae) {
4369 arguments.push_back(ConstantExpr::alloc(argc, Expr::Int32));
4370 if (++ai!=ae) {
4371 Instruction *first = &*(f->begin()->begin());
4372 argvMO =
4373 memory->allocate((argc + 1 + envc + 1 + 1) * NumPtrBytes,
4374 /*isLocal=*/false, /*isGlobal=*/true,
4375 /*allocSite=*/first, /*alignment=*/8);
4376
4377 if (!argvMO)
4378 klee_error("Could not allocate memory for function arguments");
4379
4380 arguments.push_back(argvMO->getBaseExpr());
4381
4382 if (++ai!=ae) {
4383 uint64_t envp_start = argvMO->address + (argc+1)*NumPtrBytes;
4384 arguments.push_back(Expr::createPointer(envp_start));
4385
4386 if (++ai!=ae)
4387 klee_error("invalid main function (expect 0-3 arguments)");
4388 }
4389 }
4390 }
4391
4392 ExecutionState *state = new ExecutionState(kmodule->functionMap[f]);
4393
4394 if (pathWriter)
4395 state->pathOS = pathWriter->open();
4396 if (symPathWriter)
4397 state->symPathOS = symPathWriter->open();
4398
4399
4400 if (statsTracker)
4401 statsTracker->framePushed(*state, 0);
4402
4403 assert(arguments.size() == f->arg_size() && "wrong number of arguments");
4404 for (unsigned i = 0, e = f->arg_size(); i != e; ++i)
4405 bindArgument(kf, i, *state, arguments[i]);
4406
4407 if (argvMO) {
4408 ObjectState *argvOS = bindObjectInState(*state, argvMO, false);
4409
4410 for (int i=0; i<argc+1+envc+1+1; i++) {
4411 if (i==argc || i>=argc+1+envc) {
4412 // Write NULL pointer
4413 argvOS->write(i * NumPtrBytes, Expr::createPointer(0));
4414 } else {
4415 char *s = i<argc ? argv[i] : envp[i-(argc+1)];
4416 int j, len = strlen(s);
4417
4418 MemoryObject *arg =
4419 memory->allocate(len + 1, /*isLocal=*/false, /*isGlobal=*/true,
4420 /*allocSite=*/state->pc->inst, /*alignment=*/8);
4421 if (!arg)
4422 klee_error("Could not allocate memory for function arguments");
4423 ObjectState *os = bindObjectInState(*state, arg, false);
4424 for (j=0; j<len+1; j++)
4425 os->write8(j, s[j]);
4426
4427 // Write pointer to newly allocated and initialised argv/envp c-string
4428 argvOS->write(i * NumPtrBytes, arg->getBaseExpr());
4429 }
4430 }
4431 }
4432
4433 initializeGlobals(*state);
4434
4435 processTree = std::make_unique<PTree>(state);
4436 run(*state);
4437 processTree = nullptr;
4438
4439 // hack to clear memory objects
4440 delete memory;
4441 memory = new MemoryManager(NULL);
4442
4443 globalObjects.clear();
4444 globalAddresses.clear();
4445
4446 if (statsTracker)
4447 statsTracker->done();
4448}
4449
4451 assert(pathWriter);
4452 return state.pathOS.getID();
4453}
4454
4456 assert(symPathWriter);
4457 return state.symPathOS.getID();
4458}
4459
4460void Executor::getConstraintLog(const ExecutionState &state, std::string &res,
4461 Interpreter::LogType logFormat) {
4462
4463 switch (logFormat) {
4464 case STP: {
4466 char *log = solver->getConstraintLog(query);
4467 res = std::string(log);
4468 free(log);
4469 } break;
4470
4471 case KQUERY: {
4472 std::string Str;
4473 llvm::raw_string_ostream info(Str);
4475 res = info.str();
4476 } break;
4477
4478 case SMTLIB2: {
4479 std::string Str;
4480 llvm::raw_string_ostream info(Str);
4481 ExprSMTLIBPrinter printer;
4482 printer.setOutput(info);
4484 printer.setQuery(query);
4485 printer.generateOutput();
4486 res = info.str();
4487 } break;
4488
4489 default:
4490 klee_warning("Executor::getConstraintLog() : Log format not supported!");
4491 }
4492}
4493
4495 std::vector<
4496 std::pair<std::string,
4497 std::vector<unsigned char> > >
4498 &res) {
4500
4501 ConstraintSet extendedConstraints(state.constraints);
4502 ConstraintManager cm(extendedConstraints);
4503
4504 // Go through each byte in every test case and attempt to restrict
4505 // it to the constraints contained in cexPreferences. (Note:
4506 // usually this means trying to make it an ASCII character (0-127)
4507 // and therefore human readable. It is also possible to customize
4508 // the preferred constraints. See test/Features/PreferCex.c for
4509 // an example) While this process can be very expensive, it can
4510 // also make understanding individual test cases much easier.
4511 for (auto& pi: state.cexPreferences) {
4512 bool mustBeTrue;
4513 // Attempt to bound byte to constraints held in cexPreferences
4514 bool success =
4515 solver->mustBeTrue(extendedConstraints, Expr::createIsZero(pi),
4516 mustBeTrue, state.queryMetaData);
4517 // If it isn't possible to add the condition without making the entire list
4518 // UNSAT, then just continue to the next condition
4519 if (!success) break;
4520 // If the particular constraint operated on in this iteration through
4521 // the loop isn't implied then add it to the list of constraints.
4522 if (!mustBeTrue)
4523 cm.addConstraint(pi);
4524 }
4525
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);
4530 bool success = solver->getInitialValues(extendedConstraints, objects, values,
4531 state.queryMetaData);
4533 if (!success) {
4534 klee_warning("unable to compute initial values (invalid constraints?)!");
4535 ExprPPrinter::printQuery(llvm::errs(), state.constraints,
4537 return false;
4538 }
4539
4540 for (unsigned i = 0; i != state.symbolics.size(); ++i)
4541 res.push_back(std::make_pair(state.symbolics[i].first->name, values[i]));
4542 return true;
4543}
4544
4546 std::map<const std::string*, std::set<unsigned> > &res) {
4547 res = state.coveredLines;
4548}
4549
4551 ref<Expr> e,
4552 ref<ConstantExpr> value) {
4553 abort(); // FIXME: Broken until we sort out how to do the write back.
4554
4555 if (DebugCheckForImpliedValues)
4557
4558 ImpliedValueList results;
4559 ImpliedValue::getImpliedValues(e, value, results);
4560 for (ImpliedValueList::iterator it = results.begin(), ie = results.end();
4561 it != ie; ++it) {
4562 ReadExpr *re = it->first.get();
4563
4564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(re->index)) {
4565 // FIXME: This is the sole remaining usage of the Array object
4566 // variable. Kill me.
4567 const MemoryObject *mo = 0; //re->updates.root->object;
4568 const ObjectState *os = state.addressSpace.findObject(mo);
4569
4570 if (!os) {
4571 // object has been free'd, no need to concretize (although as
4572 // in other cases we would like to concretize the outstanding
4573 // reads, but we have no facility for that yet)
4574 } else {
4575 assert(!os->readOnly &&
4576 "not possible? read only object with static read?");
4577 ObjectState *wos = state.addressSpace.getWriteable(mo, os);
4578 wos->write(CE, it->second);
4579 }
4580 }
4581 }
4582}
4583
4585 return kmodule->targetData->getTypeSizeInBits(type);
4586}
4587
4588size_t Executor::getAllocationAlignment(const llvm::Value *allocSite) const {
4589 // FIXME: 8 was the previous default. We shouldn't hard code this
4590 // and should fetch the default from elsewhere.
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)) {
4598 // All GlobalVariables's have pointer type
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();
4603 } else {
4604 type = GO->getType();
4605 }
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)) {
4610 // FIXME: Model the semantics of the call to use the right alignment
4611#if LLVM_VERSION_CODE >= LLVM_VERSION(8, 0)
4612 const CallBase &cs = cast<CallBase>(*allocSite);
4613#else
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)));
4618#endif
4619 llvm::Function *fn =
4620 klee::getDirectCallTarget(cs, /*moduleIsFullyLinked=*/true);
4621 if (fn)
4622 allocationSiteName = fn->getName().str();
4623
4624 klee_warning_once(fn != NULL ? fn : allocSite,
4625 "Alignment of memory from call \"%s\" is not "
4626 "modelled. Using alignment of %zu.",
4627 allocationSiteName.c_str(), forcedAlignment);
4628 alignment = forcedAlignment;
4629 } else {
4630 llvm_unreachable("Unhandled allocation site");
4631 }
4632
4633 if (alignment == 0) {
4634 assert(type != NULL);
4635 // No specified alignment. Get the alignment for the type.
4636 if (type->isSized()) {
4637 alignment = kmodule->targetData->getPrefTypeAlignment(type);
4638 } else {
4639 klee_warning_once(allocSite, "Cannot determine memory alignment for "
4640 "\"%s\". Using alignment of %zu.",
4641 allocationSiteName.c_str(), forcedAlignment);
4642 alignment = forcedAlignment;
4643 }
4644 }
4645
4646 // Currently we require alignment be a power of 2
4647 if (!bits64::isPowerOfTwo(alignment)) {
4648 klee_warning_once(allocSite, "Alignment of %zu requested for %s but this "
4649 "not supported. Using alignment of %zu",
4650 alignment, allocSite->getName().str().c_str(),
4651 forcedAlignment);
4652 alignment = forcedAlignment;
4653 }
4654 assert(bits64::isPowerOfTwo(alignment) &&
4655 "Returned alignment must be a power of two");
4656 return alignment;
4657}
4658
4660 if (statsTracker) {
4661 // Make sure stats get flushed out
4662 statsTracker->done();
4663 }
4664}
4665
4668#if !defined(__APPLE__) && !defined(__FreeBSD__)
4669 /* From /usr/include/errno.h: it [errno] is a per-thread variable. */
4670 return __errno_location();
4671#else
4672 return __error();
4673#endif
4674}
4675
4676
4678 if (!::dumpPTree) return;
4679
4680 char name[32];
4681 snprintf(name, sizeof(name),"ptree%08d.dot", (int) stats::instructions);
4682 auto os = interpreterHandler->openOutputFile(name);
4683 if (os) {
4684 processTree->dump(*os);
4685 }
4686
4687 ::dumpPTree = 0;
4688}
4689
4691 if (!::dumpStates) return;
4692
4693 auto os = interpreterHandler->openOutputFile("states.txt");
4694
4695 if (os) {
4696 for (ExecutionState *es : states) {
4697 *os << "(" << es << ",";
4698 *os << "[";
4699 auto next = es->stack.begin();
4700 ++next;
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 << "), ";
4706 } else {
4707 *os << next->caller->info->line << "), ";
4708 ++next;
4709 }
4710 }
4711 *os << "], ";
4712
4713 StackFrame &sf = es->stack.back();
4714 uint64_t md2u = computeMinDistToUncovered(es->pc,
4717 es->pc->info->id);
4718 uint64_t cpicnt = sf.callPathNode->statistics.getValue(stats::instructions);
4719
4720 *os << "{";
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 << ", ";
4728 *os << "}";
4729 *os << ")\n";
4730 }
4731 }
4732
4733 ::dumpStates = 0;
4734}
4735
4737
4739 InterpreterHandler *ih) {
4740 return new Executor(ctx, opts, ih);
4741}
BranchType
Reason an ExecutionState forked.
Definition: BranchTypes.h:48
static const char * okExternalsList[]
Definition: Executor.cpp:3773
static bool shouldWriteTest(const ExecutionState &state)
Definition: Executor.cpp:3622
static std::string terminationTypeFileExtension(StateTerminationType type)
Definition: Executor.cpp:3626
bool shouldExitOn(StateTerminationType reason)
Definition: Executor.cpp:3708
static std::set< std::string > okExternals(okExternalsList, okExternalsList+(sizeof(okExternalsList)/sizeof(okExternalsList[0])))
static const llvm::fltSemantics * fpWidthToSemantics(unsigned width)
Definition: Executor.cpp:1416
void *__dso_handle __attribute__((__weak__))
unsigned dumpStates
Definition: Executor.cpp:433
unsigned dumpPTree
Definition: Executor.cpp:433
#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.
Definition: ArrayCache.cpp:20
bindings_ty bindings
Definition: Assignment.h:26
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.
Definition: Expr.cpp:647
static ref< Expr > create(const ref< Expr > &l, const ref< Expr > &r)
Definition: Expr.cpp:623
static ref< ConstantExpr > create(uint64_t v, Width w)
Definition: Expr.h:1079
static ref< ConstantExpr > alloc(const llvm::APInt &v)
Definition: Expr.h:1065
uint64_t getZExtValue(unsigned bits=64) const
Definition: Expr.h:1030
ref< ConstantExpr > SExt(Width W)
Definition: Expr.cpp:395
static ref< Expr > fromMemory(void *address, Width w)
Definition: Expr.cpp:337
Manages constraints, e.g. optimisation.
Definition: Constraints.h:50
void addConstraint(const ref< Expr > &constraint)
static ref< Expr > simplifyExpr(const ConstraintSet &constraints, const ref< Expr > &expr)
Definition: Constraints.cpp:92
static void initialize(bool IsLittleEndian, Expr::Width PointerWidth)
initialize - Construct the global Context instance.
Definition: Context.cpp:24
Expr::Width getPointerWidth() const
Returns width of the pointer in bits.
Definition: Context.h:41
static const Context & get()
get - Return the global singleton instance of the Context.
Definition: Context.cpp:30
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.
Definition: Executor.h:193
void callExternalFunction(ExecutionState &state, KInstruction *target, llvm::Function *function, std::vector< ref< Expr > > &arguments)
Definition: Executor.cpp:3781
bool ivcEnabled
Definition: Executor.h:180
MemoryManager * memory
Definition: Executor.h:113
void terminateStateOnExit(ExecutionState &state)
Definition: Executor.cpp:3638
void addConstraint(ExecutionState &state, ref< Expr > condition)
Definition: Executor.cpp:1194
ArrayCache arrayCache
Assumes ownership of the created array objects.
Definition: Executor.h:190
Cell & getArgumentCell(ExecutionState &state, KFunction *kf, unsigned index)
Definition: Executor.h:356
bool checkMemoryUsage()
Definition: Executor.cpp:3388
const InstructionInfo & getLastNonKleeInternalInstruction(const ExecutionState &state, llvm::Instruction **lastInstruction)
Definition: Executor.cpp:3665
friend class StatsTracker
Definition: Executor.h:96
TreeStreamWriter * symPathWriter
Definition: Executor.h:116
unsigned replayPosition
Definition: Executor.h:161
std::string getAddressInfo(ExecutionState &state, ref< Expr > address) const
Get textual information regarding a memory address.
Definition: Executor.cpp:3543
ObjectState * bindObjectInState(ExecutionState &state, const MemoryObject *mo, bool isLocal, const Array *array=0)
Definition: Executor.cpp:3938
virtual ~Executor()
Definition: Executor.cpp:562
void initializeGlobalAlias(const llvm::Constant *c)
Definition: Executor.cpp:758
std::map< ExecutionState *, std::vector< SeedInfo > > seedMap
Definition: Executor.h:139
std::map< const llvm::GlobalValue *, ref< ConstantExpr > > globalAddresses
Definition: Executor.h:146
TimerGroup timers
Definition: Executor.h:118
ref< klee::ConstantExpr > toConstant(ExecutionState &state, ref< Expr > e, const char *purpose)
Definition: Executor.cpp:1285
ref< ConstantExpr > getEhTypeidFor(ref< Expr > type_info)
Return the typeid corresponding to a certain type_info
Definition: Executor.cpp:1641
TimingSolver * solver
Definition: Executor.h:112
void printDebugInstructions(ExecutionState &state)
Definition: Executor.cpp:1361
void branch(ExecutionState &state, const std::vector< ref< Expr > > &conditions, std::vector< ExecutionState * > &result, BranchType reason)
Definition: Executor.cpp:864
void bindArgument(KFunction *kf, unsigned index, ExecutionState &state, ref< Expr > value)
Definition: Executor.cpp:1253
llvm::Function * getTargetFunction(llvm::Value *calledVal, ExecutionState &state)
Definition: Executor.cpp:2017
std::vector< std::pair< std::pair< const MemoryObject *, const ObjectState * >, ExecutionState * > > ExactResolutionList
Definition: Executor.h:258
StatePair fork(ExecutionState &current, ref< Expr > condition, bool isInternal, BranchType reason)
Definition: Executor.cpp:1003
friend class SpecialFunctionHandler
Definition: Executor.h:95
size_t getAllocationAlignment(const llvm::Value *allocSite) const
Definition: Executor.cpp:4588
std::unique_ptr< PTree > processTree
Definition: Executor.h:119
void initializeGlobalAliases()
Definition: Executor.cpp:789
void dumpPTree()
Definition: Executor.cpp:4677
RNG theRNG
The random number generator.
Definition: Executor.h:104
const struct KTest * replayKTest
Definition: Executor.h:154
TreeStreamWriter * pathWriter
Definition: Executor.h:116
void doDumpStates()
Definition: Executor.cpp:3430
ref< Expr > toUnique(const ExecutionState &state, ref< Expr > &e)
Definition: Executor.cpp:1258
std::vector< ExecutionState * > addedStates
Definition: Executor.h:125
void terminateState(ExecutionState &state)
Remove state from queue and delete state.
Definition: Executor.cpp:3596
void computeOffsets(KGEPInstruction *kgepi, TypeIt ib, TypeIt ie)
Definition: Executor.cpp:3334
std::unordered_map< std::uint64_t, llvm::Function * > legalFunctions
Definition: Executor.h:150
void computeOffsetsSeqTy(KGEPInstruction *kgepi, ref< ConstantExpr > &constantOffset, uint64_t index, const TypeIt it)
Definition: Executor.cpp:3315
bool inhibitForking
Disables forking, set by client.
Definition: Executor.h:172
void runFunctionAsMain(llvm::Function *f, int argc, char **argv, char **envp) override
Definition: Executor.cpp:4344
llvm::raw_string_ostream debugLogBuffer
Definition: Executor.h:199
std::vector< ref< Expr > > eh_typeids
Typeids used during exception handling.
Definition: Executor.h:209
void executeAlloc(ExecutionState &state, ref< Expr > size, bool isLocal, KInstruction *target, bool zeroMemory=false, const ObjectState *reallocFrom=0, size_t allocationAlignment=0)
Definition: Executor.cpp:3955
void executeInstruction(ExecutionState &state, KInstruction *ki)
Definition: Executor.cpp:2045
void executeMemoryOperation(ExecutionState &state, bool isWrite, ref< Expr > address, ref< Expr > value, KInstruction *target)
Definition: Executor.cpp:4141
void initializeGlobals(ExecutionState &state)
Definition: Executor.cpp:634
std::set< ExecutionState *, ExecutionStateIDCompare > states
Definition: Executor.h:114
ref< Expr > maxStaticPctChecks(ExecutionState &current, ref< Expr > condition)
Definition: Executor.cpp:947
Expr::Width getWidthForLLVMType(llvm::Type *type) const
Definition: Executor.cpp:4584
Cell & getDestCell(ExecutionState &state, KInstruction *target)
Definition: Executor.h:362
bool atMemoryLimit
Definition: Executor.h:169
void bindLocal(KInstruction *target, ExecutionState &state, ref< Expr > value)
Definition: Executor.cpp:1248
void doImpliedValueConcretization(ExecutionState &state, ref< Expr > e, ref< ConstantExpr > value)
Definition: Executor.cpp:4550
void getConstraintLog(const ExecutionState &state, std::string &res, Interpreter::LogType logFormat=Interpreter::STP) override
Definition: Executor.cpp:4460
void terminateStateEarly(ExecutionState &state, const llvm::Twine &message, StateTerminationType terminationType)
Definition: Executor.cpp:3648
time::Span coreSolverTimeout
Definition: Executor.h:184
void bindInstructionConstants(KInstruction *KI)
Definition: Executor.cpp:3358
MemoryObject * serializeLandingpad(ExecutionState &state, const llvm::LandingPadInst &lpi, bool &stateTerminated)
Definition: Executor.cpp:1429
std::map< const llvm::GlobalValue *, MemoryObject * > globalObjects
Map of globals to their representative memory object.
Definition: Executor.h:142
void getCoveredLines(const ExecutionState &state, std::map< const std::string *, std::set< unsigned > > &res) override
Definition: Executor.cpp:4545
void bindModuleConstants()
bindModuleConstants - Initialize the module constant table.
Definition: Executor.cpp:3373
std::pair< ExecutionState *, ExecutionState * > StatePair
Definition: Executor.h:101
ref< Expr > replaceReadWithSymbolic(ExecutionState &state, ref< Expr > e)
Definition: Executor.cpp:3911
const Cell & eval(KInstruction *ki, unsigned index, ExecutionState &state) const
Definition: Executor.cpp:1229
void terminateStateOnExecError(ExecutionState &state, const llvm::Twine &message, const llvm::Twine &info="")
Definition: Executor.cpp:3761
bool haltExecution
Definition: Executor.h:176
void allocateGlobalObjects(ExecutionState &state)
Definition: Executor.cpp:648
void stepInstruction(ExecutionState &state)
Definition: Executor.cpp:1402
std::string debugBufferString
Definition: Executor.h:196
SpecialFunctionHandler * specialFunctionHandler
Definition: Executor.h:117
llvm::Module * setModule(std::vector< std::unique_ptr< llvm::Module > > &modules, const ModuleOptions &opts) override
Definition: Executor.cpp:499
bool getSymbolicSolution(const ExecutionState &state, std::vector< std::pair< std::string, std::vector< unsigned char > > > &res) override
Definition: Executor.cpp:4494
void prepareForEarlyExit() override
Definition: Executor.cpp:4659
void executeMakeSymbolic(ExecutionState &state, const MemoryObject *mo, const std::string &name)
Definition: Executor.cpp:4268
void run(ExecutionState &initialState)
Definition: Executor.cpp:3442
InterpreterHandler * interpreterHandler
Definition: Executor.h:108
const std::vector< bool > * replayPath
When non-null a list of branch decisions to be used for replay.
Definition: Executor.h:157
bool branchingPermitted(const ExecutionState &state) const
check if branching/forking is allowed
Definition: Executor.cpp:843
void terminateStateOnSolverError(ExecutionState &state, const llvm::Twine &message)
Definition: Executor.cpp:3767
void transferToBasicBlock(llvm::BasicBlock *dst, llvm::BasicBlock *src, ExecutionState &state)
Definition: Executor.cpp:1991
std::unique_ptr< KModule > kmodule
Definition: Executor.h:107
unsigned getSymbolicPathStreamID(const ExecutionState &state) override
Definition: Executor.cpp:4455
void terminateStateOnUserError(ExecutionState &state, const llvm::Twine &message)
Definition: Executor.cpp:3661
void resolveExact(ExecutionState &state, ref< Expr > p, ExactResolutionList &results, const std::string &name)
Definition: Executor.cpp:4110
void setHaltExecution(bool value) override
Definition: Executor.h:521
ExternalDispatcher * externalDispatcher
Definition: Executor.h:111
ExprOptimizer optimizer
Optimizes expressions.
Definition: Executor.h:202
void executeGetValue(ExecutionState &state, ref< Expr > e, KInstruction *target)
Definition: Executor.cpp:1314
void unwindToNextLandingpad(ExecutionState &state)
Definition: Executor.cpp:1532
void executeCall(ExecutionState &state, KInstruction *ki, llvm::Function *f, std::vector< ref< Expr > > &arguments)
Definition: Executor.cpp:1657
void executeFree(ExecutionState &state, ref< Expr > address, KInstruction *target=0)
Definition: Executor.cpp:4076
MemoryObject * addExternalObject(ExecutionState &state, void *addr, unsigned size, bool isReadOnly)
Definition: Executor.cpp:618
StatsTracker * statsTracker
Definition: Executor.h:115
void initializeGlobalObjects(ExecutionState &state)
Definition: Executor.cpp:796
void initializeGlobalObject(ExecutionState &state, ObjectState *os, const llvm::Constant *c, unsigned offset)
Definition: Executor.cpp:572
unsigned getPathStreamID(const ExecutionState &state) override
Definition: Executor.cpp:4450
void terminateStateOnError(ExecutionState &state, const llvm::Twine &message, StateTerminationType terminationType, const llvm::Twine &longMessage="", const char *suffix=nullptr)
Definition: Executor.cpp:3713
void updateStates(ExecutionState *current)
Definition: Executor.cpp:3289
Searcher * searcher
Definition: Executor.h:109
std::vector< ExecutionState * > removedStates
Definition: Executor.h:130
ref< klee::ConstantExpr > evalConstant(const llvm::Constant *c, const KInstruction *ki=NULL)
const std::vector< struct KTest * > * usingSeeds
Definition: Executor.h:165
void dumpStates()
Only for debug purposes; enable via debugger or klee-control.
Definition: Executor.cpp:4690
int * getErrnoLocation(const ExecutionState &state) const
Returns the errno location in memory of the state.
Definition: Executor.cpp:4667
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 const Width Int64
Definition: Expr.h:104
static const Width Int32
Definition: Expr.h:103
static ref< Expr > createZExtToPointerWidth(ref< Expr > e)
Definition: Context.cpp:42
static ref< Expr > createIsZero(ref< Expr > e)
Definition: Expr.cpp:322
static ref< Expr > createSExtToPointerWidth(ref< Expr > e)
Definition: Context.cpp:38
virtual Width getWidth() const =0
static ref< ConstantExpr > createPointer(uint64_t v)
Definition: Context.cpp:46
unsigned Width
The type of an expression is simply its width, in bits.
Definition: Expr.h:97
bool isZero() const
isZero - Is this a constant zero.
Definition: Expr.h:1150
static ref< Expr > createTempRead(const Array *array, Expr::Width w)
Definition: Expr.cpp:49
static unsigned getMinBytesForWidth(Width w)
returns the smallest number of bytes in which the given width fits
Definition: Expr.h:262
bool isTrue() const
isTrue - Is this the true expression.
Definition: Expr.h:1156
static const Width Bool
Definition: Expr.h:100
static const Width Fl80
Definition: Expr.h:105
void * resolveSymbol(const std::string &name)
bool executeCall(llvm::Function *function, llvm::Instruction *i, uint64_t *args)
void setLastErrno(int newErrno)
static ref< Expr > create(ref< Expr > e, unsigned bitOff, Width w)
Creates an ExtractExpr with the given bit offset and width.
Definition: Expr.cpp:675
iterator begin() const
Definition: ImmutableMap.h:83
iterator upper_bound(const key_type &key) const
Definition: ImmutableMap.h:95
iterator end() const
Definition: ImmutableMap.h:86
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
Definition: Interpreter.h:92
static Interpreter * create(llvm::LLVMContext &ctx, const InterpreterOptions &_interpreterOpts, InterpreterHandler *ih)
Definition: Executor.cpp:4738
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
Definition: Memory.h:125
unsigned size
size in bytes
Definition: Memory.h:52
bool isUserSpecified
Definition: Memory.h:59
void getAllocInfo(std::string &result) const
Get an identifying string for this allocation.
Definition: Memory.cpp:52
ref< ConstantExpr > getSizeExpr() const
Definition: Memory.h:112
ref< Expr > getBoundsCheckPointer(ref< Expr > pointer) const
Definition: Memory.h:118
uint64_t address
Definition: Memory.h:49
ref< Expr > getOffsetExpr(ref< Expr > pointer) const
Definition: Memory.h:115
std::string name
Definition: Memory.h:53
ref< ConstantExpr > getBaseExpr() const
Definition: Memory.h:109
static ref< Expr > create(ref< Expr > src)
Definition: Expr.cpp:501
ref< Expr > read8(unsigned offset) const
Definition: Memory.cpp:364
void initializeToZero()
Make contents all concrete and zero.
Definition: Memory.cpp:233
ref< Expr > read(ref< Expr > offset, Expr::Width width) const
Definition: Memory.cpp:434
void write8(unsigned offset, uint8_t value)
Definition: Memory.cpp:394
void initializeToRandom()
Make contents all concrete and random.
Definition: Memory.cpp:238
void write(unsigned offset, ref< Expr > value)
Definition: Memory.cpp:506
void setReadOnly(bool ro)
Definition: Memory.h:212
const MemoryObject * getObject() const
Definition: Memory.h:210
unsigned size
Definition: Memory.h:193
unsigned int getInt32()
Definition: RNG.cpp:82
bool getBool()
Definition: RNG.cpp:151
Class representing a one byte read from an array.
Definition: Expr.h:565
ref< Expr > index
Definition: Expr.h:572
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)
Definition: SeedInfo.cpp:24
Assignment assignment
Definition: SeedInfo.h:27
static ref< Expr > create(ref< Expr > c, ref< Expr > t, ref< Expr > f)
Definition: Expr.cpp:592
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
Definition: Statistics.h:142
uint64_t getValue(const Statistic &s) const
Definition: Statistics.h:120
std::uint32_t id
Definition: Statistic.h:31
static bool useStatistics()
void markBranchVisited(ExecutionState *visitedTrue, ExecutionState *visitedFalse)
void stepInstruction(ExecutionState &es)
static bool useIStats()
void framePopped(ExecutionState &es)
void framePushed(ExecutionState &es, StackFrame *parentFrame)
void reset()
Reset all timers.
Definition: Timer.cpp:76
void add(std::unique_ptr< Timer > timer)
Definition: Timer.cpp:60
void invoke()
Invoke registered timers with current time only if minimum interval exceeded.
Definition: Timer.cpp:71
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)
Definition: TimingSolver.h:41
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
Definition: TimingSolver.h:29
char * getConstraintLog(const Query &query)
Definition: TimingSolver.h:43
unsigned getID() const
Definition: TreeStream.cpp:178
TreeOStream open()
Definition: TreeStream.cpp:50
Contains information related to unwinding (Itanium ABI/2-Phase unwinding)
Definition: Ref.h:82
int const char * message
Definition: klee.h:75
int const char const char * suffix
Definition: klee.h:76
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)
Definition: Bits.h:91
uint64_t eq(uint64_t l, uint64_t r, unsigned inWidth)
uint64_t ext(uint64_t l, unsigned outWidth, unsigned inWidth)
Statistic forkTime
Statistic solverTime
Statistic instructions
Statistic forks
The number of process forks.
Point getWallTime()
Returns point in time using a monotonic steady clock.
Definition: Time.cpp:206
Span seconds(std::uint64_t)
Definition: Time.cpp:139
size_t GetTotalMallocUsage()
Get total malloc usage in bytes.
Definition: MemoryUsage.cpp:87
Definition: main.cpp:291
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
Definition: AddressSpace.h:28
llvm::cl::opt< std::string > MaxCoreSolverTime
const char ALL_QUERIES_KQUERY_FILE_NAME[]
Definition: Common.h:24
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[]
Definition: Common.h:23
cl::OptionCategory SeedingCat("Seeding options", "These options are related to the use of seeds to start exploration.")
const char ALL_QUERIES_SMT2_FILE_NAME[]
Definition: Common.h:22
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)
Definition: CoreSolver.cpp:25
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
Definition: ImpliedValue.h:27
void void void klee_warning(const char *msg,...) __attribute__((format(printf
std::pair< const MemoryObject *, const ObjectState * > ObjectPair
Definition: AddressSpace.h:25
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[]
Definition: Common.h:25
void initializeSearchOptions()
StatisticManager * theStatisticManager
Definition: Statistics.cpp:57
cl::OptionCategory ExtCallsCat("External call policy options", "These options impact external calls.")
char * name
Definition: KTest.h:19
unsigned char * bytes
Definition: KTest.h:21
unsigned numBytes
Definition: KTest.h:20
unsigned numObjects
Definition: KTest.h:35
KTestObject * objects
Definition: KTest.h:36
ref< Expr > value
Definition: Cell.h:19
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.
std::map< llvm::BasicBlock *, unsigned > basicBlockEntry
Definition: KModule.h:50
KInstruction ** instructions
Definition: KModule.h:48
unsigned numInstructions
Definition: KModule.h:47
std::vector< std::pair< unsigned, uint64_t > > indices
Definition: KInstruction.h:56
const InstructionInfo * info
Definition: KInstruction.h:35
llvm::Instruction * inst
Definition: KInstruction.h:34
std::string getSourceLocation() const
unsigned minDistToUncoveredOnReturn
MemoryObject * varargs
CallPathNode * callPathNode