repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ftsrg/gazer
include/gazer/ADT/ScopedCache.h
<reponame>ftsrg/gazer //==- ScopedCache.h ---------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_ADT_SCOPEDCACHE_H #define GAZER_ADT_SCOPEDCACHE_H #include <llvm/ADT/DenseMap.h> #include <vector> namespace gazer { /// An associative cache which stores its elements in scopes. /// /// By default, the cache is constructed with one single scope, /// called the root. If no other scopes are present in the internal stack, /// all insertions will take place in the root scope. /// The root scope cannot be pop'd out of the container, therefore clients /// can always assume that there is a scope available for insertion. template< class KeyT, class ValueT, class MapT = llvm::DenseMap<KeyT, ValueT>, class StorageT = std::vector<MapT> > class ScopedCache { public: using iterator = typename MapT::iterator; using scope_iterator = typename StorageT::iterator; public: ScopedCache() { // Create the root scope. mStorage.emplace_back(); } /// Inserts a new element with a given key into the current scope. void insert(const KeyT& key, ValueT value) { mStorage.back()[key] = value; } /// Returns an optional with the value corresponding to the given key. /// If a given key was not found in the current scope, this method will /// traverse all parent scopes. If the requested element was not found /// in any of the scopes, returns an empty optional. std::optional<ValueT> get(const KeyT& key) const { for (auto it = mStorage.rbegin(), ie = mStorage.rend(); it != ie; ++it) { auto result = it->find(key); if (result != it->end()) { return std::make_optional(result->second); } } return std::nullopt; } void clear() { mStorage.resize(1); mStorage.begin()->clear(); } void push() { mStorage.emplace_back(); } void pop() { assert(mStorage.size() > 1 && "Attempting to pop the root scope of a ScopedCache."); mStorage.pop_back(); } iterator current_begin() { return mStorage.back().begin(); } iterator current_end() { return mStorage.back().end(); } scope_iterator scope_begin() { return mStorage.begin(); } scope_iterator scope_end() { return mStorage.end(); } llvm::iterator_range<scope_iterator> scopes() { return llvm::make_range(scope_begin(), scope_end()); } private: StorageT mStorage; }; } #endif
ftsrg/gazer
test/verif/regression/unsigned_false_cex.c
// RUN: %bmc -no-optimize -math-int -trace -test-harness %t1.ll "%s" // RUN: %check-cex "%s" "%t1.ll" "%errors" | FileCheck "%s" // RUN: %bmc -math-int -trace -test-harness %t3.ll "%s" // RUN: %check-cex "%s" "%t3.ll" "%errors" | FileCheck "%s" // CHECK: __VERIFIER_error executed // Due to an erroneous encoding of unsigned comparisons, we have produced some // false-positive counterexamples in -math-int mode. This test should evaluate // as a failure and the resulting counterexample is verified through lli. int a; int d = 5; void __VERIFIER_error(); int b(); int a17 = 1; int c = 5; int e() { if (d && ((c == 1))) ; else if (((!a && (((!a17) || (c && 0)))))) d = 14; else if ((c) && d) a17 = 0; if (1 && d == 14) __VERIFIER_error(); return 2; } int main() { while (1) { int f = b(); if (f != 5 && f != 6) return 2; e(); } }
ftsrg/gazer
include/gazer/Core/Expr/ExprWalker.h
//==- ExprWalker.h - Expression visitor interface ---------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPR_EXPRWALKER_H #define GAZER_CORE_EXPR_EXPRWALKER_H #include "gazer/Core/Expr.h" #include "gazer/Core/ExprTypes.h" #include "gazer/Core/LiteralExpr.h" #include "gazer/Support/GrowingStackAllocator.h" #include <llvm/ADT/SmallVector.h> namespace gazer { /// Generic walker interface for expressions. /// /// This class avoids recursion by using an explicit stack on the heap instead /// of the normal call stack. This allows us to avoid stack overflow errors in /// the case of large input expressions. The order of the traversal is fixed /// to be post-order, thus all (translated/visited) operands of an expression /// are available in the visit() method. They may be retrieved by calling the /// getOperand(size_t) method. /// /// In order to support caching, users may override the shouldSkip() and /// handleResult() functions. The former should return true if the cache /// was hit and set the found value. The latter should be used to insert /// new entries into the cache. /// /// \tparam DerivedT A Curiously Recurring Template Pattern (CRTP) parameter of /// the derived class. /// \tparam ReturnT The visit result. Must be a default-constructible and /// copy-constructible. /// \tparam SlabSize Slab size of the underlying stack allocator. template<class DerivedT, class ReturnT, size_t SlabSize = 4096> class ExprWalker { static_assert(std::is_default_constructible_v<ReturnT>, "ExprWalker return type must be default-constructible!"); size_t tmp = 0; struct Frame { ExprPtr mExpr; size_t mIndex; Frame* mParent = nullptr; size_t mState = 0; llvm::SmallVector<ReturnT, 2> mVisitedOps; Frame(ExprPtr expr, size_t index, Frame* parent) : mExpr(std::move(expr)), mIndex(index), mParent(parent), mVisitedOps( mExpr->isNullary() ? 0 : llvm::cast<NonNullaryExpr>(mExpr)->getNumOperands() ) {} bool isFinished() const { return mExpr->isNullary() || llvm::cast<NonNullaryExpr>(mExpr)->getNumOperands() == mState; } }; private: Frame* createFrame(const ExprPtr& expr, size_t idx, Frame* parent) { size_t siz = sizeof(Frame); void* ptr = mAllocator.Allocate(siz, alignof(Frame)); return new (ptr) Frame(expr, idx, parent); } void destroyFrame(Frame* frame) { frame->~Frame(); mAllocator.Deallocate(frame, sizeof(Frame)); } private: Frame* mTop; GrowingStackAllocator<llvm::MallocAllocator, SlabSize> mAllocator; public: ExprWalker() : mTop(nullptr) { mAllocator.Init(); } ExprWalker(const ExprWalker&) = delete; ExprWalker& operator=(ExprWalker&) = delete; ~ExprWalker() = default; public: ReturnT walk(const ExprPtr& expr) { static_assert( std::is_base_of_v<ExprWalker, DerivedT>, "The derived type must be passed to the ExprWalker!" ); assert(mTop == nullptr); mTop = createFrame(expr, 0, nullptr); while (mTop != nullptr) { Frame* current = mTop; ReturnT ret; bool shouldSkip = static_cast<DerivedT*>(this)->shouldSkip(current->mExpr, &ret); if (current->isFinished() || shouldSkip) { if (!shouldSkip) { ret = this->doVisit(current->mExpr); static_cast<DerivedT*>(this)->handleResult(current->mExpr, ret); } Frame* parent = current->mParent; size_t idx = current->mIndex; this->destroyFrame(current); if (LLVM_LIKELY(parent != nullptr)) { parent->mVisitedOps[idx] = std::move(ret); mTop = parent; continue; } mTop = nullptr; return ret; } auto nn = llvm::cast<NonNullaryExpr>(current->mExpr); size_t i = current->mState; auto frame = createFrame(nn->getOperand(i), i, current); mTop = frame; current->mState++; } llvm_unreachable("Invalid walker state!"); } protected: /// Returns the operand of index \p i in the topmost frame. [[nodiscard]] ReturnT getOperand(size_t i) const { assert(mTop != nullptr); assert(i < mTop->mVisitedOps.size()); return mTop->mVisitedOps[i]; } public: /// If this function returns true, the walker will not visit \p expr /// and will use the value contained in \p ret. bool shouldSkip(const ExprPtr& expr, ReturnT* ret) { return false; } /// This function is called by the walker if an actual visit took place /// for \p expr. The visit result is contained in \p ret. void handleResult(const ExprPtr& expr, ReturnT& ret) {} ReturnT doVisit(const ExprPtr& expr) { #define GAZER_EXPR_KIND(KIND) \ case Expr::KIND: \ return static_cast<DerivedT*>(this)->visit##KIND( \ llvm::cast<KIND##Expr>(expr) \ ); \ switch (expr->getKind()) { #include "gazer/Core/Expr/ExprKind.def" } llvm_unreachable("Unknown expression kind!"); #undef GAZER_EXPR_KIND } void visitExpr(const ExprPtr& expr) {} ReturnT visitNonNullary(const ExprRef<NonNullaryExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } // Nullary ReturnT visitUndef(const ExprRef<UndefExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitLiteral(const ExprRef<LiteralExpr>& expr) { // Disambiguate here for each literal type #define EXPR_LITERAL_CASE(TYPE) \ case Type::TYPE##TypeID: \ return static_cast<DerivedT*>(this) \ ->visit##TYPE##Literal(expr_cast<TYPE##LiteralExpr>(expr)); \ switch (expr->getType().getTypeID()) { EXPR_LITERAL_CASE(Bool) EXPR_LITERAL_CASE(Int) EXPR_LITERAL_CASE(Real) EXPR_LITERAL_CASE(Bv) EXPR_LITERAL_CASE(Float) EXPR_LITERAL_CASE(Array) case Type::TupleTypeID: case Type::FunctionTypeID: llvm_unreachable("Invalid literal expression type!"); break; } #undef EXPR_LITERAL_CASE llvm_unreachable("Unknown literal expression kind!"); } ReturnT visitVarRef(const ExprRef<VarRefExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } // Literals ReturnT visitBoolLiteral(const ExprRef<BoolLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitIntLiteral(const ExprRef<IntLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitRealLiteral(const ExprRef<RealLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitBvLiteral(const ExprRef<BvLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitFloatLiteral(const ExprRef<FloatLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } ReturnT visitArrayLiteral(const ExprRef<ArrayLiteralExpr>& expr) { return static_cast<DerivedT*>(this)->visitExpr(expr); } // Unary ReturnT visitNot(const ExprRef<NotExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitZExt(const ExprRef<ZExtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitSExt(const ExprRef<SExtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitExtract(const ExprRef<ExtractExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Binary ReturnT visitAdd(const ExprRef<AddExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitSub(const ExprRef<SubExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitMul(const ExprRef<MulExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitDiv(const ExprRef<DivExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitMod(const ExprRef<ModExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitRem(const ExprRef<RemExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSDiv(const ExprRef<BvSDivExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvUDiv(const ExprRef<BvUDivExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSRem(const ExprRef<BvSRemExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvURem(const ExprRef<BvURemExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitShl(const ExprRef<ShlExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitLShr(const ExprRef<LShrExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitAShr(const ExprRef<AShrExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvAnd(const ExprRef<BvAndExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvOr(const ExprRef<BvOrExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvXor(const ExprRef<BvXorExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvConcat(const ExprRef<BvConcatExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Logic ReturnT visitAnd(const ExprRef<AndExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitOr(const ExprRef<OrExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitImply(const ExprRef<ImplyExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Compare ReturnT visitEq(const ExprRef<EqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitNotEq(const ExprRef<NotEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitLt(const ExprRef<LtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitLtEq(const ExprRef<LtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitGt(const ExprRef<GtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitGtEq(const ExprRef<GtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSLt(const ExprRef<BvSLtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSLtEq(const ExprRef<BvSLtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSGt(const ExprRef<BvSGtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvSGtEq(const ExprRef<BvSGtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvULt(const ExprRef<BvULtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvULtEq(const ExprRef<BvULtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvUGt(const ExprRef<BvUGtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvUGtEq(const ExprRef<BvUGtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Floating-point queries ReturnT visitFIsNan(const ExprRef<FIsNanExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFIsInf(const ExprRef<FIsInfExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Floating-point casts ReturnT visitFCast(const ExprRef<FCastExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitSignedToFp(const ExprRef<SignedToFpExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitUnsignedToFp(const ExprRef<UnsignedToFpExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFpToSigned(const ExprRef<FpToSignedExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFpToUnsigned(const ExprRef<FpToUnsignedExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFpToBv(const ExprRef<FpToBvExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitBvToFp(const ExprRef<BvToFpExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Floating-point arithmetic ReturnT visitFAdd(const ExprRef<FAddExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFSub(const ExprRef<FSubExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFMul(const ExprRef<FMulExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFDiv(const ExprRef<FDivExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Floating-point compare ReturnT visitFEq(const ExprRef<FEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFGt(const ExprRef<FGtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFGtEq(const ExprRef<FGtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFLt(const ExprRef<FLtExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitFLtEq(const ExprRef<FLtEqExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Ternary ReturnT visitSelect(const ExprRef<SelectExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } // Arrays ReturnT visitArrayRead(const ExprRef<ArrayReadExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitArrayWrite(const ExprRef<ArrayWriteExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitTupleSelect(const ExprRef<TupleSelectExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } ReturnT visitTupleConstruct(const ExprRef<TupleConstructExpr>& expr) { return static_cast<DerivedT*>(this)->visitNonNullary(expr); } }; } // end namespace gazer #endif
ftsrg/gazer
test/theta/verif/base/uninitialized_var_false.c
<filename>test/theta/verif/base/uninitialized_var_false.c // RUN: %theta -no-optimize -memory=havoc "%s" | FileCheck "%s" // RUN: %theta -memory=havoc "%s" | FileCheck "%s" // CHECK: Verification FAILED // This test checks that the enabled LLVM optimizations do not // strip away relevant code under an undefined value. void __VERIFIER_error(void) __attribute__((noreturn)); int main(void) { int x; if (x == 1) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
test/verif/regression/expr_simplify_invalid.c
// RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} // Due to an erroneous expression rewrite transformation, this // test has produced an invalid counterexample. int b, c, d, e, g; void __VERIFIER_error(); int a(); int f() { a(f, d, e, 0, 0); return 0; } int h() { a(g, d, e, 0, 0); return 0; } int main() { b = 1; h(); } int a(int i, int j, int k, int l, int m) { if (b == c) __VERIFIER_error(); return 0; }
ftsrg/gazer
test/verif/regression/crash_on_long.c
// RUN: %bmc -checks=signed-overflow "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL void a() __attribute__((__noreturn__)); int b() { int c; if (c - 4L) ; a(); } int main() { b(); }
ftsrg/gazer
include/gazer/LLVM/Instrumentation/Check.h
<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_INSTRUMENTATION_CHECK_H #define GAZER_LLVM_INSTRUMENTATION_CHECK_H #include <llvm/Pass.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/LegacyPassManager.h> namespace gazer { class CheckRegistry; /// A check is a special kind of an LLVM pass, which marks instrunctions /// with pre- or postconditions that must be always true. class Check : public llvm::ModulePass { friend class CheckRegistry; public: explicit Check(char& id) : ModulePass(id) {} Check(const Check&) = delete; Check& operator=(const Check&) = delete; bool runOnModule(llvm::Module& module) final; /// Returns a user-friendly error description on why this particular /// check failed. Such descriptions should be short and simple, e.g. /// "Assertion failure", "Division by zero", or "Signed integer overflow". virtual llvm::StringRef getErrorDescription() const = 0; /// Marks the given function's instructions with required /// pre- and postconditions. virtual bool mark(llvm::Function& function) = 0; protected: /// Creates an error block with a gazer.error_code(i16 code) call and a terminating unreachable instruction. llvm::BasicBlock* createErrorBlock( llvm::Function& function, const llvm::Twine& name = "", llvm::Instruction* location = nullptr ); /// Replaces all instructions matching the given predicate with an error call. /// This function assumes that all instructions that follow a matching instruction within the /// block are unreachable. /// \return True if there were any matches; false otherwise. bool replaceMatchingUnreachableWithError( llvm::Function& function, const llvm::Twine& errorBlockName, std::function<bool(llvm::Instruction&)> predicate ); CheckRegistry& getRegistry() const; private: void setCheckRegistry(CheckRegistry& registry); private: CheckRegistry* mRegistry = nullptr; }; class CheckViolation { public: CheckViolation(Check* check, llvm::DebugLoc location) : mCheck(check), mLocation(location) { assert(check != nullptr); } CheckViolation(const CheckViolation&) = default; CheckViolation& operator=(const CheckViolation&) = default; Check* getCheck() const { return mCheck; } llvm::DebugLoc getDebugLoc() const { return mLocation; } private: Check* mCheck; llvm::DebugLoc mLocation; }; class CheckRegistry { public: static constexpr char ErrorFunctionName[] = "gazer.error_code"; public: explicit CheckRegistry(llvm::LLVMContext& context) : mLlvmContext(context) {} CheckRegistry(const CheckRegistry&) = delete; CheckRegistry& operator=(const CheckRegistry&) = delete; static llvm::FunctionCallee GetErrorFunction(llvm::Module& module); static llvm::FunctionCallee GetErrorFunction(llvm::Module* module) { return GetErrorFunction(*module); } static llvm::FunctionType* GetErrorFunctionType(llvm::LLVMContext& context); static llvm::IntegerType* GetErrorCodeType(llvm::LLVMContext& context); public: /// Inserts a check into the check registry. /// This class will take ownership of the check object. void add(Check* check); /// Registers all enabled checks into the pass manager. /// As the pass manager takes ownership of all registered /// passes, this class will release all enabled checks /// after calling this method. void registerPasses(llvm::legacy::PassManager& pm); /// Creates a new check violation with a unique error code /// for a given check and location. /// \return An LLVM value representing the error code. llvm::Value* createCheckViolation(Check* check, llvm::DebugLoc loc); std::string messageForCode(unsigned ec) const; ~CheckRegistry(); private: llvm::LLVMContext& mLlvmContext; llvm::DenseMap<unsigned, CheckViolation> mCheckMap; std::vector<Check*> mChecks; bool mRegisterPassesCalled = false; // 0 stands for success, 1 for unknown failures. unsigned mErrorCodeCnt = 2; }; } // end namespace gazer #endif
ftsrg/gazer
test/theta/verif/memory/passbyref5.c
// REQUIRES: memory.burstall // RUN: %theta "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); void sumprod(int* a, int* b, int *sum, int *prod) { *sum = *a + *b; *prod = *a * *b; } int main(void) { int a = __VERIFIER_nondet_int(); int b = a + 1; int sum, prod; sumprod(&a, &b, &sum, &prod); if (a != 0 && b != 0 && prod == 0) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
test/errors.c
// A simple basic implementation of common error functions // to reproduce counterexamples targeting assertion failures. #include <stdlib.h> #include <stdio.h> void __assert_fail(void) { fprintf(stdout, "__assert_fail executed\n"); exit(0); } void __VERIFIER_error(void) { fprintf(stdout, "__VERIFIER_error executed\n"); exit(0); }
ftsrg/gazer
test/verif/regression/invalid_bmc_inline.c
// RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} // Due to an erroneous encoding of input assignments during BMC inlining, // this test yielded a false positive result. int c, d, e, f, h, i; void __VERIFIER_error(); int a(); int b(); int g() { b(0, e, f, 0, 0); return 0; } int j() { a(h, i); return 0; } int k() { return 0; } int a(l, m) { k(); b(0, e, f, 0, 0); k(); return 0; } int main() { c = 1; j(); } int b(int n, int o, int p, int q, int r) { if (c == d) __VERIFIER_error(); return 0; }
ftsrg/gazer
test/theta/cfa/counter.c
<filename>test/theta/cfa/counter.c // RUN: %theta -model-only "%s" -o "%t" // RUN: cat "%t" | /usr/bin/diff -B -Z "%p/Expected/counter.theta" - #include <assert.h> int __VERIFIER_nondet_int(); int main(void) { int sum = 0; int x = __VERIFIER_nondet_int(); for (int i = 0; i < x; ++i) { sum += 1; } assert(sum != 0); return 0; }
ftsrg/gazer
include/gazer/LLVM/Memory/MemoryObject.h
<filename>include/gazer/LLVM/Memory/MemoryObject.h //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_MEMORY_MEMORYOBJECT_H #define GAZER_LLVM_MEMORY_MEMORYOBJECT_H #include "gazer/Core/Expr.h" #include "gazer/LLVM/TypeTranslator.h" #include <llvm/IR/Instructions.h> #include <llvm/IR/Dominators.h> #include <llvm/IR/Operator.h> #include <llvm/Pass.h> #include <llvm/IR/ValueHandle.h> #include <llvm/IR/CallSite.h> #include <boost/iterator/indirect_iterator.hpp> #include <variant> namespace gazer { namespace memory { class MemorySSA; class MemorySSABuilder; } class MemoryObject; class MemoryObjectDef; class MemoryObjectUse; class MemoryObjectPhi; class MemoryAccess { friend class memory::MemorySSABuilder; public: MemoryAccess(MemoryObject* object) : mObject(object) {} MemoryAccess(const MemoryAccess&) = delete; MemoryAccess& operator=(const MemoryAccess&) = delete; MemoryObject* getObject() const { return mObject; } MemoryObjectDef* getReachingDef() const { return mReachingDef; } private: void setReachingDef(MemoryObjectDef* reachingDef) { mReachingDef = reachingDef; } private: MemoryObject* mObject; MemoryObjectDef* mReachingDef = nullptr; }; /// Represents the definition for a memory object. class MemoryObjectDef : public MemoryAccess { friend class memory::MemorySSABuilder; public: enum Kind { LiveOnEntry, ///< Inidicates that the memory object is alive when entering the function. GlobalInitializer, ///< One time initialization of a global variable. Alloca, ///< The allocation/instantiation of a local variable. Store, ///< A definition through a store instruction. Call, ///< Indicates that the call possibly clobbers this memory object. PHI }; protected: MemoryObjectDef(MemoryObject* object, unsigned version, Kind kind) : MemoryAccess(object), mKind(kind), mVersion(version) {} public: unsigned getVersion() const { return mVersion; } Kind getKind() const { return mKind; } std::string getName() const; llvm::BasicBlock* getParentBlock() const; void print(llvm::raw_ostream& os) const; virtual ~MemoryObjectDef() {} protected: virtual void doPrint(llvm::raw_ostream& os) const = 0; private: Kind mKind; unsigned mVersion; }; inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const MemoryObjectDef& def) { def.print(os); return os; } class MemoryObjectUse : public MemoryAccess { public: static unsigned constexpr UnknownVersion = std::numeric_limits<unsigned>::max(); enum Kind { Load, ///< Use through a load instruction. Call, ///< Parameter passing into a call. Return ///< Indicates that the object is alive at return. }; protected: MemoryObjectUse(MemoryObject* object, Kind kind) : MemoryAccess(object), mKind(kind) {} public: Kind getKind() const { return mKind; } llvm::BasicBlock* getParentBlock() const; virtual llvm::Instruction* getInstruction() const = 0; virtual void print(llvm::raw_ostream& os) const = 0; virtual ~MemoryObjectUse() {} private: Kind mKind; }; /// Describes the type of a memory object. This information will be used by /// later translation passes to represent the memory object as an SMT formula. enum class MemoryObjectType { Unknown, Scalar, Array, Struct }; /// Represents an abstract memory object, a continuous place in memory /// which does not overlap with other memory objects. class MemoryObject { friend class memory::MemorySSABuilder; public: using MemoryObjectSize = uint64_t; static constexpr MemoryObjectSize UnknownSize = ~uint64_t(0); public: MemoryObject( unsigned id, MemoryObjectType objectType, MemoryObjectSize size, llvm::Type* valueType = nullptr, llvm::StringRef name = "" ) : mId(id), mObjectType(objectType), mSize(size), mValueType(valueType), mName(!name.empty() ? name.str() : std::to_string(mId)) {} void print(llvm::raw_ostream& os) const; /// Sets a type hint for this memory object, indicating that it should be represented /// as the given type. void setTypeHint(gazer::Type& type) { mTypeHint = &type; } /// Returns the type hint if it is set, false otherwise. gazer::Type* getTypeHint() const { return mTypeHint; } MemoryObjectType getObjectType() const { return mObjectType; } llvm::Type* getValueType() const { return mValueType; } llvm::StringRef getName() const { return mName; } unsigned getId() const { return mId; } // Iterator support //===------------------------------------------------------------------===// using def_iterator = boost::indirect_iterator<std::vector<std::unique_ptr<MemoryObjectDef>>::iterator>; def_iterator def_begin() { return boost::make_indirect_iterator(mDefs.begin()); } def_iterator def_end() { return boost::make_indirect_iterator(mDefs.end()); } llvm::iterator_range<def_iterator> defs() { return llvm::make_range(def_begin(), def_end()); } using use_iterator = boost::indirect_iterator<std::vector<std::unique_ptr<MemoryObjectUse>>::iterator>; use_iterator use_begin() { return boost::make_indirect_iterator(mUses.begin()); } use_iterator use_end() { return boost::make_indirect_iterator(mUses.end()); } llvm::iterator_range<use_iterator> uses() { return llvm::make_range(use_begin(), use_end()); } MemoryObjectDef* getEntryDef() const { return mEntryDef; } MemoryObjectUse* getExitUse() const { return mExitUse; } bool hasEntryDef() const { return mEntryDef != nullptr; } bool hasExitUse() const { return mExitUse != nullptr; } ~MemoryObject(); private: void addDefinition(MemoryObjectDef* def); void addUse(MemoryObjectUse* use); void setEntryDef(MemoryObjectDef* def); void setExitUse(MemoryObjectUse* use); private: unsigned mId; MemoryObjectType mObjectType; MemoryObjectSize mSize; gazer::Type* mTypeHint; llvm::Type* mValueType; std::string mName; std::vector<std::unique_ptr<MemoryObjectDef>> mDefs; std::vector<std::unique_ptr<MemoryObjectUse>> mUses; MemoryObjectDef* mEntryDef = nullptr; MemoryObjectUse* mExitUse = nullptr; }; inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const MemoryObject& memoryObject) { memoryObject.print(os); return os; } namespace memory { // Definitions //===----------------------------------------------------------------------===// class InstructionAnnotationDef : public MemoryObjectDef { protected: using MemoryObjectDef::MemoryObjectDef; public: virtual llvm::Instruction* getInstruction() const = 0; static bool classof(const MemoryObjectDef* def) { switch (def->getKind()) { case LiveOnEntry: case GlobalInitializer: case PHI: return false; case Alloca: case Store: case Call: return true; } llvm_unreachable("Invalid definition kind!"); } }; class BlockAnnotationDef : public MemoryObjectDef { protected: using MemoryObjectDef::MemoryObjectDef; public: virtual llvm::BasicBlock* getBlock() const = 0; static bool classof(const MemoryObjectDef* def) { switch (def->getKind()) { case LiveOnEntry: case GlobalInitializer: case PHI: return true; case Alloca: case Store: case Call: return false; } llvm_unreachable("Invalid definition kind!"); } }; class AllocaDef : public InstructionAnnotationDef { public: AllocaDef(MemoryObject* object, unsigned int version, llvm::AllocaInst& alloca) : InstructionAnnotationDef(object, version, MemoryObjectDef::Alloca), mAllocaInst(&alloca) {} void doPrint(llvm::raw_ostream& os) const override; llvm::AllocaInst* getInstruction() const override { return mAllocaInst; } static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::Alloca; } private: llvm::AllocaInst* mAllocaInst; }; class StoreDef : public InstructionAnnotationDef { public: StoreDef(MemoryObject* object, unsigned int version, llvm::StoreInst& store) : InstructionAnnotationDef(object, version, MemoryObjectDef::Store), mStore(&store) {} llvm::StoreInst* getInstruction() const override { return mStore; } void doPrint(llvm::raw_ostream& os) const override; static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::Store; } private: llvm::StoreInst* mStore; }; class CallDef : public InstructionAnnotationDef { public: CallDef(MemoryObject* object, unsigned int version, llvm::CallSite call) : InstructionAnnotationDef(object, version, MemoryObjectDef::Call), mCall(call) {} static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::Call; } llvm::Instruction* getInstruction() const override { return mCall.getInstruction(); } protected: void doPrint(llvm::raw_ostream& os) const override; private: llvm::CallSite mCall; }; class LiveOnEntryDef : public BlockAnnotationDef { public: LiveOnEntryDef(MemoryObject* object, unsigned int version, llvm::BasicBlock* block) : BlockAnnotationDef(object, version, MemoryObjectDef::LiveOnEntry), mEntryBlock(block) {} void doPrint(llvm::raw_ostream& os) const override; llvm::BasicBlock* getBlock() const override { return mEntryBlock; } static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::LiveOnEntry; } private: llvm::BasicBlock* mEntryBlock; }; class GlobalInitializerDef : public BlockAnnotationDef { public: GlobalInitializerDef( MemoryObject* object, unsigned int version, llvm::BasicBlock* block, llvm::GlobalVariable* gv ) : BlockAnnotationDef(object, version, MemoryObjectDef::GlobalInitializer), mEntryBlock(block), mGlobalVariable(gv) {} llvm::GlobalVariable* getGlobalVariable() const { return mGlobalVariable; } llvm::BasicBlock* getBlock() const override { return mEntryBlock; } static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::GlobalInitializer; } protected: void doPrint(llvm::raw_ostream& os) const override; private: llvm::BasicBlock* mEntryBlock; llvm::GlobalVariable* mGlobalVariable; }; class PhiDef : public BlockAnnotationDef { public: PhiDef(MemoryObject* object, unsigned int version, llvm::BasicBlock* block) : BlockAnnotationDef(object, version, MemoryObjectDef::PHI), mBlock(block) {} llvm::BasicBlock* getBlock() const override { return mBlock; } MemoryObjectDef* getIncomingDefForBlock(const llvm::BasicBlock* bb) const; void addIncoming(MemoryObjectDef* def, const llvm::BasicBlock* bb); static bool classof(const MemoryObjectDef* def) { return def->getKind() == MemoryObjectDef::PHI; } protected: void doPrint(llvm::raw_ostream& os) const override; private: llvm::BasicBlock* mBlock; llvm::DenseMap<const llvm::BasicBlock*, MemoryObjectDef*> mEntryList; }; // Uses //===----------------------------------------------------------------------===// class LoadUse : public MemoryObjectUse { public: LoadUse(MemoryObject* object, llvm::LoadInst& load) : MemoryObjectUse(object, MemoryObjectUse::Load), mLoadInst(&load) {} void print(llvm::raw_ostream& os) const override; llvm::LoadInst* getInstruction() const override { return mLoadInst; } static bool classof(const MemoryObjectUse* use) { return use->getKind() == MemoryObjectUse::Load; } private: llvm::LoadInst* mLoadInst; }; class CallUse : public MemoryObjectUse { public: CallUse(MemoryObject* object, llvm::CallSite callSite) : MemoryObjectUse(object, MemoryObjectUse::Call), mCallSite(callSite) {} llvm::Instruction* getInstruction() const override { return mCallSite.getInstruction(); } llvm::CallSite getCallSite() const { return mCallSite; } void print(llvm::raw_ostream& os) const override; static bool classof(const MemoryObjectUse* use) { return use->getKind() == MemoryObjectUse::Call; } private: llvm::CallSite mCallSite; }; class RetUse : public MemoryObjectUse { public: RetUse(MemoryObject* object, llvm::ReturnInst& ret) : MemoryObjectUse(object, MemoryObjectUse::Return), mReturnInst(&ret) {} llvm::ReturnInst* getInstruction() const override { return mReturnInst; } void print(llvm::raw_ostream& os) const override; static bool classof(const MemoryObjectUse* use) { return use->getKind() == MemoryObjectUse::Return; } private: llvm::ReturnInst* mReturnInst; }; } // end namespace gazer::memory } // end namespace gazer #endif
ftsrg/gazer
test/theta/verif/overflow/overflow_loops.c
<gh_stars>1-10 // RUN: %theta -checks=signed-overflow "%s" | FileCheck "%s" // CHECK: Verification FAILED // CHECK: Signed integer overflow int __VERIFIER_nondet_int(); int main(void) { int x = 1; int y = 1; while (1) { x = x * 2 * __VERIFIER_nondet_int(); y = y * 3 * __VERIFIER_nondet_int(); if (x == 0) { goto EXIT; } } EXIT: return 0; }
ftsrg/gazer
include/gazer/Core/Expr/ExprRewrite.h
<reponame>ftsrg/gazer //==- ExprRewrite.h ---------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPR_EXPRREWRITE_H #define GAZER_CORE_EXPR_EXPRREWRITE_H #include "gazer/Core/Expr/ExprWalker.h" #include "gazer/Core/Expr/ExprBuilder.h" namespace gazer { /// Non-template dependent functionality of the expression rewriter. class ExprRewriteBase { protected: ExprRewriteBase(ExprBuilder& builder) : mExprBuilder(builder) {} ExprPtr rewriteNonNullary(const ExprRef<NonNullaryExpr>& expr, const ExprVector& ops); protected: ExprBuilder& mExprBuilder; }; /// Base class for expression rewrite implementations. template<class DerivedT> class ExprRewrite : public ExprWalker<DerivedT, ExprPtr>, public ExprRewriteBase { friend class ExprWalker<DerivedT, ExprPtr>; public: explicit ExprRewrite(ExprBuilder& builder) : ExprRewriteBase(builder) {} protected: ExprPtr visitExpr(const ExprPtr& expr) { return expr; } ExprPtr visitNonNullary(const ExprRef<NonNullaryExpr>& expr) { ExprVector ops(expr->getNumOperands(), nullptr); for (size_t i = 0; i < expr->getNumOperands(); ++i) { ops[i] = this->getOperand(i); } return this->rewriteNonNullary(expr, ops); } }; /// An expression rewriter that replaces certain variables with some /// given expression, according to the values set by operator[]. class VariableExprRewrite : public ExprRewrite<VariableExprRewrite> { friend class ExprWalker<VariableExprRewrite, ExprPtr>; public: explicit VariableExprRewrite(ExprBuilder& builder) : ExprRewrite(builder) {} ExprPtr& operator[](Variable* variable); protected: ExprPtr visitVarRef(const ExprRef<VarRefExpr>& expr); private: llvm::DenseMap<Variable*, ExprPtr> mRewriteMap; }; } #endif
ftsrg/gazer
include/gazer/ADT/Algorithm.h
<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_ADT_ALGORITHM_H #define GAZER_ADT_ALGORITHM_H #include <boost/dynamic_bitset.hpp> namespace gazer { /// A quadratic-time algorithm to find the intersection and difference of two ranges. /// Given two containers A and B, this function finds the sets A * B, A / B, B / A. /// If duplicates are present, they will not be inserted into either output set. template<class Range1, class Range2, class OutputIt1, class OutputIt2, class OutputIt3> void intersection_difference( Range1 left, Range2 right, OutputIt1 commonOut, OutputIt2 lMinusROut, OutputIt3 rMinusLOut) { size_t leftSiz = std::distance(left.begin(), left.end()); size_t rightSiz = std::distance(right.begin(), right.end()); boost::dynamic_bitset<> rightElems(rightSiz); for (size_t i = 0; i < leftSiz; ++i) { auto li = std::next(left.begin(), i); bool isPresentInRight = false; for (size_t j = 0; j < rightSiz; ++j) { auto rj = std::next(right.begin(), j); if (*li == *rj) { if (!rightElems[j] && !isPresentInRight) { *(commonOut++) = *li; } isPresentInRight = true; rightElems[j] = true; } } if (!isPresentInRight) { *(lMinusROut++) = *li; } } // Do another pass to find unpaired elements in right for (size_t j = 0; j < rightSiz; ++j) { auto rj = std::next(right.begin(), j); if (!rightElems[j]) { *(rMinusLOut++) = *rj; } } } } // end namespace gazer #endif
ftsrg/gazer
test/verif/regression/eval_error_fail.c
// RUN: %bmc -bound 1 -inline=all -trace "%s" | FileCheck "%s" // CHECK: Verification FAILED // This test caused trace generation to crash due to an invalid null pointer. int c; void __VERIFIER_error(); int a(); int b(); int d() { b(); __VERIFIER_error(); return 0; } int b() { return c; } int main() { int e = a(); c = 0; if (e) c = 7; d(); }
ftsrg/gazer
include/gazer/Support/DenseMapKeyInfo.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SUPPORT_DENSEMAPKEYINFO_H #define GAZER_SUPPORT_DENSEMAPKEYINFO_H #include <llvm/ADT/APInt.h> #include <llvm/ADT/Hashing.h> namespace gazer { /// \brief A DenseMap key information struct for APInt keys. /// /// NOTE: this class does not allow 1-width APInts as keys, /// as they are used for empty and tombstone identifications. /// /// In the LLVM libraries, DenseMap key information for APInts /// is hidden in LLVMContextImpl. /// Furthermore, constructors which would allow the construction /// of 0-width APInts are also unaccessible from the outside. struct DenseMapAPIntKeyInfo { static inline llvm::APInt getEmptyKey() { llvm::APInt value(1, 0); return value; } static inline llvm::APInt getTombstoneKey() { llvm::APInt value(1, 1); return value; } static unsigned getHashValue(const llvm::APInt &Key) { return static_cast<unsigned>(llvm::hash_value(Key)); } static bool isEqual(const llvm::APInt &lhs, const llvm::APInt &rhs) { return lhs.getBitWidth() == rhs.getBitWidth() && lhs == rhs; } }; /// \brief A DenseMap key information struct for APFloat keys. /// /// Based on the implementation found in LLVMContextImpl.h struct DenseMapAPFloatKeyInfo { static inline llvm::APFloat getEmptyKey() { return llvm::APFloat(llvm::APFloat::Bogus(), 1); } static inline llvm::APFloat getTombstoneKey() { return llvm::APFloat(llvm::APFloat::Bogus(), 2); } static unsigned getHashValue(const llvm::APFloat &key) { return static_cast<unsigned>(hash_value(key)); } static bool isEqual(const llvm::APFloat &lhs, const llvm::APFloat &rhs) { return lhs.bitwiseIsEqual(rhs); } }; } // end namespace gazer #endif
ftsrg/gazer
include/gazer/Trace/Trace.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_TRACE_TRACE_H #define GAZER_TRACE_TRACE_H #include "gazer/Trace/Location.h" #include "gazer/Core/Expr.h" #include <llvm/Support/ErrorHandling.h> #include <utility> #include <vector> namespace gazer { class Valuation; template<class ReturnT = void> class TraceEventVisitor; /// Represents a step in a counterexample trace. class TraceEvent { public: enum EventKind { Event_Assign, Event_FunctionEntry, Event_FunctionReturn, Event_FunctionCall, Event_UndefinedBehavior }; protected: explicit TraceEvent(EventKind kind, LocationInfo location = {}) : mKind(kind), mLocation(location) {} public: TraceEvent(const TraceEvent&) = delete; TraceEvent& operator=(const TraceEvent&) = delete; public: EventKind getKind() const { return mKind; } LocationInfo getLocation() const { return mLocation; } template<class ReturnT> ReturnT accept(TraceEventVisitor<ReturnT>& visitor); virtual ~TraceEvent() = default; private: EventKind mKind; LocationInfo mLocation; }; /// Represents a detailed counterexample trace, possibly provided by /// a verification algorithm. class Trace { public: explicit Trace(std::vector<std::unique_ptr<TraceEvent>> events) : mEvents(std::move(events)) {} public: Trace(const Trace&) = delete; Trace& operator=(const Trace&) = delete; public: // Iterator support for iterating events using iterator = std::vector<std::unique_ptr<TraceEvent>>::iterator; using const_iterator = std::vector<std::unique_ptr<TraceEvent>>::const_iterator; iterator begin() { return mEvents.begin(); } iterator end() { return mEvents.end(); } const_iterator begin() const { return mEvents.begin(); } const_iterator end() const { return mEvents.end(); } private: std::vector<std::unique_ptr<TraceEvent>> mEvents; }; template<class State, class Action> class TraceBuilder { public: /// Builds a trace from a sequence of states and actions. virtual std::unique_ptr<Trace> build( std::vector<State>& states, std::vector<Action>& actions ) = 0; virtual ~TraceBuilder() = default; }; /// A simple wrapper for a trace variable class TraceVariable { public: enum Representation { Rep_Unknown, Rep_Bool, Rep_Char, Rep_Signed, Rep_Unsigned, Rep_Float }; TraceVariable(std::string name, Representation representation, unsigned size = 0) : mName(std::move(name)), mRepresentation(representation), mSize(size) {} [[nodiscard]] llvm::StringRef getName() const { return mName; } [[nodiscard]] Representation getRepresentation() const { return mRepresentation; } [[nodiscard]] unsigned getSize() const { return mSize; } private: std::string mName; Representation mRepresentation; unsigned mSize; }; /// Indicates an assignment in the original program. class AssignTraceEvent final : public TraceEvent { public: AssignTraceEvent( TraceVariable variable, ExprRef<AtomicExpr> expr, LocationInfo location = {} ) : TraceEvent(TraceEvent::Event_Assign, location), mVariable(std::move(variable)), mExpr(std::move(expr)) { assert(mExpr != nullptr); } [[nodiscard]] const TraceVariable& getVariable() const { return mVariable; } [[nodiscard]] ExprRef<AtomicExpr> getExpr() const { return mExpr; } static bool classof(const TraceEvent* event) { return event->getKind() == TraceEvent::Event_Assign; } private: TraceVariable mVariable; ExprRef<AtomicExpr> mExpr; }; /// Indicates an entry into a procedure. class FunctionEntryEvent final : public TraceEvent { public: explicit FunctionEntryEvent( std::string functionName, std::vector<ExprRef<AtomicExpr>> args = {}, LocationInfo location = {} ) : TraceEvent(TraceEvent::Event_FunctionEntry, location), mFunctionName(std::move(functionName)), mArgs(std::move(args)) {} [[nodiscard]] std::string getFunctionName() const { return mFunctionName; } using arg_iterator = std::vector<ExprRef<AtomicExpr>>::const_iterator; arg_iterator arg_begin() const { return mArgs.begin(); } arg_iterator arg_end() const { return mArgs.end(); } [[nodiscard]] llvm::iterator_range<arg_iterator> args() { return llvm::make_range(arg_begin(), arg_end()); } static bool classof(const TraceEvent* event) { return event->getKind() == TraceEvent::Event_FunctionEntry; } private: std::string mFunctionName; std::vector<ExprRef<AtomicExpr>> mArgs; }; class FunctionReturnEvent : public TraceEvent { public: FunctionReturnEvent( std::string functionName, ExprRef<AtomicExpr> returnValue, LocationInfo location = {} ) : TraceEvent(TraceEvent::Event_FunctionReturn, location), mFunctionName(std::move(functionName)), mReturnValue(std::move(returnValue)) {} std::string getFunctionName() const { return mFunctionName; } ExprRef<AtomicExpr> getReturnValue() const { return mReturnValue; } bool hasReturnValue() const { return mReturnValue != nullptr; } static bool classof(const TraceEvent* event) { return event->getKind() == TraceEvent::Event_FunctionReturn; } private: std::string mFunctionName; ExprRef<AtomicExpr> mReturnValue; }; /// Indicates a call to a nondetermistic function. class FunctionCallEvent : public TraceEvent { using ArgsVectorTy = std::vector<ExprRef<AtomicExpr>>; public: FunctionCallEvent( std::string functionName, ExprRef<AtomicExpr> returnValue, ArgsVectorTy args = {}, LocationInfo location = {} ) : TraceEvent(TraceEvent::Event_FunctionCall, location), mFunctionName(functionName), mReturnValue(returnValue), mArgs(args) {} std::string getFunctionName() const { return mFunctionName; } ExprRef<AtomicExpr> getReturnValue() const { return mReturnValue; } using arg_iterator = ArgsVectorTy::iterator; arg_iterator arg_begin() { return mArgs.begin(); } arg_iterator arg_end() { return mArgs.end(); } llvm::iterator_range<arg_iterator> args() { return llvm::make_range(arg_begin(), arg_end()); } static bool classof(const TraceEvent* event) { return event->getKind() == TraceEvent::Event_FunctionCall; } private: std::string mFunctionName; ExprRef<AtomicExpr> mReturnValue; ArgsVectorTy mArgs; }; /// Indicates that undefined behavior has occured. class UndefinedBehaviorEvent : public TraceEvent { public: explicit UndefinedBehaviorEvent( ExprRef<AtomicExpr> pickedValue, LocationInfo location = {} ) : TraceEvent(TraceEvent::Event_UndefinedBehavior, location), mPickedValue(std::move(pickedValue)) {} ExprRef<AtomicExpr> getPickedValue() const { return mPickedValue; } static bool classof(const TraceEvent* event) { return event->getKind() == TraceEvent::Event_UndefinedBehavior; } private: ExprRef<AtomicExpr> mPickedValue; }; template<class ReturnT> class TraceEventVisitor { public: virtual ReturnT visit(AssignTraceEvent& event) = 0; virtual ReturnT visit(FunctionEntryEvent& event) = 0; virtual ReturnT visit(FunctionReturnEvent& event) = 0; virtual ReturnT visit(FunctionCallEvent& event) = 0; virtual ReturnT visit(UndefinedBehaviorEvent& event) = 0; virtual ~TraceEventVisitor() = default; }; template<class ReturnT> inline ReturnT TraceEvent::accept(TraceEventVisitor<ReturnT>& visitor) { switch (mKind) { case Event_Assign: return visitor.visit(*llvm::cast<AssignTraceEvent>(this)); case Event_FunctionEntry: return visitor.visit(*llvm::cast<FunctionEntryEvent>(this)); case Event_FunctionReturn: return visitor.visit(*llvm::cast<FunctionReturnEvent>(this)); case Event_FunctionCall: return visitor.visit(*llvm::cast<FunctionCallEvent>(this)); case Event_UndefinedBehavior: return visitor.visit(*llvm::cast<UndefinedBehaviorEvent>(this)); } llvm_unreachable("Unknown TraceEvent kind!"); } } // end namespace gazer #endif
ftsrg/gazer
include/gazer/Automaton/CallGraph.h
<gh_stars>1-10 //==- CallGraph.h - Call graph interface for CFAs ---------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_AUTOMATON_CALLGRAPH_H #define GAZER_AUTOMATON_CALLGRAPH_H #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/GraphTraits.h> #include <llvm/ADT/iterator.h> #include <vector> namespace gazer { class Cfa; class AutomataSystem; class CallTransition; class CallGraph { public: class Node; using CallSite = std::pair<CallTransition*, Node*>; class Node { friend class CallGraph; public: Node(Cfa* cfa) : mCfa(cfa) {} void addCall(CallTransition* call, Node* node) { assert(call != nullptr); assert(node != nullptr); mCallsToOthers.emplace_back(call, node); node->mCallsToThis.emplace_back(call); } Cfa* getCfa() const { return mCfa; } using iterator = std::vector<CallSite>::const_iterator; iterator begin() const { return mCallsToOthers.begin(); } iterator end() const { return mCallsToOthers.end(); } private: Cfa* mCfa; std::vector<CallSite> mCallsToOthers; std::vector<CallTransition*> mCallsToThis; }; public: explicit CallGraph(AutomataSystem& system); ~CallGraph(); /// Returns true if the given procedure is tail-recursive. That is, /// if it is recursive and the recursive calls only occur in /// the procedure directly before the exit. bool isTailRecursive(Cfa* cfa); AutomataSystem& getSystem() const { return mSystem; }; Node* lookupNode(Cfa* cfa); private: AutomataSystem& mSystem; llvm::DenseMap<Cfa*, std::unique_ptr<Node>> mNodes; }; } // end namespace gazer namespace llvm { template<> struct GraphTraits<gazer::CallGraph::Node*> { using NodeRef = gazer::CallGraph::Node*; static NodeRef getNodeFromCallSite(const gazer::CallGraph::CallSite cs) { return cs.second; } using ChildIteratorType = llvm::mapped_iterator< gazer::CallGraph::Node::iterator, decltype(&getNodeFromCallSite) >; static ChildIteratorType child_begin(NodeRef N) { return ChildIteratorType(N->begin(), &getNodeFromCallSite); } static ChildIteratorType child_end(NodeRef N) { return ChildIteratorType(N->end(), &getNodeFromCallSite); } static NodeRef getEntryNode(gazer::CallGraph::Node* node) { return node; } }; } // end namespace llvm #endif
ftsrg/gazer
test/verif/memory/arrays1.c
<gh_stars>1-10 // RUN: %bmc -bound 10 "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); int main(void) { int x[5]; for (int i = 0; i < 5; ++i) { x[i] = i + 1; } if (x[0] == 0) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
test/verif/memory/structs2.c
// RUN: %bmc -bound 1 -memory=flat "%s" | FileCheck "%s" // By default we assume that unknown external functions do not clobber memory objects. // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} // MODIFY: Verification FAILED int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); void make_symbolic(void* ptr); typedef struct X { int a; int b; } X; int main(void) { X x; int a = __VERIFIER_nondet_int(); x.a = a; make_symbolic(&x.b); if (x.a != a) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
include/gazer/LLVM/Transform/UndefToNondet.h
<filename>include/gazer/LLVM/Transform/UndefToNondet.h<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_TRANSFORM_UNDEFTONONDET_H #define GAZER_LLVM_TRANSFORM_UNDEFTONONDET_H #include <llvm/Pass.h> namespace gazer { /// This pass turns undef values into nondetermistic functions calls, /// forcing the optimizer to be more careful around undefined behavior. class UndefToNondetCallPass : public llvm::ModulePass { public: static char ID; static constexpr char UndefValueFunctionPrefix[] = "gazer.undef_value."; UndefToNondetCallPass() : ModulePass(ID) {} bool runOnModule(llvm::Module& module) override; }; llvm::Pass* createPromoteUndefsPass(); } #endif
ftsrg/gazer
include/gazer/Core/Type.h
<reponame>ftsrg/gazer //==- Type.h - Gazer expression types ---------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_TYPE_H #define GAZER_CORE_TYPE_H #include "gazer/Core/GazerContext.h" #include <llvm/Support/Casting.h> #include <llvm/ADT/iterator.h> #include <llvm/ADT/ArrayRef.h> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <string> #include <memory> #include <stdexcept> #include <iosfwd> namespace llvm { struct fltSemantics; class raw_ostream; } namespace gazer { class GazerContext; /// Base class for all gazer types. class Type { public: enum TypeID { // Primitive types BoolTypeID = 0, IntTypeID, BvTypeID, FloatTypeID, RealTypeID, // Composite types ArrayTypeID, TupleTypeID, FunctionTypeID }; static constexpr int FirstPrimitive = BoolTypeID; static constexpr int LastPrimitive = FloatTypeID; static constexpr int FirstComposite = ArrayTypeID; static constexpr int LastComposite = FunctionTypeID; protected: explicit Type(GazerContext& context, TypeID id) : mContext(context), mTypeID(id) {} public: Type(const Type&) = delete; Type& operator=(const Type&) = delete; [[nodiscard]] GazerContext& getContext() const { return mContext; } [[nodiscard]] TypeID getTypeID() const { return mTypeID; } [[nodiscard]] bool isPrimitiveType() const { return mTypeID >= FirstPrimitive && mTypeID <= LastPrimitive; } [[nodiscard]] bool isCompositeType() const { return mTypeID >= FirstComposite && mTypeID <= LastComposite; } [[nodiscard]] bool isBoolType() const { return getTypeID() == BoolTypeID; } [[nodiscard]] bool isIntType() const { return getTypeID() == IntTypeID; } [[nodiscard]] bool isBvType() const { return getTypeID() == BvTypeID; } [[nodiscard]] bool isFloatType() const { return getTypeID() == FloatTypeID; } [[nodiscard]] bool isRealType() const { return getTypeID() == RealTypeID; } [[nodiscard]] bool isArrayType() const { return getTypeID() == ArrayTypeID; } [[nodiscard]] bool isTupleType() const { return getTypeID() == TupleTypeID; } [[nodiscard]] bool isArithmetic() const { return isIntType() || isRealType(); } //bool isPointerType() const { return getTypeID() == PointerTypeID; } bool equals(const Type* other) const; bool operator==(const Type& other) const { return equals(&other); } bool operator!=(const Type& other) const { return !equals(&other); } [[nodiscard]] std::string getName() const; private: GazerContext& mContext; TypeID mTypeID; }; llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Type& type); // Primitive type declarations //===----------------------------------------------------------------------===// class BoolType final : public Type { friend class GazerContextImpl; protected: explicit BoolType(GazerContext& context) : Type(context, BoolTypeID) {} public: static BoolType& Get(GazerContext& context); static bool classof(const Type* type) { return type->getTypeID() == BoolTypeID; } }; class BvType final : public Type { friend class GazerContextImpl; protected: BvType(GazerContext& context, unsigned width) : Type(context, BvTypeID), mWidth(width) {} public: [[nodiscard]] unsigned getWidth() const { return mWidth; } static BvType& Get(GazerContext& context, unsigned width); static bool classof(const Type* type) { return type->getTypeID() == BvTypeID; } static bool classof(const Type& type) { return type.getTypeID() == BvTypeID; } private: unsigned mWidth; }; /// Unbounded, mathematical integer type. class IntType final : public Type { friend class GazerContextImpl; protected: explicit IntType(GazerContext& context) : Type(context, IntTypeID) {} public: static IntType& Get(GazerContext& context); static bool classof(const Type* type) { return type->getTypeID() == IntTypeID; } static bool classof(const Type& type) { return type.getTypeID() == IntTypeID; } private: }; class RealType final : public Type { friend class GazerContextImpl; protected: explicit RealType(GazerContext& context) : Type(context, RealTypeID) {} public: static RealType& Get(GazerContext& context); static bool classof(const Type* type) { return type->getTypeID() == RealTypeID; } static bool classof(const Type& type) { return type.getTypeID() == RealTypeID; } }; /// Represents an IEEE-754 floating point type. class FloatType final : public Type { friend class GazerContextImpl; public: enum FloatPrecision { Half = 16, Single = 32, Double = 64, Quad = 128 }; static constexpr unsigned SignificandBitsInHalfTy = 11; static constexpr unsigned SignificandBitsInSingleTy = 24; static constexpr unsigned SignificandBitsInDoubleTy = 53; static constexpr unsigned SignificandBitsInQuadTy = 113; static constexpr unsigned ExponentBitsInHalfTy = 5; static constexpr unsigned ExponentBitsInSingleTy = 8; static constexpr unsigned ExponentBitsInDoubleTy = 11; static constexpr unsigned ExponentBitsInQuadTy = 15; protected: FloatType(GazerContext& context, FloatPrecision precision) : Type(context, FloatTypeID), mPrecision(precision) {} public: [[nodiscard]] FloatPrecision getPrecision() const { return mPrecision; } [[nodiscard]] const llvm::fltSemantics& getLLVMSemantics() const; [[nodiscard]] unsigned getWidth() const { return mPrecision; } unsigned getExponentWidth() const; unsigned getSignificandWidth() const; static FloatType& Get(GazerContext& context, FloatPrecision precision); static bool classof(const Type* type) { return type->getTypeID() == FloatTypeID; } static bool classof(const Type& type) { return type.getTypeID() == FloatTypeID; } private: FloatPrecision mPrecision; static FloatType HalfTy, SingleTy, DoubleTy, QuadTy; }; // Composite types //===----------------------------------------------------------------------===// class CompositeType : public Type { protected: CompositeType(GazerContext& context, TypeID id, std::vector<Type*> subTypes); public: Type& getSubType(unsigned idx) const { assert(idx <= mSubTypes.size()); return *mSubTypes[idx]; } protected: std::vector<Type*> mSubTypes; }; /// Represents an array type with arbitrary index and element types. class ArrayType final : public CompositeType { ArrayType(GazerContext& context, std::vector<Type*> types); public: Type& getIndexType() const { return getSubType(0); } Type& getElementType() const { return getSubType(1); } static ArrayType& Get(Type& indexType, Type& elementType); static bool classof(const Type* type) { return type->getTypeID() == ArrayTypeID; } static bool classof(const Type& type) { return classof(&type); } }; class TupleType final : public Type { TupleType(GazerContext& context, std::vector<Type*> subtypes) : Type(context, TupleTypeID), mSubtypeList(std::move(subtypes)) { assert(!mSubtypeList.empty()); assert(mSubtypeList.size() >= 2); } public: Type& getTypeAtIndex(unsigned idx) const { return *mSubtypeList[idx]; } unsigned getNumSubtypes() const { return mSubtypeList.size(); } using subtype_iterator = boost::indirect_iterator<std::vector<Type*>::const_iterator>; subtype_iterator subtype_begin() const { return boost::make_indirect_iterator(mSubtypeList.begin()); } subtype_iterator subtype_end() const { return boost::make_indirect_iterator(mSubtypeList.end()); } template<class... Tys> static typename std::enable_if<(std::is_base_of_v<Type, Tys> && ...), TupleType&>::type Get(Type& first, Tys&... tail) { std::vector<Type*> subtypeList({ &first, &tail... }); return TupleType::Get(subtypeList); } static TupleType& Get(std::vector<Type*> subtypes); static bool classof(const Type* type) { return type->getTypeID() == TupleTypeID; } static bool classof(const Type& type) { return classof(&type); } private: std::vector<Type*> mSubtypeList; }; class FunctionType : public Type { FunctionType(GazerContext& context, Type* resultType, std::vector<Type*> paramTypes) : Type(context, FunctionTypeID), mResultType(resultType), mParamTypeList(paramTypes) {} public: template<class... Tys> static typename std::enable_if<std::is_base_of_v<Type, Tys...>, FunctionType&>::type Get(Type& result, Tys&... params) { std::array<Type*, sizeof...(Tys)> paramTypes({ &params... }); return FunctionType::Get(&result, paramTypes); } unsigned getArity() const { return mParamTypeList.size(); } Type& getResultType() const { return *mResultType; } Type& getParamType(unsigned idx) const; private: FunctionType& Get(Type* resultType, llvm::ArrayRef<Type*> paramTypes); private: Type* mResultType; std::vector<Type*> mParamTypeList; }; } #endif
ftsrg/gazer
include/gazer/Automaton/CfaUtils.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_AUTOMATON_CFAUTILS_H #define GAZER_AUTOMATON_CFAUTILS_H #include "gazer/Automaton/Cfa.h" #include <llvm/ADT/DenseSet.h> #include <llvm/ADT/PostOrderIterator.h> namespace gazer { class ExprBuilder; template<class Seq = std::vector<Location*>, class Map = llvm::DenseMap<Location*, size_t>> void createTopologicalSort(Cfa& cfa, Seq& topoVec, Map* locNumbers = nullptr) { auto poBegin = llvm::po_begin(cfa.getEntry()); auto poEnd = llvm::po_end(cfa.getEntry()); topoVec.insert(topoVec.end(), poBegin, poEnd); std::reverse(topoVec.begin(), topoVec.end()); if (locNumbers != nullptr) { for (size_t i = 0; i < topoVec.size(); ++i) { (*locNumbers)[topoVec[i]] = i; } } } /// Class for calculating verification path conditions. class PathConditionCalculator { public: PathConditionCalculator( const std::vector<Location*>& topo, ExprBuilder& builder, std::function<size_t(Location*)> index, std::function<ExprPtr(CallTransition*)> calls, std::function<void(Location*, ExprPtr)> preds = nullptr ); public: ExprPtr encode(Location* source, Location* target); private: const std::vector<Location*>& mTopo; ExprBuilder& mExprBuilder; std::function<size_t(Location*)> mIndex; std::function<ExprPtr(CallTransition*)> mCalls; std::function<void(Location*, ExprPtr)> mPredecessors; unsigned mPredIdx = 0; }; /// Returns the lowest common dominator of each transition in \p targets. /// /// \param targets A set of target locations. /// \param topo Topological sort of automaton locations. /// \param topoIdx A function which returns the index of a location in the topological sort. /// \param start The start node, which must dominate all target locations. Defaults to the /// entry location if empty. Location* findLowestCommonDominator( const std::vector<Transition*>& targets, const std::vector<Location*>& topo, std::function<size_t(Location*)> index, Location* start = nullptr ); /// Returns the highest common post-dominator of each transition in \p targets. Location* findHighestCommonPostDominator( const std::vector<Transition*>& targets, const std::vector<Location*>& topo, std::function<size_t(Location*)> index, Location* start ); } #endif
ftsrg/gazer
include/gazer/Core/Valuation.h
<reponame>ftsrg/gazer //==- Valuation.h -----------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_VALUATION_H #define GAZER_CORE_VALUATION_H #include "gazer/Core/Expr.h" #include <llvm/ADT/DenseMap.h> namespace gazer { /// Represents a simple mapping between variables and literal expressions. class Valuation { using ValuationMapT = llvm::DenseMap<const Variable*, ExprRef<LiteralExpr>>; public: class Builder { public: Valuation build() { return Valuation(mMap); } void put(Variable* variable, const ExprRef<LiteralExpr>& expr) { assert((variable->getType() == expr->getType()) && "Types must match."); mMap[variable] = expr; } private: ValuationMapT mMap; }; static Builder CreateBuilder() { return Builder(); } private: Valuation(ValuationMapT map) : mMap(std::move(map)) {} public: Valuation() = default; Valuation(const Valuation&) = default; Valuation& operator=(const Valuation&) = default; Valuation(Valuation&&) = default; Valuation& operator=(Valuation&&) = default; public: ExprRef<LiteralExpr>& operator[](const Variable& variable); ExprRef<LiteralExpr>& operator[](const Variable* variable) { return operator[](*variable); } using iterator = ValuationMapT::iterator; using const_iterator = ValuationMapT::const_iterator; iterator find(const Variable* variable) { return mMap.find(variable); } const_iterator find(const Variable* variable) const { return mMap.find(variable); } iterator begin() { return mMap.begin(); } iterator end() { return mMap.end(); } const_iterator begin() const { return mMap.begin(); } const_iterator end() const { return mMap.end(); } void print(llvm::raw_ostream& os); private: ValuationMapT mMap; }; } #endif
ftsrg/gazer
include/gazer/LLVM/ClangFrontend.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_CLANGFRONTEND_H #define GAZER_LLVM_CLANGFRONTEND_H #include <llvm/ADT/ArrayRef.h> #include <llvm/ADT/StringRef.h> #include <set> namespace llvm { class Module; class LLVMContext; } namespace gazer { /// Represents Clang configurations. class ClangOptions { public: void addSanitizerFlag(llvm::StringRef flag); void createArgumentList(std::vector<std::string>& args); private: std::set<std::string> mSanitizerFlags; }; /// Compiles a set of C and/or LLVM bitcode files using clang, links them /// together with llvm-link and parses the resulting module. std::unique_ptr<llvm::Module> ClangCompileAndLink( llvm::ArrayRef<std::string> files, llvm::LLVMContext& llvmContext, ClangOptions& settings ); } #endif //GAZER_CLANGFRONTEND_H
ftsrg/gazer
test/verif/regression/floats/fp_if_not_inlined.c
<gh_stars>1-10 // This test failed if gazer-bmc was invoked without the "-inline=all" flag. // The underlying issue was that the translation process did not handle PHI nodes correctly when jumping out of loops. // RUN: %bmc -bound 10 -inline=all "%s" | FileCheck "%s" // RUN: %bmc -bound 10 "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} float b = 16.f; void __VERIFIER_error(); void a(c) { if (!c) __VERIFIER_error(); } int main() { for (;;) { b = 3.f * b / 4.f; a(12.f); a(b); } }
ftsrg/gazer
test/theta/verif/memory/local_passbyref1_fail.c
// REQUIRES: memory.burstall // RUN: %theta "%s" | FileCheck "%s" // CHECK: Verification FAILED void __VERIFIER_error(void) __attribute__((__noreturn__)); void klee_make_symbolic(void* ptr, unsigned siz, const char* name); int main(void) { int x; klee_make_symbolic(&x, sizeof(x), "x"); if (x == 0) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
test/verif/floats/float_cast4_fail.c
// RUN: %bmc -bound 1 "%s" | FileCheck "%s" // CHECK: Verification FAILED #include <assert.h> float __VERIFIER_nondet_float(void); int main(void) { double x = __VERIFIER_nondet_float(); assert(x != 150.0); return 0; }
ftsrg/gazer
include/gazer/Core/Expr/Matcher.h
<reponame>ftsrg/gazer<gh_stars>1-10 //==- Matcher.h - A pattern matcher for expressions -------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //===----------------------------------------------------------------------===// /// /// \file This file describes the pattern matching utility for expressions. /// The matcher system is tree-based and works with ExprPtr parameters. /// This provides a powerful and intuitive tool for pattern-based expression /// rewriting. See this code snippet for an usage example: /// /// ExprPtr input = ... /// ExprPtr f1, f2, f3; /// if (match(input, m_And( /// m_Or(m_Expr(f1), m_Expr(f2)), /// m_Or(m_Specific(f1), m_Expr(f3)) /// )) { /// // (F1 | F2) & (F1 | F3) -> F1 & (F2 | F3) /// return AndExpr::Create(f1, OrExpr::Create(f2, f3)); /// } /// /// Binary and multiary patterns are always evaluated left to right. /// Multiary patterns come in different flavors, depending on the use case. /// For example, in the case of the And operator, the following patterns /// are available: /// /// \li \c m_And(P1, P2, ..., Pn): matches an AndExpr having precisely /// n operands, and matches every Pi pattern against any operand. /// The match is successful if every Pi pattern is matched. /// If multiple operands match a pattern, only the leftmost operand is /// matched and bound. If a single operand matches multiple patterns, /// only the leftmost pattern is matched and bound. /// /// \li \c m_And(U, P1, P2, ..., Pk): matches an AndExpr having /// at least k operands, matches every Pi pattern against any operand /// (with the same semantics described above) and fills the ExprVector U /// with the unmatched operands. /// /// The implementation in this file is mostly based on the Value matcher /// mechanism found in LLVM. /// //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPR_MATCHER_H #define GAZER_CORE_EXPR_MATCHER_H #include "gazer/Core/Expr.h" #include "gazer/Core/ExprTypes.h" #include "gazer/Core/LiteralExpr.h" #include <llvm/Support/Casting.h> #include <bitset> namespace gazer::PatternMatch { /// Match a given expression to a pattern template<typename ExprTy, typename Pattern> inline bool match(const ExprRef<ExprTy>& ptr, const Pattern& pattern) { return const_cast<Pattern&>(pattern).match(ptr); } /// Matches two expressions to two patterns template<typename LTy, typename RTy> inline bool match(ExprPtr e1, ExprPtr e2, const LTy& left, const RTy& right) { return const_cast<LTy&>(left).match(e1) && const_cast<RTy&>(right).match(e2); } template<typename P1, typename P2, typename P3> inline bool match(ExprPtr e1, ExprPtr e2, ExprPtr e3, const P1& p1, const P2& p2, const P3& p3) { return const_cast<P1&>(p1).match(e1) && const_cast<P2&>(p2).match(e2) && const_cast<P3&>(p3).match(e3); } template<typename LTy, typename RTy> inline bool unord_match(ExprPtr e1, ExprPtr e2, const LTy& left, const RTy& right) { return (const_cast<LTy&>(left).match(e1) && const_cast<RTy&>(right).match(e2)) || (const_cast<LTy&>(left).match(e2) && const_cast<RTy&>(right).match(e1)); } namespace detail { template<unsigned Current, typename... Patterns> inline bool vector_element_match(ExprVector& unmatched, std::tuple<Patterns...>& tuple) { if constexpr (Current < sizeof...(Patterns)) { auto& pattern = std::get<Current>(tuple); for (size_t i = 0; i < unmatched.size(); ++i) { if (pattern.match(unmatched[i])) { // We have a match here, remove the unmatched element from the array and try more patterns. unmatched.erase(unmatched.begin() + i); return vector_element_match<Current + 1>(unmatched, tuple); } } // This pattern could not be matched, we need to return false. return false; } return true; } } // end namespace detail template<typename... Patterns> inline bool unord_match(const ExprVector& vec, Patterns... patterns) { ExprVector unmatched = vec; std::tuple<Patterns...> patternsTuple(patterns...); return detail::vector_element_match<0, Patterns...>(unmatched, patternsTuple); } template<typename... Patterns> inline bool unord_match(const ExprVector& vec, ExprVector& unmatched, Patterns... patterns) { assert(&vec != &unmatched); assert(unmatched.empty() && "Can only fill an empty unmatched vector!"); std::tuple<Patterns...> patternsTuple(patterns...); unmatched = vec; return detail::vector_element_match<0, Patterns...>(unmatched, patternsTuple); } struct true_match { template<typename InputTy> bool match(const ExprRef<InputTy>& ptr) { return true; } }; template<typename ExprTy> struct expr_match { template<typename InputTy> bool match(const ExprRef<InputTy>& ptr) { return llvm::isa<ExprTy>(ptr.get()); } }; /// Matches an arbitrary expression and ignores it. inline expr_match<Expr> m_Expr() { return expr_match<Expr>(); } /// Matches an arbitrary atomic expression and ignores it. inline expr_match<AtomicExpr> m_Atomic() { return expr_match<AtomicExpr>(); } /// Matches an arbitray non-nullary expression and ignores it. inline expr_match<NonNullaryExpr> m_NonNullary() { return expr_match<NonNullaryExpr>(); } /// Matches an arbitrary undef expression and ignores it. inline expr_match<UndefExpr> m_Undef() { return expr_match<UndefExpr>(); } /// Matches an arbitrary literal expression and ignores it. inline expr_match<LiteralExpr> m_Literal() { return expr_match<LiteralExpr>(); } /// Matches an arbitrary variable reference and ignores it. inline expr_match<VarRefExpr> m_VarRef() { return expr_match<VarRefExpr>(); } struct apint_match { llvm::APInt* const result; apint_match(llvm::APInt* const result) : result(result) {} template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (auto bvLit = llvm::dyn_cast<BvLiteralExpr>(expr.get())) { *result = bvLit->getValue(); return true; } return false; } }; inline apint_match m_Bv(llvm::APInt* const result) { return apint_match(result); } struct int_match { IntLiteralExpr::ValueTy* const result; int_match(IntLiteralExpr::ValueTy* const result) : result(result) {} template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (auto intLit = llvm::dyn_cast<IntLiteralExpr>(expr)) { *result = intLit->getValue(); return true; } return false; } }; inline int_match m_Int(IntLiteralExpr::ValueTy* const result) { return int_match(result); } struct specific_match { const ExprPtr& storedExpr; specific_match(const ExprPtr& expr) : storedExpr(expr) {} bool match(const ExprPtr& expr) { return storedExpr == expr; } }; inline specific_match m_Specific(const ExprPtr& expr) { return specific_match(expr); } template<typename ExprTy> struct bind_ty { ExprRef<ExprTy>& storedPtr; bind_ty(ExprRef<ExprTy>& ptr) : storedPtr(ptr) {} template<typename InputTy> bool match(const ExprRef<InputTy>& ptr) { if (auto expr = llvm::dyn_cast<ExprTy>(ptr)) { storedPtr = expr; return true; } return false; } }; inline bind_ty<Expr> m_Expr(ExprRef<Expr>& ptr) { return bind_ty<Expr>(ptr); } template<class ExprKind> inline bind_ty<ExprKind> m_Expr(ExprRef<ExprKind>& ptr) { return bind_ty<ExprKind>(ptr); } inline bind_ty<VarRefExpr> m_VarRef(ExprRef<VarRefExpr>& ptr) { return bind_ty<VarRefExpr>(ptr); } inline bind_ty<LiteralExpr> m_Literal(ExprRef<LiteralExpr>& ptr) { return bind_ty<LiteralExpr>(ptr); } inline bind_ty<BoolLiteralExpr> m_BoolLit(ExprRef<BoolLiteralExpr>& ptr) { return bind_ty<BoolLiteralExpr>(ptr); } inline bind_ty<BvLiteralExpr> m_BvLit(ExprRef<BvLiteralExpr>& ptr) { return bind_ty<BvLiteralExpr>(ptr); } //===------------------- Matcher for unary expressions --------------------===// //============================================================================// template<typename PatternTy, Expr::ExprKind Kind> struct unary_match { static_assert(Kind >= Expr::FirstUnary, "Unary expressions must be NonNullary!"); PatternTy pattern; unary_match(const PatternTy& pattern) : pattern(pattern) {} template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (expr->getKind() != Kind) { return false; } if (NonNullaryExpr* e = llvm::dyn_cast<NonNullaryExpr>(expr.get())) { return pattern.match(e->getOperand(0)); } return false; } }; #define UNARY_MATCHER(KIND) \ template<typename PatternTy> \ inline unary_match<PatternTy, Expr::KIND> m_##KIND(const PatternTy& pattern) { \ return unary_match<PatternTy, Expr::KIND>(pattern); \ } UNARY_MATCHER(Not) UNARY_MATCHER(ZExt) UNARY_MATCHER(SExt) #undef UNARY_MATCHER //===------------------- Matcher for binary expressions -------------------===// //============================================================================// /// Helper class for matching binary expressions. /// The pattern is always evaluated left to right, regardless of commutativity. template<typename LTy, typename RTy, Expr::ExprKind Kind, bool Commutable = false> struct binary_match { static_assert(Kind >= Expr::FirstUnary, "Binary expressions must be NonNullary!"); LTy left; RTy right; binary_match(const LTy& left, const RTy& right) : left(left), right(right) {} template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (expr->getKind() != Kind) { return false; } if (NonNullaryExpr* e = llvm::dyn_cast<NonNullaryExpr>(expr.get())) { if (e->getNumOperands() != 2) { return false; } return (left.match(e->getOperand(0)) && right.match(e->getOperand(1))) || (Commutable && left.match(e->getOperand(1)) && right.match(e->getOperand(0))); } return false; } }; #define BINARY_MATCHER(KIND) \ template<typename LTy, typename RTy> \ inline binary_match<LTy, RTy, Expr::KIND> m_##KIND( \ const LTy& left, const RTy& right \ ) { \ return binary_match<LTy, RTy, Expr::KIND, false>(left, right); \ } #define BINARY_MATCHER_COMMUTATIVE(KIND) \ template<typename LTy, typename RTy> \ inline binary_match<LTy, RTy, Expr::KIND, true> m_##KIND( \ const LTy& left, const RTy& right \ ) { \ return binary_match<LTy, RTy, Expr::KIND, true>(left, right); \ } BINARY_MATCHER_COMMUTATIVE(Add) BINARY_MATCHER(Sub) BINARY_MATCHER_COMMUTATIVE(Mul) BINARY_MATCHER(BvSDiv) BINARY_MATCHER(BvUDiv) BINARY_MATCHER(BvSRem) BINARY_MATCHER(BvURem) BINARY_MATCHER(Shl) BINARY_MATCHER(LShr) BINARY_MATCHER(AShr) BINARY_MATCHER_COMMUTATIVE(BvAnd) BINARY_MATCHER_COMMUTATIVE(BvOr) BINARY_MATCHER_COMMUTATIVE(BvXor) BINARY_MATCHER_COMMUTATIVE(And) BINARY_MATCHER_COMMUTATIVE(Or) BINARY_MATCHER_COMMUTATIVE(Eq) BINARY_MATCHER_COMMUTATIVE(NotEq) BINARY_MATCHER(Lt) BINARY_MATCHER(LtEq) BINARY_MATCHER(Gt) BINARY_MATCHER(GtEq) BINARY_MATCHER(BvSLt) BINARY_MATCHER(BvSLtEq) BINARY_MATCHER(BvSGt) BINARY_MATCHER(BvSGtEq) BINARY_MATCHER(BvULt) BINARY_MATCHER(BvULtEq) BINARY_MATCHER(BvUGt) BINARY_MATCHER(BvUGtEq) #undef BINARY_MATCHER #undef BINARY_MATCHER_COMMUTATIVE template<typename CondTy, typename LTy, typename RTy> struct select_expr_match { CondTy cond; LTy then; RTy elze; select_expr_match(const CondTy& cond, const LTy& then, const RTy& elze) : cond(cond), then(then), elze(elze) {} template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (auto select = llvm::dyn_cast<SelectExpr>(expr.get())) { return cond.match(select->getCondition()) && then.match(select->getThen()) && elze.match(select->getElse()); } return false; } }; template<typename CondTy, typename LTy, typename RTy> select_expr_match<CondTy, LTy, RTy> m_Select(const CondTy& cond, const LTy& left, const RTy& right) { return select_expr_match<CondTy, LTy, RTy>(cond, left, right); } //===------------------ Matcher for multiary expressions ------------------===// //============================================================================// /// Helper for matching multiary expressions template<size_t NumOps, Expr::ExprKind Kind, bool Commutable, typename... Ts> struct multiary_match_precise { std::tuple<Ts...> patterns; multiary_match_precise(const std::tuple<Ts...>& patterns) : patterns(patterns) {} template<size_t N> bool subpattern_match_unordered(NonNullaryExpr* expr, std::bitset<NumOps> bs) { if constexpr (N < NumOps) { auto& pattern = std::get<N>(patterns); // The pattern could be matched in any order. // To do this, we traverse the operands of the input expression // and try to match the pattern. If the pattern is matched, // we set the corresponding bit in the bitset, so further // patterns will not match on this one. bool matched = false; for (size_t i = 0; i < NumOps; ++i) { if (!bs[i] && pattern.match(expr->getOperand(i))) { matched = true; bs.set(i); break; } } // No valid matches were found for this pattern if (!matched) { return false; } return subpattern_match_unordered<N + 1>(expr, bs); } return true; } template<size_t N> bool subpattern_match(NonNullaryExpr* expr) { if constexpr (N < NumOps) { auto& pattern = std::get<N>(patterns); // The order matters here (non-commutable): we just need to // check if the ith operand matches the ith pattern. bool matched = pattern.match(expr->getOperand(N)); if (!matched) { return false; } return subpattern_match<N + 1>(expr); } return true; } template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (expr->getKind() != Kind) { return false; } NonNullaryExpr* e = llvm::cast<NonNullaryExpr>(expr.get()); if (e->getNumOperands() != NumOps) { return false; } // Check each pattern separately. if constexpr (Commutable) { std::bitset<NumOps> bs; return subpattern_match_unordered<0>(e, bs); } return subpattern_match<0>(e); } }; template<size_t NumPatterns, Expr::ExprKind Kind, typename... Ts> struct multiary_match { ExprVector& unmatched; std::tuple<Ts...> patterns; multiary_match(ExprVector& unmatched, const std::tuple<Ts...>& patterns) : patterns(patterns) {} template<size_t N> bool subpattern_match_unordered(NonNullaryExpr* expr, std::vector<bool>& bs) { if constexpr (N < NumPatterns) { auto& pattern = std::get<N>(patterns); bool matched = false; for (size_t i = 0; i < NumPatterns; ++i) { if (!bs[i] && pattern.match(expr->getOperand(i))) { matched = true; bs[i] = true; break; } } // No valid matches were found for this pattern if (!matched) { return false; } return subpattern_match_unordered<N + 1>(expr, bs); } return true; } template<typename InputTy> bool match(const ExprRef<InputTy>& expr) { if (expr->getKind() != Kind) { return false; } NonNullaryExpr* e = llvm::cast<NonNullaryExpr>(expr.get()); if (e->getNumOperands() < NumPatterns) { return false; } // Check each pattern separately. std::vector<bool> bs(e->getNumOperands(), false); bool matched = subpattern_match_unordered<0>(e, bs); // Collect all the unmatched operands for (size_t i = 0; i < bs.size(); ++i) { unmatched.push_back(e->getOperand(i)); } return matched; } }; template<typename FirstTy, typename SecondTy, typename... Ts> multiary_match_precise<sizeof...(Ts) + 2, Expr::And, false, FirstTy, SecondTy, Ts...> m_Ordered_And(const FirstTy& first, const SecondTy& second, const Ts&... patterns) { return multiary_match_precise< sizeof...(Ts) + 2, Expr::And, false, FirstTy, SecondTy, Ts... >(std::make_tuple(first, second, patterns...)); } template<typename FirstTy, typename SecondTy, typename... Ts> multiary_match_precise<sizeof...(Ts) + 2, Expr::And, true, FirstTy, SecondTy, Ts...> m_And(const FirstTy& first, const SecondTy& second, const Ts&... patterns) { return multiary_match_precise< sizeof...(Ts) + 2, Expr::And, true, FirstTy, SecondTy, Ts... >(std::make_tuple(first, second, patterns...)); } } // end namespace gazer #endif
ftsrg/gazer
include/gazer/Support/GrowingStackAllocator.h
<reponame>ftsrg/gazer //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SUPPORT_GROWINGSTACKALLOCATOR_H #define GAZER_SUPPORT_GROWINGSTACKALLOCATOR_H #include <llvm/Support/Allocator.h> namespace gazer { /// An ever-growing stack-like allocator. /// /// This allocator follows a stack-like allocation policy: any object may be allocated, /// but deallocation can happen only at the end of the pool, i.e. the last object. /// The pool behaves as an ever-growing storage, but is not a continuous chunk of memory. template<class AllocatorT = llvm::MallocAllocator, size_t SlabSize = 4096> class GrowingStackAllocator : public llvm::AllocatorBase<GrowingStackAllocator<AllocatorT, SlabSize>> { struct Slab { void* Start; char* Current; char* End; void deallocate() { free(Start); } }; public: GrowingStackAllocator() = default; void Init() { this->startNewSlab(); } LLVM_ATTRIBUTE_RETURNS_NONNULL void* Allocate(size_t size, size_t alignment) { size_t adjustment = llvm::alignmentAdjustment(slab().Current, alignment); assert(adjustment + size >= size); if (size > SlabSize) { llvm::report_bad_alloc_error("Requested allocation size is larger than GrowingStackAllocator slab size!"); } if (slab().Current + adjustment + size > slab().End) { // If the requested size would overrun this slab, start a new one. this->startNewSlab(); } auto alignedPtr = slab().Current + adjustment; slab().Current = alignedPtr + size; return alignedPtr; } void Deallocate(const void *ptr, size_t size) { // Stack allocators only allow deallocation on the end of the pool. auto ptrEnd = ((char*) ptr) + size; if (ptrEnd == slab().Current) { // The pointer is at the end of our current slab. slab().Current = (char*) ptr; } else { // The pointer must be at the end of the previous slab, get that now. assert(ptrEnd == mSlabs[mCurrentSlab - 1].Current); mCurrentSlab--; slab().Current = (char*) ptr; } } ~GrowingStackAllocator() { for (size_t i = 0; i < mSlabs.size(); ++i) { mSlabs[i].deallocate(); } } private: void startNewSlab() { if (mSlabs.empty() || mCurrentSlab == mSlabs.size() - 1) { void *newSlab = mAllocator.Allocate(SlabSize, 0); mSlabs.push_back({ newSlab, (char*) newSlab, (char*) newSlab + SlabSize }); mCurrentSlab = mSlabs.size() - 1; } else { // There is an already allocated slab, we just need to change mCurrentSlab. mCurrentSlab++; } } Slab& slab() { return mSlabs[mCurrentSlab]; } private: AllocatorT mAllocator; llvm::SmallVector<Slab, 32> mSlabs; size_t mCurrentSlab = 0; }; } #endif
ftsrg/gazer
test/verif/base/simple_struct_as_tuple.c
// RUN: %bmc -bound 1 -Wno-int-conversion "%s" | FileCheck "%s" // RUN: %bmc -bound 1 -no-optimize -Wno-int-conversion "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL struct { long d; long e; } typedef f; struct { } typedef g; typedef struct h i; f j(k) { f l; return l; } long m(n, o) { f frequency; j(&frequency); return 0; } i *p; int main() { g devobj; m(&devobj, p); }
ftsrg/gazer
test/theta/verif/memory/passbyref7_fail.c
<gh_stars>1-10 // REQUIRES: memory.burstall // RUN: %theta "%s" | FileCheck "%s" // CHECK: Verification FAILED int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); void sumprod(int a, int b, int *sum, int *prod) { *sum = a + b; *prod = a * b; } int main(void) { int a = 5; int b = 5; int prod; sumprod(a, b, &prod, &prod); if (prod != 25) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
include/gazer/LLVM/Memory/MemorySSA.h
<reponame>ftsrg/gazer<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_MEMORY_MEMSSA_H #define GAZER_LLVM_MEMORY_MEMSSA_H #include "gazer/LLVM/Memory/MemoryObject.h" #include <boost/iterator/indirect_iterator.hpp> #include <unordered_map> namespace gazer::memory { class MemorySSABuilder; class MemorySSA { friend class MemorySSABuilder; using ValueToDefSetMap = llvm::DenseMap<const llvm::Value*, std::vector<MemoryObjectDef*>>; using ValueToUseSetMap = llvm::DenseMap<const llvm::Value*, std::vector<MemoryObjectUse*>>; private: MemorySSA( llvm::Function& function, std::vector<std::unique_ptr<MemoryObject>> objects, ValueToDefSetMap valueDefAnnotations, ValueToUseSetMap valueUseAnnotations ) : mFunction(function), mObjects(std::move(objects)), mValueDefs(std::move(valueDefAnnotations)), mValueUses(std::move(valueUseAnnotations)) {} public: void print(llvm::raw_ostream& os); // Def-use queries //==--------------------------------------------------------------------==// using def_iterator = boost::indirect_iterator<ValueToDefSetMap::mapped_type::iterator>; using use_iterator = boost::indirect_iterator<ValueToUseSetMap::mapped_type::iterator>; llvm::iterator_range<def_iterator> definitionAnnotationsFor(const llvm::Value*); llvm::iterator_range<use_iterator> useAnnotationsFor(const llvm::Value*); template<class AccessKind> typename std::enable_if_t<std::is_base_of_v<MemoryObjectDef, AccessKind>> memoryAccessOfKind(const llvm::Value* value, llvm::SmallVectorImpl<AccessKind*>& vec) { return this->memoryAccessOfKindImpl(this->definitionAnnotationsFor(value), vec); } template<class AccessKind> typename std::enable_if_t<std::is_base_of_v<MemoryObjectUse, AccessKind>> memoryAccessOfKind(const llvm::Value* value, llvm::SmallVectorImpl<AccessKind*>& vec) { return this->memoryAccessOfKindImpl(this->useAnnotationsFor(value), vec); } /// If \p value is annotated with a single definition for \p object, returns /// said definition. In any other case, returns nullptr. MemoryObjectDef* getUniqueDefinitionFor(const llvm::Value* value, const MemoryObject* object); MemoryObjectUse* getUniqueUseFor(const llvm::Value* value, const MemoryObject* object); // Iterator support //==--------------------------------------------------------------------==// using object_iterator = boost::indirect_iterator<std::vector<std::unique_ptr<MemoryObject>>::iterator>; object_iterator object_begin() { return boost::make_indirect_iterator(mObjects.begin()); } object_iterator object_end() { return boost::make_indirect_iterator(mObjects.end()); } llvm::iterator_range<object_iterator> objects() { return llvm::make_range(object_begin(), object_end()); } private: template<class AccessKind, class Range> static void memoryAccessOfKindImpl(Range&& range, llvm::SmallVectorImpl<AccessKind*>& vec) { static_assert(std::is_base_of_v<MemoryAccess, AccessKind>, "AccessKind must be a subclass of MemoryAccess!"); for (auto& access : range) { if (auto casted = llvm::dyn_cast<AccessKind>(&access)) { vec.push_back(casted); } } } private: llvm::Function& mFunction; std::vector<std::unique_ptr<MemoryObject>> mObjects; // MemorySSA annotations ValueToDefSetMap mValueDefs; ValueToUseSetMap mValueUses; }; /// Helper class for building memory SSA form. class MemorySSABuilder { struct MemoryObjectInfo { MemoryObject* object; llvm::SmallPtrSet<llvm::BasicBlock*, 32> defBlocks; llvm::SmallVector<MemoryObjectDef*, 8> renameStack; MemoryObjectDef* getCurrentTopDefinition() { if (!renameStack.empty()) { return renameStack.back(); } return nullptr; } }; public: MemorySSABuilder( llvm::Function& function, const llvm::DataLayout& dl, llvm::DominatorTree& dominatorTree ) : mFunction(function), mDataLayout(dl), mDominatorTree(dominatorTree) {} MemoryObject* createMemoryObject( unsigned id, MemoryObjectType objectType, MemoryObject::MemoryObjectSize size, llvm::Type* valueType, llvm::StringRef name = "" ); memory::LiveOnEntryDef* createLiveOnEntryDef(MemoryObject* object); memory::GlobalInitializerDef* createGlobalInitializerDef( MemoryObject* object, llvm::GlobalVariable* gv ); memory::AllocaDef* createAllocaDef(MemoryObject* object, llvm::AllocaInst& alloca); memory::StoreDef* createStoreDef(MemoryObject* object, llvm::StoreInst& inst); memory::CallDef* createCallDef(MemoryObject* object, llvm::CallSite call); memory::LoadUse* createLoadUse(MemoryObject* object, llvm::LoadInst& load); memory::CallUse* createCallUse(MemoryObject* object, llvm::CallSite call); memory::RetUse* createReturnUse(MemoryObject* object, llvm::ReturnInst& ret); std::unique_ptr<MemorySSA> build(); private: void calculatePHINodes(); void renamePass(); void renameBlock(llvm::BasicBlock* block); private: llvm::Function& mFunction; const llvm::DataLayout& mDataLayout; llvm::DominatorTree& mDominatorTree; std::vector<std::unique_ptr<MemoryObject>> mObjectStorage; llvm::DenseMap<MemoryObject*, MemoryObjectInfo> mObjectInfo; MemorySSA::ValueToDefSetMap mValueDefs; MemorySSA::ValueToUseSetMap mValueUses; unsigned mVersionNumber = 0; }; /// A wrapper for passes which want to construct memory SSA. /// Clients can register required analyses class MemorySSABuilderPass : public llvm::ModulePass { public: explicit MemorySSABuilderPass(char& ID) : ModulePass(ID) {} void getAnalysisUsage(llvm::AnalysisUsage& au) const final; bool runOnModule(llvm::Module& module) final; virtual void addRequiredAnalyses(llvm::AnalysisUsage& au) const {} virtual void initializeFunction(llvm::Function& function, MemorySSABuilder& builder) = 0; private: llvm::DenseMap<llvm::Function*, std::unique_ptr<MemorySSA>> mFunctions; }; } #endif
ftsrg/gazer
tools/gazer-theta/lib/ThetaCfaGenerator.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_TOOLS_GAZERTHETA_THETACFAGENERATOR_H #define GAZER_TOOLS_GAZERTHETA_THETACFAGENERATOR_H #include "gazer/Automaton/Cfa.h" #include "gazer/Automaton/CallGraph.h" #include <llvm/Support/raw_ostream.h> namespace llvm { class Pass; } // end namespace llvm namespace gazer::theta { std::string printThetaExpr(const ExprPtr& expr); std::string printThetaExpr(const ExprPtr& expr, std::function<std::string(Variable*)> variableNames); /// \brief Perform pre-processing steps required by theta on the input CFA. /// /// This pass does the following transformations: /// - Undefined values in expressions are replaced with previously havoc'd variables. /// - Array literals are replaced with a appropriately constructed array variable. void preprocessCfa(Cfa* cfa); struct ThetaNameMapping { llvm::StringMap<Location*> locations; llvm::StringMap<Variable*> variables; Location* errorLocation; Variable* errorFieldVariable; llvm::DenseMap<Location*, Location*> inlinedLocations; llvm::DenseMap<Variable*, Variable*> inlinedVariables; }; class ThetaCfaGenerator { public: ThetaCfaGenerator(AutomataSystem& system) : mSystem(system), mCallGraph(system) {} void write(llvm::raw_ostream& os, ThetaNameMapping& names); private: std::string validName(std::string name, std::function<bool(const std::string&)> isUnique); private: AutomataSystem& mSystem; CallGraph mCallGraph; unsigned mTmpCount = 0; }; llvm::Pass* createThetaCfaWriterPass(llvm::raw_ostream& os); } // end namespace gazer::theta #endif
ftsrg/gazer
include/gazer/LLVM/Automaton/InstToExpr.h
<gh_stars>1-10 //==- InstToExpr.h - Translate LLVM IR to expressions -----------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_INSTTOEXPR_H #define GAZER_LLVM_INSTTOEXPR_H #include "gazer/Core/Expr.h" #include "gazer/Core/Expr/ExprBuilder.h" #include "gazer/LLVM/Memory/ValueOrMemoryObject.h" #include "gazer/LLVM/Memory/MemoryInstructionHandler.h" #include "gazer/LLVM/TypeTranslator.h" #include "gazer/LLVM/LLVMFrontendSettings.h" #include <llvm/IR/Operator.h> #include <llvm/IR/Instructions.h> namespace gazer { class MemoryModel; /// A transformation class which may be used to transform LLVM instructions /// to gazer expressions. class InstToExpr { public: InstToExpr( llvm::Function& function, ExprBuilder& builder, LLVMTypeTranslator& types, MemoryInstructionHandler& memoryInstHandler, const LLVMFrontendSettings& settings ) : mFunction(function), mExprBuilder(builder), mTypes(types), mContext(builder.getContext()), mMemoryInstHandler(memoryInstHandler), mSettings(settings) {} ExprPtr transform(const llvm::Instruction& inst, Type& expectedType); virtual ~InstToExpr() = default; protected: virtual Variable* getVariable(ValueOrMemoryObject value) = 0; /// If \p value was inlined, returns the corresponding expression. /// Otherwise, this method should return nullptr. virtual ExprPtr lookupInlinedVariable(ValueOrMemoryObject value) { return nullptr; } protected: ExprPtr visitBinaryOperator(const llvm::BinaryOperator& binop, Type& expectedType); ExprPtr visitSelectInst(const llvm::SelectInst& select, Type& expectedType); ExprPtr visitCastInst(const llvm::CastInst& cast, Type& expectedType); ExprPtr visitICmpInst(const llvm::ICmpInst& icmp); ExprPtr visitFCmpInst(const llvm::FCmpInst& fcmp); ExprPtr visitCallInst(const llvm::CallInst& call); ExprPtr visitInsertValueInst(const llvm::InsertValueInst& insert); ExprPtr visitExtractValueInst(const llvm::ExtractValueInst& extract); ExprPtr operand(ValueOrMemoryObject value); ExprPtr asBool(const ExprPtr& operand); ExprPtr asBv(const ExprPtr& operand, unsigned int bits); ExprPtr asInt(const ExprPtr& operand); ExprPtr integerCast(const llvm::CastInst& cast, const ExprPtr& castOperand, Type& expectedType); ExprPtr bitCast(const ExprPtr& castOperand, Type& expectedType); ExprPtr castResult(const ExprPtr& expr, const Type& type); ExprPtr boolToIntCast(const llvm::CastInst& cast, const ExprPtr& operand, Type& expectedType); gazer::Type& translateType(const llvm::Type* type); template<class Ty> Ty& translateTypeTo(const llvm::Type* type) { gazer::Type& gazerTy = this->translateType(type); assert(llvm::isa<Ty>(&gazerTy)); return *llvm::cast<Ty>(&gazerTy); } private: ExprPtr doTransform(const llvm::Instruction& inst, Type& expectedType); ExprPtr unsignedLessThan(const ExprPtr& left, const ExprPtr& right); ExprPtr operandValue(const llvm::Value* value); ExprPtr operandMemoryObject(const MemoryObjectDef* def); ExprPtr handleOverflowPredicate(const llvm::CallInst& call); ExprPtr tryToRepresentBitOperator(const llvm::BinaryOperator& binOp, const ExprPtr& left, const ExprPtr& right); protected: llvm::Function& mFunction; ExprBuilder& mExprBuilder; LLVMTypeTranslator& mTypes; GazerContext& mContext; MemoryInstructionHandler& mMemoryInstHandler; const LLVMFrontendSettings& mSettings; }; } // end namespace gazer #endif
ftsrg/gazer
test/verif/regression/verifier_error_only.c
// RUN: %bmc -bound 1 -trace -memory=flat "%s" | FileCheck "%s" // CHECK: Verification FAILED void __VERIFIER_error(); int main() { __VERIFIER_error(); }
ftsrg/gazer
test/verif/regression/nested_loop_exit.c
// RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} int main() { int a; while (1) { int b, c; while (1) { if (c) goto d; if (b) while (1) ; } d: if (a) goto e; } e:; }
ftsrg/gazer
include/gazer/LLVM/Instrumentation/DefaultChecks.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #include "gazer/LLVM/ClangFrontend.h" #include "gazer/LLVM/Instrumentation/Check.h" namespace gazer::checks { /// Check for assertion violations within the program. std::unique_ptr<Check> createAssertionFailCheck(ClangOptions& options); /// This check fails if a division instruction is reachable /// with its second operand's value being 0. std::unique_ptr<Check> createDivisionByZeroCheck(ClangOptions& options); /// This check fails if a signed integer operation results /// in an over- or underflow. std::unique_ptr<Check> createSignedIntegerOverflowCheck(ClangOptions& options); } // end namespace gazer::checks
ftsrg/gazer
include/gazer/LLVM/LLVMFrontend.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_LLVMFRONTEND_H #define GAZER_LLVM_LLVMFRONTEND_H #include "gazer/LLVM/ClangFrontend.h" #include "gazer/LLVM/Instrumentation/Check.h" #include "gazer/LLVM/LLVMFrontendSettings.h" #include "gazer/Verifier/VerificationAlgorithm.h" #include <llvm/Pass.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/Support/ToolOutputFile.h> namespace gazer { class GazerContext; class LLVMFrontend; /// Builder class for LLVM frontends. class FrontendConfig { public: using CheckFactory = std::function<std::unique_ptr<Check>(ClangOptions&)>; static constexpr char AllChecksSetting[] = "all"; public: FrontendConfig(); /// Inserts a given check into the system. Inserted checks may be disabled /// through the command-line. The check factory should be responsible for /// creating the check object and inserting relevant flags into the /// provided ClangOptions object. The factory will be executed (and the /// flags will be inserted) only if the corresponding check was enabled. void registerCheck(llvm::StringRef name, CheckFactory factory); template<class T> void registerCheck(llvm::StringRef name) { static_assert(std::is_base_of_v<Check, T>, "Registered checks must inherit from Check!"); addCheck(name, []() { return std::make_unique<T>(); }); } std::unique_ptr<LLVMFrontend> buildFrontend( llvm::ArrayRef<std::string> inputs, GazerContext& context, llvm::LLVMContext& llvmContext ); LLVMFrontendSettings& getSettings() { return mSettings; } private: void createChecks(std::vector<std::unique_ptr<Check>>& checks); private: ClangOptions mClangSettings; LLVMFrontendSettings mSettings; std::map<std::string, CheckFactory> mFactories; }; /// A convenience frontend object which sets up command-line arguments /// and performs some clean-up on destruction. class FrontendConfigWrapper { public: static void PrintVersion(llvm::raw_ostream& os); public: FrontendConfigWrapper() = default; std::unique_ptr<LLVMFrontend> buildFrontend(llvm::ArrayRef<std::string> inputs) { return config.buildFrontend(inputs, context, llvmContext); } LLVMFrontendSettings& getSettings() { return config.getSettings(); } private: llvm::llvm_shutdown_obj mShutdown; // This should be kept as first, will be destroyed last public: llvm::LLVMContext llvmContext; GazerContext context; FrontendConfig config; }; class LLVMFrontend { public: LLVMFrontend( std::unique_ptr<llvm::Module> module, GazerContext& context, LLVMFrontendSettings& settings ); LLVMFrontend(const LLVMFrontend&) = delete; LLVMFrontend& operator=(const LLVMFrontend&) = delete; static std::unique_ptr<LLVMFrontend> FromInputFile( llvm::StringRef input, GazerContext& context, llvm::LLVMContext& llvmContext, LLVMFrontendSettings& settings ); /// Registers the common preprocessing analyses and transforms of the /// verification pipeline into the pass manager. After executing the /// registered passes, the input LLVM module will be optimized, and the /// translated automata system will be available, and if there is a set /// backend algorithm, it will be run. void registerVerificationPipeline(); /// Registers an arbitrary pass into the pipeline. void registerPass(llvm::Pass* pass); /// Sets the backend algorithm to be used in the verification process. /// The LLVMFrontend instance will take ownership of the backend object. /// Note: this function *must* be called before `registerVerificationPipeline`! void setBackendAlgorithm(VerificationAlgorithm* backend) { assert(mBackendAlgorithm == nullptr && "Can register only one backend algorithm!"); mBackendAlgorithm.reset(backend); } /// Runs the registered LLVM pass pipeline. void run(); CheckRegistry& getChecks() { return mChecks; } LLVMFrontendSettings& getSettings() { return mSettings; } GazerContext& getContext() const { return mContext; } llvm::Module& getModule() const { return *mModule; } private: //---------------------- Individual pipeline steps ---------------------// void registerEnabledChecks(); void registerEarlyOptimizations(); void registerLateOptimizations(); void registerInlining(); void registerVerificationStep(); private: GazerContext& mContext; std::unique_ptr<llvm::Module> mModule; CheckRegistry mChecks; llvm::legacy::PassManager mPassManager; LLVMFrontendSettings& mSettings; std::unique_ptr<VerificationAlgorithm> mBackendAlgorithm = nullptr; std::unique_ptr<llvm::ToolOutputFile> mModuleOutput = nullptr; }; } #endif
ftsrg/gazer
test/verif/regression/error_block_br.c
// RUN: %bmc -bound 1 "%s" | FileCheck "%s" // CHECK: Verification FAILED // This test makes sure that even if a unifyFunctionExitNodes pass was run, // the error block detection in ModuleToAutomata works well. void __VERIFIER_error(); void exit(); int a; int b(c) { if (a) exit(0); __VERIFIER_error(); return 2; } int main() { int c = b(c); }
ftsrg/gazer
tools/gazer-bmc/Verifier/BoundedModelCheckerImpl.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SRC_VERIFIER_BOUNDEDMODELCHECKERIMPL_H #define GAZER_SRC_VERIFIER_BOUNDEDMODELCHECKERIMPL_H #include "gazer/Verifier/BoundedModelChecker.h" #include "gazer/Core/Expr/ExprEvaluator.h" #include "gazer/Core/Expr/ExprBuilder.h" #include "gazer/Core/Solver/Solver.h" #include "gazer/Core/Solver/Model.h" #include "gazer/Automaton/Cfa.h" #include "gazer/Trace/Trace.h" #include "gazer/Support/Stopwatch.h" #include "gazer/ADT/ScopedCache.h" #include <llvm/ADT/iterator.h> #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/DenseSet.h> #include <chrono> namespace gazer { namespace bmc { using PredecessorMapT = ScopedCache<Location*, ExprPtr>; class CexState { public: CexState(Location* location, Transition* incoming) : mLocation(location), mOutgoing(incoming) {} bool operator==(const CexState& rhs) const { return mLocation == rhs.mLocation && mOutgoing == rhs.mOutgoing; } Location* getLocation() const { return mLocation; } Transition* getOutgoingTransition() const { return mOutgoing; } private: Location* mLocation; Transition* mOutgoing; }; class BmcCex; class cex_iterator : public llvm::iterator_facade_base<cex_iterator, std::forward_iterator_tag, CexState> { public: cex_iterator(BmcCex& cex, CexState state) : mCex(cex), mState(state) {} bool operator==(const cex_iterator& rhs) const { return mState == rhs.mState; } const CexState& operator*() const { return mState; } CexState& operator*() { return mState; } cex_iterator &operator++() { this->advance(); return *this; } private: void advance(); private: BmcCex& mCex; CexState mState; }; class BmcCex { friend class cex_iterator; public: BmcCex(Location* start, Cfa& cfa, ExprEvaluator& eval, PredecessorMapT& preds) : mCfa(cfa), mStart(start), mEval(eval), mPredecessors(preds) { assert(start != nullptr); } cex_iterator begin() { return cex_iterator(*this, {mStart, nullptr}); } cex_iterator end() { return cex_iterator(*this, {nullptr, nullptr}); } private: Cfa& mCfa; Location* mStart; ExprEvaluator& mEval; PredecessorMapT& mPredecessors; }; } class BoundedModelCheckerImpl { struct CallInfo { ExprPtr overApprox = nullptr; std::vector<Cfa*> callChain; unsigned getCost() const { return std::count(callChain.begin(), callChain.end(), callChain.back()); } }; public: struct Stats { std::chrono::milliseconds SolverTime{0}; unsigned NumInlined = 0; unsigned NumBeginLocs = 0; unsigned NumEndLocs = 0; unsigned NumBeginLocals = 0; unsigned NumEndLocals = 0; }; BoundedModelCheckerImpl( AutomataSystem& system, ExprBuilder& builder, SolverFactory& solverFactory, TraceBuilder<Location*, std::vector<VariableAssignment>>& traceBuilder, BmcSettings settings ); std::unique_ptr<VerificationResult> check(); void printStats(llvm::raw_ostream& os); private: void createTopologicalSorts(); bool initializeErrorField(); void removeIrrelevantLocations(); void inlineCallIntoRoot( CallTransition* call, llvm::DenseMap<Variable*, Variable*>& vmap, const llvm::Twine& suffix, llvm::SmallVectorImpl<CallTransition*>& newCalls ); /// Finds the closest common (post-)dominating node for all call transitions. /// If no call transitions are present in the CFA, this function returns nullptr. std::pair<Location*, Location*> findCommonCallAncestor(Location* fwd, Location* bwd); std::function<size_t(Location*)> createLocNumberFunc(); void findOpenCallsInCex(Model& model, llvm::SmallVectorImpl<CallTransition*>& callsInCex); std::unique_ptr<VerificationResult> createFailResult(); void push() { mSolver->push(); mPredecessors.push(); } void pop() { mPredecessors.pop(); mSolver->pop(); } Solver::SolverStatus runSolver(); private: AutomataSystem& mSystem; ExprBuilder& mExprBuilder; std::unique_ptr<Solver> mSolver; TraceBuilder<Location*, std::vector<VariableAssignment>>& mTraceBuilder; BmcSettings mSettings; Cfa* mRoot; std::vector<Location*> mTopo; Location* mError = nullptr; llvm::DenseMap<Location*, size_t> mLocNumbers; llvm::DenseSet<CallTransition*> mOpenCalls; std::unordered_map<CallTransition*, CallInfo> mCalls; std::unordered_map<Cfa*, std::vector<Location*>> mTopoSortMap; bmc::PredecessorMapT mPredecessors; llvm::DenseMap<Location*, Location*> mInlinedLocations; llvm::DenseMap<Variable*, Variable*> mInlinedVariables; size_t mTmp = 0; Stats mStats; Stopwatch<> mTimer; Variable* mErrorFieldVariable = nullptr; }; std::unique_ptr<Trace> buildBmcTrace( const std::vector<Location*>& states, const std::vector<std::vector<VariableAssignment>>& actions ); } // end namespace gazer #endif
ftsrg/gazer
include/gazer/Core/Expr.h
//==- Expr.h - Core expression classes --------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// /// /// \file This file defines the different base classes for expressions. /// For implementing subclasses, see gazer/Core/ExprTypes.h and /// gazer/Core/LiteralExpr.h. /// //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPR_H #define GAZER_CORE_EXPR_H #include "gazer/Core/Type.h" #include "gazer/Core/Decl.h" #include "gazer/Core/ExprRef.h" #include <llvm/ADT/StringRef.h> #include <boost/intrusive_ptr.hpp> #include <memory> #include <string> namespace llvm { class raw_ostream; } // namespace llvm namespace gazer { class GazerContextImpl; /// \brief Base class for all gazer expressions. /// /// Expression subclass constructors are private. The intended way of /// instantiation is by using the static ::Create() functions /// of the subclasses or using an ExprBuilder. class Expr { friend class ExprStorage; friend class GazerContextImpl; public: // If you wish to add a new expression type, make sure to do the following: // (1) Update ExprKind.inc with the new kind. // (2) Update ExprKindPrimes in Expr.cpp with a new unique prime number. // (3) Create an implementation class. If you use a template, explicitly // instantiate it in Expr.cpp. // (4) If your implementation class is atomic or a non-trivial descendant of // NonNullaryExpr, update expr_hasher in GazerContextImpl.h with a specialization // for your implementation. // (5) Update the ExprWalker interface. Note that this also means the possible // update of their implementations (such as solvers). // Things will work without the following changes, but they are highly recommended: // (6) Add a corresponding method to ExprBuilder and ConstantFolder. enum ExprKind { #define GAZER_EXPR_KIND(KIND) KIND, #include "gazer/Core/Expr/ExprKind.def" #undef GAZER_EXPR_KIND }; // Atomic and literal expressions static constexpr int FirstAtomic = Undef; static constexpr int LastAtomic = Literal; // Unary operations and casts static constexpr int FirstUnary = Not; static constexpr int LastUnary = Extract; static constexpr int FirstUnaryCast = ZExt; static constexpr int LastUnaryCast = Extract; // Binary operations static constexpr int FirstBinaryArithmetic = Add; static constexpr int LastBinaryArithmetic = BvConcat; static constexpr int FirstBitLogic = Shl; static constexpr int LastBitLogic = BvConcat; // Logic and compare static constexpr int FirstLogic = And; static constexpr int LastLogic = Imply; static constexpr int FirstCompare = Eq; static constexpr int LastCompare = BvUGtEq; // Floats static constexpr int FirstFp = FIsNan; static constexpr int LastFp = FLtEq; static constexpr int FirstFpUnary = FIsNan; static constexpr int LastFpUnary = FpToBv; static constexpr int FirstFpArithmetic = FAdd; static constexpr int LastFpArithmetic = FDiv; static constexpr int FirstFpCompare = FEq; static constexpr int LastFpCompare = FLtEq; // Generic expressions static constexpr int FirstExprKind = Undef; static constexpr int LastExprKind = TupleConstruct; protected: Expr(ExprKind kind, Type& type); public: Expr(const Expr&) = delete; Expr& operator=(const Expr&) = delete; ExprKind getKind() const { return mKind; } Type& getType() const { return mType; } GazerContext& getContext() const { return mType.getContext(); } bool isUndef() const { return mKind == Undef; } bool isNullary() const { return mKind < FirstUnary; } bool isUnary() const { return (FirstUnary <= mKind && mKind <= LastUnary) || (FirstFpUnary <= mKind && mKind <= LastFpUnary); } bool isArithmetic() const { return FirstBinaryArithmetic <= mKind && mKind <= LastBinaryArithmetic; } bool isLogic() const { return FirstLogic <= mKind && mKind <= LastLogic; } bool isBitLogic() const { return FirstBitLogic <= mKind && mKind <= LastBitLogic; } bool isCompare() const { return FirstCompare <= mKind && mKind <= LastCompare; } bool isFloatingPoint() const { return FirstFp <= mKind && mKind <= LastFp; } bool isFpArithmetic() const { return FirstFpArithmetic <= mKind && mKind <= LastFpArithmetic; } bool isFpCompare() const { return FirstFpCompare <= mKind && mKind <= LastFpCompare; } bool hasSubclassData() const { return mKind == Extract || this->isFpArithmetic(); } static bool isCommutative(ExprKind kind); static bool isAssociative(ExprKind kind); /// Calculates a hash code for this expression. std::size_t getHashCode() const; virtual void print(llvm::raw_ostream& os) const = 0; virtual ~Expr() = default; static llvm::StringRef getKindName(ExprKind kind); private: static void DeleteExpr(Expr* expr); friend void intrusive_ptr_add_ref(Expr* expr) { expr->mRefCount++; } friend void intrusive_ptr_release(Expr* expr) { assert(expr->mRefCount > 0 && "Attempting to decrease a zero ref counter!"); if (--expr->mRefCount == 0) { Expr::DeleteExpr(expr); } } protected: const ExprKind mKind; Type& mType; private: mutable unsigned mRefCount; Expr* mNextPtr = nullptr; mutable size_t mHashCode = 0; }; using ExprVector = std::vector<ExprPtr>; template<class T = Expr> inline ExprRef<T> make_expr_ref(T* expr) { return ExprRef<T>(expr); } template<class ToT, class FromT> inline ExprRef<ToT> expr_cast(const ExprRef<FromT>& value) { assert(llvm::isa<ToT>(value)); return boost::static_pointer_cast<ToT>(value); } template<class ToT, class FromT> inline ExprRef<ToT> dyn_expr_cast(const ExprRef<FromT>& value) { return llvm::isa<ToT>(value.get()) ? boost::static_pointer_cast<ToT>(value) : nullptr; } llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Expr& expr); /// Expression base class for atomic expression values. /// Currently literals and undef values are considered as atomic. class AtomicExpr : public Expr { protected: AtomicExpr(Expr::ExprKind kind, Type& type) : Expr(kind, type) {} public: static bool classof(const Expr* expr) { return expr->getKind() >= FirstAtomic && expr->getKind() <= LastAtomic; } }; /// \brief Expression base class of literal expressions. /// /// Note that while Expr::Literal is used to indicate /// that an expression is literal, this class is abstract. /// To acquire the value stored in literals, use the literal /// subclasses (BvLiteralExpr, ...). class LiteralExpr : public AtomicExpr { protected: explicit LiteralExpr(Type& type) : AtomicExpr(Literal, type) {} public: static bool classof(const Expr* expr) { return expr->getKind() == Literal; } }; class VarRefExpr final : public Expr { friend class Variable; friend class ExprStorage; private: explicit VarRefExpr(Variable* variable); public: Variable& getVariable() const { return *mVariable; } void print(llvm::raw_ostream& os) const override; static bool classof(const Expr* expr) { return expr->getKind() == Expr::VarRef; } private: Variable* mVariable; }; /// Base class for all expressions holding one or more operands. class NonNullaryExpr : public Expr { friend class ExprStorage; protected: template<class InputIterator> NonNullaryExpr(ExprKind kind, Type& type, InputIterator begin, InputIterator end) : Expr(kind, type), mOperands(begin, end) { assert(!mOperands.empty() && "Non-nullary expressions must have at least one operand."); assert(std::none_of(begin, end, [](const ExprPtr& elem) { return elem == nullptr; }) && "Non-nullary expression operands cannot be null!" ); } public: void print(llvm::raw_ostream& os) const override; //---- Operand handling ----// using op_iterator = typename std::vector<ExprPtr>::iterator; using op_const_iterator = typename std::vector<ExprPtr>::const_iterator; op_iterator op_begin() { return mOperands.begin(); } op_iterator op_end() { return mOperands.end(); } op_const_iterator op_begin() const { return mOperands.begin(); } op_const_iterator op_end() const { return mOperands.end(); } llvm::iterator_range<op_iterator> operands() { return llvm::make_range(op_begin(), op_end()); } llvm::iterator_range<op_const_iterator> operands() const { return llvm::make_range(op_begin(), op_end()); } size_t getNumOperands() const { return mOperands.size(); } ExprPtr getOperand(size_t idx) const { return mOperands[idx]; } public: static bool classof(const Expr* expr) { return expr->getKind() >= FirstUnary; } static bool classof(const Expr& expr) { return expr.getKind() >= FirstUnary; } private: std::vector<ExprPtr> mOperands; }; } // end namespace gazer // Add support for llvm-related stuff namespace llvm { template<class T> struct simplify_type<gazer::ExprRef<T>> { typedef T* SimpleType; static SimpleType getSimplifiedValue(gazer::ExprRef<T> &Val) { return Val.get(); } }; template<class T> struct simplify_type<const gazer::ExprRef<T>> { typedef T* SimpleType; static SimpleType getSimplifiedValue(const gazer::ExprRef<T> &Val) { return Val.get(); } }; } // end namespace llvm #if BOOST_VERSION < 107400 // Boost 1.74 introduced std::hash specialization for smart pointers, but we officially support 1.70. namespace std { template<> struct hash<gazer::ExprPtr> { size_t operator()(const gazer::ExprPtr& expr) const { return std::hash<gazer::Expr*>{}(expr.get()); } }; template<class T> struct hash<gazer::ExprRef<T>> { size_t operator()(const gazer::ExprRef<T>& expr) const { return std::hash<gazer::Expr*>{}(expr.get()); } }; } // end namespace std #endif #endif
ftsrg/gazer
include/gazer/LLVM/Memory/ValueOrMemoryObject.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_MEMORY_VALUEORMEMORYOBJECT_H #define GAZER_LLVM_MEMORY_VALUEORMEMORYOBJECT_H #include <llvm/ADT/DenseMapInfo.h> #include <llvm/Support/Casting.h> #include <variant> namespace llvm { class Value; class raw_ostream; } namespace gazer { class MemoryObjectDef; /// A wrapper class which can either hold an LLVM IR value or a gazer memory object definition. class ValueOrMemoryObject { // Note: all of this probably could be done more easily by using DerivedUser in MemoryObject, // however this method seems less fragile, even if it introduces considerably more boilerplate. public: /* implicit */ ValueOrMemoryObject(const llvm::Value* value) : mVariant(value) {} /* implicit */ ValueOrMemoryObject(const MemoryObjectDef* def) : mVariant(def) {} ValueOrMemoryObject(const ValueOrMemoryObject&) = default; ValueOrMemoryObject& operator=(const ValueOrMemoryObject&) = default; // We do not provide conversion operators, as an unchecked conversion may lead to runtime errors. operator const llvm::Value*() = delete; operator const MemoryObjectDef*() = delete; bool isValue() const { return std::holds_alternative<const llvm::Value*>(mVariant); } bool isMemoryObjectDef() const { return std::holds_alternative<const MemoryObjectDef*>(mVariant); } bool operator==(const ValueOrMemoryObject& rhs) const { return mVariant == rhs.mVariant; } bool operator!=(const ValueOrMemoryObject& rhs) const { return mVariant != rhs.mVariant; } const llvm::Value* asValue() const { return std::get<const llvm::Value*>(mVariant); } const MemoryObjectDef* asMemoryObjectDef() const { return std::get<const MemoryObjectDef*>(mVariant); } bool hasName() const; /// Returns the name of the contained value or memory object std::string getName() const; private: std::variant<const llvm::Value*, const MemoryObjectDef*> mVariant; }; llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const ValueOrMemoryObject& rhs); } // end namespace gazer namespace llvm { // Some LLVM-specific magic to make DenseMap and isa<> work seamlessly with ValueOrMemoryObject. // Note that while custom isa<> works, currently there is no support for cast<> or dynamic_cast<>. template<> struct DenseMapInfo<gazer::ValueOrMemoryObject> { // Empty and tombstone will be represented by a variant holding an invalid Value pointer. static inline gazer::ValueOrMemoryObject getEmptyKey() { return DenseMapInfo<Value*>::getEmptyKey(); } static inline gazer::ValueOrMemoryObject getTombstoneKey() { return DenseMapInfo<Value*>::getTombstoneKey(); } static unsigned getHashValue(const gazer::ValueOrMemoryObject& val) { // This is a bit weird, but needed to get the pointer value from the variant properly. if (val.isValue()) { return DenseMapInfo<llvm::Value*>::getHashValue(val.asValue()); } return DenseMapInfo<gazer::MemoryObjectDef*>::getHashValue(val.asMemoryObjectDef()); } static bool isEqual(const gazer::ValueOrMemoryObject& lhs, const gazer::ValueOrMemoryObject& rhs) { return lhs == rhs; } }; template<class To> struct isa_impl<To, gazer::ValueOrMemoryObject, std::enable_if_t<std::is_base_of_v<Value, To>>> { static inline bool doit(const gazer::ValueOrMemoryObject& val) { if (!val.isValue()) { return false; } return To::classof(val.asValue()); } }; template<class To> struct isa_impl<To, gazer::ValueOrMemoryObject, std::enable_if_t<std::is_base_of_v<gazer::MemoryObjectDef, To>>> { static inline bool doit(const gazer::ValueOrMemoryObject& val) { if (!val.isMemoryObjectDef()) { return false; } return To::classof(val.asMemoryObjectDef()); } }; } // end namespace llvm #endif //GAZER_LLVM_MEMORY_VALUEORMEMORYOBJECT_H
ftsrg/gazer
test/theta/verif/base/loops1.c
<filename>test/theta/verif/base/loops1.c // RUN: %theta -memory=havoc "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL extern int __VERIFIER_nondet_int(void); int calculate(int x) { int aggr = 0, aggr2 = x; int i = 0, j = 0; while (i < x) { aggr = aggr + i; while (j < x / 2) { aggr = aggr * (j + 1); aggr2 = aggr2 - 1; } } return aggr + aggr2; } int main(void) { int i = 0; int c = __VERIFIER_nondet_int(); while (i < c) { calculate(i); ++i; } }
ftsrg/gazer
test/theta/verif/overflow/overflow_simple.c
// RUN: %theta -checks=signed-overflow "%s" | FileCheck "%s" // CHECK: Verification FAILED int __VERIFIER_nondet_int(); int main(void) { int x = __VERIFIER_nondet_int(); int y = __VERIFIER_nondet_int(); // CHECK: Signed integer overflow in {{.*}}overflow_simple.c at line [[# @LINE + 1]] column 14 return x + y; }
ftsrg/gazer
include/gazer/Core/ExprTypes.h
<filename>include/gazer/Core/ExprTypes.h //==- ExprTypes.h - Expression subclass implementations ---------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPRTYPES_H #define GAZER_CORE_EXPRTYPES_H #include "gazer/Core/Expr.h" #include <llvm/ADT/APInt.h> #include <llvm/ADT/APFloat.h> #include <llvm/ADT/iterator_range.h> #include <llvm/ADT/DenseMap.h> #include <llvm/Support/Casting.h> #include <cassert> #include <array> namespace gazer { /// Base class for all unary expression kinds. class UnaryExpr : public NonNullaryExpr { protected: using NonNullaryExpr::NonNullaryExpr; public: using NonNullaryExpr::getOperand; ExprPtr getOperand() const { return getOperand(0); } }; class NotExpr final : public UnaryExpr { friend class ExprStorage; protected: using UnaryExpr::UnaryExpr; protected: public: static ExprRef<NotExpr> Create(const ExprPtr& operand); static bool classof(const Expr* expr) { return expr->getKind() == Expr::Not; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::Not; } }; // Casts //----------------------------------------------------------------------------- template<Expr::ExprKind Kind> class ExtCastExpr final : public UnaryExpr { friend class ExprStorage; static_assert(Expr::FirstUnaryCast <= Kind && Kind <= Expr::LastUnaryCast, "A unary cast expression must have a unary cast expression kind."); private: using UnaryExpr::UnaryExpr; public: unsigned getExtendedWidth() const { return llvm::cast<BvType>(&getType())->getWidth(); } unsigned getWidthDiff() const { auto opType = llvm::cast<BvType>(&getOperand(0)->getType()); return getExtendedWidth() - opType->getWidth(); } static ExprRef<ExtCastExpr<Kind>> Create(const ExprPtr& operand, Type& type); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using ZExtExpr = ExtCastExpr<Expr::ZExt>; using SExtExpr = ExtCastExpr<Expr::SExt>; /// Represents an Extract expression. /// The parameter \p offset marks the lowest order bit of the return value, /// whereas \p offset+width-1 is the highest order bit. /// /// As an example Extract(2#1111011, 0, 1) == 1, Extract(2#1111010, 0, 1) == 0. class ExtractExpr final : public UnaryExpr { // Needed for ExprStorage to call this constructor. friend class ExprStorage; protected: template<class InputIterator> ExtractExpr(ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned offset, unsigned width) : UnaryExpr(kind, type, begin, end), mOffset(offset), mWidth(width) {} public: unsigned getExtractedWidth() const { return llvm::cast<BvType>(&getType())->getWidth(); } unsigned getOffset() const { return mOffset; } unsigned getWidth() const { return mWidth; } void print(llvm::raw_ostream& os) const override; static ExprRef<ExtractExpr> Create(const ExprPtr& operand, unsigned offset, unsigned width); static bool classof(const Expr* expr) { return expr->getKind() == Expr::Extract; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::Extract; } private: unsigned mOffset; unsigned mWidth; }; /// Base class for all binary expressions. class BinaryExpr : public NonNullaryExpr { protected: using NonNullaryExpr::NonNullaryExpr; public: ExprPtr getLeft() const { return getOperand(0); } ExprPtr getRight() const { return getOperand(1); } }; /// Base template for all binary arithmetic expressions. template<Expr::ExprKind Kind> class ArithmeticExpr final : public BinaryExpr { static_assert(Expr::FirstBinaryArithmetic <= Kind && Kind <= Expr::LastBinaryArithmetic, "An arithmetic expression must have an arithmetic expression kind."); friend class ExprStorage; protected: using BinaryExpr::BinaryExpr; public: static ExprRef<ArithmeticExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right); /** * Type inquiry support. */ static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using AddExpr = ArithmeticExpr<Expr::Add>; using SubExpr = ArithmeticExpr<Expr::Sub>; using MulExpr = ArithmeticExpr<Expr::Mul>; using DivExpr = ArithmeticExpr<Expr::Div>; using ModExpr = ArithmeticExpr<Expr::Mod>; using RemExpr = ArithmeticExpr<Expr::Rem>; using BvSDivExpr = ArithmeticExpr<Expr::BvSDiv>; using BvUDivExpr = ArithmeticExpr<Expr::BvUDiv>; using BvSRemExpr = ArithmeticExpr<Expr::BvSRem>; using BvURemExpr = ArithmeticExpr<Expr::BvURem>; using ShlExpr = ArithmeticExpr<Expr::Shl>; using LShrExpr = ArithmeticExpr<Expr::LShr>; using AShrExpr = ArithmeticExpr<Expr::AShr>; using BvAndExpr = ArithmeticExpr<Expr::BvAnd>; using BvOrExpr = ArithmeticExpr<Expr::BvOr>; using BvXorExpr = ArithmeticExpr<Expr::BvXor>; using BvConcatExpr = ArithmeticExpr<Expr::BvConcat>; template<Expr::ExprKind Kind> class CompareExpr final : public BinaryExpr { static_assert(Expr::FirstCompare <= Kind && Kind <= Expr::LastCompare, "A compare expression must have a compare expression kind."); friend class ExprStorage; protected: using BinaryExpr::BinaryExpr; public: static ExprRef<CompareExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using EqExpr = CompareExpr<Expr::Eq>; using NotEqExpr = CompareExpr<Expr::NotEq>; using LtExpr = CompareExpr<Expr::Lt>; using LtEqExpr = CompareExpr<Expr::LtEq>; using GtExpr = CompareExpr<Expr::Gt>; using GtEqExpr = CompareExpr<Expr::GtEq>; using BvSLtExpr = CompareExpr<Expr::BvSLt>; using BvSLtEqExpr = CompareExpr<Expr::BvSLtEq>; using BvSGtExpr = CompareExpr<Expr::BvSGt>; using BvSGtEqExpr = CompareExpr<Expr::BvSGtEq>; using BvULtExpr = CompareExpr<Expr::BvULt>; using BvULtEqExpr = CompareExpr<Expr::BvULtEq>; using BvUGtExpr = CompareExpr<Expr::BvUGt>; using BvUGtEqExpr = CompareExpr<Expr::BvUGtEq>; template<Expr::ExprKind Kind> class MultiaryLogicExpr final : public NonNullaryExpr { static_assert(Expr::And == Kind || Expr::Or == Kind, "A logic expression must have a logic expression kind."); friend class ExprStorage; protected: using NonNullaryExpr::NonNullaryExpr; public: static ExprRef<MultiaryLogicExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right); static ExprRef<MultiaryLogicExpr<Kind>> Create(const ExprVector& ops); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using AndExpr = MultiaryLogicExpr<Expr::And>; using OrExpr = MultiaryLogicExpr<Expr::Or>; template<Expr::ExprKind Kind> class BinaryLogicExpr final : public BinaryExpr { friend class ExprStorage; protected: using BinaryExpr::BinaryExpr; public: static ExprRef<BinaryLogicExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using ImplyExpr = BinaryLogicExpr<Expr::Imply>; // Floating-point //----------------------------------------------------------------------------- template<Expr::ExprKind Kind> class FpQueryExpr final : public UnaryExpr { static_assert(Kind == Expr::FIsNan || Kind == Expr::FIsInf, "A floating point query expression must be FIsNan or FIsInf."); friend class ExprStorage; protected: using UnaryExpr::UnaryExpr; public: static ExprRef<FpQueryExpr<Kind>> Create(const ExprPtr& operand); }; using FIsNanExpr = FpQueryExpr<Expr::FIsNan>; using FIsInfExpr = FpQueryExpr<Expr::FIsInf>; namespace detail { /// Helper class to deal with all floating-point expressions which store a rounding mode. class FpExprWithRoundingMode { public: explicit FpExprWithRoundingMode(const llvm::APFloat::roundingMode& rm) : mRoundingMode(rm) {} [[nodiscard]] llvm::APFloat::roundingMode getRoundingMode() const { return mRoundingMode; } protected: llvm::APFloat::roundingMode mRoundingMode; }; } // end namespace detail template<Expr::ExprKind Kind> class BvFpCastExpr final : public UnaryExpr, public detail::FpExprWithRoundingMode { static_assert(Kind >= Expr::FCast && Kind <= Expr::FpToUnsigned, "A BvFpCastExpr must have a Bv-to-Fp or Fp-to-Bv cast kind."); friend class ExprStorage; private: template<class InputIterator> BvFpCastExpr(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, const llvm::APFloat::roundingMode& rm) : UnaryExpr(kind, type, begin, end), FpExprWithRoundingMode(rm) {} public: static ExprRef<BvFpCastExpr<Kind>> Create(const ExprPtr& operand, Type& type, const llvm::APFloat::roundingMode& rm); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using FCastExpr = BvFpCastExpr<Expr::FCast>; using SignedToFpExpr = BvFpCastExpr<Expr::SignedToFp>; using UnsignedToFpExpr = BvFpCastExpr<Expr::UnsignedToFp>; using FpToSignedExpr = BvFpCastExpr<Expr::FpToSigned>; using FpToUnsignedExpr = BvFpCastExpr<Expr::FpToUnsigned>; template<Expr::ExprKind Kind> class BitCastExpr final : public UnaryExpr { static_assert(Kind >= Expr::FpToBv && Kind <= Expr::BvToFp, "BitCast expressions can only be FpToBv or BvToFp!"); friend class ExprStorage; private: template<class InputIterator> BitCastExpr(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end) : UnaryExpr(kind, type, begin, end) {} public: static ExprRef<BitCastExpr<Kind>> Create(const ExprPtr& operand, Type& type); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using FpToBvExpr = BitCastExpr<Expr::FpToBv>; using BvToFpExpr = BitCastExpr<Expr::BvToFp>; template<Expr::ExprKind Kind> class FpArithmeticExpr final : public BinaryExpr, public detail::FpExprWithRoundingMode { static_assert(Expr::FirstFpArithmetic <= Kind && Kind <= Expr::LastFpArithmetic, "An arithmetic expression must have an floating-point arithmetic expression kind."); // Needed for ExprStorage to call this constructor. friend class ExprStorage; protected: template<class InputIterator> FpArithmeticExpr(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, const llvm::APFloat::roundingMode& rm) : BinaryExpr(kind, type, begin, end), FpExprWithRoundingMode(rm) {} public: static ExprRef<FpArithmeticExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right, const llvm::APFloat::roundingMode& rm); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using FAddExpr = FpArithmeticExpr<Expr::FAdd>; using FSubExpr = FpArithmeticExpr<Expr::FSub>; using FMulExpr = FpArithmeticExpr<Expr::FMul>; using FDivExpr = FpArithmeticExpr<Expr::FDiv>; template<Expr::ExprKind Kind> class FpCompareExpr final : public BinaryExpr { static_assert(Expr::FirstFpCompare <= Kind && Kind <= Expr::LastFpCompare, "A compare expression must have a compare expression kind."); friend class ExprStorage; protected: using BinaryExpr::BinaryExpr; public: static ExprRef<FpCompareExpr<Kind>> Create(const ExprPtr& left, const ExprPtr& right); static bool classof(const Expr* expr) { return expr->getKind() == Kind; } static bool classof(const Expr& expr) { return expr.getKind() == Kind; } }; using FEqExpr = FpCompareExpr<Expr::FEq>; using FGtExpr = FpCompareExpr<Expr::FGt>; using FGtEqExpr = FpCompareExpr<Expr::FGtEq>; using FLtExpr = FpCompareExpr<Expr::FLt>; using FLtEqExpr = FpCompareExpr<Expr::FLtEq>; class SelectExpr final : public NonNullaryExpr { friend class ExprStorage; protected: using NonNullaryExpr::NonNullaryExpr; public: static ExprRef<SelectExpr> Create(const ExprPtr& condition, const ExprPtr& then, const ExprPtr& elze); ExprPtr getCondition() const { return getOperand(0); } ExprPtr getThen() const { return getOperand(1); } ExprPtr getElse() const { return getOperand(2); } static bool classof(const Expr* expr) { return expr->getKind() == Expr::Select; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::Select; } }; // Composite type expressions //==------------------------------------------------------------------------==// class ArrayReadExpr final : public NonNullaryExpr { friend class ExprStorage; protected: using NonNullaryExpr::NonNullaryExpr; public: static ExprRef<ArrayReadExpr> Create(const ExprPtr& array, const ExprPtr& index); ExprRef<VarRefExpr> getArrayRef() const { return llvm::cast<VarRefExpr>(getOperand(0)); } ExprPtr getIndex() const { return getOperand(1); } static bool classof(const Expr* expr) { return expr->getKind() == Expr::ArrayRead; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::ArrayRead; } }; class ArrayWriteExpr final : public NonNullaryExpr { friend class ExprStorage; protected: using NonNullaryExpr::NonNullaryExpr; public: static ExprRef<ArrayWriteExpr> Create(const ExprPtr& array, const ExprPtr& index, const ExprPtr& value); ExprPtr getIndex() const { return getOperand(1); } ExprPtr getElementValue() const { return getOperand(2); } static bool classof(const Expr* expr) { return expr->getKind() == Expr::ArrayWrite; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::ArrayWrite; } }; class TupleSelectExpr final : public UnaryExpr { friend class ExprStorage; protected: template<class InputIterator> TupleSelectExpr(ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned index) : UnaryExpr(kind, type, begin, end), mIndex(index) {} public: static ExprRef<TupleSelectExpr> Create(const ExprPtr& tuple, unsigned index); unsigned getIndex() const { return mIndex; } static bool classof(const Expr* expr) { return expr->getKind() == Expr::TupleSelect; } static bool classof(const Expr& expr) { return expr.getKind() == Expr::TupleSelect; } private: unsigned mIndex; }; class TupleConstructExpr : public NonNullaryExpr { friend class ExprStorage; protected: using NonNullaryExpr::NonNullaryExpr; public: TupleType& getType() const { return llvm::cast<TupleType>(mType); } static ExprRef<TupleConstructExpr> Create(TupleType& type, const ExprVector& exprs); template<class... Args> static ExprRef<TupleConstructExpr> Create(TupleType& type, Args&&... args) { return Create(type, {args...}); } static bool classof(const Expr* expr) { return expr->getKind() == TupleConstruct; } static bool classof(const Expr& expr) { return classof(&expr); } }; } // end namespace gazer #endif
ftsrg/gazer
include/gazer/ADT/StringUtils.h
<filename>include/gazer/ADT/StringUtils.h<gh_stars>1-10 //==- StringUtils.h ---------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_ADT_STRINGUTILS_H #define GAZER_ADT_STRINGUTILS_H #include <llvm/ADT/STLExtras.h> #include <llvm/Support/raw_ostream.h> namespace gazer { template<class ValueT> std::string value_to_string(const ValueT& value) { std::string buffer; llvm::raw_string_ostream rso(buffer); rso << value; rso.flush(); return rso.str(); } template< class Range, class Iterator = decltype(std::declval<Range>().begin()), class ValueT = decltype(*std::declval<Iterator>()), class ResultIterator = llvm::mapped_iterator<Iterator, std::function<std::string(ValueT&)>> > llvm::iterator_range<ResultIterator> to_string_range(Range&& range) { std::function<std::string(ValueT&)> toString = [](ValueT& value) -> std::string { std::string buffer; llvm::raw_string_ostream rso(buffer); rso << value; rso.flush(); return rso.str(); }; auto begin = llvm::map_iterator(range.begin(), toString); auto end = llvm::map_iterator(range.end(), toString); return llvm::make_range(begin, end); } template< class StreamT, class Iterator > void join_print(StreamT& os, Iterator begin, Iterator end, llvm::StringRef separator) { if (begin == end) { return; } os << *begin; while (++begin != end) { os << separator; os << (*begin); } } template<class StreamT, class Iterator, class Function> void join_print_as(StreamT& os, Iterator begin, Iterator end, llvm::StringRef separator, Function func) { if (begin == end) { return; } func(os, *begin); while (++begin != end) { os << separator; func(os, *begin); } } } #endif
ftsrg/gazer
test/theta/verif/memory/globals1.c
// RUN: %theta "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); int a = 0, b = 1; int main(void) { a = __VERIFIER_nondet_int(); b = a + 1; if (a > b) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
include/gazer/Trace/Location.h
<reponame>ftsrg/gazer //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_TRACE_LOCATION_H #define GAZER_TRACE_LOCATION_H #include <string> namespace gazer { class LocationInfo { public: LocationInfo(unsigned int line = 0, unsigned int column = 0, std::string fileName = "") : mLine(line), mColumn(column), mFileName(fileName) {} LocationInfo(const LocationInfo&) = default; LocationInfo& operator=(const LocationInfo&) = default; int getLine() const { return mLine; } int getColumn() const { return mColumn; } std::string getFileName() const { return mFileName; } private: int mLine; int mColumn; std::string mFileName; }; } #endif
ftsrg/gazer
include/gazer/LLVM/Instrumentation/Intrinsics.h
<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// /// \file This file describes the various intrinsic functions that /// Gazer uses for instrumentation. #ifndef _GAZER_LLVM_INSTRUMENTATION_INTRINSICS_H #define _GAZER_LLVM_INSTRUMENTATION_INTRINSICS_H #include <llvm/IR/Instructions.h> #include <llvm/IR/DebugInfoMetadata.h> #include <string_view> namespace gazer { class GazerIntrinsic { public: static constexpr char FunctionEntryPrefix[] = "gazer.function.entry"; static constexpr char FunctionReturnVoidName[] = "gazer.function.return_void"; static constexpr char FunctionCallReturnedName[] = "gazer.function.call_returned"; static constexpr char FunctionReturnValuePrefix[] = "gazer.function.return_value."; static constexpr char InlinedGlobalWritePrefix[] = "gazer.inlined_global.write."; static constexpr char NoOverflowPrefix[] = "gazer.no_overflow"; static constexpr char SAddNoOverflowPrefix[] = "gazer.no_overflow.sadd."; static constexpr char SSubNoOverflowPrefix[] = "gazer.no_overflow.ssub."; static constexpr char SMulNoOverflowPrefix[] = "gazer.no_overflow.smul."; static constexpr char SDivNoOverflowPrefix[] = "gazer.no_overflow.sdiv."; static constexpr char UAddNoOverflowPrefix[] = "gazer.no_overflow.uadd."; static constexpr char USubNoOverflowPrefix[] = "gazer.no_overflow.usub."; static constexpr char UMulNoOverflowPrefix[] = "gazer.no_overflow.umul."; enum class Overflow { SAdd, UAdd, SSub, USub, SMul, UMul }; public: static llvm::CallInst* CreateInlinedGlobalWrite(llvm::Value* value, llvm::DIGlobalVariable* gv); static llvm::CallInst* CreateFunctionEntry(llvm::Module& module, llvm::DISubprogram* dsp = nullptr); public: /// Returns a 'gazer.function.entry(metadata fn_name, args...)' intrinsic. static llvm::FunctionCallee GetOrInsertFunctionEntry(llvm::Module& module, llvm::ArrayRef<llvm::Type*> args); /// Returns a 'gazer.function.return_void(metadata fn_name)' intrinsic. static llvm::FunctionCallee GetOrInsertFunctionReturnVoid(llvm::Module& module); /// Returns a 'gazer.function.call_returned(metadata fn_name)' intrinsic. static llvm::FunctionCallee GetOrInsertFunctionCallReturned(llvm::Module& module); /// Returns a 'gazer.function.return_value.T(metadata fn_name, T retval)' intrinsic, /// where 'T' is the given return type. static llvm::FunctionCallee GetOrInsertFunctionReturnValue(llvm::Module& module, llvm::Type* type); /// Returns a 'gazer.inlined_global_write.T(T value, metadata gv_name)' intrinsic. static llvm::FunctionCallee GetOrInsertInlinedGlobalWrite(llvm::Module& module, llvm::Type* type); /// Returns a 'gazer.KIND.no_overflow.T(T left, T right)' intrinsic. static llvm::FunctionCallee GetOrInsertOverflowCheck(llvm::Module& module, Overflow kind, llvm::Type* type); }; } #endif
ftsrg/gazer
include/gazer/Core/Solver/Model.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_MODEL_H #define GAZER_CORE_MODEL_H #include "gazer/Core/Expr/ExprEvaluator.h" namespace gazer { class LiteralExpr; class Model : public ExprEvaluator { public: // Inherited from ExprEvaluator: virtual ExprRef<AtomicExpr> evaluate(const ExprPtr& expr) = 0; virtual ~Model() = default; virtual void dump(llvm::raw_ostream& os) = 0; }; } #endif
ftsrg/gazer
src/LLVM/Transform/TransformUtils.h
<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #include <llvm/Analysis/CallGraph.h> namespace gazer { /// Returns true if the given call graph node represents a recursive function. /// This function does not take dynamic properties (e.g. function pointers) /// into account. bool isRecursive(llvm::CallGraphNode* target); }
ftsrg/gazer
scripts/portfolio/test-tasks/zerodiv_example.c
#include <stdio.h> extern int ioread32(void); int main(void) { int k = ioread32(); int i = 0; int j = k + 5; while (i < 3) { i = i + 1; j = j + 3; } k = k / (i - j); printf("%d\n", k); return 0; }
ftsrg/gazer
test/verif/regression/multiple_inf_loop.c
<reponame>ftsrg/gazer<gh_stars>1-10 // RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} // This test failed due to an erroneous handling of LLVM's loop information // in the ModuleToAutomataPass long a; int c() { int b; for (; b;) a = b; return a; } int main() { c(); for (;;) c(); }
ftsrg/gazer
test/verif/regression/math_int1_fail.c
// RUN: %bmc -bound 1 -math-int "%s" | FileCheck "%s" // CHECK: Verification FAILED int a, b = 5; void __VERIFIER_error(); int main() { while (1) { if (b == 5 || b == 6) b = a = 4; if (a) __VERIFIER_error(); } }
ftsrg/gazer
include/gazer/Support/Math.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SUPPORT_MATH_H #define GAZER_SUPPORT_MATH_H namespace gazer::math { /// Calculates the power of two integers and returns an int. /// Does not account for overflow and does not work for negative exponents. unsigned ipow(unsigned base, unsigned exp) { if (exp == 0) { return 1; } if (exp == 1) { return base; } unsigned tmp = ipow(base, exp / 2); if (exp % 2 == 0) { return tmp * tmp; } return base * tmp * tmp; } } #endif
ftsrg/gazer
test/verif/regression/floats/float_trace_crash.c
// RUN: %bmc -trace "%s" | FileCheck "%s" // CHECK: Verification FAILED int b; void __VERIFIER_error(); float a(); int main() { float c = a(); b = c != c; // CHECK: b := 0 if (!b) __VERIFIER_error(); }
ftsrg/gazer
test/verif/floats/float_mul_fail.c
<filename>test/verif/floats/float_mul_fail.c // RUN: %bmc -bound 1 "%s" | FileCheck "%s" // CHECK: Verification FAILED extern void __VERIFIER_error(void); extern float __VERIFIER_nondet_float(void); extern double __VERIFIER_nondet_double(void); int main(void) { float x = __VERIFIER_nondet_float(); float y = __VERIFIER_nondet_float(); float mul1 = x * x * y; float mul2 = x * (x * y); if (mul1 != mul2) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
src/SolverZ3/Z3SolverImpl.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SRC_SOLVERZ3_Z3SOLVERIMPL_H #define GAZER_SRC_SOLVERZ3_Z3SOLVERIMPL_H #include "gazer/Z3Solver/Z3Solver.h" #include "gazer/Core/Expr/ExprWalker.h" #include "gazer/ADT/ScopedCache.h" #include <llvm/Support/raw_ostream.h> #include <z3++.h> namespace gazer { // Implementation based upon Z3NodeHandle in the KLEE project: // https://github.com/klee/klee/blob/master/lib/Solver/Z3Builder.h template<class T> class Z3Handle { public: Z3Handle() = default; Z3Handle(Z3_context context, T ast) : mContext(context), mNode(ast) { assert(context != nullptr); assert(ast != nullptr); Z3_inc_ref(mContext, as_ast()); } Z3Handle(const Z3Handle& other) : mContext(other.mContext), mNode(other.mNode) { if (mContext != nullptr && mNode != nullptr) { Z3_inc_ref(mContext, as_ast()); } } Z3Handle(Z3Handle&& other) noexcept : mContext(other.mContext), mNode(other.mNode) { other.mContext = nullptr; other.mNode = nullptr; } Z3Handle& operator=(const Z3Handle& other) { if (this != &other) { if (mContext == nullptr && mNode == nullptr) { mContext = other.mContext; } assert(mContext == other.mContext); // If the node is not null then the context should not be null either. assert(mNode == nullptr || mContext != nullptr); if (mContext != nullptr && mNode != nullptr) { Z3_dec_ref(mContext, as_ast()); } mNode = other.mNode; if (mContext != nullptr && mNode != nullptr) { Z3_inc_ref(mContext, as_ast()); } } return *this; } Z3Handle& operator=(Z3Handle&& other) noexcept { if (this != &other) { if (mContext != nullptr && mNode != nullptr) { Z3_dec_ref(mContext, as_ast()); } mContext = other.mContext; mNode = other.mNode; other.mContext = nullptr; other.mNode = nullptr; } return *this; } bool operator==(const Z3Handle<T>& rhs) const { return rhs.mContext == mContext && rhs.mNode == mNode; } bool operator!=(const Z3Handle<T>& rhs) const { return !operator==(rhs); } /*implicit*/ operator T() { assert(mContext != nullptr); assert(mNode != nullptr); return mNode; } Z3_context getContext() const { return mContext; } T getNode() const { return mNode; } ~Z3Handle() { if (mContext != nullptr && mNode != nullptr) { Z3_dec_ref(mContext, as_ast()); } } private: // Must be specialized inline ::Z3_ast as_ast(); private: Z3_context mContext = nullptr; T mNode = nullptr; }; template<> inline Z3_ast Z3Handle<Z3_sort>::as_ast() { return Z3_sort_to_ast(mContext, mNode); } template<> inline Z3_ast Z3Handle<Z3_ast>::as_ast() { return mNode; } template<> inline Z3_ast Z3Handle<Z3_func_decl>::as_ast() { return Z3_func_decl_to_ast(mContext, mNode); } } // end namespace gazer // Provide a hash implementation for the AST handle namespace std { template<class T> struct hash<gazer::Z3Handle<T>> { std::size_t operator()(const gazer::Z3Handle<T>& key) const { return llvm::hash_combine(key.getContext(), key.getNode()); } }; } // end namespace std namespace gazer { using Z3AstHandle = Z3Handle<Z3_ast>; using Z3CacheMapTy = ScopedCache<ExprPtr, Z3AstHandle, std::unordered_map<ExprPtr, Z3AstHandle>>; using Z3DeclMapTy = ScopedCache< Variable*, Z3Handle<Z3_func_decl>, std::unordered_map<Variable*, Z3Handle<Z3_func_decl>> >; /// Translates expressions into Z3 nodes. class Z3ExprTransformer : public ExprWalker<Z3ExprTransformer, Z3AstHandle> { friend class ExprWalker<Z3ExprTransformer, Z3AstHandle>; struct TupleInfo { Z3Handle<Z3_sort> sort; Z3Handle<Z3_func_decl> constructor; std::vector<Z3Handle<Z3_func_decl>> projections; }; public: Z3ExprTransformer( Z3_context& context, unsigned& tmpCount, Z3CacheMapTy& cache, Z3DeclMapTy& decls ) : mZ3Context(context), mTmpCount(tmpCount), mCache(cache), mDecls(decls) {} /// Free up all data owned by this object. void clear() { mTupleInfo.clear(); } protected: Z3AstHandle createHandle(Z3_ast ast); Z3Handle<Z3_sort> typeToSort(Type& type); Z3Handle<Z3_sort> handleTupleType(TupleType& tupType); Z3Handle<Z3_func_decl> translateDecl(Variable* variable); Z3AstHandle translateLiteral(const ExprRef<LiteralExpr>& expr); private: bool shouldSkip(const ExprPtr& expr, Z3AstHandle* ret); void handleResult(const ExprPtr& expr, Z3AstHandle& ret); Z3AstHandle visitExpr(const ExprPtr& expr) // NOLINT(readability-convert-member-functions-to-static) { llvm::errs() << *expr << "\n"; llvm_unreachable("Unhandled expression type in Z3ExprTransformer."); } // Use some helper macros to translate trivial cases #define TRANSLATE_UNARY_OP(NAME, Z3_METHOD) \ Z3AstHandle visit##NAME(const ExprRef<NAME##Expr>& expr) { \ return createHandle(Z3_METHOD(mZ3Context, getOperand(0))); \ } \ #define TRANSLATE_BINARY_OP(NAME, Z3_METHOD) \ Z3AstHandle visit##NAME(const ExprRef<NAME##Expr>& expr) { \ return createHandle(Z3_METHOD(mZ3Context, getOperand(0), getOperand(1))); \ } \ #define TRANSLATE_TERNARY_OP(NAME, Z3_METHOD) \ Z3AstHandle visit##NAME(const ExprRef<NAME##Expr>& expr) { \ return createHandle(Z3_METHOD( \ mZ3Context, getOperand(0), getOperand(1), getOperand(2))); \ } \ #define TRANSLATE_BINARY_FPA_RM(NAME, Z3_METHOD) \ Z3AstHandle visit##NAME(const ExprRef<NAME##Expr>& expr) { \ return createHandle(Z3_METHOD(mZ3Context, \ transformRoundingMode(expr->getRoundingMode()), \ getOperand(0), getOperand(1) \ )); \ } \ // Nullary Z3AstHandle visitVarRef(const ExprRef<VarRefExpr>& expr); Z3AstHandle visitUndef(const ExprRef<UndefExpr>& expr) { return createHandle(Z3_mk_fresh_const(mZ3Context, "", typeToSort(expr->getType()))); } Z3AstHandle visitLiteral(const ExprRef<LiteralExpr>& expr) { return this->translateLiteral(expr); } // Unary logic TRANSLATE_UNARY_OP(Not, Z3_mk_not) // Arithmetic operators Z3AstHandle visitAdd(const ExprRef<AddExpr>& expr); Z3AstHandle visitSub(const ExprRef<SubExpr>& expr); Z3AstHandle visitMul(const ExprRef<MulExpr>& expr); TRANSLATE_BINARY_OP(Div, Z3_mk_div) TRANSLATE_BINARY_OP(Mod, Z3_mk_mod) TRANSLATE_BINARY_OP(Rem, Z3_mk_rem) // Binary logic TRANSLATE_BINARY_OP(Imply, Z3_mk_implies) // Multiary logic Z3AstHandle visitAnd(const ExprRef<AndExpr>& expr); Z3AstHandle visitOr(const ExprRef<OrExpr>& expr); // Bit-vectors TRANSLATE_BINARY_OP(BvSDiv, Z3_mk_bvsdiv) TRANSLATE_BINARY_OP(BvUDiv, Z3_mk_bvudiv) TRANSLATE_BINARY_OP(BvSRem, Z3_mk_bvsrem) TRANSLATE_BINARY_OP(BvURem, Z3_mk_bvurem) TRANSLATE_BINARY_OP(Shl, Z3_mk_bvshl) TRANSLATE_BINARY_OP(LShr, Z3_mk_bvlshr) TRANSLATE_BINARY_OP(AShr, Z3_mk_bvashr) TRANSLATE_BINARY_OP(BvAnd, Z3_mk_bvand) TRANSLATE_BINARY_OP(BvOr, Z3_mk_bvor) TRANSLATE_BINARY_OP(BvXor, Z3_mk_bvxor) TRANSLATE_BINARY_OP(BvConcat, Z3_mk_concat) // Comparisons TRANSLATE_BINARY_OP(Eq, Z3_mk_eq) TRANSLATE_BINARY_OP(Lt, Z3_mk_lt) TRANSLATE_BINARY_OP(LtEq, Z3_mk_le) TRANSLATE_BINARY_OP(Gt, Z3_mk_gt) TRANSLATE_BINARY_OP(GtEq, Z3_mk_ge) Z3AstHandle visitNotEq(const ExprRef<NotEqExpr>& expr); // Bit-vector comparisons TRANSLATE_BINARY_OP(BvSLt, Z3_mk_bvslt) TRANSLATE_BINARY_OP(BvSLtEq, Z3_mk_bvsle) TRANSLATE_BINARY_OP(BvSGt, Z3_mk_bvsgt) TRANSLATE_BINARY_OP(BvSGtEq, Z3_mk_bvsge) TRANSLATE_BINARY_OP(BvULt, Z3_mk_bvult) TRANSLATE_BINARY_OP(BvULtEq, Z3_mk_bvule) TRANSLATE_BINARY_OP(BvUGt, Z3_mk_bvugt) TRANSLATE_BINARY_OP(BvUGtEq, Z3_mk_bvuge) // Floating-point queries TRANSLATE_UNARY_OP(FIsNan, Z3_mk_fpa_is_nan) TRANSLATE_UNARY_OP(FIsInf, Z3_mk_fpa_is_infinite) // Floating-point compare TRANSLATE_BINARY_OP(FEq, Z3_mk_fpa_eq) TRANSLATE_BINARY_OP(FGt, Z3_mk_fpa_gt) TRANSLATE_BINARY_OP(FGtEq, Z3_mk_fpa_geq) TRANSLATE_BINARY_OP(FLt, Z3_mk_fpa_lt) TRANSLATE_BINARY_OP(FLtEq, Z3_mk_fpa_leq) // Floating-point arithmetic TRANSLATE_BINARY_FPA_RM(FAdd, Z3_mk_fpa_add) TRANSLATE_BINARY_FPA_RM(FMul, Z3_mk_fpa_mul) TRANSLATE_BINARY_FPA_RM(FSub, Z3_mk_fpa_sub) TRANSLATE_BINARY_FPA_RM(FDiv, Z3_mk_fpa_div) // ITE expression TRANSLATE_TERNARY_OP(Select, Z3_mk_ite) // Arrays TRANSLATE_BINARY_OP(ArrayRead, Z3_mk_select) TRANSLATE_TERNARY_OP(ArrayWrite, Z3_mk_store) #undef TRANSLATE_UNARY_OP #undef TRANSLATE_BINARY_OP #undef TRANSLATE_TERNARY_OP #undef TRANSLATE_BINARY_FPA_RM // Bit-vector casts Z3AstHandle visitZExt(const ExprRef<ZExtExpr>& expr) { return createHandle(Z3_mk_zero_ext(mZ3Context, expr->getWidthDiff(), getOperand(0))); } Z3AstHandle visitSExt(const ExprRef<SExtExpr>& expr) { return createHandle(Z3_mk_sign_ext(mZ3Context, expr->getWidthDiff(), getOperand(0))); } Z3AstHandle visitExtract(const ExprRef<ExtractExpr>& expr) { unsigned hi = expr->getOffset() + expr->getWidth() - 1; unsigned lo = expr->getOffset(); return createHandle(Z3_mk_extract(mZ3Context, hi, lo, getOperand(0))); } // Floating-point casts Z3AstHandle visitFCast(const ExprRef<FCastExpr>& expr) { return createHandle(Z3_mk_fpa_to_fp_float(mZ3Context, transformRoundingMode(expr->getRoundingMode()), getOperand(0), typeToSort(expr->getType()) )); } Z3AstHandle visitSignedToFp(const ExprRef<SignedToFpExpr>& expr) { return createHandle(Z3_mk_fpa_to_fp_signed(mZ3Context, transformRoundingMode(expr->getRoundingMode()), getOperand(0), typeToSort(expr->getType()) )); } Z3AstHandle visitUnsignedToFp(const ExprRef<UnsignedToFpExpr>& expr) { return createHandle(Z3_mk_fpa_to_fp_unsigned(mZ3Context, transformRoundingMode(expr->getRoundingMode()), getOperand(0), typeToSort(expr->getType()) )); } Z3AstHandle visitFpToSigned(const ExprRef<FpToSignedExpr>& expr) { return createHandle(Z3_mk_fpa_to_sbv(mZ3Context, transformRoundingMode(expr->getRoundingMode()), getOperand(0), llvm::cast<BvType>(&expr->getType())->getWidth() )); } Z3AstHandle visitFpToUnsigned(const ExprRef<FpToUnsignedExpr>& expr) { return createHandle(Z3_mk_fpa_to_ubv(mZ3Context, transformRoundingMode(expr->getRoundingMode()), getOperand(0), llvm::cast<BvType>(&expr->getType())->getWidth() )); } Z3AstHandle visitFpToBv(const ExprRef<FpToBvExpr>& expr) { return createHandle(Z3_mk_fpa_to_ieee_bv( mZ3Context, getOperand(0) )); } Z3AstHandle visitBvToFp(const ExprRef<BvToFpExpr>& expr) { return createHandle(Z3_mk_fpa_to_fp_bv( mZ3Context, getOperand(0), typeToSort(expr->getType()) )); } Z3AstHandle visitTupleSelect(const ExprRef<TupleSelectExpr>& expr); Z3AstHandle visitTupleConstruct(const ExprRef<TupleConstructExpr>& expr); protected: Z3AstHandle transformRoundingMode(llvm::APFloat::roundingMode rm); protected: Z3_context& mZ3Context; unsigned& mTmpCount; Z3CacheMapTy& mCache; Z3DeclMapTy& mDecls; std::unordered_map<const TupleType*, TupleInfo> mTupleInfo; }; /// Z3 solver implementation class Z3Solver : public Solver { public: explicit Z3Solver(GazerContext& context); void printStats(llvm::raw_ostream& os) override; void dump(llvm::raw_ostream& os) override; SolverStatus run() override; std::unique_ptr<Model> getModel() override; void reset() override; void push() override; void pop() override; ~Z3Solver(); protected: void addConstraint(ExprPtr expr) override; protected: Z3_config mConfig; Z3_context mZ3Context; Z3_solver mSolver; unsigned mTmpCount = 0; Z3CacheMapTy mCache; Z3DeclMapTy mDecls; Z3ExprTransformer mTransformer; }; } // end namespace gazer #endif
ftsrg/gazer
include/gazer/ADT/Graph.h
<gh_stars>1-10 //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// /// /// \file This file defines a base class template for directed graphs. /// //===----------------------------------------------------------------------===// #ifndef GAZER_ADT_GRAPH_H #define GAZER_ADT_GRAPH_H #include "gazer/ADT/Iterator.h" #include <llvm/ADT/GraphTraits.h> #include <llvm/ADT/STLExtras.h> #include <llvm/ADT/iterator_range.h> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <memory> namespace gazer { template<class NodeTy, class EdgeTy> class Graph; template<class NodeTy, class EdgeTy> class GraphNode { using EdgeVectorTy = std::vector<EdgeTy*>; friend class Graph<NodeTy, EdgeTy>; public: // Iterator support using edge_iterator = typename EdgeVectorTy::iterator; using const_edge_iterator = typename EdgeVectorTy::const_iterator; edge_iterator incoming_begin() { return mIncoming.begin(); } edge_iterator incoming_end() { return mIncoming.end(); } llvm::iterator_range<edge_iterator> incoming() { return llvm::make_range(incoming_begin(), incoming_end()); } edge_iterator outgoing_begin() { return mOutgoing.begin(); } edge_iterator outgoing_end() { return mOutgoing.end(); } llvm::iterator_range<edge_iterator> outgoing() { return llvm::make_range(outgoing_begin(), outgoing_end()); } const_edge_iterator incoming_begin() const { return mIncoming.begin(); } const_edge_iterator incoming_end() const { return mIncoming.end(); } llvm::iterator_range<const_edge_iterator> incoming() const { return llvm::make_range(incoming_begin(), incoming_end()); } const_edge_iterator outgoing_begin() const { return mOutgoing.begin(); } const_edge_iterator outgoing_end() const { return mOutgoing.end(); } llvm::iterator_range<const_edge_iterator> outgoing() const { return llvm::make_range(outgoing_begin(), outgoing_end()); } size_t getNumIncoming() const { return mIncoming.size(); } size_t getNumOutgoing() const { return mOutgoing.size(); } protected: void addIncoming(EdgeTy* edge) { assert(edge->getTarget() == this); mIncoming.emplace_back(edge); } void addOutgoing(EdgeTy* edge) { assert(edge->getSource() == this); mOutgoing.emplace_back(edge); } void removeIncoming(EdgeTy* edge) { mIncoming.erase(std::remove(mIncoming.begin(), mIncoming.end(), edge), mIncoming.end()); } void removeOutgoing(EdgeTy* edge) { mOutgoing.erase(std::remove(mOutgoing.begin(), mOutgoing.end(), edge), mOutgoing.end()); } private: EdgeVectorTy mIncoming; EdgeVectorTy mOutgoing; }; template<class NodeTy, class EdgeTy> class GraphEdge { friend class Graph<NodeTy, EdgeTy>; public: GraphEdge(NodeTy* source, NodeTy* target) : mSource(source), mTarget(target) {} NodeTy* getSource() const { return mSource; } NodeTy* getTarget() const { return mTarget; } private: NodeTy* mSource; NodeTy* mTarget; }; /// Represents a graph with a list of nodes and edges. template<class NodeTy, class EdgeTy> class Graph { static_assert(std::is_base_of_v<GraphNode<NodeTy, EdgeTy>, NodeTy>, ""); static_assert(std::is_base_of_v<GraphEdge<NodeTy, EdgeTy>, EdgeTy>, ""); using NodeVectorTy = std::vector<std::unique_ptr<NodeTy>>; using EdgeVectorTy = std::vector<std::unique_ptr<EdgeTy>>; public: using node_iterator = SmartPtrGetIterator<typename NodeVectorTy::iterator>; using const_node_iterator = SmartPtrGetIterator<typename NodeVectorTy::const_iterator>; node_iterator node_begin() { return mNodes.begin(); } node_iterator node_end() { return mNodes.end(); } const_node_iterator node_begin() const { return mNodes.begin(); } const_node_iterator node_end() const { return mNodes.end(); } llvm::iterator_range<node_iterator> nodes() { return llvm::make_range(node_begin(), node_end()); } llvm::iterator_range<const_node_iterator> nodes() const { return llvm::make_range(node_begin(), node_end()); } using edge_iterator = SmartPtrGetIterator<typename EdgeVectorTy::iterator>; using const_edge_iterator = SmartPtrGetIterator<typename EdgeVectorTy::const_iterator>; edge_iterator edge_begin() { return mEdges.begin(); } edge_iterator edge_end() { return mEdges.end(); } const_edge_iterator edge_begin() const { return mEdges.begin(); } const_edge_iterator edge_end() const { return mEdges.end(); } llvm::iterator_range<edge_iterator> edges() { return llvm::make_range(edge_begin(), edge_end()); } llvm::iterator_range<const_edge_iterator> edges() const { return llvm::make_range(edge_begin(), edge_end()); } size_t node_size() const { return mNodes.size(); } size_t edge_size() const { return mEdges.size(); } protected: void disconnectNode(NodeTy* node) { for (EdgeTy* edge : node->incoming()) { edge->mTarget = nullptr; edge->mSource->removeOutgoing(edge); } for (EdgeTy* edge : node->outgoing()) { edge->mSource = nullptr; edge->mTarget->removeIncoming(edge); } node->mIncoming.clear(); node->mOutgoing.clear(); } void disconnectEdge(EdgeTy* edge) { edge->mSource->removeOutgoing(edge); edge->mTarget->removeIncoming(edge); edge->mSource = nullptr; edge->mTarget = nullptr; } void clearDisconnectedElements() { mNodes.erase(llvm::remove_if(mNodes, [](auto& node) { return node->mIncoming.empty() && node->mOutgoing.empty(); }), mNodes.end()); mEdges.erase(llvm::remove_if(mEdges, [](auto& edge) { return edge->mSource == nullptr || edge->mTarget == nullptr; }), mEdges.end()); } template<class... Args> NodeTy* createNode(Args&&... args) { auto& ptr = mNodes.emplace_back(std::make_unique<NodeTy>(std::forward<Args...>(args...))); return &*ptr; } template<class... Args> EdgeTy* createEdge(NodeTy* source, NodeTy* target) { auto& edge = mEdges.emplace_back(std::make_unique<EdgeTy>(source, target)); static_cast<GraphNode<NodeTy, EdgeTy>*>(source)->mOutgoing.emplace_back(&*edge); static_cast<GraphNode<NodeTy, EdgeTy>*>(target)->mIncoming.emplace_back(&*edge); return &*edge; } template<class... Args> EdgeTy* createEdge(GraphNode<NodeTy, EdgeTy>* source, GraphNode<NodeTy, EdgeTy>* target, Args&&... args) { auto& edge = mEdges.emplace_back(std::make_unique<EdgeTy>( source, target, std::forward<Args...>(args...) )); source->mOutgoing.emplace_back(&*edge); target->mIncoming.emplace_back(&*edge); return &*edge; } void addNode(NodeTy* node) { mNodes.push_back(node); } void addEdge(EdgeTy* edge) { mEdges.push_back(edge); } protected: NodeVectorTy mNodes; EdgeVectorTy mEdges; }; } // namespace gazer namespace llvm { template<class NodeTy, class EdgeTy> struct GraphTraits<gazer::Graph<NodeTy, EdgeTy>> { using NodeRef = NodeTy*; using EdgeRef = EdgeTy*; static constexpr NodeRef GetEdgeTarget(EdgeRef edge) { return edge->getTarget(); } static constexpr NodeRef GetEdgeSource(EdgeRef edge) { return edge->getSource(); } // Child traversal using ChildIteratorType = llvm::mapped_iterator< typename NodeTy::edge_iterator, decltype(&GetEdgeTarget), NodeRef>; static ChildIteratorType child_begin(NodeRef node) { return ChildIteratorType(node->outgoing_begin(), GetEdgeTarget); } static ChildIteratorType child_end(NodeRef node) { return ChildIteratorType(node->outgoing_end(), GetEdgeTarget); } // Traversing nodes using nodes_iterator = typename gazer::Graph<NodeTy, EdgeTy>::const_node_iterator; static nodes_iterator nodes_begin(const gazer::Graph<NodeTy, EdgeTy>& graph) { return nodes_iterator(graph.node_begin()); } static nodes_iterator nodes_end(const gazer::Graph<NodeTy, EdgeTy>& graph) { return nodes_iterator(graph.node_end()); } // Edge traversal using ChildEdgeIteratorType = typename NodeTy::edge_iterator; static ChildEdgeIteratorType child_edge_begin(NodeRef loc) { return loc->outgoing_begin(); } static ChildEdgeIteratorType child_edge_end(NodeRef loc) { return loc->outgoing_end(); } static NodeRef edge_dest(EdgeRef edge) { return edge->getTarget(); } static unsigned size(const gazer::Graph<NodeTy, EdgeTy>& graph) { return graph.node_size(); } }; template<class NodeTy, class EdgeTy> struct GraphTraits<Inverse<gazer::Graph<NodeTy, EdgeTy>>> : public GraphTraits<gazer::Graph<NodeTy, EdgeTy>> { using NodeRef = NodeTy*; using EdgeRef = EdgeTy*; static constexpr NodeRef GetEdgeSource(const EdgeRef edge) { return edge->getSource(); } using ChildIteratorType = llvm::mapped_iterator< typename NodeTy::edge_iterator, decltype(&GetEdgeSource), NodeRef>; static ChildIteratorType child_begin(NodeRef loc) { return ChildIteratorType(loc->incoming_begin(), GetEdgeSource); } static ChildIteratorType child_end(NodeRef loc) { return ChildIteratorType(loc->incoming_end(), GetEdgeSource); } }; template<class NodeTy, class EdgeTy> struct GraphTraits<gazer::GraphNode<NodeTy, EdgeTy>*> { using NodeRef = NodeTy*; // Child traversal using ChildIteratorType = llvm::mapped_iterator< typename NodeTy::edge_iterator, decltype(&GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeTarget), NodeRef>; static ChildIteratorType child_begin(NodeRef node) { return ChildIteratorType(node->outgoing_begin(), GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeTarget); } static ChildIteratorType child_end(NodeRef node) { return ChildIteratorType(node->outgoing_end(), GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeTarget); } static NodeRef getEntryNode(NodeTy* node) { return node; } }; template<class NodeTy, class EdgeTy> struct GraphTraits<Inverse<gazer::GraphNode<NodeTy, EdgeTy>*>> { using NodeRef = NodeTy*; // Child traversal using ChildIteratorType = llvm::mapped_iterator< typename NodeTy::edge_iterator, decltype(&GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeSource), NodeRef>; static ChildIteratorType child_begin(NodeRef node) { return ChildIteratorType(node->incoming_begin(), GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeSource); } static ChildIteratorType child_end(NodeRef node) { return ChildIteratorType(node->incoming_end(), GraphTraits<gazer::Graph<NodeTy,EdgeTy>>::GetEdgeSource); } static NodeRef getEntryNode(Inverse<NodeTy*> node) { return node.Graph; } }; } // namespace gazer #endif
ftsrg/gazer
test/theta/verif/base/loops3_fail.c
// RUN: %theta -no-optimize -memory=havoc "%s" | FileCheck "%s" // CHECK: Verification FAILED #include <assert.h> extern int __VERIFIER_nondet_int(void); int main(void) { int i = 0; int n1 = __VERIFIER_nondet_int(); int n2 = __VERIFIER_nondet_int(); int sum = 0; while (i < n1) { sum = sum + i; ++i; } while (i < n2) { sum = sum * i; ++i; } assert(sum != 0); return 0; }
ftsrg/gazer
test/verif/base/loops_multi_break_fail.c
<reponame>ftsrg/gazer // RUN: %bmc -bound 10 "%s" | FileCheck "%s" // CHECK: Verification FAILED #include <assert.h> extern int __VERIFIER_nondet_int(void); int main(void) { int i = 0; int n = __VERIFIER_nondet_int(); int x = __VERIFIER_nondet_int(); int sum = 0; int prod = 0; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { if (j % x == 0) { goto err; } } } goto ok; err: assert(0); ok: return 0; }
ftsrg/gazer
test/verif/base/verifier_assume.c
<filename>test/verif/base/verifier_assume.c // RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}} int __VERIFIER_nondet_int(void); void __VERIFIER_assume(int); void __VERIFIER_error(void) __attribute__((__noreturn__)); int main() { int y = __VERIFIER_nondet_int(); __VERIFIER_assume(y != 0); if (!y) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
include/gazer/LLVM/LLVMTraceBuilder.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_LLVMTRACEBUILDER_H #define GAZER_LLVM_LLVMTRACEBUILDER_H #include "gazer/Trace/Trace.h" #include "gazer/Automaton/Cfa.h" #include "gazer/Verifier/VerificationAlgorithm.h" #include <llvm/ADT/DenseMap.h> #include <llvm/IR/Value.h> #include <llvm/IR/InstVisitor.h> namespace gazer { class CfaToLLVMTrace; class LLVMTraceBuilder : public CfaTraceBuilder { public: LLVMTraceBuilder(GazerContext& context, CfaToLLVMTrace& cfaToLlvmTrace) : mContext(context), mCfaToLlvmTrace(cfaToLlvmTrace) {} std::unique_ptr<Trace> build( std::vector<Location*>& states, std::vector<std::vector<VariableAssignment>>& actions ) override; private: void handleDbgValueInst( const Location* loc, const llvm::DbgValueInst* dvi, std::vector<std::unique_ptr<TraceEvent>>& events, Valuation& currentVals ); Type* preferredTypeFromDIType(llvm::DIType* diTy); ExprRef<AtomicExpr> getLiteralFromLLVMConst(const llvm::ConstantData* value, Type* preferredType = nullptr); ExprRef<AtomicExpr> getLiteralFromValue( Cfa* cfa, const llvm::Value* value, Valuation& model, Type* preferredType = nullptr ); static TraceVariable traceVarFromDIVar(const llvm::DIVariable* diVar); private: GazerContext& mContext; CfaToLLVMTrace& mCfaToLlvmTrace; }; } // end namespace gazer #endif
ftsrg/gazer
test/theta/verif/base/main_no_assert.c
// RUN: %theta -memory=havoc "%s" | FileCheck "%s" // CHECK: Verification SUCCESSFUL int __VERIFIER_nondet_int(void); int main(void) { int x = __VERIFIER_nondet_int(); if (x > 0) { return 0; } return 1; }
ftsrg/gazer
include/gazer/Core/ExprRef.h
//==- Expr.h - Core expression classes --------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// // /// \file This file contains a forward declaration for Expr and ExprRef. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPRREF_H #define GAZER_CORE_EXPRREF_H #include <boost/intrusive_ptr.hpp> namespace gazer { class Expr; template<class T = Expr> using ExprRef = boost::intrusive_ptr<T>; using ExprPtr = ExprRef<Expr>; } #endif
ftsrg/gazer
include/gazer/Core/Decl.h
//==- Expr.h - Core expression classes --------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_DECL_H #define GAZER_CORE_DECL_H #include "gazer/Core/Type.h" #include "gazer/Core/ExprRef.h" #include <llvm/ADT/StringMap.h> namespace gazer { class DeclContext; class VarRefExpr; /// Base class for all declarations. class Decl { public: enum DeclKind { Param, Variable, Function }; protected: Decl(DeclKind kind, Type& type) : mKind(kind), mType(type) {} protected: const DeclKind mKind; Type& mType; }; // Variables //===----------------------------------------------------------------------===// class Variable final : public Decl { friend class GazerContext; friend class GazerContextImpl; Variable(llvm::StringRef name, Type& type); public: Variable(const Variable&) = delete; Variable& operator=(const Variable&) = delete; bool operator==(const Variable& other) const; bool operator!=(const Variable& other) const { return !operator==(other); } std::string getName() const { return mName; } Type& getType() const { return mType; } ExprRef<VarRefExpr> getRefExpr() const { return mExpr; } [[nodiscard]] GazerContext& getContext() const { return mType.getContext(); } private: std::string mName; ExprRef<VarRefExpr> mExpr; }; /// Convenience class for representing assignments to variables. class VariableAssignment final { public: VariableAssignment(); VariableAssignment(Variable *variable, ExprPtr value); bool operator==(const VariableAssignment& other) const; bool operator!=(const VariableAssignment& other) const; Variable* getVariable() const; ExprPtr getValue() const; void print(llvm::raw_ostream& os) const; private: Variable* mVariable; ExprPtr mValue; }; llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Variable& variable); llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const VariableAssignment& va); } // end namespace gazer #endif
ftsrg/gazer
include/gazer/LLVM/Transform/Passes.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_TRANSFORM_PASSES_H #define GAZER_CORE_TRANSFORM_PASSES_H #include "gazer/LLVM/LLVMFrontendSettings.h" #include <llvm/Pass.h> namespace gazer { /// InlineGlobalVariables - This pass inlines all global variables into /// the main function of the program. llvm::Pass* createInlineGlobalVariablesPass(); /// This pass combines each 'gazer.error_code' call within the function /// into a single one. llvm::Pass* createLiftErrorCallsPass(llvm::Function& entry); /// This pass normalizes some known verifier calls into a uniform format. llvm::Pass* createNormalizeVerifierCallsPass(); /// A simpler (and more restricted) inlining pass. llvm::Pass* createSimpleInlinerPass(llvm::Function& entry, InlineLevel level); llvm::Pass* createCanonizeLoopExitsPass(); } #endif
ftsrg/gazer
test/verif/base/simple_fail.c
<gh_stars>1-10 // RUN: %bmc -bound 1 "%s" | FileCheck "%s" // CHECK: Verification FAILED #include <assert.h> int main(void) { int a; a = 1; a = -1; assert(a != -1); }
ftsrg/gazer
test/theta/verif/memory/structs1.c
// REQUIRES: memory.structs // RUN: %theta "%s" | FileCheck "%s" // CHECK: Verification FAILED int __VERIFIER_nondet_int(void); void __VERIFIER_error(void) __attribute__((__noreturn__)); void make_symbolic(void* ptr); typedef struct X { int a; int b; } X; int main(void) { X x; int a = __VERIFIER_nondet_int(); make_symbolic(&x); if (x.a != a) { __VERIFIER_error(); } return 0; }
ftsrg/gazer
include/gazer/Trace/TraceWriter.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_TRACE_TRACEWRITER_H #define GAZER_TRACE_TRACEWRITER_H #include "gazer/Trace/Trace.h" namespace gazer { /// Writes the contents of a trace into an output stream. class TraceWriter : public TraceEventVisitor<void> { public: explicit TraceWriter(llvm::raw_ostream& os) : mOS(os) {} void write(Trace& trace) { for (auto& event : trace) { event->accept(*this); } } protected: llvm::raw_ostream& mOS; }; namespace trace { std::unique_ptr<TraceWriter> CreateTextWriter(llvm::raw_ostream& os, bool printBv = true); } } // end namespace gazer #endif
ftsrg/gazer
include/gazer/LLVM/Automaton/SpecialFunctions.h
<filename>include/gazer/LLVM/Automaton/SpecialFunctions.h //==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_LLVM_AUTOMATON_SPECIALFUNCTIONS_H #define GAZER_LLVM_AUTOMATON_SPECIALFUNCTIONS_H #include "gazer/LLVM/Automaton/ModuleToAutomata.h" #include <functional> namespace gazer { /// This class is used to handle calls to certain known special and intrinsic functions. class SpecialFunctionHandler { public: using HandlerFuncTy = std::function<void(llvm::ImmutableCallSite, llvm2cfa::GenerationStepExtensionPoint& ep)>; enum MemoryBehavior { Memory_Pure, ///< This function does not modify memory. Memory_Default, ///< Handle memory definitions according to the rules of the used memory model. Memory_MayDefinePtr, ///< Define memory object reachable through its pointer operand(s). Memory_DefinesAll ///< Clobber and define all known memory objects. }; public: SpecialFunctionHandler(HandlerFuncTy function, MemoryBehavior memory = Memory_Default) : mHandlerFunction(function), mMemory(memory) {} void operator()(llvm::ImmutableCallSite cs, llvm2cfa::GenerationStepExtensionPoint& ep) const { return mHandlerFunction(cs, ep); } private: HandlerFuncTy mHandlerFunction; MemoryBehavior mMemory; }; class SpecialFunctions { static const SpecialFunctions EmptyInstance; public: /// Returns an object with the default handlers static std::unique_ptr<SpecialFunctions> get(); static const SpecialFunctions& empty() { return EmptyInstance; } void registerHandler( llvm::StringRef name, SpecialFunctionHandler::HandlerFuncTy function, SpecialFunctionHandler::MemoryBehavior memory = SpecialFunctionHandler::Memory_Default); bool handle(llvm::ImmutableCallSite cs, llvm2cfa::GenerationStepExtensionPoint& ep) const; // Some handlers for common cases public: static void handleAssume(llvm::ImmutableCallSite cs, llvm2cfa::GenerationStepExtensionPoint& ep); private: llvm::StringMap<SpecialFunctionHandler> mHandlers; }; } // namespace gazer #endif
ftsrg/gazer
include/gazer/ADT/Iterator.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_ADT_ITERATOR_H #define GAZER_ADT_ITERATOR_H #include <llvm/ADT/iterator.h> #include <llvm/ADT/STLExtras.h> namespace gazer { template<class T> typename std::unique_ptr<T>::pointer derefUniquePtr(std::unique_ptr<T>& ptr) { return ptr.get(); } template<class T> const typename std::unique_ptr<T>::pointer derefUniquePtr(const std::unique_ptr<T>& ptr) { return ptr.get(); } template< class BaseIterator, class ReturnTy = decltype(std::declval<BaseIterator>()->get())> class SmartPtrGetIterator : public llvm::iterator_adaptor_base< SmartPtrGetIterator<BaseIterator>, BaseIterator, typename std::iterator_traits<BaseIterator>::iterator_category > { public: /*implicit*/ SmartPtrGetIterator(BaseIterator it) : SmartPtrGetIterator::iterator_adaptor_base(std::move(it)) {} ReturnTy operator*() { return this->wrapped()->get(); } }; } // namespace gazer #endif
ftsrg/gazer
include/gazer/LLVM/Memory/MemoryModel.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_MEMORY_MEMORYMODEL_H #define GAZER_MEMORY_MEMORYMODEL_H #include "gazer/LLVM/Memory/MemorySSA.h" #include "gazer/LLVM/Memory/MemoryInstructionHandler.h" namespace llvm { class Loop; } // end namespace llvm namespace gazer { class Cfa; /// Memory models are responsible for representing memory-related types and instructions. class MemoryModel { public: MemoryModel() = default; MemoryModel(const MemoryModel&) = delete; MemoryModel& operator=(const MemoryModel&) = delete; /// Returns the memory instruction translator of this memory model. virtual MemoryInstructionHandler& getMemoryInstructionHandler(llvm::Function& function) = 0; /// Returns the type translator of this memory model. virtual MemoryTypeTranslator& getMemoryTypeTranslator() = 0; virtual ~MemoryModel() = default; }; //==------------------------------------------------------------------------==// /// HavocMemoryModel - A havoc memory model which does not create any memory /// objects. Load operations return an unknown value and store instructions /// have no effect. No MemoryObjectPhi's are inserted. std::unique_ptr<MemoryModel> CreateHavocMemoryModel(GazerContext& context); //==-----------------------------------------------------------------------==// // FlatMemoryModel - a memory model which represents all memory as a single // array, where loads and stores are reads and writes in said array. std::unique_ptr<MemoryModel> CreateFlatMemoryModel( GazerContext& context, const LLVMFrontendSettings& settings, llvm::Module& module, std::function<llvm::DominatorTree&(llvm::Function&)> dominators ); class MemoryModelWrapperPass : public llvm::ModulePass { public: static char ID; MemoryModelWrapperPass(GazerContext& context, const LLVMFrontendSettings& settings) : ModulePass(ID), mContext(context), mSettings(settings) {} void getAnalysisUsage(llvm::AnalysisUsage& au) const override; bool runOnModule(llvm::Module& module) override; MemoryModel& getMemoryModel() const { return *mMemoryModel; } llvm::StringRef getPassName() const override { return "Memory model wrapper pass"; } private: GazerContext& mContext; const LLVMFrontendSettings& mSettings; std::unique_ptr<MemoryModel> mMemoryModel; }; } // namespace gazer #endif //GAZER_MEMORY_MEMORYMODEL_H
ftsrg/gazer
src/Core/GazerContextImpl.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SRC_GAZERCONTEXTIMPL_H #define GAZER_SRC_GAZERCONTEXTIMPL_H #include "gazer/Core/Type.h" #include "gazer/Core/Decl.h" #include "gazer/Core/GazerContext.h" #include "gazer/Core/LiteralExpr.h" #include "gazer/Core/ExprTypes.h" #include "gazer/Support/DenseMapKeyInfo.h" #include "gazer/Support/Debug.h" #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/Hashing.h> #include <llvm/Support/raw_ostream.h> #include <boost/container_hash/hash.hpp> #include <unordered_set> #include <unordered_map> namespace llvm { template<class IntTy> llvm::hash_code hash_value(const boost::rational<IntTy>& arg) { return llvm::hash_value(std::make_pair(arg.numerator(), arg.denominator())); } } namespace gazer { /// Helper struct for acquiring the ExprKind enum value for a given type. template<class ExprTy> struct ExprTypeToExprKind {}; #define GAZER_EXPR_KIND(KIND) \ template<> struct ExprTypeToExprKind<KIND##Expr> { \ static constexpr Expr::ExprKind Kind = Expr::KIND; \ }; \ #include "gazer/Core/Expr/ExprKind.def" #undef GAZER_EXPR_KIND /// Returns a unique hash constant for a given expression kind. /// Defined in src/Core/Expr.cpp. std::size_t expr_kind_prime(Expr::ExprKind kind); template<class InputIterator, class... SubclassData> inline std::size_t expr_ops_hash(Expr::ExprKind kind, InputIterator begin, InputIterator end, SubclassData... subclassData) { return llvm::hash_combine( subclassData..., expr_kind_prime(kind), llvm::hash_combine_range(begin, end) ); } //-------------------------- Expression utilities ---------------------------// // These templates contain functionality which is used to compare expressions // without having access to an expression instance. template<class ExprTy, class T = void> struct expr_hasher; template<class ExprTy> struct expr_hasher<ExprTy, std::enable_if_t< std::is_base_of_v<NonNullaryExpr, ExprTy> && !(std::is_base_of_v<detail::FpExprWithRoundingMode, ExprTy>) >> { template<class InputIterator> static std::size_t hash_value(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end) { return expr_ops_hash(kind, begin, end); } template<class InputIterator> static bool equals( const Expr* other, Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end ) { if (other->getKind() != kind || other->getType() != type) { return false; } auto nn = llvm::cast<NonNullaryExpr>(other); return std::equal(begin, end, nn->op_begin(), nn->op_end()); } }; template<class ExprTy> const ExprTy* literal_equals(const Expr* expr, Type& type) { if (expr->getKind() != Expr::Literal) { return nullptr; } if (expr->getType() != type) { return nullptr; } return llvm::cast<ExprTy>(expr); }; // Expression hashing template for most literals. template<class ExprTy> struct expr_hasher<ExprTy, std::enable_if_t<std::is_base_of_v<LiteralExpr, ExprTy>>> { using ValT = decltype(std::declval<ExprTy>().getValue()); static std::size_t hash_value(Type& type, ValT value) { return llvm::hash_value(value); } static bool equals(const Expr* other, Type& type, ValT value) { if (auto i = literal_equals<ExprTy>(other, type)) { return i->getValue() == value; } return false; } }; // Specialization for float literals, as operator==() cannot be used with APFloats. template<> struct expr_hasher<FloatLiteralExpr> { static std::size_t hash_value(Type& type, llvm::APFloat value) { return llvm::hash_value(value); } static bool equals(const Expr* other, Type& type, llvm::APFloat value) { if (auto bv = literal_equals<FloatLiteralExpr>(other, type)) { return bv->getValue().bitwiseIsEqual(value); } return false; } }; // Specialization for array literals, using container hash template<> struct expr_hasher<ArrayLiteralExpr> { static std::size_t hash_value( Type& type, const ArrayLiteralExpr::MappingT& values, const ExprRef<LiteralExpr>& elze ) { std::size_t hash = 0; boost::hash_combine(hash, values); boost::hash_combine(hash, elze.get()); return hash; } static bool equals( const Expr* other, Type& type, const ArrayLiteralExpr::MappingT& value, const ExprRef<LiteralExpr>& elze ) { if (auto arr = literal_equals<ArrayLiteralExpr>(other, type)) { return arr->getMap() == value && arr->getDefault() == elze; } return false; } }; template<> struct expr_hasher<VarRefExpr> { static std::size_t hash_value(Variable* variable) { return llvm::hash_value(variable->getName()); } static bool equals(const Expr* other, Variable* variable) { if (auto expr = llvm::dyn_cast<VarRefExpr>(other)) { return &expr->getVariable() == variable; } return false; } }; template<class ExprTy> struct expr_hasher<ExprTy, std::enable_if_t<std::is_base_of_v<detail::FpExprWithRoundingMode, ExprTy>>> { template<class InputIterator> static std::size_t hash_value(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, llvm::APFloat::roundingMode rm) { return llvm::hash_combine(rm, expr_ops_hash(kind, begin, end)); } template<class InputIterator> static bool equals( const Expr* other, Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, llvm::APFloat::roundingMode rm ) { if (!expr_hasher<NonNullaryExpr>::equals(other, kind, type, begin, end)) { return false; } // If the previous equals call returned true, // the expression must be of the right type. auto fp = llvm::cast<ExprTy>(other); return fp->getRoundingMode() == rm; } }; template<> struct expr_hasher<ExtractExpr> { template<class InputIterator> static std::size_t hash_value(Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned offset, unsigned width) { return llvm::hash_combine( offset, width, expr_ops_hash(Expr::Extract, begin, end) ); } template<class InputIterator> static bool equals( const Expr* other, Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned offset, unsigned width) { if (!expr_hasher<NonNullaryExpr>::equals(other, kind, type, begin, end)) { return false; } // If the previous equals call returned true, // the expression must be an ExtractExpr. auto extract = llvm::cast<ExtractExpr>(other); return extract->getOffset() == offset && extract->getWidth() == width; } }; template<> struct expr_hasher<UndefExpr> { static std::size_t hash_value(Type& type) { return llvm::hash_combine(496549u, &type); } static bool equals(const Expr* other, Type& type) { return other->getKind() == Expr::Undef && other->getType() == type; } }; template<> struct expr_hasher<TupleSelectExpr> { template<class InputIterator> static std::size_t hash_value( Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned index ) { return llvm::hash_combine( index, expr_ops_hash(Expr::TupleSelect, begin, end) ); } template<class InputIterator> static bool equals( const Expr* other, Expr::ExprKind kind, Type& type, InputIterator begin, InputIterator end, unsigned index ) { if (!expr_hasher<NonNullaryExpr>::equals(other, kind, type, begin, end)) { return false; } auto tupSel = llvm::cast<TupleSelectExpr>(other); return tupSel->getIndex() == index; } }; //--------------------------- Expression storage ----------------------------// /// \brief Internal hashed set storage for all non-nullary expressions /// created by a given context. /// /// Construction is done by calling the (private) constructors of the /// befriended expression classes. class ExprStorage { static constexpr size_t DefaultBucketCount = 64; using NodeT = Expr; struct Bucket { Bucket() : Ptr(nullptr) {} Bucket(const Bucket&) = delete; Expr* Ptr; }; public: ExprStorage() : mBucketCount(DefaultBucketCount) { mStorage = new Bucket[mBucketCount]; } ~ExprStorage(); template< class ExprTy, class = std::enable_if<std::is_base_of<NonNullaryExpr, ExprTy>::value>, class... SubclassData > ExprRef<ExprTy> create(Type &type, std::initializer_list<ExprPtr> init, SubclassData&&... data) { return createRange<ExprTy>(type, init.begin(), init.end(), std::forward<SubclassData>(data)...); } template< class ExprTy, class = std::enable_if<std::is_base_of<NonNullaryExpr, ExprTy>::value>, Expr::ExprKind Kind = ExprTypeToExprKind<ExprTy>::Kind, class InputIterator, class... SubclassData > ExprRef<ExprTy> createRange( Type& type, InputIterator op_begin, InputIterator op_end, SubclassData&&... subclassData ) { return createIfNotExists<ExprTy>(Kind, type, op_begin, op_end, std::forward<SubclassData>(subclassData)...); } template< class ExprTy, class = std::enable_if<std::is_base_of<LiteralExpr, ExprTy>::value>, class... ConstructorArgs > ExprRef<ExprTy> create(ConstructorArgs&&... args) { return createIfNotExists<ExprTy>(std::forward<ConstructorArgs>(args)...); } void destroy(Expr* expr); void rehashTable(size_t newSize); size_t size() const { return mEntryCount; } private: template<class ExprTy, class... ConstructorArgs> ExprRef<ExprTy> createIfNotExists(ConstructorArgs&&... args) { auto hash = expr_hasher<ExprTy>::hash_value(args...); Bucket* bucket = &getBucketForHash(hash); Expr* current = bucket->Ptr; while (current != nullptr) { if (expr_hasher<ExprTy>::equals(current, args...)) { return ExprRef<ExprTy>(llvm::cast<ExprTy>(current)); } current = current->mNextPtr; } if (needsRehash(mEntryCount + 1)) { this->rehashTable(mBucketCount * 2); // Rehashing invalidated the previously calculated bucket, // so we need to get it again. bucket = &getBucketForHash(hash); } auto expr = new ExprTy(args...); expr->mHashCode = hash; GAZER_DEBUG( llvm::errs() << "[ExprStorage] Created new " << Expr::getKindName(expr->getKind()) << " address " << expr << "\n" ); ++mEntryCount; expr->mNextPtr = bucket->Ptr; bucket->Ptr = expr; return ExprRef<ExprTy>(expr); }; Bucket& getBucketForHash(size_t hash) const { return mStorage[hash % mBucketCount]; } bool needsRehash(size_t entries) const { return entries * 4 >= mBucketCount * 3; } void removeFromList(Expr* expr); private: Bucket* mStorage; size_t mBucketCount; size_t mEntryCount = 0; }; class GazerContextImpl { friend class GazerContext; explicit GazerContextImpl(GazerContext& ctx); public: ~GazerContextImpl(); public: //---------------------- Types ----------------------// BoolType BoolTy; IntType IntTy; RealType RealTy; BvType Bv1Ty, Bv8Ty, Bv16Ty, Bv32Ty, Bv64Ty; std::unordered_map<unsigned, std::unique_ptr<BvType>> BvTypes; FloatType FpHalfTy, FpSingleTy, FpDoubleTy, FpQuadTy; std::unordered_map< std::vector<Type*>, std::unique_ptr<ArrayType>, boost::hash<std::vector<Type*>> > ArrayTypes; std::unordered_map< std::vector<Type*>, std::unique_ptr<TupleType>, boost::hash<std::vector<Type*>> > TupleTypes; std::unordered_map< std::pair<Type*, std::vector<Type*>>, std::unique_ptr<FunctionType>, boost::hash<std::pair<Type*, std::vector<Type*>>> > FunctionTypes; //------------------- Expressions -------------------// ExprStorage Exprs; ExprRef<BoolLiteralExpr> TrueLit, FalseLit; llvm::StringMap<std::unique_ptr<Variable>> VariableTable; private: }; } // end namespace gazer #endif
ftsrg/gazer
src/LLVM/Automaton/FunctionToCfa.h
//==-------------------------------------------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_SRC_FUNCTIONTOAUTOMATA_H #define GAZER_SRC_FUNCTIONTOAUTOMATA_H #include "gazer/LLVM/Automaton/ModuleToAutomata.h" #include "gazer/LLVM/Automaton/SpecialFunctions.h" #include "gazer/Core/GazerContext.h" #include "gazer/Core/Expr/ExprBuilder.h" #include "gazer/Automaton/Cfa.h" #include "gazer/LLVM/Memory/MemoryObject.h" #include "gazer/LLVM/Memory/MemoryModel.h" #include "gazer/LLVM/Automaton/InstToExpr.h" #include "gazer/LLVM/LLVMTraceBuilder.h" #include <llvm/IR/Function.h> #include <llvm/IR/InstrTypes.h> #include <llvm/IR/Instructions.h> #include <llvm/Analysis/LoopInfo.h> #include <llvm/ADT/MapVector.h> #include <variant> namespace gazer { extern llvm::cl::opt<bool> PrintTrace; namespace llvm2cfa { using ValueToVariableMap = llvm::DenseMap<llvm::Value*, Variable*>; /// Stores information about loops which were transformed to automata. class CfaGenInfo { public: GenerationContext& Context; llvm::MapVector<ValueOrMemoryObject, Variable*> Inputs; llvm::MapVector<ValueOrMemoryObject, Variable*> Outputs; llvm::MapVector<ValueOrMemoryObject, Variable*> PhiInputs; llvm::MapVector<ValueOrMemoryObject, VariableAssignment> LoopOutputs; llvm::MapVector<const llvm::BasicBlock*, std::pair<Location*, Location*>> Blocks; llvm::DenseMap<ValueOrMemoryObject, Variable*> Locals; Cfa* Automaton; std::variant<llvm::Function*, llvm::Loop*> Source; using ExitEdge = std::pair<const llvm::BasicBlock*, const llvm::BasicBlock*>; // For automata with multiple exit paths, this variable tells us which was taken. Variable* ExitVariable = nullptr; llvm::SmallDenseMap<ExitEdge, ExprRef<LiteralExpr>> ExitEdges; // For functions with return values Variable* ReturnVariable = nullptr; public: CfaGenInfo(GenerationContext& context, Cfa* cfa, std::variant<llvm::Function*, llvm::Loop*> source) : Context(context), Automaton(cfa), Source(source) {} CfaGenInfo(CfaGenInfo&&) = default; CfaGenInfo(const CfaGenInfo&) = delete; CfaGenInfo& operator=(const CfaGenInfo&) = delete; // Blocks //==--------------------------------------------------------------------==// void addBlockToLocationsMapping(const llvm::BasicBlock* bb, Location* entry, Location* exit); // Sources //==--------------------------------------------------------------------==// bool isSourceLoop() const { return std::holds_alternative<llvm::Loop*>(Source); } bool isSourceFunction() const { return std::holds_alternative<llvm::Function*>(Source); } llvm::Loop* getSourceLoop() const { if (this->isSourceLoop()) { return std::get<llvm::Loop*>(Source); } return nullptr; } llvm::Function* getSourceFunction() const { if (this->isSourceFunction()) { return std::get<llvm::Function*>(Source); } return nullptr; } llvm::BasicBlock* getEntryBlock() const { if (auto function = getSourceFunction()) { return &function->getEntryBlock(); } if (auto loop = getSourceLoop()) { return loop->getHeader(); } llvm_unreachable("A CFA source can only be a function or a loop!"); } // Variables //==--------------------------------------------------------------------==// void addInput(ValueOrMemoryObject value, Variable* variable) { Inputs[value] = variable; addVariableToContext(value, variable); } void addPhiInput(ValueOrMemoryObject value, Variable* variable) { PhiInputs[value] = variable; addVariableToContext(value, variable); } void addLocal(ValueOrMemoryObject value, Variable* variable) { Locals[value] = variable; addVariableToContext(value, variable); } Variable* findVariable(ValueOrMemoryObject value) { Variable* result = Inputs.lookup(value); if (result != nullptr) { return result; } result = PhiInputs.lookup(value); if (result != nullptr) { return result; } result = Locals.lookup(value); if (result != nullptr) { return result; } return nullptr; } Variable* findInput(ValueOrMemoryObject value) { Variable* result = Inputs.lookup(value); if (result != nullptr) { return result; } return PhiInputs.lookup(value); } Variable* findOutput(ValueOrMemoryObject value) { return Outputs.lookup(value);} Variable* findLocal(ValueOrMemoryObject value) { return Locals.lookup(value); } bool hasInput(llvm::Value* value) { return Inputs.count(value) != 0; } bool hasLocal(const llvm::Value* value) { return Locals.count(value) != 0; } MemoryInstructionHandler& getMemoryInstructionHandler() const; private: void addVariableToContext(ValueOrMemoryObject value, Variable* variable); }; class GenerationContext; /// Helper structure for CFA generation information. class GenerationContext { public: using VariantT = std::variant<llvm::Function*, llvm::Loop*>; public: GenerationContext( AutomataSystem& system, MemoryModel& memoryModel, LLVMTypeTranslator& types, LoopInfoFuncTy loopInfos, const SpecialFunctions& specialFunctions, const LLVMFrontendSettings& settings ) : mSystem(system), mMemoryModel(memoryModel), mTypes(types), mLoopInfos(loopInfos), mSpecialFunctions(specialFunctions), mSettings(settings) {} GenerationContext(const GenerationContext&) = delete; GenerationContext& operator=(const GenerationContext&) = delete; CfaGenInfo& createLoopCfaInfo(Cfa* cfa, llvm::Loop* loop) { CfaGenInfo& info = mProcedures.try_emplace(loop, *this, cfa, loop).first->second; return info; } CfaGenInfo& createFunctionCfaInfo(Cfa* cfa, llvm::Function* function) { CfaGenInfo& info = mProcedures.try_emplace(function, *this, cfa, function).first->second; return info; } void addReverseBlockIfTraceEnabled( const llvm::BasicBlock* bb, Location* loc, CfaToLLVMTrace::LocationKind kind ) { if (mSettings.trace) { mTraceInfo.mLocationsToBlocks[loc] = { bb, kind }; } } void addExprValueIfTraceEnabled(Cfa* cfa, ValueOrMemoryObject value, ExprPtr expr) { if (mSettings.trace) { mTraceInfo.mValueMaps[cfa].values[value] = std::move(expr); } } CfaGenInfo& getLoopCfa(llvm::Loop* loop) { return getInfoFor(loop); } CfaGenInfo& getFunctionCfa(llvm::Function* function) { return getInfoFor(function); } llvm::iterator_range<typename std::unordered_map<VariantT, CfaGenInfo>::iterator> procedures() { return llvm::make_range(mProcedures.begin(), mProcedures.end()); } llvm::LoopInfo* getLoopInfoFor(const llvm::Function* function) { return mLoopInfos(function); } std::string uniqueName(const llvm::Twine& base = ""); AutomataSystem& getSystem() const { return mSystem; } MemoryModel& getMemoryModel() const { return mMemoryModel; } LLVMTypeTranslator& getTypes() const { return mTypes; } const LLVMFrontendSettings& getSettings() { return mSettings; } CfaToLLVMTrace& getTraceInfo() { return mTraceInfo; } const SpecialFunctions& getSpecialFunctions() const { return mSpecialFunctions; } private: CfaGenInfo& getInfoFor(VariantT key) { auto it = mProcedures.find(key); assert(it != mProcedures.end()); return it->second; } private: AutomataSystem& mSystem; MemoryModel& mMemoryModel; LLVMTypeTranslator& mTypes; LoopInfoFuncTy mLoopInfos; const SpecialFunctions& mSpecialFunctions; const LLVMFrontendSettings& mSettings; std::unordered_map<VariantT, CfaGenInfo> mProcedures; CfaToLLVMTrace mTraceInfo; unsigned mTmp = 0; }; class ModuleToCfa final { public: static constexpr char FunctionReturnValueName[] = "RET_VAL"; static constexpr char LoopOutputSelectorName[] = "__output_selector"; ModuleToCfa( llvm::Module& module, LoopInfoFuncTy loops, GazerContext& context, MemoryModel& memoryModel, LLVMTypeTranslator& types, const SpecialFunctions& specialFunctions, const LLVMFrontendSettings& settings ); std::unique_ptr<AutomataSystem> generate(CfaToLLVMTrace& cfaToLlvmTrace); protected: void createAutomata(); void declareLoopVariables( llvm::Loop* loop, CfaGenInfo& loopGenInfo, MemoryInstructionHandler& memoryInstHandler, llvm::ArrayRef<llvm::BasicBlock*> loopBlocks, llvm::ArrayRef<llvm::BasicBlock*> loopOnlyBlocks, llvm::DenseSet<llvm::BasicBlock*>& visitedBlocks ); private: llvm::Module& mModule; GazerContext& mContext; MemoryModel& mMemoryModel; const LLVMFrontendSettings& mSettings; std::unique_ptr<AutomataSystem> mSystem; GenerationContext mGenCtx; std::unique_ptr<ExprBuilder> mExprBuilder; // Generation helpers std::unordered_map<llvm::Function*, Cfa*> mFunctionMap; std::unordered_map<llvm::Loop*, Cfa*> mLoopMap; }; class BlocksToCfa : public InstToExpr { protected: class ExtensionPointImpl : public GenerationStepExtensionPoint { public: ExtensionPointImpl( BlocksToCfa& blocksToCfa, std::vector<VariableAssignment>& assigns, Location** entry, Location** exit ) : GenerationStepExtensionPoint(blocksToCfa.mGenInfo), mBlocksToCfa(blocksToCfa), mAssigns(assigns), mEntry(entry), mExit(exit) {} ExprPtr getAsOperand(ValueOrMemoryObject val) override; bool tryToEliminate(ValueOrMemoryObject val, Variable* variable, const ExprPtr& expr) override; void insertAssignment(Variable* variable, const ExprPtr& value) override; void splitCurrentTransition(const ExprPtr& guard) override; using guard_iterator = std::vector<ExprPtr>::const_iterator; llvm::iterator_range<guard_iterator> guards() const { return llvm::make_range(mGuards.begin(), mGuards.end()); } private: BlocksToCfa& mBlocksToCfa; std::vector<VariableAssignment>& mAssigns; std::vector<ExprPtr> mGuards; Location** mEntry; Location** mExit; }; public: BlocksToCfa( GenerationContext& generationContext, CfaGenInfo& genInfo, ExprBuilder& exprBuilder ); void encode(); protected: Variable* getVariable(ValueOrMemoryObject value) override; ExprPtr lookupInlinedVariable(ValueOrMemoryObject value) override; private: GazerContext& getContext() const { return mGenCtx.getSystem().getContext(); } private: bool tryToEliminate(ValueOrMemoryObject val, Variable* variable, const ExprPtr& expr); void insertOutputAssignments(CfaGenInfo& callee, std::vector<VariableAssignment>& outputArgs); void insertPhiAssignments(const llvm::BasicBlock* source, const llvm::BasicBlock* target, std::vector<VariableAssignment>& phiAssignments); bool handleCall(const llvm::CallInst* call, Location** entry, Location* exit, std::vector<VariableAssignment>& previousAssignments); void handleTerminator(const llvm::BasicBlock* bb, Location* entry, Location* exit); void handleSuccessor( const llvm::BasicBlock* succ, const ExprPtr& succCondition, const llvm::BasicBlock* parent, Location* exit ); void createExitTransition(const llvm::BasicBlock* source, const llvm::BasicBlock* target, Location* pred, const ExprPtr& succCondition); void createCallToLoop(llvm::Loop* loop, const llvm::BasicBlock* source, const ExprPtr& condition, Location* exit); ExprPtr getExitCondition(const llvm::BasicBlock* source, const llvm::BasicBlock* target, Variable* exitSelector, CfaGenInfo& nestedInfo); size_t getNumUsesInBlocks(const llvm::Instruction* inst) const; ExtensionPointImpl createExtensionPoint( std::vector<VariableAssignment>& assignments, Location** entry, Location** exit); private: GenerationContext& mGenCtx; CfaGenInfo& mGenInfo; Cfa* mCfa; unsigned mCounter = 0; llvm::DenseMap<ValueOrMemoryObject, ExprPtr> mInlinedVars; llvm::DenseSet<Variable*> mEliminatedVarsSet; llvm::BasicBlock* mEntryBlock; }; } // end namespace llvm2cfa } // end namespace gazer #endif //GAZER_SRC_FUNCTIONTOAUTOMATA_H
ftsrg/gazer
include/gazer/Core/Solver/Solver.h
<filename>include/gazer/Core/Solver/Solver.h //==- Solver.h - SMT solver interface ---------------------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_SOLVER_SOLVER_H #define GAZER_CORE_SOLVER_SOLVER_H #include "gazer/Core/Expr.h" namespace gazer { class Model; /// Base interface for all solvers. class Solver { public: enum SolverStatus { SAT, UNSAT, UNKNOWN }; public: explicit Solver(GazerContext& context) : mContext(context) {} Solver(const Solver&) = delete; Solver& operator=(const Solver&) = delete; void add(const ExprPtr& expr) { assert(expr->getType().isBoolType() && "Can only add bool expressions to a solver."); mStatCount++; addConstraint(expr); } unsigned getNumConstraints() const { return mStatCount; } GazerContext& getContext() const { return mContext; } virtual void printStats(llvm::raw_ostream& os) = 0; virtual void dump(llvm::raw_ostream& os) = 0; virtual SolverStatus run() = 0; virtual std::unique_ptr<Model> getModel() = 0; virtual void reset() = 0; virtual void push() = 0; virtual void pop() = 0; virtual ~Solver() = default; protected: virtual void addConstraint(ExprPtr expr) = 0; GazerContext& mContext; private: unsigned mStatCount = 0; }; /// Identifies an interpolation group. using ItpGroup = unsigned; /// Interface for interpolating solvers. class ItpSolver : public Solver { using ItpGroupMapTy = std::unordered_map<ItpGroup, llvm::SmallVector<ExprPtr, 1>>; public: using Solver::Solver; void add(ItpGroup group, const ExprPtr& expr) { assert(expr->getType().isBoolType() && "Can only add bool expressions to a solver."); mGroupFormulae[group].push_back(expr); this->addConstraint(group, expr); } // Interpolant groups ItpGroup createItpGroup() { return mGroupId++; } using itp_formula_iterator = typename ItpGroupMapTy::mapped_type::iterator; itp_formula_iterator group_formula_begin(ItpGroup group) { return mGroupFormulae[group].begin(); } itp_formula_iterator group_formula_end(ItpGroup group) { return mGroupFormulae[group].end(); } /// Returns an interpolant for a given interpolation group. virtual ExprPtr getInterpolant(ItpGroup group) = 0; protected: using Solver::addConstraint; virtual void addConstraint(ItpGroup group, ExprPtr expr) = 0; private: unsigned mGroupId = 1; ItpGroupMapTy mGroupFormulae; }; /// Base factory class for all solvers, used to create new Solver instances. class SolverFactory { public: /// Creates a new solver instance with a given symbol table. virtual std::unique_ptr<Solver> createSolver(GazerContext& symbols) = 0; }; } #endif
ftsrg/gazer
include/gazer/Core/GazerContext.h
//==- GazerContext.h - Lifetime management for gazer objects ----*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// /// /// \file This file defines GazerContext, a container for all unique types, /// variables and expressions. /// //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_GAZERCONTEXT_H #define GAZER_CORE_GAZERCONTEXT_H #include <llvm/ADT/StringRef.h> namespace gazer { class Type; class Variable; class GazerContext; class GazerContextImpl; class Decl; class GazerContext { public: GazerContext(); GazerContext(const GazerContext&) = delete; GazerContext& operator=(const GazerContext&) = delete; ~GazerContext(); public: Variable *getVariable(llvm::StringRef name); Variable *createVariable(const std::string& name, Type &type); void removeVariable(Variable* variable); void dumpStats(llvm::raw_ostream& os) const; public: const std::unique_ptr<GazerContextImpl> pImpl; }; inline bool operator==(const GazerContext& lhs, const GazerContext& rhs) { // We only consider two context objects equal if they are the same object. return &lhs == &rhs; } inline bool operator!=(const GazerContext& lhs, const GazerContext& rhs) { return !(lhs == rhs); } } // end namespace gazer #endif
ftsrg/gazer
test/verif/regression/inline_fail.c
<filename>test/verif/regression/inline_fail.c // RUN: %bmc -bound 10 -math-int "%s" | FileCheck "%s" // RUN: %bmc -bound 10 -math-int "%s" | FileCheck "%s" // CHECK: Verification FAILED int a, b; int c(f) { if (f) { b = 3; return 3; } if (b) a = e(); } int e() { if (a) __VERIFIER_error(); } int main(void) { while (1) { int d; c(d); } }
ftsrg/gazer
include/gazer/Core/Expr/ExprBuilder.h
<gh_stars>1-10 //==- ExprBuilder.h - Expression builder interface --------------*- C++ -*--==// // // Copyright 2019 Contributors to the Gazer project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// #ifndef GAZER_CORE_EXPR_EXPRBUILDER_H #define GAZER_CORE_EXPR_EXPRBUILDER_H #include "gazer/Core/Expr.h" #include "gazer/Core/ExprTypes.h" #include "gazer/Core/LiteralExpr.h" namespace llvm { class APInt; } namespace gazer { class ExprBuilder { public: explicit ExprBuilder(GazerContext& context) : mContext(context) {} [[nodiscard]] GazerContext& getContext() const { return mContext; } public: virtual ~ExprBuilder() = default; // Literals and non-virtual convenience methods //===------------------------------------------------------------------===// ExprRef<BvLiteralExpr> BvLit(uint64_t value, unsigned bits) { return BvLiteralExpr::Get(BvType::Get(mContext, bits), llvm::APInt(bits, value)); } ExprRef<BvLiteralExpr> BvLit8(uint64_t value) { return BvLit(value, 8); } ExprRef<BvLiteralExpr> BvLit32(uint64_t value) { return BvLit(value, 32); } ExprRef<BvLiteralExpr> BvLit64(uint64_t value) { return BvLit(value, 64); } ExprRef<BvLiteralExpr> BvLit(const llvm::APInt& value) { return BvLiteralExpr::Get(BvType::Get(mContext, value.getBitWidth()), value); } ExprRef<IntLiteralExpr> IntLit(int64_t value) { return IntLiteralExpr::Get(IntType::Get(mContext), value); } ExprRef<BoolLiteralExpr> BoolLit(bool value) { return value ? True() : False(); } ExprRef<BoolLiteralExpr> True() { return BoolLiteralExpr::True(BoolType::Get(mContext)); } ExprRef<BoolLiteralExpr> False() { return BoolLiteralExpr::False(BoolType::Get(mContext)); } ExprRef<UndefExpr> Undef(Type& type) { return UndefExpr::Get(type); } ExprRef<FloatLiteralExpr> FloatLit(const llvm::APFloat& value) { auto numbits = llvm::APFloat::getSizeInBits(value.getSemantics()); auto& type = FloatType::Get(mContext, static_cast<FloatType::FloatPrecision>(numbits)); return FloatLiteralExpr::Get(type, value); } ExprPtr Trunc(const ExprPtr& op, BvType& type) { return this->Extract(op, 0, type.getWidth()); } /// Resize bit-vector operand \p op to match \p type. /// If \p type is wider than the type of \p op, ZExt, otherwise /// Extract is used to do the cast. ExprPtr BvResize(const ExprPtr& op, BvType& type); // Virtual methods //===------------------------------------------------------------------===// virtual ExprPtr Not(const ExprPtr& op) { return NotExpr::Create(op); } virtual ExprPtr ZExt(const ExprPtr& op, BvType& type) { return ZExtExpr::Create(op, type); } virtual ExprPtr SExt(const ExprPtr& op, BvType& type) { return SExtExpr::Create(op, type); } virtual ExprPtr Extract(const ExprPtr& op, unsigned offset, unsigned width) { return ExtractExpr::Create(op, offset, width); } //--- Binary ---// virtual ExprPtr Add(const ExprPtr& left, const ExprPtr& right) { return AddExpr::Create(left, right); } virtual ExprPtr Sub(const ExprPtr& left, const ExprPtr& right) { return SubExpr::Create(left, right); } virtual ExprPtr Mul(const ExprPtr& left, const ExprPtr& right) { return MulExpr::Create(left, right); } virtual ExprPtr Div(const ExprPtr& left, const ExprPtr& right) { return DivExpr::Create(left, right); } virtual ExprPtr Mod(const ExprPtr& left, const ExprPtr& right) { return ModExpr::Create(left, right); } virtual ExprPtr Rem(const ExprPtr& left, const ExprPtr& right) { return RemExpr::Create(left, right); } virtual ExprPtr BvSDiv(const ExprPtr& left, const ExprPtr& right) { return BvSDivExpr::Create(left, right); } virtual ExprPtr BvUDiv(const ExprPtr& left, const ExprPtr& right) { return BvUDivExpr::Create(left, right); } virtual ExprPtr BvSRem(const ExprPtr& left, const ExprPtr& right) { return BvSRemExpr::Create(left, right); } virtual ExprPtr BvURem(const ExprPtr& left, const ExprPtr& right) { return BvURemExpr::Create(left, right); } virtual ExprPtr Shl(const ExprPtr& left, const ExprPtr& right) { return ShlExpr::Create(left, right); } virtual ExprPtr LShr(const ExprPtr& left, const ExprPtr& right) { return LShrExpr::Create(left, right); } virtual ExprPtr AShr(const ExprPtr& left, const ExprPtr& right) { return AShrExpr::Create(left, right); } virtual ExprPtr BvAnd(const ExprPtr& left, const ExprPtr& right) { return BvAndExpr::Create(left, right); } virtual ExprPtr BvOr(const ExprPtr& left, const ExprPtr& right) { return BvOrExpr::Create(left, right); } virtual ExprPtr BvXor(const ExprPtr& left, const ExprPtr& right) { return BvXorExpr::Create(left, right); } virtual ExprPtr BvConcat(const ExprPtr& left, const ExprPtr& right) { return BvConcatExpr::Create(left, right); } //--- Logic ---// virtual ExprPtr And(const ExprVector& vector) { return AndExpr::Create(vector); } virtual ExprPtr Or(const ExprVector& vector) { return OrExpr::Create(vector); } template<class Left, class Right> ExprPtr And(const ExprRef<Left>& left, const ExprRef<Right>& right) { return this->And({left, right}); } template<class Left, class Right> ExprPtr Or(const ExprRef<Left>& left, const ExprRef<Right>& right) { return this->Or({left, right}); } ExprPtr Xor(const ExprPtr& left, const ExprPtr& right) { assert(left->getType().isBoolType() && right->getType().isBoolType()); return this->NotEq(left, right); } virtual ExprPtr Imply(const ExprPtr& left, const ExprPtr& right) { return ImplyExpr::Create(left, right); } //--- Compare ---// virtual ExprPtr NotEq(const ExprPtr& left, const ExprPtr& right) { return this->Not(this->Eq(left, right)); } virtual ExprPtr Eq(const ExprPtr& left, const ExprPtr& right) { return EqExpr::Create(left, right); } virtual ExprPtr Lt(const ExprPtr& left, const ExprPtr& right) { return LtExpr::Create(left, right); } virtual ExprPtr LtEq(const ExprPtr& left, const ExprPtr& right) { return LtEqExpr::Create(left, right); } virtual ExprPtr Gt(const ExprPtr& left, const ExprPtr& right) { return GtExpr::Create(left, right); } virtual ExprPtr GtEq(const ExprPtr& left, const ExprPtr& right) { return GtEqExpr::Create(left, right); } virtual ExprPtr BvSLt(const ExprPtr& left, const ExprPtr& right) { return BvSLtExpr::Create(left, right); } virtual ExprPtr BvSLtEq(const ExprPtr& left, const ExprPtr& right) { return BvSLtEqExpr::Create(left, right); } virtual ExprPtr BvSGt(const ExprPtr& left, const ExprPtr& right) { return BvSGtExpr::Create(left, right); } virtual ExprPtr BvSGtEq(const ExprPtr& left, const ExprPtr& right) { return BvSGtEqExpr::Create(left, right); } virtual ExprPtr BvULt(const ExprPtr& left, const ExprPtr& right) { return BvULtExpr::Create(left, right); } virtual ExprPtr BvULtEq(const ExprPtr& left, const ExprPtr& right) { return BvULtEqExpr::Create(left, right); } virtual ExprPtr BvUGt(const ExprPtr& left, const ExprPtr& right) { return BvUGtExpr::Create(left, right); } virtual ExprPtr BvUGtEq(const ExprPtr& left, const ExprPtr& right) { return BvUGtEqExpr::Create(left, right); } //--- Floating point ---// virtual ExprPtr FCast(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) { return FCastExpr::Create(op, type, rm); } virtual ExprPtr FIsNan(const ExprPtr& op) { return FIsNanExpr::Create(op); } virtual ExprPtr FIsInf(const ExprPtr& op) { return FIsInfExpr::Create(op); } virtual ExprPtr SignedToFp(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) { return SignedToFpExpr::Create(op, type, rm); } virtual ExprPtr UnsignedToFp(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) { return UnsignedToFpExpr::Create(op, type, rm); } virtual ExprPtr FpToSigned(const ExprPtr& op, BvType& type, llvm::APFloat::roundingMode rm) { return FpToSignedExpr::Create(op, type, rm); } virtual ExprPtr FpToUnsigned(const ExprPtr& op, BvType& type, llvm::APFloat::roundingMode rm) { return FpToUnsignedExpr::Create(op, type, rm); } virtual ExprPtr FpToBv(const ExprPtr& op, BvType& type) { return FpToBvExpr::Create(op, type); } virtual ExprPtr BvToFp(const ExprPtr& op, FloatType& type) { return BvToFpExpr::Create(op, type); } virtual ExprPtr FAdd(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) { return FAddExpr::Create(left, right, rm); } virtual ExprPtr FSub(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) { return FSubExpr::Create(left, right, rm); } virtual ExprPtr FMul(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) { return FMulExpr::Create(left, right, rm); } virtual ExprPtr FDiv(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) { return FDivExpr::Create(left, right, rm); } virtual ExprPtr FEq(const ExprPtr& left, const ExprPtr& right) { return FEqExpr::Create(left, right); } virtual ExprPtr FGt(const ExprPtr& left, const ExprPtr& right) { return FGtExpr::Create(left, right); } virtual ExprPtr FGtEq(const ExprPtr& left, const ExprPtr& right) { return FGtEqExpr::Create(left, right); } virtual ExprPtr FLt(const ExprPtr& left, const ExprPtr& right) { return FLtExpr::Create(left, right); } virtual ExprPtr FLtEq(const ExprPtr& left, const ExprPtr& right) { return FLtEqExpr::Create(left, right); } //--- Ternary ---// virtual ExprPtr Select(const ExprPtr& condition, const ExprPtr& then, const ExprPtr& elze) { return SelectExpr::Create(condition, then, elze); } virtual ExprPtr Write(const ExprPtr& array, const ExprPtr& index, const ExprPtr& value) { return ArrayWriteExpr::Create(array, index, value); } virtual ExprPtr Read(const ExprPtr& array, const ExprPtr& index) { return ArrayReadExpr::Create(array, index); } template<class First, class Second, class... Tail> ExprPtr Tuple(const First& first, const Second& second, const Tail&... exprs) { TupleType& type = TupleType::Get(first->getType(), second->getType(), exprs->getType()...); return this->createTupleConstructor(type, {first, second, exprs...}); } /// Constructs a new tuple based on \p tuple, where the element at \p index /// will be set to \p value. ExprPtr TupleInsert(const ExprPtr& tuple, const ExprPtr& value, unsigned index); virtual ExprPtr TupSel(const ExprPtr& tuple, unsigned index); protected: /// Tuple constructor. virtual ExprPtr createTupleConstructor(TupleType& type, const ExprVector& members); private: GazerContext& mContext; }; // Expression builder implementations //===----------------------------------------------------------------------===// /// Instantiates the default expression builder. std::unique_ptr<ExprBuilder> CreateExprBuilder(GazerContext& context); /// Instantiates an expression builder which provides constant folding and /// some basic simplifications. std::unique_ptr<ExprBuilder> CreateFoldingExprBuilder(GazerContext& context); } #endif
LazyPanda07/CleanCustomBuildSteps
CleanCustomBuildSteps/src/Global.h
<reponame>LazyPanda07/CleanCustomBuildSteps #pragma once #include <string_view> #include <vector> namespace globals { inline std::vector<std::string_view> arguments; }
LazyPanda07/CleanCustomBuildSteps
CleanCustomBuildSteps/src/Commands/EraseFilesByTypeCommand.h
<filename>CleanCustomBuildSteps/src/Commands/EraseFilesByTypeCommand.h<gh_stars>0 #pragma once #include "ICommand.h" namespace commands { class EraseFilesByTypeCommand : public ICommand { public: EraseFilesByTypeCommand() = default; void run(std::string_view path) const override; ~EraseFilesByTypeCommand() = default; }; }
LazyPanda07/CleanCustomBuildSteps
CleanCustomBuildSteps/src/Commands/ICommand.h
#pragma once #include <string_view> namespace commands { class ICommand { public: ICommand() = default; virtual void run(std::string_view path) const = 0; virtual ~ICommand() = default; }; }
LazyPanda07/CleanCustomBuildSteps
CleanCustomBuildSteps/src/Commands/EraseFileCommand.h
<filename>CleanCustomBuildSteps/src/Commands/EraseFileCommand.h #pragma once #include "ICommand.h" namespace commands { class EraseFileCommand : public ICommand { public: EraseFileCommand() = default; void run(std::string_view path) const override; ~EraseFileCommand() = default; }; }
peroff/8-Bit-Tea-Party
Science/Questions/06 Input data to dynamic memory.c
#include <stdio.h> #include <stdlib.h> #include <string.h> // Вещание на канале 8-Bit-Tea-Party. /* rerum: Написать программу, которая осуществляет считывание введенных данных, * определяет их тип и сохраняет в виде массива данных. Результатом работы программы * является вывод на экран размера массива и объем памяти занимаемый им. * Требования: Программа должна иметь примитивное «меню». После вывода результата, * программа должна передоложить повторный ввод пользователю. * Данные должны храниться в виде динамического массива. * Запрещена запись в незарезервированные участки памяти! * Для второй, дополнение: Правила формирования входной последовательности * Последовательность символов разделенных символом «пробел». * По первой последовательности символов определяется тип данных в последующих. * В случае не соответствия определенного типа выводится сообщение об ошибке введенных данных, * при возможности, данные преобразуются и программа продолжает своё выполнение. */ int getline(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != '\n'; ++i) s[i] = c; s[i] = '\0'; return i; } int myisdigit(int c) { return (c >= '0' && c <= '9'); } int lower(int c) { return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; } double my_atof(char s[]) { double value, power, base = 10; int i, sign; for (i = 0; s[i] != '\0' && !myisdigit(s[i]) && s[i] != '+' && s[i] != '-'; i++) ; sign = (s[i] == '-') ? -1 : 1; if (s[i] == '+' || s[i] == '-') i++; for (value = 0.0; myisdigit(s[i]); ++i) value = base * value + (s[i] - '0'); if (s[i] == '.') i++; for (power = 1.0; myisdigit(s[i]); i++) { value = base * value + (s[i] - '0'); power *= base; } if (lower(s[i]) == 'e' && (s[i+1] == '-' || s[i+1] == '+')) { double exp = 0.0, multiplier; multiplier = (s[i+1] == '+') ? base : (1.0 / base); i += 2; while (myisdigit(s[i])) exp = exp * base + (s[i++] - '0'); while (exp > 0) { power /= multiplier; exp -= 1.0; } } return sign * value / power; } int my_atoi(char s[]) { int i = 0, n = 0; while (s[i] != '-' && s[i] != '+' && !myisdigit(s[i])) i++; int sign = (s[i] == '-') ? -1 : 1; if (s[i] == '-' || s[i] == '+') i++; while (s[i] >= '0' && s[i] <= '9') n = n * 10 + (s[i++] - '0'); return (n * sign); } int length(char s[]) { int i = 0; while (s[i] != '\0') ++i; return i; } int main() { #define MAXLINE 256 char s[MAXLINE], word[MAXLINE]; void* data[MAXLINE]; int data_size = 0, memory = 0; enum data_type { Void, Char, Int, Double } types[MAXLINE]; const char* type_names[] = { "Void", "Char", "Int", "Double" }; printf("Save char, int and double to dynamic memory, maximum %d objects.\n", MAXLINE); printf("Maximum length string %d and empty to exit.\n", MAXLINE); printf("Size of types char %d, integer %d and double %d bytes.\n", sizeof(char), sizeof(int), sizeof(double)); int i, j, k, l; while ((l = getline(s, MAXLINE)) != 0 && data_size < MAXLINE) { // Source "3.0 -5.3 3.1 text 123 82..." printf("Source length[%d]: %s\n", l, s); printf("Word:\tType:\tData:\tMemory:\n"); for (i = 0; i < l; i += j + 1) { for (j = 0; s[i + j] != '\0' && s[i + j] != ' ' && s[i + j] != '\t'; ++j) word[j] = s[i + j]; word[j] = '\0'; // Word "-32.25" enum data_type wtype = Void; for (k = 0; k < j && wtype != Char && data_size < MAXLINE; ++k) { if ((k == 0 && j > 1) && (word[k] == '-' || word[k] == '+')) k++; if (word[k] == '.' && wtype == Int) wtype = Double; else if (myisdigit(word[k]) && wtype == Void) wtype = Int; else if (!myisdigit(word[k])) wtype = Char; } double d_write, d_verify; int i_write, i_verify; unsigned int word_len; switch (wtype) { case Double: d_write = my_atof(word); data[data_size] = malloc(sizeof(double)); memory += sizeof(double); memcpy(data[data_size], &d_write, sizeof(double)); d_verify = *((double*)data[data_size]); printf("%s\t%s\t%3.3f\t%d\n", word, type_names[wtype], d_verify, sizeof(double)); types[data_size++] = wtype; break; case Int: i_write = my_atoi(word); data[data_size] = malloc(sizeof(int)); memory += sizeof(int); memcpy(data[data_size], &i, sizeof(int)); i_verify = *((int*)data[data_size]); printf("%s\t%s\t%d\t%d\n", word, type_names[wtype], i_verify, sizeof(int)); types[data_size++] = wtype; break; case Char: word_len = (unsigned int)length(word) + 1; data[data_size] = malloc(sizeof(char) * word_len); memory += word_len; memcpy(data[data_size], &word, word_len); // char* sr = (char*)(data[data_size]); printf("%s\t%s\t%s\t%d\n", word, type_names[wtype], (char*)(data[data_size]), word_len); types[data_size++] = wtype; break; default: printf("'%s'\t%s\tIndex = %d\n", word, type_names[wtype], i); } } printf("Dynamic array has %d objects and use %d bytes of memory.\n\n", data_size, memory); } return 0; }
peroff/8-Bit-Tea-Party
Science/main.c
<reponame>peroff/8-Bit-Tea-Party<gh_stars>10-100 #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int power(int base, int n) { int r = 1; for (int i = 1; i <= n; ++i) r = r * base; return r; } float celsius(int fahr) { float r = (5.0 / 9.0) * (fahr - 32); return r; } int getline(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != '\n'; ++i) s[i] = c; s[i] = '\0'; return i; } void copy(char to[], char from[]) { int i = 0; while ((to[i] = from[i]) != '\0') ++i; } int length(char s[]) { int i = 0; while (s[i] != '\0') ++i; return i; } void reverse(char s[]) { for (int i = 0, j = length(s) - 1; i < j; ++i, --j) { char c = s[i]; s[i] = s[j]; s[j] = c; } } void chapter_1() { printf("Hello World!\n"); printf("\nChapter 1.\n"); printf("\nHorizontal tab:\t\tHello!\n"); printf("Vertical tab:\vHello!\n"); printf("Hello!\b.\n"); printf("\tCarriage return.\rOk.\n"); printf("New page.\f\n"); printf("Sound beeper.\a\n"); printf("Hex char 'A': \x41\n"); printf("\nFahrenheit:\tCelsius:\n"); float fahr, cels; int lower = 0, upper = 200, step = 20; fahr = lower; while (fahr <= upper) { cels = (5.0 / 9.0) * (fahr - 32.0); printf("%3.0f\t\t%.2f\n", fahr, cels); fahr = fahr + step; } printf("\nCelsius:\tFahrenheit:\n"); #define CelsMax 100 #define CelsMin 0 #define CelsStep 10 lower = CelsMin; upper = CelsMax; step = CelsStep; cels = lower; while (cels <= CelsMax) { fahr = cels * (9.0 / 5.0) + 32.0; printf("%.2f\t\t%3.0f\n", cels, fahr); cels = cels + CelsStep; } printf("\nFahrenheit:\tCelsius, using operator for.\n"); for (int fahr = 0; fahr <= 200; fahr = fahr + 20) printf("%d\t\t%.2f\n", fahr, (5.0 / 9.0) * (fahr - 32)); printf("\nCelsius:\tFahrenheit, using operator for.\n"); for (int cels = 100; cels >= 0; cels = cels - 10) printf("%d\t\t%.2f\n", cels, cels * (9.0 / 5.0) + 32.0); printf("\nStandard input/output stream, enter for exit, not EOF.\n"); int c = 0; while ((c = getchar()) != '\n') putchar(c); printf("\nConstant EOF = %d and logic (c != EOF) is %d\n", EOF, (c != EOF)); #define IN 1 #define OUT 0 printf("\nCount for chars, lines, spaces and tabs in stream, enter to exit.\n"); int size = 0, lines = 0, spaces = 0, tabs = 0; int prev = 0, state = OUT, word = 0; while ((c = getchar()) != '\n') { ++size; if (c == '\n') ++lines; if (c == '\t') ++tabs; if (c == ' ') ++spaces; if (c == ' ' || c == '\t' || c == '\n') { if (state == IN) putchar('\n'); state = OUT; } else if (state == OUT) { state = IN; ++word; } if (c == '\t') { putchar('\\'); putchar('t'); } else if (c == '\b') { putchar('\\'); putchar('b'); } else if (c == '\\') { putchar('\\'); putchar('\\'); } else if (c != ' ' || prev != ' ') putchar(c); prev = c; } printf("\nChars %d, lines %d, spaces %d, tabs %d\n", size, lines, spaces, tabs); printf("All words in stream %d\n", word); printf("\nDigits in stream.\n"); int digits[10], chars[256], words[10]; word = 0; for (int i = 0; i < 10; ++i) { digits[i] = 0; words[i] = 0; } for (int i = 0; i < 256; ++i) chars[i] = 0; while ((c = getchar()) != '\n') { if (c >= ' ' && c <= '~') ++chars[c]; if (c >= '0' && c <= '9') ++digits[c - '0']; if (c == ' ' || c == '\t') { if (word > 0) ++words[--word]; word = 0; } else if (word == 0) word = 1; if (word > 0) { ++word; putchar(c); } } if (word > 0) ++words[--word]; printf("\nDigits frequency in stream: "); for (int i = 0; i < 10; ++i) if (digits[i] > 0) printf("%d[%d] ", i, digits[i]); printf("\nChars frequency in stream: "); for (int i = 0; i < 256; ++i) if (chars[i] > 0) printf("%c[%d] ", i, chars[i]); printf("\nWords frequency in stream, length: "); for (int i = 0; i < 10; ++i) if (words[i] > 0) printf("%d[%d] ", i, words[i]); printf("\n\nPower function(5,3) = %d\n", power(5,3)); printf("\nFahrenheit:\tCelsius:\n"); for (int fahr = 0; fahr <= 200; fahr = fahr + 20) { float cels = celsius(fahr); printf("%d\t\t%.2f\n", fahr, cels); } #define MAXLINE 0x100 char line[MAXLINE], longest[MAXLINE]; int max = 0, len, longer = 5; printf("\nThe longest string in stream. Empty string to exit.\n"); printf("Echo strings with length more than %d.\n", longer); printf("Spaces and tabs in tail of strings will be removed.\n"); printf("All strings in stream reversed.\n"); while ((len = getline(line, MAXLINE)) > 0) { reverse(line); int i = len; while ((i > 0) && (line[i - 1] == '\t' || line[i - 1] == ' ')) line[--i] = '\0'; if (i < len) printf("String '%s' has extra tabs and spaces in tail.\n", line); else printf("String has no extra tail.\n"); len = i; if (len > longer) printf("String '%s' is longer than %d.\n", line, longer); if (len > max) { copy(longest, line); max = len; } } if (max > 0) printf("The longest string '%s' with length %d.\n", longest, max); else printf("No strings was found in stream.\n"); int tabSize = 8, column = 0; printf("\nReplace all tabs in stream, with spaces.\n"); printf("TABS:\t1:\t2:\t3:\t4:\t5:\n"); while ((c = getchar()) != '\n') { if (c == '\t') { do { putchar('.'); ++column; } while (column % tabSize != 0); } else { putchar(c); ++column; } } putchar('\n'); printf("\nReplace extra spaces with tabs and spaces.\n"); printf("TABS:\t1:\t2:\t3:\t4:\t5:\n"); column = 0; spaces = 0; while ((c = getchar()) != '\n') { if (c == '\t') column += tabSize - (column % tabSize); else ++column; if (c == ' ') ++spaces; else while (spaces > 0) { putchar(' '); --spaces; } if (spaces > 0) { if (column % tabSize == 0) { putchar('\t'); spaces = 0; } } else putchar(c); } putchar('\n'); longer = 16; printf("\nFormat long strings to %d chars.\n", longer); printf("TABS:\t1:\t2:\t3:\t4:\t5:\n"); while ((len = getline(line, MAXLINE)) > 0) { int word = 0; column = 0; for (int i = 0; i <= length(line); ++i) { if (line[i] == '\t' || line[i] == ' ' || line[i] == '\0') while (word != i) putchar(line[word++]); if (c == '\t') column += tabSize - (column % tabSize); else ++column; if (column > longer) { while ((word < i) && (line[word] == '\t' || line[word] == ' ')) ++word; putchar('\n'); column = i - word + (column - longer); } } putchar('\n'); } // This section need to test next task and various comments types. // Non of variables are using in tasks. char p = '\''; /**/ /**/char s = '/'; const char str[] = "Comment \" in str/ing /* not comment */, after chars // not comment too..."; int ai; // Comment with string and literal char c = 'r'; /* trying many lines*/ /* ai = 0; // Comment with many lines. And string "text". Literal ''. * /* Open comment, but not actual. * */ ai = 15; // In the same line. char w2 = '\"'; /**/// Constant char with all comments. w2 = 'a'; // End of section. printf("\nContent of the file main.c without comments, file must compile correctly.\n"); FILE* main = fopen("main.c", "r"); if (!main) { printf("File main.c does not exist. Check paths.\n"); return; } int isString = 0, isSingleLine = 0, isManyLines = 0; const char brackets[] = "()[]{}"; int bracketCounters[] = { 0, 0, 0, 0, 0, 0 }; while ( (c = getc(main)) != EOF) { if ( !isSingleLine && !isManyLines ) { if ( c == '\\' ) { printf("%c", c); c = getc(main); } else { if ( !isString && ( c == '\'' || c == '"')) isString = c; else if ( isString == c ) isString = 0; if ( !isString ) { if ( c == '/' ) { c = getc(main); if ( c == '*' ) isManyLines = 1; else if ( c == '/' ) isSingleLine = 1; else printf("/"); } } } if ( !isSingleLine && !isManyLines ) { printf("%c", c); int i = 0; while (brackets[i] != '\0' && brackets[i] != c) i++; if ( c == brackets[i] ) bracketCounters[i]++; } } else { if ( isSingleLine && c == '\n' ) { printf("\n"); isSingleLine = 0; } if ( isManyLines && c == '*') { c = getc(main); if ( c == '/' ) isManyLines = 0; } } } printf("\nAll brackets in source file main.c: "); for (int i = 0; i < 6; i++) printf("'%c':%i ", brackets[i], bracketCounters[i]); printf("\n"); fclose(main); } int myisdigit(int c); int my_atoi(char s[]) { int i = 0, n = 0; while (s[i] != '-' && s[i] != '+' && !myisdigit(s[i])) i++; int sign = (s[i] == '-') ? -1 : 1; if (s[i] == '-' || s[i] == '+') i++; while (s[i] >= '0' && s[i] <= '9') n = n * 10 + (s[i++] - '0'); return (n * sign); } int lower(int c) { return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; } int htoi(char s[]) { int n = 0; for (int i = 0; s[i] != '\0'; ++i) { char c = lower(s[i]); if (c >= '0' && c <= '9') n = n * 16 + (c - '0'); else if (c >= 'a' && c <= 'f') n = n * 16 + (c - 'a' + 10); } return n; } void squeeze(char s1[], char s2[]) { int i, j, k; for (i = 0, j = 0; s1[i] != '\0'; ++i) { k = 0; while (s2[k] != '\0' && s2[k] != s1[i]) ++k; if (s2[k] == '\0') s1[j++] = s1[i]; } s1[j] = '\0'; } int any(char s1[], char s2[]) { for (int i = 0; s1[i] != '\0'; ++i) { int j = 0; while (s2[j] != '\0' && s2[j] != s1[i]) ++j; if (s1[i] == s2[j]) return i; } return -1; } unsigned char getbits(unsigned char x, int p, int n) { return (x >> (p + 1 + n)) & ~(0xFF << n); } void printbinary(unsigned char byte, const char message[]) { char binary[CHAR_BIT + 1]; const int tabSize = 8; for (int i = 0; i < CHAR_BIT; ++i) if ((0x01 << i) & byte) binary[CHAR_BIT - (i + 1)] = '1'; else binary[CHAR_BIT - (i + 1)] = '0'; binary[CHAR_BIT] = '\0'; int i = 0; while (message[i] != '\0') ++i; if (i <= tabSize) printf("%s\t\t%d\t%s\n", message, byte, binary); else printf("%s\t%d\t%s\n", message, byte, binary); } int bitcount(unsigned char x) { int b; for (b = 0; x > 0; ++b) x &= (x - 1); return b; } void chapter_2() { printf("Chapter 2.\n"); printf("\nAll basic types and parameters.\n"); printf("Type:\t\tBits[calc]:\tMin:\t\tMax:\n"); int bits = 0; for (char c = 1; c > 0; ++bits) c = c * 2; printf("Signed char\t%d[%d]\t\t%d\t\t%d\n", CHAR_BIT, bits, CHAR_MIN, CHAR_MAX); bits = 0; for (unsigned char c = 1; c > 0; ++bits) c = c * 2; printf("Unsigned char\t%d[%d]\t\t%d\t\t%d\n", CHAR_BIT, bits, 0, UCHAR_MAX); bits = 0; for (short int i = 1; i > 0; ++bits) i = i * 2; printf("Signed short\t%d[%d]\t\t%d\t\t%d\n", bits, bits, SHRT_MIN, SHRT_MAX); bits = 0; for (unsigned short int i = 1; i > 0; ++bits) i = i * 2; printf("Unsigned short\t%d[%d]\t\t%d\t\t%d\n", bits, bits, 0, USHRT_MAX); printf("Signed int\t%d[%d]\t\t%d\t%d\n", sizeof(int) * CHAR_BIT, 31, INT_MIN, INT_MAX); printf("Unsigned int\t%d[%d]\t\t%d\t\t%u\n", sizeof(int) * CHAR_BIT, 32, 0, UINT_MAX); printf("Signed long\t%d[%d]\t\t%ld\t%ld\n", sizeof(long) * CHAR_BIT, 31, LONG_MIN, LONG_MAX); printf("Unsigned long\t%d[%d]\t\t%d\t\t%lu\n", sizeof(long) * CHAR_BIT, 32, 0, ULONG_MAX); printf("\nFloating:\tBits:\tDigits:\tMant:\tMinExp:\tMaxExp:\tMin:\tMax:\n"); printf("Float\t\t%d\t%d\t%d\t%d\t%d\t%2.2g%2.2g\n", sizeof(float) * CHAR_BIT, FLT_DIG, FLT_MANT_DIG, FLT_MIN_EXP, FLT_MAX_EXP, FLT_MIN, FLT_MAX); printf("Double\t\t%d\t%d\t%d\t%d\t%d\t%2.2g%2.2g\n", sizeof(double) * CHAR_BIT, DBL_DIG, DBL_MANT_DIG, DBL_MIN_EXP, DBL_MAX_EXP, DBL_MIN, DBL_MAX); printf("Long double\t%d\t%d\t%d\t%d\t%d\t%2.2f%2.2f\n", sizeof(long double) * CHAR_BIT, LDBL_DIG, LDBL_MANT_DIG, LDBL_MIN_EXP, LDBL_MAX_EXP, LDBL_MIN, LDBL_MAX); enum colors { red, green, blue }; printf("\nEnumeration example. Red %d, green %d and blue %d.\n", red, green, blue); char line[MAXLINE]; const int limit = 5; printf("\nEnter simple string, limit %d chars.\n", limit); for (int i = 0, c = ' '; c != '\0'; ++i) { c = getchar(); if (c == '\n') c = '\0'; else if (i == limit) c = '\0'; else if (c == EOF) c = '\0'; line[i] = c; } printf("String was '%s'.\n", line); char numstr[] = "15"; printf("\nString '%s' to intger %d.\n", numstr, my_atoi(numstr)); int left = 3, right = 5; printf("Values of simple logic operators 'if (%d < %d), integer %d, if (%d == 0), integer %d'.\n", left, right, (left > right), right, (right == 0)); char hexstr[] = "0x1F"; printf("\nString '%s' to integer %d.\n", hexstr, htoi(hexstr)); char str1[] = "abc def eg", str2[] = "eg"; printf("\nDelete extra chars from string '%s'.\n", str1); squeeze(str1, str2); printf("String without chars '%s', '%s'.\n", str2, str1); char str3[] = "e "; printf("\nFinding any char of '%s', in string '%s'.\n", str3, str1); int pos = any(str1, str3); if (pos != -1) printf("Index of first char %d.\n", pos); else printf("No chars was found.\n"); unsigned char x = 171, y = 173; int n = 4, p = 3; printf("\nCopy N %d lower bits from Y %d to X %d to P %d index.\n", n, y, x, p); printf("Step:\t\tValue:\tBinary:\n"); unsigned char mask = 0xFF >> (CHAR_BIT - n); printbinary(mask, "Mask for Y"); printbinary(y, "Y"); y = y & mask; printbinary(y, "Y and Mask"); y = y << p; printbinary(y, "Y roll left"); printbinary(x, "X"); mask = ~((0xFF >> (CHAR_BIT - n)) << p); printbinary(mask, "Mask for X"); x = x & mask; printbinary(x, "X and mask"); x = x | y; printbinary(x, "X or Y"); printf("\nInvert N %d bits in X %d from P %d index.\n", n, x, p); printf("Step:\t\tValue:\tBinary:\n"); printbinary(x, "X"); mask = (0xFF >> (CHAR_BIT - n)) << p; printbinary(mask, "Mask for X"); x = x ^ mask; printbinary(x, "X xor mask"); printf("\nCycle roll to the right N %d bits from X %d.\n", n, x); printf("Step:\t\tValue:\tBinary:\n"); printbinary(x, "X"); mask = (0xFF >> (CHAR_BIT - n)); printbinary(mask, "Mask for X"); unsigned char tail = x & mask; printbinary(tail, "Tail for X"); x = x >> n; printbinary(x, "X roll right"); x = x | (tail << (CHAR_BIT - n)); printbinary(x, "X or tail"); printf("\nBit counter in X %d, %d.\n", x, bitcount(x)); char str4[] = "A bc hd D EG"; printf("\nOriginal string '%s', ", str4); for (int i = 0; str4[i] != '\0'; ++i) str4[i] = lower(str4[i]); printf("with lower chars '%s'.\n", str4); } int binsearch(int x, int v[], int n) { int low = 0, high = n - 1; int mid = (low + high) / 2; while (low <= high && v[mid] != x) { if (x < v[mid]) high = mid - 1; else low = mid + 1; mid = (low + high) / 2; } if (v[mid] == x) return mid; else return -1; } void escape(char s[], char t[]) { int j = 0; for (int i = 0; t[i] != '\0'; ++i) { switch (t[i]) { case '\t': s[j++] = '\\'; s[j++] = 't'; break; case '\n': s[j++] = '\\'; s[j++] = 'n'; break; default: s[j++] = t[i]; break; } } s[j] = '\0'; } void unescape(char s[], char t[]) { int j = 0; for (int i = 0; t[i] != '\0'; ++i) if (t[i] == '\\' && t[i + 1] != '\0') switch (t[i+1]) { case 't': s[j++] = '\t'; ++i; break; case 'n': s[j++] = '\n'; ++i; default: break; } else s[j++] = t[i]; s[j] = '\0'; } int myatois(char s[]) { int i = 0, n, sign = (s[i] == '-') ? -1 : 1; if (s[i] == '+' || s[i] == '-') ++i; for (n = 0; (s[i] >= '0' && s[i] <= '9'); ++i) n = 10 * n + (s[i] - '0'); return sign * n; } int myisalpha(int c) { return (lower(c) >= 'a' && lower(c) <= 'z'); } int myisdigit(int c) { return (c >= '0' && c <= '9'); } void expand(char s1[], char s2[]) { int j = 0; for (int i = 0; s1[i] != '\0'; ++i) { char c = s1[i], c1 = s1[i + 1], c2 = s1[i + 2]; if (c1 == '-' && c2 >= c && ((myisalpha(c) && myisalpha(c2)) || (myisdigit(c) && myisdigit(c2)))) { c1 = c; while (c < c2) s2[j++] = s1[i] + (c++ - c1); ++i; } else s2[j++] = s1[i]; } s2[j] = '\0'; } void myitoa(int n, char s[]) { int i = 0, sign = (n < 0) ? -1 : 1; do { s[i++] = (n % 10) * sign + '0'; } while ((n /= 10) * sign > 0); if (sign == -1) s[i++] = '-'; s[i] = '\0'; reverse(s); } void itob(int n, char s[], int b) { if (b < 2 || b > 16) return; char digits[] = "0123456789ABCDEF"; int i = 0, sign = (n < 0) ? -1 : 1; do { s[i++] = digits[(n * sign) % b]; } while ((n /= b) * sign > 0); if (sign == -1) s[i++] = '-'; s[i] = '\0'; reverse(s); } void myitoafield(int n, char s[], int f) { int i = f - 1, sign = (n < 0) ? -1 : 1; if (f < 1 + (sign == -1)) return; do { s[i--] = (n % 10) * sign + '0'; } while ((n /= 10) * sign > 0 && i >= (sign == -1)); if (sign < 0) s[i--] = '-'; while (i >= 0) s[i--] = ' '; s[f] = '\0'; } void chapter_3() { printf("Chapter 3.\n"); int v[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; printf("\nBinary search in V[0..9], value %d, position %d.\n", 7, binsearch(7, v, 10)); printf("Binary search in V[0..9], value %d, position %d.\n", 0, binsearch(0, v, 10)); printf("Binary search in V[0..9], value %d, position %d.\n", 9, binsearch(9, v, 10)); char s1[] = "\t abc \t\tdef\ngh\t\n", s2[MAXLINE], s3[MAXLINE]; printf("\nString with all espace sequences '%s'.\n", s1); escape(s2, s1); printf("String with all escape sequences '%s'.\n", s2); unescape(s3, s2); printf("String after unescape sequences '%s'.\n", s3); char s4[] = "53"; printf("\nSigned atoi function string %s, to integer %d.\n", s4, myatois(s4)); char s5[] = "-- f-d b-b A-D a-c-f -pre post- 3-7 1-3-5 --"; printf("\nExpanding string '%s'.\n", s5); expand(s5, s2); printf("Expanded string '%s'.\n", s2); int i1 = INT_MIN; myitoa(i1, s2); printf("\nInteger %d to string '%s'.\n", i1, s2); int i2 = -173; itob(i2, s2, 10); printf("\nInteger %d, in decimal '%s'.\n", i2, s2); itob(i2, s2, 2); printf("Integer %d, in binary '%s'.\n", i2, s2); itob(i2, s2, 8); printf("Integer %d, in oct '%s'.\n", i2, s2); itob(i2, s2, 16); printf("Integer %d, in hex '%s'.\n", i2, s2); int i3 = -235; myitoafield(i3, s2, 8); printf("\nInteger %d to string '%s', field %d.\n", i3, s2, 8); myitoafield(i3, s2, 4); printf("Integer %d to string '%s', field %d.\n", i3, s2, 4); char s6[] = "3 tabs and 2 spaces in tail \t\t \t"; printf("\nString with extra tail '%s'.\n", s6); int i; for (i = length(s6) - 1; i >= 0; --i) if (s6[i] != '\t' && s6[i] != ' ' && s6[i] != '\n') break; s6[++i] = '\0'; printf("String without extra tail '%s'.\n", s6); printf("\nTesting operator 'goto'.\n"); int i4 = 5; if (i4 == 7) goto label1; printf("Operand before 'goto' operator.\n"); label1: printf("Operand after 'goto' operator, label 'label1'.\n"); } int str_index(char source[], char search[]); int str_index(char src[], char str[]) { int i, j, k; for (i = 0; src[i] != '\0'; ++i) { for (j = i, k = 0; str[k] != '\0' && str[k] == src[j]; j++, k++) ; if (k > 0 && str[k] == '\0') return i; } return -1; } double my_atof(char s[]) { double value, power, base = 10; int i, sign; for (i = 0; s[i] != '\0' && !myisdigit(s[i]) && s[i] != '+' && s[i] != '-'; i++) ; sign = (s[i] == '-') ? -1 : 1; if (s[i] == '+' || s[i] == '-') i++; for (value = 0.0; myisdigit(s[i]); ++i) value = base * value + (s[i] - '0'); if (s[i] == '.') i++; for (power = 1.0; myisdigit(s[i]); i++) { value = base * value + (s[i] - '0'); power *= base; } if (lower(s[i]) == 'e' && (s[i+1] == '-' || s[i+1] == '+')) { double exp = 0.0, multiplier; multiplier = (s[i+1] == '+') ? base : (1.0 / base); i += 2; while (myisdigit(s[i])) exp = exp * base + (s[i++] - '0'); while (exp > 0) { power /= multiplier; exp -= 1.0; } } return sign * value / power; } static int stack_calc[MAXLINE]; static int sp_calc = 0; void push_calc(int i) { if (sp_calc < MAXLINE) stack_calc[sp_calc++] = i; else printf("Stack is full, no more push.\n"); } int pop_calc() { if (sp_calc > 0) return stack_calc[--sp_calc]; else { printf("No values in stack."); return -1; } } void chapter_4() { printf("Chapter 4.\n"); /* char line[MAXLINE], search[] = "ab"; int i1 = 0; printf("Enter strings with possible substring '%s' or empty to exit.\n", search); while (getline(line, MAXLINE) > 0) if (str_index(line, search) >= 0) { printf("String with '%s' substring - %s.\n", search, line); ++i1; } else printf("String does not contains substring '%s'.\n", search); printf("All findings %d.\n", i1); printf("\nConvert strings to double.\n"); char num1[] = "0.0", num2[] = "-0.15", num3[] = "+100.0"; char num4[] = "10.5e+2", num5[] = "-5.1E-1"; printf("%s\t%0.3f\n", num1, my_atof(num1)); printf("%s\t%0.3f\n", num2, my_atof(num2)); printf("%s\t%0.3f\n", num3, my_atof(num3)); printf("%s\t%0.3f\n", num4, my_atof(num4)); printf("%s\t%0.3f\n", num5, my_atof(num5)); */ printf("Calculator with reverse polish notation.\n"); printf("Empty string for exit: "); char s[MAXLINE], n[MAXLINE]; while ((getline(s, MAXLINE)) != 0) { int i, j, r_op; printf("Index:\tStack:\tOperator:\n"); for (i = 0; s[i] != '\0'; i++) { printf("\n%d\t", i); for (j = 0; j < sp_calc; j++) printf("%d ", stack_calc[j]); switch (s[i]) { case '+': printf("\t+"); push_calc(pop_calc() + pop_calc()); break; case '-': printf("\t-"); r_op = pop_calc(); push_calc(pop_calc() - r_op); break; case '*': printf("\t*"); push_calc(pop_calc() * pop_calc()); break; case '/': printf("\t/"); r_op = pop_calc(); push_calc(pop_calc() / r_op); break; default: for (j = 0; myisdigit(s[i]); n[j++] = s[i++]); if (j > 0) { n[j] = '\0'; int d = my_atoi(n); push_calc(d); printf("[%d]", d); break; } } } printf("\nResult: %d", pop_calc()); } } int main() { chapter_4(); return 0; }
peroff/8-Bit-Tea-Party
Science/Questions/07 Playing with factorial and recursion.c
#include <stdio.h> #include <limits.h> // Вещание на канале 8-Bit-Tea-Party. /* rerum: Написать программу, которая проверят является ли введенное значение факториалом, если это так, то вывести факториалом какого числа. Программа должна иметь примитивное «меню». Пользователю должно быть предложено: Нахождение факториала рекурсивным методом. Нахождение факториала не рекурсивным методом. Выход из программы. После вывода результата перед завершение программа должна передоложить повторный ввод пользователю. */ int getline(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != '\n'; ++i) s[i] = c; s[i] = '\0'; return i; } int myisdigit(int c) { return (c >= '0' && c <= '9'); } int my_atoi(char s[]) { int i = 0, n = 0; while (s[i] != '-' && s[i] != '+' && !myisdigit(s[i])) i++; int sign = (s[i] == '-') ? -1 : 1; if (s[i] == '-' || s[i] == '+') i++; while (s[i] >= '0' && s[i] <= '9') n = n * 10 + (s[i++] - '0'); return (n * sign); } unsigned int is_factorial_mult(unsigned int n) { if (n <= 1) return 1; unsigned int d = 1, s = 1; while (s < n) { d++; s = s * d; printf("Number %u and factorial %u.\n", s, d); } if(s == n) return d; return 0; } unsigned int is_factorial_cycles(unsigned int n) { unsigned int m = 2; while (n > 1 && n % m == 0) { n /= m++; printf("Number %u and delimeter %u.\n", n, m); } if (n == 1) return --m; return 0; } unsigned int is_factorial_recursion(unsigned int n, unsigned int m) { if (n == 1) return --m; if (n % m != 0) return 0; n = n / m; m++; printf("Number %u and delimiter %u.\n", n, m); return is_factorial_recursion(n, m); } int main() { #define MAXLINE 256 printf("Unsinged integer is %u bytes and maxiumum value is %u.\n", sizeof(unsigned int), UINT_MAX); char s[MAXLINE]; printf("Enter number that can factorial of any number in [0..12], empty string to exit.\n"); while (getline(s, MAXLINE)) { unsigned int n = (unsigned int)my_atoi(s); if (n > 1 && n <= 479001600) { printf("Finding factorial of N = %u, using multiplier.\n", n); printf("N = %u is factorial of %u.\n", n, is_factorial_mult(n)); printf("Finding factorial of N = %u, using delemiter.\n", n); printf("N = %u is factorial of %u.\n", n, is_factorial_cycles(n)); printf("Finding factorial of N = %u, using recursion.\n", n); printf("N = %u is factorial of %u.\n", n, is_factorial_recursion(n, 1)); } else printf("Factorial is 1.\n"); } return 0; }
mingduo/Masonry
MasonryDemo/MasonryDemo/UserMarginView.h
// // UserMarginView.h // MasonryDemo // // Created by Mr.LuDashi on 16/5/4. // Copyright © 2016年 zeluli. All rights reserved. // #import <UIKit/UIKit.h> @interface UserMarginView : UIView @end
mingduo/Masonry
MasonryDemo/MasonryDemo/BasicAnimatedView.h
<reponame>mingduo/Masonry<filename>MasonryDemo/MasonryDemo/BasicAnimatedView.h // // BasicAnimatedView.h // MasonryDemo // // Created by Mr.LuDashi on 16/5/3. // Copyright © 2016年 zeluli. All rights reserved. // #import <UIKit/UIKit.h> @interface BasicAnimatedView : UIView @end
mingduo/Masonry
MasonryDemo/MasonryDemo/SubViewController.h
<reponame>mingduo/Masonry // // SubViewController.h // MasonryDemo // // Created by ZeluLi on 16/5/2. // Copyright © 2016年 zeluli. All rights reserved. // #import <UIKit/UIKit.h> @interface SubViewController : UIViewController - (instancetype)initWithTitle:(NSString *)title viewClass:(Class)viewClass; @end
mingduo/Masonry
MasonryDemo/MasonryDemo/DistributeView.h
<reponame>mingduo/Masonry<gh_stars>0 // // DistributeView.h // MasonryDemo // // Created by Mr.LuDashi on 16/5/4. // Copyright © 2016年 zeluli. All rights reserved. // #import <UIKit/UIKit.h> @interface DistributeView : UIView @end
mingduo/Masonry
MasonryDemo/MasonryDemo/MasonryTableViewController.h
// // MasonryTableViewController.h // MasonryDemo // // Created by ZeluLi on 16/5/2. // Copyright © 2016年 zeluli. All rights reserved. // #import <UIKit/UIKit.h> @interface MasonryTableViewController : UITableViewController @end
willmexe/opuntiaOS
kernel/include/platform/generic/vmm/pde.h
#ifdef __i386__ #include <platform/x86/vmm/pde.h> #elif __arm__ #include <platform/aarch32/vmm/pde.h> #endif
willmexe/opuntiaOS
libs/libc/include/shadow.h
<filename>libs/libc/include/shadow.h #ifndef _LIBC_SHADOW_H #define _LIBC_SHADOW_H #include <sys/cdefs.h> #include <sys/types.h> __BEGIN_DECLS struct spwd { char* sp_namp; char* sp_pwdp; int sp_lstchg; int sp_min; int sp_max; int sp_warn; int sp_inact; int sp_expire; uint32_t sp_flag; }; typedef struct spwd spwd_t; void setspent(); void endspent(); spwd_t* getspent(); spwd_t* getspnam(const char* name); __END_DECLS #endif // _LIBC_SHADOW_H
willmexe/opuntiaOS
kernel/kernel/fs/procfs/sysctl.c
<filename>kernel/kernel/fs/procfs/sysctl.c<gh_stars>0 /* * Copyright (C) 2020-2022 The opuntiaOS Project Authors. * + Contributed by <NAME> <<EMAIL>> * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <fs/procfs/procfs.h> #include <fs/vfs.h> #include <libkern/bits/errno.h> #include <libkern/libkern.h> #include <tasking/tasking.h> /** * inode: xxxxBBBBBBBBBBBBBBBBBBBBBBBBBBBB * x - level bits * B - bits of files at this level */ #define PROCFS_SYS_LEVEL 3 static int _sysctl_enable = 1; /* PID */ int procfs_sys_getdents(dentry_t* dir, uint8_t* buf, off_t* offset, size_t len); int procfs_sys_lookup(dentry_t* dir, const char* name, size_t len, dentry_t** result); /* FILES */ static bool procfs_sys_doint_can_read(dentry_t* dentry, size_t start); static int procfs_sys_doint_read(dentry_t* dentry, uint8_t* buf, size_t start, size_t len); /** * DATA */ const file_ops_t procfs_sys_ops = { .getdents = procfs_sys_getdents, .lookup = procfs_sys_lookup, }; const file_ops_t procfs_sys_doint_ops = { .can_read = procfs_sys_doint_can_read, .read = procfs_sys_doint_read, }; static const procfs_files_t static_procfs_files[] = { { .name = "sysctl_enable", .mode = 0444, .ops = &procfs_sys_doint_ops, .data = &_sysctl_enable }, }; #define PROCFS_STATIC_FILES_COUNT_AT_LEVEL (sizeof(static_procfs_files) / sizeof(procfs_files_t)) /** * HELPERS */ static const procfs_files_t* procfs_sys_get_sfile(dentry_t* file) { uint32_t body = procfs_inode_get_body(file->inode_indx); if (body >= PROCFS_STATIC_FILES_COUNT_AT_LEVEL) { return NULL; } return &static_procfs_files[body]; } static uint32_t procfs_sys_sfiles_get_inode_index(dentry_t* dir, int fileid) { return procfs_inode_get_index(PROCFS_SYS_LEVEL, fileid); } /** * PID */ int procfs_sys_getdents(dentry_t* dir, uint8_t* buf, off_t* offset, size_t len) { int already_read = 0; dirent_t tmp; for (int i = 0; i < PROCFS_STATIC_FILES_COUNT_AT_LEVEL; i++) { if (*offset <= i) { uint32_t inode_index = procfs_sys_sfiles_get_inode_index(dir, i); ssize_t read = vfs_helper_write_dirent((dirent_t*)(buf + already_read), len, inode_index, static_procfs_files[i].name); if (read <= 0) { if (!already_read) { return -EINVAL; } return already_read; } already_read += read; len -= read; (*offset)++; } } return already_read; } int procfs_sys_lookup(dentry_t* dir, const char* name, size_t len, dentry_t** result) { procfs_inode_t* procfs_inode = (procfs_inode_t*)dir->inode; if (len == 1) { if (name[0] == '.') { *result = dentry_duplicate(dir); return 0; } } if (len == 2) { if (name[0] == '.' && name[1] == '.') { *result = dentry_duplicate(dir->parent); return 0; } } for (int i = 0; i < PROCFS_STATIC_FILES_COUNT_AT_LEVEL; i++) { uint32_t child_name_len = strlen(static_procfs_files[i].name); if (len == child_name_len) { if (strncmp(name, static_procfs_files[i].name, len) == 0) { int newly_allocated; *result = dentry_get_no_inode(dir->dev_indx, procfs_sys_sfiles_get_inode_index(dir, i), &newly_allocated); if (newly_allocated) { procfs_inode_t* new_procfs_inode = (procfs_inode_t*)((*result)->inode); new_procfs_inode->mode = static_procfs_files[i].mode; new_procfs_inode->ops = static_procfs_files[i].ops; } return 0; } } } return -ENOENT; } /** * FILES */ static bool procfs_sys_doint_can_read(dentry_t* dentry, size_t start) { return true; } static int procfs_sys_doint_read(dentry_t* dentry, uint8_t* buf, size_t start, size_t len) { int* data = procfs_sys_get_sfile(dentry)->data; char res[16]; snprintf(res, 16, "%d", *data); size_t size = strlen(res); if (start == size) { return 0; } if (len < size) { return -EFAULT; } memcpy(buf, res, size); return size; }
willmexe/opuntiaOS
kernel/kernel/drivers/x86/bga.c
<filename>kernel/kernel/drivers/x86/bga.c /* * Copyright (C) 2020-2022 The opuntiaOS Project Authors. * + Contributed by <NAME> <<EMAIL>> * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <drivers/driver_manager.h> #include <drivers/x86/bga.h> #include <drivers/x86/pci.h> #include <fs/devfs/devfs.h> #include <fs/vfs.h> #include <libkern/bits/errno.h> #include <libkern/libkern.h> #include <libkern/log.h> #include <tasking/proc.h> #include <tasking/tasking.h> #define VBE_DISPI_IOPORT_INDEX 0x01CE #define VBE_DISPI_IOPORT_DATA 0x01CF #define VBE_DISPI_INDEX_ID 0x0 #define VBE_DISPI_INDEX_XRES 0x1 #define VBE_DISPI_INDEX_YRES 0x2 #define VBE_DISPI_INDEX_BPP 0x3 #define VBE_DISPI_INDEX_ENABLE 0x4 #define VBE_DISPI_INDEX_BANK 0x5 #define VBE_DISPI_INDEX_VIRT_WIDTH 0x6 #define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7 #define VBE_DISPI_INDEX_X_OFFSET 0x8 #define VBE_DISPI_INDEX_Y_OFFSET 0x9 #define VBE_DISPI_DISABLED 0x00 #define VBE_DISPI_ENABLED 0x01 #define VBE_DISPI_LFB_ENABLED 0x40 static uint16_t bga_screen_width, bga_screen_height; static uint32_t bga_screen_line_size, bga_screen_buffer_size; static uint32_t bga_buf_paddr; static int _bga_swap_page_mode(struct memzone* zone, uintptr_t vaddr) { return SWAP_NOT_ALLOWED; } static vm_ops_t mmap_file_vm_ops = { .load_page_content = NULL, .restore_swapped_page = NULL, .swap_page_mode = _bga_swap_page_mode, }; static inline void _bga_write_reg(uint16_t cmd, uint16_t data) { port_16bit_out(VBE_DISPI_IOPORT_INDEX, cmd); port_16bit_out(VBE_DISPI_IOPORT_DATA, data); } static inline uint16_t _bga_read_reg(uint16_t cmd) { port_16bit_out(VBE_DISPI_IOPORT_INDEX, cmd); return port_16bit_in(VBE_DISPI_IOPORT_DATA); } static void _bga_set_resolution(uint16_t width, uint16_t height) { _bga_write_reg(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_DISABLED); _bga_write_reg(VBE_DISPI_INDEX_XRES, width); _bga_write_reg(VBE_DISPI_INDEX_YRES, height); _bga_write_reg(VBE_DISPI_INDEX_VIRT_WIDTH, width); _bga_write_reg(VBE_DISPI_INDEX_VIRT_HEIGHT, (uint16_t)height * 2); _bga_write_reg(VBE_DISPI_INDEX_BPP, 32); _bga_write_reg(VBE_DISPI_INDEX_X_OFFSET, 0); _bga_write_reg(VBE_DISPI_INDEX_Y_OFFSET, 0); _bga_write_reg(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_ENABLED | VBE_DISPI_LFB_ENABLED); _bga_write_reg(VBE_DISPI_INDEX_BANK, 0); bga_screen_line_size = (uint32_t)width * 4; } static int _bga_ioctl(dentry_t* dentry, uint32_t cmd, uint32_t arg) { uint32_t y_offset = 0; switch (cmd) { case BGA_GET_HEIGHT: return bga_screen_height; case BGA_GET_WIDTH: return bga_screen_width; case BGA_SWAP_BUFFERS: y_offset = bga_screen_height * (arg & 1); _bga_write_reg(VBE_DISPI_INDEX_Y_OFFSET, (uint16_t)y_offset); return 0; default: return -EINVAL; } } static memzone_t* _bga_mmap(dentry_t* dentry, mmap_params_t* params) { bool map_shared = ((params->flags & MAP_SHARED) > 0); if (!map_shared) { return 0; } memzone_t* zone = memzone_new_random(RUNNING_THREAD->process, bga_screen_buffer_size); if (!zone) { return 0; } zone->flags |= ZONE_WRITABLE | ZONE_READABLE | ZONE_NOT_CACHEABLE; zone->type |= ZONE_TYPE_DEVICE; zone->file = dentry_duplicate(dentry); zone->ops = &mmap_file_vm_ops; for (int offset = 0; offset < bga_screen_buffer_size; offset += VMM_PAGE_SIZE) { vmm_map_page(zone->start + offset, bga_buf_paddr + offset, zone->flags); } return zone; } static void bga_recieve_notification(uint32_t msg, uint32_t param) { if (msg == DEVMAN_NOTIFICATION_DEVFS_READY) { dentry_t* mp; if (vfs_resolve_path("/dev", &mp) < 0) { kpanic("Can't init bga in /dev"); } file_ops_t fops = { 0 }; fops.ioctl = _bga_ioctl; fops.mmap = _bga_mmap; devfs_inode_t* res = devfs_register(mp, MKDEV(10, 156), "bga", 3, 0777, &fops); dentry_put(mp); } } static inline driver_desc_t _bga_driver_info() { driver_desc_t bga_desc = { 0 }; bga_desc.type = DRIVER_VIDEO_DEVICE; bga_desc.listened_device_mask = DEVICE_DISPLAY; bga_desc.system_funcs.init_with_dev = bga_init_with_dev; bga_desc.system_funcs.recieve_notification = bga_recieve_notification; bga_desc.functions[DRIVER_VIDEO_INIT] = NULL; bga_desc.functions[DRIVER_VIDEO_SET_RESOLUTION] = bga_set_resolution; return bga_desc; } void bga_install() { devman_register_driver(_bga_driver_info(), "bga86"); } devman_register_driver_installation(bga_install); int bga_init_with_dev(device_t* dev) { if (dev->device_desc.type != DEVICE_DESC_PCI) { return -1; } if (dev->device_desc.pci.class_id != 0x03) { return -1; } if (dev->device_desc.pci.vendor_id != 0x1234) { return -1; } if (dev->device_desc.pci.device_id != 0x1111) { return -1; } bga_buf_paddr = pci_read_bar(dev, 0) & 0xfffffff0; #ifdef TARGET_DESKTOP bga_set_resolution(1024, 768); #elif TARGET_MOBILE bga_set_resolution(320, 568); #endif return 0; } void bga_set_resolution(uint16_t width, uint16_t height) { _bga_set_resolution(width, height); bga_screen_width = width; bga_screen_height = height; bga_screen_buffer_size = bga_screen_line_size * (uint32_t)height * 2; }
willmexe/opuntiaOS
libs/libc/include/sys/_types/_ints.h
<filename>libs/libc/include/sys/_types/_ints.h #ifndef _LIBC_SYS__TYPES__INTS_H #define _LIBC_SYS__TYPES__INTS_H #include <bits/types.h> #ifndef __stdints_defined #define __stdints_defined typedef __int8_t int8_t; typedef __int16_t int16_t; typedef __int32_t int32_t; typedef __int64_t int64_t; typedef __uint8_t uint8_t; typedef __uint16_t uint16_t; typedef __uint32_t uint32_t; typedef __uint64_t uint64_t; #endif // __stdints_defined #ifndef __dev_t_defined #define __dev_t_defined typedef __dev_t dev_t; #endif // __dev_t_defined #ifndef __uid_t_defined #define __uid_t_defined typedef __uid_t uid_t; #endif // __uid_t_defined #ifndef __gid_t_defined #define __gid_t_defined typedef __gid_t gid_t; #endif // __gid_t_defined #ifndef __ino_t_defined #define __ino_t_defined typedef __ino_t ino_t; #endif // __ino_t_defined #ifndef __ino64_t_defined #define __ino64_t_defined typedef __ino64_t ino64_t; #endif // __ino64_t_defined #ifndef __mode_t_defined #define __mode_t_defined typedef __mode_t mode_t; #endif // __mode_t_defined #ifndef __nlink_t_defined #define __nlink_t_defined typedef __nlink_t nlink_t; #endif // __nlink_t_defined #ifndef __off_t_defined #define __off_t_defined typedef __off_t off_t; #endif // __off_t_defined #ifndef __off64_t_defined #define __off64_t_defined typedef __off64_t off64_t; #endif // __off64_t_defined #ifndef __pid_t_defined #define __pid_t_defined typedef __pid_t pid_t; #endif // __pid_t_defined #ifndef __fsid_t_defined #define __fsid_t_defined typedef __fsid_t fsid_t; #endif // __fsid_t_defined #ifndef __time_t_defined #define __time_t_defined typedef __time_t time_t; #endif // __time_t_defined #endif // _LIBC_SYS__TYPES__INTS_H
willmexe/opuntiaOS
libs/libc/init/_lib.c
<gh_stars>100-1000 int errno; char** environ; int __environ_malloced = 0; extern int _stdio_init(); extern int _stdio_deinit(); extern int _malloc_init(); void _libc_init(int argc, char* argv[], char* envp[]) { environ = envp; _malloc_init(); _stdio_init(); extern void (*__init_array_start[])(int, char**, char**) __attribute__((visibility("hidden"))); extern void (*__init_array_end[])(int, char**, char**) __attribute__((visibility("hidden"))); const unsigned int size = __init_array_end - __init_array_start; for (unsigned int i = 0; i < size; i++) { (*__init_array_start[i])(argc, argv, envp); } } void _libc_deinit() { _stdio_deinit(); }
willmexe/opuntiaOS
libs/libipc/include/libipc/Message.h
#pragma once #include <sys/types.h> #include <vector> typedef std::vector<uint8_t> EncodedMessage; typedef int message_key_t; class Message { public: Message() = default; virtual ~Message() = default; virtual int decoder_magic() const { return 0; } virtual int id() const { return 0; } virtual message_key_t key() const { return -1; } virtual int reply_id() const { return -1; } // -1 means that there is no reply. virtual EncodedMessage encode() const { return std::vector<uint8_t>(); } };