Executor.cpp

Go to the documentation of this file.
00001 //===-- Executor.cpp ------------------------------------------------------===//
00002 //
00003 //                     The KLEE Symbolic Virtual Machine
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "Common.h"
00011 
00012 #include "Executor.h"
00013  
00014 #include "CoreStats.h"
00015 #include "ExternalDispatcher.h"
00016 #include "ImpliedValue.h"
00017 #include "Memory.h"
00018 #include "MemoryManager.h"
00019 #include "PTree.h"
00020 #include "Searcher.h"
00021 #include "SeedInfo.h"
00022 #include "SpecialFunctionHandler.h"
00023 #include "StatsTracker.h"
00024 #include "TimingSolver.h"
00025 #include "UserSearcher.h"
00026 #include "../Solver/SolverStats.h"
00027 
00028 #include "klee/ExecutionState.h"
00029 #include "klee/Expr.h"
00030 #include "klee/Interpreter.h"
00031 #include "klee/Machine.h"
00032 #include "klee/TimerStatIncrementer.h"
00033 #include "klee/util/Assignment.h"
00034 #include "klee/util/ExprPPrinter.h"
00035 #include "klee/util/ExprUtil.h"
00036 #include "klee/Config/config.h"
00037 #include "klee/Internal/ADT/KTest.h"
00038 #include "klee/Internal/ADT/RNG.h"
00039 #include "klee/Internal/Module/Cell.h"
00040 #include "klee/Internal/Module/InstructionInfoTable.h"
00041 #include "klee/Internal/Module/KInstruction.h"
00042 #include "klee/Internal/Module/KModule.h"
00043 #include "klee/Internal/Support/FloatEvaluation.h"
00044 #include "klee/Internal/System/Time.h"
00045 
00046 #include "llvm/Attributes.h"
00047 #include "llvm/BasicBlock.h"
00048 #include "llvm/Constants.h"
00049 #include "llvm/Function.h"
00050 #include "llvm/Instructions.h"
00051 #include "llvm/IntrinsicInst.h"
00052 #include "llvm/Module.h"
00053 #include "llvm/Support/CallSite.h"
00054 #include "llvm/Support/CommandLine.h"
00055 #include "llvm/Support/GetElementPtrTypeIterator.h"
00056 #include "llvm/System/Process.h"
00057 #include "llvm/Target/TargetData.h"
00058 
00059 #include <cassert>
00060 #include <algorithm>
00061 #include <iostream>
00062 #include <iomanip>
00063 #include <fstream>
00064 #include <sstream>
00065 #include <vector>
00066 #include <string>
00067 
00068 #include <sys/mman.h>
00069 
00070 #include <errno.h>
00071 #include <cxxabi.h>
00072 
00073 using namespace llvm;
00074 using namespace klee;
00075 
00076 // omg really hard to share cl opts across files ...
00077 bool WriteTraces = false;
00078 
00079 namespace {
00080   cl::opt<bool>
00081   DumpStatesOnHalt("dump-states-on-halt",
00082                    cl::init(true));
00083  
00084   cl::opt<bool>
00085   NoPreferCex("no-prefer-cex",
00086               cl::init(false));
00087  
00088   cl::opt<bool>
00089   UseAsmAddresses("use-asm-addresses",
00090                   cl::init(false));
00091  
00092   cl::opt<bool>
00093   RandomizeFork("randomize-fork",
00094                 cl::init(false));
00095  
00096   cl::opt<bool>
00097   AllowExternalSymCalls("allow-external-sym-calls",
00098                         cl::init(false));
00099 
00100   cl::opt<bool>
00101   DebugPrintInstructions("debug-print-instructions", 
00102                          cl::desc("Print instructions during execution."));
00103 
00104   cl::opt<bool>
00105   DebugCheckForImpliedValues("debug-check-for-implied-values");
00106 
00107 
00108   cl::opt<bool>
00109   SimplifySymIndices("simplify-sym-indices",
00110                      cl::init(false));
00111 
00112   cl::opt<unsigned>
00113   MaxSymArraySize("max-sym-array-size",
00114                   cl::init(0));
00115 
00116   cl::opt<bool>
00117   DebugValidateSolver("debug-validate-solver",
00118                       cl::init(false));
00119 
00120   cl::opt<bool>
00121   SuppressExternalWarnings("suppress-external-warnings");
00122 
00123   cl::opt<bool>
00124   AllExternalWarnings("all-external-warnings");
00125 
00126   cl::opt<bool>
00127   OnlyOutputStatesCoveringNew("only-output-states-covering-new",
00128                               cl::init(false));
00129 
00130   cl::opt<bool>
00131   AlwaysOutputSeeds("always-output-seeds",
00132                               cl::init(true));
00133 
00134   cl::opt<bool>
00135   UseFastCexSolver("use-fast-cex-solver",
00136                    cl::init(false));
00137 
00138   cl::opt<bool>
00139   UseIndependentSolver("use-independent-solver",
00140                        cl::init(true),
00141                        cl::desc("Use constraint independence"));
00142 
00143   cl::opt<bool>
00144   EmitAllErrors("emit-all-errors",
00145                 cl::init(false),
00146                 cl::desc("Generate tests cases for all errors "
00147                          "(default=one per (error,instruction) pair)"));
00148 
00149   cl::opt<bool>
00150   UseCexCache("use-cex-cache",
00151               cl::init(true),
00152               cl::desc("Use counterexample caching"));
00153 
00154   cl::opt<bool>
00155   UseQueryLog("use-query-log",
00156               cl::init(false));
00157 
00158   cl::opt<bool>
00159   UseQueryPCLog("use-query-pc-log",
00160                 cl::init(false));
00161   
00162   cl::opt<bool>
00163   UseSTPQueryPCLog("use-stp-query-pc-log",
00164                    cl::init(false));
00165 
00166   cl::opt<bool>
00167   NoExternals("no-externals", 
00168            cl::desc("Do not allow external functin calls"));
00169 
00170   cl::opt<bool>
00171   UseCache("use-cache",
00172            cl::init(true),
00173            cl::desc("Use validity caching"));
00174 
00175   cl::opt<bool>
00176   OnlyReplaySeeds("only-replay-seeds", 
00177                   cl::desc("Discard states that do not have a seed."));
00178  
00179   cl::opt<bool>
00180   OnlySeed("only-seed", 
00181            cl::desc("Stop execution after seeding is done without doing regular search."));
00182  
00183   cl::opt<bool>
00184   AllowSeedExtension("allow-seed-extension", 
00185                      cl::desc("Allow extra (unbound) values to become symbolic during seeding."));
00186  
00187   cl::opt<bool>
00188   ZeroSeedExtension("zero-seed-extension");
00189  
00190   cl::opt<bool>
00191   AllowSeedTruncation("allow-seed-truncation", 
00192                       cl::desc("Allow smaller buffers than in seeds."));
00193  
00194   cl::opt<bool>
00195   NamedSeedMatching("named-seed-matching",
00196                     cl::desc("Use names to match symbolic objects to inputs."));
00197 
00198   cl::opt<double>
00199   MaxStaticForkPct("max-static-fork-pct", cl::init(1.));
00200   cl::opt<double>
00201   MaxStaticSolvePct("max-static-solve-pct", cl::init(1.));
00202   cl::opt<double>
00203   MaxStaticCPForkPct("max-static-cpfork-pct", cl::init(1.));
00204   cl::opt<double>
00205   MaxStaticCPSolvePct("max-static-cpsolve-pct", cl::init(1.));
00206 
00207   cl::opt<double>
00208   MaxInstructionTime("max-instruction-time",
00209                      cl::desc("Only allow a single instruction to take this much time (default=0 (off))"),
00210                      cl::init(0));
00211   
00212   cl::opt<double>
00213   SeedTime("seed-time",
00214            cl::desc("Amount of time to dedicate to seeds, before normal search (default=0 (off))"),
00215            cl::init(0));
00216   
00217   cl::opt<double>
00218   MaxSTPTime("max-stp-time",
00219              cl::desc("Maximum amount of time for a single query (default=120s)"),
00220              cl::init(120.0));
00221   
00222   cl::opt<unsigned int>
00223   StopAfterNInstructions("stop-after-n-instructions",
00224                          cl::desc("Stop execution after specified number of instructions (0=off)"),
00225                          cl::init(0));
00226   
00227   cl::opt<unsigned>
00228   MaxForks("max-forks",
00229            cl::desc("Only fork this many times (-1=off)"),
00230            cl::init(~0u));
00231   
00232   cl::opt<unsigned>
00233   MaxDepth("max-depth",
00234            cl::desc("Only allow this many symbolic branches (0=off)"),
00235            cl::init(0));
00236   
00237   cl::opt<unsigned>
00238   MaxMemory("max-memory",
00239             cl::desc("Refuse to fork when more above this about of memory (in MB, 0=off)"),
00240             cl::init(0));
00241 
00242   cl::opt<bool>
00243   MaxMemoryInhibit("max-memory-inhibit",
00244             cl::desc("Inhibit forking at memory cap (vs. random terminat)"),
00245             cl::init(true));
00246 
00247   // use 'external storage' because also needed by tools/klee/main.cpp
00248   cl::opt<bool, true>
00249   WriteTracesProxy("write-traces", 
00250            cl::desc("Write .trace file for each terminated state"),
00251            cl::location(WriteTraces),
00252            cl::init(false));
00253 
00254   cl::opt<bool>
00255   UseForkedSTP("use-forked-stp", 
00256                  cl::desc("Run STP in forked process"));
00257 }
00258 
00259 
00260 static void *theMMap = 0;
00261 static unsigned theMMapSize = 0;
00262 
00263 namespace klee {
00264   RNG theRNG;
00265 }
00266 
00267 Solver *constructSolverChain(STPSolver *stpSolver,
00268                              std::string queryLogPath,
00269                              std::string stpQueryLogPath,
00270                              std::string queryPCLogPath,
00271                              std::string stpQueryPCLogPath) {
00272   Solver *solver = stpSolver;
00273 
00274   if (UseSTPQueryPCLog)
00275     solver = createPCLoggingSolver(solver, 
00276                                    stpQueryLogPath);
00277 
00278   if (UseFastCexSolver)
00279     solver = createFastCexSolver(solver);
00280 
00281   if (UseCexCache)
00282     solver = createCexCachingSolver(solver);
00283 
00284   if (UseCache)
00285     solver = createCachingSolver(solver);
00286 
00287   if (UseIndependentSolver)
00288     solver = createIndependentSolver(solver);
00289 
00290   if (DebugValidateSolver)
00291     solver = createValidatingSolver(solver, stpSolver);
00292 
00293   if (UseQueryPCLog)
00294     solver = createPCLoggingSolver(solver, 
00295                                    queryPCLogPath);
00296   
00297   return solver;
00298 }
00299 
00300 Executor::Executor(const InterpreterOptions &opts,
00301                    InterpreterHandler *ih) 
00302   : Interpreter(opts),
00303     kmodule(0),
00304     interpreterHandler(ih),
00305     searcher(0),
00306     externalDispatcher(new ExternalDispatcher()),
00307     statsTracker(0),
00308     pathWriter(0),
00309     symPathWriter(0),
00310     specialFunctionHandler(0),
00311     processTree(0),
00312     replayOut(0),
00313     replayPath(0),    
00314     usingSeeds(0),
00315     atMemoryLimit(false),
00316     inhibitForking(false),
00317     haltExecution(false),
00318     ivcEnabled(false),
00319     stpTimeout(std::min(MaxSTPTime,MaxInstructionTime)) {
00320   STPSolver *stpSolver = new STPSolver(UseForkedSTP);
00321   Solver *solver = 
00322     constructSolverChain(stpSolver,
00323                          interpreterHandler->getOutputFilename("queries.qlog"),
00324                          interpreterHandler->getOutputFilename("stp-queries.qlog"),
00325                          interpreterHandler->getOutputFilename("queries.pc"),
00326                          interpreterHandler->getOutputFilename("stp-queries.pc"));
00327   
00328   this->solver = new TimingSolver(solver, stpSolver);
00329 
00330   memory = new MemoryManager();
00331 }
00332 
00333 
00334 const Module *Executor::setModule(llvm::Module *module, 
00335                                   const ModuleOptions &opts) {
00336   assert(!kmodule && module && "can only register one module"); // XXX gross
00337 
00338   kmodule = new KModule(module);
00339 
00340   specialFunctionHandler = new SpecialFunctionHandler(*this);
00341 
00342   specialFunctionHandler->prepare();
00343   kmodule->prepare(opts, interpreterHandler);
00344   specialFunctionHandler->bind();
00345 
00346   if (StatsTracker::useStatistics()) {
00347     statsTracker = 
00348       new StatsTracker(*this,
00349                        interpreterHandler->getOutputFilename("assembly.ll"),
00350                        userSearcherRequiresMD2U());
00351   }
00352   
00353   return module;
00354 }
00355 
00356 Executor::~Executor() {
00357   delete memory;
00358   delete externalDispatcher;
00359   if (processTree)
00360     delete processTree;
00361   if (specialFunctionHandler)
00362     delete specialFunctionHandler;
00363   if (statsTracker)
00364     delete statsTracker;
00365   delete solver;
00366   delete kmodule;
00367 }
00368 
00369 /***/
00370 
00371 void Executor::initializeGlobalObject(ExecutionState &state, ObjectState *os,
00372                                       Constant *c, 
00373                                       unsigned offset) {
00374   TargetData *targetData = kmodule->targetData;
00375   if (ConstantVector *cp = dyn_cast<ConstantVector>(c)) {
00376     unsigned elementSize =
00377       targetData->getTypeStoreSize(cp->getType()->getElementType());
00378     for (unsigned i=0, e=cp->getNumOperands(); i != e; ++i)
00379       initializeGlobalObject(state, os, cp->getOperand(i), 
00380                              offset + i*elementSize);
00381   } else if (isa<ConstantAggregateZero>(c)) {
00382     unsigned i, size = targetData->getTypeStoreSize(c->getType());
00383     for (i=0; i<size; i++)
00384       os->write8(offset+i, (uint8_t) 0);
00385   } else if (ConstantArray *ca = dyn_cast<ConstantArray>(c)) {
00386     unsigned elementSize =
00387       targetData->getTypeStoreSize(ca->getType()->getElementType());
00388     for (unsigned i=0, e=ca->getNumOperands(); i != e; ++i)
00389       initializeGlobalObject(state, os, ca->getOperand(i), 
00390                              offset + i*elementSize);
00391   } else if (ConstantStruct *cs = dyn_cast<ConstantStruct>(c)) {
00392     const StructLayout *sl =
00393       targetData->getStructLayout(cast<StructType>(cs->getType()));
00394     for (unsigned i=0, e=cs->getNumOperands(); i != e; ++i)
00395       initializeGlobalObject(state, os, cs->getOperand(i), 
00396                              offset + sl->getElementOffset(i));
00397   } else {
00398     os->write(offset, evalConstant(c));
00399   }
00400 }
00401 
00402 MemoryObject * Executor::addExternalObject(ExecutionState &state, 
00403                                            void *addr, unsigned size, 
00404                                            bool isReadOnly) {
00405   MemoryObject *mo = memory->allocateFixed((uint64_t) (unsigned long) addr, 
00406                                            size, 0);
00407   ObjectState *os = bindObjectInState(state, mo, false);
00408   for(unsigned i = 0; i < size; i++)
00409     os->write8(i, ((uint8_t*)addr)[i]);
00410   if(isReadOnly)
00411     os->setReadOnly(true);  
00412   return mo;
00413 }
00414 
00415 void Executor::initializeGlobals(ExecutionState &state) {
00416   Module *m = kmodule->module;
00417 
00418   if (m->getModuleInlineAsm() != "")
00419     klee_warning("executable has module level assembly (ignoring)");
00420 
00421   assert(m->lib_begin() == m->lib_end() &&
00422          "XXX do not support dependent libraries");
00423 
00424   // represent function globals using the address of the actual llvm function
00425   // object. given that we use malloc to allocate memory in states this also
00426   // ensures that we won't conflict. we don't need to allocate a memory object
00427   // since reading/writing via a function pointer is unsupported anyway.
00428   for (Module::iterator i = m->begin(), ie = m->end(); i != ie; ++i) {
00429     Function *f = i;
00430     ref<Expr> addr(0);
00431 
00432     // If the symbol has external weak linkage then it is implicitly
00433     // not defined in this module; if it isn't resolvable then it
00434     // should be null.
00435     if (f->hasExternalWeakLinkage() && 
00436         !externalDispatcher->resolveSymbol(f->getName())) {
00437       addr = Expr::createPointer(0);
00438     } else {
00439       addr = Expr::createPointer((unsigned long) (void*) f);
00440       legalFunctions.insert(f);
00441     }
00442     
00443     globalAddresses.insert(std::make_pair(f, addr));
00444   }
00445 
00446   // Disabled, we don't want to promote use of live externals.
00447 #ifdef HAVE_CTYPE_EXTERNALS
00448 #ifndef WINDOWS
00449 #ifndef DARWIN
00450   /* From /usr/include/errno.h: it [errno] is a per-thread variable. */
00451   int *errno_addr = __errno_location();
00452   addExternalObject(state, (void *)errno_addr, sizeof *errno_addr, false);
00453 
00454   /* from /usr/include/ctype.h:
00455        These point into arrays of 384, so they can be indexed by any `unsigned
00456        char' value [0,255]; by EOF (-1); or by any `signed char' value
00457        [-128,-1).  ISO C requires that the ctype functions work for `unsigned */
00458   const uint16_t **addr = __ctype_b_loc();
00459   addExternalObject(state, (void *)(*addr-128), 
00460                     384 * sizeof **addr, true);
00461   addExternalObject(state, addr, 4, true);
00462     
00463   const int32_t **lower_addr = __ctype_tolower_loc();
00464   addExternalObject(state, (void *)(*lower_addr-128), 
00465                     384 * sizeof **lower_addr, true);
00466   addExternalObject(state, lower_addr, 4, true);
00467   
00468   const int32_t **upper_addr = __ctype_toupper_loc();
00469   addExternalObject(state, (void *)(*upper_addr-128), 
00470                     384 * sizeof **upper_addr, true);
00471   addExternalObject(state, upper_addr, 4, true);
00472 #endif
00473 #endif
00474 #endif
00475 
00476   // allocate and initialize globals, done in two passes since we may
00477   // need address of a global in order to initialize some other one.
00478 
00479   // allocate memory objects for all globals
00480   for (Module::const_global_iterator i = m->global_begin(),
00481          e = m->global_end();
00482        i != e; ++i) {
00483     if (i->isDeclaration()) {
00484       // FIXME: We have no general way of handling unknown external
00485       // symbols. If we really cared about making external stuff work
00486       // better we could support user definition, or use the EXE style
00487       // hack where we check the object file information.
00488 
00489       const Type *ty = i->getType()->getElementType();
00490       const std::string &name = i->getName();
00491       uint64_t size = kmodule->targetData->getTypeStoreSize(ty);
00492 
00493       // XXX - DWD - hardcode some things until we decide how to fix.
00494 #ifndef WINDOWS
00495       if (name == "_ZTVN10__cxxabiv117__class_type_infoE") {
00496         size = 0x2C;
00497       } else if (name == "_ZTVN10__cxxabiv120__si_class_type_infoE") {
00498         size = 0x2C;
00499       } else if (name == "_ZTVN10__cxxabiv121__vmi_class_type_infoE") {
00500         size = 0x2C;
00501       }
00502 #endif
00503 
00504       if (size == 0) {
00505         llvm::cerr << "Unable to find size for global variable: " << i->getName() 
00506                    << " (use will result in out of bounds access)\n";
00507       }
00508 
00509       MemoryObject *mo = memory->allocate(size, false, true, i);
00510       ObjectState *os = bindObjectInState(state, mo, false);
00511       globalObjects.insert(std::make_pair(i, mo));
00512       globalAddresses.insert(std::make_pair(i, mo->getBaseExpr()));
00513 
00514       // Program already running = object already initialized.  Read
00515       // concrete value and write it to our copy.
00516       if (size) {
00517         void *addr;
00518         if (name=="__dso_handle") {
00519           extern void *__dso_handle __attribute__ ((__weak__));
00520           addr = &__dso_handle; // wtf ?
00521         } else {
00522           addr = externalDispatcher->resolveSymbol(name);
00523         }
00524         if (!addr)
00525           klee_error("unable to load symbol(%s) while initializing globals.", 
00526                      name.c_str());
00527 
00528         for (unsigned offset=0; offset<mo->size; offset++)
00529           os->write8(offset, ((unsigned char*)addr)[offset]);
00530       }
00531     } else {
00532       const std::string &name = i->getName();
00533       const Type *ty = i->getType()->getElementType();
00534       uint64_t size = kmodule->targetData->getTypeStoreSize(ty);
00535       MemoryObject *mo = 0;
00536 
00537       if (UseAsmAddresses && name[0]=='\01') {
00538         char *end;
00539         uint64_t address = ::strtoll(name.c_str()+1, &end, 0);
00540 
00541         if (end && *end == '\0') {
00542           klee_message("NOTE: allocated global at asm specified address: %#08llx"
00543                        " (%llu bytes)",
00544                        address, size);
00545           mo = memory->allocateFixed(address, size, &*i);
00546           mo->isUserSpecified = true; // XXX hack;
00547         }
00548       }
00549 
00550       if (!mo)
00551         mo = memory->allocate(size, false, true, &*i);
00552       assert(mo && "out of memory");
00553       ObjectState *os = bindObjectInState(state, mo, false);
00554       globalObjects.insert(std::make_pair(i, mo));
00555       globalAddresses.insert(std::make_pair(i, mo->getBaseExpr()));
00556 
00557       if (!i->hasInitializer())
00558           os->initializeToRandom();
00559     }
00560   }
00561   
00562   // link aliases to their definitions (if bound)
00563   for (Module::alias_iterator i = m->alias_begin(), ie = m->alias_end(); 
00564        i != ie; ++i) {
00565     // Map the alias to its aliasee's address. This works because we have
00566     // addresses for everything, even undefined functions. 
00567     globalAddresses.insert(std::make_pair(i, evalConstant(i->getAliasee())));
00568   }
00569 
00570   // once all objects are allocated, do the actual initialization
00571   for (Module::const_global_iterator i = m->global_begin(),
00572          e = m->global_end();
00573        i != e; ++i) {
00574     if (i->hasInitializer()) {
00575       MemoryObject *mo = globalObjects.find(i)->second;
00576       const ObjectState *os = state.addressSpace.findObject(mo);
00577       assert(os);
00578       ObjectState *wos = state.addressSpace.getWriteable(mo, os);
00579       
00580       initializeGlobalObject(state, wos, i->getInitializer(), 0);
00581       // if(i->isConstant()) os->setReadOnly(true);
00582     }
00583   }
00584 }
00585 
00586 void Executor::branch(ExecutionState &state, 
00587                       const std::vector< ref<Expr> > &conditions,
00588                       std::vector<ExecutionState*> &result) {
00589   TimerStatIncrementer timer(stats::forkTime);
00590   unsigned N = conditions.size();
00591   assert(N);
00592 
00593   stats::forks += N-1;
00594 
00595   // XXX do proper balance or keep random?
00596   result.push_back(&state);
00597   for (unsigned i=1; i<N; ++i) {
00598     ExecutionState *es = result[theRNG.getInt32() % i];
00599     ExecutionState *ns = es->branch();
00600     addedStates.insert(ns);
00601     result.push_back(ns);
00602     es->ptreeNode->data = 0;
00603     std::pair<PTree::Node*,PTree::Node*> res = 
00604       processTree->split(es->ptreeNode, ns, es);
00605     ns->ptreeNode = res.first;
00606     es->ptreeNode = res.second;
00607   }
00608 
00609   // If necessary redistribute seeds to match conditions, killing
00610   // states if necessary due to OnlyReplaySeeds (inefficient but
00611   // simple).
00612   
00613   std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it = 
00614     seedMap.find(&state);
00615   if (it != seedMap.end()) {
00616     std::vector<SeedInfo> seeds = it->second;
00617     seedMap.erase(it);
00618 
00619     // Assume each seed only satisfies one condition (necessarily true
00620     // when conditions are mutually exclusive and their conjunction is
00621     // a tautology).
00622     for (std::vector<SeedInfo>::iterator siit = seeds.begin(), 
00623            siie = seeds.end(); siit != siie; ++siit) {
00624       unsigned i;
00625       for (i=0; i<N; ++i) {
00626         ref<ConstantExpr> res;
00627         bool success = 
00628           solver->getValue(state, siit->assignment.evaluate(conditions[i]), 
00629                            res);
00630         assert(success && "FIXME: Unhandled solver failure");
00631         (void) success;
00632         if (res->getConstantValue())
00633           break;
00634       }
00635       
00636       // If we didn't find a satisfying condition randomly pick one
00637       // (the seed will be patched).
00638       if (i==N)
00639         i = theRNG.getInt32() % N;
00640 
00641       seedMap[result[i]].push_back(*siit);
00642     }
00643 
00644     if (OnlyReplaySeeds) {
00645       for (unsigned i=0; i<N; ++i) {
00646         if (!seedMap.count(result[i])) {
00647           terminateState(*result[i]);
00648           result[i] = NULL;
00649         }
00650       } 
00651     }
00652   }
00653 
00654   for (unsigned i=0; i<N; ++i)
00655     if (result[i])
00656       addConstraint(*result[i], conditions[i]);
00657 }
00658 
00659 Executor::StatePair 
00660 Executor::fork(ExecutionState &current, ref<Expr> condition, bool isInternal) {
00661   Solver::Validity res;
00662   std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it = 
00663     seedMap.find(&current);
00664   bool isSeeding = it != seedMap.end();
00665 
00666   if (!isSeeding && !isa<ConstantExpr>(condition) && 
00667       (MaxStaticForkPct!=1. || MaxStaticSolvePct != 1. ||
00668        MaxStaticCPForkPct!=1. || MaxStaticCPSolvePct != 1.) &&
00669       statsTracker->elapsed() > 60.) {
00670     StatisticManager &sm = *theStatisticManager;
00671     CallPathNode *cpn = current.stack.back().callPathNode;
00672     if ((MaxStaticForkPct<1. &&
00673          sm.getIndexedValue(stats::forks, sm.getIndex()) > 
00674          stats::forks*MaxStaticForkPct) ||
00675         (MaxStaticCPForkPct<1. &&
00676          cpn && (cpn->statistics.getValue(stats::forks) > 
00677                  stats::forks*MaxStaticCPForkPct)) ||
00678         (MaxStaticSolvePct<1 &&
00679          sm.getIndexedValue(stats::solverTime, sm.getIndex()) > 
00680          stats::solverTime*MaxStaticSolvePct) ||
00681         (MaxStaticCPForkPct<1. &&
00682          cpn && (cpn->statistics.getValue(stats::solverTime) > 
00683                  stats::solverTime*MaxStaticCPSolvePct))) {
00684       ref<ConstantExpr> value; 
00685       bool success = solver->getValue(current, condition, value);
00686       assert(success && "FIXME: Unhandled solver failure");
00687       (void) success;
00688       addConstraint(current, EqExpr::create(value, condition));
00689       condition = value;
00690     }      
00691   }
00692 
00693   double timeout = stpTimeout;
00694   if (isSeeding)
00695     timeout *= it->second.size();
00696   solver->setTimeout(timeout);
00697   bool success = solver->evaluate(current, condition, res);
00698   solver->setTimeout(0);
00699   if (!success) {
00700     current.pc = current.prevPC;
00701     terminateStateEarly(current, "query timed out");
00702     return StatePair(0, 0);
00703   }
00704 
00705   if (!isSeeding) {
00706     if (replayPath && !isInternal) {
00707       assert(replayPosition<replayPath->size() &&
00708              "ran out of branches in replay path mode");
00709       bool branch = (*replayPath)[replayPosition++];
00710       
00711       if (res==Solver::True) {
00712         assert(branch && "hit invalid branch in replay path mode");
00713       } else if (res==Solver::False) {
00714         assert(!branch && "hit invalid branch in replay path mode");
00715       } else {
00716         // add constraints
00717         if(branch) {
00718           res = Solver::True;
00719           addConstraint(current, condition);
00720         } else  {
00721           res = Solver::False;
00722           addConstraint(current, Expr::createNot(condition));
00723         }
00724       }
00725     } else if (res==Solver::Unknown) {
00726       assert(!replayOut && "in replay mode, only one branch can be true.");
00727       
00728       if ((MaxMemoryInhibit && atMemoryLimit) || 
00729           current.forkDisabled ||
00730           inhibitForking || 
00731           (MaxForks!=~0u && stats::forks >= MaxForks)) {
00732         TimerStatIncrementer timer(stats::forkTime);
00733         if (theRNG.getBool()) {
00734           addConstraint(current, condition);
00735           res = Solver::True;        
00736         } else {
00737           addConstraint(current, Expr::createNot(condition));
00738           res = Solver::False;
00739         }
00740       }
00741     }
00742   }
00743 
00744   // Fix branch in only-replay-seed mode, if we don't have both true
00745   // and false seeds.
00746   if (isSeeding && 
00747       (current.forkDisabled || OnlyReplaySeeds) && 
00748       res == Solver::Unknown) {
00749     bool trueSeed=false, falseSeed=false;
00750     // Is seed extension still ok here?
00751     for (std::vector<SeedInfo>::iterator siit = it->second.begin(), 
00752            siie = it->second.end(); siit != siie; ++siit) {
00753       ref<ConstantExpr> res;
00754       bool success = 
00755         solver->getValue(current, siit->assignment.evaluate(condition), res);
00756       assert(success && "FIXME: Unhandled solver failure");
00757       (void) success;
00758       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(res)) {
00759         if (CE->getConstantValue()) {
00760           trueSeed = true;
00761         } else {
00762           falseSeed = true;
00763         }
00764         if (trueSeed && falseSeed)
00765           break;
00766       }
00767     }
00768     if (!(trueSeed && falseSeed)) {
00769       assert(trueSeed || falseSeed);
00770       
00771       res = trueSeed ? Solver::True : Solver::False;
00772       addConstraint(current, trueSeed ? condition : Expr::createNot(condition));
00773     }
00774   }
00775 
00776 
00777   // XXX - even if the constraint is provable one way or the other we
00778   // can probably benefit by adding this constraint and allowing it to
00779   // reduce the other constraints. For example, if we do a binary
00780   // search on a particular value, and then see a comparison against
00781   // the value it has been fixed at, we should take this as a nice
00782   // hint to just use the single constraint instead of all the binary
00783   // search ones. If that makes sense.
00784   if (res==Solver::True) {
00785     if (!isInternal) {
00786       if (pathWriter) {
00787         current.pathOS << "1";
00788       }
00789     }
00790 
00791     return StatePair(&current, 0);
00792   } else if (res==Solver::False) {
00793     if (!isInternal) {
00794       if (pathWriter) {
00795         current.pathOS << "0";
00796       }
00797     }
00798 
00799     return StatePair(0, &current);
00800   } else {
00801     TimerStatIncrementer timer(stats::forkTime);
00802     ExecutionState *falseState, *trueState = &current;
00803 
00804     ++stats::forks;
00805 
00806     falseState = trueState->branch();
00807     addedStates.insert(falseState);
00808 
00809     if (RandomizeFork && theRNG.getBool())
00810       std::swap(trueState, falseState);
00811 
00812     if (it != seedMap.end()) {
00813       std::vector<SeedInfo> seeds = it->second;
00814       it->second.clear();
00815       std::vector<SeedInfo> &trueSeeds = seedMap[trueState];
00816       std::vector<SeedInfo> &falseSeeds = seedMap[falseState];
00817       for (std::vector<SeedInfo>::iterator siit = seeds.begin(), 
00818              siie = seeds.end(); siit != siie; ++siit) {
00819         ref<ConstantExpr> res;
00820         bool success = 
00821           solver->getValue(current, siit->assignment.evaluate(condition), res);
00822         assert(success && "FIXME: Unhandled solver failure");
00823         (void) success;
00824         if (res->getConstantValue()) {
00825           trueSeeds.push_back(*siit);
00826         } else {
00827           falseSeeds.push_back(*siit);
00828         }
00829       }
00830       
00831       bool swapInfo = false;
00832       if (trueSeeds.empty()) {
00833         if (&current == trueState) swapInfo = true;
00834         seedMap.erase(trueState);
00835       }
00836       if (falseSeeds.empty()) {
00837         if (&current == falseState) swapInfo = true;
00838         seedMap.erase(falseState);
00839       }
00840       if (swapInfo) {
00841         std::swap(trueState->coveredNew, falseState->coveredNew);
00842         std::swap(trueState->coveredLines, falseState->coveredLines);
00843       }
00844     }
00845 
00846     current.ptreeNode->data = 0;
00847     std::pair<PTree::Node*, PTree::Node*> res =
00848       processTree->split(current.ptreeNode, falseState, trueState);
00849     falseState->ptreeNode = res.first;
00850     trueState->ptreeNode = res.second;
00851 
00852     if (!isInternal) {
00853       if (pathWriter) {
00854         falseState->pathOS = pathWriter->open(current.pathOS);
00855         trueState->pathOS << "1";
00856         falseState->pathOS << "0";
00857       }      
00858       if (symPathWriter) {
00859         falseState->symPathOS = symPathWriter->open(current.symPathOS);
00860         trueState->symPathOS << "1";
00861         falseState->symPathOS << "0";
00862       }
00863     }
00864 
00865     addConstraint(*trueState, condition);
00866     addConstraint(*falseState, Expr::createNot(condition));
00867 
00868     // Kinda gross, do we even really still want this option?
00869     if (MaxDepth && MaxDepth<=trueState->depth) {
00870       terminateStateEarly(*trueState, "max-depth exceeded");
00871       terminateStateEarly(*falseState, "max-depth exceeded");
00872       return StatePair(0, 0);
00873     }
00874 
00875     return StatePair(trueState, falseState);
00876   }
00877 }
00878 
00879 void Executor::addConstraint(ExecutionState &state, ref<Expr> condition) {
00880   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(condition)) {
00881     assert(CE->getConstantValue() && "attempt to add invalid constraint");
00882     return;
00883   }
00884 
00885   // Check to see if this constraint violates seeds.
00886   std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it = 
00887     seedMap.find(&state);
00888   if (it != seedMap.end()) {
00889     bool warn = false;
00890     for (std::vector<SeedInfo>::iterator siit = it->second.begin(), 
00891            siie = it->second.end(); siit != siie; ++siit) {
00892       bool res;
00893       bool success = 
00894         solver->mustBeFalse(state, siit->assignment.evaluate(condition), res);
00895       assert(success && "FIXME: Unhandled solver failure");
00896       (void) success;
00897       if (res) {
00898         siit->patchSeed(state, condition, solver);
00899         warn = true;
00900       }
00901     }
00902     if (warn)
00903       klee_warning("seeds patched for violating constraint"); 
00904   }
00905 
00906   state.addConstraint(condition);
00907   if (ivcEnabled)
00908     doImpliedValueConcretization(state, condition, 
00909                                  ConstantExpr::alloc(1, Expr::Bool));
00910 }
00911 
00912 ref<Expr> Executor::evalConstant(Constant *c) {
00913   if (llvm::ConstantExpr *ce = dyn_cast<llvm::ConstantExpr>(c)) {
00914     return evalConstantExpr(ce);
00915   } else {
00916     if (const ConstantInt *ci = dyn_cast<ConstantInt>(c)) {
00917       switch(ci->getBitWidth()) {
00918       case  1: return ConstantExpr::create(ci->getZExtValue(), Expr::Bool);
00919       case  8: return ConstantExpr::create(ci->getZExtValue(), Expr::Int8);
00920       case 16: return ConstantExpr::create(ci->getZExtValue(), Expr::Int16);
00921       case 32: return ConstantExpr::create(ci->getZExtValue(), Expr::Int32);
00922       case 64: return ConstantExpr::create(ci->getZExtValue(), Expr::Int64);
00923       default:
00924         assert(0 && "XXX arbitrary bit width constants unhandled");
00925       }
00926     } else if (const ConstantFP *cf = dyn_cast<ConstantFP>(c)) {      
00927       switch(cf->getType()->getTypeID()) {
00928       case Type::FloatTyID: {
00929         float f = cf->getValueAPF().convertToFloat();
00930         return ConstantExpr::create(floats::FloatAsUInt64(f), Expr::Int32);
00931       }
00932       case Type::DoubleTyID: {
00933         double d = cf->getValueAPF().convertToDouble();
00934         return ConstantExpr::create(floats::DoubleAsUInt64(d), Expr::Int64);
00935       } 
00936       case Type::X86_FP80TyID: {
00937         // FIXME: This is really broken, but for now we just convert
00938         // to a double. This isn't going to work at all in general,
00939         // but we need support for wide constants.
00940         APFloat apf = cf->getValueAPF();
00941         bool ignored;
00942         APFloat::opStatus r = apf.convert(APFloat::IEEEdouble, 
00943                                           APFloat::rmNearestTiesToAway,
00944                                           &ignored);
00945         (void) r;
00946         //assert(!(r & APFloat::opOverflow) && !(r & APFloat::opUnderflow) &&
00947         //       "Overflow/underflow while converting from FP80 (x87) to 64-bit double");
00948         double d = apf.convertToDouble();
00949         return ConstantExpr::create(floats::DoubleAsUInt64(d), Expr::Int64);
00950       }
00951       default:          
00952         llvm::cerr << "Constant of type " << cf->getType()->getDescription() 
00953                    << " not supported\n";
00954         llvm::cerr << "Constant used at ";
00955         KConstant *kc = kmodule->getKConstant((Constant*) cf);
00956         if (kc && kc->ki && kc->ki->info)
00957           llvm::cerr << kc->ki->info->file << ":" << kc->ki->info->line << "\n";
00958         else llvm::cerr << "<unknown>\n";
00959           
00960         assert(0 && "Arbitrary bit width floating point constants unsupported");
00961       }
00962     } else if (const GlobalValue *gv = dyn_cast<GlobalValue>(c)) {
00963       return globalAddresses.find(gv)->second;
00964     } else if (isa<ConstantPointerNull>(c)) {
00965       return Expr::createPointer(0);
00966     } else if (isa<UndefValue>(c)) {
00967       return ConstantExpr::create(0, Expr::getWidthForLLVMType(c->getType()));
00968     } else {
00969       // Constant{AggregateZero,Array,Struct,Vector}
00970       assert(0 && "invalid argument to evalConstant()");
00971     }
00972   }
00973 }
00974 
00975 const Cell& Executor::eval(KInstruction *ki, unsigned index, 
00976                            ExecutionState &state) const {
00977   assert(index < ki->inst->getNumOperands());
00978   int vnumber = ki->operands[index];
00979 
00980   // Determine if this is a constant or not.
00981   if (vnumber < 0) {
00982     unsigned index = -vnumber - 2;
00983     return kmodule->constantTable[index];
00984   } else {
00985     unsigned index = vnumber;
00986     StackFrame &sf = state.stack.back();
00987     return sf.locals[index];
00988   }
00989 }
00990 
00991 void Executor::bindLocal(KInstruction *target, ExecutionState &state, 
00992                          ref<Expr> value) {
00993   getDestCell(state, target).value = value;
00994 }
00995 
00996 void Executor::bindArgument(KFunction *kf, unsigned index, 
00997                             ExecutionState &state, ref<Expr> value) {
00998   getArgumentCell(state, kf, index).value = value;
00999 }
01000 
01001 ref<Expr> Executor::toUnique(const ExecutionState &state, 
01002                              ref<Expr> &e) {
01003   ref<Expr> result = e;
01004 
01005   if (!isa<ConstantExpr>(e)) {
01006     ref<ConstantExpr> value;
01007     bool isTrue = false;
01008 
01009     solver->setTimeout(stpTimeout);      
01010     if (solver->getValue(state, e, value) &&
01011         solver->mustBeTrue(state, EqExpr::create(e, value), isTrue) &&
01012         isTrue)
01013       result = value;
01014     solver->setTimeout(0);
01015   }
01016   
01017   return result;
01018 }
01019 
01020 
01021 /* Concretize the given expression, and return a possible constant value. 
01022    'reason' is just a documentation string stating the reason for concretization. */
01023 ref<klee::ConstantExpr> 
01024 Executor::toConstant(ExecutionState &state, 
01025                      ref<Expr> e,
01026                      const char *reason) {
01027   e = state.constraints.simplifyExpr(e);
01028   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(e))
01029     return CE;
01030 
01031   ref<ConstantExpr> value;
01032   bool success = solver->getValue(state, e, value);
01033   assert(success && "FIXME: Unhandled solver failure");
01034   (void) success;
01035     
01036   std::ostringstream os;
01037   os << "silently concretizing (reason: " << reason << ") expression " << e 
01038      << " to value " << value 
01039      << " (" << (*(state.pc)).info->file << ":" << (*(state.pc)).info->line << ")";
01040       
01041   if (AllExternalWarnings)
01042     klee_warning(reason, os.str().c_str());
01043   else
01044     klee_warning_once(reason, "%s", os.str().c_str());
01045 
01046   addConstraint(state, EqExpr::create(e, value));
01047     
01048   return value;
01049 }
01050 
01051 void Executor::executeGetValue(ExecutionState &state,
01052                                ref<Expr> e,
01053                                KInstruction *target) {
01054   e = state.constraints.simplifyExpr(e);
01055   std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it = 
01056     seedMap.find(&state);
01057   if (it==seedMap.end() || isa<ConstantExpr>(e)) {
01058     ref<ConstantExpr> value;
01059     bool success = solver->getValue(state, e, value);
01060     assert(success && "FIXME: Unhandled solver failure");
01061     (void) success;
01062     bindLocal(target, state, value);
01063   } else {
01064     std::set< ref<Expr> > values;
01065     for (std::vector<SeedInfo>::iterator siit = it->second.begin(), 
01066            siie = it->second.end(); siit != siie; ++siit) {
01067       ref<ConstantExpr> value;
01068       bool success = 
01069         solver->getValue(state, siit->assignment.evaluate(e), value);
01070       assert(success && "FIXME: Unhandled solver failure");
01071       (void) success;
01072       values.insert(value);
01073     }
01074     
01075     std::vector< ref<Expr> > conditions;
01076     for (std::set< ref<Expr> >::iterator vit = values.begin(), 
01077            vie = values.end(); vit != vie; ++vit)
01078       conditions.push_back(EqExpr::create(e, *vit));
01079 
01080     std::vector<ExecutionState*> branches;
01081     branch(state, conditions, branches);
01082     
01083     std::vector<ExecutionState*>::iterator bit = branches.begin();
01084     for (std::set< ref<Expr> >::iterator vit = values.begin(), 
01085            vie = values.end(); vit != vie; ++vit) {
01086       ExecutionState *es = *bit;
01087       if (es)
01088         bindLocal(target, *es, *vit);
01089       ++bit;
01090     }
01091   }
01092 }
01093 
01094 void Executor::stepInstruction(ExecutionState &state) {
01095   if (DebugPrintInstructions) {
01096     printFileLine(state, state.pc);
01097     llvm::cerr << std::setw(10) << stats::instructions << " " << *state.pc->inst;
01098   }
01099 
01100   if (statsTracker)
01101     statsTracker->stepInstruction(state);
01102 
01103   ++stats::instructions;
01104   state.prevPC = state.pc;
01105   ++state.pc;
01106 
01107   if (stats::instructions==StopAfterNInstructions)
01108     haltExecution = true;
01109 }
01110 
01111 void Executor::executeCall(ExecutionState &state, 
01112                            KInstruction *ki,
01113                            Function *f,
01114                            std::vector< ref<Expr> > &arguments) {
01115   if (WriteTraces) {
01116     // don't print out special debug stop point 'function' calls
01117     if (f->getIntrinsicID() != Intrinsic::dbg_stoppoint) {
01118       const std::string& calleeFuncName = f->getName();
01119       state.exeTraceMgr.addEvent(new FunctionCallTraceEvent(state, ki, calleeFuncName));
01120     }
01121   }
01122 
01123   Instruction *i = ki->inst;
01124   if (f && f->isDeclaration()) {
01125     if (f!=kmodule->dbgStopPointFn) { // special case speed hack
01126       switch(f->getIntrinsicID()) {
01127       case Intrinsic::dbg_stoppoint:
01128       case Intrinsic::dbg_region_start:
01129       case Intrinsic::dbg_region_end:
01130       case Intrinsic::dbg_func_start:
01131       case Intrinsic::dbg_declare:
01132       case Intrinsic::not_intrinsic:
01133         // state may be destroyed by this call, cannot touch
01134         callExternalFunction(state, ki, f, arguments);
01135         break;
01136           
01137         // vararg is handled by caller and intrinsic lowering,
01138         // see comment for ExecutionState::varargs
01139       case Intrinsic::vastart:  {
01140         StackFrame &sf = state.stack.back();
01141         assert(sf.varargs && 
01142                "vastart called in function with no vararg object");
01143         executeMemoryOperation(state, true, arguments[0], 
01144                                sf.varargs->getBaseExpr(), 0);
01145         break;
01146       }
01147       case Intrinsic::vaend:    // va_end is a noop for the interpreter
01148         break;
01149           
01150       case Intrinsic::vacopy: // should be lowered
01151       default:
01152         klee_error("unknown intrinsic: %s", f->getName().c_str());
01153       }
01154     }
01155 
01156     if (InvokeInst *ii = dyn_cast<InvokeInst>(i)) {
01157       transferToBasicBlock(ii->getNormalDest(), i->getParent(), state);
01158     }
01159   } else {
01160     // XXX not really happy about this reliance on prevPC but is ok I
01161     // guess. This just done to avoid having to pass KInstIterator
01162     // everywhere instead of the actual instruction, since we can't
01163     // make a KInstIterator from just an instruction (unlike LLVM).
01164     KFunction *kf = kmodule->functionMap[f];
01165     state.pushFrame(state.prevPC, kf);
01166     state.pc = kf->instructions;
01167         
01168     if (statsTracker)
01169       statsTracker->framePushed(state, &state.stack[state.stack.size()-2]);
01170         
01171     unsigned callingArgs = arguments.size();
01172     unsigned funcArgs = f->arg_size();
01173     if (!f->isVarArg()) {
01174       if (callingArgs > funcArgs) {
01175         klee_warning_once(f, "calling %s with extra arguments.", 
01176                           f->getName().c_str());
01177       } else if (callingArgs < funcArgs) {
01178         terminateStateOnError(state, "calling function with too few arguments", 
01179                               "user.err");
01180         return;
01181       }
01182     } else {
01183       if (callingArgs < funcArgs) {
01184         terminateStateOnError(state, "calling function with too few arguments", 
01185                               "user.err");
01186         return;
01187       }
01188             
01189       StackFrame &sf = state.stack.back();
01190       unsigned size = 0;
01191       for (unsigned i = funcArgs; i < callingArgs; i++)
01192         size += Expr::getMinBytesForWidth(arguments[i]->getWidth());
01193 
01194       MemoryObject *mo = sf.varargs = memory->allocate(size, true, false, 
01195                                                        state.prevPC->inst);
01196       if (!mo) {
01197         terminateStateOnExecError(state, "out of memory (varargs)");
01198         return;
01199       }
01200       ObjectState *os = bindObjectInState(state, mo, true);
01201       unsigned offset = 0;
01202       for (unsigned i = funcArgs; i < callingArgs; i++) {
01203         // XXX: DRE: i think we bind memory objects here?
01204         os->write(offset, arguments[i]);
01205         offset += Expr::getMinBytesForWidth(arguments[i]->getWidth());
01206       }
01207     }
01208 
01209     unsigned numFormals = f->arg_size();
01210     for (unsigned i=0; i<numFormals; ++i) 
01211       bindArgument(kf, i, state, arguments[i]);
01212   }
01213 }
01214 
01215 void Executor::transferToBasicBlock(BasicBlock *dst, BasicBlock *src, 
01216                                     ExecutionState &state) {
01217   // Note that in general phi nodes can reuse phi values from the same
01218   // block but the incoming value is the eval() result *before* the
01219   // execution of any phi nodes. this is pathological and doesn't
01220   // really seem to occur, but just in case we run the PhiCleanerPass
01221   // which makes sure this cannot happen and so it is safe to just
01222   // eval things in order. The PhiCleanerPass also makes sure that all
01223   // incoming blocks have the same order for each PHINode so we only
01224   // have to compute the index once.
01225   //
01226   // With that done we simply set an index in the state so that PHI
01227   // instructions know which argument to eval, set the pc, and continue.
01228   
01229   // XXX this lookup has to go ?
01230   KFunction *kf = state.stack.back().kf;
01231   unsigned entry = kf->basicBlockEntry[dst];
01232   state.pc = &kf->instructions[entry];
01233   if (state.pc->inst->getOpcode() == Instruction::PHI) {
01234     PHINode *first = static_cast<PHINode*>(state.pc->inst);
01235     state.incomingBBIndex = first->getBasicBlockIndex(src);
01236   }
01237 }
01238 
01239 void Executor::printFileLine(ExecutionState &state, KInstruction *ki) {
01240   const InstructionInfo &ii = *ki->info;
01241   if (ii.file != "") 
01242     llvm::cerr << "     " << ii.file << ":" << ii.line << ":";
01243   else
01244     llvm::cerr << "     [no debug info]:";
01245 }
01246 
01247 
01248 Function* Executor::getCalledFunction(CallSite &cs, ExecutionState &state) {
01249   Function *f = cs.getCalledFunction();
01250   
01251   if (f) {
01252     std::string alias = state.getFnAlias(f->getName());
01253     if (alias != "") {
01254       //llvm::cerr << f->getName() << "() is aliased with " << alias << "()\n";
01255       llvm::Module* currModule = kmodule->module;
01256       Function* old_f = f;
01257       f = currModule->getFunction(alias);
01258       if (!f) {
01259         llvm::cerr << "Function " << alias << "(), alias for " << old_f->getName() << " not found!\n";
01260         assert(f && "function alias not found");
01261       }
01262     }
01263   }
01264   
01265   return f;
01266 }
01267 
01268 
01269 void Executor::executeInstruction(ExecutionState &state, KInstruction *ki) {
01270   Instruction *i = ki->inst;
01271   switch (i->getOpcode()) {
01272     // Control flow
01273   case Instruction::Ret: {
01274     ReturnInst *ri = cast<ReturnInst>(i);
01275     KInstIterator kcaller = state.stack.back().caller;
01276     Instruction *caller = kcaller ? kcaller->inst : 0;
01277     bool isVoidReturn = (ri->getNumOperands() == 0);
01278     ref<Expr> result = ConstantExpr::alloc(0, Expr::Bool);
01279 
01280     if (WriteTraces) {
01281       state.exeTraceMgr.addEvent(new FunctionReturnTraceEvent(state, ki));
01282     }
01283     
01284     if (!isVoidReturn) {
01285       result = eval(ki, 0, state).value;
01286     }
01287     
01288     if (state.stack.size() <= 1) {
01289       assert(!caller && "caller set on initial stack frame");
01290       terminateStateOnExit(state);
01291     } else {
01292       state.popFrame();
01293 
01294       if (statsTracker)
01295         statsTracker->framePopped(state);
01296 
01297       if (InvokeInst *ii = dyn_cast<InvokeInst>(caller)) {
01298         transferToBasicBlock(ii->getNormalDest(), caller->getParent(), state);
01299       } else {
01300         state.pc = kcaller;
01301         ++state.pc;
01302       }
01303 
01304       if (!isVoidReturn) {
01305         const Type *t = caller->getType();
01306         if (t != Type::VoidTy) {
01307           // may need to do coercion due to bitcasts
01308           Expr::Width from = result->getWidth();
01309           Expr::Width to = Expr::getWidthForLLVMType(t);
01310             
01311           if (from != to) {
01312             CallSite cs = (isa<InvokeInst>(caller) ? CallSite(cast<InvokeInst>(caller)) : 
01313                            CallSite(cast<CallInst>(caller)));
01314 
01315             // XXX need to check other param attrs ?
01316             if (cs.paramHasAttr(0, llvm::Attribute::SExt)) {
01317               result = SExtExpr::create(result, to);
01318             } else {
01319               result = ZExtExpr::create(result, to);
01320             }
01321           }
01322 
01323           bindLocal(kcaller, state, result);
01324         }
01325       } else {
01326         // We check that the return value has no users instead of
01327         // checking the type, since C defaults to returning int for
01328         // undeclared functions.
01329         if (!caller->use_empty()) {
01330           terminateStateOnExecError(state, "return void when caller expected a result");
01331         }
01332       }
01333     }      
01334     break;
01335   }
01336   case Instruction::Unwind: {
01337     for (;;) {
01338       KInstruction *kcaller = state.stack.back().caller;
01339       state.popFrame();
01340 
01341       if (statsTracker)
01342         statsTracker->framePopped(state);
01343 
01344       if (state.stack.empty()) {
01345         terminateStateOnExecError(state, "unwind from initial stack frame");
01346         break;
01347       } else {
01348         Instruction *caller = kcaller->inst;
01349         if (InvokeInst *ii = dyn_cast<InvokeInst>(caller)) {
01350           transferToBasicBlock(ii->getUnwindDest(), caller->getParent(), state);
01351           break;
01352         }
01353       }
01354     }
01355     break;
01356   }
01357   case Instruction::Br: {
01358     BranchInst *bi = cast<BranchInst>(i);
01359     if (bi->isUnconditional()) {
01360       transferToBasicBlock(bi->getSuccessor(0), bi->getParent(), state);
01361     } else {
01362       // FIXME: Find a way that we don't have this hidden dependency.
01363       assert(bi->getCondition() == bi->getOperand(0) &&
01364              "Wrong operand index!");
01365       ref<Expr> cond = eval(ki, 0, state).value;
01366       Executor::StatePair branches = fork(state, cond, false);
01367 
01368       if (WriteTraces) {
01369         bool isTwoWay = (branches.first && branches.second);
01370 
01371         if (branches.first) {
01372           branches.first->exeTraceMgr.addEvent(
01373             new BranchTraceEvent(state, ki, true, isTwoWay));
01374         }
01375 
01376         if (branches.second) {
01377           branches.second->exeTraceMgr.addEvent(
01378             new BranchTraceEvent(state, ki, false, isTwoWay));
01379         }
01380       }
01381 
01382       // NOTE: There is a hidden dependency here, markBranchVisited
01383       // requires that we still be in the context of the branch
01384       // instruction (it reuses its statistic id). Should be cleaned
01385       // up with convenient instruction specific data.
01386       if (statsTracker && state.stack.back().kf->trackCoverage)
01387         statsTracker->markBranchVisited(branches.first, branches.second);
01388 
01389       if (branches.first)
01390         transferToBasicBlock(bi->getSuccessor(0), bi->getParent(), *branches.first);
01391       if (branches.second)
01392         transferToBasicBlock(bi->getSuccessor(1), bi->getParent(), *branches.second);
01393     }
01394     break;
01395   }
01396   case Instruction::Switch: {
01397     SwitchInst *si = cast<SwitchInst>(i);
01398     ref<Expr> cond = eval(ki, 0, state).value;
01399     unsigned cases = si->getNumCases();
01400     BasicBlock *bb = si->getParent();
01401 
01402     cond = toUnique(state, cond);
01403     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(cond)) {
01404       // Somewhat gross to create these all the time, but fine till we
01405       // switch to an internal rep.
01406       ConstantInt *ci = ConstantInt::get(si->getCondition()->getType(),
01407                                          CE->getConstantValue());
01408       unsigned index = si->findCaseValue(ci);
01409       transferToBasicBlock(si->getSuccessor(index), si->getParent(), state);
01410     } else {
01411       std::map<BasicBlock*, ref<Expr> > targets;
01412       ref<Expr> isDefault = ConstantExpr::alloc(1, Expr::Bool);
01413       for (unsigned i=1; i<cases; ++i) {
01414         ref<Expr> value = evalConstant(si->getCaseValue(i));
01415         ref<Expr> match = EqExpr::create(cond, value);
01416         isDefault = AndExpr::create(isDefault, Expr::createNot(match));
01417         bool result;
01418         bool success = solver->mayBeTrue(state, match, result);
01419         assert(success && "FIXME: Unhandled solver failure");
01420         (void) success;
01421         if (result) {
01422           std::map<BasicBlock*, ref<Expr> >::iterator it =
01423             targets.insert(std::make_pair(si->getSuccessor(i),
01424                                           ConstantExpr::alloc(0, Expr::Bool))).first;
01425           it->second = OrExpr::create(match, it->second);
01426         }
01427       }
01428       bool res;
01429       bool success = solver->mayBeTrue(state, isDefault, res);
01430       assert(success && "FIXME: Unhandled solver failure");
01431       (void) success;
01432       if (res)
01433         targets.insert(std::make_pair(si->getSuccessor(0), isDefault));
01434       
01435       std::vector< ref<Expr> > conditions;
01436       for (std::map<BasicBlock*, ref<Expr> >::iterator it = 
01437              targets.begin(), ie = targets.end();
01438            it != ie; ++it)
01439         conditions.push_back(it->second);
01440       
01441       std::vector<ExecutionState*> branches;
01442       branch(state, conditions, branches);
01443         
01444       std::vector<ExecutionState*>::iterator bit = branches.begin();
01445       for (std::map<BasicBlock*, ref<Expr> >::iterator it = 
01446              targets.begin(), ie = targets.end();
01447            it != ie; ++it) {
01448         ExecutionState *es = *bit;
01449         if (es)
01450           transferToBasicBlock(it->first, bb, *es);
01451         ++bit;
01452       }
01453     }
01454     break;
01455  }
01456   case Instruction::Unreachable:
01457     // Note that this is not necessarily an internal bug, llvm will
01458     // generate unreachable instructions in cases where it knows the
01459     // program will crash. So it is effectively a SEGV or internal
01460     // error.
01461     terminateStateOnExecError(state, "reached \"unreachable\" instruction");
01462     break;
01463 
01464   case Instruction::Invoke:
01465   case Instruction::Call: {
01466     CallSite cs;
01467     unsigned argStart;
01468     if (i->getOpcode()==Instruction::Call) {
01469       cs = CallSite(cast<CallInst>(i));
01470       argStart = 1;
01471     } else {
01472       cs = CallSite(cast<InvokeInst>(i));
01473       argStart = 3;
01474     }
01475 
01476     unsigned numArgs = cs.arg_size();
01477     Function *f = getCalledFunction(cs, state);
01478       
01479     // evaluate arguments
01480     std::vector< ref<Expr> > arguments;
01481     arguments.reserve(numArgs);
01482 
01483     for (unsigned j=0; j<numArgs; ++j)
01484       arguments.push_back(eval(ki, argStart+j, state).value);
01485 
01486     if (!f) {
01487       // special case the call with a bitcast case
01488       Value *fp = cs.getCalledValue();
01489       llvm::ConstantExpr *ce = dyn_cast<llvm::ConstantExpr>(fp);
01490         
01491       if (ce && ce->getOpcode()==Instruction::BitCast) {
01492         f = dyn_cast<Function>(ce->getOperand(0));
01493         assert(f && "XXX unrecognized constant expression in call");
01494         const FunctionType *fType = 
01495           dyn_cast<FunctionType>(cast<PointerType>(f->getType())->getElementType());
01496         const FunctionType *ceType =
01497           dyn_cast<FunctionType>(cast<PointerType>(ce->getType())->getElementType());
01498         assert(fType && ceType && "unable to get function type");
01499 
01500         // XXX check result coercion
01501 
01502         // XXX this really needs thought and validation
01503         unsigned i=0;
01504         for (std::vector< ref<Expr> >::iterator
01505                ai = arguments.begin(), ie = arguments.end();
01506              ai != ie; ++ai) {
01507           Expr::Width to, from = (*ai)->getWidth();
01508             
01509           if (i<fType->getNumParams()) {
01510             to = Expr::getWidthForLLVMType(fType->getParamType(i));
01511 
01512             if (from != to) {
01513               // XXX need to check other param attrs ?
01514               if (cs.paramHasAttr(i+1, llvm::Attribute::SExt)) {
01515                 arguments[i] = SExtExpr::create(arguments[i], to);
01516               } else {
01517                 arguments[i] = ZExtExpr::create(arguments[i], to);
01518               }
01519             }
01520           }
01521             
01522           i++;
01523         }
01524       } else if (isa<InlineAsm>(fp)) {
01525         terminateStateOnExecError(state, "inline assembly is unsupported");
01526         break;
01527       }
01528     }
01529 
01530     if (f) {
01531       executeCall(state, ki, f, arguments);
01532     } else {
01533       ref<Expr> v = eval(ki, 0, state).value;
01534 
01535       ExecutionState *free = &state;
01536       bool hasInvalid = false, first = true;
01537 
01538       /* XXX This is wasteful, no need to do a full evaluate since we
01539          have already got a value. But in the end the caches should
01540          handle it for us, albeit with some overhead. */
01541       do {
01542         ref<ConstantExpr> value;
01543         bool success = solver->getValue(*free, v, value);
01544         assert(success && "FIXME: Unhandled solver failure");
01545         (void) success;
01546         StatePair res = fork(*free, EqExpr::create(v, value), true);
01547         if (res.first) {
01548           void *addr = (void*) (unsigned long) value->getConstantValue();
01549           std::set<void*>::iterator it = legalFunctions.find(addr);
01550           if (it != legalFunctions.end()) {
01551             f = (Function*) addr;
01552 
01553             // Don't give warning on unique resolution
01554             if (res.second || !first)
01555               klee_warning_once(addr, 
01556                                 "resolved symbolic function pointer to: %s",
01557                                 f->getName().c_str());
01558 
01559             executeCall(*res.first, ki, f, arguments);
01560           } else {
01561             if (!hasInvalid) {
01562               terminateStateOnExecError(state, "invalid function pointer");
01563               hasInvalid = true;
01564             }
01565           }
01566         }
01567 
01568         first = false;
01569         free = res.second;
01570       } while (free);
01571     }
01572     break;
01573   }
01574   case Instruction::PHI: {
01575     ref<Expr> result = eval(ki, state.incomingBBIndex * 2, state).value;
01576     bindLocal(ki, state, result);
01577     break;
01578   }
01579 
01580     // Special instructions
01581   case Instruction::Select: {
01582     SelectInst *SI = cast<SelectInst>(ki->inst);
01583     assert(SI->getCondition() == SI->getOperand(0) &&
01584            "Wrong operand index!");
01585     ref<Expr> cond = eval(ki, 0, state).value;
01586     ref<Expr> tExpr = eval(ki, 1, state).value;
01587     ref<Expr> fExpr = eval(ki, 2, state).value;
01588     ref<Expr> result = SelectExpr::create(cond, tExpr, fExpr);
01589     bindLocal(ki, state, result);
01590     break;
01591   }
01592 
01593   case Instruction::VAArg:
01594     terminateStateOnExecError(state, "unexpected VAArg instruction");
01595     break;
01596 
01597     // Arithmetic / logical
01598 
01599   case Instruction::Add: {
01600     ref<Expr> left = eval(ki, 0, state).value;
01601     ref<Expr> right = eval(ki, 1, state).value;
01602     bindLocal(ki, state, AddExpr::create(left, right));
01603     break;
01604   }
01605 
01606   case Instruction::Sub: {
01607     ref<Expr> left = eval(ki, 0, state).value;
01608     ref<Expr> right = eval(ki, 1, state).value;
01609     bindLocal(ki, state, SubExpr::create(left, right));
01610     break;
01611   }
01612  
01613   case Instruction::Mul: {
01614     ref<Expr> left = eval(ki, 0, state).value;
01615     ref<Expr> right = eval(ki, 1, state).value;
01616     bindLocal(ki, state, MulExpr::create(left, right));
01617     break;
01618   }
01619 
01620   case Instruction::UDiv: {
01621     ref<Expr> left = eval(ki, 0, state).value;
01622     ref<Expr> right = eval(ki, 1, state).value;
01623     ref<Expr> result = UDivExpr::create(left, right);
01624     bindLocal(ki, state, result);
01625     break;
01626   }
01627 
01628   case Instruction::SDiv: {
01629     ref<Expr> left = eval(ki, 0, state).value;
01630     ref<Expr> right = eval(ki, 1, state).value;
01631     ref<Expr> result = SDivExpr::create(left, right);
01632     bindLocal(ki, state, result);
01633     break;
01634   }
01635 
01636   case Instruction::URem: {
01637     ref<Expr> left = eval(ki, 0, state).value;
01638     ref<Expr> right = eval(ki, 1, state).value;
01639     ref<Expr> result = URemExpr::create(left, right);
01640     bindLocal(ki, state, result);
01641     break;
01642   }
01643  
01644   case Instruction::SRem: {
01645     ref<Expr> left = eval(ki, 0, state).value;
01646     ref<Expr> right = eval(ki, 1, state).value;
01647     ref<Expr> result = SRemExpr::create(left, right);
01648     bindLocal(ki, state, result);
01649     break;
01650   }
01651 
01652   case Instruction::And: {
01653     ref<Expr> left = eval(ki, 0, state).value;
01654     ref<Expr> right = eval(ki, 1, state).value;
01655     ref<Expr> result = AndExpr::create(left, right);
01656     bindLocal(ki, state, result);
01657     break;
01658   }
01659 
01660   case Instruction::Or: {
01661     ref<Expr> left = eval(ki, 0, state).value;
01662     ref<Expr> right = eval(ki, 1, state).value;
01663     ref<Expr> result = OrExpr::create(left, right);
01664     bindLocal(ki, state, result);
01665     break;
01666   }
01667 
01668   case Instruction::Xor: {
01669     ref<Expr> left = eval(ki, 0, state).value;
01670     ref<Expr> right = eval(ki, 1, state).value;
01671     ref<Expr> result = XorExpr::create(left, right);
01672     bindLocal(ki, state, result);
01673     break;
01674   }
01675 
01676   case Instruction::Shl: {
01677     ref<Expr> left = eval(ki, 0, state).value;
01678     ref<Expr> right = eval(ki, 1, state).value;
01679     ref<Expr> result = ShlExpr::create(left, right);
01680     bindLocal(ki, state, result);
01681     break;
01682   }
01683 
01684   case Instruction::LShr: {
01685     ref<Expr> left = eval(ki, 0, state).value;
01686     ref<Expr> right = eval(ki, 1, state).value;
01687     ref<Expr> result = LShrExpr::create(left, right);
01688     bindLocal(ki, state, result);
01689     break;
01690   }
01691 
01692   case Instruction::AShr: {
01693     ref<Expr> left = eval(ki, 0, state).value;
01694     ref<Expr> right = eval(ki, 1, state).value;
01695     ref<Expr> result = AShrExpr::create(left, right);
01696     bindLocal(ki, state, result);
01697     break;
01698   }
01699 
01700     // Compare
01701 
01702   case Instruction::ICmp: {
01703     CmpInst *ci = cast<CmpInst>(i);
01704     ICmpInst *ii = cast<ICmpInst>(ci);
01705  
01706     switch(ii->getPredicate()) {
01707     case ICmpInst::ICMP_EQ: {
01708       ref<Expr> left = eval(ki, 0, state).value;
01709       ref<Expr> right = eval(ki, 1, state).value;
01710       ref<Expr> result = EqExpr::create(left, right);
01711       bindLocal(ki, state, result);
01712       break;
01713     }
01714 
01715     case ICmpInst::ICMP_NE: {
01716       ref<Expr> left = eval(ki, 0, state).value;
01717       ref<Expr> right = eval(ki, 1, state).value;
01718       ref<Expr> result = NeExpr::create(left, right);
01719       bindLocal(ki, state, result);
01720       break;
01721     }
01722 
01723     case ICmpInst::ICMP_UGT: {
01724       ref<Expr> left = eval(ki, 0, state).value;
01725       ref<Expr> right = eval(ki, 1, state).value;
01726       ref<Expr> result = UgtExpr::create(left, right);
01727       bindLocal(ki, state,result);
01728       break;
01729     }
01730 
01731     case ICmpInst::ICMP_UGE: {
01732       ref<Expr> left = eval(ki, 0, state).value;
01733       ref<Expr> right = eval(ki, 1, state).value;
01734       ref<Expr> result = UgeExpr::create(left, right);
01735       bindLocal(ki, state, result);
01736       break;
01737     }
01738 
01739     case ICmpInst::ICMP_ULT: {
01740       ref<Expr> left = eval(ki, 0, state).value;
01741       ref<Expr> right = eval(ki, 1, state).value;
01742       ref<Expr> result = UltExpr::create(left, right);
01743       bindLocal(ki, state, result);
01744       break;
01745     }
01746 
01747     case ICmpInst::ICMP_ULE: {
01748       ref<Expr> left = eval(ki, 0, state).value;
01749       ref<Expr> right = eval(ki, 1, state).value;
01750       ref<Expr> result = UleExpr::create(left, right);
01751       bindLocal(ki, state, result);
01752       break;
01753     }
01754 
01755     case ICmpInst::ICMP_SGT: {
01756       ref<Expr> left = eval(ki, 0, state).value;
01757       ref<Expr> right = eval(ki, 1, state).value;
01758       ref<Expr> result = SgtExpr::create(left, right);
01759       bindLocal(ki, state, result);
01760       break;
01761     }
01762 
01763     case ICmpInst::ICMP_SGE: {
01764       ref<Expr> left = eval(ki, 0, state).value;
01765       ref<Expr> right = eval(ki, 1, state).value;
01766       ref<Expr> result = SgeExpr::create(left, right);
01767       bindLocal(ki, state, result);
01768       break;
01769     }
01770 
01771     case ICmpInst::ICMP_SLT: {
01772       ref<Expr> left = eval(ki, 0, state).value;
01773       ref<Expr> right = eval(ki, 1, state).value;
01774       ref<Expr> result = SltExpr::create(left, right);
01775       bindLocal(ki, state, result);
01776       break;
01777     }
01778 
01779     case ICmpInst::ICMP_SLE: {
01780       ref<Expr> left = eval(ki, 0, state).value;
01781       ref<Expr> right = eval(ki, 1, state).value;
01782       ref<Expr> result = SleExpr::create(left, right);
01783       bindLocal(ki, state, result);
01784       break;
01785     }
01786 
01787     default:
01788       terminateStateOnExecError(state, "invalid ICmp predicate");
01789     }
01790     break;
01791   }
01792  
01793     // Memory instructions...
01794   case Instruction::Alloca:
01795   case Instruction::Malloc: {
01796     AllocationInst *ai = cast<AllocationInst>(i);
01797     unsigned elementSize = 
01798       kmodule->targetData->getTypeStoreSize(ai->getAllocatedType());
01799     ref<Expr> size = Expr::createPointer(elementSize);
01800     if (ai->isArrayAllocation()) {
01801       // XXX coerce?
01802       ref<Expr> count = eval(ki, 0, state).value;
01803       size = MulExpr::create(count, size);
01804     }
01805     bool isLocal = i->getOpcode()==Instruction::Alloca;
01806     executeAlloc(state, size, isLocal, ki);
01807     break;
01808   }
01809   case Instruction::Free: {
01810     executeFree(state, eval(ki, 0, state).value);
01811     break;
01812   }
01813 
01814   case Instruction::Load: {
01815     ref<Expr> base = eval(ki, 0, state).value;
01816     executeMemoryOperation(state, false, base, 0, ki);
01817     break;
01818   }
01819   case Instruction::Store: {
01820     ref<Expr> base = eval(ki, 1, state).value;
01821     ref<Expr> value = eval(ki, 0, state).value;
01822     executeMemoryOperation(state, true, base, value, 0);
01823     break;
01824   }
01825 
01826   case Instruction::GetElementPtr: {
01827     KGEPInstruction *kgepi = static_cast<KGEPInstruction*>(ki);
01828     ref<Expr> base = eval(ki, 0, state).value;
01829 
01830     for (std::vector< std::pair<unsigned, unsigned> >::iterator 
01831            it = kgepi->indices.begin(), ie = kgepi->indices.end(); 
01832          it != ie; ++it) {
01833       unsigned elementSize = it->second;
01834       ref<Expr> index = eval(ki, it->first, state).value;
01835       base = AddExpr::create(base,
01836                              MulExpr::create(Expr::createCoerceToPointerType(index),
01837                                              Expr::createPointer(elementSize)));
01838     }
01839     if (kgepi->offset)
01840       base = AddExpr::create(base,
01841                              Expr::createPointer(kgepi->offset));
01842     bindLocal(ki, state, base);
01843     break;
01844   }
01845 
01846     // Conversion
01847   case Instruction::Trunc: {
01848     CastInst *ci = cast<CastInst>(i);
01849     ref<Expr> result = ExtractExpr::createByteOff(eval(ki, 0, state).value,
01850                                                   0,
01851                                                   Expr::getWidthForLLVMType(ci->getType()));
01852     bindLocal(ki, state, result);
01853     break;
01854   }
01855   case Instruction::ZExt: {
01856     CastInst *ci = cast<CastInst>(i);
01857     ref<Expr> result = ZExtExpr::create(eval(ki, 0, state).value,
01858                                         Expr::getWidthForLLVMType(ci->getType()));
01859     bindLocal(ki, state, result);
01860     break;
01861   }
01862   case Instruction::SExt: {
01863     CastInst *ci = cast<CastInst>(i);
01864     ref<Expr> result = SExtExpr::create(eval(ki, 0, state).value,
01865                                         Expr::getWidthForLLVMType(ci->getType()));
01866     bindLocal(ki, state, result);
01867     break;
01868   }
01869 
01870   case Instruction::IntToPtr: {
01871     CastInst *ci = cast<CastInst>(i);
01872     Expr::Width pType = Expr::getWidthForLLVMType(ci->getType());
01873     ref<Expr> arg = eval(ki, 0, state).value;
01874     bindLocal(ki, state, ZExtExpr::create(arg, pType));
01875     break;
01876   } 
01877   case Instruction::PtrToInt: {
01878     CastInst *ci = cast<CastInst>(i);
01879     Expr::Width iType = Expr::getWidthForLLVMType(ci->getType());
01880     ref<Expr> arg = eval(ki, 0, state).value;
01881     bindLocal(ki, state, ZExtExpr::create(arg, iType));
01882     break;
01883   }
01884 
01885   case Instruction::BitCast: {
01886     ref<Expr> result = eval(ki, 0, state).value;
01887     bindLocal(ki, state, result);
01888     break;
01889   }
01890 
01891     // Floating point specific instructions
01892 
01893 #define FP_CONSTANT_BINOP(op, type, l, r, target, state)        \
01894     bindLocal(target, state,                                            \
01895               ConstantExpr::alloc(op(toConstant(state, l,               \
01896                                                 "floating point")->getConstantValue(), \
01897                                      toConstant(state, r,               \
01898                                                 "floating point")->getConstantValue(), \
01899                                      type), type))
01900 
01901   case Instruction::FAdd: {
01902     BinaryOperator *bi = cast<BinaryOperator>(i);
01903     ref<Expr> left = eval(ki, 0, state).value;
01904     ref<Expr> right = eval(ki, 1, state).value;
01905     Expr::Width type = Expr::getWidthForLLVMType(bi->getType());
01906     FP_CONSTANT_BINOP(floats::add, type, left, right, ki, state);
01907     break;
01908   }
01909 
01910   case Instruction::FSub: {
01911     BinaryOperator *bi = cast<BinaryOperator>(i);
01912     ref<Expr> left = eval(ki, 0, state).value;
01913     ref<Expr> right = eval(ki, 1, state).value;
01914     Expr::Width type = Expr::getWidthForLLVMType(bi->getType());
01915     FP_CONSTANT_BINOP(floats::sub, type, left, right, ki, state);
01916     break;
01917   }
01918  
01919   case Instruction::FMul: {
01920     BinaryOperator *bi = cast<BinaryOperator>(i);
01921     ref<Expr> left = eval(ki, 0, state).value;
01922     ref<Expr> right = eval(ki, 1, state).value;
01923     Expr::Width type = Expr::getWidthForLLVMType(bi->getType());
01924     FP_CONSTANT_BINOP(floats::mul, type, left, right, ki, state);
01925     break;
01926   }
01927 
01928   case Instruction::FPTrunc: {
01929     FPTruncInst *fi = cast<FPTruncInst>(i);
01930     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01931     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01932                                        "floating point");
01933     uint64_t value = floats::trunc(arg->getConstantValue(),
01934                                    resultType,
01935                                    arg->getWidth());
01936     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01937     break;
01938   }
01939 
01940   case Instruction::FPExt: {
01941     FPExtInst *fi = cast<FPExtInst>(i);
01942     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01943     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01944                                        "floating point");
01945     uint64_t value = floats::ext(arg->getConstantValue(),
01946                                  resultType,
01947                                  arg->getWidth());
01948     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01949     break;
01950   }
01951 
01952   case Instruction::FPToUI: {
01953     FPToUIInst *fi = cast<FPToUIInst>(i);
01954     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01955     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01956                                        "floating point");
01957     uint64_t value = floats::toUnsignedInt(arg->getConstantValue(),
01958                                            resultType,
01959                                            arg->getWidth());
01960     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01961     break;
01962   }
01963 
01964   case Instruction::FPToSI: {
01965     FPToSIInst *fi = cast<FPToSIInst>(i);
01966     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01967     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01968                                        "floating point");
01969     uint64_t value = floats::toSignedInt(arg->getConstantValue(),
01970                                          resultType,
01971                                          arg->getWidth());
01972     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01973     break;
01974   }
01975 
01976   case Instruction::UIToFP: {
01977     UIToFPInst *fi = cast<UIToFPInst>(i);
01978     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01979     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01980                                        "floating point");
01981     uint64_t value = floats::UnsignedIntToFP(arg->getConstantValue(),
01982                                              resultType);
01983     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01984     break;
01985   }
01986 
01987   case Instruction::SIToFP: {
01988     SIToFPInst *fi = cast<SIToFPInst>(i);
01989     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
01990     ref<ConstantExpr> arg = toConstant(state, eval(ki, 0, state).value,
01991                                        "floating point");
01992     uint64_t value = floats::SignedIntToFP(arg->getConstantValue(),
01993                                            resultType,
01994                                            arg->getWidth());
01995     bindLocal(ki, state, ConstantExpr::alloc(value, resultType));
01996     break;
01997   }
01998 
01999   case Instruction::FCmp: {
02000     FCmpInst *fi = cast<FCmpInst>(i);
02001     Expr::Width resultType = Expr::getWidthForLLVMType(fi->getType());
02002     ref<ConstantExpr> left  = toConstant(state, eval(ki, 0, state).value, 
02003                                          "floating point");
02004     ref<ConstantExpr> right = toConstant(state, eval(ki, 1, state).value,
02005                                          "floating point");
02006     uint64_t leftVal = left->getConstantValue();
02007     uint64_t rightVal = right->getConstantValue();
02008  
02009     //determine whether the operands are NANs
02010     unsigned inWidth = left->getWidth();
02011     bool leftIsNaN   = floats::isNaN( leftVal,  inWidth );
02012     bool rightIsNaN  = floats::isNaN( rightVal, inWidth );
02013 
02014     //handle NAN based on whether the predicate is "ordered" or "unordered"
02015     uint64_t ret = (uint64_t)-1;
02016     bool done = false;
02017     switch( fi->getPredicate() ) {
02018       //predicates which only care about whether or not the operands are NaNs
02019     case FCmpInst::FCMP_ORD:
02020       done = true;
02021       ret = !leftIsNaN && !rightIsNaN;
02022       break;
02023 
02024     case FCmpInst::FCMP_UNO:
02025       done = true;
02026       ret = leftIsNaN || rightIsNaN;
02027       break;
02028 
02029       //ordered comparisons return false if either operand is NaN
02030     case FCmpInst::FCMP_OEQ:
02031     case FCmpInst::FCMP_OGT:
02032     case FCmpInst::FCMP_OGE:
02033     case FCmpInst::FCMP_OLT:
02034     case FCmpInst::FCMP_OLE:
02035     case FCmpInst::FCMP_ONE:
02036       if( !leftIsNaN && !rightIsNaN) //only fall through and return false if there are NaN(s)
02037         break;
02038 
02039     case FCmpInst::FCMP_FALSE: { //always return false for this predicate
02040       done = true;
02041       ret  = false;
02042       break;
02043     }
02044 
02045       //unordered comparisons return true if either operand is NaN
02046     case FCmpInst::FCMP_UEQ:
02047     case FCmpInst::FCMP_UGT:
02048     case FCmpInst::FCMP_UGE:
02049     case FCmpInst::FCMP_ULT:
02050     case FCmpInst::FCMP_ULE:
02051     case FCmpInst::FCMP_UNE:
02052       if( !leftIsNaN && !rightIsNaN) //only fall through and return true if there are NaN(s)
02053         break;
02054 
02055     case FCmpInst::FCMP_TRUE: //always return true for this predicate
02056       done = true;
02057       ret  = true;
02058 
02059     default:
02060     case FCmpInst::BAD_FCMP_PREDICATE: /* will fall through and trigger fatal in the next switch */
02061       break;
02062     }
02063 
02064     //if not done, then we need to actually do a comparison to get the result
02065     if( !done ) {
02066       switch( fi->getPredicate() ) {
02067         //ordered comparisons return false if either operand is NaN
02068       case FCmpInst::FCMP_OEQ:
02069       case FCmpInst::FCMP_UEQ:
02070         ret = floats::eq( leftVal, rightVal, inWidth );
02071         break;
02072 
02073       case FCmpInst::FCMP_OGT:
02074       case FCmpInst::FCMP_UGT:
02075         ret = floats::gt( leftVal, rightVal, inWidth );
02076         break;
02077 
02078       case FCmpInst::FCMP_OGE:
02079       case FCmpInst::FCMP_UGE:
02080         ret = floats::ge( leftVal, rightVal, inWidth );
02081         break;
02082 
02083       case FCmpInst::FCMP_OLT:
02084       case FCmpInst::FCMP_ULT:
02085         ret = floats::lt( leftVal, rightVal, inWidth );
02086         break;
02087 
02088       case FCmpInst::FCMP_OLE:
02089       case FCmpInst::FCMP_ULE:
02090         ret = floats::le( leftVal, rightVal, inWidth );
02091         break;
02092 
02093       case FCmpInst::FCMP_ONE:
02094       case FCmpInst::FCMP_UNE:
02095         ret = floats::ne( leftVal, rightVal, inWidth );
02096         break;
02097       
02098       default:
02099         terminateStateOnExecError(state, "invalid FCmp predicate");
02100       }
02101     }
02102 
02103     bindLocal(ki, state, ConstantExpr::alloc(ret, resultType));
02104     break;
02105   }
02106 
02107   case Instruction::FDiv: {
02108     BinaryOperator *bi = cast<BinaryOperator>(i);
02109 
02110     ref<Expr> dividend = eval(ki, 0, state).value;
02111     ref<Expr> divisor = eval(ki, 1, state).value;
02112     Expr::Width type = Expr::getWidthForLLVMType(bi->getType());
02113     FP_CONSTANT_BINOP(floats::div, type, dividend, divisor, ki, state);
02114     break;
02115   }
02116 
02117   case Instruction::FRem: {
02118     BinaryOperator *bi = cast<BinaryOperator>(i);
02119 
02120     ref<Expr> dividend = eval(ki, 0, state).value;
02121     ref<Expr> divisor = eval(ki, 1, state).value;
02122     Expr::Width type = Expr::getWidthForLLVMType(bi->getType());
02123     FP_CONSTANT_BINOP(floats::mod, type, dividend, divisor, ki, state);
02124     break;
02125   }
02126 
02127  
02128     // Other instructions...
02129     // Unhandled
02130   case Instruction::ExtractElement:
02131   case Instruction::InsertElement:
02132   case Instruction::ShuffleVector:
02133     terminateStateOnError(state, "XXX vector instructions unhandled",
02134                           "xxx.err");
02135     break;
02136  
02137   default:
02138     terminateStateOnExecError(state, "illegal instruction");
02139     break;
02140   }
02141 }
02142 
02143 void Executor::updateStates(ExecutionState *current) {
02144   if (searcher) {
02145     searcher->update(current, addedStates, removedStates);
02146   }
02147   
02148   states.insert(addedStates.begin(), addedStates.end());
02149   addedStates.clear();
02150   
02151   for (std::set<ExecutionState*>::iterator
02152          it = removedStates.begin(), ie = removedStates.end();
02153        it != ie; ++it) {
02154     ExecutionState *es = *it;
02155     std::set<ExecutionState*>::iterator it2 = states.find(es);
02156     assert(it2!=states.end());
02157     states.erase(it2);
02158     std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it3 = 
02159       seedMap.find(es);
02160     if (it3 != seedMap.end())
02161       seedMap.erase(it3);
02162     processTree->remove(es->ptreeNode);
02163     delete es;
02164   }
02165   removedStates.clear();
02166 }
02167 
02168 void Executor::bindInstructionConstants(KInstruction *KI) {
02169   GetElementPtrInst *gepi = dyn_cast<GetElementPtrInst>(KI->inst);
02170   if (!gepi)
02171     return;
02172 
02173   KGEPInstruction *kgepi = static_cast<KGEPInstruction*>(KI);
02174   ref<Expr> constantOffset = Expr::createPointer(0);
02175   unsigned index = 1;
02176   for (gep_type_iterator ii = gep_type_begin(gepi), ie = gep_type_end(gepi);
02177        ii != ie; ++ii) {
02178     if (const StructType *st = dyn_cast<StructType>(*ii)) {
02179       const StructLayout *sl = 
02180         kmodule->targetData->getStructLayout(st);
02181       const ConstantInt *ci = cast<ConstantInt>(ii.getOperand());
02182       ref<Expr> addend = Expr::createPointer(sl->getElementOffset((unsigned) 
02183                                                                   ci->getZExtValue()));
02184       constantOffset = AddExpr::create(constantOffset, addend);
02185     } else {
02186       const SequentialType *st = cast<SequentialType>(*ii);
02187       unsigned elementSize = 
02188         kmodule->targetData->getTypeStoreSize(st->getElementType());
02189       Value *operand = ii.getOperand();
02190       if (Constant *c = dyn_cast<Constant>(operand)) {
02191         ref<Expr> index = evalConstant(c);
02192         ref<Expr> addend = MulExpr::create(Expr::createCoerceToPointerType(index), 
02193                                            Expr::createPointer(elementSize));
02194         constantOffset = AddExpr::create(constantOffset, addend);
02195       } else {
02196         kgepi->indices.push_back(std::make_pair(index, elementSize));
02197       }
02198     }
02199     index++;
02200   }
02201   kgepi->offset = cast<ConstantExpr>(constantOffset)->getConstantValue();
02202 }
02203 
02204 void Executor::bindModuleConstants() {
02205   for (std::vector<KFunction*>::iterator it = kmodule->functions.begin(), 
02206          ie = kmodule->functions.end(); it != ie; ++it) {
02207     KFunction *kf = *it;
02208     for (unsigned i=0; i<kf->numInstructions; ++i)
02209       bindInstructionConstants(kf->instructions[i]);
02210   }
02211 
02212   kmodule->constantTable = new Cell[kmodule->constants.size()];
02213   for (unsigned i=0; i<kmodule->constants.size(); ++i) {
02214     Cell &c = kmodule->constantTable[i];
02215     c.value = evalConstant(kmodule->constants[i]);
02216   }
02217 }
02218 
02219 void Executor::run(ExecutionState &initialState) {
02220   bindModuleConstants();
02221 
02222   // Delay init till now so that ticks don't accrue during
02223   // optimization and such.
02224   initTimers();
02225 
02226   states.insert(&initialState);
02227 
02228   if (usingSeeds) {
02229     std::vector<SeedInfo> &v = seedMap[&initialState];
02230     
02231     for (std::vector<KTest*>::const_iterator it = usingSeeds->begin(), 
02232            ie = usingSeeds->end(); it != ie; ++it)
02233       v.push_back(SeedInfo(*it));
02234 
02235     int lastNumSeeds = usingSeeds->size()+10;
02236     double lastTime, startTime = lastTime = util::getWallTime();
02237     ExecutionState *lastState = 0;
02238     while (!seedMap.empty()) {
02239       if (haltExecution) goto dump;
02240 
02241       std::map<ExecutionState*, std::vector<SeedInfo> >::iterator it = 
02242         seedMap.upper_bound(lastState);
02243       if (it == seedMap.end())
02244         it = seedMap.begin();
02245       lastState = it->first;
02246       unsigned numSeeds = it->second.size();
02247       ExecutionState &state = *lastState;
02248       KInstruction *ki = state.pc;
02249       stepInstruction(state);
02250 
02251       executeInstruction(state, ki);
02252       processTimers(&state, MaxInstructionTime * numSeeds);
02253       updateStates(&state);
02254 
02255       if ((stats::instructions % 1000) == 0) {
02256         int numSeeds = 0, numStates = 0;
02257         for (std::map<ExecutionState*, std::vector<SeedInfo> >::iterator
02258                it = seedMap.begin(), ie = seedMap.end();
02259              it != ie; ++it) {
02260           numSeeds += it->second.size();
02261           numStates++;
02262         }
02263         double time = util::getWallTime();
02264         if (SeedTime>0. && time > startTime + SeedTime) {
02265           klee_warning("seed time expired, %d seeds remain over %d states",
02266                        numSeeds, numStates);
02267           break;
02268         } else if (numSeeds<=lastNumSeeds-10 ||
02269                    time >= lastTime+10) {
02270           lastTime = time;
02271           lastNumSeeds = numSeeds;          
02272           klee_message("%d seeds remaining over: %d states", 
02273                        numSeeds, numStates);
02274         }
02275       }
02276     }
02277 
02278     klee_message("seeding done (%d states remain)", (int) states.size());
02279 
02280     // XXX total hack, just because I like non uniform better but want
02281     // seed results to be equally weighted.
02282     for (std::set<ExecutionState*>::iterator
02283            it = states.begin(), ie = states.end();
02284          it != ie; ++it) {
02285       (*it)->weight = 1.;
02286     }
02287 
02288     if (OnlySeed)
02289       goto dump;
02290   }
02291 
02292   searcher = constructUserSearcher(*this);
02293 
02294   searcher->update(0, states, std::set<ExecutionState*>());
02295 
02296   while (!states.empty() && !haltExecution) {
02297     ExecutionState &state = searcher->selectState();
02298     KInstruction *ki = state.pc;
02299     stepInstruction(state);
02300 
02301     executeInstruction(state, ki);
02302     processTimers(&state, MaxInstructionTime);
02303 
02304     if (MaxMemory) {
02305       if ((stats::instructions & 0xFFFF) == 0) {
02306         // We need to avoid calling GetMallocUsage() often because it
02307         // is O(elts on freelist). This is really bad since we start
02308         // to pummel the freelist once we hit the memory cap.
02309         unsigned mbs = sys::Process::GetTotalMemoryUsage() >> 20;
02310         
02311         if (mbs > MaxMemory) {
02312           if (mbs > MaxMemory + 100) {
02313             // just guess at how many to kill
02314             unsigned numStates = states.size();
02315             unsigned toKill = std::max(1U, numStates - numStates*MaxMemory/mbs);
02316 
02317             if (MaxMemoryInhibit)
02318               klee_warning("killing %d states (over memory cap)",
02319                            toKill);
02320 
02321             std::vector<ExecutionState*> arr(states.begin(), states.end());
02322             for (unsigned i=0,N=arr.size(); N && i<toKill; ++i,--N) {
02323               unsigned idx = rand() % N;
02324 
02325               // Make two pulls to try and not hit a state that
02326               // covered new code.
02327               if (arr[idx]->coveredNew)
02328                 idx = rand() % N;
02329 
02330               std::swap(arr[idx], arr[N-1]);
02331               terminateStateEarly(*arr[N-1], "memory limit");
02332             }
02333           }
02334           atMemoryLimit = true;
02335         } else {
02336           atMemoryLimit = false;
02337         }
02338       }
02339     }
02340 
02341     updateStates(&state);
02342   }
02343 
02344   delete searcher;
02345   searcher = 0;
02346   
02347  dump:
02348   if (DumpStatesOnHalt && !states.empty()) {
02349     llvm::cerr << "KLEE: halting execution, dumping remaining states\n";
02350     for (std::set<ExecutionState*>::iterator
02351            it = states.begin(), ie = states.end();
02352          it != ie; ++it) {
02353       ExecutionState &state = **it;
02354       stepInstruction(state); // keep stats rolling
02355       terminateStateEarly(state, "execution halting");
02356     }
02357     updateStates(0);
02358   }
02359 }
02360 
02361 std::string Executor::getAddressInfo(ExecutionState &state, 
02362                                      ref<Expr> address) const{
02363   std::ostringstream info;
02364   info << "\taddress: " << address << "\n";
02365   uint64_t example;
02366   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(address)) {
02367     example = CE->getConstantValue();
02368   } else {
02369     ref<ConstantExpr> value;
02370     bool success = solver->getValue(state, address, value);
02371     assert(success && "FIXME: Unhandled solver failure");
02372     (void) success;
02373     example = value->getConstantValue();
02374     info << "\texample: " << example << "\n";
02375     std::pair< ref<Expr>, ref<Expr> > res = solver->getRange(state, address);
02376     info << "\trange: [" << res.first << ", " << res.second <<"]\n";
02377   }
02378   
02379   MemoryObject hack((unsigned) example);    
02380   MemoryMap::iterator lower = state.addressSpace.objects.upper_bound(&hack);
02381   info << "\tnext: ";
02382   if (lower==state.addressSpace.objects.end()) {
02383     info << "none\n";
02384   } else {
02385     const MemoryObject *mo = lower->first;
02386     info << "object at " << mo->address
02387          << " of size " << mo->size << "\n";
02388   }
02389   if (lower!=state.addressSpace.objects.begin()) {
02390     --lower;
02391     info << "\tprev: ";
02392     if (lower==state.addressSpace.objects.end()) {
02393       info << "none\n";
02394     } else {
02395       const MemoryObject *mo = lower->first;
02396       info << "object at " << mo->address 
02397            << " of size " << mo->size << "\n";
02398     }
02399   }
02400 
02401   return info.str();
02402 }
02403 
02404 void Executor::terminateState(ExecutionState &state) {
02405   if (replayOut && replayPosition!=replayOut->numObjects) {
02406     klee_warning_once(replayOut, 
02407                       "replay did not consume all objects in test input.");
02408   }
02409 
02410   interpreterHandler->incPathsExplored();
02411 
02412   std::set<ExecutionState*>::iterator it = addedStates.find(&state);
02413   if (it==addedStates.end()) {
02414     state.pc = state.prevPC;
02415 
02416     removedStates.insert(&state);
02417   } else {
02418     // never reached searcher, just delete immediately
02419     std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it3 = 
02420       seedMap.find(&state);
02421     if (it3 != seedMap.end())
02422       seedMap.erase(it3);
02423     addedStates.erase(it);
02424     processTree->remove(state.ptreeNode);
02425     delete &state;
02426   }
02427 }
02428 
02429 void Executor::terminateStateEarly(ExecutionState &state, std::string message) {
02430   if (!OnlyOutputStatesCoveringNew || state.coveredNew ||
02431       (AlwaysOutputSeeds && seedMap.count(&state)))
02432     interpreterHandler->processTestCase(state, (message + "\n").c_str(), "early");
02433   terminateState(state);
02434 }
02435 
02436 void Executor::terminateStateOnExit(ExecutionState &state) {
02437   if (!OnlyOutputStatesCoveringNew || state.coveredNew || 
02438       (AlwaysOutputSeeds && seedMap.count(&state)))
02439     interpreterHandler->processTestCase(state, 0, 0);
02440   terminateState(state);
02441 }
02442 
02443 void Executor::terminateStateOnError(ExecutionState &state,
02444                                      const std::string &message,
02445                                      const std::string &suffix,
02446                                      const std::string &info) {
02447   static std::set< std::pair<Instruction*, std::string> > emittedErrors;
02448   const InstructionInfo &ii = *state.prevPC->info;
02449   
02450   if (EmitAllErrors ||
02451       emittedErrors.insert(std::make_pair(state.prevPC->inst,message)).second) {
02452     if (ii.file != "") {
02453       klee_message("ERROR: %s:%d: %s", ii.file.c_str(), ii.line, message.c_str());
02454     } else {
02455       klee_message("ERROR: %s", message.c_str());
02456     }
02457     if (!EmitAllErrors)
02458       klee_message("NOTE: now ignoring this error at this location");
02459     
02460     std::ostringstream msg;
02461     msg << "Error: " << message << "\n";
02462     if (ii.file != "") {
02463       msg << "File: " << ii.file << "\n";
02464       msg << "Line: " << ii.line << "\n";
02465     }
02466     msg << "Stack: \n";
02467     unsigned idx = 0;
02468     const KInstruction *target = state.prevPC;
02469     for (ExecutionState::stack_ty::reverse_iterator
02470            it = state.stack.rbegin(), ie = state.stack.rend();
02471          it != ie; ++it) {
02472       StackFrame &sf = *it;
02473       Function *f = sf.kf->function;
02474       const InstructionInfo &ii = *target->info;
02475       msg << "\t#" << idx++ 
02476           << " " << std::setw(8) << std::setfill('0') << ii.assemblyLine
02477           << " in " << f->getName() << " (";
02478       // Yawn, we could go up and print varargs if we wanted to.
02479       unsigned index = 0;
02480       for (Function::arg_iterator ai = f->arg_begin(), ae = f->arg_end();
02481            ai != ae; ++ai) {
02482         if (ai!=f->arg_begin()) msg << ", ";
02483 
02484         msg << ai->getName();
02485         // XXX should go through function
02486         ref<Expr> value = sf.locals[sf.kf->getArgRegister(index++)].value; 
02487         if (isa<ConstantExpr>(value))
02488           msg << "=" << value;
02489       }
02490       msg << ")";
02491       if (ii.file != "")
02492         msg << " at " << ii.file << ":" << ii.line;
02493       msg << "\n";
02494       target = sf.caller;
02495     }
02496 
02497     if (info != "")
02498       msg << "Info: \n" << info;
02499     interpreterHandler->processTestCase(state, msg.str().c_str(), suffix.c_str());
02500   }
02501     
02502   terminateState(state);
02503 }
02504 
02505 // XXX shoot me
02506 static const char *okExternalsList[] = { "printf", 
02507                                          "fprintf", 
02508                                          "puts",
02509                                          "getpid" };
02510 static std::set<std::string> okExternals(okExternalsList,
02511                                          okExternalsList + 
02512                                          (sizeof(okExternalsList)/sizeof(okExternalsList[0])));
02513 
02514 void Executor::callExternalFunction(ExecutionState &state,
02515                                     KInstruction *target,
02516                                     Function *function,
02517                                     std::vector< ref<Expr> > &arguments) {
02518   // check if specialFunctionHandler wants it
02519   if (specialFunctionHandler->handle(state, function, target, arguments))
02520     return;
02521   
02522   if (NoExternals && !okExternals.count(function->getName())) {
02523     llvm::cerr << "KLEE:ERROR: Calling not-OK external function : " << function->getName() << "\n";
02524     terminateStateOnError(state, "externals disallowed", "user.err");
02525     return;
02526   }
02527 
02528   // normal external function handling path
02529   uint64_t *args = (uint64_t*) alloca(sizeof(*args) * (arguments.size() + 1));
02530   memset(args, 0, sizeof(*args) * (arguments.size() + 1));
02531 
02532   unsigned i = 1;
02533   for (std::vector<ref<Expr> >::iterator ai = arguments.begin(), ae = arguments.end();
02534        ai!=ae; ++ai, ++i) {
02535     if (AllowExternalSymCalls) { // don't bother checking uniqueness
02536       ref<ConstantExpr> ce;
02537       bool success = solver->getValue(state, *ai, ce);
02538       assert(success && "FIXME: Unhandled solver failure");
02539       (void) success;
02540       static_cast<ConstantExpr*>(ce.get())->toMemory((void*) &args[i]);
02541     } else {
02542       ref<Expr> arg = toUnique(state, *ai);
02543       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(arg)) {
02544         // XXX kick toMemory functions from here
02545         CE->toMemory((void*) &args[i]);
02546       } else {
02547         std::string msg = "external call with symbolic argument: " + function->getName();
02548         terminateStateOnExecError(state, msg);
02549         return;
02550       }
02551     }
02552   }
02553 
02554   state.addressSpace.copyOutConcretes();
02555 
02556   if (!SuppressExternalWarnings) {
02557     std::ostringstream os;
02558     os << "calling external: " << function->getName().c_str() << "(";
02559     for (unsigned i=0; i<arguments.size(); i++) {
02560       os << arguments[i];
02561       if (i != arguments.size()-1)
02562         os << ", ";
02563     }
02564     os << ")";
02565     
02566     if (AllExternalWarnings)
02567       klee_warning("%s", os.str().c_str());
02568     else
02569       klee_warning_once(function, "%s", os.str().c_str());
02570   }
02571   
02572   bool success = externalDispatcher->executeCall(function, target->inst, args);
02573   if (!success) {
02574     terminateStateOnError(state, "failed external call: " + function->getName(), "external.err");
02575     return;
02576   }
02577 
02578   if (!state.addressSpace.copyInConcretes()) {
02579     terminateStateOnError(state, "external modified read-only object", "external.err");
02580     return;
02581   }
02582 
02583   const Type *resultType = target->inst->getType();
02584   if (resultType != Type::VoidTy) {
02585     ref<Expr> e = ConstantExpr::fromMemory((void*) args, 
02586                                            Expr::getWidthForLLVMType(resultType));
02587     bindLocal(target, state, e);
02588   }
02589 }
02590 
02591 /***/
02592 
02593 ref<Expr> Executor::replaceReadWithSymbolic(ExecutionState &state, 
02594                                             ref<Expr> e) {
02595   unsigned n = interpreterOpts.MakeConcreteSymbolic;
02596   if (!n || replayOut || replayPath)
02597     return e;
02598 
02599   // right now, we don't replace symbolics (is there any reason too?)
02600   if (!isa<ConstantExpr>(e))
02601     return e;
02602 
02603   if (n != 1 && random() %  n)
02604     return e;
02605 
02606   // create a new fresh location, assert it is equal to concrete value in e
02607   // and return it.
02608   
02609   const MemoryObject *mo =
02610     memory->allocate(Expr::getMinBytesForWidth(e->getWidth()), false, false,
02611                      state.prevPC->inst);
02612   assert(mo && "out of memory");
02613   ref<Expr> res = Expr::createTempRead(mo->array, e->getWidth());
02614   ref<Expr> eq = NotOptimizedExpr::create(EqExpr::create(e, res));
02615   llvm::cerr << "Making symbolic: " << eq << "\n";
02616   state.addConstraint(eq);
02617   return res;
02618 }
02619 
02620 ObjectState *Executor::bindObjectInState(ExecutionState &state, const MemoryObject *mo,
02621                                          bool isLocal) {
02622   ObjectState *os = new ObjectState(mo, mo->size);
02623   state.addressSpace.bindObject(mo, os);
02624 
02625   // Its possible that multiple bindings of the same mo in the state
02626   // will put multiple copies on this list, but it doesn't really
02627   // matter because all we use this list for is to unbind the object
02628   // on function return.
02629   if (isLocal)
02630     state.stack.back().allocas.push_back(mo);
02631 
02632   return os;
02633 }
02634 
02635 void Executor::executeAlloc(ExecutionState &state,
02636                             ref<Expr> size,
02637                             bool isLocal,
02638                             KInstruction *target,
02639                             bool zeroMemory,
02640                             const ObjectState *reallocFrom) {
02641   size = toUnique(state, size);
02642   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(size)) {
02643     MemoryObject *mo = 
02644       memory->allocate(CE->getConstantValue(), isLocal, false, 
02645                        state.prevPC->inst);
02646     if (!mo) {
02647       bindLocal(target, state, ConstantExpr::alloc(0, kMachinePointerType));
02648     } else {
02649       ObjectState *os = bindObjectInState(state, mo, isLocal);
02650       if (zeroMemory) {
02651         os->initializeToZero();
02652       } else {
02653         os->initializeToRandom();
02654       }
02655       bindLocal(target, state, mo->getBaseExpr());
02656       
02657       if (reallocFrom) {
02658         unsigned count = std::min(reallocFrom->size, os->size);
02659         for (unsigned i=0; i<count; i++)
02660           os->write(i, reallocFrom->read8(i));
02661         state.addressSpace.unbindObject(reallocFrom->getObject());
02662       }
02663     }
02664   } else {
02665     // XXX For now we just pick a size. Ideally we would support
02666     // symbolic sizes fully but even if we don't it would be better to
02667     // "smartly" pick a value, for example we could fork and pick the
02668     // min and max values and perhaps some intermediate (reasonable
02669     // value).
02670     // 
02671     // It would also be nice to recognize the case when size has
02672     // exactly two values and just fork (but we need to get rid of
02673     // return argument first). This shows up in pcre when llvm
02674     // collapses the size expression with a select.
02675 
02676     ref<ConstantExpr> example;
02677     bool success = solver->getValue(state, size, example);
02678     assert(success && "FIXME: Unhandled solver failure");
02679     (void) success;
02680     
02681     // Try and start with a small example
02682     while (example->getConstantValue() > 128) {
02683       ref<ConstantExpr> tmp = 
02684         ConstantExpr::alloc(example->getConstantValue() >> 1, 
02685                             example->getWidth());
02686       bool res;
02687       bool success = solver->mayBeTrue(state, EqExpr::create(tmp, size), res);
02688       assert(success && "FIXME: Unhandled solver failure");      
02689       (void) success;
02690       if (!res)
02691         break;
02692       example = tmp;
02693     }
02694 
02695     StatePair fixedSize = fork(state, EqExpr::create(example, size), true);
02696     
02697     if (fixedSize.second) { 
02698       // Check for exactly two values
02699       ref<ConstantExpr> tmp;
02700       bool success = solver->getValue(*fixedSize.second, size, tmp);
02701       assert(success && "FIXME: Unhandled solver failure");      
02702       (void) success;
02703       bool res;
02704       success = solver->mustBeTrue(*fixedSize.second, 
02705                                    EqExpr::create(tmp, size),
02706                                    res);
02707       assert(success && "FIXME: Unhandled solver failure");      
02708       (void) success;
02709       if (res) {
02710         executeAlloc(*fixedSize.second, tmp, isLocal,
02711                      target, zeroMemory, reallocFrom);
02712       } else {
02713         // See if a *really* big value is possible. If so assume
02714         // malloc will fail for it, so lets fork and return 0.
02715         StatePair hugeSize = 
02716           fork(*fixedSize.second, 
02717                UltExpr::create(ConstantExpr::alloc(1<<31, Expr::Int32),
02718                                size), 
02719                true);
02720         if (hugeSize.first) {
02721           klee_message("NOTE: found huge malloc, returing 0");
02722           bindLocal(target, *hugeSize.first, 
02723                     ConstantExpr::alloc(0, kMachinePointerType));
02724         }
02725         
02726         if (hugeSize.second) {
02727           std::ostringstream info;
02728           ExprPPrinter::printOne(info, "  size expr", size);
02729           info << "  concretization : " << example << "\n";
02730           info << "  unbound example: " << tmp << "\n";
02731           terminateStateOnError(*hugeSize.second, 
02732                                 "concretized symbolic size", 
02733                                 "model.err", 
02734                                 info.str());
02735         }
02736       }
02737     }
02738 
02739     if (fixedSize.first) // can be zero when fork fails
02740       executeAlloc(*fixedSize.first, example, isLocal, 
02741                    target, zeroMemory, reallocFrom);
02742   }
02743 }
02744 
02745 void Executor::executeFree(ExecutionState &state,
02746                            ref<Expr> address,
02747                            KInstruction *target) {
02748   StatePair zeroPointer = fork(state, Expr::createIsZero(address), true);
02749   if (zeroPointer.first) {
02750     if (target)
02751       bindLocal(target, *zeroPointer.first, Expr::createPointer(0));
02752   }
02753   if (zeroPointer.second) { // address != 0
02754     ExactResolutionList rl;
02755     resolveExact(*zeroPointer.second, address, rl, "free");
02756     
02757     for (Executor::ExactResolutionList::iterator it = rl.begin(), 
02758            ie = rl.end(); it != ie; ++it) {
02759       const MemoryObject *mo = it->first.first;
02760       if (mo->isLocal) {
02761         terminateStateOnError(*it->second, 
02762                               "free of alloca", 
02763                               "free.err",
02764                               getAddressInfo(*it->second, address));
02765       } else if (mo->isGlobal) {
02766         terminateStateOnError(*it->second, 
02767                               "free of global", 
02768                               "free.err",
02769                               getAddressInfo(*it->second, address));
02770       } else {
02771         it->second->addressSpace.unbindObject(mo);
02772         if (target)
02773           bindLocal(target, *it->second, Expr::createPointer(0));
02774       }
02775     }
02776   }
02777 }
02778 
02779 void Executor::resolveExact(ExecutionState &state,
02780                             ref<Expr> p,
02781                             ExactResolutionList &results, 
02782                             const std::string &name) {
02783   // XXX we may want to be capping this?
02784   ResolutionList rl;
02785   state.addressSpace.resolve(state, solver, p, rl);
02786   
02787   ExecutionState *unbound = &state;
02788   for (ResolutionList::iterator it = rl.begin(), ie = rl.end(); 
02789        it != ie; ++it) {
02790     ref<Expr> inBounds = EqExpr::create(p, it->first->getBaseExpr());
02791     
02792     StatePair branches = fork(*unbound, inBounds, true);
02793     
02794     if (branches.first)
02795       results.push_back(std::make_pair(*it, branches.first));
02796 
02797     unbound = branches.second;
02798     if (!unbound) // Fork failure
02799       break;
02800   }
02801 
02802   if (unbound) {
02803     terminateStateOnError(*unbound,
02804                           "memory error: invalid pointer: " + name,
02805                           "ptr.err",
02806                           getAddressInfo(*unbound, p));
02807   }
02808 }
02809 
02810 void Executor::executeMemoryOperation(ExecutionState &state,
02811                                       bool isWrite,
02812                                       ref<Expr> address,
02813                                       ref<Expr> value /* undef if read */,
02814                                       KInstruction *target /* undef if write */) {
02815   Expr::Width type = (isWrite ? value->getWidth() : 
02816                      Expr::getWidthForLLVMType(target->inst->getType()));
02817   unsigned bytes = Expr::getMinBytesForWidth(type);
02818 
02819   if (SimplifySymIndices) {
02820     if (!isa<ConstantExpr>(address))
02821       address = state.constraints.simplifyExpr(address);
02822     if (isWrite && !isa<ConstantExpr>(value))
02823       value = state.constraints.simplifyExpr(value);
02824   }
02825 
02826   // fast path: single in-bounds resolution
02827   ObjectPair op;
02828   bool success;
02829   solver->setTimeout(stpTimeout);
02830   if (!state.addressSpace.resolveOne(state, solver, address, op, success)) {
02831     address = toConstant(state, address, "resolveOne failure");
02832     success = state.addressSpace.resolveOne(cast<ConstantExpr>(address)->getConstantValue(), op);
02833   }
02834   solver->setTimeout(0);
02835 
02836   if (success) {
02837     const MemoryObject *mo = op.first;
02838 
02839     if (MaxSymArraySize && mo->size>=MaxSymArraySize) {
02840       address = toConstant(state, address, "max-sym-array-size");
02841     }
02842     
02843     ref<Expr> offset = mo->getOffsetExpr(address);
02844 
02845     bool inBounds;
02846     solver->setTimeout(stpTimeout);
02847     bool success = solver->mustBeTrue(state, 
02848                                       mo->getBoundsCheckOffset(offset, bytes),
02849                                       inBounds);
02850     solver->setTimeout(0);
02851     if (!success) {
02852       state.pc = state.prevPC;
02853       terminateStateEarly(state, "query timed out");
02854       return;
02855     }
02856 
02857     if (inBounds) {
02858       const ObjectState *os = op.second;
02859       if (isWrite) {
02860         if (os->readOnly) {
02861           terminateStateOnError(state,
02862                                 "memory error: object read only",
02863                                 "readonly.err");
02864         } else {
02865           ObjectState *wos = state.addressSpace.getWriteable(mo, os);
02866           wos->write(offset, value);
02867         }          
02868       } else {
02869         ref<Expr> result = os->read(offset, type);
02870         
02871         if (interpreterOpts.MakeConcreteSymbolic)
02872           result = replaceReadWithSymbolic(state, result);
02873         
02874         bindLocal(target, state, result);
02875       }
02876 
02877       return;
02878     }
02879   } 
02880 
02881   // we are on an error path (no resolution, multiple resolution, one
02882   // resolution with out of bounds)
02883   
02884   ResolutionList rl;  
02885   solver->setTimeout(stpTimeout);
02886   bool incomplete = state.addressSpace.resolve(state, solver, address, rl,
02887                                                0, stpTimeout);
02888   solver->setTimeout(0);
02889   
02890   // XXX there is some query wasteage here. who cares?
02891   ExecutionState *unbound = &state;
02892   
02893   for (ResolutionList::iterator i = rl.begin(), ie = rl.end(); i != ie; ++i) {
02894     const MemoryObject *mo = i->first;
02895     const ObjectState *os = i->second;
02896     ref<Expr> inBounds = mo->getBoundsCheckPointer(address, bytes);
02897     
02898     StatePair branches = fork(*unbound, inBounds, true);
02899     ExecutionState *bound = branches.first;
02900 
02901     // bound can be 0 on failure or overlapped 
02902     if (bound) {
02903       if (isWrite) {
02904         if (os->readOnly) {
02905           terminateStateOnError(*bound,
02906                                 "memory error: object read only",
02907                                 "readonly.err");
02908         } else {
02909           ObjectState *wos = bound->addressSpace.getWriteable(mo, os);
02910           wos->write(mo->getOffsetExpr(address), value);
02911         }
02912       } else {
02913         ref<Expr> result = os->read(mo->getOffsetExpr(address), type);
02914         bindLocal(target, *bound, result);
02915       }
02916     }
02917 
02918     unbound = branches.second;
02919     if (!unbound)
02920       break;
02921   }
02922   
02923   // XXX should we distinguish out of bounds and overlapped cases?
02924   if (unbound) {
02925     if (incomplete) {
02926       terminateStateEarly(*unbound, "query timed out (resolve)");
02927     } else {
02928       terminateStateOnError(*unbound,
02929                             "memory error: out of bound pointer",
02930                             "ptr.err",
02931                             getAddressInfo(*unbound, address));
02932     }
02933   }
02934 }
02935 
02936 void Executor::executeMakeSymbolic(ExecutionState &state, 
02937                                    const MemoryObject *mo) {
02938   // make a new one and rebind, we use bind here because we want to
02939   // create a flat out new state, not a copy. although I'm not really
02940   // sure it matters.
02941   ObjectState *os = bindObjectInState(state, mo, false);
02942   if (!replayOut) {
02943     os->makeSymbolic();
02944     state.addSymbolic(mo);
02945     
02946     std::map< ExecutionState*, std::vector<SeedInfo> >::iterator it = 
02947       seedMap.find(&state);
02948     if (it!=seedMap.end()) { // In seed mode we need to add this as a
02949                              // binding.
02950       for (std::vector<SeedInfo>::iterator siit = it->second.begin(), 
02951              siie = it->second.end(); siit != siie; ++siit) {
02952         SeedInfo &si = *siit;
02953         KTestObject *obj = si.getNextInput(mo,
02954                                           NamedSeedMatching);
02955 
02956         if (!obj) {
02957           if (ZeroSeedExtension) {
02958             std::vector<unsigned char> &values = 
02959               si.assignment.bindings[mo->array];
02960             values = std::vector<unsigned char>(mo->size, '\0');
02961           } else if (!AllowSeedExtension) {
02962             terminateStateOnError(state, 
02963                                   "ran out of inputs during seeding",
02964                                   "user.err");
02965             break;
02966           }
02967         } else {
02968           if (obj->numBytes != mo->size &&
02969               ((!(AllowSeedExtension || ZeroSeedExtension)
02970                 && obj->numBytes < mo->size) ||
02971                (!AllowSeedTruncation && obj->numBytes > mo->size))) {
02972             std::stringstream msg;
02973             msg << "replace size mismatch: "
02974                 << mo->name << "[" << mo->size << "]"
02975                 << " vs " << obj->name << "[" << obj->numBytes << "]"
02976                 << " in test\n";
02977 
02978             terminateStateOnError(state,
02979                                   msg.str(),
02980                                   "user.err");
02981             break;
02982           } else {
02983             std::vector<unsigned char> &values = 
02984               si.assignment.bindings[mo->array];
02985             values.insert(values.begin(), obj->bytes, 
02986                           obj->bytes + std::min(obj->numBytes, mo->size));            
02987             if (ZeroSeedExtension) {
02988               for (unsigned i=obj->numBytes; i<mo->size; ++i)
02989                 values.push_back('\0');
02990             }
02991           }
02992         }
02993       }
02994     }
02995   } else {
02996     if (replayPosition >= replayOut->numObjects) {
02997       terminateStateOnError(state, "replay count mismatch", "user.err");
02998     } else {
02999       KTestObject *obj = &replayOut->objects[replayPosition++];
03000       if (obj->numBytes != mo->size) {
03001         terminateStateOnError(state, "replay size mismatch", "user.err");
03002       } else {
03003         for (unsigned i=0; i<mo->size; i++)
03004           os->write8(i, obj->bytes[i]);
03005       }
03006     }
03007   }
03008 }
03009 
03010 /***/
03011 
03012 void Executor::runFunctionAsMain(Function *f,
03013                                  int argc,
03014                                  char **argv,
03015                                  char **envp) {
03016   std::vector<ref<Expr> > arguments;
03017 
03018   // force deterministic initialization of memory objects
03019   srand(1);
03020   srandom(1);
03021   
03022   MemoryObject *argvMO = 0;
03023 
03024   // In order to make uclibc happy and be closer to what the system is
03025   // doing we lay out the environments at the end of the argv array
03026   // (both are terminated by a null). There is also a final terminating
03027   // null that uclibc seems to expect, possibly the ELF header?
03028 
03029   int envc;
03030   for (envc=0; envp[envc]; ++envc) ;
03031 
03032   KFunction *kf = kmodule->functionMap[f];
03033   assert(kf);
03034   Function::arg_iterator ai = f->arg_begin(), ae = f->arg_end();
03035   if (ai!=ae) {
03036     arguments.push_back(ConstantExpr::alloc(argc, Expr::Int32));
03037 
03038     if (++ai!=ae) {
03039       argvMO = memory->allocate((argc+1+envc+1+1) * kMachinePointerSize, false, true,
03040                                 f->begin()->begin());
03041       
03042       arguments.push_back(argvMO->getBaseExpr());
03043 
03044       if (++ai!=ae) {
03045         uint64_t envp_start = argvMO->address + (argc+1)*kMachinePointerSize;
03046         arguments.push_back(Expr::createPointer(envp_start));
03047 
03048         if (++ai!=ae)
03049           klee_error("invalid main function (expect 0-3 arguments)");
03050       }
03051     }
03052   }
03053 
03054   ExecutionState *state = new ExecutionState(kmodule->functionMap[f]);
03055   
03056   if (pathWriter) 
03057     state->pathOS = pathWriter->open();
03058   if (symPathWriter) 
03059     state->symPathOS = symPathWriter->open();
03060 
03061 
03062   if (statsTracker)
03063     statsTracker->framePushed(*state, 0);
03064 
03065   assert(arguments.size() == f->arg_size() && "wrong number of arguments");
03066   for (unsigned i = 0, e = f->arg_size(); i != e; ++i)
03067     bindArgument(kf, i, *state, arguments[i]);
03068 
03069   if (argvMO) {
03070     ObjectState *argvOS = bindObjectInState(*state, argvMO, false);
03071 
03072     for (int i=0; i<argc+1+envc+1+1; i++) {
03073       MemoryObject *arg;
03074       
03075       if (i==argc || i>=argc+1+envc) {
03076         arg = 0;
03077       } else {
03078         char *s = i<argc ? argv[i] : envp[i-(argc+1)];
03079         int j, len = strlen(s);
03080         
03081         arg = memory->allocate(len+1, false, true, state->pc->inst);
03082         ObjectState *os = bindObjectInState(*state, arg, false);
03083         for (j=0; j<len+1; j++)
03084           os->write8(j, s[j]);
03085       }
03086 
03087       if (arg) {
03088         argvOS->write(i * kMachinePointerSize, arg->getBaseExpr());
03089       } else {
03090         argvOS->write(i * kMachinePointerSize, Expr::createPointer(0));
03091       }
03092     }
03093   }
03094   
03095   initializeGlobals(*state);
03096 
03097   processTree = new PTree(state);
03098   state->ptreeNode = processTree->root;
03099   run(*state);
03100   delete processTree;
03101   processTree = 0;
03102 
03103   // hack to clear memory objects
03104   delete memory;
03105   memory = new MemoryManager();
03106   
03107   globalObjects.clear();
03108   globalAddresses.clear();
03109 
03110   if (statsTracker)
03111     statsTracker->done();
03112 
03113   if (theMMap) {
03114     munmap(theMMap, theMMapSize);
03115     theMMap = 0;
03116   }
03117 }
03118 
03119 unsigned Executor::getPathStreamID(const ExecutionState &state) {
03120   assert(pathWriter);
03121   return state.pathOS.getID();
03122 }
03123 
03124 unsigned Executor::getSymbolicPathStreamID(const ExecutionState &state) {
03125   assert(symPathWriter);
03126   return state.symPathOS.getID();
03127 }
03128 
03129 void Executor::getConstraintLog(const ExecutionState &state,
03130                                 std::string &res,
03131                                 bool asCVC) {
03132   if (asCVC) {
03133     Query query(state.constraints, ConstantExpr::alloc(0, Expr::Bool));
03134     char *log = solver->stpSolver->getConstraintLog(query);
03135     res = std::string(log);
03136     free(log);
03137   } else {
03138     std::ostringstream info;
03139     ExprPPrinter::printConstraints(info, state.constraints);
03140     res = info.str();    
03141   }
03142 }
03143 
03144 bool Executor::getSymbolicSolution(const ExecutionState &state,
03145                                    std::vector< 
03146                                    std::pair<std::string,
03147                                    std::vector<unsigned char> > >
03148                                    &res) {
03149   solver->setTimeout(stpTimeout);
03150 
03151   ExecutionState tmp(state);
03152   if (!NoPreferCex) {
03153     for (std::vector<const MemoryObject*>::const_iterator 
03154            it = state.symbolics.begin(), ie = state.symbolics.end(); 
03155          it != ie; ++it) {
03156       const MemoryObject *mo = *it;
03157       std::vector< ref<Expr> >::const_iterator pi = 
03158         mo->cexPreferences.begin(), pie = mo->cexPreferences.end();
03159       for (; pi != pie; ++pi) {
03160         bool mustBeTrue;
03161         bool success = solver->mustBeTrue(tmp, Expr::createNot(*pi), 
03162                                           mustBeTrue);
03163         if (!success) break;
03164         if (!mustBeTrue) tmp.addConstraint(*pi);
03165       }
03166       if (pi!=pie) break;
03167     }
03168   }
03169 
03170   std::vector< std::vector<unsigned char> > values;
03171   std::vector<const Array*> objects;
03172   for (unsigned i = 0; i != state.symbolics.size(); ++i)
03173     objects.push_back(state.symbolics[i]->array);
03174   bool success = solver->getInitialValues(tmp, objects, values);
03175   solver->setTimeout(0);
03176   if (!success) {
03177     klee_warning("unable to compute initial values (invalid constraints?)!");
03178     ExprPPrinter::printQuery(std::cerr,
03179                              state.constraints, 
03180                              ConstantExpr::alloc(0, Expr::Bool));
03181     return false;
03182   }
03183   
03184   unsigned i = 0;
03185   for (std::vector<const MemoryObject*>::const_iterator 
03186          it = state.symbolics.begin(), ie = state.symbolics.end(); 
03187        it != ie; ++it) {
03188     res.push_back(std::make_pair((*it)->name, values[i]));
03189     ++i;
03190   }
03191   return true;
03192 }
03193 
03194 void Executor::getCoveredLines(const ExecutionState &state,
03195                                std::map<const std::string*, std::set<unsigned> > &res) {
03196   res = state.coveredLines;
03197 }
03198 
03199 void Executor::doImpliedValueConcretization(ExecutionState &state,
03200                                             ref<Expr> e,
03201                                             ref<ConstantExpr> value) {
03202   if (DebugCheckForImpliedValues)
03203     ImpliedValue::checkForImpliedValues(solver->solver, e, value);
03204 
03205   ImpliedValueList results;
03206   ImpliedValue::getImpliedValues(e, value, results);
03207   for (ImpliedValueList::iterator it = results.begin(), ie = results.end();
03208        it != ie; ++it) {
03209     ReadExpr *re = it->first.get();
03210     
03211     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(re->index)) {
03212       // FIXME: This is the sole remaining usage of the Array object
03213       // variable. Kill me.
03214       const MemoryObject *mo = re->updates.root->object;
03215       const ObjectState *os = state.addressSpace.findObject(mo);
03216 
03217       if (!os) {
03218         // object has been free'd, no need to concretize (although as
03219         // in other cases we would like to concretize the outstanding
03220         // reads, but we have no facility for that yet)
03221       } else {
03222         assert(!os->readOnly && 
03223                "not possible? read only object with static read?");
03224         ObjectState *wos = state.addressSpace.getWriteable(mo, os);
03225         wos->write(CE->getConstantValue(), it->second);
03226       }
03227     }
03228   }
03229 }
03230 
03232 
03233 Interpreter *Interpreter::create(const InterpreterOptions &opts,
03234                                  InterpreterHandler *ih) {
03235   return new Executor(opts, ih);
03236 }

Generated on Fri Jun 5 03:31:31 2009 for klee by  doxygen 1.5.8