3
0
Fork 0
mirror of https://github.com/Z3Prover/z3 synced 2025-11-01 12:07:51 +00:00
z3/README-CMake.md
Ilana Shapiro e4a285187b
Setting up param tuning infrastructure in C++ (#8006)
* draft attempt at optimizing cube tree with resolvents. have not tested/ran yet

* adding comments

* fix bug about needing to bubble resolvent upwards to highest ancestor

* fix bug where we need to cover the whole resolvent in the path when bubbling up

* clean up comments

* Bump actions/checkout from 4 to 5 (#7954)

Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* close entire tree when sibling resolvent is empty

* integrate asms directly into cube tree, remove separate tracking

* try to fix bug about redundant resolutions, merging close and try_resolve_upwards into once function

* separate the logic again to avoid mutual recursion

* [WIP] Add a mutex to warning.cpp to ensure that warning messages from different threads don't interfere (#7963)

* Initial plan

* Add mutex to warning.cpp for thread safety

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Remove unused variable 'first' in mpz.cpp

Removed unused variable 'first' from the function.

* fixing the order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* fixing the order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* fix the order of parameter evaluation

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* remove AI slop

Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* param order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* param order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* param order evaluation

* parameter eval order

* parameter evaluation order

* param eval

* param eval order

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* parameter eval order

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* Bump github/codeql-action from 3 to 4 (#7971)

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3 to 4.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Update Z3_mk_datatype_sort API to accept array of sort parameters and add Z3_mk_polymorphic_datatype (#7966)

* Initial plan

* Update Z3_mk_datatype_sort API to accept array of parameters

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Update language bindings for parametric datatype sort API

- Python: Updated DatatypeSort() to accept optional params list
- OCaml: Added mk_sort_ref_p/mk_sort_ref_ps for parametric datatypes
- .NET: Added MkDatatypeSortRef() methods with optional params
- Java: Added mkDatatypeSortRef() methods with optional params
- All changes maintain backward compatibility

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Fix .NET build error - rename params to parameters

The 'params' keyword is reserved in C#, causing compilation errors.
Renamed parameter from 'params' to 'parameters' in MkDatatypeSortRef methods.

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Add unit test for parametric datatypes

Added test_parametric_datatype.cpp to demonstrate polymorphic datatypes.
The test creates two concrete instantiations of a generic pair concept:
- pair_int_real with fields (first:Int, second:Real)
- pair_real_int with fields (first:Real, second:Int)
Then verifies that accessors work correctly and type checking is enforced.

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Implement polymorphic type variables support for parametric datatypes

- Modified datatype_decl_plugin to allow type variables as parameters
- Updated mk_datatype_decl to extract type variables from field sorts
- Type variables are collected in order of first appearance
- Revised unit test to use Z3_mk_type_variable for polymorphic datatypes
- Test creates pair datatype with type variables alpha and beta
- Successfully instantiates with concrete types (pair Int Real) and (pair Real Int)
- Verifies accessor types match and equality terms are well-typed
- All tests pass

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Add Z3_mk_polymorphic_datatype API and refactor datatype creation

- Added new API Z3_mk_polymorphic_datatype to z3_api.h
- Renamed static mk_datatype_decl to api_datatype_decl in api_datatype.cpp
- Modified api_datatype_decl to accept explicit type parameters
- Updated all callers to use renamed function
- Added test_polymorphic_datatype_api demonstrating new API usage
- Both tests pass successfully

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Remove type variable collection logic from constructors

Removed the logic for collecting type variables from field sorts based on constructors.

* Update comments on parameter handling in api_datatype.cpp

Clarify usage of parameters in API documentation.

* Fix OCaml build error - use list instead of array for mk_datatype_sort

Changed mk_sort_ref to pass empty list [] instead of empty array [||].
Changed mk_sort_ref_p to pass params list directly instead of converting to array.
Z3native.mk_datatype_sort expects a list, not an array.

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Add polymorphic datatype example to C++ examples

Added polymorphic_datatype_example() demonstrating:
- Creating type variables alpha and beta with Z3_mk_type_variable
- Defining parametric Pair datatype with fields of type alpha and beta
- Instantiating with concrete types (Pair Int Real) and (Pair Real Int)
- Getting constructors and accessors from instantiated datatypes
- Creating constants and expressions using the polymorphic types
- Verifying type correctness with equality (= (first p1) (second p2))

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Co-authored-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* trim parametric datatype test

Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* restore single cell

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* restore the method behavior

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* setting up python tuning experiment, not done

* Add finite_set_value_factory for creating finite set values in model generation (#7981)

* Initial plan

* Add finite_set_value_factory implementation

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Remove unused dl_decl_plugin variable and include

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Update copyright and add TODOs in finite_set_value_factory

Updated copyright information and added TODO comments for handling in finite_set_value_factory methods.

* Update copyright information in finite_set_value_factory.h

Updated copyright year from 2006 to 2025.

* Implement finite_set_value_factory using array_util to create singleton sets

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Simplify empty set creation in finite_set_value_factory

Refactor finite_set_value_factory to simplify empty set handling and remove array-specific logic.

* Change family ID for finite_set_value_factory

* Fix build error by restoring array_decl_plugin include and implementation

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Update finite_set_value_factory.h

* Add SASSERT for finite set check in factory

Added assertion to check if the sort is a finite set.

* Rename member variable from m_util to u

* Refactor finite_set_value_factory for value handling

* Use register_value instead of direct set insertion

Replaced direct insertion into set with register_value calls.

* Update finite_set_value_factory.cpp

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Co-authored-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* Revert "Add finite_set_value_factory for creating finite set values in model …" (#7985)

This reverts commit 05ffc0a77b.

* Update arith_rewriter.cpp

fix memory leak introduced by update to ensure determinism

* update pythonnn prototyping experiment, need to add a couple more things

* add explicit constructors for nightly mac build failure

Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* build fixes

Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* fixes

* fix some more things but now it hangs

* change multithread to multiprocess seems to have resolved current deadlock

* fix some bugs, it seems to run now

* fix logic about checking clauses individually, and add proof prefix clause selection (naively) via the OnClause hook

* disable manylinux until segfault is resolved

Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>

* add the  "noexcept" keyword to value_score=(value_score&&) declaration

* expose a status flag for clauses but every single one is being coded as an assumption...

* Add a fast-path to _coerce_exprs. (#7995)

When the inputs are already the same sort, we can skip most of the
coercion logic and just return.

Currently, `_coerce_exprs` is by far the most expensive part of
building up many common Z3 ASTs, so this fast-path is a substantial
speedup for many use-cases.

* Bump actions/setup-node from 5 to 6 (#7994)

Bumps [actions/setup-node](https://github.com/actions/setup-node) from 5 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Enabling Control Flow Guard (CFG) by default for MSVC on Windows, with options to disable CFG. (#7988)

* Enabling Control Flow Guard by default for MSVC on Windows, with options to disable it.

* Fix configuration error for non-MSVC compilers.

* Reviewed and updated configuration for Python build and added comment for CFG.

* try exponential delay in grobner

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* throttle grobner method more actively

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* enable always add all coeffs in nlsat

Signed-off-by: Lev Nachmanson <levnach@hotmail.com>

* initial parameter probe thread setup in C++

* more param tuning setup

* setting up the param probe solvers and mutation generator

* adding the learned clauses from the internalizer

* fix some things for clause replay

* score the param probes, but i can't figure out how to access the relevant solver statistics fields from the statistics obj

* set up pattern to notify batch manager so worker threads can update their params according
ly

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Lev Nachmanson <levnach@hotmail.com>
Signed-off-by: Nikolaj Bjorner <nbjorner@microsoft.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Co-authored-by: Nikolaj Bjorner <nbjorner@microsoft.com>
Co-authored-by: Lev Nachmanson <levnach@hotmail.com>
Co-authored-by: Nelson Elhage <nelhage@nelhage.com>
Co-authored-by: hwisungi <hwisungi@users.noreply.github.com>
2025-10-30 03:15:32 -07:00

26 KiB

Z3's CMake build system

CMake is a "meta build system" that reads a description of the project written in the CMakeLists.txt files and emits a build system for that project of your choice using one of CMake's "generators". This allows CMake to support many different platforms and build tools. You can run cmake --help to see the list of supported "generators" on your platform. Example generators include "UNIX Makefiles" and "Visual Studio 12 2013".

Getting started

Fixing a polluted source tree

If you have never used the python build system you can skip this step.

The existing Python build system creates generated source files in the source tree. The CMake build system will refuse to work if it detects this so you need to clean your source tree first.

To do this run the following in the root of the repository

git clean -nx src

This will list everything that will be removed. If you are happy with this then run.

git clean -fx src

which will remove the generated source files.

Unix Makefiles

Run the following in the top level directory of the Z3 repository.

mkdir build
cd build
cmake -G "Unix Makefiles" ../
make -j4 # Replace 4 with an appropriate number

Note that on some platforms "Unix Makefiles" is the default generator so on those platforms you don't need to pass -G "Unix Makefiles" command line option to cmake.

Note there is nothing special about the build directory name here. You can call it whatever you like.

Note the "Unix Makefile" generator is a "single" configuration generator which means you pick the build type (e.g. Debug, Release) when you invoke CMake. You can set the build type by passing it to the cmake invocation like so:

cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ../

See the section on "Build Types" for the different CMake build types.

If you wish to use a different compiler set the CXX and CC environment variables passed to cmake. This must be done at the very first invocation to cmake in the build directory because once configuration has happened the compiler is fixed. If you want to use a different compiler to the one you have already configured you either need to make a new build directory or delete the contents of the current build directory and start again.

For example to use clang the cmake line would be

CC=clang CXX=clang++ cmake ../

Note that CMake build will detect the target architecture that compiler is set up to build for and the generated build system will build for that architecture. If there is a way to tell your compiler to build for a different architecture via compiler flags then you can set the CFLAGS and CXXFLAGS environment variables to have the build target that architecture.

For example if you are on a x86_64 machine and you want to do a 32-bit build and have a multilib version of GCC you can run cmake like this

CFLAGS="-m32" CXXFLAGS="-m32" CC=gcc CXX=g++ cmake ../

Note like with the CC and CXX flags this must be done on the very first invocation to CMake in the build directory.

Adding Z3 as a dependency to a CMAKE Project

CMake's FetchContent allows the fetching and populating of an external project. This is useful when a certain version of z3 is required that may not match with the system version. With the following code in the cmake file of your project, z3 version 4.12.1 is downloaded to the build directory and the cmake targets are added to the project:

include(FetchContent)
FetchContent_Declare(Z3
        GIT_REPOSITORY https://github.com/Z3Prover/z3
        GIT_TAG        z3-4.15.3
)
FetchContent_MakeAvailable(Z3)

# Add the C++ API include directory for z3++.h
if(TARGET libz3)
    target_include_directories(libz3 INTERFACE
        $<BUILD_INTERFACE:${z3_SOURCE_DIR}/src/api/c++>
    )
endif()

Once fetched, you can link the z3 library to your target:

target_link_libraries(yourTarget PRIVATE libz3)

Important notes for FetchContent approach:

  • The target name is libz3 (referring to the library target from src/CMakeLists.txt)
  • An additional include directory for src/api/c++ is added to enable #include "z3++.h" in C++ code
  • Without the additional include directory, you would need #include "c++/z3++.h" instead

Recommended: Create an alias for consistency with system installs:

# Create an alias for consistency with system install
if(NOT TARGET z3::libz3)
    add_library(z3::libz3 ALIAS libz3)
endif()
target_link_libraries(yourTarget PRIVATE z3::libz3)

Using system-installed Z3

If you have Z3 installed on your system (e.g., via package manager or by building and installing Z3 yourself), you can use CMake's find_package to locate it:

set(Z3_MIN_VERSION "4.15.3")
find_package(Z3 ${Z3_MIN_VERSION} REQUIRED CONFIG)

Once found, you can link to Z3 using the exported target (recommended):

target_link_libraries(yourTarget PRIVATE z3::libz3)

Alternative using variables (for compatibility with older CMake code):

# For C projects
target_include_directories(yourTarget PRIVATE ${Z3_C_INCLUDE_DIRS})
target_link_libraries(yourTarget PRIVATE ${Z3_LIBRARIES})

# For C++ projects  
target_include_directories(yourTarget PRIVATE ${Z3_CXX_INCLUDE_DIRS})
target_link_libraries(yourTarget PRIVATE ${Z3_LIBRARIES})

The find_package(Z3 CONFIG) approach uses Z3's provided Z3Config.cmake file, which is installed to a standard location (typically <prefix>/lib/cmake/z3/). If CMake cannot automatically find Z3, you can help it by setting -DZ3_DIR=<path> where <path> is the directory containing the Z3Config.cmake file.

Note: This approach requires that Z3 was built and installed using CMake. Z3 installations from the Python build system may not provide the necessary CMake configuration files. The exported target z3::libz3 automatically provides the correct include directories and linking flags.

Using system-installed Z3 with FetchContent fallback

This approach combines the benefits of both methods above: it uses a system-installed Z3 if available and meets the minimum version requirement, otherwise falls back to fetching Z3 from the repository. This is often the most practical approach for projects.

set(Z3_MIN_VERSION "4.15.3")

# First, try to find Z3 on the system
find_package(Z3 ${Z3_MIN_VERSION} CONFIG QUIET)

if(Z3_FOUND)
    message(STATUS "Found system Z3 version ${Z3_VERSION_STRING}")
    # Z3_LIBRARIES will contain z3::libz3
else()
    message(STATUS "System Z3 not found or version too old, fetching Z3 ${Z3_MIN_VERSION}")
    
    # Fallback to FetchContent
    include(FetchContent)
    FetchContent_Declare(Z3
        GIT_REPOSITORY https://github.com/Z3Prover/z3
        GIT_TAG        z3-${Z3_MIN_VERSION}
    )
    FetchContent_MakeAvailable(Z3)
    
    # Add the C++ API include directory for z3++.h
    if(TARGET libz3)
        target_include_directories(libz3 INTERFACE
            $<BUILD_INTERFACE:${z3_SOURCE_DIR}/src/api/c++>
        )
    endif()
    
    # Create an alias to match the system install target name
    if(NOT TARGET z3::libz3)
        add_library(z3::libz3 ALIAS libz3)
    endif()
endif()

# Now use Z3 consistently regardless of how it was found
target_link_libraries(yourTarget PRIVATE z3::libz3)

Key benefits of this approach:

  • Consistent interface: Both paths result in the same z3::libz3 target
  • Version control: Ensures minimum version requirements are met
  • Flexible deployment: Works whether Z3 is pre-installed or not
  • Proper linking: Uses CMake targets which handle include directories and linking automatically

Important notes:

  • Use z3::libz3 target instead of raw library names for better CMake integration
  • The target automatically provides the correct include directories, so no need for manual target_include_directories
  • When using FetchContent, an alias is created to ensure target name consistency
  • Set QUIET in find_package to avoid error messages when Z3 isn't found

Ninja

Ninja is a simple build system that is built for speed. It can be significantly faster than "UNIX Makefile"s because it is not a recursive build system and thus doesn't create a new process every time it traverses into a directory. Ninja is particularly appropriate if you want fast incremental building.

Basic usage is as follows:

mkdir build
cd build
cmake -G "Ninja" ../
ninja

Note the discussion of the CC, CXX, CFLAGS and CXXFLAGS for "Unix Makefiles" also applies here.

Note also that like the "Unix Makefiles" generator, the "Ninja" generator is a single configuration generator so you pick the build type when you invoke cmake by passing CMAKE_BUILD_TYPE=<build_type> to cmake. See the section on "Build Types".

Note that Ninja runs in parallel by default. Use the -j flag to change this.

Note that Ninja also runs on Windows. You just need to run cmake in an environment where the compiler can be found. If you have Visual Studio installed it typically ships with a "Developer Command Prompt Window" that you can use which has the environment variables setup for you.

NMake

NMake is a build system that ships with Visual Studio. You are advised to use Ninja instead which is significantly faster due to supporting concurrent builds. However CMake does support NMake if you wish to use it. Note that NMake is a single configuration generator so you must set CMAKE_BUILD_TYPE to set the build type.

Basic usage:

  1. Launch the "Developer Command Prompt Windows"
  2. Change to the root of the Z3 repository
mkdir build
cd build
cmake -G "NMake Makefiles" ../
nmake

Visual Studio

Visual Studio 19 comes with integrated support for CMake. It suffices to open the (z3) folder where this file and the Z3 project CMakeLists.txt resides, and Visual Studio does the rest.

For legacy versions of Visual Studio a process is as follows: For the Visual Studio generators you need to know which version of Visual Studio you wish to use and also what architecture you want to build for.

We'll use the cmake-gui here as it is easier to pick the right generator but this can be scripted if need be.

Here are the basic steps:

  1. Create an empty build directory
  2. Start the cmake-gui program
  3. Set "where is the source code" to the root of the Z3 project repository. You can do this by pressing the "Browse Source..." button and picking the directory.
  4. Set "where to build the binaries" to the empty build directory you just created. You can do this by pressing the "Browse build..." button and picking the directory.
  5. Press the "Configure" button
  6. A window will appear asking you to pick the generator to use. Pick the generator that matches the version of Visual Studio you are using. Note also that some of the generator names contain Win64 (e.g. Visual Studio 12 2013 Win64) this indicates a x86 64-bit build. Generator names without this (e.g. Visual Studio 12 2013) are x86 32-bit build.
  7. Press the "Finish" button and wait for CMake to finish it's first configure.
  8. A set of configuration options will appear which will affect various aspects of the build. Change them as you desire. If you change a set of options press the "Configure" again. Additional options may appear when you do this.
  9. When you have finished changing configuration options press the "Generate" button.
  10. When generation is done close cmake-gui.
  11. In the build directory open the generated Z3.sln solution file created by CMake with Visual Studio.
  12. In Visual Studio pick the build type (e.g. Debug, Release) you want.
  13. Click "BUILD > Build Solution".

Note that unlike the "Unix Makefile" and "Ninja" generators the Visual Studio generators are multi-configuration generators which means you don't set the build type when invoking CMake. Instead you set the build type inside Visual Studio. See the "Build Type" section for more information.

General workflow

The general workflow when using CMake is the following

  1. Create a new build directory
  2. Configure the project
  3. Generate the build system
  4. Invoke the build system to build the project

To perform steps 2 and 3 you can choose from three different tools

  • cmake
  • ccmake
  • cmake-gui

cmake is a command line tool and is what you should use if you are writing a script to build Z3. This tool performs steps 1 and 2 in one go without user interaction. The ccmake and cmake-gui tools are more interactive and allow you to change various options. In both these tools the basic steps to follow are:

  1. Configure.
  2. Change any options you wish. Every time you change a set of options You should configure again. This may cause new options to appear
  3. Generate.

For information see https://cmake.org/runningcmake/

Note when invoking CMake you give it the path to the source directory. This is the top-level directory in the Z3 repository containing a CMakeLists.txt. That file should contain the line project(Z3 C CXX). If you give it a path deeper into the Z3 repository (e.g. the src directory) the configure step will fail.

Build Types

Several build types are supported.

  • Release
  • Debug
  • RelWithDebInfo
  • MinSizeRel

For the single configuration generators (e.g. "Unix Makefile" and "Ninja") you set the build type when invoking cmake by passing -DCMAKE_BUILD_TYPE=<build_type> where <build_type> is one of the build types specified above.

For multi-configuration generators (e.g. Visual Studio) you don't set the build type when invoking CMake and instead set the build type within Visual Studio itself.

MSVC Security Features

When building with Microsoft Visual C++ (MSVC), Z3 automatically enables several security features by default:

Control Flow Guard (CFG)

  • CMake Option: Z3_ENABLE_CFG - Defaults to ON for MSVC builds
  • Compiler flag: /guard:cf - Automatically enabled when Z3_ENABLE_CFG=ON
  • Linker flag: /GUARD:CF - Automatically enabled when Z3_ENABLE_CFG=ON
  • Purpose: Control Flow Guard analyzes control flow for indirect call targets at compile time and inserts runtime verification code to detect attempts to compromise your code by redirecting control flow to attacker-controlled locations
  • Note: Automatically enables /DYNAMICBASE as required by /GUARD:CF

Address Space Layout Randomization (ASLR)

  • Linker flag: /DYNAMICBASE - Enabled when Control Flow Guard is active
  • Purpose: Randomizes memory layout to make exploitation more difficult
  • Note: Required for Control Flow Guard to function properly

Incompatibilities

Control Flow Guard is incompatible with:

  • /ZI (Edit and Continue debug information format)
  • /clr (Common Language Runtime compilation)

When these incompatible options are detected, Control Flow Guard will be automatically disabled with a warning message.

Disabling Control Flow Guard

To disable Control Flow Guard, set the CMake option:

cmake -DZ3_ENABLE_CFG=OFF ../

Useful options

The following useful options can be passed to CMake whilst configuring.

  • CMAKE_BUILD_TYPE - STRING. The build type to use. Only relevant for single configuration generators (e.g. "Unix Makefile" and "Ninja").
  • CMAKE_INSTALL_BINDIR - STRING. The path to install z3 binaries (relative to CMAKE_INSTALL_PREFIX), e.g. bin.
  • CMAKE_INSTALL_INCLUDEDIR - STRING. The path to install z3 include files (relative to CMAKE_INSTALL_PREFIX), e.g. include.
  • CMAKE_INSTALL_LIBDIR - STRING. The path to install z3 libraries (relative to CMAKE_INSTALL_PREFIX), e.g. lib.
  • CMAKE_INSTALL_PREFIX - STRING. The install prefix to use (e.g. /usr/local/).
  • CMAKE_INSTALL_PKGCONFIGDIR - STRING. The path to install pkgconfig files.
  • CMAKE_INSTALL_PYTHON_PKG_DIR - STRING. The path to install the z3 python bindings. This can be relative (to CMAKE_INSTALL_PREFIX) or absolute.
  • CMAKE_INSTALL_Z3_CMAKE_PACKAGE_DIR - STRING. The path to install CMake package files (e.g. /usr/lib/cmake/z3).
  • CMAKE_INSTALL_API_BINDINGS_DOC - STRING. The path to install documentation for API bindings.
  • Python3_EXECUTABLE - STRING. The python executable to use during the build.
  • Z3_ENABLE_TRACING_FOR_NON_DEBUG - BOOL. If set to TRUE enable tracing in non-debug builds, if set to FALSE disable tracing in non-debug builds. Note in debug builds tracing is always enabled.
  • Z3_BUILD_LIBZ3_SHARED - BOOL. If set to TRUE build libz3 as a shared library otherwise build as a static library.
  • Z3_ENABLE_EXAMPLE_TARGETS - BOOL. If set to TRUE add the build targets for building the API examples.
  • Z3_USE_LIB_GMP - BOOL. If set to TRUE use the GNU multiple precision library. If set to FALSE use an internal implementation.
  • Z3_BUILD_PYTHON_BINDINGS - BOOL. If set to TRUE then Z3's python bindings will be built.
  • Z3_INSTALL_PYTHON_BINDINGS - BOOL. If set to TRUE and Z3_BUILD_PYTHON_BINDINGS is TRUE then running the install target will install Z3's Python bindings.
  • Z3_BUILD_DOTNET_BINDINGS - BOOL. If set to TRUE then Z3's .NET bindings will be built.
  • Z3_INSTALL_DOTNET_BINDINGS - BOOL. If set to TRUE and Z3_BUILD_DOTNET_BINDINGS is TRUE then running the install target will install Z3's .NET bindings.
  • Z3_DOTNET_CSC_EXECUTABLE - STRING. The path to the C# compiler to use. Only relevant if Z3_BUILD_DOTNET_BINDINGS is set to TRUE.
  • Z3_DOTNET_GACUTIL_EXECUTABLE - STRING. The path to the gacutil program to use. Only relevant if BUILD_DOTNET_BINDINGS is set to TRUE.
  • Z3_BUILD_JAVA_BINDINGS - BOOL. If set to TRUE then Z3's Java bindings will be built.
  • Z3_INSTALL_JAVA_BINDINGS - BOOL. If set to TRUE and Z3_BUILD_JAVA_BINDINGS is TRUE then running the install target will install Z3's Java bindings.
  • Z3_JAVA_JAR_INSTALLDIR - STRING. The path to directory to install the Z3 Java .jar file. This path should be relative to CMAKE_INSTALL_PREFIX.
  • Z3_JAVA_JNI_LIB_INSTALLDIRR - STRING. The path to directory to install the Z3 Java JNI bridge library. This path should be relative to CMAKE_INSTALL_PREFIX.
  • Z3_BUILD_OCAML_BINDINGS - BOOL. If set to TRUE then Z3's OCaml bindings will be built.
  • Z3_BUILD_JULIA_BINDINGS - BOOL. If set to TRUE then Z3's Julia bindings will be built.
  • Z3_INSTALL_JULIA_BINDINGS - BOOL. If set to TRUE and Z3_BUILD_JULIA_BINDINGS is TRUE then running the install target will install Z3's Julia bindings.
  • Z3_INCLUDE_GIT_DESCRIBE - BOOL. If set to TRUE and the source tree of Z3 is a git repository then the output of git describe will be included in the build.
  • Z3_INCLUDE_GIT_HASH - BOOL. If set to TRUE and the source tree of Z3 is a git repository then the git hash will be included in the build.
  • Z3_BUILD_DOCUMENTATION - BOOL. If set to TRUE then documentation for the API bindings can be built by invoking the api_docs target.
  • Z3_INSTALL_API_BINDINGS_DOCUMENTATION - BOOL. If set to TRUE and Z3_BUILD_DOCUMENTATION` is TRUEthen documentation for API bindings will be installed when running theinstall`` target.
  • Z3_ALWAYS_BUILD_DOCS - BOOL. If set to TRUE and Z3_BUILD_DOCUMENTATION is TRUE then documentation for API bindings will always be built. Disabling this is useful for faster incremental builds. The documentation can be manually built by invoking the api_docs target.
  • Z3_LINK_TIME_OPTIMIZATION - BOOL. If set to TRUE link time optimization will be enabled.
  • Z3_ENABLE_CFI - BOOL. If set to TRUE will enable Control Flow Integrity security checks. This is only supported by Clang and will fail on other compilers. This requires Z3_LINK_TIME_OPTIMIZATION to also be enabled.
  • Z3_ENABLE_CFG - BOOL. If set to TRUE will enable Control Flow Guard security checks. This is only supported by MSVC and will fail on other compilers. This does not require link time optimization. Control Flow Guard is enabled by default for MSVC builds. Note: Control Flow Guard is incompatible with /ZI (Edit and Continue debug information) and /clr (Common Language Runtime compilation).
  • Z3_API_LOG_SYNC - BOOL. If set to TRUE will enable experimental API log sync feature.
  • WARNINGS_AS_ERRORS - STRING. If set to ON compiler warnings will be treated as errors. If set to OFF compiler warnings will not be treated as errors. If set to SERIOUS_ONLY a subset of compiler warnings will be treated as errors.
  • Z3_C_EXAMPLES_FORCE_CXX_LINKER - BOOL. If set to TRUE the C API examples will request that the C++ linker is used rather than the C linker.
  • Z3_BUILD_EXECUTABLE - BOOL. If set to TRUE build the z3 executable. Defaults to TRUE unless z3 is being built as a submodule in which case it defaults to FALSE.
  • Z3_BUILD_TEST_EXECUTABLES - BOOL. If set to TRUE build the z3 test executables. Defaults to TRUE unless z3 is being built as a submodule in which case it defaults to FALSE.
  • Z3_SAVE_CLANG_OPTIMIZATION_RECORDS - BOOL. If set to TRUE saves Clang optimization records by setting the compiler flag -fsave-optimization-record.
  • Z3_SINGLE_THREADED - BOOL. If set to TRUE compiles Z3 for single threaded mode.
  • Z3_POLLING_TIMER - BOOL. If set to TRUE compiles Z3 to use polling based timer instead of requiring a thread. This is useful for wasm builds and avoids spawning threads that interfere with how WASM is run.
  • Z3_ADDRESS_SANITIZE - BOOL. If set to TRUE compiles Z3 with address sanitization enabled.

On the command line these can be passed to cmake using the -D option. In ccmake and cmake-gui these can be set in the user interface.

Example

cmake -DCMAKE_BUILD_TYPE=Release -DZ3_ENABLE_TRACING_FOR_NON_DEBUG=FALSE ../

Z3 API Bindings

Z3 exposes various language bindings for its API. Below are some notes on building and/or installing these bindings when building Z3 with CMake.

Java bindings

The CMake build uses the FindJava and FindJNI cmake modules to detect the installation of Java. If CMake fails to find your installation of Java set the JAVA_HOME environment variable when invoking CMake so that it points at the correct location. For example

JAVA_HOME=/usr/lib/jvm/default cmake -DZ3_BUILD_JAVA_BINDINGS=ON ../

Note that the built .jar file is named com.microsoft.z3-VERSION.jar where VERSION is the Z3 version. Under non Windows systems a symbolic link named com.microsoft.z3.jar is provided. This symbolic link is not created when building under Windows.

Developer/packager notes

These notes are help developers and packagers of Z3.

Install/Uninstall

Install and uninstall targets are supported. Use CMAKE_INSTALL_PREFIX to set the install prefix. If you also need to control which directories are used for install set the documented CMAKE_INSTALL_* options.

To install run

make install

To uninstall run

make uninstall

Note that DESTDIR is supported for staged installs.

To install

mkdir staged
make install DESTDIR=/full/path/to/staged/

to uninstall

make uninstall DESTDIR=/full/path/to/staged

The above also works for Ninja but DESTDIR must be an environment variable instead.

Examining invoked commands

If you are using the "UNIX Makefiles" generator and want to see exactly the commands that are being run you can pass VERBOSE=1 to make.

make VERBOSE=1

If you are using Ninja you can use the -v flag.

Additional targets

To see the list of targets run

make help

There are a few special targets:

  • clean all the built targets in the current directory and below
  • edit_cache will invoke one of the CMake tools (depending on which is available) to let you change configuration options.
  • rebuild_cache will reinvoke cmake for the project.
  • api_docs will build the documentation for the API bindings.

Setting build type specific flags

The build system supports single configuration and multi-configuration generators. This means it is not possible to know the build type at configure time and therefore ${CMAKE_BUILD_TYPE} should not be conditionally used to set compiler flags or definitions. Instead you should use Generator expressions which are evaluated by the generator.

For example

$<$<CONFIG:Debug>:Z3DEBUG>

If the build type at build time is Debug this evaluates to Z3DEBUG but evaluates to nothing for all other configurations. You can see examples of this in the CMakeLists.txt files.

File-globbing

It is tempting use file-globbing in CMakeLists.txt to find a set for files matching a pattern and use them as the sources to build a target. This however is a bad idea because it prevents CMake from knowing when it needs to rerun itself. This is why source file names are explicitly listed in the CMakeLists.txt so that when changes are made the source files used to build a target automatically triggers a rerun of CMake.

Long story short. Don't use file globbing.

Serious warning flags

By default the WARNINGS_AS_ERRORS flag is set to SERIOUS_ONLY which means some warnings will be treated as errors. These warnings are controlled by the relevant *_WARNINGS_AS_ERRORS list defined in cmake/compiler_warnings.cmake.

Additional warnings should only be added here if the warnings has no false positives.

Building TPTP with CMAKE

Build instructions:

  1. cd z3
  2. mkdir release
  3. cd release
  4. cmake3 -DZ3_BUILD_LIBZ3_SHARED=FALSE -DCMAKE_BUILD_TYPE=RelWithDebInfo -G "Unix Makefiles" ../
  5. make
  6. make z3_tptp5
  7. cp examples/tptp_build_dir/z3_tptp5 ../../bin/z3_tptp